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
NewRabbitMQServer returns the new rabbitmq server with the connection and channel
func NewRabbitMQServer(username string, password string, host string) *Server { return &Server{ RabbitMQUsername: username, RabbitMQPassword: password, RabbitMQHost: host, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewServer(cfg *ServerConfig) (*Server, error) {\n\tvar s = &Server{\n\t\tmux: http.NewServeMux(),\n\t}\n\n\t// register api handlers\n\ts.registerHandlers()\n\tconsole.Info(\"registered handlers\")\n\n\t// http client for authorization\n\ts.hc = &http.Client{}\n\n\t// establish rabbitmq session\n\tmqaddr := fmt.Sprintf(\"%s:%d\", cfg.RabbitMQ.IP, cfg.RabbitMQ.Port)\n\tbaseConfig.User = cfg.RabbitMQ.User\n\tbaseConfig.Password = cfg.RabbitMQ.Password\n\tbaseConfig.Addr = mqaddr\n\tmqSession := mq.NewSession(\"api\", baseConfig)\n\n\t// connecte the session\n\tconsole.Info(\"connect to RabbitMQ...\")\n\tif err := mqSession.TryConnect(40, 3000*time.Millisecond); err != nil {\n\t\treturn nil, fmt.Errorf(\"on NewServer: %v\", err)\n\t}\n\ts.mqss = mqSession\n\tconsole.Info(\"session(%q) established between RabbitMQ\", mqaddr)\n\n\t// create response packet map\n\ts.packetChans = server.NewChannelMap()\n\n\t// start to listen from RabbitMQ\n\terr := s.mqss.Consume(server.MGDB, server.DB2API, s.onDBResponse, 2)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"on NewServer: %v\", err)\n\t}\n\n\t// addlitionaly send logs to RabbitMQ.\n\tconsole.AddLogHandler(\n\t\tfunc(l console.Level, format string, v ...interface{}) bool {\n\t\t\tpacket := server.PacketLog{\n\t\t\t\tTimestamp: time.Now(),\n\t\t\t\tLogLevel: l,\n\t\t\t\tMsg: fmt.Sprintf(format, v...),\n\t\t\t}\n\n\t\t\tif err := s.mqss.Publish(\n\t\t\t\tserver.MGLogs,\n\t\t\t\t\"\",\n\t\t\t\tserver.API,\n\t\t\t\t&packet,\n\t\t\t); err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn true\n\t\t},\n\t)\n\n\treturn s, nil\n}", "func initialize() *RabbitServer {\n\n\trabbitURL := utilities.GetRabbitInfo()\n\tserver := MakeRabbitServer(rabbitURL)\n\tserver.Connect()\n\n\treturn server\n\n}", "func New(uri string) *RabbitMQ {\n\n\tctx, cancel := context.WithCancel(context.Background())\n\trmq := &RabbitMQ{URI: uri, ConnectionContext: ctx, connectionCancelFunc: cancel, reconnected: false}\n\n\trmq.connect(uri)\n\n\t//launch a goroutine that will listen for messages on ErrorChan and try to reconnect in case of errors\n\tgo rmq.reconnector()\n\n\treturn rmq\n}", "func NewServer(\n\tconnection *Connection,\n\tqueue string,\n\tconcurrency uint32,\n\ttimeout time.Duration,\n\trequestParser RequestParser,\n\treplyParser ReplyParser,\n) (Server, error) {\n\tsession, err := connection.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsenderCache, err := NewSenderCache(connection)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &rpcServer{\n\t\tconnection: connection,\n\t\tsession: session,\n\t\tqueue: queue,\n\t\tconcurrency: concurrency,\n\t\ttimeout: timeout,\n\t\trequestParser: requestParser,\n\t\treplyParser: replyParser,\n\t\tsenderCache: senderCache,\n\t\tdone: make(chan bool),\n\t}, nil\n}", "func New(config *config.Config) (MsgBroker, error) {\n\n\t//create connection\n\tlog.Printf(\"Connecting to broker %s\", config.Broker)\n\tconn, err := amqp.Dial(config.Broker)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tch, err := conn.Channel()\n\t//create channel\n\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := &amqpBroker{*conn, *ch, make(chan *amqp.Error), config}\n\tlog.Println(\"Returning broker\")\n\treturn b, nil\n}", "func createRabbitConnection(cr *Credentials) (*Rabbit, error) {\n\tconnectionStr := fmt.Sprintf(\"amqp://%v:%v@%v:%v/\", cr.Username, cr.Password, cr.Host, cr.Port)\n\tconn, err := amqp.Dial(connectionStr)\n\tfailOnError(err, \"Failed to connect to RabbitMQ; Connection string:\"+connectionStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tch, err := conn.Channel()\n\tfailOnError(err, \"Failed to open a channel\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Rabbit{\n\t\tConnection: conn,\n\t\tChannel: ch,\n\t\tCredentials: cr,\n\t}, nil\n}", "func buildChannel() (rChan *RabbitChanWriter) {\n connection, err := amqp.Dial(*uri)\n if err != nil {\n log.Printf(\"Dial: %s\", err)\n return nil\n }\n\n channel, err := connection.Channel()\n if err != nil {\n log.Printf(\"Channel: %s\", err)\n return nil\n }\n\n // build the exchange\n if err := channel.ExchangeDeclare(\n *exchange, // name\n *exchangeType, // type\n true, // durable\n false, // auto-deleted\n false, // internal\n false, // noWait\n nil, // arguments\n ); err != nil {\n log.Fatalf(\"Exchange Declare: %s\", err)\n }\n\n // create a queue with the routing key and bind to it\n if _, err := channel.QueueDeclare(\n *routingKey, // name\n true, // durable\n false, // autoDelete\n false, // exclusive\n false, // noWait\n nil, // args\n ); err != nil {\n log.Fatalf(\"Queue Declare: %s\", err)\n }\n\n if err := channel.QueueBind(\n *routingKey, // name\n *routingKey, // key\n *exchange, // exchange\n false, // noWait\n nil, // args\n ); err != nil {\n log.Fatalf(\"Queue Bind: %s\", err)\n }\n\n\n rChan = &RabbitChanWriter{channel, connection}\n return\n}", "func NewServer() *Server {}", "func channel(conn *amqp.Connection, msgtype string) (*amqp.Channel, error) {\n\t// Open a channel to communicate with the server\n\tchannel, err := conn.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Declare the exchange to use when publishing\n\tif err := channel.ExchangeDeclare(\n\t\tmsgtype,\n\t\t\"direct\",\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tnil,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Declare the queue to use when publishing\n\tchannel.QueueDeclare(\n\t\tmsgtype,\n\t\tfalse,\n\t\ttrue,\n\t\tfalse,\n\t\tfalse,\n\t\tnil,\n\t)\n\n\t// Bind the queue to the exchange\n\tchannel.QueueBind(\n\t\tmsgtype,\n\t\t\"\",\n\t\tmsgtype,\n\t\tfalse,\n\t\tnil,\n\t)\n\n\treturn channel, nil\n}", "func NewConsumer(amqpURI, exchange, queue, routingKey, tag string, prefetch int) *RabbitMQ {\n\tconn, err := amqp.Dial(amqpURI)\n\tif err != nil {\n\t\tlog.Fatalf(\"writer failed to connect to Rabbit: %s\", err)\n\t\treturn nil\n\t}\n\n\tgo func() {\n\t\tlog.Printf(\"writer closing: %s\", <-conn.NotifyClose(make(chan *amqp.Error)))\n\t\tlog.Printf(\"writer blocked by rabbit: %v\", <-conn.NotifyBlocked(make(chan amqp.Blocking)))\n\t}()\n\n\tchannel, err := conn.Channel()\n\tif err != nil {\n\t\tlog.Fatalf(\"writer failed to get a channel from Rabbit: %s\", err)\n\t\treturn nil\n\t}\n\n\tq, err := channel.QueueDeclarePassive(\n\t\tqueue, // name of the queue\n\t\ttrue, // durable\n\t\tfalse, // delete when usused\n\t\tfalse, // exclusive\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\tif err != nil {\n\t\tlog.Fatalf(\"Queue Declare: %s\", err)\n\t}\n\tif q.Messages == 0 {\n\t\tlog.Fatalf(\"No messages in RabbitMQ Queue: %s\", q.Name)\n\t}\n\n\tr := &RabbitMQ{\n\t\tconn: conn,\n\t\tchannel: channel,\n\t\texchange: exchange,\n\t\tcontentType: \"application/json\",\n\t\tcontentEncoding: \"UTF-8\",\n\t}\n\tlog.Print(\"RabbitMQ connected: \", amqpURI)\n\tlog.Printf(\"Bind to Exchange: %q and Queue: %q, Messaging waiting: %d\", exchange, queue, q.Messages)\n\n\treturn r\n}", "func (r Rabbit) NewCh() (*amqp.Channel, error) {\n\treturn r.conn.Channel()\n}", "func NewMqttServer(sqz int, url string, retain bool, qos int) *Server {\n\treturn &Server{\n\t\tsessionQueueSize: sqz,\n\t\turl: url,\n\t\ttree: topic.NewTree(),\n\t\tretain: retain,\n\t\tqos: qos,\n\t}\n}", "func NewRabbitMQConnection(config *Configuration) (RabbitMQ, error) {\n\tconn, err := amqp.Dial(config.RabbitURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rabbitMQConnection{configuration: config, channel: ch}, nil\n}", "func NewRabbitConnection(URI string) (Connection, error) {\n\tamqpNativeConn, err := amqp.Dial(URI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn RabbitConnection{amqpNativeConn}, nil\n}", "func NewRabbitMQ() *RabbitMQ {\n\treturn &RabbitMQ{}\n}", "func NewServer(buildBroker BrokerBuilder, options ...serverOption) (*Server, error) {\n\tif buildBroker == nil {\n\t\treturn nil, errors.New(\"chat.NewServer: required chat.BrokerBuilder is nil\")\n\t}\n\tinbox := make(chan broker.MessageEvent)\n\tjoin := make(chan broker.JoinEvent)\n\tpart := make(chan broker.PartEvent)\n\tb, err := buildBroker(inbox, join, part)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"chat.NewServer: can't build broker: %v\", err)\n\t}\n\tctx, cancel := context.WithCancel(context.Background())\n\ts := &Server{\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\twg: &sync.WaitGroup{},\n\t\tbroker: b,\n\t\tinbox: inbox,\n\t\tjoin: join,\n\t\tpart: part,\n\t}\n\tif err := setup(s, options...); err != nil {\n\t\treturn nil, err\n\t}\n\ts.handleEvents()\n\treturn s, nil\n}", "func CreateConnection(host string, port int) *RabbitmqConnection {\n\trc := &RabbitmqConnection{Host: host, Port: port}\n\trc.connectToRabbitMQ()\n\treturn rc\n}", "func NewServer(ctx context.Context) (*Server, error) {\n\tcmds := make(chan *mc.Command)\n\n\tserver := &Server{\n\t\tcommands: cmds,\n\t\tticker: time.NewTicker(TickDuration),\n\t}\n\n\tctx = context.WithValue(ctx, mc.ServerCommands, cmds)\n\tserver.Runner = runner.NewRunner(ctx, server)\n\n\tif isatty.IsTerminal(os.Stdin.Fd()) {\n\t\twriter := &utils.LineWriter{\n\t\t\tWriter: log.StandardLogger().WriterLevel(log.InfoLevel),\n\t\t}\n\n\t\tif cons, err := console.NewConsole(server.Context, \"Console\", os.Stdin, writer); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tserver.console = cons\n\t\t}\n\t}\n\n\tif mcServer, err := NewMCServer(server.Context, mc.Properties().ServerAddr()); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tserver.mc = mcServer\n\t}\n\n\trconAddr := mc.Properties().RCONAddr()\n\trconPass := mc.Properties().RCON.Password\n\n\tif rconAddr != \"\" && rconPass != \"\" {\n\t\tif rcon, err := NewRCONServer(server.Context, rconAddr); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tserver.rcon = rcon\n\t\t}\n\t}\n\n\treturn server, nil\n}", "func NewServer(pattern string) *Server {\n\tmessages := GetMessages()\n\tclients := make(map[string]*Client)\n\tgroups := make(map[string]*Group)\n\taddCh := make(chan *Client)\n\tdelCh := make(chan *Client)\n\tsendAllCh := make(chan *Message)\n\tdoneCh := make(chan bool)\n\terrCh := make(chan error)\n\n\treturn &Server{\n\t\tpattern,\n\t\tmessages,\n\t\tclients,\n\t\tgroups,\n\t\taddCh,\n\t\tdelCh,\n\t\tsendAllCh,\n\t\tdoneCh,\n\t\terrCh,\n\t}\n}", "func NewServer(port string, newClients chan<- *Client, clientInput chan<- *ClientInputMessage) *Server {\n\tid := NewID(\"server\")\n\tlog := NewLogger(id)\n\treturn &Server{id, newClients, clientInput, port, nil, log}\n}", "func GetConnectionRabbit(rabbitURL string) (ConnectionRabbitMQ, error) {\n\tconn, err := amqp.Dial(rabbitURL)\n\tif err != nil {\n\t\treturn ConnectionRabbitMQ{}, err\n\t}\n\n\tch, err := conn.Channel()\n\treturn ConnectionRabbitMQ{\n\t\tChannel: ch,\n\t\tConn: conn,\n\t}, err\n}", "func CreateServer(url string, queue string, requestParser RequestParser) (Server, error) {\n\tconn, err := CreateConnection(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tch := conn.Channel\n\terr = ch.Qos(\n\t\t1, // prefetchCount\n\t\t0, // prefetchSize\n\t\tfalse, // global\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tq, err := ch.QueueDeclare(\n\t\tqueue, // name\n\t\ttrue, // durable\n\t\tfalse, // auto-delete\n\t\tfalse, // exclusive\n\t\tfalse, // no-wait\n\t\tnil, // args\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmessages, err := ch.Consume(\n\t\tq.Name,\n\t\t\"\", // consumer\n\t\tfalse, // auto-ack\n\t\tfalse, // exclusive\n\t\tfalse, // no-local\n\t\tfalse, // no-wait\n\t\tnil, // args\n\t)\n\n\treturn &rpcServer{\n\t\tconnection: conn,\n\t\tmessages: messages,\n\t\tdone: make(chan bool),\n\t\trequestParser: requestParser,\n\t}, nil\n}", "func NewService(mqConfig *commonCfg.MQConfig) (*AMQPService, func(), error) {\n\tconn, ch, err := rabbitmq.Dial(mqConfig.Username, mqConfig.Password, mqConfig.Host, mqConfig.Port)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tchannelWrapper := rabbitmq.AMQPChannel{ch}\n\tAMQPService := AMQPService{\n\t\tChannel: &channelWrapper,\n\t}\n\n\treturn &AMQPService, func() {\n\t\tconn.Close()\n\t\tch.Close()\n\t}, nil\n}", "func NewServer(name string, logger termlog.Logger) *Server {\n\tbroadcast := make(chan string, 50)\n\ts := &Server{\n\t\tname: name,\n\t\tbroadcast: broadcast,\n\t\tconnections: make(map[*websocket.Conn]bool),\n\t\tlogger: logger,\n\t}\n\tgo s.run(broadcast)\n\treturn s\n}", "func NewConsumer(amqpURI, exchange, exchangeType, queueName, key, ctag string) (*Consumer, error) {\n\tc := &Consumer{\n\t\tconn: nil,\n\t\tchannel: nil,\n\t\ttag: ctag,\n\t\tdone: make(chan error),\n\t}\n\n\tvar err error\n\n\tlog.Printf(\"dialing %q\", amqpURI)\n\tc.conn, err = amqp.Dial(amqpURI)\n\tif err != nil {\n\t\tlog.Printf(\"RMQERR Dial: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Dial: %s\", err)\n\t}\n\n\tgo func() {\n\t\tlog.Printf(\"closing: %s\", <-c.conn.NotifyClose(make(chan *amqp.Error)))\n\t}()\n\n\tlog.Printf(\"got Connection, getting Channel\")\n\tc.channel, err = c.conn.Channel()\n\tif err != nil {\n\t\tlog.Printf(\"RMQERR Channel: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Channel: %s\", err)\n\t}\n\n\tlog.Printf(\"got Channel, declaring Exchange (%q)\", exchange)\n\tif err = c.channel.ExchangeDeclare(\n\t\texchange, // name of the exchange\n\t\texchangeType, // type\n\t\ttrue, // durable\n\t\tfalse, // delete when complete\n\t\tfalse, // internal\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t); err != nil {\n\t\tlog.Printf(\"RMQERR Exchange Declare: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Exchange Declare: %s\", err)\n\t}\n\n\tlog.Printf(\"declared Exchange, declaring Queue %q\", queueName)\n\tqueue, err := c.channel.QueueDeclare(\n\t\tqueueName, // name of the queue\n\t\ttrue, // durable\n\t\tfalse, // delete when usused\n\t\tfalse, // exclusive\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\tif err != nil {\n\t\tlog.Printf(\"RMQERR Queue Declare: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Queue Declare: %s\", err)\n\t}\n\n\tlog.Printf(\"declared Queue (%q %d messages, %d consumers), binding to Exchange (key %q)\",\n\t\tqueue.Name, queue.Messages, queue.Consumers, key)\n\n\tif err = c.channel.QueueBind(\n\t\tqueue.Name, // name of the queue\n\t\tkey, // bindingKey\n\t\texchange, // sourceExchange\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t); err != nil {\n\t\tlog.Printf(\"RMQERR Queue Bind: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Queue Bind: %s\", err)\n\t}\n\n\tlog.Printf(\"Queue bound to Exchange, starting Consume (consumer tag %q)\", c.tag)\n\tdeliveries, err := c.channel.Consume(\n\t\tqueue.Name, // name\n\t\tc.tag, // consumerTag,\n\t\tfalse, // noAck\n\t\tfalse, // exclusive\n\t\tfalse, // noLocal\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\tif err != nil {\n\t\tlog.Printf(\"RMQERR Queue Consume: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Queue Consume: %s\", err)\n\t}\n\tgo handle(deliveries, c.done)\n\n\treturn c, nil\n}", "func ConnectToRabbitMQ() error {\n\ttime.Sleep(50 * time.Second)\n\tcfg := RabbitMqEnv{}\n\tif err := env.Parse(&cfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse env: %v\", err)\n\t}\n\n\tfmt.Printf(\"%+v\", cfg)\n\n\tconn, err := amqp.Dial(fmt.Sprintf(\"amqp://%s:%s@%s:%s/\",\n\t\tcfg.RabbitMqPass,\n\t\tcfg.RabbitMqUser,\n\t\tcfg.RabbitMqHost,\n\t\tcfg.RabbitMqPort,\n\t))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to connect to RabbitMQ: %v\", err)\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open a channel: %v\", err)\n\t}\n\n\tq, err := ch.QueueDeclare(\n\t\t\"hello\", // name\n\t\tfalse, // durable\n\t\tfalse, // delete when unused\n\t\tfalse, // exclusive\n\t\tfalse, // no-wait\n\t\tnil, // arguments\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to declare a queue: %v\", err)\n\t}\n\n\tRabbitMQChan = ch\n\tRabbitMQQueue = q\n\n\treturn nil\n}", "func newServer(sc *ServerConfig, b backends.Backend, l log.Logger) (*server, error) {\n\tserver := &server{\n\t\tclientPool: NewPool(sc.MaxClients),\n\t\tclosedListener: make(chan bool, 1),\n\t\tlistenInterface: sc.ListenInterface,\n\t\tstate: ServerStateNew,\n\t\tenvelopePool: mail.NewPool(sc.MaxClients),\n\t}\n\tserver.logStore.Store(l)\n\tserver.backendStore.Store(b)\n\tlogFile := sc.LogFile\n\tif logFile == \"\" {\n\t\t// none set, use the same log file as mainlog\n\t\tlogFile = server.mainlog().GetLogDest()\n\t}\n\t// set level to same level as mainlog level\n\tmainlog, logOpenError := log.GetLogger(logFile, server.mainlog().GetLevel())\n\tserver.mainlogStore.Store(mainlog)\n\tif logOpenError != nil {\n\t\tserver.log().WithError(logOpenError).Errorf(\"Failed creating a logger for server [%s]\", sc.ListenInterface)\n\t}\n\n\tserver.setConfig(sc)\n\tserver.setTimeout(sc.Timeout)\n\tif err := server.configureSSL(); err != nil {\n\t\treturn server, err\n\t}\n\treturn server, nil\n}", "func NewServer(connectionString string, opts ...ServerOption) (*Server, error) {\n\ts := &Server{\n\t\tsubscribe: make(chan *subscription),\n\t\tredactions: make(FieldRedactions),\n\n\t\tctx: context.Background(),\n\t\tlistenerPingInterval: defaultPingInterval,\n\t}\n\tfor _, o := range opts {\n\t\to(s)\n\t}\n\tif s.logger == nil {\n\t\ts.logger = logrus.StandardLogger()\n\t}\n\tdb, err := sql.Open(\"postgres\", connectionString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := db.Ping(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"ping\")\n\t}\n\ts.l = pq.NewListener(connectionString, minReconnectInterval, maxReconnectInterval, func(ev pq.ListenerEventType, err error) {\n\t\ts.logger.WithField(\"listener-event\", ev).Debugln(\"got listener event\")\n\t\tif err != nil {\n\t\t\ts.logger.WithField(\"listener-event\", ev).WithError(err).Errorln(\"got listener event error\")\n\t\t}\n\t})\n\tif err := s.l.Listen(channel); err != nil {\n\t\treturn nil, errors.Wrap(err, \"listen\")\n\t}\n\tif err := s.l.Listen(channel + \"-ctl\"); err != nil {\n\t\treturn nil, errors.Wrap(err, \"listen\")\n\t}\n\ts.db = db\n\treturn s, nil\n}", "func NewServer(ctx context.Context, factory dependency.Factory) (*Server, error) {\n\tctx1, cancel := context.WithCancel(ctx)\n\n\ts := &Server{\n\t\tctx: ctx1,\n\t\tcancel: cancel,\n\t\tquerynode: qn.NewQueryNode(ctx, factory),\n\t\tgrpcErrChan: make(chan error),\n\t}\n\treturn s, nil\n}", "func NewServer() *Server {\n\tserver := &Server{\n\t\tmessages: make(chan []byte, 1),\n\t\tclients: make(map[chan []byte]bool),\n\t\tregister: make(chan chan []byte),\n\t\tunregister: make(chan chan []byte),\n\t}\n\tgo server.listen()\n\treturn server\n}", "func connectRabbitMQ() {\n\n\t// Start connection.\n\tconn, err := amqp.Dial(config.Client.Uri)\n\tutility.InitErrorHandler(\"Failed to connect to RabbitMQ\", err)\n\tdefer conn.Close()\n\n\tch, err := conn.Channel()\n\tutility.InitErrorHandler(\"Failed to open a channel\", err)\n\tdefer ch.Close()\n\n\t// Declare queue.\n\t_, err = ch.QueueDeclare(\n\t\tconfig.QueueName,\n\t\tconfig.Client.Queue.Durable,\n\t\tconfig.Client.Queue.AutoDelete,\n\t\tconfig.Client.Queue.Exclusive,\n\t\tconfig.Client.Queue.NoWait,\n\t\tnil,\n\t)\n\tutility.InitErrorHandler(\"Failed to declare a queue\", err)\n\n\terr = ch.Qos(\n\t\tconfig.Client.Prefetch.Count,\n\t\tconfig.Client.Prefetch.Size,\n\t\tconfig.Client.Prefetch.Global,\n\t)\n\tutility.InitErrorHandler(\"Failed to set QoS\", err)\n\n\tmsgs, err := ch.Consume(\n\t\tconfig.QueueName,\n\t\tconfig.Consumer,\n\t\tconfig.Client.Consume.AutoAck,\n\t\tconfig.Client.Consume.Exclusive,\n\t\tconfig.Client.Consume.NoLocal,\n\t\tconfig.Client.Consume.NoWait,\n\t\tnil,\n\t)\n\tutility.InitErrorHandler(\"Failed to register a consumer\", err)\n\n\tforever := make(chan bool)\n\n\tgo func() {\n\t\tfor d := range msgs {\n\t\t\t// Process queue items.\n\t\t\tprocessQueueItem(d)\n\t\t}\n\t}()\n\n\tfmt.Println(\" [*] Waiting for messages. To exit press CTRL+C\")\n\t<-forever\n}", "func NewServer(driver Driver, addr chan string) *GrpcServer {\n\treturn &GrpcServer{\n\t\tdriver: driver,\n\t\taddress: addr,\n\t}\n}", "func (p *LightningPool) new(ctx context.Context) (*amqp.Channel, error) {\n\treturn p.conn.Channel(ctx)\n}", "func NewServer() *Server {\n\ts := &Server{quit: make(chan bool)}\n\treturn s\n}", "func NewServer(host string, port int, packetQueue chan PacketQueue) (*Server, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", fmt.Sprintf(\"%s:%d\", host, port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Info(\"Starting server...\", addr.String())\n\n\treturn &Server{\n\t\tpacketQueue: packetQueue,\n\t\taddr: addr,\n\t\tsocket: nil,\n\t\tconnections: make(map[*Connection]struct{}),\n\t\tsignal: make(chan os.Signal, 1),\n\t\tmutex: new(sync.Mutex),\n\t}, nil\n}", "func NewRabbitMQConnection(conn *amqp.Connection) *RabbitMQConnection {\n\treturn &RabbitMQConnection{*conn}\n}", "func NewServer(conf Config, chatHander http.HandlerFunc, logs *logger.Logger) (*Server, error) {\n\tgabbleServer := new(Server)\n\n\tif logs != nil {\n\t\tgabbleServer.logs = logs\n\t}\n\n\tgabbleServer.addr = conf.GetHost() + \":\" + conf.GetPort()\n\n\tserv := new(http.Server)\n\tserv.Addr = gabbleServer.addr\n\tserv.Handler = chatHander\n\n\tgabbleServer.httpServer = serv\n\n\treturn gabbleServer, nil\n}", "func NewServerFactory(ctx context.Context, rcmd *channels.Remote, s string, l *logrus.Logger, wg *sync.WaitGroup) *Server {\n\treturn &Server{\n\t\tlogger: l,\n\t\tunixSocket: s,\n\t\trcmd: rcmd,\n\t\tctx: ctx,\n\t\twg: wg,\n\t}\n}", "func NewServer(ports []uint, hosts []string, pipelineFactory *PipelineFactory) *Server {\n\ts := new(Server)\n\ts.ports = ports\n\ts.hosts = hosts\n\ts.pipelineFactory = pipelineFactory\n\ts.eventHandlers = make([]ServerEventHandler, 0)\n\tcurrentServerState = make(chan server_state)\n\n\treturn s\n}", "func newServer(ctx common.Context, self *replica, listener net.Listener, workers int) (net.Server, error) {\n\tserver := &rpcServer{ctx: ctx, logger: ctx.Logger(), self: self}\n\treturn net.NewServer(ctx, listener, serverInitHandler(server), workers)\n}", "func (c *Consumer) init() (err error) {\n\tc.connection, err = amqp.Dial(c.config.URI)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Consumer.Init() connect to RabbitMQ (%s) error: %v\", c.config.URI, err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t// close established connection in case of error\n\t\t\tcloseErr := c.connection.Close()\n\t\t\tif closeErr != nil {\n\t\t\t\terr = fmt.Errorf(\"%v: Consumer.Init() close connection to RabbitMQ error: %v\", err, closeErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\tc.channel, err = c.connection.Channel()\n\tif err != nil {\n\t\terrString := \"Consumer.Init() create channel to RabbitMQ (%s) error: %v\"\n\t\treturn fmt.Errorf(errString, c.config.URI, err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t// close established channel in case of error\n\t\t\tcloseErr := c.channel.Close()\n\t\t\tif closeErr != nil {\n\t\t\t\terr = fmt.Errorf(\"%v: Consumer.Init() close channel error: %v\", err, closeErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = c.channel.Qos(c.config.PrefetchCount, c.config.PrefetchSize, c.config.PrefetchGlobal)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Consumer.Init() declare prefetch policy error: %v\", err)\n\t}\n\n\tc.deliveryChannel, err = c.channel.Consume(\n\t\tc.config.Queue, // queue\n\t\tc.config.Name, // consumer\n\t\tc.config.AutoAck, // autoAck\n\t\tc.config.Exclusive, // exclusive\n\t\tc.config.NoLocal, // noLocal\n\t\tc.config.NoWait, // noWait\n\t\tnil, // TODO: may be I should add support for args\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Consumer.Init() create delivery channel error: %v\", err)\n\t}\n\n\t// channels for event listeners (connection)\n\tconnCloseChannel := make(chan *amqp.Error)\n\tc.connCloseChannel = c.connection.NotifyClose(connCloseChannel)\n\n\t// channels for event listeners (channel)\n\tchanCancelChannel := make(chan string)\n\tc.chanCancelChannel = c.channel.NotifyCancel(chanCancelChannel)\n\n\tchanCloseChannel := make(chan *amqp.Error)\n\tc.chanCloseChannel = c.channel.NotifyClose(chanCloseChannel)\n\n\treturn nil\n}", "func NewServer(rpc *cosmos.RPC, eventPublisher *publisher.EventPublisher, tokenToRunnerHash *sync.Map, logger tmlog.Logger) *Server {\n\treturn &Server{\n\t\trpc: rpc,\n\t\teventPublisher: eventPublisher,\n\t\ttokenToRunnerHash: tokenToRunnerHash,\n\t\texecInProgress: &sync.Map{},\n\t\tlogger: logger,\n\t}\n}", "func NewServer(config Config, shutdownChan chan bool) *server {\n\tif config.ReadTimeout == 0 {\n\t\tconfig.ReadTimeout = 10 * time.Second\n\t}\n\n\tif config.WriteTimeout == 0 {\n\t\tconfig.WriteTimeout = 10 * time.Second\n\t}\n\n\tconfig.nextCommandTimeout = 5 * time.Minute\n\n\treturn &server{\n\t\tconfig: config,\n\t\tshutdownChan: shutdownChan,\n\t}\n}", "func main(){\n\t//Connect to local host server\n\tport, err := amqp.Dial(\"amqp://guest:guest@rabbitmq:5672/\")\n\tfailError(err, \"Failed to connect to RabbitMQ.\")\n\tdefer port.Close()\n\n\t//Create a channel on port\n\tch, err := port.Channel()\n\tfailError(err, \"Failed to open a channel on port.\")\n\tdefer ch.Close()\n\n\t//Declare a callback queue\n\tqueue, err := ch.QueueDeclare(\n\t\t\"rpc_queue\", // name\n\t\tfalse, // durable flag\n\t\tfalse, // auto delete flag\n\t\tfalse, // exclusive flat\n\t\tfalse, // no-wait flag\n\t\tnil, // extra arguments\n\t)\n\tfailError(err, \"Failed to create a queue for channel.\")\n\n\t//Set QoS\n\terr = ch.Qos(\n\t\t1,\n\t\t0,\n\t\tfalse,\n\t\t)\n\tfailError(err, \"Failed to set channel QoS.\")\n\n\t//Register a client\n\tmsgs, err := ch.Consume(\n\t\tqueue.Name, // queue\n\t\t\"\", // consumer\n\t\tfalse, // auto-ack\n\t\tfalse, // exclusive\n\t\tfalse, // no-local\n\t\tfalse, // no-wait\n\t\tnil, // args\n\t)\n\tfailError(err, \"Failed to register a consumer\")\n\n\t//Channel repeats receiving to keep server running\n\tloop := make(chan bool)\n\n\t//Process message and reply\n\tgo func() {\n\t\tfor d := range msgs {\n\t\t\t//Receive a message from client\n\t\t\tphrase := string(d.Body)\n\n\t\t\t//Convert phrase into fields\n\t\t\tphraseArr := strings.Fields(phrase)\n\n\t\t\t//Extract array elements\n\t\t\ta, _ := strconv.Atoi(phraseArr[1])\n\t\t\tb, _ := strconv.Atoi(phraseArr[2])\n\t\t\tc, _ := strconv.Atoi(phraseArr[3])\n\n\t\t\tvar response string\n\n\t\t\t//Perform an image processing function based on input\n\t\t\tswitch{\n\t\t\tcase a == 1:\n\t\t\t\tlog.Printf(\"Scaling %s\\n\", phraseArr[0])\n\t\t\t\tresponse = scaleImg(phraseArr[0], b)\n\t\t\tcase a == 2:\n\t\t\t\tlog.Printf(\"Copying %s\\n\", phraseArr[0])\n\t\t\t\tresponse = copyImg(phraseArr[0], b, c)\n\n\t\t\tcase a == 3:\n\t\t\t\tlog.Printf(\"Recursing %s\\n\", phraseArr[0])\n\t\t\t\tresponse = recurseImg(phraseArr[0])\n\t\t\t}\n\n\n\t\t\terr = ch.Publish(\n\t\t\t\t\"\", // exchange\n\t\t\t\td.ReplyTo, // routing key\n\t\t\t\tfalse, // mandatory\n\t\t\t\tfalse, // immediate\n\t\t\t\tamqp.Publishing{\n\t\t\t\t\tContentType: \"text/plain\",\n\t\t\t\t\tCorrelationId: d.CorrelationId,\n\t\t\t\t\tBody: []byte(response),\n\t\t\t\t})\n\t\t\tfailError(err, \"Failed to publish a reply.\")\n\n\t\t\td.Ack(false)\n\t\t}\n\t}()\n\n\t//Waiting on messages\n\tlog.Printf(\"Waiting on RPC Message\")\n\t<-loop\n}", "func New() *Aggregator {\n\tmq, _ := messaging.Connect(\"amqp://guest:guest@localhost:5672/\")\n\treturn &Aggregator{\n\t\tservers: make(map[URL]*serverStats),\n\t\twindowSize: 120,\n\t\tmq: mq,\n\t\tlogger: log.New(os.Stdout, \"aggregator: \", log.LstdFlags),\n\t}\n}", "func newBroker(config []byte) (*broker, error) {\n\tvar b broker\n\tvar c Config\n\tif err := json.Unmarshal(config, &c); err != nil {\n\t\treturn &b, errors.Wrap(err, \"unable to parse AMQP config\")\n\t}\n\tif err := c.validate(); err != nil {\n\t\treturn &b, errors.Wrap(err, \"could not validate config\")\n\t}\n\tb.Config = c\n\tb.closed = make(chan *amqp.Error)\n\tclose(b.closed)\n\treturn &b, nil\n}", "func Server(l net.Listener) {\n\tcont := electron.NewContainer(\"server\")\n\tc, err := cont.Accept(l)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tl.Close() // This server only accepts one connection\n\t// Process incoming endpoints till we get a Receiver link\n\tvar r electron.Receiver\n\tfor r == nil {\n\t\tin := <-c.Incoming()\n\t\tswitch in := in.(type) {\n\t\tcase *electron.IncomingSession, *electron.IncomingConnection:\n\t\t\tin.Accept() // Accept the incoming connection and session for the receiver\n\t\tcase *electron.IncomingReceiver:\n\t\t\tin.SetCapacity(10)\n\t\t\tin.SetPrefetch(true) // Automatic flow control for a buffer of 10 messages.\n\t\t\tr = in.Accept().(electron.Receiver)\n\t\tcase nil:\n\t\t\treturn // Connection is closed\n\t\tdefault:\n\t\t\tin.Reject(amqp.Errorf(\"example-server\", \"unexpected endpoint %v\", in))\n\t\t}\n\t}\n\tgo func() { // Reject any further incoming endpoints\n\t\tfor in := range c.Incoming() {\n\t\t\tin.Reject(amqp.Errorf(\"example-server\", \"unexpected endpoint %v\", in))\n\t\t}\n\t}()\n\t// Receive messages till the Receiver closes\n\trm, err := r.Receive()\n\tfor ; err == nil; rm, err = r.Receive() {\n\t\tfmt.Printf(\"server received: %q\\n\", rm.Message.Body())\n\t\trm.Accept() // Signal to the client that the message was accepted\n\t}\n\tfmt.Printf(\"server receiver closed: %v\\n\", err)\n}", "func NewServer(config *Config, logger kitlog.Logger) *Server {\n\tdb := postgres.NewDB(&postgres.Config{\n\t\tConnStr: config.ConnStr,\n\t\tEncryptionPassword: config.EncryptionPassword,\n\t}, logger)\n\n\tds := datastore.NewDatastoreProtobufClient(\n\t\tconfig.DatastoreAddr,\n\t\t&http.Client{\n\t\t\tTimeout: time.Second * 10,\n\t\t},\n\t)\n\n\tmv := pipeline.NewMovingAverager(config.Verbose, clock.New(), logger)\n\n\tprocessor := pipeline.NewProcessor(ds, mv, config.Verbose, logger)\n\n\tmqttClient := mqtt.NewClient(logger, config.Verbose)\n\n\tenc := rpc.NewEncoder(&rpc.Config{\n\t\tDB: db,\n\t\tMQTTClient: mqttClient,\n\t\tProcessor: processor,\n\t\tVerbose: config.Verbose,\n\t\tBrokerAddr: config.BrokerAddr,\n\t\tBrokerUsername: config.BrokerUsername,\n\t}, logger)\n\n\thooks := twrpprom.NewServerHooks(registry.DefaultRegisterer)\n\n\tbuildInfo.WithLabelValues(version.BinaryName, version.Version, version.BuildDate)\n\n\tlogger = kitlog.With(logger, \"module\", \"server\")\n\tlogger.Log(\n\t\t\"msg\", \"creating server\",\n\t\t\"datastore\", config.DatastoreAddr,\n\t\t\"mqttBroker\", config.BrokerAddr,\n\t\t\"listenAddr\", config.ListenAddr,\n\t\t\"mqttUsername\", config.BrokerAddr,\n\t)\n\n\ttwirpHandler := encoder.NewEncoderServer(enc, hooks)\n\n\t// multiplex twirp handler into a mux with our other handlers\n\tmux := goji.NewMux()\n\n\tmux.Handle(pat.Post(encoder.EncoderPathPrefix+\"*\"), twirpHandler)\n\tmux.Handle(pat.Get(\"/pulse\"), PulseHandler(db))\n\tmux.Handle(pat.Get(\"/metrics\"), promhttp.Handler())\n\n\tmux.Use(middleware.RequestIDMiddleware)\n\n\tmetricsMiddleware := middleware.MetricsMiddleware(\"decode\", \"encoder\", registry.DefaultRegisterer)\n\tmux.Use(metricsMiddleware)\n\n\t// create our http.Server instance\n\tsrv := &http.Server{\n\t\tAddr: config.ListenAddr,\n\t\tHandler: mux,\n\t}\n\n\t// return the instantiated server\n\treturn &Server{\n\t\tsrv: srv,\n\t\tencoder: enc,\n\t\tdb: db,\n\t\tmqtt: mqttClient,\n\t\tlogger: kitlog.With(logger, \"module\", \"server\"),\n\t\tdomains: config.Domains,\n\t}\n}", "func NewRabbitMQScaler(config *ScalerConfig) (Scaler, error) {\n\thttpClient := kedautil.CreateHTTPClient(config.GlobalHTTPTimeout)\n\tmeta, err := parseRabbitMQMetadata(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing rabbitmq metadata: %s\", err)\n\t}\n\n\tif meta.protocol == httpProtocol {\n\t\treturn &rabbitMQScaler{\n\t\t\tmetadata: meta,\n\t\t\thttpClient: httpClient,\n\t\t}, nil\n\t}\n\n\t// Override vhost if requested.\n\thost := meta.host\n\tif meta.vhostName != nil {\n\t\thostURI, err := amqp.ParseURI(host)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing rabbitmq connection string: %s\", err)\n\t\t}\n\t\thostURI.Vhost = *meta.vhostName\n\t\thost = hostURI.String()\n\t}\n\n\tconn, ch, err := getConnectionAndChannel(host)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error establishing rabbitmq connection: %s\", err)\n\t}\n\n\treturn &rabbitMQScaler{\n\t\tmetadata: meta,\n\t\tconnection: conn,\n\t\tchannel: ch,\n\t\thttpClient: httpClient,\n\t}, nil\n}", "func NewDefaultChannel() amqp.Channel {\n\tconn, err := amqp.Dial(\"amqp://guest:guest@localhost:5672/\")\n\tfailOnError(err, \"Failed to connect to RabbitMQ\")\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tfailOnError(err, \"Failed to open channel\")\n\t}\n\treturn *ch\n}", "func newServer() *negroni.Negroni {\n\tn := negroni.Classic()\n\tn.UseHandler(router())\n\treturn n\n}", "func Publisher(\n\tconStr string, // sample: \"amqp://guest:guest@127.0.0.1:5672/\"\n\tqueueName string,\n\tmsg []byte) bool {\n\tret := false\n\n\t//============================================\n\t// Connect to Server\n\t//============================================\n\tconn, err := amqp.Dial(conStr)\n\tif err != nil {\n\t\tutil.Log(\"(RabbitMQ=>Publisher) Failed to connect to RabbitMQ\", err)\n\n\t\tdefer conn.Close()\n\t\treturn ret\n\t}\n\n\t//============================================\n\t// Create Channel\n\t//============================================\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tutil.Log(\"(RabbitMQ=>Publisher) Failed to open a channel\", err)\n\n\t\tdefer ch.Close()\n\t\tdefer conn.Close()\n\t\treturn ret\n\t}\n\n\t//============================================\n\t// Create Queue\n\t//============================================\n\tq, err := ch.QueueDeclare(\n\t\tqueueName, // name\n\t\ttrue, // durable\n\t\tfalse, // delete when unused\n\t\tfalse, // exclusive\n\t\tfalse, // no-wait\n\t\tnil, // arguments\n\t)\n\n\tif err != nil {\n\t\tutil.Log(\"(RabbitMQ=>Publisher) Failed to declare a queue\", err)\n\n\t\tdefer ch.Close()\n\t\tdefer conn.Close()\n\t\treturn ret\n\t}\n\n\t//============================================\n\t// Send Message\n\t//============================================\n\tbody := msg\n\terr = ch.Publish(\n\t\t\"\", // exchange\n\t\tq.Name, // routing key\n\t\tfalse, // mandatory\n\t\tfalse, // immediate\n\t\tamqp.Publishing{\n\t\t\tContentType: \"text/plain\",\n\t\t\tBody: body,\n\t\t\tDeliveryMode: amqp.Persistent, // 1=Transient(non-persistent), 2=Persistent\n\t\t})\n\n\tif err == nil {\n\t\tret = true\n\t} else {\n\t\tutil.Log(\"(RabbitMQ=>Publisher) Failed to publish a message\", err)\n\t}\n\n\t//============================================\n\t// Close\n\t//============================================\n\tdefer ch.Close()\n\tdefer conn.Close()\n\n\t//============================================\n\t// Return\n\t//============================================\n\treturn ret\n}", "func NewServer(db db, queue queue, logger logging.Logger, apiToken string, enableAPI, enableJobs bool) (*Server, error) {\n\treturn &Server{\n\t\tlogger: logger,\n\t\tqueue: queue,\n\t\tdb: db,\n\t\tapiToken: apiToken,\n\t\tenableAPI: enableAPI,\n\t\tenableJobs: enableJobs,\n\t}, nil\n}", "func NewRabbitMQClient(configurations config.RabbitMQConfigurations) (MessageClient, error) {\n\tconnection, channel, queue, err := setupRabbitMQ(configurations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewClient := &RabbitMQClient{\n\t\texchangeName: configurations.ExchangeName,\n\t\tqueueName: configurations.QueueName,\n\t\turl: configurations.URL,\n\t\tconnection: connection,\n\t\tchannel: channel,\n\t\tqueue: queue,\n\t}\n\n\treturn newClient, nil\n}", "func NewServer(t *testing.T, dbc *sql.DB) (*server.Server, string) {\n\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tjtest.RequireNil(t, err)\n\n\tgrpcServer := grpc.NewServer(\n\t\tgrpc.UnaryInterceptor(interceptors.UnaryServerInterceptor),\n\t\tgrpc.StreamInterceptor(interceptors.StreamServerInterceptor))\n\n\tsrv := server.New(dbc, dbc)\n\n\tpb.RegisterGokuServer(grpcServer, srv)\n\n\tgo func() {\n\t\terr := grpcServer.Serve(l)\n\t\tjtest.RequireNil(t, err)\n\t}()\n\n\treturn srv, l.Addr().String()\n}", "func (mq *MessageQueue) NewChannel() (*amqp.Channel, error) {\n\tch, err := mq.Connection.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tch.Qos(mq.Prefetch, 0, false)\n\treturn ch, nil\n}", "func NewServer() *Server {\n return &Server{\n Addr: DefaultAddr,\n }\n}", "func NewServer(options ...Option) *Server {\n\ts := &Server{\n\t\tsubscriptions: make(map[string]map[string]struct{}),\n\t}\n\ts.BaseService = *service.NewBaseService(nil, \"PubSub\", s)\n\n\tfor _, option := range options {\n\t\toption(s)\n\t}\n\n\t// if BufferCapacity option was not set, the channel is unbuffered\n\ts.cmds = make(chan cmd, s.cmdsCap)\n\n\treturn s\n}", "func New(cfg *Config) (*Handler, error) {\n\thandler := new(Handler)\n\turi := fmt.Sprintf(`amqp://%s`, cfg.Username)\n\turi += fmt.Sprintf(`:%s`, cfg.Password)\n\turi += fmt.Sprintf(`@%s:5672`, cfg.Host)\n\tif cfg.Vhost != \"/\" {\n\t\turi += fmt.Sprintf(`/%s`, cfg.Vhost)\n\t}\n\n\tconn, err := amqp.Dial(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thandler.conn = conn\n\treturn handler, nil\n\n}", "func (s *Server) newServer(spec *loads.Document, tcpPort int) *healthApi.Server {\n\tapi := restapi.NewCiliumHealthAPI(spec)\n\tapi.Logger = log.Printf\n\n\t// /hello\n\tapi.GetHelloHandler = NewGetHelloHandler(s)\n\n\tif enableAPI(s.Config.Admin, tcpPort) {\n\t\tapi.GetHealthzHandler = NewGetHealthzHandler(s)\n\t\tapi.ConnectivityGetStatusHandler = NewGetStatusHandler(s)\n\t\tapi.ConnectivityPutStatusProbeHandler = NewPutStatusProbeHandler(s)\n\t}\n\n\tsrv := healthApi.NewServer(api)\n\tif tcpPort == 0 {\n\t\tsrv.EnabledListeners = []string{\"unix\"}\n\t\tsrv.SocketPath = flags.Filename(defaults.SockPath)\n\t} else {\n\t\tsrv.EnabledListeners = []string{\"http\"}\n\t\tsrv.Port = tcpPort\n\t\tsrv.Host = \"\" // FIXME: Allow binding to specific IPs\n\t}\n\tsrv.ConfigureAPI()\n\n\treturn srv\n}", "func NewServer(mqttEndpoint string) Server {\n\treturn &server{\n\t\tdbPath: GetRandomDBName(),\n\t\tmqttEndpoint: mqttEndpoint,\n\t}\n}", "func newConfigServer() *ConfigServer {\n\treturn &ConfigServer{}\n}", "func main() {\n\n\tconn, err := amqp.Dial(\"amqp://guest:guest@localhost:5672/\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tpanic(err)\n\t}\n\n\tdefer conn.Close()\n\n\tfmt.Println(\"Successfully connected to our RabbitMQ\")\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tpanic(err)\n\t}\n\tdefer ch.Close()\n\n\tq, err := ch.QueueDeclare(\"Test Queue\", false, false, false, false, nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(q)\n\n\tfor i := 0; i < 1000; i++ {\n\n\t\terr = ch.Publish(\"\", \"Test Queue\", false, false, amqp.Publishing{\n\t\t\tContentType: \"test/plain\",\n\t\t\tBody: []byte(\"Hello world!\"),\n\t\t})\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(\"Successfully published Message to Queue\")\n\t\ttime.Sleep(time.Second)\n\t}\n\n\tfmt.Println(q)\n}", "func NewServer(config *Config, cmFilter types.ClusterManagerFilter, clMng types.ClusterManager) Server {\n\tif config != nil {\n\t\t//graceful timeout setting\n\t\tif config.GracefulTimeout != 0 {\n\t\t\tGracefulTimeout = config.GracefulTimeout\n\t\t}\n\n\t\tnetwork.UseNetpollMode = config.UseNetpollMode\n\t\tif config.UseNetpollMode {\n\t\t\tlog.DefaultLogger.Infof(\"[server] [reconfigure] [new server] Netpoll mode enabled.\")\n\t\t}\n\t}\n\n\tkeeper.OnProcessShutDown(log.CloseAll)\n\n\tserver := &server{\n\t\tserverName: config.ServerName,\n\t\tstopChan: make(chan struct{}),\n\t\thandler: NewHandler(cmFilter, clMng),\n\t}\n\n\tinitListenerAdapterInstance(server.serverName, server.handler)\n\n\tservers = append(servers, server)\n\n\treturn server\n}", "func NewServer() *server {\n\treturn &server{}\n}", "func PrepareRabbitMQ(\n\tc config.Config,\n) (*amqp.Connection, *amqp.Queue, *amqp.Channel, error) {\n\t// connect to rabbit\n\tconn, err := amqp.Dial(c.MQURI)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tq, err := ch.QueueDeclare(\n\t\t\"notifications\", // name\n\t\ttrue, // durable\n\t\tfalse, // delete when unused\n\t\tfalse, // exclusion\n\t\tfalse, // no-wait\n\t\tnil, // args\n\t)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\treturn conn, &q, ch, nil\n}", "func NewServer(config *Config) *Server {\n\treturn &Server{\n\t\tconfig: config,\n\t\trouter: chi.NewRouter(),\n\t}\n}", "func NewServer(config config.Provider, service *service.Service, dbMysql *gorp.DbMap, dbPostgre *gorp.DbMap, cachePool *redis.Pool, logger *log.Logger) IServer {\n\treturn &server{\n\t\tconfig: config,\n\t\tservice: service,\n\t\tdbMysql: dbMysql,\n\t\tdbPostgre: dbPostgre,\n\t\tcachePool: cachePool,\n\t\tlogger: logger,\n\t}\n}", "func NewConsumer(cfg Config) *Consumer {\n\tconsumer := &Consumer{\n\t\tconfig: cfg,\n\t\tpubDeliveryChannel: make(chan amqp.Delivery, 100), // TODO: buffer size to config\n\t\treconnectMutex: make(chan struct{}, 1),\n\t\tfatalChannel: make(chan struct{}, 1),\n\t\tinvalidationChannel: make(chan struct{}, 1),\n\t\twg: sync.WaitGroup{},\n\t}\n\treturn consumer\n}", "func NewServer(appSender common.AppSender) *Server {\n\treturn &Server{appSender: appSender}\n}", "func initAmqp() (*amqp.Connection, *amqp.Channel) {\n\tconn, err := amqp.Dial(*amqpURI)\n\tfailOnError(err, \"Failed to connect to RabbitMQ\")\n\n\tch, err := conn.Channel()\n\tfailOnError(err, \"Failed to open a channel\")\n\n\terr = ch.ExchangeDeclare(\n\t\t\"test-exchange\", // name\n\t\t\"direct\", // type\n\t\ttrue, // durable\n\t\tfalse, // auto-deleted\n\t\tfalse, // internal\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\tfailOnError(err, \"Failed to declare the Exchange\")\n\treturn conn, ch\n}", "func NewServer(logger log.Logger, options ...Option) *Server {\n\ts := &Server{logger: logger}\n\n\ts.BaseService = *service.NewBaseService(logger, \"PubSub\", s)\n\tfor _, opt := range options {\n\t\topt(s)\n\t}\n\n\t// The queue receives items to be published.\n\ts.queue = make(chan item, s.queueCap)\n\n\t// The index tracks subscriptions by ID and query terms.\n\ts.subs.index = newSubIndex()\n\n\treturn s\n}", "func NewServer(options ...Option) *Server {\n\ts := &Server{\n\t\tsubscriptions: make(map[string]map[string]Query),\n\t}\n\ts.BaseService = *cmn.NewBaseService(nil, \"PubSub\", s)\n\n\tfor _, option := range options {\n\t\toption(s)\n\t}\n\n\t// if BufferCapacity option was not set, the channel is unbuffered\n\ts.cmds = make(chan cmd, s.cmdsCap)\n\n\treturn s\n}", "func RabbitMQConnect(addr string) (*RmqConnection, error) {\n\tvar c RmqConnection\n\tvar err error\n\tif c.conn, err = amqp.Dial(addr); err != nil {\n\t\treturn nil, err\n\t}\n\tif c.ch, err = c.conn.Channel(); err != nil {\n\t\tc.conn.Close()\n\t\treturn nil, err\n\t}\n\tc.stop = make(chan struct{})\n\tc.wg = &sync.WaitGroup{}\n\treturn &c, nil\n}", "func NewServer(credentials *RegistryCredentials, registryURL string) api.PublishRequestServer {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\t// creates the clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\ts := &publisherServer{Clientset: clientset, Credentials: credentials, RegistryURL: registryURL}\n\treturn s\n}", "func New(ctx context.Context, cfg models.Config) (*Queue, error) {\n\tconn, err := connect(ctx, cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to connect to RabbitMQ \")\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to open a channel \")\n\t}\n\n\t_, err = ch.QueueDeclare(\"ItemQueue\", false, false, false, false, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to declare a queue \")\n\t}\n\n\treturn &Queue{ch, conn}, nil\n}", "func (r *RabbitMQ) Init(metadata bindings.Metadata) error {\n\tmeta, err := r.getRabbitMQMetadata(metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.metadata = meta\n\n\tconn, err := amqp.Dial(meta.Host)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.connection = conn\n\tr.channel = ch\n\treturn nil\n}", "func NewServer(conf config.Config) *Server {\n\tlog := logrus.New()\n\tif conf.Debug {\n\t\tlog.SetLevel(logrus.DebugLevel)\n\t}\n\tserver := &Server{\n\t\tconf: conf,\n\t\trouter: chi.NewRouter(),\n\t\troomManager: rooms.NewManager(log),\n\t\tlog: log,\n\t}\n\n\tr := server.router\n\t// A good base middleware stack\n\tr.Use(middleware.RequestID)\n\tr.Use(middleware.RealIP)\n\tr.Use(middleware.Logger)\n\tr.Use(middleware.Recoverer)\n\n\tr.Handle(\"/metrics\", promhttp.Handler())\n\tr.Get(\"/rooms/{roomName}/websocket\", server.websocketHandler)\n\tr.Group(func(r chi.Router) {\n\t\t// set timeout for non classic http calls\n\t\tr.Use(middleware.Timeout(60 * time.Second))\n\t\tserver.mountRestRoutes(r)\n\t\tserver.mountFileRoutes(r)\n\n\t})\n\n\treturn server\n}", "func NewServer(binding string, nodeMgr NodeManagerInterface) GRPCServer {\n\ts := grpc.NewServer()\n\tmyServer := &server{\n\t\tbinding: binding,\n\t\ts: s,\n\t\tnodeMgr: nodeMgr,\n\t}\n\tpb.RegisterCloudProviderVsphereServer(s, myServer)\n\treflection.Register(s)\n\treturn myServer\n}", "func NewConnection(d string) (*amqp.Connection, error) {\n\treturn amqp.Dial(d)\n}", "func NewServer(chatCmd chat.CommandService, chatQuery chat.QueryService, chatHub chat.Hub, login chat.LoginService, conf *Config) *Server {\n\tif conf == nil {\n\t\tconf = &DefaultConfig\n\t}\n\n\te := echo.New()\n\te.HideBanner = true\n\n\ts := &Server{\n\t\techo: e,\n\t\tloginHandler: NewLoginHandler(login),\n\t\trestHandler: NewRESTHandler(chatCmd, chatQuery),\n\t\tchatHub: chatHub,\n\t\tconf: *conf,\n\t}\n\ts.wsServer = ws.NewServerFunc(s.handleWsConn)\n\n\t// initilize router\n\te.Use(middleware.Logger())\n\te.Use(middleware.Recover())\n\n\t// set login handler\n\te.Use(s.loginHandler.Middleware())\n\te.POST(\"/login\", s.loginHandler.Login).\n\t\tName = \"doLogin\"\n\te.GET(\"/login\", s.loginHandler.GetLoginState).\n\t\tName = \"getLoginInfo\"\n\te.POST(\"/logout\", s.loginHandler.Logout).\n\t\tName = \"doLogout\"\n\n\tchatPath := path.Join(s.conf.ChatAPIPrefix, \"/chat\")\n\tchatGroup := e.Group(chatPath, s.loginHandler.Filter())\n\n\t// set restHandler\n\tchatGroup.POST(\"/rooms\", s.restHandler.CreateRoom).\n\t\tName = \"chat.createRoom\"\n\tchatGroup.DELETE(\"/rooms/:room_id\", s.restHandler.DeleteRoom).\n\t\tName = \"chat.deleteRoom\"\n\tchatGroup.GET(\"/rooms/:room_id\", s.restHandler.GetRoomInfo).\n\t\tName = \"chat.getRoomInfo\"\n\tchatGroup.POST(\"/rooms/:room_id/members\", s.restHandler.AddRoomMember).\n\t\tName = \"chat.addRoomMember\"\n\tchatGroup.DELETE(\"/rooms/:room_id/members\", s.restHandler.RemoveRoomMember).\n\t\tName = \"chat.removeRoomMember\"\n\n\tchatGroup.GET(\"/users/:user_id\", s.restHandler.GetUserInfo).\n\t\tName = \"chat.getUserInfo\"\n\n\tchatGroup.POST(\"/rooms/:room_id/messages\", s.restHandler.PostRoomMessage).\n\t\tName = \"chat.postRoomMessage\"\n\tchatGroup.GET(\"/rooms/:room_id/messages\", s.restHandler.GetRoomMessages).\n\t\tName = \"chat.getRoomMessages\"\n\tchatGroup.POST(\"/rooms/:room_id/messages/read\", s.restHandler.ReadRoomMessages).\n\t\tName = \"chat.readRoomMessages\"\n\tchatGroup.GET(\"/rooms/:room_id/messages/unread\", s.restHandler.GetUnreadRoomMessages).\n\t\tName = \"chat.getUnreadRoomMessages\"\n\n\t// set websocket handler\n\tchatGroup.GET(\"/ws\", s.serveChatWebsocket).\n\t\tName = \"chat.connentWebsocket\"\n\n\t// serve static content\n\tif s.conf.EnableServeStaticFile {\n\t\troute := path.Join(s.conf.StaticHandlerPrefix, \"/\")\n\t\te.Static(route, s.conf.StaticFileDir).Name = \"staticContents\"\n\t}\n\treturn s\n}", "func NewServer(be Backend) *Server {\n\treturn &Server{\n\t\t// Doubled maximum line length per RFC 5321 (Section 4.5.3.1.6)\n\t\tMaxLineLength: 2000,\n\n\t\tBackend: be,\n\t\tdone: make(chan struct{}, 1),\n\t\tErrorLog: log.New(os.Stderr, \"smtp/server \", log.LstdFlags),\n\t\tcaps: []string{\"PIPELINING\", \"8BITMIME\", \"ENHANCEDSTATUSCODES\", \"CHUNKING\"},\n\t\tauths: map[string]SaslServerFactory{\n\t\t\tsasl.Plain: func(conn *Conn) sasl.Server {\n\t\t\t\treturn sasl.NewPlainServer(func(identity, username, password string) error {\n\t\t\t\t\tif identity != \"\" && identity != username {\n\t\t\t\t\t\treturn errors.New(\"identities not supported\")\n\t\t\t\t\t}\n\n\t\t\t\t\tsess := conn.Session()\n\t\t\t\t\tif sess == nil {\n\t\t\t\t\t\tpanic(\"No session when AUTH is called\")\n\t\t\t\t\t}\n\n\t\t\t\t\treturn sess.AuthPlain(username, password)\n\t\t\t\t})\n\t\t\t},\n\t\t},\n\t\tconns: make(map[*Conn]struct{}),\n\t}\n}", "func NewServer(configFilename string, config *Config) *Server {\n\tcasefoldedName, err := Casefold(config.Server.Name)\n\tif err != nil {\n\t\tlog.Println(fmt.Sprintf(\"Server name isn't valid: [%s]\", config.Server.Name), err.Error())\n\t\treturn nil\n\t}\n\n\t// startup check that we have HELP entries for every command\n\tfor name := range Commands {\n\t\t_, exists := Help[strings.ToLower(name)]\n\t\tif !exists {\n\t\t\tlog.Fatal(\"Help entry does not exist for \", name)\n\t\t}\n\t}\n\n\tif config.AuthenticationEnabled {\n\t\tSupportedCapabilities[SASL] = true\n\t}\n\n\tif config.Limits.LineLen.Tags > 512 || config.Limits.LineLen.Rest > 512 {\n\t\tSupportedCapabilities[MaxLine] = true\n\t\tCapValues[MaxLine] = fmt.Sprintf(\"%d,%d\", config.Limits.LineLen.Tags, config.Limits.LineLen.Rest)\n\t}\n\n\toperClasses, err := config.OperatorClasses()\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading oper classes:\", err.Error())\n\t}\n\topers, err := config.Operators(operClasses)\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading operators:\", err.Error())\n\t}\n\n\tconnectionLimits, err := NewConnectionLimits(config.Server.ConnectionLimits)\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading connection limits:\", err.Error())\n\t}\n\tconnectionThrottle, err := NewConnectionThrottle(config.Server.ConnectionThrottle)\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading connection throttler:\", err.Error())\n\t}\n\n\tserver := &Server{\n\t\taccounts: make(map[string]*ClientAccount),\n\t\tauthenticationEnabled: config.AuthenticationEnabled,\n\t\tchannels: make(ChannelNameMap),\n\t\tclients: NewClientLookupSet(),\n\t\tcommands: make(chan Command),\n\t\tconfigFilename: configFilename,\n\t\tconnectionLimits: connectionLimits,\n\t\tconnectionThrottle: connectionThrottle,\n\t\tctime: time.Now(),\n\t\tcurrentOpers: make(map[*Client]bool),\n\t\tidle: make(chan *Client),\n\t\tlimits: Limits{\n\t\t\tAwayLen: int(config.Limits.AwayLen),\n\t\t\tChannelLen: int(config.Limits.ChannelLen),\n\t\t\tKickLen: int(config.Limits.KickLen),\n\t\t\tMonitorEntries: int(config.Limits.MonitorEntries),\n\t\t\tNickLen: int(config.Limits.NickLen),\n\t\t\tTopicLen: int(config.Limits.TopicLen),\n\t\t\tChanListModes: int(config.Limits.ChanListModes),\n\t\t\tLineLen: LineLenLimits{\n\t\t\t\tTags: config.Limits.LineLen.Tags,\n\t\t\t\tRest: config.Limits.LineLen.Rest,\n\t\t\t},\n\t\t},\n\t\tlisteners: make(map[string]ListenerInterface),\n\t\tmonitoring: make(map[string][]Client),\n\t\tname: config.Server.Name,\n\t\tnameCasefolded: casefoldedName,\n\t\tnetworkName: config.Network.Name,\n\t\tnewConns: make(chan clientConn),\n\t\toperclasses: *operClasses,\n\t\toperators: opers,\n\t\tsignals: make(chan os.Signal, len(ServerExitSignals)),\n\t\trehashSignal: make(chan os.Signal, 1),\n\t\trestAPI: &config.Server.RestAPI,\n\t\twhoWas: NewWhoWasList(config.Limits.WhowasEntries),\n\t\tcheckIdent: config.Server.CheckIdent,\n\t}\n\n\t// open data store\n\tdb, err := buntdb.Open(config.Datastore.Path)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Failed to open datastore: %s\", err.Error()))\n\t}\n\tserver.store = db\n\n\t// check db version\n\terr = server.store.View(func(tx *buntdb.Tx) error {\n\t\tversion, _ := tx.Get(keySchemaVersion)\n\t\tif version != latestDbSchema {\n\t\t\tlog.Println(fmt.Sprintf(\"Database must be updated. Expected schema v%s, got v%s.\", latestDbSchema, version))\n\t\t\treturn errDbOutOfDate\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\t// close the db\n\t\tdb.Close()\n\t\treturn nil\n\t}\n\n\t// load *lines\n\tserver.loadDLines()\n\tserver.loadKLines()\n\n\t// load password manager\n\terr = server.store.View(func(tx *buntdb.Tx) error {\n\t\tsaltString, err := tx.Get(keySalt)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Could not retrieve salt string: %s\", err.Error())\n\t\t}\n\n\t\tsalt, err := base64.StdEncoding.DecodeString(saltString)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpwm := NewPasswordManager(salt)\n\t\tserver.passwords = &pwm\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Could not load salt: %s\", err.Error()))\n\t}\n\n\tif config.Server.MOTD != \"\" {\n\t\tfile, err := os.Open(config.Server.MOTD)\n\t\tif err == nil {\n\t\t\tdefer file.Close()\n\n\t\t\treader := bufio.NewReader(file)\n\t\t\tfor {\n\t\t\t\tline, err := reader.ReadString('\\n')\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tline = strings.TrimRight(line, \"\\r\\n\")\n\t\t\t\t// \"- \" is the required prefix for MOTD, we just add it here to make\n\t\t\t\t// bursting it out to clients easier\n\t\t\t\tline = fmt.Sprintf(\"- %s\", line)\n\n\t\t\t\tserver.motdLines = append(server.motdLines, line)\n\t\t\t}\n\t\t}\n\t}\n\n\tif config.Server.Password != \"\" {\n\t\tserver.password = config.Server.PasswordBytes()\n\t}\n\n\tfor _, addr := range config.Server.Listen {\n\t\tserver.createListener(addr, config.TLSListeners())\n\t}\n\n\tif config.Server.Wslisten != \"\" {\n\t\tserver.wslisten(config.Server.Wslisten, config.Server.TLSListeners)\n\t}\n\n\t// registration\n\taccountReg := NewAccountRegistration(config.Registration.Accounts)\n\tserver.accountRegistration = &accountReg\n\n\t// Attempt to clean up when receiving these signals.\n\tsignal.Notify(server.signals, ServerExitSignals...)\n\tsignal.Notify(server.rehashSignal, syscall.SIGHUP)\n\n\tserver.setISupport()\n\n\t// start API if enabled\n\tif server.restAPI.Enabled {\n\t\tLog.info.Printf(\"%s rest API started on %s .\", server.name, server.restAPI.Listen)\n\t\tserver.startRestAPI()\n\t}\n\n\treturn server\n}", "func InitializeRabbitConnection(credentials *Credentials) {\n\tRabbitConnection, _ = createRabbitConnection(credentials)\n\t/*\n\t\tconfig.Config.Rabbit.Host,\n\t\t\tconfig.Config.Rabbit.Port,\n\t\t\tconfig.Config.Rabbit.Username,\n\t\t\tconfig.Config.Rabbit.Password,\n\t\t)*/\n}", "func RabbitMQAMQP(server, vHost string) Option {\n\treturn func(c *config) {\n\t\tc.serverURL = server\n\t\tc.vHost = vHost\n\t}\n}", "func newServer(handler connHandler, logger *zap.Logger) *server {\n\ts := &server{\n\t\thandler: handler,\n\t\tlogger: logger.With(zap.String(\"sector\", \"server\")),\n\t}\n\treturn s\n}", "func NewServer(c *Config) (*Server, error) {\n\t// validate config\n\tif err := validation.Validate.Struct(c); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid config: %v\", err)\n\t}\n\n\t// create root context\n\tctx, cancel := context.WithCancel(context.Background())\n\n\t// register handlers\n\tmux := runtime.NewServeMux()\n\topts := []grpc.DialOption{grpc.WithInsecure()}\n\terr := proto.RegisterTodosHandlerFromEndpoint(ctx, mux, c.Endpoint, opts)\n\tif err != nil {\n\t\tdefer cancel()\n\t\treturn nil, fmt.Errorf(\"unable to register gateway handler: %v\", err)\n\t}\n\n\ts := Server{\n\t\tcancel: cancel,\n\t\tlog: c.Log,\n\t\tmux: mux,\n\t\tport: c.Port,\n\t}\n\treturn &s, nil\n}", "func NewSignalingServer(callQueue CallQueue) *SignalingServer {\n\treturn &SignalingServer{callQueue: callQueue}\n}", "func NewAMQPConsumer(config AMQPConfig, rk string) (*AMQPConsumer, error) {\n\ta, err := NewAMQP(config.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tDebug(\"amqp: setting channel QoS to\", config.Qos)\n\tif err := a.Channel.Qos(config.Qos, 0, false); err != nil {\n\t\treturn nil, err\n\t}\n\n\te := config.Exchange\n\tif err := a.Channel.ExchangeDeclare(\n\t\te.Name,\n\t\te.Kind,\n\t\te.Durable,\n\t\te.AutoDelete,\n\t\te.Internal,\n\t\te.NoWait,\n\t\tnil,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\tq := config.Queue\n\tqueue, err := a.Channel.QueueDeclare(\n\t\tq.Name,\n\t\tq.Durable,\n\t\tq.AutoDelete,\n\t\tq.Exclusive,\n\t\tq.NoWait,\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, exch := range config.Queue.Bind {\n\t\tif err := a.Channel.QueueBind(queue.Name, rk, exch, q.NoWait, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tDebugf(\"amqp: binded queue %s to exchange %s with routing key %s\", queue.Name, exch, rk)\n\t}\n\n\treturn &AMQPConsumer{\n\t\tAMQP: a,\n\t\tConfig: config,\n\t\tQueue: queue,\n\t}, nil\n}", "func NewServer(cfg *Config) *Server {\n\treturn &Server{cfg}\n}", "func NewServer() *Server {\n\tlog.Println(\"Creating new instance of chat server...\")\n\treturn &Server{\n\t\trooms: make(map[string]*client.Room),\n\t\tcommands: make(chan client.Command),\n\t}\n}", "func NewServer() (Server, error) {\n\tconfig, err := config.GetConfig()\n\tif err != nil {\n\t\treturn Server{}, err\n\t}\n\n\tlogFormatter := &logrus.TextFormatter{\n\t\tFullTimestamp: true,\n\t\tTimestampFormat: \"2006-01-02 15:04:05-0700\",\n\t}\n\tlogger := logrus.New()\n\tlogger.Formatter = logFormatter\n\n\tdatabaseConnection, err := db.NewDatabaseConnection(logger)\n\tif err != nil {\n\t\treturn Server{}, err\n\t}\n\n\terr = databaseConnection.Connect()\n\tif err != nil {\n\t\treturn Server{}, err\n\t}\n\n\t_, err = setup(databaseConnection)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\tupstreamChannel := make(chan firebasexmpp.UpstreamMessage)\n\tsendChannel := make(chan firebasexmpp.DownstreamPayload)\n\tsupervisor := NewXMPPSupervisor(upstreamChannel, sendChannel, logger)\n\n\tlistenAddress := config.Web.GetListenAddress()\n\twebserver, err := web.NewWebserver(listenAddress, databaseConnection, sendChannel, logger)\n\tif err != nil {\n\t\treturn Server{}, err\n\t}\n\n\treturn Server{\n\t\tdatabaseConnection: databaseConnection,\n\t\tlogger: logger,\n\t\tupstreamChannel: upstreamChannel,\n\t\tsendChannel: sendChannel,\n\t\tsupervisor: supervisor,\n\t\twebserver: webserver,\n\t}, nil\n}", "func NewServer(upstreams []*Upstream, cfg Config) *Server {\n\tdialer := cfg.Dialer\n\tif dialer == nil {\n\t\tdialer = &net.Dialer{}\n\t}\n\tlogger := cfg.Logger\n\tif logger == nil {\n\t\tlogger = log.DefaultLogger()\n\t}\n\n\ts := &Server{\n\t\tServer: well.Server{\n\t\t\tShutdownTimeout: cfg.ShutdownTimeout,\n\t\t},\n\n\t\tupstreams: upstreams,\n\t\tlogger: logger,\n\t\tdialer: dialer,\n\t\tpool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\tbuf := make([]byte, copyBufferSize)\n\t\t\t\treturn &buf\n\t\t\t},\n\t\t},\n\t}\n\ts.Server.Handler = s.handleConnection\n\n\treturn s\n}", "func NewServer(config domain.ServerConfig) *Server {\n\tdebugger := logger.New(log.New(ioutil.Discard, \"\", 0))\n\tif config.Debug {\n\t\tdebugger = logger.New(log.New(os.Stderr, \"[debug] \", log.Flags()|log.Lshortfile))\n\t}\n\n\tdb, err := bolt.Open(config.BoltPath, 0644, nil)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to start bolt db\")\n\t}\n\tdefer db.Close()\n\n\ts := &Server{\n\t\tConfig: config,\n\t\ti: uc.NewInteractor(\n\t\t\tconfig,\n\t\t\tcookies.New(config.CookieAge),\n\t\t\tdebugger,\n\t\t\tresources.New(encoder.New()),\n\t\t\thttpCaller.New(),\n\t\t\tmail.New(domain.EmailConfig{}),\n\t\t\tpathInfo.New(config),\n\t\t\tencoder.New(),\n\t\t\tsparql.New(),\n\t\t\tpages.New(config.DataRoot),\n\t\t\ttokenStorer.New(db),\n\t\t\tdomain.URIHandler{},\n\t\t\tuuid.New(),\n\t\t\tauthentication.New(httpCaller.New()),\n\t\t\tspkac.New(),\n\t\t),\n\t\tlogger: debugger,\n\t\tcookieManager: cookies.New(config.CookieAge),\n\t\tpathInformer: pathInfo.New(config),\n\t\turiManipulator: domain.URIHandler{},\n\t}\n\n\tmime.AddRDFExtension(s.Config.ACLSuffix)\n\tmime.AddRDFExtension(s.Config.MetaSuffix)\n\n\ts.logger.Debug(\"---- starting server ----\")\n\ts.logger.Debug(\"config: %#v\\n\", s.Config)\n\treturn s\n}", "func NewServer(db *sql.DB, numShards int) (*Server, error) {\n\tif numShards < 1 {\n\t\tnumShards = 1\n\t}\n\n\tqueue, err := NewEventQueue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Server{\n\t\tdb: db,\n\t\tqueue: queue,\n\t\tLoadAllMembers: true,\n\t\treadyShards: make([]bool, numShards),\n\t\treadyGuilds: make(map[int64]bool),\n\t\tloadedUsers: make(map[string]bool),\n\t}, nil\n}", "func NewServer(conf *Config, be *backend.Backend) (*Server, error) {\n\tauthInterceptor := interceptors.NewAuthInterceptor(be.Config.AuthWebhookURL)\n\tdefaultInterceptor := interceptors.NewDefaultInterceptor()\n\n\topts := []grpc.ServerOption{\n\t\tgrpc.UnaryInterceptor(grpcmiddleware.ChainUnaryServer(\n\t\t\tauthInterceptor.Unary(),\n\t\t\tdefaultInterceptor.Unary(),\n\t\t\tgrpcprometheus.UnaryServerInterceptor,\n\t\t)),\n\t\tgrpc.StreamInterceptor(grpcmiddleware.ChainStreamServer(\n\t\t\tauthInterceptor.Stream(),\n\t\t\tdefaultInterceptor.Stream(),\n\t\t\tgrpcprometheus.StreamServerInterceptor,\n\t\t)),\n\t}\n\n\tif conf.CertFile != \"\" && conf.KeyFile != \"\" {\n\t\tcreds, err := credentials.NewServerTLSFromFile(conf.CertFile, conf.KeyFile)\n\t\tif err != nil {\n\t\t\tlog.Logger.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\t\topts = append(opts, grpc.Creds(creds))\n\t}\n\n\topts = append(opts, grpc.MaxConcurrentStreams(math.MaxUint32))\n\n\tyorkieServiceCtx, yorkieServiceCancel := context.WithCancel(context.Background())\n\n\tgrpcServer := grpc.NewServer(opts...)\n\thealthpb.RegisterHealthServer(grpcServer, health.NewServer())\n\tapi.RegisterYorkieServer(grpcServer, newYorkieServer(yorkieServiceCtx, be))\n\tapi.RegisterClusterServer(grpcServer, newClusterServer(be))\n\tgrpcprometheus.Register(grpcServer)\n\n\treturn &Server{\n\t\tconf: conf,\n\t\tgrpcServer: grpcServer,\n\t\tyorkieServiceCancel: yorkieServiceCancel,\n\t}, nil\n}", "func NewServer() *Server {\n\treturn &Server{name: \"\", handlers: nil}\n}", "func (service *QueueService) CreateChannel() (*amqp.Channel, error) {\n\treturn service.amqp.Channel()\n}", "func NewServer(configGetter core.KubernetesConfigGetter, kubeappsCluster string, stopCh <-chan struct{}, pluginConfigPath string) (*Server, error) {\n\tlog.Infof(\"+fluxv2 NewServer(kubeappsCluster: [%v], pluginConfigPath: [%s]\",\n\t\tkubeappsCluster, pluginConfigPath)\n\n\trepositoriesGvr := schema.GroupVersionResource{\n\t\tGroup: fluxGroup,\n\t\tVersion: fluxVersion,\n\t\tResource: fluxHelmRepositories,\n\t}\n\n\tif redisCli, err := common.NewRedisClientFromEnv(); err != nil {\n\t\treturn nil, err\n\t} else if chartCache, err := cache.NewChartCache(\"chartCache\", redisCli, stopCh); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\t// If no config is provided, we default to the existing values for backwards\n\t\t// compatibility.\n\t\tversionsInSummary := pkgutils.GetDefaultVersionsInSummary()\n\t\ttimeoutSecs := int32(-1)\n\t\tif pluginConfigPath != \"\" {\n\t\t\tversionsInSummary, timeoutSecs, err = parsePluginConfig(pluginConfigPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"%s\", err)\n\t\t\t}\n\t\t\tlog.Infof(\"+fluxv2 using custom packages config with %v\\n\", versionsInSummary)\n\t\t} else {\n\t\t\tlog.Infof(\"+fluxv2 using default config since pluginConfigPath is empty\")\n\t\t}\n\n\t\ts := repoEventSink{\n\t\t\tclientGetter: clientgetter.NewBackgroundClientGetter(),\n\t\t\tchartCache: chartCache,\n\t\t}\n\t\trepoCacheConfig := cache.NamespacedResourceWatcherCacheConfig{\n\t\t\tGvr: repositoriesGvr,\n\t\t\tClientGetter: s.clientGetter,\n\t\t\tOnAddFunc: s.onAddRepo,\n\t\t\tOnModifyFunc: s.onModifyRepo,\n\t\t\tOnGetFunc: s.onGetRepo,\n\t\t\tOnDeleteFunc: s.onDeleteRepo,\n\t\t\tOnResyncFunc: s.onResync,\n\t\t}\n\t\tif repoCache, err := cache.NewNamespacedResourceWatcherCache(\n\t\t\t\"repoCache\", repoCacheConfig, redisCli, stopCh); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\treturn &Server{\n\t\t\t\tclientGetter: clientgetter.NewClientGetterWithApiExt(configGetter, kubeappsCluster),\n\t\t\t\tactionConfigGetter: clientgetter.NewHelmActionConfigGetter(configGetter, kubeappsCluster),\n\t\t\t\trepoCache: repoCache,\n\t\t\t\tchartCache: chartCache,\n\t\t\t\tkubeappsCluster: kubeappsCluster,\n\t\t\t\tversionsInSummary: versionsInSummary,\n\t\t\t\ttimeoutSeconds: timeoutSecs,\n\t\t\t}, nil\n\t\t}\n\t}\n}", "func main() {\n\tvar user string\n\tvar pwd string\n\tfmt.Print(\"RabbitMQ username: \")\n\tfmt.Scanln(&user)\n\tfmt.Print(\"RabbitMQ password: \")\n\tfmt.Scanln(&pwd)\n\n\tconn, err := amqp.Dial(fmt.Sprintf(\"amqp://%s:%s@159.65.220.217:5672\", user, pwd))\n\tfailOnError(err, \"Failed to connect\")\n\tdefer conn.Close()\n\n\tch, err := conn.Channel()\n\tfailOnError(err, \"Failed to create a channel\")\n\tdefer ch.Close()\n\n\tqueue, err := ch.QueueDeclare(\"hello-queue\", false, false, false, false, nil)\n\tfailOnError(err, \"Failed to create a queue\")\n\n\tmsgs, err := ch.Consume(queue.Name, \"\", false, false, false, false, nil)\n\tfailOnError(err, \"Failed to consume queue messages \")\n\n\tgo func() {\n\t\tfor d := range msgs {\n\t\t\tlog.Printf(\"Received message: %s\\n\", d.Body)\n\t\t\td.Ack(true)\n\t\t}\n\t}()\n\tlog.Printf(\"[*] Waiting for messages, please exit the program to stop\")\n\tforever := make(chan bool)\n\t<-forever\n}" ]
[ "0.7595138", "0.66407835", "0.6526455", "0.6236298", "0.6043651", "0.6040377", "0.6027341", "0.58490276", "0.58328205", "0.5806928", "0.5803156", "0.57954323", "0.5707904", "0.5688219", "0.5674982", "0.55992335", "0.55966425", "0.5593839", "0.5593327", "0.558049", "0.55695677", "0.55499446", "0.55499446", "0.5537921", "0.55231905", "0.54996526", "0.5492996", "0.5491618", "0.5485729", "0.54804355", "0.54778963", "0.54568166", "0.54401225", "0.543051", "0.54296714", "0.54131776", "0.5410793", "0.540596", "0.5405145", "0.5386939", "0.53737783", "0.5369777", "0.53676283", "0.5365264", "0.5355587", "0.53481364", "0.5344726", "0.5339063", "0.53306013", "0.53280693", "0.5325408", "0.5325091", "0.5322869", "0.5318536", "0.53139", "0.5307811", "0.5304836", "0.5297936", "0.52971905", "0.5293392", "0.52900714", "0.5289437", "0.5288942", "0.5285103", "0.5271811", "0.5259187", "0.52541184", "0.5253991", "0.5251747", "0.52432084", "0.5239343", "0.5236953", "0.5230357", "0.5230025", "0.5222238", "0.5221857", "0.5214534", "0.52099174", "0.52013636", "0.51973", "0.51900226", "0.51876235", "0.5184247", "0.5179556", "0.51789755", "0.5178107", "0.5174009", "0.5172696", "0.5171808", "0.5171337", "0.51582843", "0.51581097", "0.5149867", "0.5146988", "0.5142353", "0.51403415", "0.5138293", "0.5137628", "0.51342165", "0.5133087" ]
0.7509787
1
Connect connects to the RabbitMQ server
func (s *Server) Connect() { connectionAddr := fmt.Sprintf("amqp://%s:%s@%s", s.RabbitMQUsername, s.RabbitMQPassword, s.RabbitMQHost) conn, err := amqp.Dial(connectionAddr) FailOnError(err, "Failed to connect to RabbitMQ") s.Conn = conn }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RabbitMQ) Connect() (err error) {\n\tr.conn, err = amqp.Dial(Conf.AMQPUrl)\n\tif err != nil {\n\t\tlog.Info(\"[amqp] connect error: %s\\n\", err)\n\t\treturn err\n\t}\n\tr.channel, err = r.conn.Channel()\n\tif err != nil {\n\t\tlog.Info(\"[amqp] get channel error: %s\\n\", err)\n\t\treturn err\n\t}\n\tr.done = make(chan error)\n\treturn nil\n}", "func (rc *RabbitmqConnection) connectToRabbitMQ() {\n\trc.connect()\n}", "func RabbitMQConnect(addr string) (*RmqConnection, error) {\n\tvar c RmqConnection\n\tvar err error\n\tif c.conn, err = amqp.Dial(addr); err != nil {\n\t\treturn nil, err\n\t}\n\tif c.ch, err = c.conn.Channel(); err != nil {\n\t\tc.conn.Close()\n\t\treturn nil, err\n\t}\n\tc.stop = make(chan struct{})\n\tc.wg = &sync.WaitGroup{}\n\treturn &c, nil\n}", "func ConnectToRabbitMQ() error {\n\ttime.Sleep(50 * time.Second)\n\tcfg := RabbitMqEnv{}\n\tif err := env.Parse(&cfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse env: %v\", err)\n\t}\n\n\tfmt.Printf(\"%+v\", cfg)\n\n\tconn, err := amqp.Dial(fmt.Sprintf(\"amqp://%s:%s@%s:%s/\",\n\t\tcfg.RabbitMqPass,\n\t\tcfg.RabbitMqUser,\n\t\tcfg.RabbitMqHost,\n\t\tcfg.RabbitMqPort,\n\t))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to connect to RabbitMQ: %v\", err)\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open a channel: %v\", err)\n\t}\n\n\tq, err := ch.QueueDeclare(\n\t\t\"hello\", // name\n\t\tfalse, // durable\n\t\tfalse, // delete when unused\n\t\tfalse, // exclusive\n\t\tfalse, // no-wait\n\t\tnil, // arguments\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to declare a queue: %v\", err)\n\t}\n\n\tRabbitMQChan = ch\n\tRabbitMQQueue = q\n\n\treturn nil\n}", "func connectRabbitMQ() {\n\n\t// Start connection.\n\tconn, err := amqp.Dial(config.Client.Uri)\n\tutility.InitErrorHandler(\"Failed to connect to RabbitMQ\", err)\n\tdefer conn.Close()\n\n\tch, err := conn.Channel()\n\tutility.InitErrorHandler(\"Failed to open a channel\", err)\n\tdefer ch.Close()\n\n\t// Declare queue.\n\t_, err = ch.QueueDeclare(\n\t\tconfig.QueueName,\n\t\tconfig.Client.Queue.Durable,\n\t\tconfig.Client.Queue.AutoDelete,\n\t\tconfig.Client.Queue.Exclusive,\n\t\tconfig.Client.Queue.NoWait,\n\t\tnil,\n\t)\n\tutility.InitErrorHandler(\"Failed to declare a queue\", err)\n\n\terr = ch.Qos(\n\t\tconfig.Client.Prefetch.Count,\n\t\tconfig.Client.Prefetch.Size,\n\t\tconfig.Client.Prefetch.Global,\n\t)\n\tutility.InitErrorHandler(\"Failed to set QoS\", err)\n\n\tmsgs, err := ch.Consume(\n\t\tconfig.QueueName,\n\t\tconfig.Consumer,\n\t\tconfig.Client.Consume.AutoAck,\n\t\tconfig.Client.Consume.Exclusive,\n\t\tconfig.Client.Consume.NoLocal,\n\t\tconfig.Client.Consume.NoWait,\n\t\tnil,\n\t)\n\tutility.InitErrorHandler(\"Failed to register a consumer\", err)\n\n\tforever := make(chan bool)\n\n\tgo func() {\n\t\tfor d := range msgs {\n\t\t\t// Process queue items.\n\t\t\tprocessQueueItem(d)\n\t\t}\n\t}()\n\n\tfmt.Println(\" [*] Waiting for messages. To exit press CTRL+C\")\n\t<-forever\n}", "func (s *MQ) connect(name string) (*amqp.Connection, error) {\n\tif name == \"\" {\n\t\tname = s.ConnectionName\n\t}\n\tif name == \"\" {\n\t\tname = s.name\n\t}\n\ts.Log(\"connecting %q\", name)\n\n\tvar heartBeat = s.HeartBeat\n\tif heartBeat == 0 {\n\t\theartBeat = 10\n\t}\n\n\t// Use the user provided client name\n\tconnection, err := amqp.DialConfig(s.Url, amqp.Config{\n\t\tHeartbeat: time.Duration(heartBeat) * time.Second,\n\t\tProperties: amqp.Table{\n\t\t\t\"product\": s.Product,\n\t\t\t\"version\": s.Version,\n\t\t\t\"connection_name\": name,\n\t\t},\n\t\tLocale: \"en_US\",\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.Log(\"connected\")\n\treturn connection, nil\n}", "func (b *broker) connect() error {\n\tvar err error\n\turi := fmt.Sprintf(\n\t\t\"%v://%v:%v@%v:%v/\",\n\t\tb.Scheme,\n\t\tb.User,\n\t\tb.Pass,\n\t\tb.Host,\n\t\tb.Port,\n\t)\n\tif b.connection, err = amqp.Dial(uri); err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"url\": uri,\n\t\t\t\"error\": err,\n\t\t}).Warn(\"error while dialling AMQP broker\")\n\t\treturn errors.Wrap(err, \"while dialling AMQP broker\")\n\t}\n\tif b.achannel, err = b.connection.Channel(); err != nil {\n\t\treturn errors.Wrap(err, \"could not open AMQP channel\")\n\t}\n\t// Best practice for AMQP is to unconditionally declare the exchange on connection\n\tif err = b.achannel.ExchangeDeclare(\n\t\tb.Exchange, // name of the exchange\n\t\t\"topic\", // type is always topic\n\t\ttrue, // durable\n\t\tfalse, // delete when complete\n\t\tfalse, // internal\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"could not declare AMQP exchange\")\n\t}\n\tb.closed = make(chan *amqp.Error)\n\tb.achannel.NotifyClose(b.closed)\n\n\treturn nil\n}", "func (r *Rmq) Connect() {\n\tconn, err := amqp.Dial(r.uri)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr.conn = conn\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr.ch = ch\n}", "func (c *CommunicationClient) Connect() error{\r\n\r\n if c.conn != nil{\r\n if c.conn.IsClosed() {\r\n conn, err := amqp.Dial(c.host)\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n ch, err := conn.Channel()\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n c.conn = conn\r\n c.ch = ch\r\n\r\n return nil\r\n }else{\r\n\r\n ch, err := c.conn.Channel()\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n c.ch = ch\r\n\r\n return nil\r\n }\r\n }else{\r\n conn, err := amqp.Dial(c.host)\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n ch, err := conn.Channel()\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n c.conn = conn\r\n c.ch = ch\r\n\r\n return nil\r\n }\r\n\r\n\r\n}", "func connectToRabbitMQ(uri string) *amqp.Connection {\r\n\tfor {\r\n\t\tconn, err := amqp.Dial(uri)\r\n\r\n\t\tif err == nil {\r\n\t\t\treturn conn\r\n\t\t}\r\n\r\n\t\tcore.CheckError(err)\r\n\t\tcore.SendMessage(\"Trying to reconnect to RabbitMQ\")\r\n\t\ttime.Sleep(500 * time.Millisecond)\r\n\t}\r\n}", "func connect(server string, port int, user string, password string, vhost string) (*amqp.Connection, error) {\n\t// Workaround to parse / in vhost name to %2F\n\tparsedVhost := strings.Replace(vhost, \"/\", \"%2F\", -1)\n\n\t// Create a uri string from arguments\n\turi := \"amqp://\" + user + \":\" + password + \"@\" + server + \":\" + strconv.Itoa(port) + \"/\" + parsedVhost\n\n\t// Open a connection to the amqp server\n\tconn, err := amqp.Dial(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn conn, nil\n}", "func (rabbitmq *RabbitMQ) Connect(config *Config) (result bool, err error) {\r\n\tif config == nil {\r\n\t\treturn false, ErrCursor\r\n\t}\r\n\r\n\tconn, err := amqp.Dial(config.ConString)\r\n\t// defer conn.Close()\r\n\tif err != nil {\r\n\t\treturn false, ErrConnection\r\n\t}\r\n\trabbitmq.Connection = conn\r\n\tgetChannel(rabbitmq, conn)\r\n\treturn true, nil\r\n}", "func (a *amqpPubSub) connect(ctx context.Context) (*amqp.Session, error) {\n\turi, err := url.Parse(a.metadata.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientOpts := a.createClientOptions(uri)\n\n\ta.logger.Infof(\"Attempting to connect to %s\", a.metadata.URL)\n\tclient, err := amqp.Dial(ctx, a.metadata.URL, &clientOpts)\n\tif err != nil {\n\t\ta.logger.Fatal(\"Dialing AMQP server:\", err)\n\t}\n\n\t// Open a session\n\tsession, err := client.NewSession(ctx, nil)\n\tif err != nil {\n\t\ta.logger.Fatal(\"Creating AMQP session:\", err)\n\t}\n\n\treturn session, nil\n}", "func (s *AmqpStream) Connect() error {\n\n\ts.URI = &amqp.URI{\n\t\tScheme: \"amqp\",\n\t\tHost: s.Config.Amqp.Host,\n\t\tPort: s.Config.Amqp.Port,\n\t\tUsername: s.Config.Amqp.Username,\n\t\tPassword: s.Config.Amqp.Password,\n\t\tVhost: s.Config.Amqp.VHost,\n\t}\n\n\tvar err error\n\n\t// Open an AMQP connection\n\ts.Connection, err = amqp.Dial(s.URI.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Open the channel in the new connection\n\ts.Channel, err = s.Connection.Channel()\n\tif err != nil {\n\t\ts.Connection.Close()\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a *agent) connect() error {\n\terr := backoff.Retry(func() error {\n\t\tif a.amqpURL == \"\" {\n\t\t\treturn fmt.Errorf(\"no mq URL\")\n\t\t}\n\t\tparts := strings.Split(a.amqpURL, \"@\")\n\t\thostport := parts[len(parts)-1]\n\n\t\ta.logger.InfoF(\"dialing %q\", hostport)\n\t\tconn, err := amqp.Dial(a.amqpURL)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"dialing %q\", hostport)\n\t\t}\n\t\t// Set connection to agent for reference\n\t\ta.mu.Lock()\n\t\ta.conn = conn\n\t\ta.mu.Unlock()\n\n\t\tif err := a.openChannel(); err != nil {\n\t\t\treturn errors.Wrapf(err, \"openChannel\")\n\t\t}\n\n\t\tif err := a.runWorker(); err != nil {\n\t\t\treturn errors.Wrapf(err, \"startWorkers\")\n\t\t}\n\n\t\ta.wg.Add(1)\n\t\tgo func() {\n\t\t\tdefer a.wg.Done()\n\t\t\ta.waitChannel()\n\t\t}()\n\t\ta.logger.InfoF(\"connected %q\", hostport)\n\t\treturn nil\n\t}, backoff.WithContext(a.connBackOff, a.ctx))\n\tif err != nil {\n\t\ta.logger.ErrorF(\"connect failed: %q\", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}", "func Connect(aconf *config.AmqpConfig) (*amqp.Connection, error) {\n\turi, err := amqp.ParseURI(aconf.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar tconf *tls.Config\n\tvar auth []amqp.Authentication\n\tif uri.Scheme == \"amqps\" {\n\t\ttconf = &tls.Config{}\n\t\tif aconf.CaCert != \"\" {\n\t\t\tif err := x509tools.LoadCertPool(aconf.CaCert, tconf); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tif aconf.CertFile != \"\" {\n\t\t\tcert, err := certloader.LoadX509KeyPair(aconf.CertFile, aconf.KeyFile)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ttconf.Certificates = []tls.Certificate{cert.TLS()}\n\t\t}\n\t\tx509tools.SetKeyLogFile(tconf)\n\t\tif len(tconf.Certificates) != 0 {\n\t\t\tauth = append(auth, externalAuth{})\n\t\t}\n\t}\n\tif uri.Password != \"\" {\n\t\tauth = append(auth, uri.PlainAuth())\n\t}\n\tqconf := amqp.Config{SASL: auth, TLSClientConfig: tconf}\n\treturn amqp.DialConfig(aconf.URL, qconf)\n}", "func (client *Client) Connect() error {\n\tclient.Lock()\n\tdefer client.Unlock()\n\n\tif client.IsActive() {\n\t\treturn nil\n\t}\n\tif client.config.AmqpConfig == nil {\n\t\tclient.config.AmqpConfig = defaultAmqpConfig\n\t}\n\tconn, err := amqp.DialConfig(client.config.GetConnString(), *client.config.AmqpConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient.conn = conn\n\tchannel, err := client.Channel()\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient.amqpChannel = channel\n\tclient.connected = true\n\tnotifyCloseChan := make(chan *amqp.Error)\n\tclient.notifyCloseChan = notifyCloseChan\n\tconn.NotifyClose(notifyCloseChan)\n\n\tgo client.handleClose()\n\treturn nil\n}", "func (p *AMQPClient) Connect(ip string) {\n\t// start logging\n\tif env.IsLoggingEnabled() {\n\t\tl, err := logs.CreateAndConnect(env.GetLoggingCredentials())\n\t\tp.Logger = l\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Couldn't connect to logging service! No logs will be stored..\")\n\t\t}\n\t}\n\n\tconn, err := amqp.Dial(ip)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tp.Connection = conn\n\tfmt.Println(\"Connected to amqp node @\" + ip + \".\")\n\n\t// creates a channel to amqp server\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tp.Channel = ch\n\n\t// declares an exchange with name `chat` and type `fanout`\n\t// sends to every queue bound to this exchange\n\terr = ch.ExchangeDeclare(\"chat\", \"fanout\", true,\n\t\tfalse, false, false, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// declares a new queue with name=`queueName`\n\tq, err := ch.QueueDeclare(queueName+\"_\"+p.UUID.String(), false, false, true, false, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tp.Queue = q\n\n\t// binds the queue to the exchange\n\terr = ch.QueueBind(q.Name, \"\", \"chat\", false, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// handles outgoing messages\n\tgo func(p *AMQPClient) {\n\t\tfor {\n\t\t\tselect {\n\t\t\t// publishes a new message to the amqp server\n\t\t\t// if the channel received a new message\n\t\t\tcase s := <-p.outgoingMessages:\n\t\t\t\terr = ch.Publish(\"chat\", \"\", false, false,\n\t\t\t\t\tamqp.Publishing{\n\t\t\t\t\t\tContentType: \"text/plain\",\n\t\t\t\t\t\tBody: []byte(s.Message),\n\t\t\t\t\t})\n\t\t\tcase m := <-p.incomingMessages:\n\t\t\t\tfmt.Println(m.Message)\n\n\t\t\t\t// log the message\n\t\t\t\tif env.IsLoggingEnabled() {\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tuser, message := m.UserAndMessage()\n\t\t\t\t\t\terr := p.Logger.AddEntry(user, message)\n\n\t\t\t\t\t\tif p.Logger.Connected && err != nil {\n\t\t\t\t\t\t\tfmt.Println(\"Couldn't sent log!\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}()\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}(p)\n\n\t// get the channel consumer\n\tmsgs, err := ch.Consume(q.Name, \"\", true, false, false, false, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// handles incoming messages\n\tgo func(p *AMQPClient) {\n\t\tfor d := range msgs {\n\t\t\t// send a message packet to incoming handler\n\t\t\t// if a new message is inside the channel\n\t\t\tp.incomingMessages <- &network.MessagePacket{Message: string(d.Body)}\n\t\t}\n\t}(p)\n\n\tselect {\n\tcase p.stateUpdates <- true:\n\t\tbreak\n\t}\n}", "func (rmq *RmqStruct) createConnect() error {\n\tamqpURL := amqp.URI{\n\t\tScheme: \"amqp\",\n\t\tHost: rmq.rmqCfg.Host,\n\t\tUsername: rmq.rmqCfg.Username,\n\t\tPassword: \"XXXXX\",\n\t\tPort: rmq.rmqCfg.Port,\n\t\tVhost: rmq.rmqCfg.Vhost,\n\t}\n\n\tlog.Logger.Info(\n\t\t\"connect URL\",\n\t\tzap.String(\"service\", serviceName),\n\t\tzap.String(\"uuid\", rmq.uuid),\n\t\tzap.String(\"url\", amqpURL.String()),\n\t)\n\n\tamqpURL.Password = rmq.rmqCfg.Password\n\n\t// tcp connection timeout in 3 seconds\n\tmyconn, err := amqp.DialConfig(\n\t\tamqpURL.String(),\n\t\tamqp.Config{\n\t\t\tVhost: rmq.rmqCfg.Vhost,\n\t\t\tDial: func(network, addr string) (net.Conn, error) {\n\t\t\t\treturn net.DialTimeout(network, addr, 3*time.Second)\n\t\t\t},\n\t\t\tHeartbeat: 10 * time.Second,\n\t\t\tLocale: \"en_US\"},\n\t)\n\tif err != nil {\n\t\tlog.Logger.Warn(\n\t\t\t\"open connection failed\",\n\t\t\tzap.String(\"service\", serviceName),\n\t\t\tzap.String(\"uuid\", rmq.uuid),\n\t\t\tzap.String(\"error\", err.Error()),\n\t\t)\n\n\t\treturn err\n\t}\n\n\trmq.rmqConnection = myconn\n\trmq.connCloseError = make(chan *amqp.Error)\n\trmq.rmqConnection.NotifyClose(rmq.connCloseError)\n\treturn nil\n}", "func (d *RMQ) Connect() error { return nil }", "func (q *Queue) Connect() error {\n\tconn, err := amqp.Dial(q.url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tq.conn = conn\n\tq.channel = ch\n\treturn nil\n}", "func InitializeRabbitConnection(credentials *Credentials) {\n\tRabbitConnection, _ = createRabbitConnection(credentials)\n\t/*\n\t\tconfig.Config.Rabbit.Host,\n\t\t\tconfig.Config.Rabbit.Port,\n\t\t\tconfig.Config.Rabbit.Username,\n\t\t\tconfig.Config.Rabbit.Password,\n\t\t)*/\n}", "func (me Broker) Connect() (*nats.Conn, error) {\n\treturn nats.Connect(strings.Join(me.URI, \",\"), nats.Timeout(me.Timeout))\n}", "func createRabbitConnection(cr *Credentials) (*Rabbit, error) {\n\tconnectionStr := fmt.Sprintf(\"amqp://%v:%v@%v:%v/\", cr.Username, cr.Password, cr.Host, cr.Port)\n\tconn, err := amqp.Dial(connectionStr)\n\tfailOnError(err, \"Failed to connect to RabbitMQ; Connection string:\"+connectionStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tch, err := conn.Channel()\n\tfailOnError(err, \"Failed to open a channel\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Rabbit{\n\t\tConnection: conn,\n\t\tChannel: ch,\n\t\tCredentials: cr,\n\t}, nil\n}", "func initialize() *RabbitServer {\n\n\trabbitURL := utilities.GetRabbitInfo()\n\tserver := MakeRabbitServer(rabbitURL)\n\tserver.Connect()\n\n\treturn server\n\n}", "func (c *Client) connect() (conn *net.TCPConn, err error) {\n\n\ttype DialResp struct {\n\t\tConn *net.TCPConn\n\t\tError error\n\t}\n\n\t// Open connection to Zabbix host\n\tiaddr, err := c.getTCPAddr()\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// dial tcp and handle timeouts\n\tch := make(chan DialResp)\n\n\tgo func() {\n\t\tconn, err = net.DialTCP(\"tcp\", nil, iaddr)\n\t\tch <- DialResp{Conn: conn, Error: err}\n\t}()\n\n\tselect {\n\tcase <-time.After(5 * time.Second):\n\t\terr = fmt.Errorf(\"Connection Timeout\")\n\tcase resp := <-ch:\n\t\tif resp.Error != nil {\n\t\t\terr = resp.Error\n\t\t\tbreak\n\t\t}\n\n\t\tconn = resp.Conn\n\t}\n\n\treturn\n}", "func (transport *IRCTransport) connect() error {\n\tvar conn net.Conn\n\tvar err error\n\t// Establish the connection.\n\tif transport.tlsConfig == nil {\n\t\ttransport.log.Infof(\"Connecting to %s...\", transport.server)\n\t\tconn, err = net.Dial(\"tcp\", transport.server)\n\t} else {\n\t\ttransport.log.Infof(\"Connecting to %s using TLS...\", transport.server)\n\t\tconn, err = tls.Dial(\"tcp\", transport.server, transport.tlsConfig)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Store connection.\n\ttransport.connection = conn\n\ttransport.decoder = irc.NewDecoder(conn)\n\ttransport.encoder = irc.NewEncoder(conn)\n\n\t// Send initial messages.\n\tif transport.password != \"\" {\n\t\ttransport.SendRawMessage(irc.PASS, []string{transport.password}, \"\")\n\t}\n\ttransport.SendRawMessage(irc.NICK, []string{transport.name}, \"\")\n\ttransport.SendRawMessage(irc.USER, []string{transport.user, \"0\", \"*\"}, transport.user)\n\n\ttransport.log.Debugf(\"Succesfully connected.\")\n\treturn nil\n}", "func ConnectWithRetry(uri string, retryInterval time.Duration) (conn *amqp.Connection) {\n\tvar err error\n\tfor {\n\t\tconn, err = amqp.Dial(uri)\n\t\tif err == nil {\n\t\t\tlog.Println(`event=\"Established connection to rabbit\"`)\n\t\t\treturn conn\n\t\t}\n\t\tlog.Printf(`event=\"Failed to connect to rabbit - retrying\" err=\"%v\"`, err)\n\t\ttime.Sleep(retryInterval)\n\t}\n}", "func CreateConnection(host string, port int) *RabbitmqConnection {\n\trc := &RabbitmqConnection{Host: host, Port: port}\n\trc.connectToRabbitMQ()\n\treturn rc\n}", "func rabbitConnector(uri string) {\r\n\tvar rabbitErr *amqp.Error\r\n\tvar rabbitConn *amqp.Connection\r\n\r\n\tgo func() {\r\n\t\tfor {\r\n\t\t\trabbitErr = <-rabbitCloseError\r\n\t\t\tif rabbitErr != nil {\r\n\t\t\t\tcore.SendMessage(\"Connecting to RabbitMQ\")\r\n\t\t\t\trabbitConn = connectToRabbitMQ(uri)\r\n\t\t\t\trabbitCloseError = make(chan *amqp.Error)\r\n\t\t\t\trabbitConn.NotifyClose(rabbitCloseError)\r\n\t\t\t}\r\n\t\t}\r\n\t}()\r\n\r\n\tfor rabbitConn == nil {\r\n\t\ttime.Sleep(1 * time.Second)\r\n\t}\r\n}", "func (c *GatewayClient) connect() error {\n\tif !c.ready {\n\t\treturn errors.New(\"already tried to connect and failed\")\n\t}\n\n\tc.ready = false\n\tc.resuming = false\n\tc.heartbeatAcknowledged = true\n\tc.lastIdentify = time.Time{}\n\n\tc.Logf(\"connecting\")\n\t// TODO Need to set read deadline for hello packet and I also need to set write deadlines.\n\t// TODO also max message\n\tvar err error\n\tc.wsConn, _, err = websocket.DefaultDialer.Dial(c.GatewayURL, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo c.manager()\n\n\treturn nil\n}", "func doConnect(qmName string) error {\n\n\t// Set connection configuration\n\tvar connConfig mqmetric.ConnectionConfig\n\tconnConfig.ClientMode = false\n\tconnConfig.UserId = \"\"\n\tconnConfig.Password = \"\"\n\n\t// Connect to the queue manager - open the command and dynamic reply queues\n\terr := mqmetric.InitConnectionStats(qmName, \"SYSTEM.DEFAULT.MODEL.QUEUE\", \"\", &connConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to connect to queue manager %s: %v\", qmName, err)\n\t}\n\n\t// Discover available metrics for the queue manager and subscribe to them\n\terr = mqmetric.DiscoverAndSubscribe(\"\", true, \"\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to discover and subscribe to metrics: %v\", err)\n\t}\n\n\treturn nil\n}", "func GetConnectionRabbit(rabbitURL string) (ConnectionRabbitMQ, error) {\n\tconn, err := amqp.Dial(rabbitURL)\n\tif err != nil {\n\t\treturn ConnectionRabbitMQ{}, err\n\t}\n\n\tch, err := conn.Channel()\n\treturn ConnectionRabbitMQ{\n\t\tChannel: ch,\n\t\tConn: conn,\n\t}, err\n}", "func initAmqp() (*amqp.Connection, *amqp.Channel) {\n\tconn, err := amqp.Dial(*amqpURI)\n\tfailOnError(err, \"Failed to connect to RabbitMQ\")\n\n\tch, err := conn.Channel()\n\tfailOnError(err, \"Failed to open a channel\")\n\n\terr = ch.ExchangeDeclare(\n\t\t\"test-exchange\", // name\n\t\t\"direct\", // type\n\t\ttrue, // durable\n\t\tfalse, // auto-deleted\n\t\tfalse, // internal\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\tfailOnError(err, \"Failed to declare the Exchange\")\n\treturn conn, ch\n}", "func (c *RedialConnection) connect() {\n\tif c.closed {\n\t\t// We don't really want to connect\n\t\treturn\n\t}\n\tif c.conn != nil && !c.conn.IsClosed() {\n\t\t// We already have a connection\n\t\treturn\n\t}\n\tfailCount := 0\n\tfor {\n\t\tconn, err := net.Dial(\"tcp\", c.address.String())\n\t\tif err == nil {\n\t\t\tc.conn = NewBasicConnection(conn, c.inbox)\n\t\t\treturn\n\t\t}\n\n\t\tfailCount++\n\t\ttimer := time.NewTimer(time.Duration(failCount) * time.Second)\n\t\tselect {\n\t\tcase <-c.quit:\n\t\t\treturn\n\t\tcase <-timer.C:\n\t\t\t// Looping again will try to reconnect\n\t\t}\n\t}\n}", "func (c *client) connect() error {\n\tvar connection *sql.DB\n\tvar err error\n\tif os.Getenv(\"MODE\") == \"development\" {\n\t\tvar connectionString = fmt.Sprintf(\n\t\t\t\"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable\",\n\t\t\tos.Getenv(\"PGHOST\"),\n\t\t\tos.Getenv(\"PGPORT\"),\n\t\t\tos.Getenv(\"PGUSER\"),\n\t\t\tos.Getenv(\"PGPASSWORD\"),\n\t\t\tos.Getenv(\"PGDATABASE\"),\n\t\t)\n\t\tc.connectionString = connectionString\n\t\tconnection, err = sql.Open(\"postgres\", connectionString)\n\t} else if os.Getenv(\"MODE\") == \"production\" {\n\t\tconnection, err = sql.Open(\"postgres\", os.Getenv(\"DATABASE_URL\"))\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"connection to pg failed: %v\", err)\n\t}\n\n\tc.db = connection\n\n\tfmt.Println(\"postgres connection established...\")\n\treturn nil\n}", "func (p *Producer) connect() error {\n\t// make the producers\n\tproducers := make(map[string]*gonsq.Producer)\n\tfor _, host := range p.opt.NSQdAddrs {\n\t\tfor i := 0; i < p.numConns; i++ {\n\t\t\tproducer, err := gonsq.NewProducer(host, p.nsqConf)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// set custom logger\n\t\t\tif p.opt.Logger != nil {\n\t\t\t\tproducer.SetLogger(p.opt.Logger, p.opt.LogLvl)\n\t\t\t}\n\n\t\t\t// check that producer has good host\n\t\t\terr = producer.Ping()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpk := strconv.Itoa(i) + \"|\" + host\n\t\t\tproducers[pk] = producer\n\t\t}\n\t}\n\n\tif len(producers) == 0 {\n\t\treturn errors.New(\"no nsqd hosts provided\")\n\t}\n\n\tkeys := make([]string, 0)\n\tfor key := range producers {\n\t\tkeys = append(keys, key)\n\t}\n\n\tp.hostPool = hostpool.New(keys)\n\tp.producers = producers\n\n\treturn nil\n}", "func (c *Connection) connect(ctx context.Context) error {\n\tc.log.Debug(\"Connection: %s\",\n\t\tLogField{Key: ConnectionLogMsgKey, Value: \"dialing transport\"})\n\n\t// connect\n\ttransport, err := c.transport.Dial(ctx)\n\tif err != nil {\n\t\tc.log.Warning(\"Connection: error %s: %v\",\n\t\t\tLogField{Key: ConnectionLogMsgKey, Value: \"dialing transport\"},\n\t\t\tLogField{Key: \"error\", Value: err})\n\t\treturn err\n\t}\n\n\tclient := NewClient(transport, c.errorUnwrapper, c.tagsFunc)\n\tserver := NewServer(transport, c.wef)\n\n\tfor _, p := range c.protocols {\n\t\tif err := server.Register(p); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// call the connect handler\n\tc.log.Debug(\"Connection: %s\", LogField{Key: ConnectionLogMsgKey, Value: \"calling OnConnect\"})\n\terr = c.handler.OnConnect(ctx, c, client, server)\n\tif err != nil {\n\t\tc.log.Warning(\"Connection: error calling %s handler: %v\",\n\t\t\tLogField{Key: ConnectionLogMsgKey, Value: \"OnConnect\"},\n\t\t\tLogField{Key: \"error\", Value: err})\n\t\treturn err\n\t}\n\n\t// set the client for other callers.\n\t// we wait to do this so the handler has time to do\n\t// any setup required, e.g. authenticate.\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tc.client = client\n\tc.server = server\n\tc.transport.Finalize()\n\n\tc.log.Debug(\"Connection: %s\", LogField{Key: ConnectionLogMsgKey, Value: \"connected\"})\n\treturn nil\n}", "func (this *Client) AwaitConnect() {\n\tthis.getConsumerConnection().awaitConnection()\n\tthis.getPublisherConnection().awaitConnection()\n}", "func (r *RabbitMQ) Init(metadata bindings.Metadata) error {\n\tmeta, err := r.getRabbitMQMetadata(metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.metadata = meta\n\n\tconn, err := amqp.Dial(meta.Host)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.connection = conn\n\tr.channel = ch\n\treturn nil\n}", "func connect() (Publisher, error) {\n\tif publisher != nil {\n\t\treturn publisher, nil\n\t}\n\tconfigNSQ := nsq.NewConfig()\n\tclient, err := nsq.NewProducer(os.Getenv(\"NSQ_PUBLISHER\"), configNSQ)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.SetLogger(nullLogger, nsq.LogLevelInfo)\n\tpublisher = &Produce{\n\t\tInstance: client,\n\t}\n\treturn publisher, nil\n}", "func connect() net.Conn {\n\t//connection, err := net.Dial(\"unix\", \"/var/www/bot/irc/sock\")\n\tconnection, err := net.Dial(\"tcp\", \"localhost:8765\")\n\n\t//\tsendCommand(connection, \"PASS\", password)\n\t//\tsendCommand(connection, \"USER\", fmt.Sprintf(\"%s 8 * :%s\\r\\n\", nickname, nickname))\n\t//\tsendCommand(connection, \"NICK\", nickname)\n\t//\tfmt.Println(\"Registration sent\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tjoinChannels(connection)\n\n\treturn connection\n}", "func Setup() error {\n\tc, err := getConnection()\n\tif err != nil {\n\t\treturn err\n\t}\n\tconn = c\n\tch, err := getChannel()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tchannel = ch\n\n\t// listen for close events so we can reconnect.\n\terrChan := channel.NotifyClose(make(chan *amqp.Error))\n\tgo func() {\n\t\tfor e := range errChan {\n\t\t\tfmt.Println(\"connection to rabbitmq lost.\")\n\t\t\tfmt.Println(e)\n\t\t\tfmt.Println(\"attempting to create new rabbitmq channel.\")\n\t\t\tch, err := getChannel()\n\t\t\tif err == nil {\n\t\t\t\tchannel = ch\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t//could not create channel, so lets close the connection\n\t\t\t// and re-create.\n\t\t\t_ = conn.Close()\n\n\t\t\tfor err != nil {\n\t\t\t\ttime.Sleep(2 * time.Second)\n\t\t\t\tfmt.Println(\"attempting to reconnect to rabbitmq.\")\n\t\t\t\terr = Setup()\n\t\t\t}\n\t\t\tfmt.Println(\"Connected to rabbitmq again.\")\n\t\t}\n\t}()\n\n\treturn nil\n}", "func connect() redis.Conn{\n\tconnWithRedis,err := redis.Dial(\"tcp\",\":6379\")\n\n\tif err != nil{\n\t\tlog.Fatalln(err)\n\t}\n\n\treturn connWithRedis\n\n}", "func ConnectBroker() {\n\tconfig := config.GetConfig()\n\tconn, err := amqp.Dial(config.URL)\n\tlogger.LogMessage(err, \"Could Not Connect to Broker\", \"Successfully connected to Message Broker\")\n\n\tch, err = conn.Channel()\n\tlogger.LogMessage(err, \"Could Not open a Channel\", \"Successfully opened a Channel\")\n\n\tq, err = ch.QueueDeclare(\n\t\t\"ConnectQueue\",\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tnil,\n\t)\n\tlogger.LogMessage(err, \"Failed to declare the Queue\", \"Declared the queue\")\n\treturn\n}", "func (m *MqttClientBase) connect() {\n\tif token := m.Client.Connect(); token.Wait() && token.Error() != nil {\n\t\tif !m.Connecting {\n\t\t\tlog.Printf(\"MQTT client %v\", token.Error())\n\t\t\tm.retryConnect()\n\t\t}\n\t}\n}", "func NewRabbitConnection(URI string) (Connection, error) {\n\tamqpNativeConn, err := amqp.Dial(URI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn RabbitConnection{amqpNativeConn}, nil\n}", "func (mon *SocketMonitor) Connect() error {\n\tenc := json.NewEncoder(mon.c)\n\tdec := json.NewDecoder(mon.c)\n\n\t// Check for banner on startup\n\tvar ban banner\n\tif err := dec.Decode(&ban); err != nil {\n\t\treturn err\n\t}\n\tmon.Version = &ban.QMP.Version\n\tmon.Capabilities = ban.QMP.Capabilities\n\n\t// Issue capabilities handshake\n\tcmd := Command{Execute: qmpCapabilities}\n\tif err := enc.Encode(cmd); err != nil {\n\t\treturn err\n\t}\n\n\t// Check for no error on return\n\tvar r response\n\tif err := dec.Decode(&r); err != nil {\n\t\treturn err\n\t}\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\t// Initialize socket listener for command responses and asynchronous\n\t// events\n\tevents := make(chan Event)\n\tstream := make(chan streamResponse)\n\tgo mon.listen(mon.c, events, stream)\n\n\tmon.events = events\n\tmon.stream = stream\n\n\treturn nil\n}", "func (s *service) connect() {\n\tif s.destroyed {\n\t\ts.logger.Warnf(\"connect already destroyed\")\n\t\treturn\n\t}\n\n\taddr := fmt.Sprintf(\"%s:%d\", s.Host, s.Port)\n\n\ts.logger.Infof(\"start %s %s\", s.Name, addr)\n\n\ts.Connecting = true\n\tconn, err := net.Dial(\"tcp\", addr)\n\tfor err != nil {\n\t\tif s.destroyed {\n\t\t\ts.logger.Warnf(\"dial already destroyed\")\n\t\t\treturn\n\t\t}\n\t\tif s.restarted {\n\t\t\ts.logger.WithError(err).Warnf(\"dial %v\", err)\n\t\t} else {\n\t\t\ts.logger.WithError(err).Errorf(\"dial %v\", err)\n\t\t}\n\t\ttime.Sleep(time.Duration(1) * time.Second)\n\t\tconn, err = net.Dial(\"tcp\", addr)\n\t}\n\ts.conn = conn\n\ts.restarted = false\n\ts.Connecting = false\n\ts.logger.Infof(\"connected %s %s\", s.Name, addr)\n\n\tquit := make(chan struct{})\n\ts.Send = s.makeSendFun(conn)\n\tmsg := types.Message{\n\t\tRouterHeader: constants.RouterHeader.Connect,\n\t\tUserID: s.RouterID,\n\t\tPayloadURI: types.PayloadURI(s.Caller),\n\t}\n\ts.Send(msg)\n\tgo common.WithRecover(func() { s.readPump(conn, quit) }, \"read-pump\")\n\ts.startHB(conn, quit)\n}", "func NewRabbitMQConnection(config *Configuration) (RabbitMQ, error) {\n\tconn, err := amqp.Dial(config.RabbitURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rabbitMQConnection{configuration: config, channel: ch}, nil\n}", "func connect() *r.Session {\n\tsession, _ := r.Connect(r.ConnectOpts{\n\t\tAddress: \"localhost:28015\",\n\t})\n\treturn session\n}", "func (c *Consumer) init() (err error) {\n\tc.connection, err = amqp.Dial(c.config.URI)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Consumer.Init() connect to RabbitMQ (%s) error: %v\", c.config.URI, err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t// close established connection in case of error\n\t\t\tcloseErr := c.connection.Close()\n\t\t\tif closeErr != nil {\n\t\t\t\terr = fmt.Errorf(\"%v: Consumer.Init() close connection to RabbitMQ error: %v\", err, closeErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\tc.channel, err = c.connection.Channel()\n\tif err != nil {\n\t\terrString := \"Consumer.Init() create channel to RabbitMQ (%s) error: %v\"\n\t\treturn fmt.Errorf(errString, c.config.URI, err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t// close established channel in case of error\n\t\t\tcloseErr := c.channel.Close()\n\t\t\tif closeErr != nil {\n\t\t\t\terr = fmt.Errorf(\"%v: Consumer.Init() close channel error: %v\", err, closeErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = c.channel.Qos(c.config.PrefetchCount, c.config.PrefetchSize, c.config.PrefetchGlobal)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Consumer.Init() declare prefetch policy error: %v\", err)\n\t}\n\n\tc.deliveryChannel, err = c.channel.Consume(\n\t\tc.config.Queue, // queue\n\t\tc.config.Name, // consumer\n\t\tc.config.AutoAck, // autoAck\n\t\tc.config.Exclusive, // exclusive\n\t\tc.config.NoLocal, // noLocal\n\t\tc.config.NoWait, // noWait\n\t\tnil, // TODO: may be I should add support for args\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Consumer.Init() create delivery channel error: %v\", err)\n\t}\n\n\t// channels for event listeners (connection)\n\tconnCloseChannel := make(chan *amqp.Error)\n\tc.connCloseChannel = c.connection.NotifyClose(connCloseChannel)\n\n\t// channels for event listeners (channel)\n\tchanCancelChannel := make(chan string)\n\tc.chanCancelChannel = c.channel.NotifyCancel(chanCancelChannel)\n\n\tchanCloseChannel := make(chan *amqp.Error)\n\tc.chanCloseChannel = c.channel.NotifyClose(chanCloseChannel)\n\n\treturn nil\n}", "func (c *client) Connect(ctx context.Context) error {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tc.ctx = ctx\n\n\tremote := c.cfg.GetURL()\n\n\tvar subList []string\n\n\tfor topic := range c.SubscribedTopics {\n\t\tif IsPublicTopic(topic) {\n\t\t\tc.createCache(topic)\n\n\t\t\tsubList = append(subList, c.normalizeTopic(topic))\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsPrivateTopic(topic) && c.hasAuth() {\n\t\t\tc.createCache(topic)\n\n\t\t\tsubList = append(subList, c.normalizeTopic(topic))\n\t\t}\n\t}\n\n\tif len(subList) > 0 {\n\t\tremote.RawQuery = \"subscribe=\" + strings.Join(subList, \",\")\n\t}\n\n\tlog.Info(\"Connecting to: \", remote.String())\n\n\tconn, rsp, err := websocket.DefaultDialer.DialContext(\n\t\tctx, remote.String(), c.getHeader())\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Fail to connect[%s]: %v, %v\",\n\t\t\tremote.String(), err, rsp)\n\t}\n\n\tdefer func() {\n\t\tgo c.messageHandler()\n\t\tgo c.heartbeatHandler()\n\t}()\n\n\tc.ws = conn\n\tc.connected = true\n\tc.ws.SetCloseHandler(c.closeHandler)\n\n\treturn nil\n}", "func (z *ZkRegistry) connect() error {\n\tif !z.isConnected() {\n\t\tconn, connChan, err := zk.Connect(z.NodeParams.Servers, time.Second)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor {\n\t\t\tisConnected := false\n\n\t\t\tselect {\n\t\t\tcase connEvent := <-connChan:\n\t\t\t\tif connEvent.State == zk.StateConnected {\n\t\t\t\t\tisConnected = true\n\t\t\t\t}\n\t\t\tcase _ = <-time.After(time.Second * 3):\n\t\t\t\treturn errors.New(\"Connect to zookeeper server timeout!\")\n\t\t\t}\n\n\t\t\tif isConnected {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\terr = conn.AddAuth(\"digest\", []byte(z.node.User.UserName+\":\"+z.node.User.Password))\n\t\tif err != nil {\n\t\t\treturn errors.New(\"AddAuth error: \\n\" + err.Error())\n\t\t}\n\n\t\tz.Conn = conn\n\t}\n\n\treturn nil\n}", "func (c *Driver) Connect() error {\n\tif !IsChannelValid(c.channel) {\n\t\treturn InvalidChanName\n\t}\n\n\tc.clean()\n\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", c.Host, c.Port))\n\tif err != nil {\n\t\treturn err\n\t} \n\t\n\tc.closed = false\n\tc.conn = conn\n\tc.reader = bufio.NewReader(c.conn)\n\n\terr = c.write(fmt.Sprintf(\"START %s %s\", c.channel, c.Password))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = c.read()\n\t_, err = c.read()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func connect() *websocket.Conn {\n\turl := url.URL{Scheme: \"ws\", Host: *addr, Path: \"/ws\"}\n\tlog.Info(\"Connecting to \", url.String())\n\tconn, _, err := dialer.Dial(url.String(), nil)\n\tcheckError(err)\n\tlog.Info(\"Connected to \", url.String())\n\n\t// Read the message from server with deadline of ResponseWait(30) seconds\n\tconn.SetReadDeadline(time.Now().Add(utils.ResponseWait * time.Second))\n\n\treturn conn\n}", "func (c *Easee) connect(ts oauth2.TokenSource) func() (signalr.Connection, error) {\n\tbo := backoff.NewExponentialBackOff()\n\tbo.MaxInterval = time.Minute\n\n\treturn func() (conn signalr.Connection, err error) {\n\t\tdefer func() {\n\t\t\tif err != nil {\n\t\t\t\ttime.Sleep(bo.NextBackOff())\n\t\t\t} else {\n\t\t\t\tbo.Reset()\n\t\t\t}\n\t\t}()\n\n\t\ttok, err := ts.Token()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), request.Timeout)\n\t\tdefer cancel()\n\n\t\treturn signalr.NewHTTPConnection(ctx, \"https://streams.easee.com/hubs/chargers\",\n\t\t\tsignalr.WithHTTPClient(c.Client),\n\t\t\tsignalr.WithHTTPHeaders(func() (res http.Header) {\n\t\t\t\treturn http.Header{\n\t\t\t\t\t\"Authorization\": []string{fmt.Sprintf(\"Bearer %s\", tok.AccessToken)},\n\t\t\t\t}\n\t\t\t}),\n\t\t)\n\t}\n}", "func (client *Client) Connect(brokers []string, config *sarama.Config) error {\n\tproducer, err := sarama.NewAsyncProducer(brokers, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient.producer = producer\n\tclient.brokers = brokers\n\tclient.config = config\n\n\treturn nil\n}", "func (h *Harness) connectRPCClient() (e error) {\n\tvar client *rpcclient.Client\n\trpcConf := h.node.config.rpcConnConfig()\n\tfor i := 0; i < h.maxConnRetries; i++ {\n\t\tif client, e = rpcclient.New(&rpcConf, h.handlers, qu.T()); E.Chk(e) {\n\t\t\ttime.Sleep(time.Duration(i) * 50 * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\tif client == nil {\n\t\treturn fmt.Errorf(\"connection timeout\")\n\t}\n\th.Node = client\n\th.wallet.SetRPCClient(client)\n\treturn nil\n}", "func (ch *ServerChannel) Connect(c *Client) {}", "func (n *natsBroker) Connect() error {\n\tconn, err := nats.Connect(n.Address())\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[NATS]: Connected to %s\", n.Address())\n\tn.connection = conn\n\treturn nil\n}", "func (c *Notification2Client) connect() error {\n\tif c.dialer == nil {\n\t\tpanic(\"Missing dialer for realtime client\")\n\t}\n\tws, err := c.createWebsocket()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\tc.ws = ws\n\tif c.tomb == nil {\n\t\tc.tomb = &tomb.Tomb{}\n\t\tc.tomb.Go(c.worker)\n\t}\n\tc.connected = true\n\n\treturn nil\n}", "func (bili *BiliClient) Connect(rid int) error {\n\troomID, err := getRealRoomID(rid)\n\tif err != nil {\n\t\tlog.Println(\"client Connect \" + err.Error())\n\t\treturn errors.New(\"无法获取房间真实ID: \" + err.Error())\n\t}\n\n\tu := url.URL{Scheme: \"ws\", Host: serverAddr, Path: \"/sub\"}\n\n\tif bili.serverConn, _, err = websocket.DefaultDialer.Dial(u.String(), nil); err != nil {\n\t\tlog.Println(\"client Connect \" + err.Error())\n\t\treturn errors.New(\"Cannot dail websocket: \" + err.Error())\n\t}\n\tbili.roomID = roomID\n\n\tif err := bili.sendJoinChannel(roomID); err != nil {\n\t\treturn errors.New(\"Cannot send join channel: \" + err.Error())\n\t}\n\tbili.setConnect(true)\n\n\tgo bili.heartbeatLoop()\n\tgo bili.receiveMessages()\n\treturn nil\n}", "func (rhost *rhostData) connect() {\n\n\t// Get local IP list\n\tips, _ := rhost.getIPs()\n\n\t// Create command buffer\n\tbuf := new(bytes.Buffer)\n\t_, port := rhost.teo.td.GetAddr()\n\tbinary.Write(buf, binary.LittleEndian, byte(len(ips)))\n\tfor _, addr := range ips {\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t}\n\tbinary.Write(buf, binary.LittleEndian, uint32(port))\n\tdata := buf.Bytes()\n\tfmt.Printf(\"Connect to r-host, send local IPs\\nip: %v\\nport: %d\\n\", ips, port)\n\n\t// Send command to r-host\n\trhost.teo.sendToTcd(rhost.tcd, CmdConnectR, data)\n\trhost.connected = true\n}", "func (confRabbit RabbitMq) Conn() *amqp.Connection {\n\treturn confRabbit.conn\n}", "func Connect(config *viper.Viper) (Connection, error) {\n\tvar c Connection\n\n\terr := c.InitLog(\"\")\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\thost := config.GetString(\"server.host\")\n\tport := config.GetString(\"server.controlPort\")\n\n\tserver := host + \":\" + port\n\tc.connection, err = net.Dial(\"tcp\", server)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\treturn c, nil\n}", "func (gc *GokuyamaClient) Connect(hostname string, portNo int) error {\n\tvar err error\n\tgc.conn, err = net.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", hostname, portNo))\n\treturn err\n}", "func (c *Client) Connect(bus *bus.Bus) error {\n\tserver := viper.GetString(\"irc.server\")\n\tlog.Println(\"Attempting to connect to\", server)\n\tif err := c.Connection.Connect(server); err != nil {\n\t\treturn err\n\t}\n\tbus.Sub(\"note-gh-event-commit\", c.NoteGhEvent(bus, \"commit\"))\n\tbus.Sub(\"note-gh-event-pullRequest\", c.NoteGhEvent(bus, \"pullRequest\"))\n\tbus.Sub(\"note-gh-event-issue\", c.NoteGhEvent(bus, \"issue\"))\n\treturn nil\n}", "func (h *Handler) getAMQPClient() (*amqp.Connection, error) {\n\n\t//generate access token\n\taccesstoken, err := h.Maskinporten.CreateAccessToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//create connection url\n\tcombinedString := h.RabbitMQ.Password + \" \" + accesstoken.AccessToken\n\tt := &url.URL{Path: combinedString}\n\tencodedPW := t.String()\n\n\turl := fmt.Sprintf(\n\t\t\"amqps://%s:%s@%s:%s/\",\n\t\th.RabbitMQ.Username,\n\t\tencodedPW,\n\t\th.RabbitMQ.Host,\n\t\th.RabbitMQ.Port,\n\t)\n\n\tlog.Logger.Infof(\"Trying to connect to %s\", url)\n\n\t//try to connect, 30s default timeout\n\treturn amqp.Dial(url)\n}", "func (c *Config) connect() {\n\tc.emitEvent(Event{Type: EventConnected})\n}", "func (queueWriter *QueueWriter) Connect(connectionAddress string) {\n\tconnection, err := stomp.Dial(\"tcp\", connectionAddress)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not connect to %s\", connectionAddress)\n\t\treturn\n\t}\n\n\tqueueWriter.isConnected = true\n\tqueueWriter.connection = connection\n\n\tlog.Printf(\"Connected to address: %s\", connectionAddress)\n}", "func (m *AmqpClient) ConnectToBroker(connectionString string) error {\n\tif connectionString == \"\" {\n\t\treturn fmt.Errorf(\"empty dns\")\n\t}\n\n\tvar err error\n\tm.conn, err = amqp.Dial(fmt.Sprintf(\"%s/\", connectionString))\n\n\treturn err\n}", "func (c *Client) Connect() error {\n\t// Open WebSocket connection\n\n\tlogrus.Debugln(\"Connecting to websocket: \", c.URL)\n\theader := http.Header{}\n\theader.Add(\"x-acs-session-token\", c.token)\n\tconn, _, err := c.Dialer.Dial(c.URL, header)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Conn = conn\n\tc.Connected = true\n\n\t// Initialize message types for gotty\n\t// go c.pingLoop()\n\n\treturn nil\n}", "func (mb *tcpTransporter) Connect() error {\n\tmb.mu.Lock()\n\tdefer mb.mu.Unlock()\n\n\treturn mb.connect()\n}", "func (client *Client) connect(connType string) net.Conn {\n\tconn, err := net.Dial(connType, client.ipAddr+\":\"+client.port)\n\tif err != nil {\n\t\tlog.Fatal(\"Error during the connection :\", err)\n\t}\n\treturn conn\n}", "func connect() (*websocket.Conn, error) {\n\thost := fmt.Sprintf(\"%s:%s\", configuration.TV.Host, *configuration.TV.Port)\n\tpath := \"/api/v2/channels/samsung.remote.control\"\n\tquery := fmt.Sprintf(\"name=%s\", base64.StdEncoding.EncodeToString([]byte(configuration.Controller.Name)))\n\tu := url.URL{Scheme: *configuration.TV.Protocol, Host: host, Path: path, RawQuery: query}\n\n\tlog.Infof(\"Opening connection to %s ...\", u.String())\n\n\twebsocket.DefaultDialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\n\tconnection, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\n\tif err != nil {\n\t\tlog.Debugf(\"%v\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Infof(\"Connection is established.\")\n\n\treturn connection, nil\n}", "func (rc *RemoteCollector) connect() error {\n\tif rc.pconn != nil {\n\t\trc.pconn.Close()\n\t\trc.pconn = nil\n\t}\n\n\tc, err := rc.dial()\n\tif err == nil {\n\t\t// Create a protobuf delimited writer wrapping the connection. When the\n\t\t// writer is closed, it also closes the underlying connection (see\n\t\t// source code for details).\n\t\trc.pconn = pio.NewDelimitedWriter(c)\n\t}\n\treturn err\n}", "func (c *rpcclient) connect(ctx context.Context) (err error) {\n\tvar success bool\n\n\tc.clients = make([]*ethConn, 0, len(c.endpoints))\n\tc.neverConnectedEndpoints = make([]endpoint, 0, len(c.endpoints))\n\n\tfor _, endpoint := range c.endpoints {\n\t\tec, err := c.connectToEndpoint(ctx, endpoint)\n\t\tif err != nil {\n\t\t\tc.log.Errorf(\"Error connecting to %q: %v\", endpoint, err)\n\t\t\tc.neverConnectedEndpoints = append(c.neverConnectedEndpoints, endpoint)\n\t\t\tcontinue\n\t\t}\n\n\t\tdefer func() {\n\t\t\t// If all connections are outdated, we will not start, so close any open connections.\n\t\t\tif !success {\n\t\t\t\tec.Close()\n\t\t\t}\n\t\t}()\n\n\t\tc.clients = append(c.clients, ec)\n\t}\n\n\tsuccess = c.sortConnectionsByHealth(ctx)\n\n\tif !success {\n\t\treturn fmt.Errorf(\"failed to connect to an up-to-date ethereum node\")\n\t}\n\n\tgo c.monitorConnectionsHealth(ctx)\n\n\treturn nil\n}", "func Connect() error {\n\tredisHost := os.Getenv(\"REDIS_HOST\")\n\tredisPassword := os.Getenv(\"REDIS_PASSWORD\")\n\tredisPort := os.Getenv(\"REDIS_PORT\")\n\n\t// create a client instance\n\tClient = redis.NewClient(&redis.Options{\n\t\tAddr: redisHost + \":\" + redisPort,\n\t\tPassword: redisPassword,\n\t\tDB: 0,\n\t})\n\n\t// ping the server\n\t_, pingError := Client.Ping(ctx).Result()\n\tif pingError != nil {\n\t\treturn pingError\n\t}\n\n\treturn nil\n}", "func (c *GatewayClient) Connect() error {\n\t// XXX: probably we can merge this code in SendTo\n\tc.Lock()\n\tdefer c.Unlock()\n\treturn c.connect()\n}", "func (db *Postgres) connect() error {\n\tdbMap, err := gosql.Open(\"postgres\", db.URI)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to open database with uri: %s\", db.URI)\n\t}\n\n\t// Configure the database mapping object\n\tdb.DbMap = &gorp.DbMap{Db: dbMap, Dialect: gorp.PostgresDialect{}}\n\n\t// Verify database\n\terr = db.ping()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to ping database with uri: %s\", db.URI)\n\t}\n\n\treturn nil\n}", "func (this Scanner) connect(user, host string, conf ssh.ClientConfig) (*ssh.Client, *ssh.Session, error) {\n\t// Develop the network connection out\n\tconn, err := ssh.Dial(\"tcp\", host, &conf)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Actually perform our connection\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn nil, nil, err\n\t}\n\n\treturn conn, session, nil\n}", "func (pc *Client) Connect() (err error) {\n\n\tif debug {\n\t\tfmt.Printf(\"Connecting to %s\\n\", pc.server)\n\t}\n\n\tc, _, err := websocket.DefaultDialer.Dial(pc.server, nil)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpc.connection = c\n\n\tgo func() {\n\t\tfor {\n\t\t\t_, message, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tpc.disconnected()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpc.receive(message)\n\t\t}\n\t}()\n\n\terr = pc.wait(messages.TYPE_HELLO)\n\n\tif err != nil {\n\t\tpc.connected = true\n\t}\n\n\treturn\n}", "func (cg *CandlesGroup) connect() {\n\tcg.wsClient = websocket.NewClient(wsURL, cg.httpProxy)\n\tif err := cg.wsClient.Connect(); err != nil {\n\t\tlog.Println(\"[BITFINEX] Error connecting to bitfinex API: \", err)\n\t\tcg.restart()\n\t\treturn\n\t}\n\tcg.wsClient.Listen(cg.bus.dch, cg.bus.ech)\n}", "func Connect(host string) (redis.Conn, error) {\n\tconn, err := redis.Dial(\"tcp\", host)\n\tif err != nil {\n\t\tlogp.Err(\"Redis connection error: %v\", err)\n\t}\n\n\treturn conn, err\n}", "func (ch *InternalChannel) Connect(c *Client) {}", "func main() {\n\n\tconn, err := amqp.Dial(\"amqp://guest:guest@localhost:5672/\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tpanic(err)\n\t}\n\n\tdefer conn.Close()\n\n\tfmt.Println(\"Successfully connected to our RabbitMQ\")\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tpanic(err)\n\t}\n\tdefer ch.Close()\n\n\tq, err := ch.QueueDeclare(\"Test Queue\", false, false, false, false, nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(q)\n\n\tfor i := 0; i < 1000; i++ {\n\n\t\terr = ch.Publish(\"\", \"Test Queue\", false, false, amqp.Publishing{\n\t\t\tContentType: \"test/plain\",\n\t\t\tBody: []byte(\"Hello world!\"),\n\t\t})\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(\"Successfully published Message to Queue\")\n\t\ttime.Sleep(time.Second)\n\t}\n\n\tfmt.Println(q)\n}", "func Connect(host, clientid, username, password string) (c mqtt.Client) {\n\n\topts := mqtt.NewClientOptions().AddBroker(host).SetClientID(clientid)\n\topts.SetKeepAlive(2 * time.Second)\n\topts.SetDefaultPublishHandler(\n\t\tfunc(client mqtt.Client, msg mqtt.Message) {\n\t\t\tmqtt.ERROR.Println(\"TOPIC: %s MSG: %s\", msg.Topic(), msg.Payload())\n\t\t})\n\topts.SetPingTimeout(1 * time.Second)\n\topts.SetUsername(username).SetPassword(password)\n\tc = mqtt.NewClient(opts)\n\n\tif token := c.Connect(); token.Wait() && token.Error() != nil {\n\t\tpanic(token.Error())\n\t}\n\treturn\n}", "func (amqpSuite *AmqpSuite) dialConnection() *amqp.Connection {\n\taddress := amqpSuite.Opts.dialAddress\n\tif address == \"\" {\n\t\taddress = TestDialAddress\n\t}\n\n\tconfig := amqpSuite.Opts.dialConfig\n\tif !amqpSuite.Opts.dialConfigSet {\n\t\tconfig = amqp.DefaultConfig()\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tconn, err := amqp.DialConfigCtx(ctx, address, config)\n\tif err != nil {\n\t\tamqpSuite.T().Errorf(\"error dialing connection: %v\", err)\n\t\tamqpSuite.T().FailNow()\n\t}\n\n\treturn conn\n}", "func (ec *ejabberdClient) Connect() (err error) {\n\tname := ec.getClientName()\n\n\tlog.Info(\"connect client \", name, \" to host \", ec.opt.Host)\n\tec.conn, err = xmpp.Dial(ec.opt.Host, ec.opt.Username, ec.opt.Domain,\n\t\tec.getClientResource(), ec.opt.Password, &xmpp.Config{\n\t\t\tSkipTLS: true,\n\t\t\tTLSConfig: &tls.Config{},\n\t\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo ec.keepConnectionAlive()\n\treturn\n}", "func NewConnection(d string) (*amqp.Connection, error) {\n\treturn amqp.Dial(d)\n}", "func (r *Redis) Connect() {\n\tr.client = redis.NewUniversalClient(&redis.UniversalOptions{\n\t\tAddrs: []string{r.config.Addr()},\n\t\tPassword: r.config.Password,\n\t\tDB: r.config.DB,\n\t})\n}", "func (p *pahoClient) Connect(c chan error) {\n\n\ttoken := p.client.Connect()\n\tc <- p.waitForToken(token)\n}", "func (ms *MqttSocket) Connect() error {\n\tms.client = mqtt.NewClient(ms.options)\n\tif token := ms.client.Connect(); token.Wait() && token.Error() != nil {\n\t\treturn token.Error()\n\t}\n\treturn nil\n}", "func connect(dialOpts *DialOpts, grpcServer *grpc.Server, yDialer *YamuxDialer) error {\n\t// dial underlying tcp connection\n\tvar conn net.Conn\n\tvar err error\n\n\tif dialOpts.TLS {\n\t\t// use tls\n\t\tcfg := dialOpts.TLSConfig\n\t\tif cfg == nil {\n\t\t\tcfg = &tls.Config{}\n\t\t}\n\t\tconn, err = tls.Dial(\"tcp\", dialOpts.Addr, cfg)\n\n\t} else {\n\t\tconn, err = (&net.Dialer{}).DialContext(context.Background(), \"tcp\", dialOpts.Addr)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tsession, err := yamux.Client(conn, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\t// now that we have a connection, create both clients & servers\n\n\t// setup client\n\tyDialer.SetSession(session)\n\n\t// start grpc server in a separate goroutine. this will exit when the\n\t// underlying session (conn) closes and clean itself up.\n\tgo grpcServer.Serve(session)\n\n\t// return when the conn closes so we can try reconnecting\n\t<-session.CloseChan()\n\treturn nil\n}", "func (c *Notification2Client) Connect() error {\n\tif !c.IsConnected() {\n\t\terr := c.connect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (r *CacheRedis) connect() {\n\n}", "func (l *Logger) connect() (err error) {\n\tif l.conn != nil {\n\t\t// ignore err from close, it makes sense to continue anyway\n\t\tl.conn.close()\n\t\tl.conn = nil\n\t}\n\n\tif l.network == \"\" {\n\t\tl.conn, err = unixSyslog()\n\t\tif l.hostname == \"\" {\n\t\t\tl.hostname = \"localhost\"\n\t\t}\n\t} else {\n\t\tvar c net.Conn\n\t\tc, err = net.Dial(l.network, l.raddr)\n\t\tif err == nil {\n\t\t\tl.conn = &netConn{conn: c}\n\t\t\tif l.hostname == \"\" {\n\t\t\t\tl.hostname = c.LocalAddr().String()\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (client *ClientRPC) connect() bool {\n\tconnection, err := net.DialTimeout(\"tcp\", \"localhost:7398\", time.Duration(10)*time.Second)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to connect to relay server at localhost: %v\", err)\n\t\treturn false\n\t}\n\tclient.relay = jsonrpc.NewClient(connection)\n\tlog.Println(\"Connected to relay server\")\n\treturn true\n}", "func connect(host string) (*rpc.Client, error) {\n\taddr := fmt.Sprintf(\"%s:%d\", host, *Port)\n\tc, e := rpc.DialHTTP(\"tcp\", addr)\n\tif e != nil {\n\t\treturn nil, fmt.Errorf(\"Dialing Prism %s: %v\", addr, e)\n\t}\n\treturn c, nil\n}" ]
[ "0.7894139", "0.7789549", "0.76434803", "0.72879946", "0.72490144", "0.7248601", "0.7241409", "0.72375685", "0.7220578", "0.715189", "0.7151718", "0.7076857", "0.70511913", "0.7030396", "0.702692", "0.69975215", "0.69159627", "0.6912748", "0.6884651", "0.6796288", "0.6754217", "0.6726855", "0.6571243", "0.64217895", "0.63589734", "0.63464105", "0.63345766", "0.6330692", "0.632389", "0.6322934", "0.63107514", "0.62949485", "0.6262077", "0.6229016", "0.62187946", "0.62158054", "0.6172799", "0.61497045", "0.61456496", "0.6122762", "0.60822004", "0.6070923", "0.60704684", "0.6065763", "0.6064862", "0.60647494", "0.6054457", "0.6053922", "0.6022852", "0.6010523", "0.59716004", "0.5970665", "0.59619427", "0.59132516", "0.59120375", "0.5903799", "0.58997804", "0.5895029", "0.5894884", "0.58947086", "0.5886511", "0.5882681", "0.58814245", "0.5875162", "0.58684856", "0.5859438", "0.5854532", "0.5849094", "0.5844649", "0.5818403", "0.5818012", "0.576642", "0.5765489", "0.5761155", "0.5743998", "0.5736675", "0.57344234", "0.57197", "0.57172966", "0.57115024", "0.5710665", "0.5709404", "0.5707573", "0.5705703", "0.5703756", "0.57031244", "0.56953394", "0.569106", "0.5686302", "0.5685014", "0.56848574", "0.5676438", "0.5672832", "0.56664383", "0.5654885", "0.5638318", "0.56364393", "0.5626578", "0.5613673", "0.56127393" ]
0.76561403
2
Close closes the connection and channel
func (s *Server) Close() { s.Conn.Close() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ch *Channel) Close() {}", "func (c *client) Close() error { return c.c.Close() }", "func (cha *Channel) close() {\n\t// not care about channel close error, because it's the client action\n\tcha.cha.Close()\n\n\tcha.conn.decrNumOpenedChannel()\n\tcha.cha = nil\n\tcha.conn = nil\n}", "func (con *IRCConn) Close() {\n close(con.read);\n close(con.Write);\n con.sock.Close();\n}", "func (c *UDPChannel) Close() {\n\n}", "func (c *Client) Close() { c.streamLayer.Close() }", "func (c *Client) Close() {}", "func (c *Client) Close() {}", "func (c *client) close() {\n\tc.leave()\n\tc.Conn.Close()\n\tc.Message <- \"/quit\"\n}", "func (self *Client) close() {\n\t// TODO: Cleanly close connection to remote\n}", "func (rw *Channel) Close() error {\n\tclose(rw.writeChannel)\n\treturn rw.conn.Close()\n}", "func (c *Client) Close() {\n}", "func (c *Client) Close() {\n}", "func (c *Connection) Close() error { return c.pump.Close() }", "func (c *RmqConnection) Close() {\n\tclose(c.stop)\n\tc.wg.Wait()\n\tc.ch.Close()\n\tc.conn.Close()\n}", "func (c *TestConnection) Close() error {\n if c.CloseError != nil {\n return c.CloseError\n }\n \n c.Closed = true\n return nil\n}", "func (c *Connection) Close() {\n\tif c.IsConnected == false {\n\t\treturn\n\t}\n\tc.IsConnected = false\n\tif r := recover(); r != nil {\n\t\tlog.Print(\"Closing due to problematic connection.\")\n\t} else {\n\t\tc.Send(CommandBasic{\n\t\t\tType: Cya,\n\t\t})\n\t}\n\tc.Conn.Close()\n\tvar blank struct{}\n\tc.ClosedChan <- blank\n}", "func (c *Client) Close() error { return c.redis.Close() }", "func (t *Client) Close() error { return nil }", "func (self *Echo_Client) Close() {\n\tself.cc.Close()\n}", "func (pc *Client) Close() {\n\tpc.connected = false\n\tpc.connection.Close()\n}", "func (c *Channel) Close() error {\n\treturn c.exit(false)\n}", "func (c *ManetConnection) Close() {\n\tc.conn.Close()\n}", "func (p *TCPProxy) Close(c chan struct{}) {\n\tclose(c)\n}", "func (self *AMQPChannel) Close() error {\n\treturn self.channel.Close()\n}", "func (c *Conn) Close() error { return nil }", "func (b *BIRDClient) Close() error { return b.conn.Close() }", "func (a *AMQP) Close() {\n\ta.Channel.Close()\n\ta.Connection.Close()\n}", "func (ch *clientSecureChannel) Close(ctx context.Context) error {\n\tch.Lock()\n\tdefer ch.Unlock()\n\tch.closing = true\n\tvar request = &ua.CloseSecureChannelRequest{}\n\t_, err := ch.Request(ctx, request)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ch.conn != nil {\n\t\treturn ch.conn.Close()\n\t}\n\treturn nil\n}", "func (q *Queue) Close() {\n\tdefer q.conn.Close()\n\tdefer q.channel.Close()\n}", "func (i ios) Close(ctx context.Context) error {\n\ti.Connection.Close(ctx)\n\n\treturn nil\n}", "func (gc *GokuyamaClient) Close() error {\n\tvar err error\n\terr = gc.conn.Close()\n\treturn err\n}", "func (c *Conn) Close() error {\n\t// Resets client\n\tc.client = nil\n\treturn nil\n}", "func (conn *Connection) Close() {\n\tclose(conn.directChan)\n\tclose(conn.rpcChan)\n\tfor direct := range conn.directChan {\n\t\terr := direct.Close()\n\t\tif err != nil{\n\t\t\tlog.Errorln(err)\n\t\t}\n\t}\n\tfor client := range conn.rpcChan {\n\t\terr := client.Close()\n\t\tif err != nil{\n\t\t\tlog.Errorln(err)\n\t\t}\n\t}\n}", "func (v *connection) Close() error {\n\tconnectionLogger.Trace(\"connection.Close()\")\n\n\tv.sendMessage(&msgs.FETerminateMsg{})\n\n\tvar result error = nil\n\n\tif v.conn != nil {\n\t\tresult = v.conn.Close()\n\t\tv.conn = nil\n\t}\n\n\treturn result\n}", "func ConnClose(c *tls.Conn,) error", "func (c *clientImpl) Close() error {\n\tif c.conn != nil {\n\t\tif err := c.conn.Close(); err != nil {\n\t\t\treturn errors.Wrap(err, \"conn.Close() failed\")\n\t\t}\n\t\tc.pbClient = nil\n\t\tc.conn = nil\n\t\tc.stream = nil\n\t\treturn nil\n\t}\n\treturn errors.Errorf(\"already Closed\")\n}", "func (c *Client) Close() {\n\t_ = c.conn.Close()\n}", "func (bc BufConn) Close() error { return nil }", "func (c *CryptoStreamConn) Close() error {\n\treturn nil\n}", "func (c *SodaClient) Close() {\n\tc.conn.Close()\n}", "func (r *RTCPeerConnection) Close() error {\n\tr.networkManager.Close()\n\treturn nil\n}", "func (replayer *replayer) closeConnection(ctx context.Context) {\n\t// Call Shutdown RCP on the replayer\n\tif replayer.rpcClient != nil {\n\t\t// Use a clean context, since ctx is most likely already cancelled.\n\t\tsdCtx := attachAuthToken(context.Background(), replayer.deviceConnectionInfo.authToken)\n\t\t_, err := replayer.rpcClient.Shutdown(sdCtx, &replaysrv.ShutdownRequest{})\n\t\tif err != nil {\n\t\t\tlog.E(ctx, \"Sending replayer Shutdown request: %v\", err)\n\t\t}\n\t}\n\treplayer.rpcClient = nil\n\n\tif replayer.rpcStream != nil {\n\t\treplayer.rpcStream.CloseSend()\n\t}\n\treplayer.rpcStream = nil\n\n\tif replayer.conn != nil {\n\t\treplayer.conn.Close()\n\t}\n\treplayer.conn = nil\n\n\treplayer.deviceConnectionInfo.cleanupFunc()\n}", "func (c *minecraftConn) close() error {\n\treturn c.closeKnown(true)\n}", "func (recv *receiver) close() {\n\terr := recv.conn.Close()\n\tif err != nil {\n\t\tlog.Printf(\"receiver.close: %s\\n\", err)\n\t}\n}", "func (c *Connection) Close() (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Trace(\"Recovered in Close\", r)\n\t\t}\n\t}()\n\n\tc.ready = false\n\tif c.client != nil {\n\t\tc.client.CloseIdleConnections()\n\t}\n\tif c.tor != nil {\n\t\terr = c.tor.Close()\n\t}\n\treturn\n}", "func (ctx *rabbitMQContext) Close() {\n\tctx.channel.Close()\n\tctx.connection.Close()\n}", "func (r *Receiver) Close() error { return nil }", "func (c *Connection) Close() error {\n\tc.identity = nil\n\tif c.clientConn != nil {\n\t\terr := c.clientConn.Close()\n\t\tc.clientConn = nil\n\t\treturn err\n\t}\n\treturn nil\n}", "func Close() {\n\t_ = client.Close()\n}", "func (c *Client) Close() error {\n\tif c.AStream != nil {\n\t\tif err := c.AStream.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.AStream = nil\n\t}\n\n\tif c.PStream != nil {\n\t\tif err := c.PStream.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.PStream = nil\n\t}\n\n\treturn nil\n}", "func (c *Connector) Close() {\n\tc.conn.Close()\n\tclose(c.die)\n}", "func (c *Client) Close() error {\n\tc.done <- struct{}{}\n\tclose(c.ch)\n\n\tif err := c.conn.Close(); err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Channel) Close() {\n\tclose(c.done)\n\tc.sharedDone()\n}", "func (c *Conn) Close() error { return c.pc.Close() }", "func (c *connection) Close() {\n\tbaseurl := \"http://fritz.box/webservices/homeautoswitch.lua\"\n\tparameters := make(map[string]string)\n\tparameters[\"sid\"] = c.sid\n\tparameters[\"logout\"] = \"logout\"\n\tUrl := prepareRequest(baseurl, parameters)\n\tsendRequest(Url)\n}", "func (rw *NopConn) Close() error { return nil }", "func (dataChannel *DataChannel) Close(log log.T) error {\n\tlog.Infof(\"Closing datachannel with url %s\", dataChannel.wsChannel.GetStreamUrl())\n\treturn dataChannel.wsChannel.Close(log)\n}", "func (s *SshConnection) Close() {\n\tif s.Client != nil {\n\t\ts.Client.Close()\n\t}\n\ts.connectionStatusMU.Lock()\n\ts.connectionStatus = STATUS_CLOSED\n\ts.connectionStatusMU.Unlock()\n}", "func (client *Client) Close() {\n\t// Set halting flag and then close our socket to server.\n\t// This will cause the blocked getIO() in readReplies() to return.\n\tclient.Lock()\n\tclient.halting = true\n\tif client.connection.state == CONNECTED {\n\t\tclient.connection.state = INITIAL\n\t\tclient.connection.Close()\n\t}\n\tclient.Unlock()\n\n\t// Wait for the goroutines to return\n\tclient.goroutineWG.Wait()\n\tbucketstats.UnRegister(bucketStatsPkgName, client.GetStatsGroupName())\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n\tclose(c.In)\n\tclose(c.Out)\n}", "func (c Connection) Close() error {\n\tpanic(\"TODO\")\n}", "func (clt *client) close() {\n\t// Apply exclusive lock\n\tclt.statusLock.Lock()\n\n\tif clt.status != StatusConnected {\n\t\tclt.status = StatusDisabled\n\t\tclt.statusLock.Unlock()\n\t\treturn\n\t}\n\tclt.status = StatusDisabled\n\tclt.statusLock.Unlock()\n\n\tif err := clt.conn.Close(); err != nil {\n\t\tclt.options.ErrorLog.Printf(\"Failed closing connection: %s\", err)\n\t}\n\n\t// Wait for the reader goroutine to die before returning\n\t<-clt.readerClosing\n}", "func (c OutputChannel) Close() {\n\tclose(c)\n}", "func (r *client) Close() error {\n\treturn r.conn.Close()\n}", "func (c *fakeRedisConn) Close() error { return nil }", "func (conn *Tunnel) Close() {\n\tconn.once.Do(func() {\n\t\tconn.requestDisc()\n\n\t\tclose(conn.done)\n\t\tconn.wait.Wait()\n\n\t\tconn.sock.Close()\n\t})\n}", "func (recv *receiver) Close() {\n\trecv.conn.Close()\n\tclose(recv.close)\n}", "func (c *Connection) Close() error {\n\trerr := c.ReadCloser.Close()\n\twerr := c.WriteCloser.Close()\n\tif rerr != nil {\n\t\treturn rerr\n\t}\n\treturn werr\n}", "func (j *JSONWebsocketCodec) Close() error {\n\treturn j.conn.Close()\n}", "func (self *File_Client) Close() {\n\tself.cc.Close()\n}", "func (c *ClientConn) Close() error {\n\tif c.state == clientConnStatePlay || c.state == clientConnStateRecord {\n\t\tclose(c.backgroundTerminate)\n\t\t<-c.backgroundDone\n\n\t\tc.Do(&base.Request{\n\t\t\tMethod: base.Teardown,\n\t\t\tURL: c.streamURL,\n\t\t\tSkipResponse: true,\n\t\t})\n\t}\n\n\tfor _, l := range c.udpRTPListeners {\n\t\tl.close()\n\t}\n\n\tfor _, l := range c.udpRTCPListeners {\n\t\tl.close()\n\t}\n\n\terr := c.nconn.Close()\n\treturn err\n}", "func (c *botsGRPCClient) Close() error {\n\treturn c.connPool.Close()\n}", "func (c *NOOPConnection) Close() {\n}", "func (cl *Client) Close() (err error) {\n\tcl.url = nil\n\treturn cl.conn.Close()\n}", "func (w *Client) Close() error {\n\treturn w.connection.Close()\n}", "func (r *ResourceConn) Close() {\n\tr.ClientConn.Close()\n}", "func (closer *Closer) Close() {\n\tclose(closer.channel)\n}", "func (s *Connection) Close() error {\n\ts.receiveIdLock.Lock()\n\tif s.goneAway {\n\t\ts.receiveIdLock.Unlock()\n\t\treturn nil\n\t}\n\ts.goneAway = true\n\ts.receiveIdLock.Unlock()\n\n\tvar lastStreamId spdy.StreamId\n\tif s.receivedStreamId > 2 {\n\t\tlastStreamId = s.receivedStreamId - 2\n\t}\n\n\tgoAwayFrame := &spdy.GoAwayFrame{\n\t\tLastGoodStreamId: lastStreamId,\n\t\tStatus: spdy.GoAwayOK,\n\t}\n\n\terr := s.framer.WriteFrame(goAwayFrame)\n\tgo s.shutdown(s.closeTimeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) Close() error {\n\treturn c.connection.Close()\n}", "func (c *Conn) Close(ctx context.Context) error {\n\treturn c.redfishwrapper.Close(ctx)\n}", "func (s *Socket) Close() {\n\ts.Online = false\n\t(*s.conn).Close()\n}", "func (client *Client) Close() {\n\tclient.conn.Close()\n\tclient.conn = nil\n}", "func (s *Session) Close() error {\n\tif !s.IsReady() {\n\t\treturn errAlreadyClosed\n\t}\n\tif err := s.channel.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := s.connection.Close(); err != nil {\n\t\treturn err\n\t}\n\tclose(s.done)\n\n\ts.m.Lock()\n\t{\n\t\ts.isReady = false\n\t}\n\ts.m.Unlock()\n\n\treturn nil\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n}", "func (r *RTNL) Close() {\n\tif r.conn != nil {\n\t\tr.conn.Close()\n\t\tr.conn = nil\n\t}\n}", "func (c *channel) close() {\n\tc.heartbeatLck.Lock()\n\t// nil heartbeatStop indicates that heartbeat is disabled\n\t// due to lost remote and channel is basically in\n\t// \"dangling\" state.\n\tif c.heartbeatInterval != 0 && c.heartbeatStop != nil {\n\t\tc.heartbeatStop <- struct{}{}\n\t\tc.heartbeatTicker.Stop()\n\t\t<-c.heartbeatStop\n\t}\n\n\tc.heartbeatLck.Unlock()\n\n\tc.stateLck.Lock()\n\tdefer c.stateLck.Unlock()\n\n\tc.stopping = true\n\n\tclose(c.queue)\n\tc.errorCh = nil\n}", "func (s *socket) close() error {\n\tfor _, c := range s.Channels {\n\t\tc.close()\n\t\ts.removeChannel(c)\n\t}\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tlog.Printf(\"ZeroRPC socket closed\")\n\treturn s.zmqSocket.Close()\n}", "func (r *Connection) Close() {\n\t// no-op\n}", "func (w *reply) Close() (err error) {\n\treturn w.conn.Close()\n}", "func (c *UDPClientProvider) close() error {\n\tc.quit <- true\n\tc.conn.Close()\n\treturn nil\n}", "func (c *MulticastController) Close() {\n\tc.jrConn.Close()\n\tc.queryFlooder.Close()\n}", "func (rc *RecognitionClient) Close() error {\n\treturn rc.conn.Close()\n}", "func (s *Server) CloseConnection() {}", "func (c *conn) Close() error {\n\tif atomic.CompareAndSwapInt32(&c.closed, 0, 1) {\n\t\tc.log(\"close connection\", c.url.Scheme, c.url.Host, c.url.Path)\n\t\tcancel := c.cancel\n\t\ttransport := c.transport\n\t\tc.transport = nil\n\t\tc.cancel = nil\n\n\t\tif cancel != nil {\n\t\t\tcancel()\n\t\t}\n\t\tif transport != nil {\n\t\t\ttransport.CloseIdleConnections()\n\t\t}\n\t}\n\treturn nil\n}", "func (self *SQL_Client) Close() {\n\tself.cc.Close()\n}" ]
[ "0.8092423", "0.7488273", "0.74117875", "0.7401336", "0.7297787", "0.72844076", "0.7258919", "0.7258919", "0.70475566", "0.70170844", "0.6994085", "0.68766195", "0.68766195", "0.68566006", "0.6801606", "0.67880464", "0.67727214", "0.6753569", "0.67466146", "0.67429197", "0.67075324", "0.6697052", "0.6694391", "0.6690074", "0.6688379", "0.6678317", "0.6672311", "0.666654", "0.6645878", "0.66402256", "0.6637389", "0.66261077", "0.662094", "0.6617695", "0.66137046", "0.66109514", "0.66074395", "0.66004974", "0.6597978", "0.6595577", "0.6581355", "0.6572331", "0.6568714", "0.6564743", "0.6561171", "0.65572", "0.65557015", "0.654935", "0.654855", "0.65475607", "0.65474117", "0.65281814", "0.65175986", "0.6517547", "0.6504884", "0.64995456", "0.6499403", "0.6489407", "0.6477494", "0.647181", "0.6471131", "0.6465213", "0.6462887", "0.6453746", "0.6444994", "0.6443679", "0.6440415", "0.6436135", "0.64326924", "0.6431869", "0.64286566", "0.64161545", "0.64106727", "0.64079803", "0.64070386", "0.6405031", "0.6403366", "0.6402103", "0.63923883", "0.6389957", "0.63886154", "0.63826436", "0.6380023", "0.63774574", "0.6372628", "0.6372628", "0.6372628", "0.6372628", "0.6372628", "0.6372628", "0.63721883", "0.63717675", "0.6368003", "0.6355773", "0.6354669", "0.63497204", "0.63428056", "0.6327377", "0.6321788", "0.632076", "0.63197255" ]
0.0
-1
Defang Takes an IOC and defangs it using the standard defangReplacements
func (ioc *IOC) Defang() *IOC { copy := *ioc ioc = &copy // Just do a string replace on each if replacements, ok := defangReplacements[ioc.Type]; ok { for _, fangPair := range replacements { ioc.IOC = strings.ReplaceAll(ioc.IOC, fangPair.fanged, fangPair.defanged) } } return ioc }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ioc *IOC) Fang() *IOC {\n\tcopy := *ioc\n\tioc = &copy\n\n\t// String replace all defangs in our standard set\n\tif replacements, ok := defangReplacements[ioc.Type]; ok {\n\t\tfor _, fangPair := range replacements {\n\t\t\tioc.IOC = strings.ReplaceAll(ioc.IOC, fangPair.defanged, fangPair.fanged)\n\t\t}\n\t}\n\n\t// Regex replace everything from the fang replacements\n\tif replacements, ok := fangReplacements[ioc.Type]; ok {\n\t\tfor _, regexReplacement := range replacements {\n\t\t\t// Offset is incase we shrink the string and need to offset locations\n\t\t\toffset := 0\n\n\t\t\t// Get indexes of replacements and replace them\n\t\t\ttoReplace := regexReplacement.pattern.FindAllStringIndex(ioc.IOC, -1)\n\t\t\tfor _, location := range toReplace {\n\t\t\t\t// Update this found string\n\t\t\t\tstartSize := len(ioc.IOC)\n\t\t\t\tioc.IOC = ioc.IOC[0:location[0]-offset] + regexReplacement.replace + ioc.IOC[location[1]-offset:len(ioc.IOC)]\n\t\t\t\t// Update offset with how much the string shrunk (or grew)\n\t\t\t\toffset += startSize - len(ioc.IOC)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ioc\n}", "func goConvInvoc(a ClientArg) string {\n\tjsonConvTmpl := `\nvar {{.GoArg}} {{.GoType}}\nif {{.FlagArg}} != nil && len(*{{.FlagArg}}) > 0 {\n\terr = json.Unmarshal([]byte(*{{.FlagArg}}), &{{.GoArg}})\n\tif err != nil {\n\t\tpanic(errors.Wrapf(err, \"unmarshalling {{.GoArg}} from %v:\", {{.FlagArg}}))\n\t}\n}\n`\n\tif a.Repeated || !a.IsBaseType {\n\t\tcode, err := applyTemplate(\"UnmarshalCliArgs\", jsonConvTmpl, a, nil)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Couldn't apply template: %v\", err))\n\t\t}\n\t\treturn code\n\t}\n\treturn fmt.Sprintf(`%s := %s`, a.GoArg, flagTypeConversion(a))\n}", "func Defun(opname string, funcBody Mapper, quoter Mapper, env *Environment) {\n\topsym := GlobalEnvironment.Intern(opname, false)\n\topsym.Value = Atomize(&internalOp{sym: opsym, caller: funcBody, quoter: quoter})\n\tT().Debugf(\"new interal op %s = %v\", opsym.Name, opsym.Value)\n}", "func render(template string, def definition, params map[string]interface{}) (string, error) {\n\tctx := plush.NewContext()\n\tctx.Set(\"camelize_down\", camelizeDown)\n\tctx.Set(\"def\", def)\n\tctx.Set(\"params\", params)\n\ts, err := plush.Render(string(template), ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn s, nil\n}", "func (h *Handler) sidecarInjection(del bool, version, ns string) error {\n\texe, err := h.getExecutable(version)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinjectCmd := \"add\"\n\tif del {\n\t\tinjectCmd = \"remove\"\n\t}\n\n\tcmd := &exec.Cmd{\n\t\tPath: exe,\n\t\tArgs: []string{\n\t\t\texe,\n\t\t\t\"namespace\",\n\t\t\tinjectCmd,\n\t\t\tns,\n\t\t},\n\t\tStdout: os.Stdout,\n\t\tStderr: os.Stdout,\n\t}\n\n\tif err := cmd.Run(); err != nil {\n\t\treturn ErrRunExecutable(err)\n\t}\n\n\treturn nil\n}", "func (e Environment) Overridef(name string, format string, a ...interface{}) {\n\te[fmt.Sprintf(\"%s.override\", name)] = fmt.Sprintf(format, a...)\n}", "func setupSubst(objType string, search string, replace string) {\n\tif !globalType[objType] {\n\t\tabort.Msg(\"Unknown type %s\", objType)\n\t}\n\taddSubst := func(objType, search, replace string) {\n\t\tsubMap, ok := subst[objType]\n\t\tif !ok {\n\t\t\tsubMap = make(map[string]string)\n\t\t\tsubst[objType] = subMap\n\t\t}\n\t\tsubMap[search] = replace\n\t}\n\n\taddSubst(objType, search, replace)\n\n\tfor _, other := range aliases[objType] {\n\t\taddSubst(other, search, replace)\n\t}\n}", "func doBind(sc *Collection, originalInvokeF *provider, originalInitF *provider, real bool) error {\n\t// Split up the collection into LITERAL, STATIC, RUN, and FINAL groups. Add\n\t// init and invoke as faked providers. Flatten into one ordered list.\n\tvar invokeIndex int\n\tvar invokeF *provider\n\tvar initF *provider\n\tvar debuggingProvider **provider\n\tfuncs := make([]*provider, 0, len(sc.contents)+3)\n\t{\n\t\tvar err error\n\t\tinvokeF, err = characterizeInitInvoke(originalInvokeF, charContext{inputsAreStatic: false})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif invokeF.flows == nil {\n\t\t\treturn fmt.Errorf(\"internal error #4: no flows for invoke\")\n\t\t}\n\t\tnonStaticTypes := make(map[typeCode]bool)\n\t\tfor _, tc := range invokeF.flows[outputParams] {\n\t\t\tnonStaticTypes[tc] = true\n\t\t}\n\n\t\tbeforeInvoke, afterInvoke, err := sc.characterizeAndFlatten(nonStaticTypes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Add debugging provider\n\t\t{\n\t\t\td := newProvider(func() *Debugging { return nil }, -1, \"Debugging\")\n\t\t\td.cacheable = true\n\t\t\td.mustCache = true\n\t\t\td, err = characterizeFunc(d, charContext{inputsAreStatic: true})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"internal error #29: problem with debugging injectors: %s\", err)\n\t\t\t}\n\t\t\td.isSynthetic = true\n\t\t\tdebuggingProvider = &d\n\t\t\tfuncs = append(funcs, d)\n\t\t}\n\n\t\t// Add init\n\t\tif originalInitF != nil {\n\t\t\tinitF, err = characterizeInitInvoke(originalInitF, charContext{inputsAreStatic: true})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif initF.flows == nil {\n\t\t\t\treturn fmt.Errorf(\"internal error #5: no flows for initF\")\n\t\t\t}\n\t\t\tfuncs = append(funcs, initF)\n\t\t}\n\n\t\tfuncs = append(funcs, beforeInvoke...)\n\t\tinvokeIndex = len(funcs)\n\t\tfuncs = append(funcs, invokeF)\n\t\tfuncs = append(funcs, afterInvoke...)\n\n\t\tfor i, fm := range funcs {\n\t\t\tfm.chainPosition = i\n\t\t\tif fm.required {\n\t\t\t\tfm.include = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// Figure out which providers must be included in the final chain. To do this,\n\t// first we figure out where each provider will get its inputs from when going\n\t// down the chain and where its inputs can be consumed when going up the chain.\n\t// Each of these linkages will be recorded as a dependency. Any dependency that\n\t// cannot be met will result in that provider being marked as impossible to\n\t// include.\n\t//\n\t// After all the dependencies are mapped, then we mark which providers will be\n\t// included in the final chain.\n\t//\n\t// The parameter list for the init function is complicated: both the inputs\n\t// and outputs are associated with downVmap, but they happen at different times:\n\t// some of the bookkeeping related to init happens in sequence with its position\n\t// in the function list, and some of it happens just before handling the invoke\n\t// function.\n\t//\n\t//\n\t// When that is finished, we can compute the upVmap and the downVmap.\n\n\t// Compute dependencies: set fm.downRmap, fm.upRmap, fm.cannotInclude,\n\t// fm.whyIncluded, fm.include\n\terr := computeDependenciesAndInclusion(funcs, initF)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Build the lists of parameters that are included in the value collections.\n\t// These are maps from types to position in the value collection.\n\t//\n\t// Also: calculate bypass zero for static chain. If there is a fallible injector\n\t// in the static chain, then part of the static chain my not run. Fallible\n\t// injectors need to know know which types need to be zeroed if the remaining\n\t// static injectors are skipped.\n\t//\n\t// Also: calculate the skipped-inner() zero for the run chain. If a wrapper\n\t// does not call the remainder of the chain, then the values returned by the remainder\n\t// of the chain must be zero'ed.\n\tdownVmap := make(map[typeCode]int)\n\tdownCount := 0\n\tupVmap := make(map[typeCode]int)\n\tupCount := 0\n\tfor _, fm := range funcs {\n\t\tif !fm.include {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, flow := range fm.flows {\n\t\t\tfor _, tc := range flow {\n\t\t\t\tupVmap[tc] = -1\n\t\t\t\tdownVmap[tc] = -1\n\t\t\t}\n\t\t}\n\t}\n\t// calculate for the static set\n\tfor i := invokeIndex - 1; i >= 0; i-- {\n\t\tfm := funcs[i]\n\t\tfm.mustZeroIfRemainderSkipped = vmapMapped(downVmap)\n\t\taddToVmap(fm, outputParams, downVmap, fm.downRmap, &downCount)\n\t}\n\tif initF != nil {\n\t\tfor _, tc := range initF.flows[bypassParams] {\n\t\t\tif rm, found := initF.downRmap[tc]; found {\n\t\t\t\ttc = rm\n\t\t\t}\n\t\t\tif downVmap[tc] == -1 {\n\t\t\t\treturn fmt.Errorf(\"Type required by init func, %s, not provided by any static group injectors\", tc)\n\t\t\t}\n\t\t}\n\t}\n\t// calculate for the run set\n\tfor i := len(funcs) - 1; i >= invokeIndex; i-- {\n\t\tfm := funcs[i]\n\t\tfm.downVmapCount = downCount\n\t\taddToVmap(fm, inputParams, downVmap, fm.downRmap, &downCount)\n\t\tfm.upVmapCount = upCount\n\t\taddToVmap(fm, returnParams, upVmap, fm.upRmap, &upCount)\n\t\tfm.mustZeroIfInnerNotCalled = vmapMapped(upVmap)\n\t}\n\n\t// Fill in debugging (if used)\n\tif (*debuggingProvider).include {\n\t\t(*debuggingProvider).fn = func() *Debugging {\n\t\t\tincluded := make([]string, 0, len(funcs)+3)\n\t\t\tfor _, fm := range funcs {\n\t\t\t\tif fm.include {\n\t\t\t\t\tincluded = append(included, fmt.Sprintf(\"%s %s\", fm.group, fm))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnamesIncluded := make([]string, 0, len(funcs)+3)\n\t\t\tfor _, fm := range funcs {\n\t\t\t\tif fm.include {\n\t\t\t\t\tif fm.index >= 0 {\n\t\t\t\t\t\tnamesIncluded = append(namesIncluded, fmt.Sprintf(\"%s(%d)\", fm.origin, fm.index))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnamesIncluded = append(namesIncluded, fm.origin)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tincludeExclude := make([]string, 0, len(funcs)+3)\n\t\t\tfor _, fm := range funcs {\n\t\t\t\tif fm.include {\n\t\t\t\t\tincludeExclude = append(includeExclude, fmt.Sprintf(\"INCLUDED: %s %s BECAUSE %s\", fm.group, fm, fm.whyIncluded))\n\t\t\t\t} else {\n\t\t\t\t\tincludeExclude = append(includeExclude, fmt.Sprintf(\"EXCLUDED: %s %s BECAUSE %s\", fm.group, fm, fm.cannotInclude))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar trace string\n\t\t\tif debugEnabled() {\n\t\t\t\ttrace = \"debugging already in progress\"\n\t\t\t} else {\n\t\t\t\ttrace = captureDoBindDebugging(sc, originalInvokeF, originalInitF)\n\t\t\t}\n\n\t\t\treproduce := generateReproduce(funcs, invokeF, initF)\n\n\t\t\treturn &Debugging{\n\t\t\t\tIncluded: included,\n\t\t\t\tNamesIncluded: namesIncluded,\n\t\t\t\tIncludeExclude: includeExclude,\n\t\t\t\tTrace: trace,\n\t\t\t\tReproduce: reproduce,\n\t\t\t}\n\t\t}\n\t}\n\tif debugEnabled() {\n\t\tfor _, fm := range funcs {\n\t\t\tdumpF(\"funclist\", fm)\n\t\t}\n\t}\n\n\t// Generate wrappers and split the handlers into groups (static, middleware, final)\n\tcollections := make(map[groupType][]*provider)\n\tfor _, fm := range funcs {\n\t\tif !fm.include {\n\t\t\tcontinue\n\t\t}\n\t\terr := generateWrappers(fm, downVmap, upVmap, upCount)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcollections[fm.group] = append(collections[fm.group], fm)\n\t}\n\tif len(collections[finalGroup]) != 1 {\n\t\treturn fmt.Errorf(\"internal error #1: no final func provided\")\n\t}\n\n\t// Over the course of the following loop, f will be redefined\n\t// over and over so that at the end of the loop it will be a\n\t// function that executes the entire RUN chain.\n\tf := collections[finalGroup][0].wrapEndpoint\n\tfor i := len(collections[runGroup]) - 1; i >= 0; i-- {\n\t\tn := collections[runGroup][i]\n\n\t\tswitch n.class {\n\t\tcase wrapperFunc:\n\t\t\tinner := f\n\t\t\tw := n.wrapWrapper\n\t\t\tf = func(v valueCollection) valueCollection {\n\t\t\t\treturn w(v, inner)\n\t\t\t}\n\t\tcase injectorFunc, fallibleInjectorFunc:\n\t\t\tj := i - 1\n\t\tInjectors:\n\t\t\tfor j >= 0 {\n\t\t\t\tswitch collections[runGroup][j].class {\n\t\t\t\tdefault:\n\t\t\t\t\tbreak Injectors\n\t\t\t\tcase injectorFunc, fallibleInjectorFunc: //okay\n\t\t\t\t}\n\t\t\t\tj--\n\t\t\t}\n\t\t\tj++\n\t\t\tnext := f\n\t\t\tinjectors := make([]func(valueCollection) (bool, valueCollection), 0, i-j+1)\n\t\t\tfor k := j; k <= i; k++ {\n\t\t\t\tinjectors = append(injectors, collections[runGroup][k].wrapFallibleInjector)\n\t\t\t}\n\t\t\tf = func(v valueCollection) valueCollection {\n\t\t\t\tfor _, injector := range injectors {\n\t\t\t\t\terrored, upV := injector(v)\n\t\t\t\t\tif errored {\n\t\t\t\t\t\treturn upV\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn next(v)\n\t\t\t}\n\t\t\ti = j\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"internal error #2: should not be here: %s\", n.class)\n\t\t}\n\t}\n\n\t// Initialize the value collection. When invoke is called the baseValues\n\t// collection will be copied.\n\tbaseValues := make(valueCollection, downCount)\n\tfor _, lit := range collections[literalGroup] {\n\t\ti := downVmap[lit.flows[outputParams][0]]\n\t\tif i >= 0 {\n\t\t\tbaseValues[i] = reflect.ValueOf(lit.fn)\n\t\t}\n\t}\n\n\t// Generate static chain function\n\trunStaticChain := func() error {\n\t\tdebugf(\"STATIC CHAIN LENGTH: %d\", len(collections[staticGroup]))\n\t\tfor _, inj := range collections[staticGroup] {\n\t\t\tdebugf(\"STATIC CHAIN CALLING %s\", inj)\n\n\t\t\terr := inj.wrapStaticInjector(baseValues)\n\t\t\tif err != nil {\n\t\t\t\tdebugf(\"STATIC CHAIN RETURNING EARLY DUE TO ERROR %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tfor _, inj := range collections[staticGroup] {\n\t\tif inj.wrapStaticInjector == nil {\n\t\t\treturn inj.errorf(\"internal error #3: missing static injector wrapping\")\n\t\t}\n\t}\n\n\t// Generate and bind init func.\n\tinitFunc := func() {}\n\tvar initOnce sync.Once\n\tif initF != nil {\n\t\toutMap, err := generateOutputMapper(initF, 0, outputParams, downVmap, \"init inputs\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinMap, err := generateInputMapper(initF, 0, bypassParams, initF.bypassRmap, downVmap, \"init results\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdebugln(\"SET INIT FUNC\")\n\t\tif real {\n\t\t\treflect.ValueOf(initF.fn).Elem().Set(\n\t\t\t\treflect.MakeFunc(reflect.ValueOf(initF.fn).Type().Elem(),\n\t\t\t\t\tfunc(inputs []reflect.Value) []reflect.Value {\n\t\t\t\t\t\tdebugln(\"INSIDE INIT\")\n\t\t\t\t\t\t// if initDone panic, return error, or ignore?\n\t\t\t\t\t\tinitOnce.Do(func() {\n\t\t\t\t\t\t\toutMap(baseValues, inputs)\n\t\t\t\t\t\t\tdebugln(\"RUN STATIC CHAIN\")\n\t\t\t\t\t\t\t_ = runStaticChain()\n\t\t\t\t\t\t})\n\t\t\t\t\t\tdumpValueArray(baseValues, \"base values before init return\", downVmap)\n\t\t\t\t\t\tout := inMap(baseValues)\n\t\t\t\t\t\tdebugln(\"DONE INIT\")\n\t\t\t\t\t\tdumpValueArray(out, \"init return\", nil)\n\t\t\t\t\t\tdumpF(\"init\", initF)\n\n\t\t\t\t\t\treturn out\n\t\t\t\t\t}))\n\t\t}\n\t\tdebugln(\"SET INIT FUNC - DONE\")\n\n\t} else {\n\t\tinitFunc = func() {\n\t\t\tinitOnce.Do(func() {\n\t\t\t\t_ = runStaticChain()\n\t\t\t})\n\t\t}\n\t}\n\n\t// Generate and bind invoke func\n\t{\n\t\toutMap, err := generateOutputMapper(invokeF, 0, outputParams, downVmap, \"invoke inputs\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinMap, err := generateInputMapper(invokeF, 0, returnedParams, invokeF.upRmap, upVmap, \"invoke results\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdebugln(\"SET INVOKE FUNC\")\n\t\tif real {\n\t\t\treflect.ValueOf(invokeF.fn).Elem().Set(\n\t\t\t\treflect.MakeFunc(reflect.ValueOf(invokeF.fn).Type().Elem(),\n\t\t\t\t\tfunc(inputs []reflect.Value) []reflect.Value {\n\t\t\t\t\t\tinitFunc()\n\t\t\t\t\t\tvalues := baseValues.Copy()\n\t\t\t\t\t\tdumpValueArray(values, \"invoke - before input copy\", downVmap)\n\t\t\t\t\t\toutMap(values, inputs)\n\t\t\t\t\t\tdumpValueArray(values, \"invoke - after input copy\", downVmap)\n\t\t\t\t\t\tret := f(values)\n\t\t\t\t\t\treturn inMap(ret)\n\t\t\t\t\t}))\n\t\t}\n\t\tdebugln(\"SET INVOKE FUNC - DONE\")\n\t}\n\n\treturn nil\n}", "func istioUninject(args []string, opts *options.Options) error {\n\tglooNS := opts.Metadata.Namespace\n\n\tclient := helpers.MustKubeClient()\n\t_, err := client.CoreV1().Namespaces().Get(opts.Top.Ctx, glooNS, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Remove gateway_proxy_sds cluster from the gateway-proxy configmap\n\tconfigMaps, err := client.CoreV1().ConfigMaps(glooNS).List(opts.Top.Ctx, metav1.ListOptions{})\n\tfor _, configMap := range configMaps.Items {\n\t\tif configMap.Name == gatewayProxyConfigMap {\n\t\t\t// Make sure we don't already have the gateway_proxy_sds cluster set up\n\t\t\terr := removeSdsCluster(&configMap)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = client.CoreV1().ConfigMaps(glooNS).Update(opts.Top.Ctx, &configMap, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tdeployments, err := client.AppsV1().Deployments(glooNS).List(opts.Top.Ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, deployment := range deployments.Items {\n\t\tif deployment.Name == \"gateway-proxy\" {\n\t\t\tcontainers := deployment.Spec.Template.Spec.Containers\n\n\t\t\t// Remove Sidecars\n\t\t\tsdsPresent := false\n\t\t\tistioPresent := false\n\t\t\tif len(containers) > 1 {\n\t\t\t\tfor i := len(containers) - 1; i >= 0; i-- {\n\t\t\t\t\tcontainer := containers[i]\n\t\t\t\t\tif container.Name == \"sds\" {\n\t\t\t\t\t\tsdsPresent = true\n\t\t\t\t\t\tcopy(containers[i:], containers[i+1:])\n\t\t\t\t\t\tcontainers = containers[:len(containers)-1]\n\t\t\t\t\t}\n\t\t\t\t\tif container.Name == \"istio-proxy\" {\n\t\t\t\t\t\tistioPresent = true\n\n\t\t\t\t\t\tcopy(containers[i:], containers[i+1:])\n\t\t\t\t\t\tcontainers = containers[:len(containers)-1]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !sdsPresent || !istioPresent {\n\t\t\t\treturn ErrMissingSidecars\n\t\t\t}\n\n\t\t\tdeployment.Spec.Template.Spec.Containers = containers\n\n\t\t\tremoveIstioVolumes(&deployment)\n\t\t\t_, err = client.AppsV1().Deployments(glooNS).Update(opts.Top.Ctx, &deployment, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn nil\n}", "func revertInitialisms(s string) string {\n\tfor i := 0; i < len(commonInitialisms); i++ {\n\t\ts = strings.ReplaceAll(s, commonInitialisms[i][0], commonInitialisms[i][1])\n\t}\n\treturn s\n}", "func preprocessString(alias *Alias, str string) (string, error) {\n\t// Load Remote/Local alias definitions\n\tif externalDefinitionErr := alias.loadExternalAlias(); externalDefinitionErr != nil {\n\t\treturn \"\", externalDefinitionErr\n\t}\n\n\talias.loadGlobalAlias()\n\n\t// Validate alias definitions\n\tif improperFormatErr := alias.resolveMapAndValidate(); improperFormatErr != nil {\n\t\treturn \"\", improperFormatErr\n\t}\n\n\tvar out strings.Builder\n\tvar command strings.Builder\n\tongoingCmd := false\n\n\t// Search and replace all strings with the directive\n\t// (sam) we add a placeholder space at the end of the string below\n\t// to force the state machine to END. We remove it before returning\n\t// the result to user\n\tfor _, char := range str + \" \" {\n\t\tif ongoingCmd {\n\t\t\tif char == alias.directive && command.Len() == 0 { // Escape Character Triggered\n\t\t\t\tout.WriteRune(alias.directive)\n\t\t\t\tongoingCmd = false\n\t\t\t} else if !isAlphanumeric(char) { // Delineates the end of an alias\n\t\t\t\tresolvedCommand, commandPresent := alias.AliasMap[command.String()]\n\t\t\t\t// If command is not found we assume this to be the expect item itself.\n\t\t\t\tif !commandPresent {\n\t\t\t\t\tout.WriteString(string(alias.directive) + command.String() + string(char))\n\t\t\t\t\tongoingCmd = false\n\t\t\t\t\tcommand.Reset()\n\t\t\t\t} else {\n\t\t\t\t\tout.WriteString(resolvedCommand)\n\t\t\t\t\tif char != alias.directive {\n\t\t\t\t\t\tongoingCmd = false\n\t\t\t\t\t\tout.WriteRune(char)\n\t\t\t\t\t}\n\t\t\t\t\tcommand.Reset()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcommand.WriteRune(char)\n\t\t\t}\n\t\t} else if char == alias.directive {\n\t\t\tongoingCmd = true\n\t\t} else {\n\t\t\tout.WriteRune(char)\n\t\t}\n\t}\n\n\treturn strings.TrimSuffix(out.String(), \" \"), nil\n}", "func newServiceNameReplacer() *strings.Replacer {\n\tvar mapping [256]byte\n\t// we start with everything being replaces with underscore, and later fix some safe characters\n\tfor i := range mapping {\n\t\tmapping[i] = '_'\n\t}\n\t// digits are safe\n\tfor i := '0'; i <= '9'; i++ {\n\t\tmapping[i] = byte(i)\n\t}\n\t// lower case letters are safe\n\tfor i := 'a'; i <= 'z'; i++ {\n\t\tmapping[i] = byte(i)\n\t}\n\t// upper case letters are safe, but convert them to lower case\n\tfor i := 'A'; i <= 'Z'; i++ {\n\t\tmapping[i] = byte(i - 'A' + 'a')\n\t}\n\t// dash and dot are safe\n\tmapping['-'] = '-'\n\tmapping['.'] = '.'\n\n\t// prepare array of pairs of bad/good characters\n\toldnew := make([]string, 0, 2*(256-2-10-int('z'-'a'+1)))\n\tfor i := range mapping {\n\t\tif mapping[i] != byte(i) {\n\t\t\toldnew = append(oldnew, string(rune(i)), string(rune(mapping[i])))\n\t\t}\n\t}\n\n\treturn strings.NewReplacer(oldnew...)\n}", "func Auto(c *rux.Context, i interface{}) {\n\n}", "func replaceImports(content string, imports []string) string {\n\t// make sure that deeper imports will be replaced first\n\t// it is required for correct processing of nested packages\n\tsort.Sort(sort.Reverse(sort.StringSlice(imports)))\n\tfor i, imp := range imports {\n\t\tcontent = strings.Replace(content, imp, genPackageAlias(i), -1)\n\t}\n\treturn content\n}", "func substitution(answer string) string {\n\treflections := map[string]string{\n\t\t\"am\": \"are\",\n\t\t\"was\": \"were\",\n\t\t\"i\": \"you\",\n\t\t\"i'd\": \"you would\",\n\t\t\"i've\": \"you have\",\n\t\t\"i'll\": \"you will\",\n\t\t\"my\": \"your\",\n\t\t\"are\": \"am\",\n\t\t\"you've\": \"I have\",\n\t\t\"you'll\": \"I will\",\n\t\t\"your\": \"my\",\n\t\t\"yours\": \"mine\",\n\t\t\"you\": \"me\",\n\t\t\"me\": \"you\",\n\t\t\"myself\": \"yourself\",\n\t\t\"yourself\": \"myself\",\n\t\t\"i'm\": \"you are\",\n\t}\n\n\twords := strings.Split(answer, \" \") // get slices of the words\n\n\tfor i, word := range words {\t// loop through whole sentence\n\t\tif val, ok := reflections[word]; ok {\t// check for the word in reflection\n\t\t\twords[i] = val // substitite the value\n\t\t}//if\n\t}//for\n\n\t// Return substituted string\n\treturn strings.Join(words, \" \") // join back into sentence\n}", "func AddComponent(parent *ast.File, compo *adl.Struct) (component *ast.Struct, _ error) {\n\trequiresInitStub := false\n\tfor _, method := range compo.Methods {\n\t\tif method.StubDefault {\n\t\t\trequiresInitStub = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif len(compo.Inject) > 0 {\n\t\trequiresInitStub = true\n\t}\n\n\tcomponent = ast.NewStruct(compo.Name.String()).SetComment(compo.Comment.String() + \"\\n\\nThe stereotype of this type is '\" + compo.Stereotype.String() + \"'.\")\n\tparent.AddTypes(component)\n\n\tif requiresInitStub {\n\t\tshortName := strings.ToLower(compo.Name.String()[0:1])\n\t\tc := ast.NewFunc(\"New\"+golang.MakePublic(compo.Name.String())).SetComment(\"...allocates and initializes a new \"+compo.Name.String()+\" instance.\").\n\t\t\tAddResults(\n\t\t\t\tast.NewParam(\"\", ast.NewTypeDeclPtr(ast.NewSimpleTypeDecl(ast.Name(parent.Pkg().Path+\".\"+compo.Name.String())))),\n\t\t\t\tast.NewParam(\"\", ast.NewSimpleTypeDecl(stdlib.Error)),\n\t\t\t)\n\n\t\tinjectFieldAssigns := \"\"\n\t\tfor _, injection := range compo.Inject {\n\t\t\tp := ast.NewParam(injection.Name.String(), astutil.MakeTypeDecl(injection.Type))\n\t\t\tif injection.Comment.String() != \"\" {\n\t\t\t\tp.SetComment(injection.Comment.String())\n\t\t\t}\n\n\t\t\tc.AddParams(p)\n\t\t\tinjectFieldAssigns += shortName + \".\" + MakePrivate(injection.Name.String()) + \"=\" + injection.Name.String() + \"\\n\"\n\t\t}\n\n\t\tc.SetBody(ast.NewBlock(ast.NewTpl(shortName + \" := &\" + compo.Name.String() + \"{}\\n\" + injectFieldAssigns + \"\\nif err := \" + shortName + \".init(); err != nil {\\nreturn nil, {{.Use \\\"fmt.Errorf\\\"}}(\\\"cannot initialize '\" + compo.Name.String() + \"': %w\\\",err)}\\n\\n return \" + shortName + \",nil\\n\")))\n\n\t\tcomponent.AddFactoryRefs(c)\n\t\tparent.AddNodes(c)\n\t}\n\n\tif requiresInitStub {\n\t\tdefaultComponent := ast.NewStruct(golang.MakePrivate(\"Default\" + compo.Name.String())).\n\t\t\tSetComment(\"...is an implementation stub for \" + compo.Name.String() + \".\\nThe sole purpose of this type is to mock the method contract and each method should be shadowed\\nby a concrete implementation.\").\n\t\t\tSetVisibility(ast.Private)\n\n\t\tdefaultComponent.AddMethods(ast.NewFunc(\"init\").\n\t\t\tAddResults(ast.NewParam(\"\", ast.NewSimpleTypeDecl(stdlib.Error))).\n\t\t\tSetVisibility(ast.Private).\n\t\t\tSetComment(\"...is invoked from the constructor/factory function to setup any pre-variants.\\nShadow this method as required.\").\n\t\t\tSetBody(ast.NewBlock(ast.NewReturnStmt(ast.NewIdentLit(\"nil\")))))\n\n\t\tcomponent.AddEmbedded(ast.NewSimpleTypeDecl(ast.Name(defaultComponent.TypeName)))\n\n\t\tfor _, method := range compo.Methods {\n\t\t\taMethod := ast.NewFunc(method.Name.String()).SetComment(method.Comment.String() + \"\\nShadow this method as required.\")\n\t\t\tfor _, param := range method.In {\n\t\t\t\taMethod.AddParams(ast.NewParam(param.Name.String(), astutil.MakeTypeDecl(param.Type)).SetComment(param.Comment.String()))\n\t\t\t}\n\n\t\t\tfor _, param := range method.Out {\n\t\t\t\taMethod.AddResults(ast.NewParam(param.Name.String(), astutil.MakeTypeDecl(param.Type)).SetComment(param.Comment.String()))\n\t\t\t}\n\n\t\t\taMethod.SetBody(ast.NewBlock(ast.NewTpl(`panic(\"not yet implemented\")`)))\n\t\t\tdefaultComponent.AddMethods(aMethod)\n\n\t\t}\n\n\t\tparent.AddTypes(defaultComponent)\n\t}\n\n\tfor _, decl := range compo.Inject {\n\t\tf := ast.NewField(MakePrivate(decl.Name.String()),\n\t\t\tastutil.MakeTypeDecl(decl.Type)).\n\t\t\tSetComment(decl.Comment.String()).\n\t\t\tSetVisibility(ast.Private)\n\n\t\tif decl.Comment.String() == \"\" {\n\t\t\tswitch decl.Stereotype.String() {\n\t\t\tcase adl.Cfg:\n\t\t\t\tf.SetComment(\"...is the components configuration and injected at construction time.\")\n\t\t\tdefault:\n\t\t\t\tif decl.Stereotype.String() != \"\" {\n\t\t\t\t\tf.SetComment(\"...is the components '\" + decl.Stereotype.String() + \"' and injected at construction time.\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcomponent.AddFields(f)\n\t}\n\n\tfor _, field := range compo.Fields {\n\t\tf := ast.NewField(field.Name.String(), astutil.MakeTypeDecl(field.Type)).SetComment(field.Comment.String())\n\t\tif field.Private {\n\t\t\tf.SetVisibility(ast.Private)\n\t\t}\n\n\t\tif field.CfgCmdLineFlag {\n\t\t\tstereotype.FieldFrom(f).SetProgramFlag(true)\n\t\t}\n\n\t\tcomponent.AddFields(f)\n\t}\n\n\tswitch compo.Stereotype.String() {\n\tcase adl.Cfg:\n\t\tstereotype.StructFrom(component).\n\t\t\tSetIsConfiguration(true)\n\t}\n\n\treturn component, nil\n}", "func (b *Baa) SetDI(name string, h interface{}) {\n\tswitch name {\n\tcase \"logger\":\n\t\tif _, ok := h.(Logger); !ok {\n\t\t\tpanic(\"DI logger must be implement interface baa.Logger\")\n\t\t}\n\tcase \"render\":\n\t\tif _, ok := h.(Renderer); !ok {\n\t\t\tpanic(\"DI render must be implement interface baa.Renderer\")\n\t\t}\n\tcase \"router\":\n\t\tif _, ok := h.(Router); !ok {\n\t\t\tpanic(\"DI router must be implement interface baa.Router\")\n\t\t}\n\t}\n\tb.di.Set(name, h)\n}", "func IFaceAnnotationGenerator(toDir string, an ast.AnnotationDeclaration, itr ast.InterfaceDeclaration, pkgDeclr ast.PackageDeclaration, pkg ast.Package) ([]gen.WriteDirective, error) {\n\tinterfaceName := itr.Object.Name.Name\n\tinterfaceNameLower := strings.ToLower(interfaceName)\n\n\tmethods := itr.Methods(&pkgDeclr)\n\n\timports := make(map[string]string, 0)\n\n\tfor _, method := range methods {\n\t\t// Retrieve all import paths for arguments.\n\t\tfunc(args []ast.ArgType) {\n\t\t\tfor _, argument := range args {\n\t\t\t\tif argument.Import2.Path != \"\" {\n\t\t\t\t\timports[argument.Import2.Path] = argument.Import2.Name\n\t\t\t\t}\n\t\t\t\tif argument.Import.Path != \"\" {\n\t\t\t\t\timports[argument.Import.Path] = argument.Import.Name\n\t\t\t\t}\n\t\t\t}\n\t\t}(method.Args)\n\n\t\t// Retrieve all import paths for returns.\n\t\tfunc(args []ast.ArgType) {\n\t\t\tfor _, argument := range args {\n\t\t\t\tif argument.Import2.Path != \"\" {\n\t\t\t\t\timports[argument.Import2.Path] = argument.Import2.Name\n\t\t\t\t}\n\t\t\t\tif argument.Import.Path != \"\" {\n\t\t\t\t\timports[argument.Import.Path] = argument.Import.Name\n\t\t\t\t}\n\t\t\t}\n\t\t}(method.Returns)\n\t}\n\n\tvar wantedImports []gen.ImportItemDeclr\n\n\tfor path, name := range imports {\n\t\twantedImports = append(wantedImports, gen.Import(path, name))\n\t}\n\n\timplGen := gen.Block(\n\t\tgen.Package(\n\t\t\tgen.Name(ast.WhichPackage(toDir, pkg)),\n\t\t\tgen.Imports(wantedImports...),\n\t\t\tgen.Block(\n\t\t\t\tgen.SourceText(\n\t\t\t\t\tstring(templates.Must(\"iface/iface.tml\")),\n\t\t\t\t\tstruct {\n\t\t\t\t\t\tInterfaceName string\n\t\t\t\t\t\tPackage ast.Package\n\t\t\t\t\t\tMethods []ast.FunctionDefinition\n\t\t\t\t\t}{\n\t\t\t\t\t\tPackage: pkg,\n\t\t\t\t\t\tMethods: methods,\n\t\t\t\t\t\tInterfaceName: interfaceName,\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t)\n\n\tvar directives []gen.WriteDirective\n\n\timpImports := append([]gen.ImportItemDeclr{\n\t\tgen.Import(\"time\", \"\"),\n\t\tgen.Import(\"runtime\", \"\"),\n\t\tgen.Import(pkg.Path, \"\"),\n\t}, wantedImports...)\n\n\tdirectives = append(directives, gen.WriteDirective{\n\t\tWriter: fmtwriter.New(implGen, true, true),\n\t\tFileName: fmt.Sprintf(\"%s_impl.go\", interfaceNameLower),\n\t\tDontOverride: true,\n\t})\n\n\tif val, ok := an.Params[\"tests\"]; ok && val == \"true\" {\n\t\timplSnitchGen := gen.Block(\n\t\t\tgen.Package(\n\t\t\t\tgen.Name(\"snitch\"),\n\t\t\t\tgen.Imports(impImports...),\n\t\t\t\tgen.Block(\n\t\t\t\t\tgen.SourceText(\n\t\t\t\t\t\tstring(templates.Must(\"iface/iface-little-snitch.tml\")),\n\t\t\t\t\t\tstruct {\n\t\t\t\t\t\t\tPackage ast.Package\n\t\t\t\t\t\t\tInterfaceName string\n\t\t\t\t\t\t\tMethods []ast.FunctionDefinition\n\t\t\t\t\t\t}{\n\t\t\t\t\t\t\tPackage: pkg,\n\t\t\t\t\t\t\tInterfaceName: interfaceName,\n\t\t\t\t\t\t\tMethods: itr.Methods(&pkgDeclr),\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\n\t\tdirectives = append(directives, gen.WriteDirective{\n\t\t\tDir: \"snitch\",\n\t\t\tWriter: fmtwriter.New(implSnitchGen, true, true),\n\t\t\tFileName: fmt.Sprintf(\"%s_little_snitch.go\", interfaceNameLower),\n\t\t\tDontOverride: true,\n\t\t})\n\n\t\ttestImports := append([]gen.ImportItemDeclr{\n\t\t\tgen.Import(\"testing\", \"\"),\n\t\t\tgen.Import(pkg.Path, \"\"),\n\t\t\tgen.Import(\"github.com/influx6/faux/tests\", \"\"),\n\t\t\tgen.Import(filepath.Join(pkg.Path, toDir, \"snitch\"), \"\"),\n\t\t}, wantedImports...)\n\n\t\ttestGen := gen.Block(\n\t\t\tgen.Package(\n\t\t\t\tgen.Name(fmt.Sprintf(\"%s_test\", ast.WhichPackage(toDir, pkg))),\n\t\t\t\tgen.Imports(testImports...),\n\t\t\t\tgen.Block(\n\t\t\t\t\tgen.SourceText(\n\t\t\t\t\t\tstring(templates.Must(\"iface/iface-test.tml\")),\n\t\t\t\t\t\tstruct {\n\t\t\t\t\t\t\tInterfaceName string\n\t\t\t\t\t\t\tPackage ast.Package\n\t\t\t\t\t\t\tMethods []ast.FunctionDefinition\n\t\t\t\t\t\t}{\n\t\t\t\t\t\t\tPackage: pkg,\n\t\t\t\t\t\t\tInterfaceName: interfaceName,\n\t\t\t\t\t\t\tMethods: itr.Methods(&pkgDeclr),\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\n\t\tdirectives = append(directives, gen.WriteDirective{\n\t\t\tWriter: fmtwriter.New(testGen, true, true),\n\t\t\tFileName: fmt.Sprintf(\"%s_impl_test.go\", interfaceNameLower),\n\t\t\tDontOverride: true,\n\t\t})\n\t}\n\n\treturn directives, nil\n}", "func Replace(node Node, visitor func(Node) Node) {\n\tswitch n := node.(type) {\n\tcase *Abort:\n\tcase *API:\n\t\tfor i, c := range n.Enums {\n\t\t\tn.Enums[i] = visitor(c).(*Enum)\n\t\t}\n\t\tfor i, c := range n.Definitions {\n\t\t\tn.Definitions[i] = visitor(c).(*Definition)\n\t\t}\n\t\tfor i, c := range n.Classes {\n\t\t\tn.Classes[i] = visitor(c).(*Class)\n\t\t}\n\t\tfor i, c := range n.Pseudonyms {\n\t\t\tn.Pseudonyms[i] = visitor(c).(*Pseudonym)\n\t\t}\n\t\tfor i, c := range n.Externs {\n\t\t\tn.Externs[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Subroutines {\n\t\t\tn.Subroutines[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Functions {\n\t\t\tn.Functions[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Methods {\n\t\t\tn.Methods[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Globals {\n\t\t\tn.Globals[i] = visitor(c).(*Global)\n\t\t}\n\t\tfor i, c := range n.StaticArrays {\n\t\t\tn.StaticArrays[i] = visitor(c).(*StaticArray)\n\t\t}\n\t\tfor i, c := range n.Maps {\n\t\t\tn.Maps[i] = visitor(c).(*Map)\n\t\t}\n\t\tfor i, c := range n.Pointers {\n\t\t\tn.Pointers[i] = visitor(c).(*Pointer)\n\t\t}\n\t\tfor i, c := range n.Slices {\n\t\t\tn.Slices[i] = visitor(c).(*Slice)\n\t\t}\n\t\tfor i, c := range n.References {\n\t\t\tn.References[i] = visitor(c).(*Reference)\n\t\t}\n\t\tfor i, c := range n.Signatures {\n\t\t\tn.Signatures[i] = visitor(c).(*Signature)\n\t\t}\n\tcase *ArrayAssign:\n\t\tn.To = visitor(n.To).(*ArrayIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *ArrayIndex:\n\t\tn.Array = visitor(n.Array).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *ArrayInitializer:\n\t\tn.Array = visitor(n.Array).(Type)\n\t\tfor i, c := range n.Values {\n\t\t\tn.Values[i] = visitor(c).(Expression)\n\t\t}\n\tcase *Slice:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *SliceIndex:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *SliceAssign:\n\t\tn.To = visitor(n.To).(*SliceIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *Assert:\n\t\tn.Condition = visitor(n.Condition).(Expression)\n\tcase *Assign:\n\t\tn.LHS = visitor(n.LHS).(Expression)\n\t\tn.RHS = visitor(n.RHS).(Expression)\n\tcase *Annotation:\n\t\tfor i, c := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(c).(Expression)\n\t\t}\n\tcase *Block:\n\t\tfor i, c := range n.Statements {\n\t\t\tn.Statements[i] = visitor(c).(Statement)\n\t\t}\n\tcase BoolValue:\n\tcase *BinaryOp:\n\t\tif n.LHS != nil {\n\t\t\tn.LHS = visitor(n.LHS).(Expression)\n\t\t}\n\t\tif n.RHS != nil {\n\t\t\tn.RHS = visitor(n.RHS).(Expression)\n\t\t}\n\tcase *BitTest:\n\t\tn.Bitfield = visitor(n.Bitfield).(Expression)\n\t\tn.Bits = visitor(n.Bits).(Expression)\n\tcase *UnaryOp:\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *Branch:\n\t\tn.Condition = visitor(n.Condition).(Expression)\n\t\tn.True = visitor(n.True).(*Block)\n\t\tif n.False != nil {\n\t\t\tn.False = visitor(n.False).(*Block)\n\t\t}\n\tcase *Builtin:\n\tcase *Reference:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *Call:\n\t\tn.Type = visitor(n.Type).(Type)\n\t\tn.Target = visitor(n.Target).(*Callable)\n\t\tfor i, a := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(a).(Expression)\n\t\t}\n\tcase *Callable:\n\t\tif n.Object != nil {\n\t\t\tn.Object = visitor(n.Object).(Expression)\n\t\t}\n\t\tn.Function = visitor(n.Function).(*Function)\n\tcase *Case:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, c := range n.Conditions {\n\t\t\tn.Conditions[i] = visitor(c).(Expression)\n\t\t}\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase *Cast:\n\t\tn.Object = visitor(n.Object).(Expression)\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Class:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, f := range n.Fields {\n\t\t\tn.Fields[i] = visitor(f).(*Field)\n\t\t}\n\t\tfor i, m := range n.Methods {\n\t\t\tn.Methods[i] = visitor(m).(*Function)\n\t\t}\n\tcase *ClassInitializer:\n\t\tfor i, f := range n.Fields {\n\t\t\tn.Fields[i] = visitor(f).(*FieldInitializer)\n\t\t}\n\tcase *Choice:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, c := range n.Conditions {\n\t\t\tn.Conditions[i] = visitor(c).(Expression)\n\t\t}\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *Definition:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *DefinitionUsage:\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\t\tn.Definition = visitor(n.Definition).(*Definition)\n\tcase *DeclareLocal:\n\t\tn.Local = visitor(n.Local).(*Local)\n\t\tif n.Local.Value != nil {\n\t\t\tn.Local.Value = visitor(n.Local.Value).(Expression)\n\t\t}\n\tcase Documentation:\n\tcase *Enum:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, e := range n.Entries {\n\t\t\tn.Entries[i] = visitor(e).(*EnumEntry)\n\t\t}\n\tcase *EnumEntry:\n\tcase *Fence:\n\t\tif n.Statement != nil {\n\t\t\tn.Statement = visitor(n.Statement).(Statement)\n\t\t}\n\tcase *Field:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Type = visitor(n.Type).(Type)\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(Expression)\n\t\t}\n\tcase *FieldInitializer:\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase Float32Value:\n\tcase Float64Value:\n\tcase *Function:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tif n.Return != nil {\n\t\t\tn.Return = visitor(n.Return).(*Parameter)\n\t\t}\n\t\tfor i, c := range n.FullParameters {\n\t\t\tn.FullParameters[i] = visitor(c).(*Parameter)\n\t\t}\n\t\tif n.Block != nil {\n\t\t\tn.Block = visitor(n.Block).(*Block)\n\t\t}\n\t\tn.Signature = visitor(n.Signature).(*Signature)\n\tcase *Global:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\tcase *StaticArray:\n\t\tn.ValueType = visitor(n.ValueType).(Type)\n\t\tn.SizeExpr = visitor(n.SizeExpr).(Expression)\n\tcase *Signature:\n\tcase Int8Value:\n\tcase Int16Value:\n\tcase Int32Value:\n\tcase Int64Value:\n\tcase *Iteration:\n\t\tn.Iterator = visitor(n.Iterator).(*Local)\n\t\tn.From = visitor(n.From).(Expression)\n\t\tn.To = visitor(n.To).(Expression)\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase *MapIteration:\n\t\tn.IndexIterator = visitor(n.IndexIterator).(*Local)\n\t\tn.KeyIterator = visitor(n.KeyIterator).(*Local)\n\t\tn.ValueIterator = visitor(n.ValueIterator).(*Local)\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase Invalid:\n\tcase *Length:\n\t\tn.Object = visitor(n.Object).(Expression)\n\tcase *Local:\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Map:\n\t\tn.KeyType = visitor(n.KeyType).(Type)\n\t\tn.ValueType = visitor(n.ValueType).(Type)\n\tcase *MapAssign:\n\t\tn.To = visitor(n.To).(*MapIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *MapContains:\n\t\tn.Key = visitor(n.Key).(Expression)\n\t\tn.Map = visitor(n.Map).(Expression)\n\tcase *MapIndex:\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *MapRemove:\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Key = visitor(n.Key).(Expression)\n\tcase *MapClear:\n\t\tn.Map = visitor(n.Map).(Expression)\n\tcase *Member:\n\t\tn.Object = visitor(n.Object).(Expression)\n\t\tn.Field = visitor(n.Field).(*Field)\n\tcase *MessageValue:\n\t\tfor i, a := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(a).(*FieldInitializer)\n\t\t}\n\tcase *New:\n\t\tn.Type = visitor(n.Type).(*Reference)\n\tcase *Parameter:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Pointer:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *Pseudonym:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.To = visitor(n.To).(Type)\n\t\tfor i, m := range n.Methods {\n\t\t\tn.Methods[i] = visitor(m).(*Function)\n\t\t}\n\tcase *Return:\n\t\tif n.Value != nil {\n\t\t\tn.Value = visitor(n.Value).(Expression)\n\t\t}\n\tcase *Select:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tfor i, c := range n.Choices {\n\t\t\tn.Choices[i] = visitor(c).(*Choice)\n\t\t}\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(Expression)\n\t\t}\n\tcase StringValue:\n\tcase *Switch:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tfor i, c := range n.Cases {\n\t\t\tn.Cases[i] = visitor(c).(*Case)\n\t\t}\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(*Block)\n\t\t}\n\tcase Uint8Value:\n\tcase Uint16Value:\n\tcase Uint32Value:\n\tcase Uint64Value:\n\tcase *Unknown:\n\tcase *Clone:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *Copy:\n\t\tn.Src = visitor(n.Src).(Expression)\n\t\tn.Dst = visitor(n.Dst).(Expression)\n\tcase *Create:\n\t\tn.Type = visitor(n.Type).(*Reference)\n\t\tn.Initializer = visitor(n.Initializer).(*ClassInitializer)\n\tcase *Ignore:\n\tcase *Make:\n\t\tn.Type = visitor(n.Type).(*Slice)\n\t\tn.Size = visitor(n.Size).(Expression)\n\tcase Null:\n\tcase *PointerRange:\n\t\tn.Pointer = visitor(n.Pointer).(Expression)\n\t\tn.Range = visitor(n.Range).(*BinaryOp)\n\tcase *Read:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *SliceContains:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *SliceRange:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\t\tn.Range = visitor(n.Range).(*BinaryOp)\n\tcase *Write:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tdefault:\n\t\tpanic(fmt.Errorf(\"Unsupported semantic node type %T\", n))\n\t}\n}", "func nonResolvingHandler(name string, input interface{}, template interface{}) interface{} {\n\treturn nil\n}", "func IC(o ...interface{}) {\n\tif enableOutput {\n\t\tas, _ := toArgSlice(o, reflectsource.GetParentArgExprAllAsString())\n\t\toutputFunction(formatToString(as, enableSyntaxHighlighting))\n\t}\n}", "func (r *NuxeoReconciler) annotateDep(backingService v1alpha1.BackingService, dep *appsv1.Deployment) error {\n\tbuf := &bytes.Buffer{}\n\tenc := gob.NewEncoder(buf)\n\tif err := enc.Encode(backingService); err != nil {\n\t\treturn err\n\t}\n\tutil.AnnotateTemplate(dep, common.BackingSvcAnnotation+\".\"+backingService.Name, util.CRCBytes(buf.Bytes()))\n\treturn nil\n}", "func Infod(output string, d interface{}) {\n\tbuildAndShipMessage(output, \"INFO\", false, d)\n}", "func (d *DefaulterBuilder) ToInterfaceImplementation() *astmodel.InterfaceImplementation {\n\tgrp, ver := d.resourceName.PackageReference().GroupVersion()\n\n\t// e.g. grp = \"microsoft.network.azure.com\"\n\t// e.g. resource = \"backendaddresspools\"\n\t// e.g. ver = \"v1\"\n\n\tresource := d.resourceName.Name()\n\n\tgrp = strings.ToLower(grp + astmodel.GroupSuffix)\n\tnonPluralResource := strings.ToLower(resource)\n\tresource = strings.ToLower(d.resourceName.Plural().Name())\n\n\t// e.g. \"mutate-microsoft-network-azure-com-v1-backendaddresspool\"\n\t// note that this must match _exactly_ how controller-runtime generates the path\n\t// or it will not work!\n\tpath := fmt.Sprintf(\"/mutate-%s-%s-%s\", strings.ReplaceAll(grp, \".\", \"-\"), ver, nonPluralResource)\n\n\t// e.g. \"default.v123.backendaddresspool.azure.com\"\n\tname := fmt.Sprintf(\"default.%s.%s.%s\", ver, resource, grp)\n\n\tannotation := fmt.Sprintf(\n\t\t\"+kubebuilder:webhook:path=%s,mutating=true,sideEffects=None,\"+\n\t\t\t\"matchPolicy=Exact,failurePolicy=fail,groups=%s,resources=%s,\"+\n\t\t\t\"verbs=create;update,versions=%s,name=%s,admissionReviewVersions=v1\",\n\t\tpath,\n\t\tgrp,\n\t\tresource,\n\t\tver,\n\t\tname)\n\n\tfuncs := []astmodel.Function{\n\t\tNewResourceFunction(\n\t\t\t\"Default\",\n\t\t\td.resource,\n\t\t\td.idFactory,\n\t\t\td.defaultFunction,\n\t\t\tastmodel.NewPackageReferenceSet(astmodel.GenRuntimeReference)),\n\t\tNewResourceFunction(\n\t\t\t\"defaultImpl\",\n\t\t\td.resource,\n\t\t\td.idFactory,\n\t\t\td.localDefault,\n\t\t\tastmodel.NewPackageReferenceSet(astmodel.GenRuntimeReference)),\n\t}\n\n\t// Add the actual individual default functions\n\tfor _, def := range d.defaults {\n\t\tfuncs = append(funcs, def)\n\t}\n\n\treturn astmodel.NewInterfaceImplementation(\n\t\tastmodel.DefaulterInterfaceName,\n\t\tfuncs...).WithAnnotation(annotation)\n}", "func cgounimpl() {\n\tthrow(\"cgo not implemented\")\n}", "func init() {\n\timports.Packages[\"github.com/cosmos72/gomacro/typeutil\"] = imports.Package{\n\t\tBinds: map[string]r.Value{\n\t\t\t\"Identical\": r.ValueOf(Identical),\n\t\t\t\"IdenticalIgnoreTags\": r.ValueOf(IdenticalIgnoreTags),\n\t\t\t\"MakeHasher\": r.ValueOf(MakeHasher),\n\t\t},\n\t\tTypes: map[string]r.Type{\n\t\t\t\"Hasher\": r.TypeOf((*Hasher)(nil)).Elem(),\n\t\t\t\"Map\": r.TypeOf((*Map)(nil)).Elem(),\n\t\t},\n\t\tProxies: map[string]r.Type{}}\n}", "func DoReplacements(input string, mapping MappingFunc) interface{} {\n\tvar buf strings.Builder\n\tcheckpoint := 0\n\tfor cursor := 0; cursor < len(input); cursor++ {\n\t\tif input[cursor] == operator && cursor+1 < len(input) {\n\t\t\t// Copy the portion of the input string since the last\n\t\t\t// checkpoint into the buffer\n\t\t\tbuf.WriteString(input[checkpoint:cursor])\n\n\t\t\t// Attempt to read the variable name as defined by the\n\t\t\t// syntax from the input string\n\t\t\tread, isVar, advance := tryReadVariableName(input[cursor+1:])\n\n\t\t\tif isVar {\n\t\t\t\t// We were able to read a variable name correctly;\n\t\t\t\t// apply the mapping to the variable name and copy the\n\t\t\t\t// bytes into the buffer\n\t\t\t\tmapped := mapping(read)\n\t\t\t\tif input == syntaxWrap(read) {\n\t\t\t\t\t// Preserve the type of variable\n\t\t\t\t\treturn mapped\n\t\t\t\t}\n\n\t\t\t\t// Variable is used in a middle of a string\n\t\t\t\tbuf.WriteString(fmt.Sprintf(\"%v\", mapped))\n\t\t\t} else {\n\t\t\t\t// Not a variable name; copy the read bytes into the buffer\n\t\t\t\tbuf.WriteString(read)\n\t\t\t}\n\n\t\t\t// Advance the cursor in the input string to account for\n\t\t\t// bytes consumed to read the variable name expression\n\t\t\tcursor += advance\n\n\t\t\t// Advance the checkpoint in the input string\n\t\t\tcheckpoint = cursor + 1\n\t\t}\n\t}\n\n\t// Return the buffer and any remaining unwritten bytes in the\n\t// input string.\n\treturn buf.String() + input[checkpoint:]\n}", "func dialectMsgDefToGo(in string) string {\n\tre := regexp.MustCompile(\"_[a-z]\")\n\tin = strings.ToLower(in)\n\tin = re.ReplaceAllStringFunc(in, func(match string) string {\n\t\treturn strings.ToUpper(match[1:2])\n\t})\n\treturn strings.ToUpper(in[:1]) + in[1:]\n}", "func si(vm *VM, argument string) {\n\tsco := &Scope{\n\t\tprevious: vm.Scope,\n\t}\n\tvm.Scope = sco\n}", "func (*bzlLibraryLang) Fix(c *config.Config, f *rule.File) {}", "func MergeInjections(inja ...Injections) (ret Injections) {\n\tret = make(Injections)\n\tfor _, is := range inja {\n\t\tfor it, io := range is {\n\t\t\tret[it] = io\n\t\t}\n\t}\n\treturn\n}", "func (b Container) SetupGlobalInjection(i interface{}) {\n\tt := reflect.TypeOf(i)\n\tb.globalInjections[t] = i\n\tb.Bindings().AddInjection(i) // Add Injection for all existing bindings.\n}", "func convertInitialisms(s string) string {\n\tfor i := 0; i < len(commonInitialisms); i++ {\n\t\ts = strings.ReplaceAll(s, commonInitialisms[i][1], commonInitialisms[i][0])\n\t}\n\treturn s\n}", "func init() {\n\tPackages[\"encoding/gob\"] = Package{\n\tBinds: map[string]Value{\n\t\t\"NewDecoder\":\tValueOf(gob.NewDecoder),\n\t\t\"NewEncoder\":\tValueOf(gob.NewEncoder),\n\t\t\"Register\":\tValueOf(gob.Register),\n\t\t\"RegisterName\":\tValueOf(gob.RegisterName),\n\t}, Types: map[string]Type{\n\t\t\"CommonType\":\tTypeOf((*gob.CommonType)(nil)).Elem(),\n\t\t\"Decoder\":\tTypeOf((*gob.Decoder)(nil)).Elem(),\n\t\t\"Encoder\":\tTypeOf((*gob.Encoder)(nil)).Elem(),\n\t\t\"GobDecoder\":\tTypeOf((*gob.GobDecoder)(nil)).Elem(),\n\t\t\"GobEncoder\":\tTypeOf((*gob.GobEncoder)(nil)).Elem(),\n\t}, Proxies: map[string]Type{\n\t\t\"GobDecoder\":\tTypeOf((*P_encoding_gob_GobDecoder)(nil)).Elem(),\n\t\t\"GobEncoder\":\tTypeOf((*P_encoding_gob_GobEncoder)(nil)).Elem(),\n\t}, \n\t}\n}", "func (db Db) ServiceDefinitionToOsb(sd map[string]interface{}) osb.Service {\n\t// TODO: Marshal spec straight from the yaml in an osb.Plan, possibly using gjson\n\tglog.Infof(\"converting service definition %q \", sd[\"name\"].(string))\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tglog.Errorln(errors.Wrap(r, 2).ErrorStack())\n\t\t\tglog.Errorf(\"Failed to convert service definition for %q\", sd[\"name\"].(string))\n\t\t}\n\t}()\n\tf := false\n\tserviceid := uuid.NewV5(db.Accountuuid, sd[\"name\"].(string)).String()\n\toutp := osb.Service{}\n\toutp.ID = serviceid\n\toutp.Name = sd[\"name\"].(string)\n\toutp.Bindable = sd[\"bindable\"].(bool)\n\toutp.Description = sd[\"description\"].(string)\n\toutp.PlanUpdatable = &f\n\tmetadata := make(map[string]interface{})\n\tfor index, key := range sd[\"metadata\"].(map[interface{}]interface{}) {\n\t\tmetadata[index.(string)] = key\n\t}\n\toutp.Metadata = metadata\n\tvar tags []string\n\tfor _, key := range sd[\"tags\"].([]interface{}) {\n\t\ttags = append(tags, key.(string))\n\t}\n\toutp.Tags = tags\n\tvar plans []osb.Plan\n\tfor _, key := range sd[\"plans\"].([]interface{}) {\n\t\tplan := osb.Plan{}\n\t\tfor i, k := range key.(map[interface{}]interface{}) {\n\t\t\tif i.(string) == \"name\" {\n\t\t\t\tplan.Name = k.(string)\n\t\t\t} else if i.(string) == \"description\" {\n\t\t\t\tplan.Description = k.(string)\n\t\t\t} else if i.(string) == \"free\" {\n\t\t\t\tfree := k.(bool)\n\t\t\t\tplan.Free = &free\n\t\t\t} else if i.(string) == \"metadata\" {\n\t\t\t\tmetadata := make(map[string]interface{})\n\t\t\t\tfor i2, k2 := range k.(map[interface{}]interface{}) {\n\t\t\t\t\tmetadata[i2.(string)] = k2\n\t\t\t\t}\n\t\t\t\tplan.Metadata = metadata\n\t\t\t} else if i.(string) == \"parameters\" {\n\t\t\t\tpropsForCreate := make(map[string]interface{})\n\t\t\t\trequiredForCreate := make([]string, 0)\n\t\t\t\tpropsForUpdate := make(map[string]interface{})\n\t\t\t\trequiredForUpdate := make([]string, 0)\n\t\t\t\tfor _, param := range k.([]interface{}) {\n\t\t\t\t\tvar name string\n\t\t\t\t\tvar required, updatable bool\n\t\t\t\t\tpvals := make(map[string]interface{})\n\t\t\t\t\tfor pk, pv := range param.(map[interface{}]interface{}) {\n\t\t\t\t\t\tswitch pk {\n\t\t\t\t\t\tcase \"name\":\n\t\t\t\t\t\t\tname = pv.(string)\n\t\t\t\t\t\tcase \"required\":\n\t\t\t\t\t\t\trequired = pv.(bool)\n\t\t\t\t\t\tcase \"type\":\n\t\t\t\t\t\t\tswitch pv {\n\t\t\t\t\t\t\tcase \"enum\":\n\t\t\t\t\t\t\t\tpvals[pk.(string)] = \"string\"\n\t\t\t\t\t\t\tcase \"int\":\n\t\t\t\t\t\t\t\tpvals[pk.(string)] = \"integer\"\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tpvals[pk.(string)] = pv\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"updatable\":\n\t\t\t\t\t\t\tupdatable = pv.(bool)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tpvals[pk.(string)] = pv\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tpropsForCreate[name] = pvals\n\t\t\t\t\tif required {\n\t\t\t\t\t\trequiredForCreate = append(requiredForCreate, name)\n\t\t\t\t\t}\n\t\t\t\t\tif updatable {\n\t\t\t\t\t\tpropsForUpdate[name] = pvals\n\t\t\t\t\t\tif required {\n\t\t\t\t\t\t\trequiredForUpdate = append(requiredForUpdate, name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tplan.Schemas = &osb.Schemas{\n\t\t\t\t\tServiceInstance: &osb.ServiceInstanceSchema{\n\t\t\t\t\t\tCreate: &osb.InputParametersSchema{\n\t\t\t\t\t\t\tParameters: map[string]interface{}{\n\t\t\t\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\t\t\t\"properties\": propsForCreate,\n\t\t\t\t\t\t\t\t\"$schema\": \"http://json-schema.org/draft-06/schema#\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tif len(requiredForCreate) > 0 {\n\t\t\t\t\t// Cloud Foundry does not allow \"required\" to be an empty slice\n\t\t\t\t\tplan.Schemas.ServiceInstance.Create.Parameters.(map[string]interface{})[\"required\"] = requiredForCreate\n\t\t\t\t}\n\t\t\t\tif len(propsForUpdate) > 0 {\n\t\t\t\t\tplan.Schemas.ServiceInstance.Update = &osb.InputParametersSchema{\n\t\t\t\t\t\tParameters: map[string]interface{}{\n\t\t\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\t\t\"properties\": propsForUpdate,\n\t\t\t\t\t\t\t\"$schema\": \"http://json-schema.org/draft-06/schema#\",\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t\tif len(requiredForUpdate) > 0 {\n\t\t\t\t\t\t// Cloud Foundry does not allow \"required\" to be an empty slice\n\t\t\t\t\t\tplan.Schemas.ServiceInstance.Update.Parameters.(map[string]interface{})[\"required\"] = requiredForUpdate\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tplanid := uuid.NewV5(db.Accountuuid, \"service__\"+sd[\"name\"].(string)+\"__plan__\"+plan.Name).String()\n\t\tplan.ID = planid\n\t\tplans = append(plans, plan)\n\t}\n\toutp.Plans = plans\n\tglog.Infof(\"done converting service definition %q \", sd[\"name\"].(string))\n\treturn outp\n}", "func (self *Dependency) BindDep(controller Controller) {\n\tctrl := reflect.ValueOf(controller).Elem() //controllers are all pointer\n\tfor i := 0; i < ctrl.NumField(); i++ {\n\t\tf := ctrl.Field(i)\n\t\tif f.Kind() != reflect.Ptr || !f.IsNil() {\n\t\t\tcontinue\n\t\t}\n\t\tif p := self.GetDep(f.Type()); p != nil && f.CanInterface() {\n\t\t\tf.Set(reflect.New(f.Type().Elem()))\n\t\t\tf.Elem().Set(reflect.ValueOf(p).Elem())\n\t\t}\n\t}\n}", "func init() {\n\tPackages[\"fmt\"] = Package{\n\tBinds: map[string]Value{\n\t\t\"Errorf\":\tValueOf(fmt.Errorf),\n\t\t\"Fprint\":\tValueOf(fmt.Fprint),\n\t\t\"Fprintf\":\tValueOf(fmt.Fprintf),\n\t\t\"Fprintln\":\tValueOf(fmt.Fprintln),\n\t\t\"Fscan\":\tValueOf(fmt.Fscan),\n\t\t\"Fscanf\":\tValueOf(fmt.Fscanf),\n\t\t\"Fscanln\":\tValueOf(fmt.Fscanln),\n\t\t\"Print\":\tValueOf(fmt.Print),\n\t\t\"Printf\":\tValueOf(fmt.Printf),\n\t\t\"Println\":\tValueOf(fmt.Println),\n\t\t\"Scan\":\tValueOf(fmt.Scan),\n\t\t\"Scanf\":\tValueOf(fmt.Scanf),\n\t\t\"Scanln\":\tValueOf(fmt.Scanln),\n\t\t\"Sprint\":\tValueOf(fmt.Sprint),\n\t\t\"Sprintf\":\tValueOf(fmt.Sprintf),\n\t\t\"Sprintln\":\tValueOf(fmt.Sprintln),\n\t\t\"Sscan\":\tValueOf(fmt.Sscan),\n\t\t\"Sscanf\":\tValueOf(fmt.Sscanf),\n\t\t\"Sscanln\":\tValueOf(fmt.Sscanln),\n\t}, Types: map[string]Type{\n\t\t\"Formatter\":\tTypeOf((*fmt.Formatter)(nil)).Elem(),\n\t\t\"GoStringer\":\tTypeOf((*fmt.GoStringer)(nil)).Elem(),\n\t\t\"ScanState\":\tTypeOf((*fmt.ScanState)(nil)).Elem(),\n\t\t\"Scanner\":\tTypeOf((*fmt.Scanner)(nil)).Elem(),\n\t\t\"State\":\tTypeOf((*fmt.State)(nil)).Elem(),\n\t\t\"Stringer\":\tTypeOf((*fmt.Stringer)(nil)).Elem(),\n\t}, Proxies: map[string]Type{\n\t\t\"Formatter\":\tTypeOf((*P_fmt_Formatter)(nil)).Elem(),\n\t\t\"GoStringer\":\tTypeOf((*P_fmt_GoStringer)(nil)).Elem(),\n\t\t\"ScanState\":\tTypeOf((*P_fmt_ScanState)(nil)).Elem(),\n\t\t\"Scanner\":\tTypeOf((*P_fmt_Scanner)(nil)).Elem(),\n\t\t\"State\":\tTypeOf((*P_fmt_State)(nil)).Elem(),\n\t\t\"Stringer\":\tTypeOf((*P_fmt_Stringer)(nil)).Elem(),\n\t}, \n\t}\n}", "func Uninject(opts *options.Options, optionsFunc ...cliutils.OptionsFunc) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"uninject\",\n\t\tShort: \"Remove SDS & istio-proxy sidecars from gateway-proxy pod\",\n\t\tLong: \"Removes the istio-proxy sidecar from the gateway-proxy pod. \" +\n\t\t\t\"Also removes the sds sidecar from the gateway-proxy pod. \" +\n\t\t\t\"Also removes the gateway_proxy_sds cluster from the gateway-proxy envoy bootstrap ConfigMap.\",\n\t\tPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nil\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\terr := istioUninject(args, opts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tcliutils.ApplyOptions(cmd, optionsFunc)\n\treturn cmd\n}", "func (self *Rectangle) InflateI(args ...interface{}) *Rectangle{\n return &Rectangle{self.Object.Call(\"inflate\", args)}\n}", "func demangle(s string) string {\n\tvar correct strings.Builder\n\n\t// copy s into correct, using lookahead to rewrite letters\n\tvar i int\n\tfor i = 0; i < len(s)-1; i++ {\n\t\tc := s[i]\n\t\tif c == '!' {\n\t\t\tnext := s[i+1]\n\t\t\tif next >= 'a' && next <= 'z' {\n\t\t\t\tcorrect.WriteByte(next - ('a' - 'A'))\n\t\t\t\ti++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tcorrect.WriteByte(c)\n\t}\n\n\t// if the last 2 letters were not an encoding, copy the last letter\n\tif i == len(s)-1 {\n\t\tcorrect.WriteByte(s[i])\n\t}\n\n\treturn correct.String()\n}", "func returnGoSubServiceSvcDefinition(name string, hasDB bool) (string, error) {\n\t// service types\n\tsrvcDefinitionString := fmt.Sprintf(\"\\n\\n // New%s loads related SQL statements and initializes the container struct\\n\", strings.Title(name)+\"Service\") +\n\t\tfmt.Sprintf(\"func New%s(s *Services) %s {\\n\", strings.Title(name)+\"Service\", strings.Title(name)+\"Service\")\n\n\tif hasDB {\n\t\tsrvcDefinitionString += fmt.Sprintf(\"\t// create initial interface \\n\") +\n\t\t\tfmt.Sprintf(\"\tctx := &db.%s{}\\n\", strings.Title(name)+\"StructDB\") +\n\t\t\tfmt.Sprintf(\"\tctx.DB = s.db \\n\")\n\t}\n\n\tsrvcDefinitionString += fmt.Sprintf(\"\tsrvc := &%s{}\\n\", strings.ToLower(name)+\"Service\")\n\n\tif hasDB {\n\t\tsrvcDefinitionString += fmt.Sprintf(\"\tsrvc.I%s = &validation.%s{I%s: ctx}\\n\", strings.Title(name)+\"DB\", strings.Title(name)+\"Validator\", strings.Title(name)+\"DB\")\n\t}\n\tsrvcDefinitionString += fmt.Sprintf(\"\treturn srvc\\n }\\n\\n\") +\n\t\t// interface type\n\t\tfmt.Sprintf(\"// %s is a wrapper for related components\\n\", strings.Title(name)+\"Services\") +\n\t\tfmt.Sprintf(\"type %s interface {\\n\", strings.Title(name)+\"Service\")\n\tif hasDB {\n\t\tsrvcDefinitionString += fmt.Sprintf(\"\tdb.I%s\\n\", strings.Title(name)+\"DB\")\n\t}\n\tsrvcDefinitionString += fmt.Sprintf(\"}\\n\\n\") +\n\t\t// struct type\n\t\tfmt.Sprintf(\"type %s struct {\\n\", strings.ToLower(name)+\"Service\")\n\tif hasDB {\n\t\tsrvcDefinitionString += fmt.Sprintf(\"\tdb.I%s\\n\", strings.Title(name)+\"DB\")\n\t}\n\tsrvcDefinitionString += fmt.Sprintf(\"}\\n\")\n\n\treturn srvcDefinitionString, nil\n}", "func DI() proto.RoomServicesServer {\n\tiulidGenerator := util.NewULIDGenerator()\n\tiFactory := room.NewFactory(iulidGenerator)\n\tdb := mysql.ConnectGorm()\n\tiRepository := room2.NewRepositoryImpl(db)\n\tiDomainService := room3.NewDomainService(iRepository)\n\tiInputPort := room4.NewInteractor(iFactory, iRepository, iDomainService)\n\troomIInputPort := room5.NewInteractor(iRepository)\n\tclient := redis.NewClient()\n\tmessageIRepository := message.NewRepositoryImpl(db, client)\n\tmessageIInputPort := message2.NewInteractor(messageIRepository)\n\tmessageIFactory := message3.NewFactory(iulidGenerator)\n\tiInputPort2 := room6.NewInteractor(messageIFactory, messageIRepository, iRepository)\n\troomServicesServer := room7.NewController(iInputPort, roomIInputPort, messageIInputPort, iInputPort2)\n\treturn roomServicesServer\n}", "func InjectGraphQLService(\n\truntime env.Runtime,\n\tprefix provider.LogPrefix,\n\tlogLevel logger.LogLevel,\n\tsqlDB *sql.DB,\n\tgraphqlPath provider.GraphQLPath,\n\tsecret provider.ReCaptchaSecret,\n\tjwtSecret provider.JwtSecret,\n\tbufferSize provider.KeyGenBufferSize,\n\tkgsRPCConfig provider.KgsRPCConfig,\n\ttokenValidDuration provider.TokenValidDuration,\n\tdataDogAPIKey provider.DataDogAPIKey,\n\tsegmentAPIKey provider.SegmentAPIKey,\n\tipStackAPIKey provider.IPStackAPIKey,\n\tgoogleAPIKey provider.GoogleAPIKey,\n) (service.GraphQL, error) {\n\twire.Build(\n\t\twire.Bind(new(timer.Timer), new(timer.System)),\n\t\twire.Bind(new(graphql.API), new(gqlapi.Short)),\n\t\twire.Bind(new(graphql.Handler), new(graphql.GraphGopherHandler)),\n\n\t\twire.Bind(new(risk.BlackList), new(google.SafeBrowsing)),\n\t\twire.Bind(new(repository.UserURLRelation), new(sqldb.UserURLRelationSQL)),\n\t\twire.Bind(new(repository.ChangeLog), new(sqldb.ChangeLogSQL)),\n\t\twire.Bind(new(repository.URL), new(*sqldb.URLSql)),\n\n\t\twire.Bind(new(changelog.ChangeLog), new(changelog.Persist)),\n\t\twire.Bind(new(url.Retriever), new(url.RetrieverPersist)),\n\t\twire.Bind(new(url.Creator), new(url.CreatorPersist)),\n\n\t\tobservabilitySet,\n\t\tauthSet,\n\t\tkeyGenSet,\n\n\t\tenv.NewDeployment,\n\t\tprovider.NewGraphQLService,\n\t\tgraphql.NewGraphGopherHandler,\n\t\twebreq.NewHTTPClient,\n\t\twebreq.NewHTTP,\n\t\ttimer.NewSystem,\n\n\t\tgqlapi.NewShort,\n\t\tprovider.NewSafeBrowsing,\n\t\trisk.NewDetector,\n\t\tprovider.NewReCaptchaService,\n\t\tsqldb.NewChangeLogSQL,\n\t\tsqldb.NewURLSql,\n\t\tsqldb.NewUserURLRelationSQL,\n\n\t\tvalidator.NewLongLink,\n\t\tvalidator.NewCustomAlias,\n\t\tchangelog.NewPersist,\n\t\turl.NewRetrieverPersist,\n\t\turl.NewCreatorPersist,\n\t\trequester.NewVerifier,\n\t)\n\treturn service.GraphQL{}, nil\n}", "func TempDI(name string) (di DI, clean func(), err error) {\n\thdir, err := homedir.Dir()\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to determine homedir\")\n\t}\n\n\tkcfg, err := clientcmd.BuildConfigFromFlags(\"\", filepath.Join(hdir, \".kube\", \"config\"))\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to build config form kube config\")\n\t}\n\n\tif !strings.Contains(fmt.Sprintf(\"%#v\", kcfg), \"minikube\") {\n\t\treturn nil, nil, ErrMinikubeOnly\n\t}\n\n\tval := validator.New()\n\tval.RegisterValidation(\"is-abs-path\", ValidateAbsPath)\n\n\ttdi := &tmpDI{\n\t\tlogs: logrus.New(),\n\t\tval: val,\n\t}\n\n\ttdi.kube, err = kubernetes.NewForConfig(kcfg)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create kube client from config\")\n\t}\n\n\ttdi.crd, err = crd.NewForConfig(kcfg)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create CRD client from config\")\n\t}\n\n\tif name == \"\" {\n\t\td := make([]byte, 16)\n\t\t_, err = rand.Read(d)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.Wrap(err, \"failed to read random bytes\")\n\t\t}\n\n\t\tname = hex.EncodeToString(d)\n\t}\n\n\tns, err := tdi.kube.CoreV1().Namespaces().Create(&v1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{GenerateName: name},\n\t})\n\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create temporary namespace\")\n\t}\n\n\ttdi.ns = ns.GetName()\n\treturn tdi, func() {\n\t\terr := tdi.kube.CoreV1().Namespaces().Delete(ns.Name, nil)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}, nil\n}", "func UserTypeUnmarshalerImpl(u *design.UserTypeDefinition, versioned bool, defaultPkg, context string) string {\n\tvar required []string\n\tfor _, v := range u.Validations {\n\t\tif r, ok := v.(*design.RequiredValidationDefinition); ok {\n\t\t\trequired = r.Names\n\t\t\tbreak\n\t\t}\n\t}\n\tvar impl string\n\tswitch {\n\tcase u.IsObject():\n\t\timpl = objectUnmarshalerR(u, required, versioned, defaultPkg, context, \"source\", \"target\", 1)\n\tcase u.IsArray():\n\t\timpl = arrayUnmarshalerR(u.ToArray(), versioned, defaultPkg, context, \"source\", \"target\", 1)\n\tcase u.IsHash():\n\t\timpl = hashUnmarshalerR(u.ToHash(), versioned, defaultPkg, context, \"source\", \"target\", 1)\n\tdefault:\n\t\treturn \"\" // No function for primitive types - they just get casted\n\t}\n\tdata := map[string]interface{}{\n\t\t\"Name\": userTypeUnmarshalerFuncName(u),\n\t\t\"Type\": u,\n\t\t\"Impl\": impl,\n\t}\n\treturn RunTemplate(unmUserImplT, data)\n}", "func godef(ds design.DataStructure, versioned bool, defPkg string, tabs int, jsonTags, inner, res bool) string {\n\tvar buffer bytes.Buffer\n\tdef := ds.Definition()\n\tt := def.Type\n\tswitch actual := t.(type) {\n\tcase design.Primitive:\n\t\treturn GoTypeName(t, tabs)\n\tcase *design.Array:\n\t\treturn \"[]\" + godef(actual.ElemType, versioned, defPkg, tabs, jsonTags, true, res)\n\tcase *design.Hash:\n\t\tkeyDef := godef(actual.KeyType, versioned, defPkg, tabs, jsonTags, true, res)\n\t\telemDef := godef(actual.ElemType, versioned, defPkg, tabs, jsonTags, true, res)\n\t\treturn fmt.Sprintf(\"map[%s]%s\", keyDef, elemDef)\n\tcase design.Object:\n\t\tif inner {\n\t\t\tbuffer.WriteByte('*')\n\t\t}\n\t\tbuffer.WriteString(\"struct {\\n\")\n\t\tkeys := make([]string, len(actual))\n\t\ti := 0\n\t\tfor n := range actual {\n\t\t\tkeys[i] = n\n\t\t\ti++\n\t\t}\n\t\tsort.Strings(keys)\n\t\tfor _, name := range keys {\n\t\t\tWriteTabs(&buffer, tabs+1)\n\t\t\ttypedef := godef(actual[name], versioned, defPkg, tabs+1, jsonTags, true, res)\n\t\t\tfname := Goify(name, true)\n\t\t\tvar tags string\n\t\t\tif jsonTags {\n\t\t\t\tvar omit string\n\t\t\t\tif !def.IsRequired(name) {\n\t\t\t\t\tomit = \",omitempty\"\n\t\t\t\t}\n\t\t\t\ttags = fmt.Sprintf(\" `json:\\\"%s%s\\\"`\", name, omit)\n\t\t\t}\n\t\t\tdesc := actual[name].Description\n\t\t\tif desc != \"\" {\n\t\t\t\tdesc = fmt.Sprintf(\"// %s\\n\", desc)\n\t\t\t}\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"%s%s %s%s\\n\", desc, fname, typedef, tags))\n\t\t}\n\t\tWriteTabs(&buffer, tabs)\n\t\tbuffer.WriteString(\"}\")\n\t\treturn buffer.String()\n\tcase *design.UserTypeDefinition:\n\t\tname := GoPackageTypeName(actual, versioned, defPkg, tabs)\n\t\tif actual.Type.IsObject() {\n\t\t\treturn \"*\" + name\n\t\t}\n\t\treturn name\n\tcase *design.MediaTypeDefinition:\n\t\tif res && actual.Resource != nil {\n\t\t\treturn \"*\" + Goify(actual.Resource.Name, true)\n\t\t}\n\t\tname := GoPackageTypeName(actual, versioned, defPkg, tabs)\n\t\tif actual.Type.IsObject() {\n\t\t\treturn \"*\" + name\n\t\t}\n\t\treturn name\n\tdefault:\n\t\tpanic(\"goa bug: unknown data structure type\")\n\t}\n}", "func sf(vm *VM, argument string) {\n\tsco := vm.Scope\n\tif sco == nil || sco.previous == nil {\n\t\tvm.err = ErrorScopeMin\n\t\treturn\n\t}\n\tvm.Scope = sco.previous\n\tfor name, variable := range sco.variables {\n\t\tvm.scopeResolve(name, func(scope *Scope) {\n\t\t\tscope.variables[name] = variable\n\t\t})\n\t}\n}", "func (app AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}", "func NoopTranslator() Translator { return noopTranslator }", "func CovertSwaggerMethordToLocalMethord(schema *registry.SchemaContent, src *registry.MethodInfo, dst *DefMethod) {\n\tdst.OperaID = src.OperationID\n\ttmpParas := make([]MethParam, len(src.Parameters))\n\ti := 0\n\tfor _, para := range src.Parameters {\n\t\tvar defPara MethParam\n\t\tdefPara.Name = para.Name\n\t\tif para.Type == \"\" {\n\t\t\tif para.Schema.Type != \"\" {\n\t\t\t\tdefPara.Dtype = para.Schema.Type\n\t\t\t} else {\n\t\t\t\tdefPara.Dtype = \"object\"\n\t\t\t\tif para.Schema.Reference != \"\" {\n\t\t\t\t\tdefPara.ObjRef = GetDefTypeFromDef(schema.Definition, para.Schema.Reference)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tdefPara.Dtype = para.Type\n\t\t}\n\t\tdefPara.Required = para.Required\n\t\tdefPara.Where = para.In\n\t\tdefPara.Indx = i\n\t\ttmpParas[i] = defPara\n\t\ti++\n\t}\n\tdst.Paras = tmpParas\n\ttmpRsps := make(map[string]*MethRespond)\n\tfor key, rsp := range src.Response {\n\t\tvar defRsp MethRespond\n\t\tif dtype, ok := rsp.Schema[\"type\"]; ok {\n\t\t\tdefRsp.DType = dtype\n\t\t} else {\n\t\t\tdefRsp.DType = \"object\"\n\t\t\tif dRef, ok := rsp.Schema[\"$ref\"]; ok {\n\t\t\t\tdefRsp.ObjRef = GetDefTypeFromDef(schema.Definition, dRef)\n\t\t\t}\n\t\t}\n\t\tdefRsp.Status = key\n\t\ttmpRsps[key] = &defRsp\n\t}\n\tdst.Responds = tmpRsps\n}", "func init() {\n\ttransformCmd.AddCommand(replaceCmd)\n}", "func _() {\n\tX(Interface[*F /* ERROR got 1 arguments but 2 type parameters */ [string]](Impl{}))\n}", "func definition(s selection, args []string) {\n\tvar gd serial.Definition\n\tjs := runWithStdin(s.archive(), \"guru\", \"-json\", \"-modified\", \"definition\", s.pos())\n\tif err := json.Unmarshal([]byte(js), &gd); err != nil {\n\t\tlog.Fatalf(\"failed to unmarshal guru json: %v\\n\", err)\n\t}\n\tif err := plumbText(gd.ObjPos); err != nil {\n\t\tfmt.Println(gd.ObjPos)\n\t\tlog.Fatalf(\"failed to plumb: %v\\n\", err)\n\t}\n}", "func initTagConversionMap() {\n\n\tTagStrToInt[\"bos\"] = 0\n\tTagStrToInt[\"$\"] = 1\n\tTagStrToInt[\"\\\"\"] = 2\n\tTagStrToInt[\"(\"] = 3\n\tTagStrToInt[\")\"] = 4\n\tTagStrToInt[\",\"] = 5\n\tTagStrToInt[\"--\"] = 6\n\tTagStrToInt[\".\"] = 7\n\tTagStrToInt[\":\"] = 8\n\tTagStrToInt[\"cc\"] = 9\n\tTagStrToInt[\"cd\"] = 10\n\tTagStrToInt[\"dt\"] = 11\n\tTagStrToInt[\"fw\"] = 12\n\tTagStrToInt[\"jj\"] = 13\n\tTagStrToInt[\"ls\"] = 14\n\tTagStrToInt[\"nn\"] = 15\n\tTagStrToInt[\"np\"] = 16\n\tTagStrToInt[\"pos\"] = 17\n\tTagStrToInt[\"pr\"] = 18\n\tTagStrToInt[\"rb\"] = 19\n\tTagStrToInt[\"sym\"] = 20\n\tTagStrToInt[\"to\"] = 21\n\tTagStrToInt[\"uh\"] = 22\n\tTagStrToInt[\"vb\"] = 23\n\tTagStrToInt[\"md\"] = 24\n\tTagStrToInt[\"in\"] = 25\n\n\tTagIntToStr[0] = \"bos\"\n\tTagIntToStr[1] = \"$\"\n\tTagIntToStr[2] = \"\\\"\"\n\tTagIntToStr[3] = \"(\"\n\tTagIntToStr[4] = \")\"\n\tTagIntToStr[5] = \",\"\n\tTagIntToStr[6] = \"--\"\n\tTagIntToStr[7] = \".\"\n\tTagIntToStr[8] = \":\"\n\tTagIntToStr[9] = \"cc\"\n\tTagIntToStr[10] = \"cd\"\n\tTagIntToStr[11] = \"dt\"\n\tTagIntToStr[12] = \"fw\"\n\tTagIntToStr[13] = \"jj\"\n\tTagIntToStr[14] = \"ls\"\n\tTagIntToStr[15] = \"nn\"\n\tTagIntToStr[16] = \"np\"\n\tTagIntToStr[17] = \"pos\"\n\tTagIntToStr[18] = \"pr\"\n\tTagIntToStr[19] = \"rb\"\n\tTagIntToStr[20] = \"sym\"\n\tTagIntToStr[21] = \"to\"\n\tTagIntToStr[22] = \"uh\"\n\tTagIntToStr[23] = \"vb\"\n\tTagIntToStr[24] = \"md\"\n\tTagIntToStr[25] = \"in\"\n}", "func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}", "func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}", "func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}", "func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}", "func Replacer(old, new string) NameMapper {\n\treturn func(s string) string {\n\t\treturn strings.ReplaceAll(s, old, new)\n\t}\n}", "func (s *BaseSyslParserListener) EnterFacade(ctx *FacadeContext) {}", "func (a *Client) ReplaceBind(params *ReplaceBindParams, authInfo runtime.ClientAuthInfoWriter) (*ReplaceBindOK, *ReplaceBindAccepted, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewReplaceBindParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"replaceBind\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/services/haproxy/configuration/binds/{name}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &ReplaceBindReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tswitch value := result.(type) {\n\tcase *ReplaceBindOK:\n\t\treturn value, nil, nil\n\tcase *ReplaceBindAccepted:\n\t\treturn nil, value, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ReplaceBindDefault)\n\treturn nil, nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func ZopfliDeflate(d policies.DEFLATE,data []byte) []byte {\n\tbuf := new(bytes.Buffer)\n\to := zopfli.DefaultOptions()\n\to.NumIterations = 15\n\to.BlockSplittingLast = true\n\to.BlockType = 2\n\tdef := zopfli.NewDeflator(buf,&o)\n\tdef.Deflate(true,data)\n\treturn buf.Bytes()\n}", "func initApiScope(scope *apiScope) *apiScope {\n\tname := scope.name\n\tscopeByName[name] = scope\n\tallScopeNames = append(allScopeNames, name)\n\tscope.propertyName = strings.ReplaceAll(name, \"-\", \"_\")\n\tscope.fieldName = proptools.FieldNameForProperty(scope.propertyName)\n\tscope.stubsTag = scopeDependencyTag{\n\t\tname: name + \"-stubs\",\n\t\tapiScope: scope,\n\t\tdepInfoExtractor: (*scopePaths).extractStubsLibraryInfoFromDependency,\n\t}\n\tscope.stubsSourceTag = scopeDependencyTag{\n\t\tname: name + \"-stubs-source\",\n\t\tapiScope: scope,\n\t\tdepInfoExtractor: (*scopePaths).extractStubsSourceInfoFromDep,\n\t}\n\tscope.apiFileTag = scopeDependencyTag{\n\t\tname: name + \"-api\",\n\t\tapiScope: scope,\n\t\tdepInfoExtractor: (*scopePaths).extractApiInfoFromDep,\n\t}\n\tscope.stubsSourceAndApiTag = scopeDependencyTag{\n\t\tname: name + \"-stubs-source-and-api\",\n\t\tapiScope: scope,\n\t\tdepInfoExtractor: (*scopePaths).extractStubsSourceAndApiInfoFromApiStubsProvider,\n\t}\n\n\t// To get the args needed to generate the stubs source append all the args from\n\t// this scope and all the scopes it extends as each set of args adds additional\n\t// members to the stubs.\n\tvar scopeSpecificArgs []string\n\tif scope.annotation != \"\" {\n\t\tscopeSpecificArgs = []string{\"--show-annotation\", scope.annotation}\n\t}\n\tfor s := scope; s != nil; s = s.extends {\n\t\tscopeSpecificArgs = append(scopeSpecificArgs, s.extraArgs...)\n\n\t\t// Ensure that the generated stubs includes all the API elements from the API scope\n\t\t// that this scope extends.\n\t\tif s != scope && s.annotation != \"\" {\n\t\t\tscopeSpecificArgs = append(scopeSpecificArgs, \"--show-for-stub-purposes-annotation\", s.annotation)\n\t\t}\n\t}\n\n\t// Escape any special characters in the arguments. This is needed because droidstubs\n\t// passes these directly to the shell command.\n\tscope.droidstubsArgs = proptools.ShellEscapeList(scopeSpecificArgs)\n\n\treturn scope\n}", "func (injector *InterfaceImplementationInjector) Inject(\n\tdef TypeDefinition, implementations ...*InterfaceImplementation) (TypeDefinition, error) {\n\tresult := def\n\n\tfor _, impl := range implementations {\n\t\tvar err error\n\t\tresult, err = injector.visitor.VisitDefinition(result, impl)\n\t\tif err != nil {\n\t\t\treturn TypeDefinition{}, err\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func (self *PhysicsP2) CreateRotationalSpringI(args ...interface{}) *PhysicsP2RotationalSpring{\n return &PhysicsP2RotationalSpring{self.Object.Call(\"createRotationalSpring\", args)}\n}", "func (g *Generator) Fgenerate(w io.Writer) {\n\ttpkg := templateBuilder(\"package\", `package {{ .Package }}{{\"\\n\\n\"}}`)\n\n\ttimp := templateBuilder(\"imports\", `import {{ if eq (len .Imports) 1 }}\"{{ index .Imports 0 }}\"{{else}}(\n{{ range .Imports }}{{\"\\t\"}}\"{{ . }}\"\n{{ end }}){{ end }}{{\"\\n\\n\"}}`)\n\n\tttyp := templateBuilder(\"type\", `type {{ .Opts.Type }} struct{{\"{\"}}\n{{- if gt (len .Deps) 0 -}}{{ \"\\n\" }}\n {{- range .Deps -}}\n {{- \"\\t\" }}{{ .Name }} {{ .Type -}}{{ \"\\n\" }}\n {{- end -}}\n{{- end -}}\n}{{\"\\n\\n\"}}`)\n\n\ttdep := templateBuilder(\"deps\", `{{- $cname := .Opts.Name -}}\n{{- $ctype := .Opts.Type -}}\n{{- range .Deps -}}\nfunc ({{ $cname }} *{{ $ctype }}) New{{ .Name | ucfirst }}() {{ .Type }} {{ .Func }}{{ \"\\n\\n\" }}\nfunc ({{ $cname }} *{{ $ctype }}) {{ .Name | ucfirst }}() {{ .Type }} {\n{{ \"\\t\" }}if {{ $cname }}.{{ .Name | lcfirst }} == nil {\n{{ \"\\t\\t\" }}{{ $cname }}.{{ .Name | lcfirst }} = {{ $cname }}.New{{ .Name | ucfirst }}()\n{{ \"\\t\" }}}\n{{ \"\\t\" }}return {{ $cname }}.{{ .Name | lcfirst }}\n}{{ \"\\n\\n\" }}\n{{- end -}}`)\n\n\terr := tpkg.Execute(w, g.opts)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif len(g.opts.Imports) > 0 {\n\t\terr = timp.Execute(w, g.opts)\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tgWithPublicFields := struct {\n\t\tOpts opts\n\t\tDeps []dep\n\t}{\n\t\tg.opts,\n\t\tg.deps,\n\t}\n\n\terr = ttyp.Execute(w, gWithPublicFields)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif len(g.deps) > 0 {\n\t\terr = tdep.Execute(w, gWithPublicFields)\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (mdr *Modder) ReplaceDependency(m *Module) error {\n\t// Don't add the root module to the dependencies\n\tif mdr.module.Module == m.Module {\n\t\treturn nil\n\t}\n\t// save module to depsMap, that's it? (yes)\n\tmdr.depsMap[m.Module] = m\n\n\treturn nil\n}", "func (cli *CLI) hookBeforeCall(cc *Arg) {\n\tcli.loadDataSyntax(cc)\n\tcli.loadScriptSyntax(cc)\n}", "func main() {\n\t// initialize the app with custom registered objects in the injection container\n\tc := clif.New(\"My App\", \"1.0.0\", \"An example application\").\n\t\tRegister(&exampleStruct{\"bar1\"}).\n\t\tRegisterAs(reflect.TypeOf((*exampleInterface)(nil)).Elem().String(), &exampleStruct{\"bar2\"}).\n\t\tNew(\"hello\", \"The obligatory hello world\", callHello)\n\n\t// extend output styles\n\tclif.DefaultStyles[\"mine\"] = \"\\033[32;1m\"\n\n\t// customize error handler\n\tclif.Die = func(msg string, args ...interface{}) {\n\t\tc.Output().Printf(\"<error>Everyting went wrong: %s<reset>\\n\\n\", fmt.Sprintf(msg, args...))\n\t\tos.Exit(1)\n\t}\n\n\t// build & add a complex command\n\tcmd := clif.NewCommand(\"foo\", \"It does foo\", callFoo).\n\t\tNewArgument(\"name\", \"Name for greeting\", \"\", true, false).\n\t\tNewArgument(\"more-names\", \"And more names for greeting\", \"\", false, true).\n\t\tNewOption(\"whatever\", \"w\", \"Some required option\", \"\", true, false)\n\tcnt := clif.NewOption(\"counter\", \"c\", \"Show how high you can count\", \"\", false, false)\n\tcnt.SetValidator(clif.IsInt)\n\tcmd.AddOption(cnt)\n\tc.Add(cmd)\n\n\tcb := func(c *clif.Command, out clif.Output) {\n\t\tout.Printf(\"Called %s\\n\", c.Name)\n\t}\n\tc.New(\"bar:baz\", \"A grouped command\", cb).\n\t\tNew(\"bar:zoing\", \"Another grouped command\", cb).\n\t\tNew(\"hmm:huh\", \"Yet another grouped command\", cb).\n\t\tNew(\"hmm:uhm\", \"And yet another grouped command\", cb)\n\n\t// execute the main loop\n\tc.Run()\n}", "func (c *Converter) convertDefinition(decl *nast.Definition, visitType int) error {\n\tif visitType == ast.PreVisit {\n\t\tc.setDefinition(decl.Name, decl)\n\t\treturn ast.NewNodeReplacement()\n\t}\n\treturn nil\n}", "func AddDefaultRefactorings() {\n\tAddRefactoring(\"rename\", new(refactoring.Rename))\n\tAddRefactoring(\"extract\", new(refactoring.ExtractFunc))\n\tAddRefactoring(\"var\", new(refactoring.ExtractLocal))\n\tAddRefactoring(\"toggle\", new(refactoring.ToggleVar))\n\tAddRefactoring(\"godoc\", new(refactoring.AddGoDoc))\n\tAddRefactoring(\"debug\", new(refactoring.Debug))\n\tAddRefactoring(\"null\", new(refactoring.Null))\n}", "func (s *BaseCobol85PreprocessorListener) EnterReplacement(ctx *ReplacementContext) {}", "func OnDelString(stringID string) {\n\tundeclareServicesOfString(stringID)\n}", "func FromOracle(layout string) string {\n\treturn oracleStringReplacer.Replace(strings.ToUpper(layout))\n}", "func (c *Converter) setDefinition(name string, val *nast.Definition) {\n\tname = strings.ToLower(name)\n\tc.definitions[name] = val\n}", "func Init() {\n\tfmt.Println(\"Loading sanitizer...\")\n\treplacer = *strings.NewReplacer(append(confusables, diacritics...)...)\n\tfmt.Printf(\"Loaded %d confusables and %d diacritics\\n\", len(confusables)/2, len(diacritics)/2)\n}", "func injectNameSpace(namespace string) mf.Transformer {\n\treturn func(u *unstructured.Unstructured) error {\n\t\tkind := u.GetKind()\n\t\tif kind == \"Role\" || kind == \"RoleBinding\" {\n\t\t\tu.SetNamespace(namespace)\n\t\t}\n\t\treturn nil\n\t}\n}", "func newBinder(chart *chart.Chart, cmIface v1.ConfigMapInterface) (mode.Binder, error) {\n\t// parse the values file for steward-specific config map info\n\tcmNames, err := getStewardConfigMapInfo(chart.Values)\n\tif err != nil {\n\t\tlogger.Errorf(\"getting steward config map info (%s)\", err)\n\t\treturn nil, err\n\t}\n\tlogger.Debugf(\"got config map names for helm chart %s\", cmNames)\n\treturn binder{\n\t\tcmNames: cmNames,\n\t\tcmIface: cmIface,\n\t}, nil\n}", "func (l *Libvirt) InterfaceUndefine(Iface Interface) (err error) {\n\tvar buf []byte\n\n\targs := InterfaceUndefineArgs {\n\t\tIface: Iface,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\n\t_, err = l.requestStream(132, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func defangIPaddr(address string) string {\n\treturn strings.Replace(address, \".\", \"[.]\", -1)\n}", "func (b binding) resolve(c Container) (interface{}, error) {\n\tif b.instance != nil {\n\t\treturn b.instance, nil\n\t}\n\n\treturn c.invoke(b.resolver)\n}", "func BindToFS(w common.WellFormedName) (fs string) {\n\t// Initialize the output with the CPE v2.3 string prefix.\n\tfs = \"cpe:2.3:\"\n\tattributes := []string{\"part\", \"vendor\", \"product\", \"version\",\n\t\t\"update\", \"edition\", \"language\", \"sw_edition\", \"target_sw\",\n\t\t\"target_hw\", \"other\"}\n\tfor _, a := range attributes {\n\t\tv := bindValueForFS(w.Get(a))\n\t\tfs += v\n\t\tif a != common.AttributeOther {\n\t\t\tfs += \":\"\n\t\t}\n\t}\n\treturn fs\n}", "func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}", "func (self *PhysicsP2) RemoveSpringI(args ...interface{}) *PhysicsP2Spring{\n return &PhysicsP2Spring{self.Object.Call(\"removeSpring\", args)}\n}", "func libNameByConvention(nc namingConvention, imp string, pkgName string) string {\n\tif nc == goDefaultLibraryNamingConvention {\n\t\treturn defaultLibName\n\t}\n\tname := libNameFromImportPath(imp)\n\tisCommand := pkgName == \"main\"\n\tif name == \"\" {\n\t\tif isCommand {\n\t\t\tname = \"lib\"\n\t\t} else {\n\t\t\tname = pkgName\n\t\t}\n\t} else if isCommand {\n\t\tname += \"_lib\"\n\t}\n\treturn name\n}", "func (b Binding) addGlobalInjections() {\n\tfor _, v := range b.base().container.globalInjections {\n\t\tb.AddInjection(v)\n\t}\n}", "func InjectRoutingService(\n\truntime env.Runtime,\n\tprefix provider.LogPrefix,\n\tlogLevel logger.LogLevel,\n\tsqlDB *sql.DB,\n\tgithubClientID provider.GithubClientID,\n\tgithubClientSecret provider.GithubClientSecret,\n\tfacebookClientID provider.FacebookClientID,\n\tfacebookClientSecret provider.FacebookClientSecret,\n\tfacebookRedirectURI provider.FacebookRedirectURI,\n\tgoogleClientID provider.GoogleClientID,\n\tgoogleClientSecret provider.GoogleClientSecret,\n\tgoogleRedirectURI provider.GoogleRedirectURI,\n\tjwtSecret provider.JwtSecret,\n\tbufferSize provider.KeyGenBufferSize,\n\tkgsRPCConfig provider.KgsRPCConfig,\n\twebFrontendURL provider.WebFrontendURL,\n\ttokenValidDuration provider.TokenValidDuration,\n\tdataDogAPIKey provider.DataDogAPIKey,\n\tsegmentAPIKey provider.SegmentAPIKey,\n\tipStackAPIKey provider.IPStackAPIKey,\n) (service.Routing, error) {\n\twire.Build(\n\t\twire.Bind(new(timer.Timer), new(timer.System)),\n\t\twire.Bind(new(geo.Geo), new(geo.IPStack)),\n\n\t\twire.Bind(new(url.Retriever), new(url.RetrieverPersist)),\n\t\twire.Bind(new(repository.UserURLRelation), new(sqldb.UserURLRelationSQL)),\n\t\twire.Bind(new(repository.User), new(*sqldb.UserSQL)),\n\t\twire.Bind(new(repository.URL), new(*sqldb.URLSql)),\n\n\t\tobservabilitySet,\n\t\tauthSet,\n\t\tgithubAPISet,\n\t\tfacebookAPISet,\n\t\tgoogleAPISet,\n\t\tkeyGenSet,\n\t\tfeatureDecisionSet,\n\n\t\tservice.NewRouting,\n\t\twebreq.NewHTTPClient,\n\t\twebreq.NewHTTP,\n\t\tgraphql.NewClientFactory,\n\t\ttimer.NewSystem,\n\t\tprovider.NewIPStack,\n\t\tenv.NewDeployment,\n\n\t\tsqldb.NewUserSQL,\n\t\tsqldb.NewURLSql,\n\t\tsqldb.NewUserURLRelationSQL,\n\t\turl.NewRetrieverPersist,\n\t\taccount.NewProvider,\n\t\tprovider.NewShortRoutes,\n\t)\n\treturn service.Routing{}, nil\n}", "func camelizeDown(s string) string {\n\tif s == \"ID\" {\n\t\treturn \"id\"\n\t\t// note: not sure why I need this, there's a lot that deals with\n\t\t// accronyms in the dependency packages but they don't seem to behave\n\t\t// as expected in this case.\n\t}\n\treturn defaultRuleset.CamelizeDownFirst(s)\n}", "func toGobDiagnostic(posToLocation func(start, end token.Pos) (protocol.Location, error), a *analysis.Analyzer, diag analysis.Diagnostic) (gobDiagnostic, error) {\n\tvar fixes []gobSuggestedFix\n\tfor _, fix := range diag.SuggestedFixes {\n\t\tvar gobEdits []gobTextEdit\n\t\tfor _, textEdit := range fix.TextEdits {\n\t\t\tloc, err := posToLocation(textEdit.Pos, textEdit.End)\n\t\t\tif err != nil {\n\t\t\t\treturn gobDiagnostic{}, fmt.Errorf(\"in SuggestedFixes: %w\", err)\n\t\t\t}\n\t\t\tgobEdits = append(gobEdits, gobTextEdit{\n\t\t\t\tLocation: loc,\n\t\t\t\tNewText: textEdit.NewText,\n\t\t\t})\n\t\t}\n\t\tfixes = append(fixes, gobSuggestedFix{\n\t\t\tMessage: fix.Message,\n\t\t\tTextEdits: gobEdits,\n\t\t})\n\t}\n\n\tvar related []gobRelatedInformation\n\tfor _, r := range diag.Related {\n\t\tloc, err := posToLocation(r.Pos, r.End)\n\t\tif err != nil {\n\t\t\treturn gobDiagnostic{}, fmt.Errorf(\"in Related: %w\", err)\n\t\t}\n\t\trelated = append(related, gobRelatedInformation{\n\t\t\tLocation: loc,\n\t\t\tMessage: r.Message,\n\t\t})\n\t}\n\n\tloc, err := posToLocation(diag.Pos, diag.End)\n\tif err != nil {\n\t\treturn gobDiagnostic{}, err\n\t}\n\n\t// The Code column of VSCode's Problems table renders this\n\t// information as \"Source(Code)\" where code is a link to CodeHref.\n\t// (The code field must be nonempty for anything to appear.)\n\tdiagURL := effectiveURL(a, diag)\n\tcode := \"default\"\n\tif diag.Category != \"\" {\n\t\tcode = diag.Category\n\t}\n\n\treturn gobDiagnostic{\n\t\tLocation: loc,\n\t\t// Severity for analysis diagnostics is dynamic,\n\t\t// based on user configuration per analyzer.\n\t\tCode: code,\n\t\tCodeHref: diagURL,\n\t\tSource: a.Name,\n\t\tMessage: diag.Message,\n\t\tSuggestedFixes: fixes,\n\t\tRelated: related,\n\t\t// Analysis diagnostics do not contain tags.\n\t}, nil\n}", "func newInjection() *injection {\n\treturn &injection{\n\t\tmarkerSQLs: map[injectionMarker][]string{},\n\t}\n}", "func AdvicesReplacer(locale, entry, response, _ string) (string, string) {\n\n\tresp, err := http.Get(adviceURL)\n\tif err != nil {\n\t\tresponseTag := \"no advices\"\n\t\treturn responseTag, util.GetMessage(locale, responseTag)\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tresponseTag := \"no advices\"\n\t\treturn responseTag, util.GetMessage(locale, responseTag)\n\t}\n\n\tvar result map[string]interface{}\n\tjson.Unmarshal(body, &result)\n\tadvice := result[\"slip\"].(map[string]interface{})[\"advice\"]\n\n\treturn AdvicesTag, fmt.Sprintf(response, advice)\n}", "func bindEnvs(iface interface{}, parts ...string) {\n\tifv := reflect.ValueOf(iface)\n\tift := reflect.TypeOf(iface)\n\tfor i := 0; i < ift.NumField(); i++ {\n\t\tv := ifv.Field(i)\n\t\tt := ift.Field(i)\n\t\ttv, ok := t.Tag.Lookup(\"mapstructure\")\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tswitch v.Kind() {\n\t\tcase reflect.Struct:\n\t\t\tbindEnvs(v.Interface(), append(parts, tv)...)\n\t\tdefault:\n\t\t\tviper.BindEnv(strings.Join(append(parts, tv), \".\"))\n\t\t}\n\t}\n}", "func reflect(fragment string) string {\n words := strings.Split(fragment, \" \")\n for i, word := range words {\n if Reflections, ok := Reflections[word]; ok {\n words[i] = Reflections\n }\n }\n return strings.Join(words, \" \")\n}", "func AutoG(w http.ResponseWriter, req *http.Request) {\n\tvar frase Frase\n\t_ = json.NewDecoder(req.Body).Decode(&frase)\n\tfraseNooized := \"\"\n\trand.Seed(time.Now().UnixNano())\n\tnum := rand.Intn(3)\n\tswitch num {\n\tcase 0:\n\t\tfraseNooized = NDecorator(frase.Testo)\n\tcase 1:\n\t\tfraseNooized = GDecorator(frase.Testo)\n\tdefault:\n\t\tfraseNooized = EDecorator(frase.Testo)\n\t}\n\tjson.NewEncoder(w).Encode(fraseNooized)\n}", "func (s *SidecarInjectField) Inject(pod *corev1.Pod) {\n\tlog.Info(fmt.Sprintf(\"inject pod : %s\", pod.GenerateName))\n\t// add initcontrainers to spec\n\tif pod.Spec.InitContainers != nil {\n\t\tpod.Spec.InitContainers = append(pod.Spec.InitContainers, s.Initcontainer)\n\t} else {\n\t\tpod.Spec.InitContainers = []corev1.Container{s.Initcontainer}\n\t}\n\n\t// add volume to spec\n\tif pod.Spec.Volumes == nil {\n\t\tpod.Spec.Volumes = []corev1.Volume{}\n\t}\n\tpod.Spec.Volumes = append(pod.Spec.Volumes, s.SidecarVolume)\n\n\t// choose a specific container to inject\n\ttargetContainers := s.findInjectContainer(pod.Spec.Containers)\n\n\t// add volumemount and env to container\n\tfor i := range targetContainers {\n\t\tlog.Info(fmt.Sprintf(\"inject container : %s\", targetContainers[i].Name))\n\t\tif (*targetContainers[i]).VolumeMounts == nil {\n\t\t\t(*targetContainers[i]).VolumeMounts = []corev1.VolumeMount{}\n\t\t}\n\n\t\t(*targetContainers[i]).VolumeMounts = append((*targetContainers[i]).VolumeMounts, s.SidecarVolumeMount)\n\n\t\tif (*targetContainers[i]).Env != nil {\n\t\t\t(*targetContainers[i]).Env = append((*targetContainers[i]).Env, s.Env)\n\t\t} else {\n\t\t\t(*targetContainers[i]).Env = []corev1.EnvVar{s.Env}\n\t\t}\n\n\t\t// envs to be append\n\t\tvar envsTBA []corev1.EnvVar\n\t\tfor j, envInject := range s.Envs {\n\t\t\tisExists := false\n\t\t\tfor _, envExists := range targetContainers[i].Env {\n\t\t\t\tif strings.EqualFold(envExists.Name, envInject.Name) {\n\t\t\t\t\tisExists = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !isExists {\n\t\t\t\tenvsTBA = append(envsTBA, s.Envs[j])\n\t\t\t}\n\t\t}\n\t\tif len(s.Envs) > 0 {\n\t\t\t(*targetContainers[i]).Env = append((*targetContainers[i]).Env, envsTBA...)\n\t\t}\n\t}\n}", "func (compilerWrapper *CompilerWrapper) resolveAbiParamType(contractName string,\r\n typeStr string,\r\n aliases map[string]string,\r\n staticIntConsts *map[string]*big.Int) string {\r\n\r\n if IsArrayType(typeStr) {\r\n return compilerWrapper.resolveArrayTypeStaticIntConsts(contractName, typeStr, staticIntConsts)\r\n } else {\r\n return ResolveType(typeStr, aliases)\r\n }\r\n}", "func Connect(tag string, reference interface{}) (Injector, error) {\n\tinjector := injector{tag, reflect.Indirect(reflect.ValueOf(reference))}\n\treturn injector, injector.Inject(getFields(reference)...)\n}", "func findServiceInheritance(t *defs, svcOffset *serviceOffset, useAttr attrVal, hostname string, hgEnabled *attrVal , hgExcluded *attrVal, ID string, name string, vistedTemplate *attrVal) {\n // speed up lookup for the same inheritance chain\n for _, tmpl := range useAttr {\n // check if the template already been lookup for inheritance\n if !vistedTemplate.Has(tmpl){\n for _, def := range *t {\n if tmpl == def[\"name\"].ToString() {\n *vistedTemplate = append(*vistedTemplate, tmpl)\n if def.attrExist(\"host_name\") {\n if def[\"host_name\"].RegexHas(hostname){\n if def.attrExist(\"name\"){\n svcOffset.Add(\"tmplhostName\", ID, def[\"name\"].ToString())\n if def.attrExist(\"service_description\") {\n svcOffset.others.Add(def[\"service_description\"].ToString())\n }\n }else {\n svcOffset.Add(\"tmplhostName\", ID, def[\"service_description\"].ToString())\n }\n }\n if def[\"host_name\"].RegexHas(\"!\"+hostname){\n if def.attrExist(\"name\"){\n svcOffset.Add(\"tmplhostNameExcl\", ID, def[\"name\"].ToString())\n }else{\n svcOffset.Add(\"tmplhostNameExcl\", ID, def[\"service_description\"].ToString())\n }\n }\n }\n if def.attrExist(\"hostgroup_name\"){\n if def[\"hostgroup_name\"].HasAny(*hgEnabled...){\n if def.attrExist(\"name\"){\n svcOffset.Add(\"tmplhostgroupName\", ID, def[\"name\"].ToString())\n if def.attrExist(\"service_description\") {\n svcOffset.others.Add(def[\"service_description\"].ToString())\n }\n }else{\n svcOffset.Add(\"tmplhostgroupName\", ID, def[\"service_description\"].ToString())\n }\n }\n if def[\"hostgroup_name\"].HasAny(*hgExcluded...){\n if def.attrExist(\"name\"){\n svcOffset.Add(\"tmplhostgroupNameExcl\", ID, def[\"name\"].ToString())\n }else{\n svcOffset.Add(\"tmplhostgroupNameExcl\", ID, def[\"service_description\"].ToString())\n }\n }\n }\n if def.attrExist(\"use\") {\n findServiceInheritance(t , svcOffset , *def[\"use\"], hostname , hgEnabled, hgExcluded, ID, name, vistedTemplate)\n }\n break\n }\n }\n }\n }\n}", "func ExpandAbbreviations(template, abbreviations string) {\n\n}", "func (t *Taipan) bindFlags(ctx context.Context, cmd *cobra.Command) error {\n\tcollector := &gotils.ErrCollector{}\n\tb := func(flag *pflag.Flag, name string) {\n\t\tlog.Ctx(ctx).Trace().Str(\"flag\", flag.Name).Str(\"viper-name\", name).Msg(\"Binding flag\")\n\t\tcollector.Collect(t.v.BindPFlag(name, flag))\n\n\t\tenvVarSuffix := name\n\t\tif strings.ContainsAny(name, \"-.\") {\n\t\t\tenvVarSuffix = strings.NewReplacer(\"-\", \"_\", \".\", \"_\").Replace(name)\n\t\t}\n\n\t\tenvVarSuffix = strings.ToUpper(envVarSuffix)\n\t\tenvVar := fmt.Sprintf(\"%s_%s\", t.config.EnvironmentPrefix, envVarSuffix)\n\t\tlog.Ctx(ctx).Trace().Str(\"env-key\", envVar).Str(\"viper-name\", name).Msg(\"Binding environment\")\n\n\t\tcollector.Collect(t.v.BindEnv(name, envVar))\n\n\t\t// Apply the viper config value to the flag when the flag is not set and viper has a value\n\t\tif !flag.Changed && t.v.IsSet(name) {\n\t\t\tval := t.v.Get(name)\n\t\t\tcollector.Collect(cmd.Flags().Set(flag.Name, fmt.Sprintf(\"%v\", val)))\n\t\t}\n\t}\n\n\treplace := identity\n\tif t.config.NamespaceFlags {\n\t\treplacer := strings.NewReplacer(\"-\", \".\", \"_\", \".\")\n\t\treplace = replacer.Replace\n\t}\n\n\tcmd.Flags().VisitAll(func(f *pflag.Flag) {\n\t\tname := replace(f.Name)\n\n\t\tif t.config.PrefixCommands {\n\t\t\tprefix := prefix(cmd)\n\t\t\tfor _, p := range prefix {\n\t\t\t\talias := fmt.Sprintf(\"%s.%s\", p, name)\n\t\t\t\tb(f, alias)\n\t\t\t}\n\t\t}\n\n\t\tb(f, name)\n\t})\n\n\tif collector.HasErrors() {\n\t\treturn collector\n\t}\n\n\treturn nil\n}" ]
[ "0.61296785", "0.5149551", "0.4850799", "0.47487968", "0.46673915", "0.44889128", "0.4452262", "0.44432408", "0.44358099", "0.44134143", "0.43503362", "0.43301424", "0.4324857", "0.43207198", "0.4270548", "0.42602628", "0.425869", "0.425649", "0.42529112", "0.42438713", "0.42188358", "0.42141685", "0.41994244", "0.41947135", "0.41941774", "0.41940698", "0.41816735", "0.41756913", "0.41740984", "0.41641256", "0.41562235", "0.41242582", "0.41154313", "0.41023657", "0.40737808", "0.4067468", "0.40670443", "0.40613684", "0.4061049", "0.40546718", "0.4053674", "0.4049933", "0.4034684", "0.40337527", "0.40227175", "0.40185314", "0.40106186", "0.4007622", "0.40021145", "0.40018573", "0.3999768", "0.3998142", "0.39959064", "0.39944077", "0.39897314", "0.39897314", "0.39897314", "0.39897314", "0.39809662", "0.3976137", "0.3965891", "0.39529097", "0.39503893", "0.3949454", "0.39428008", "0.39409465", "0.39349908", "0.39306146", "0.39295295", "0.39284873", "0.39282256", "0.39278227", "0.39251047", "0.39244518", "0.3924136", "0.3919737", "0.39184526", "0.39180705", "0.39089775", "0.39071113", "0.39056405", "0.39054117", "0.3905208", "0.3904074", "0.39019206", "0.38928527", "0.3892732", "0.38924327", "0.38869646", "0.38856128", "0.38848478", "0.38842747", "0.38815728", "0.38811028", "0.387294", "0.3870656", "0.3870292", "0.3870138", "0.38673803", "0.38654825" ]
0.7187308
0
Fang Takes an IOC and removes the defanging stuff from it (converts to a fanged IOC).
func (ioc *IOC) Fang() *IOC { copy := *ioc ioc = &copy // String replace all defangs in our standard set if replacements, ok := defangReplacements[ioc.Type]; ok { for _, fangPair := range replacements { ioc.IOC = strings.ReplaceAll(ioc.IOC, fangPair.defanged, fangPair.fanged) } } // Regex replace everything from the fang replacements if replacements, ok := fangReplacements[ioc.Type]; ok { for _, regexReplacement := range replacements { // Offset is incase we shrink the string and need to offset locations offset := 0 // Get indexes of replacements and replace them toReplace := regexReplacement.pattern.FindAllStringIndex(ioc.IOC, -1) for _, location := range toReplace { // Update this found string startSize := len(ioc.IOC) ioc.IOC = ioc.IOC[0:location[0]-offset] + regexReplacement.replace + ioc.IOC[location[1]-offset:len(ioc.IOC)] // Update offset with how much the string shrunk (or grew) offset += startSize - len(ioc.IOC) } } } return ioc }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ioc *IOC) Defang() *IOC {\n\tcopy := *ioc\n\tioc = &copy\n\n\t// Just do a string replace on each\n\tif replacements, ok := defangReplacements[ioc.Type]; ok {\n\t\tfor _, fangPair := range replacements {\n\t\t\tioc.IOC = strings.ReplaceAll(ioc.IOC, fangPair.fanged, fangPair.defanged)\n\t\t}\n\t}\n\n\treturn ioc\n}", "func istioUninject(args []string, opts *options.Options) error {\n\tglooNS := opts.Metadata.Namespace\n\n\tclient := helpers.MustKubeClient()\n\t_, err := client.CoreV1().Namespaces().Get(opts.Top.Ctx, glooNS, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Remove gateway_proxy_sds cluster from the gateway-proxy configmap\n\tconfigMaps, err := client.CoreV1().ConfigMaps(glooNS).List(opts.Top.Ctx, metav1.ListOptions{})\n\tfor _, configMap := range configMaps.Items {\n\t\tif configMap.Name == gatewayProxyConfigMap {\n\t\t\t// Make sure we don't already have the gateway_proxy_sds cluster set up\n\t\t\terr := removeSdsCluster(&configMap)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = client.CoreV1().ConfigMaps(glooNS).Update(opts.Top.Ctx, &configMap, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tdeployments, err := client.AppsV1().Deployments(glooNS).List(opts.Top.Ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, deployment := range deployments.Items {\n\t\tif deployment.Name == \"gateway-proxy\" {\n\t\t\tcontainers := deployment.Spec.Template.Spec.Containers\n\n\t\t\t// Remove Sidecars\n\t\t\tsdsPresent := false\n\t\t\tistioPresent := false\n\t\t\tif len(containers) > 1 {\n\t\t\t\tfor i := len(containers) - 1; i >= 0; i-- {\n\t\t\t\t\tcontainer := containers[i]\n\t\t\t\t\tif container.Name == \"sds\" {\n\t\t\t\t\t\tsdsPresent = true\n\t\t\t\t\t\tcopy(containers[i:], containers[i+1:])\n\t\t\t\t\t\tcontainers = containers[:len(containers)-1]\n\t\t\t\t\t}\n\t\t\t\t\tif container.Name == \"istio-proxy\" {\n\t\t\t\t\t\tistioPresent = true\n\n\t\t\t\t\t\tcopy(containers[i:], containers[i+1:])\n\t\t\t\t\t\tcontainers = containers[:len(containers)-1]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !sdsPresent || !istioPresent {\n\t\t\t\treturn ErrMissingSidecars\n\t\t\t}\n\n\t\t\tdeployment.Spec.Template.Spec.Containers = containers\n\n\t\t\tremoveIstioVolumes(&deployment)\n\t\t\t_, err = client.AppsV1().Deployments(glooNS).Update(opts.Top.Ctx, &deployment, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn nil\n}", "func AutoUnpatch(f func()) {\n\tdefer popPatchStack()\n\taddPatchStack()\n\tf()\n}", "func clean(isa *isabellebot.Bot) {\n\tisa.Service.Event.Clean()\n\tisa.Service.Trade.Clean()\n\tisa.Service.User.Clean()\n}", "func UnLimbo(x Interface) {\n ref_str := x.(ref.Interface).Ref()\n if sptr, isIn := Limbo[ref_str]; isIn {\n x.SetDescPage(sptr)\n delete(Limbo, ref_str)\n }\n}", "func ClearRefactorings() {\n\trefactorings = map[string]refactoring.Refactoring{}\n\trefactoringsInOrder = []string{}\n}", "func (self *dependencies) remove(definition string) {\n for index, dependency := range *self {\n if dependency == definition {\n (*self) = append((*self)[:index], (*self)[index+1:]...)\n }\n }\n}", "func (b *Bzr) Clean(d *Dependency) {\n\treturn\n}", "func (rign *CFGoReadIgnore) Clean() {\n}", "func elimDeadAutosGeneric(f *Func) {\n\taddr := make(map[*Value]GCNode) // values that the address of the auto reaches\n\telim := make(map[*Value]GCNode) // values that could be eliminated if the auto is\n\tused := make(map[GCNode]bool) // used autos that must be kept\n\n\t// visit the value and report whether any of the maps are updated\n\tvisit := func(v *Value) (changed bool) {\n\t\targs := v.Args\n\t\tswitch v.Op {\n\t\tcase OpAddr, OpLocalAddr:\n\t\t\t// Propagate the address if it points to an auto.\n\t\t\tn, ok := v.Aux.(GCNode)\n\t\t\tif !ok || n.StorageClass() != ClassAuto {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif addr[v] == nil {\n\t\t\t\taddr[v] = n\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t\treturn\n\t\tcase OpVarDef, OpVarKill:\n\t\t\t// v should be eliminated if we eliminate the auto.\n\t\t\tn, ok := v.Aux.(GCNode)\n\t\t\tif !ok || n.StorageClass() != ClassAuto {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif elim[v] == nil {\n\t\t\t\telim[v] = n\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t\treturn\n\t\tcase OpVarLive:\n\t\t\t// Don't delete the auto if it needs to be kept alive.\n\n\t\t\t// We depend on this check to keep the autotmp stack slots\n\t\t\t// for open-coded defers from being removed (since they\n\t\t\t// may not be used by the inline code, but will be used by\n\t\t\t// panic processing).\n\t\t\tn, ok := v.Aux.(GCNode)\n\t\t\tif !ok || n.StorageClass() != ClassAuto {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !used[n] {\n\t\t\t\tused[n] = true\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t\treturn\n\t\tcase OpStore, OpMove, OpZero:\n\t\t\t// v should be eliminated if we eliminate the auto.\n\t\t\tn, ok := addr[args[0]]\n\t\t\tif ok && elim[v] == nil {\n\t\t\t\telim[v] = n\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t\t// Other args might hold pointers to autos.\n\t\t\targs = args[1:]\n\t\t}\n\n\t\t// The code below assumes that we have handled all the ops\n\t\t// with sym effects already. Sanity check that here.\n\t\t// Ignore Args since they can't be autos.\n\t\tif v.Op.SymEffect() != SymNone && v.Op != OpArg {\n\t\t\tpanic(\"unhandled op with sym effect\")\n\t\t}\n\n\t\tif v.Uses == 0 && v.Op != OpNilCheck || len(args) == 0 {\n\t\t\t// Nil check has no use, but we need to keep it.\n\t\t\treturn\n\t\t}\n\n\t\t// If the address of the auto reaches a memory or control\n\t\t// operation not covered above then we probably need to keep it.\n\t\t// We also need to keep autos if they reach Phis (issue #26153).\n\t\tif v.Type.IsMemory() || v.Type.IsFlags() || v.Op == OpPhi || v.MemoryArg() != nil {\n\t\t\tfor _, a := range args {\n\t\t\t\tif n, ok := addr[a]; ok {\n\t\t\t\t\tif !used[n] {\n\t\t\t\t\t\tused[n] = true\n\t\t\t\t\t\tchanged = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// Propagate any auto addresses through v.\n\t\tnode := GCNode(nil)\n\t\tfor _, a := range args {\n\t\t\tif n, ok := addr[a]; ok && !used[n] {\n\t\t\t\tif node == nil {\n\t\t\t\t\tnode = n\n\t\t\t\t} else if node != n {\n\t\t\t\t\t// Most of the time we only see one pointer\n\t\t\t\t\t// reaching an op, but some ops can take\n\t\t\t\t\t// multiple pointers (e.g. NeqPtr, Phi etc.).\n\t\t\t\t\t// This is rare, so just propagate the first\n\t\t\t\t\t// value to keep things simple.\n\t\t\t\t\tused[n] = true\n\t\t\t\t\tchanged = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif node == nil {\n\t\t\treturn\n\t\t}\n\t\tif addr[v] == nil {\n\t\t\t// The address of an auto reaches this op.\n\t\t\taddr[v] = node\n\t\t\tchanged = true\n\t\t\treturn\n\t\t}\n\t\tif addr[v] != node {\n\t\t\t// This doesn't happen in practice, but catch it just in case.\n\t\t\tused[node] = true\n\t\t\tchanged = true\n\t\t}\n\t\treturn\n\t}\n\n\titerations := 0\n\tfor {\n\t\tif iterations == 4 {\n\t\t\t// give up\n\t\t\treturn\n\t\t}\n\t\titerations++\n\t\tchanged := false\n\t\tfor _, b := range f.Blocks {\n\t\t\tfor _, v := range b.Values {\n\t\t\t\tchanged = visit(v) || changed\n\t\t\t}\n\t\t\t// keep the auto if its address reaches a control value\n\t\t\tfor _, c := range b.ControlValues() {\n\t\t\t\tif n, ok := addr[c]; ok && !used[n] {\n\t\t\t\t\tused[n] = true\n\t\t\t\t\tchanged = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !changed {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Eliminate stores to unread autos.\n\tfor v, n := range elim {\n\t\tif used[n] {\n\t\t\tcontinue\n\t\t}\n\t\t// replace with OpCopy\n\t\tv.SetArgs1(v.MemoryArg())\n\t\tv.Aux = nil\n\t\tv.AuxInt = 0\n\t\tv.Op = OpCopy\n\t}\n}", "func React(inputPolymer *string) {\n\tfor {\n\n\t\tmatch := parta.FindAllStringIndex(*inputPolymer, 1)\n\t\tif len(match) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif *debug2 {\n\t\t\tfmt.Printf(\"Removed %s at [%d:%d] -> \", (*inputPolymer)[match[0][0]:match[0][1]], match[0][0], match[0][1])\n\t\t}\n\t\t*inputPolymer = strings.Replace(*inputPolymer, (*inputPolymer)[match[0][0]:match[0][1]], \"\", 1)\n\t\tif *debug2 {\n\t\t\tfmt.Printf(\"New string is %s\\n\", *inputPolymer)\n\t\t}\n\t}\n\tif *debug2 {\n\t\tfmt.Printf(\"Final string is %s\\n\", *inputPolymer)\n\t}\n}", "func removeArraiInfo(scope rel.Scope) rel.Scope {\n\troot, _ := scope.Get(\"//\")\n\trootTuple, _ := root.(rel.Tuple)\n\n\tarrai, _ := rootTuple.Get(\"arrai\")\n\tarraiTuple, _ := arrai.(rel.Tuple)\n\n\treturn scope.With(\"//\", rootTuple.With(\"arrai\", arraiTuple.Without(\"info\")))\n}", "func (l *Libvirt) InterfaceUndefine(Iface Interface) (err error) {\n\tvar buf []byte\n\n\targs := InterfaceUndefineArgs {\n\t\tIface: Iface,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\n\t_, err = l.requestStream(132, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (f *Forest) cleanup(overshoot uint64) {\n\tfor p := f.numLeaves; p < f.numLeaves+overshoot; p++ {\n\t\tdelete(f.positionMap, f.data.read(p).Mini()) // clear position map\n\t\t// TODO ^^^^ that probably does nothing\n\t\tf.data.write(p, empty) // clear forest\n\t}\n}", "func (rp *CFGoReadPackage) Clean() {\n\trp.first = true\n}", "func Uninject(opts *options.Options, optionsFunc ...cliutils.OptionsFunc) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"uninject\",\n\t\tShort: \"Remove SDS & istio-proxy sidecars from gateway-proxy pod\",\n\t\tLong: \"Removes the istio-proxy sidecar from the gateway-proxy pod. \" +\n\t\t\t\"Also removes the sds sidecar from the gateway-proxy pod. \" +\n\t\t\t\"Also removes the gateway_proxy_sds cluster from the gateway-proxy envoy bootstrap ConfigMap.\",\n\t\tPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nil\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\terr := istioUninject(args, opts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tcliutils.ApplyOptions(cmd, optionsFunc)\n\treturn cmd\n}", "func (da *DrugAllergy) Unwrap() *DrugAllergy {\n\ttx, ok := da.config.driver.(*txDriver)\n\tif !ok {\n\t\tpanic(\"ent: DrugAllergy is not a transactional entity\")\n\t}\n\tda.config.driver = tx.drv\n\treturn da\n}", "func FixDirt() {\n\tfixDirt()\n}", "func (rc *ReferencedComponents) Clean(used UsedReferences) {\n\tvar cleaned []ReferencedComponent\n\tfor _, v := range rc.Refs {\n\t\tfor k := range used.Refs {\n\t\t\tif v.Component.Id == k {\n\t\t\t\tcleaned = append(cleaned, v)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\trc.Refs = cleaned\n}", "func (self *PhysicsP2) RemoveSpringI(args ...interface{}) *PhysicsP2Spring{\n return &PhysicsP2Spring{self.Object.Call(\"removeSpring\", args)}\n}", "func TempDI(name string) (di DI, clean func(), err error) {\n\thdir, err := homedir.Dir()\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to determine homedir\")\n\t}\n\n\tkcfg, err := clientcmd.BuildConfigFromFlags(\"\", filepath.Join(hdir, \".kube\", \"config\"))\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to build config form kube config\")\n\t}\n\n\tif !strings.Contains(fmt.Sprintf(\"%#v\", kcfg), \"minikube\") {\n\t\treturn nil, nil, ErrMinikubeOnly\n\t}\n\n\tval := validator.New()\n\tval.RegisterValidation(\"is-abs-path\", ValidateAbsPath)\n\n\ttdi := &tmpDI{\n\t\tlogs: logrus.New(),\n\t\tval: val,\n\t}\n\n\ttdi.kube, err = kubernetes.NewForConfig(kcfg)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create kube client from config\")\n\t}\n\n\ttdi.crd, err = crd.NewForConfig(kcfg)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create CRD client from config\")\n\t}\n\n\tif name == \"\" {\n\t\td := make([]byte, 16)\n\t\t_, err = rand.Read(d)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.Wrap(err, \"failed to read random bytes\")\n\t\t}\n\n\t\tname = hex.EncodeToString(d)\n\t}\n\n\tns, err := tdi.kube.CoreV1().Namespaces().Create(&v1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{GenerateName: name},\n\t})\n\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create temporary namespace\")\n\t}\n\n\ttdi.ns = ns.GetName()\n\treturn tdi, func() {\n\t\terr := tdi.kube.CoreV1().Namespaces().Delete(ns.Name, nil)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}, nil\n}", "func containerNuke() {\n\t// walk CGROUP_PATH for tasks, killing each one\n\tif _, err := os.Stat(CGROUP_PATH); err == nil {\n\t\terr := filepath.Walk(CGROUP_PATH, containerNukeWalker)\n\t\tif err != nil {\n\t\t\tlog.Errorln(err)\n\t\t}\n\t}\n\n\t// Allow udev to sync\n\ttime.Sleep(time.Second * 1)\n\n\t// umount megamount_*, this include overlayfs mounts\n\td, err := ioutil.ReadFile(\"/proc/mounts\")\n\tif err != nil {\n\t\tlog.Errorln(err)\n\t} else {\n\t\tmounts := strings.Split(string(d), \"\\n\")\n\t\tfor _, m := range mounts {\n\t\t\tif strings.Contains(m, \"megamount\") {\n\t\t\t\tmount := strings.Split(m, \" \")[1]\n\t\t\t\tif err := syscall.Unmount(mount, 0); err != nil {\n\t\t\t\t\tlog.Error(\"overlay unmount %s: %v\", m, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\terr = containerCleanCgroupDirs()\n\tif err != nil {\n\t\tlog.Errorln(err)\n\t}\n\n\t// umount cgroup_root\n\terr = syscall.Unmount(CGROUP_ROOT, 0)\n\tif err != nil {\n\t\tlog.Error(\"cgroup_root unmount: %v\", err)\n\t}\n\n\t// remove meganet_* from /var/run/netns\n\tif _, err := os.Stat(\"/var/run/netns\"); err == nil {\n\t\tnetns, err := ioutil.ReadDir(\"/var/run/netns\")\n\t\tif err != nil {\n\t\t\tlog.Errorln(err)\n\t\t} else {\n\t\t\tfor _, n := range netns {\n\t\t\t\tif strings.Contains(n.Name(), \"meganet\") {\n\t\t\t\t\terr := os.Remove(filepath.Join(\"/var/run/netns\", n.Name()))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorln(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func cgounimpl() {\n\tthrow(\"cgo not implemented\")\n}", "func (cd *circularDependency) pop() {\n\t//log.Println(\"Removing:\", cd.Dependents[len(cd.Dependents)-1])\n\tcd.dependents = cd.dependents[:len(cd.dependents)-1]\n}", "func (bt *BloodType) Unwrap() *BloodType {\n\ttx, ok := bt.config.driver.(*txDriver)\n\tif !ok {\n\t\tpanic(\"ent: BloodType is not a transactional entity\")\n\t}\n\tbt.config.driver = tx.drv\n\treturn bt\n}", "func (fs fakeService) Globber() *rpc.GlobState {\n\tlog.Printf(\"Fake Service Globber???\")\n\treturn nil\n}", "func (ridt *CFGoReadLexUnit) Clean() {\n}", "func (r *LocalRegistry) moveToDangling(name *core.PackageName) {\n\t// get the package repository\n\trepo := r.findRepository(name)\n\t// get the package in the repository\n\tp := r.FindPackageByName(name)\n\t// get the dangling artefact repository\n\tdangRepo := r.findDanglingRepo()\n\t// remove the package from the original repository\n\trepo.Packages = rmPackage(repo.Packages, p)\n\t// change the package tag to none\n\tp.Tags = []string{\"<none>\"}\n\t// add the package to the dangling repo\n\tdangRepo.Packages = append(dangRepo.Packages, p)\n}", "func (plugin *FIBConfigurator) clearMapping() {\n\tplugin.fibIndexes.Clear()\n\tplugin.addCacheIndexes.Clear()\n\tplugin.delCacheIndexes.Clear()\n}", "func serviceClean(svc corev1.Service) corev1.Service {\n\tsvc.Spec.ExternalIPs = []string{}\n\tsvc.Spec.LoadBalancerIP = \"\"\n\tsvc.Spec.LoadBalancerSourceRanges = []string{}\n\tsvc.Spec.ExternalName = \"\"\n\tsvc.Status.LoadBalancer = corev1.LoadBalancerStatus{}\n\treturn svc\n}", "func (d *Release) rebase(with []string) {\n\tif len(with) == 0 {\n\t\treturn\n\t}\n\t// Converts variable names in map of deploy keys.\n\tonly := make(map[string]struct{})\n\tfor _, name := range with {\n\t\tfor _, ev1 := range d.env1 {\n\t\t\tfor _, ev2 := range d.env2 {\n\t\t\t\tpid := string(d.ref.Key())\n\t\t\t\tonly[Key(pid, ev1, ev2, name)] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\t// Cleans the source by removing all the data to ignore.\n\tfor k := range d.src {\n\t\tif _, ok := only[k]; !ok {\n\t\t\tdelete(d.src, k)\n\t\t}\n\t}\n}", "func (self *PhysicsP2) ClearI(args ...interface{}) {\n self.Object.Call(\"clear\", args)\n}", "func (fe ForbiddenChange) Unwrap() error {\n\treturn fe.UndError\n}", "func (i *IContainer) Clear() {\n\ti.mutex.Lock()\n\tdefer i.mutex.Unlock()\n\n\ti.data = make(map[string]*injectionDef)\n}", "func cleanUmociMetadata(bundlePath string) error {\n\tents, err := ioutil.ReadDir(bundlePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, ent := range ents {\n\t\tif ent.Name() == \"rootfs\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tos.Remove(path.Join(bundlePath, ent.Name()))\n\t}\n\n\treturn nil\n}", "func toGobDiagnostic(posToLocation func(start, end token.Pos) (protocol.Location, error), a *analysis.Analyzer, diag analysis.Diagnostic) (gobDiagnostic, error) {\n\tvar fixes []gobSuggestedFix\n\tfor _, fix := range diag.SuggestedFixes {\n\t\tvar gobEdits []gobTextEdit\n\t\tfor _, textEdit := range fix.TextEdits {\n\t\t\tloc, err := posToLocation(textEdit.Pos, textEdit.End)\n\t\t\tif err != nil {\n\t\t\t\treturn gobDiagnostic{}, fmt.Errorf(\"in SuggestedFixes: %w\", err)\n\t\t\t}\n\t\t\tgobEdits = append(gobEdits, gobTextEdit{\n\t\t\t\tLocation: loc,\n\t\t\t\tNewText: textEdit.NewText,\n\t\t\t})\n\t\t}\n\t\tfixes = append(fixes, gobSuggestedFix{\n\t\t\tMessage: fix.Message,\n\t\t\tTextEdits: gobEdits,\n\t\t})\n\t}\n\n\tvar related []gobRelatedInformation\n\tfor _, r := range diag.Related {\n\t\tloc, err := posToLocation(r.Pos, r.End)\n\t\tif err != nil {\n\t\t\treturn gobDiagnostic{}, fmt.Errorf(\"in Related: %w\", err)\n\t\t}\n\t\trelated = append(related, gobRelatedInformation{\n\t\t\tLocation: loc,\n\t\t\tMessage: r.Message,\n\t\t})\n\t}\n\n\tloc, err := posToLocation(diag.Pos, diag.End)\n\tif err != nil {\n\t\treturn gobDiagnostic{}, err\n\t}\n\n\t// The Code column of VSCode's Problems table renders this\n\t// information as \"Source(Code)\" where code is a link to CodeHref.\n\t// (The code field must be nonempty for anything to appear.)\n\tdiagURL := effectiveURL(a, diag)\n\tcode := \"default\"\n\tif diag.Category != \"\" {\n\t\tcode = diag.Category\n\t}\n\n\treturn gobDiagnostic{\n\t\tLocation: loc,\n\t\t// Severity for analysis diagnostics is dynamic,\n\t\t// based on user configuration per analyzer.\n\t\tCode: code,\n\t\tCodeHref: diagURL,\n\t\tSource: a.Name,\n\t\tMessage: diag.Message,\n\t\tSuggestedFixes: fixes,\n\t\tRelated: related,\n\t\t// Analysis diagnostics do not contain tags.\n\t}, nil\n}", "func deleteLoopbackIntf(inParams *XfmrParams, loName *string) error {\n var err error\n intTbl := IntfTypeTblMap[IntfTypeLoopback]\n subOpMap := make(map[db.DBNum]map[string]map[string]db.Value)\n resMap := make(map[string]map[string]db.Value)\n loMap := make(map[string]db.Value)\n\n loMap[*loName] = db.Value{Field:map[string]string{}}\n\n IntfMapObj, err := inParams.d.GetMapAll(&db.TableSpec{Name:intTbl.cfgDb.portTN + \"|\" + *loName})\n if err != nil || !IntfMapObj.IsPopulated() {\n errStr := \"Retrieving data from LOOPBACK_INTERFACE table for Loopback: \" + *loName + \" failed!\"\n log.Errorf(errStr)\n return tlerr.InvalidArgsError{Format:errStr}\n }\n /* If L3 config exist, return error */\n ipKeys, err := doGetIntfIpKeys(inParams.d, intTbl.cfgDb.intfTN, *loName)\n if err != nil {\n log.Errorf(\"Get for IP keys failed, err:%v\", err)\n return tlerr.InvalidArgsError{Format:err.Error()}\n }\n if (len(ipKeys)) > 0 {\n l3ErrStr := \"IP Configuration exists for Loopback: \" + *loName\n return tlerr.InvalidArgsError{Format:l3ErrStr}\n }\n IntfMap := IntfMapObj.Field\n if len(IntfMap) > 1 {\n if log.V(3) {\n log.Infof(\"Existing entries in LOOPBACK_INTERFACE|%s: %v\", *loName, IntfMap)\n }\n l3ErrStr := \"L3 config exists in LOOPBACK_INTERFACE table for Loopback: \" + *loName\n return tlerr.InvalidArgsError{Format:l3ErrStr}\n }\n\n resMap[intTbl.cfgDb.intfTN] = loMap\n\n subOpMap[db.ConfigDB] = resMap\n inParams.subOpDataMap[DELETE] = &subOpMap\n return nil\n}", "func revertCNIBackup() error {\n\treturn filepath.Walk(cniPath,\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !info.Mode().IsRegular() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif !strings.HasSuffix(path, \".cilium_bak\") {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\torigFileName := strings.TrimSuffix(path, \".cilium_bak\")\n\t\t\treturn os.Rename(path, origFileName)\n\t\t})\n}", "func Clean(c Config) {\n\n\tSetup(&c)\n\tContainers, _ := model.DockerContainerList()\n\n\tfor _, Container := range Containers {\n\t\ttarget := false\n\t\tif l := Container.Labels[\"pygmy.enable\"]; l == \"true\" || l == \"1\" {\n\t\t\ttarget = true\n\t\t}\n\t\tif l := Container.Labels[\"pygmy\"]; l == \"pygmy\" {\n\t\t\ttarget = true\n\t\t}\n\n\t\tif target {\n\t\t\terr := model.DockerKill(Container.ID)\n\t\t\tif err == nil {\n\t\t\t\tfmt.Printf(\"Successfully killed %v.\\n\", Container.Names[0])\n\t\t\t}\n\n\t\t\terr = model.DockerRemove(Container.ID)\n\t\t\tif err == nil {\n\t\t\t\tfmt.Printf(\"Successfully removed %v.\\n\", Container.Names[0])\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, network := range c.Networks {\n\t\tmodel.DockerNetworkRemove(&network)\n\t\tif s, _ := model.DockerNetworkStatus(&network); s {\n\t\t\tfmt.Printf(\"Successfully removed network %v\\n\", network.Name)\n\t\t} else {\n\t\t\tfmt.Printf(\"Network %v was not removed\\n\", network.Name)\n\t\t}\n\t}\n\n\tfor _, resolver := range c.Resolvers {\n\t\tresolver.Clean()\n\t}\n}", "func Fix[T any](h Interface[T], i int) {\n\tif !down(h, i, h.Len()) {\n\t\tup(h, i)\n\t}\n}", "func (rg *CFGoReadGlobals) Clean() {\n\trg.first = true\n\trg.goBatchGlobals = nil\n\trg.mutiStatus = mutiStatusUnknown\n\trg.lleftPNum = 0\n\trg.varType = \"\"\n\trg.gName = \"\"\n\trg.gCode = nil\n\trg.lleftCNum = 0\n}", "func (si *ServiceInfo) Unwrap() *ServiceInfo {\n\ttx, ok := si.config.driver.(*txDriver)\n\tif !ok {\n\t\tpanic(\"ent: ServiceInfo is not a transactional entity\")\n\t}\n\tsi.config.driver = tx.drv\n\treturn si\n}", "func (m *resmgr) stopIntrospection() {\n\tm.introspect.Stop()\n}", "func cleanupUpper(ctx context.Context, parent *Inode, name string) {\n\tif err := parent.InodeOperations.Remove(ctx, parent, name); err != nil {\n\t\t// Unfortunately we don't have much choice. We shouldn't\n\t\t// willingly give the caller access to a nonsense filesystem.\n\t\tpanic(fmt.Sprintf(\"overlay filesystem is in an inconsistent state: failed to remove %q from upper filesystem: %v\", name, err))\n\t}\n}", "func (d *Doctorinfo) Unwrap() *Doctorinfo {\n\ttx, ok := d.config.driver.(*txDriver)\n\tif !ok {\n\t\tpanic(\"ent: Doctorinfo is not a transactional entity\")\n\t}\n\td.config.driver = tx.drv\n\treturn d\n}", "func Uninstall() error { return mageextras.Uninstall(\"factorio\") }", "func (i *IntransitiveActivity) Clean() {\n\ti.BCC = nil\n\ti.Bto = nil\n}", "func (i *Interest) ClearForwardingHints() {\n\ti.forwardingHint = []Delegation{}\n\ti.wire = nil\n}", "func (m *mapReact) Clean() {\n\tm.ro.Lock()\n\tm.ma = make(map[SenderDetachCloser]bool)\n\tm.ro.Unlock()\n}", "func (st *ServiceType) Unwrap() *ServiceType {\n\ttx, ok := st.config.driver.(*txDriver)\n\tif !ok {\n\t\tpanic(\"ent: ServiceType is not a transactional entity\")\n\t}\n\tst.config.driver = tx.drv\n\treturn st\n}", "func (pa *Patient) Unwrap() *Patient {\n\ttx, ok := pa.config.driver.(*txDriver)\n\tif !ok {\n\t\tpanic(\"ent: Patient is not a transactional entity\")\n\t}\n\tpa.config.driver = tx.drv\n\treturn pa\n}", "func inheritFacts(act, dep *Action) {\n\tfor key, fact := range dep.objectFacts {\n\t\t// Filter out facts related to objects\n\t\t// that are irrelevant downstream\n\t\t// (equivalently: not in the compiler export data).\n\t\tif !exportedFrom(key.obj, dep.Pkg.GetTypes()) {\n\t\t\tcontinue\n\t\t}\n\t\tact.objectFacts[key] = fact\n\t}\n\n\tfor key, fact := range dep.packageFacts {\n\t\t// TODO: filter out facts that belong to\n\t\t// packages not mentioned in the export data\n\t\t// to prevent side channels.\n\n\t\tact.packageFacts[key] = fact\n\t}\n}", "func Demangle(prof *profile.Profile, force bool, demanglerMode string) {\n\tif force {\n\t\t// Remove the current demangled names to force demangling\n\t\tfor _, f := range prof.Function {\n\t\t\tif f.Name != \"\" && f.SystemName != \"\" {\n\t\t\t\tf.Name = f.SystemName\n\t\t\t}\n\t\t}\n\t}\n\n\toptions := demanglerModeToOptions(demanglerMode)\n\tfor _, fn := range prof.Function {\n\t\tdemangleSingleFunction(fn, options)\n\t}\n}", "func (plugin *BDConfigurator) ResolveDeletedInterface(interfaceName string) error {\n\tplugin.Log.Infof(\"Interface %v was removed. Unregister from real state \", interfaceName)\n\t// Lookup IfToBdIndexes in order to find a bridge domain for this interface (if exists)\n\t_, meta, found := plugin.IfToBdIndexes.LookupIdx(interfaceName)\n\tif !found {\n\t\tplugin.Log.Debugf(\"Removed interface %s does not belong to any bridge domain\", interfaceName)\n\t\treturn nil\n\t}\n\tbdID := meta.(*BridgeDomainMeta).BridgeDomainIndex\n\t// Find bridge domain name\n\tbdName, meta, found := plugin.BdIndexes.LookupName(bdID)\n\tif !found {\n\t\treturn fmt.Errorf(\"unknown bridge domain ID %v\", bdID)\n\t}\n\t// If interface belonging to a bridge domain is removed, VPP handles internal bridge domain update itself. However\n\t// the etcd operational state still needs to be updated to reflect changed VPP state\n\terr := plugin.LookupBridgeDomainDetails(bdID, bdName)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Unregister removed interface from real state\n\tplugin.IfToBdRealStateIdx.UnregisterName(interfaceName)\n\n\treturn nil\n}", "func (g *GlobalVar) TurnCafAppOff() error {\n\tg.IsCafAppRunning = false\n\treturn g.Save()\n}", "func cfi(g *Graph) (Graph, error) {\n\tcfig, err := buildGraph(false)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t//**make an array with all the Cfi Gadgets**//\n\tvar gadgets map[Vertex]Cfigadget\n\tgadgets = make(map[Vertex]Cfigadget)\n\n\t//number the vertices in the original graphs\n\tvertcount := 1\n\n\t//the current vertcount will be the key for a vertex of the new graph\n\tvar nodekeys map[int]Vertex\n\tnodekeys = make(map[int]Vertex)\n\n\tfor node, value := range g.vertices {\n\t\tif value {\n\t\t\tdeg, err := g.degree(node)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\t//Make a new Gadget\n\t\t\tgadget := Cfigadget{\n\t\t\t\touter: make([]Vertex, 2*deg),\n\t\t\t\tinner: make([]Vertex, int(math.Exp2(float64(deg-1)))),\n\t\t\t\tref: &node,\n\t\t\t\tdegree: deg,\n\t\t\t\tedges: make([]Edge, deg*int(math.Exp2(float64(deg-1)))),\n\t\t\t\tneighbours: make([]Vertex, deg),\n\t\t\t}\n\n\t\t\tgadget.neighbours, err = g.neighbourhood(node)\n\n\t\t\t//insert actual vertices into the gadget\n\t\t\tfor ind := range gadget.inner {\n\t\t\t\tgadget.inner[ind] = Vertex{vert: vertcount}\n\t\t\t\tnodekeys[vertcount] = gadget.inner[ind]\n\t\t\t\tvertcount++\n\t\t\t}\n\t\t\tfor ind := range gadget.outer {\n\t\t\t\tgadget.outer[ind] = Vertex{vert: vertcount}\n\t\t\t\tnodekeys[vertcount] = gadget.outer[ind]\n\t\t\t\tvertcount++\n\t\t\t}\n\n\t\t\t//just somewhere to save the number of edges to\n\t\t\tedgecount := 0\n\n\t\t\t//Build the gadget\n\t\t\tmax := int(math.Exp2(float64(deg)))\n\t\t\tinnercount := 0 //tells how many of the inner vertices have been used\n\t\t\tfor i := 0; i < max; i++ {\n\t\t\t\tcur := i\n\n\t\t\t\t//save the calculated bits\n\t\t\t\tvar bits []int\n\t\t\t\tbits = make([]int, deg)\n\n\t\t\t\t//number of 1s in the binary representation of the number\n\t\t\t\tones := 0\n\n\t\t\t\t//calculate binary representation\n\t\t\t\tfor j := 0; j < deg; j++ {\n\t\t\t\t\tif cur&1 == 1 {\n\t\t\t\t\t\tones++\n\t\t\t\t\t\tbits[j] = 1\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbits[j] = 0\n\t\t\t\t\t}\n\t\t\t\t\tcur = cur >> 1\n\t\t\t\t}\n\n\t\t\t\t//with an even number of ones, connect the vertices\n\t\t\t\tif ones%2 == 0 {\n\t\t\t\t\tfor ind := 0; ind < deg; ind++ {\n\t\t\t\t\t\toutbit := ((ind + 1) * 2) / 2 //which of the outer bits is controlled\n\n\t\t\t\t\t\tif bits[outbit-1] == 0 { //connect to b vertices\n\t\t\t\t\t\t\toutvertex := ind*2 + 1\n\t\t\t\t\t\t\tgadget.edges[edgecount] = Edge{\n\t\t\t\t\t\t\t\tfrom: gadget.outer[outvertex],\n\t\t\t\t\t\t\t\tto: gadget.inner[innercount],\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else { //connect to a vertices\n\t\t\t\t\t\t\toutvertex := ind * 2\n\t\t\t\t\t\t\tgadget.edges[edgecount] = Edge{\n\t\t\t\t\t\t\t\tfrom: gadget.outer[outvertex],\n\t\t\t\t\t\t\t\tto: gadget.inner[innercount],\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tedgecount++\n\t\t\t\t\t}\n\t\t\t\t\tinnercount++\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t//Save it to the map\n\t\t\tgadgets[node] = gadget\n\t\t}\n\t}\n\n\t//**build a graph from the gadgets**//\n\n\t//add inner and outer vertices (the content of nodekeys) to the graph\n\tfor _, v := range nodekeys {\n\t\tcfig.vertices[v] = true\n\t\tcfig.numvert++\n\t}\n\n\t//add the known edges from within the gadgets\n\tfor _, gadget := range gadgets {\n\t\tfor _, e := range gadget.edges {\n\t\t\tcfig.addEdge(e.from, e.to)\n\t\t}\n\t}\n\n\t//connect the gadgets\n\tfor e := range g.edges {\n\t\tedgefrom := e.from\n\t\tedgeto := e.to\n\t\tgadgetfrom := gadgets[edgefrom]\n\t\tgadgetto := gadgets[edgeto]\n\n\t\tneighbournofrom := 0 //number of the to-neighbour in the \"from\" gadget\n\t\tneighbournoto := 0 //number of the from-neighbour in the \"to\" gadget\n\n\t\tfor ind, n := range gadgetfrom.neighbours {\n\t\t\tif n == edgeto {\n\t\t\t\tneighbournofrom = ind\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tfor ind, n := range gadgetto.neighbours {\n\t\t\tif n == edgefrom {\n\t\t\t\tneighbournoto = ind\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tcfig.addEdge(gadgetfrom.outer[2*neighbournofrom], gadgetto.outer[2*neighbournoto])\n\t\tcfig.addEdge(gadgetfrom.outer[2*neighbournofrom+1], gadgetto.outer[2*neighbournoto+1])\n\t}\n\n\t//cfig.printGraph()\n\treturn cfig, nil\n}", "func (d *Diagnosis) Unwrap() *Diagnosis {\n\ttx, ok := d.config.driver.(*txDriver)\n\tif !ok {\n\t\tpanic(\"ent: Diagnosis is not a transactional entity\")\n\t}\n\td.config.driver = tx.drv\n\treturn d\n}", "func (m *PatientMutation) ResetAllergic() {\n\tm._Allergic = nil\n}", "func goConvInvoc(a ClientArg) string {\n\tjsonConvTmpl := `\nvar {{.GoArg}} {{.GoType}}\nif {{.FlagArg}} != nil && len(*{{.FlagArg}}) > 0 {\n\terr = json.Unmarshal([]byte(*{{.FlagArg}}), &{{.GoArg}})\n\tif err != nil {\n\t\tpanic(errors.Wrapf(err, \"unmarshalling {{.GoArg}} from %v:\", {{.FlagArg}}))\n\t}\n}\n`\n\tif a.Repeated || !a.IsBaseType {\n\t\tcode, err := applyTemplate(\"UnmarshalCliArgs\", jsonConvTmpl, a, nil)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Couldn't apply template: %v\", err))\n\t\t}\n\t\treturn code\n\t}\n\treturn fmt.Sprintf(`%s := %s`, a.GoArg, flagTypeConversion(a))\n}", "func (opt *OperationTracker) Clean(op *Operation) {\n\tcidStr := op.Cid().String()\n\n\topt.mu.Lock()\n\tdefer opt.mu.Unlock()\n\top2, ok := opt.operations[cidStr]\n\tif ok && op == op2 { // same pointer\n\t\tdelete(opt.operations, cidStr)\n\t}\n}", "func (b *DrawList) Clean() {\r\n\t*b = (*b)[:0]\r\n}", "func (c *common) clean() error {\n\tvar err error\n\n\tif len(c.flags.clean) == 0 {\n\t\treturn nil\n\t}\n\n\targs := append(c.flags.global, c.flags.clean...)\n\n\terr = shared.RunCommand(c.ctx, nil, nil, c.commands.clean, args...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.hooks.clean != nil {\n\t\terr = c.hooks.clean()\n\t}\n\n\treturn err\n}", "func (o Outside) Fix(ctx context.Context, c *github.Client, owner, repo string) error {\n\tlog.Warn().\n\t\tStr(\"org\", owner).\n\t\tStr(\"repo\", repo).\n\t\tStr(\"area\", polName).\n\t\tMsg(\"Action fix is configured, but not implemented.\")\n\treturn nil\n}", "func ClearFactory() {\n\tfactory = nil\n}", "func Defun(opname string, funcBody Mapper, quoter Mapper, env *Environment) {\n\topsym := GlobalEnvironment.Intern(opname, false)\n\topsym.Value = Atomize(&internalOp{sym: opsym, caller: funcBody, quoter: quoter})\n\tT().Debugf(\"new interal op %s = %v\", opsym.Name, opsym.Value)\n}", "func MakeFoilHopper(commonHopper1 *Hopper, commonHopper2 *Hopper, commonHopper3 *Hopper, sources ...[]Card) *FoilHopper {\n\tret := FoilHopper{OtherHoppers: []*Hopper{commonHopper1, commonHopper2, commonHopper3}}\n\tfor _, cardList := range sources {\n\t\tfor _, v := range cardList {\n\t\t\tvar copiedCard Card\n\t\t\tcopiedCard = v // this copies???\n\t\t\tcopiedCard.Foil = true\n\t\t\tret.Source = append(ret.Source, copiedCard)\n\t\t}\n\t}\n\tret.Refill()\n\treturn &ret\n}", "func cleanupDesc(desc string) string {\n\tif *debug {\n\t\tfmt.Printf(\"Desc FROM: %s\\n\", desc)\n\t}\n\td := descGarbage.ReplaceAllLiteralString(desc, \"\")\n\tif d != \"\" {\n\t\tdesc = d\n\t}\n\tdesc = strings.Replace(desc, \"--\", \" \", 1)\n\t// desc = descRemoveSymbols.ReplaceAllLiteralString(desc, \" \")\n\tdesc = normalizeWhitespace(desc)\n\tdesc = dedupDescription(desc)\n\tif *debug {\n\t\tfmt.Printf(\"Desc TO : %s\\n\\n\", desc)\n\t}\n\treturn desc\n}", "func (ioc *IOC) IsFanged() bool {\n\tif ioc.Type == Bitcoin ||\n\t\tioc.Type == MD5 ||\n\t\tioc.Type == SHA1 ||\n\t\tioc.Type == SHA256 ||\n\t\tioc.Type == SHA512 ||\n\t\tioc.Type == File ||\n\t\tioc.Type == CVE {\n\t\treturn false\n\t}\n\n\t// Basically just check if the fanged version is different from the input\n\t// This does label a partially fanged IOC is NOT fanged. I.e https://exampe[.]test.com/url is labled as NOT fanged\n\tif ioc.Fang().IOC == ioc.IOC {\n\t\t// They are equal, it's fanged\n\t\treturn true\n\t}\n\treturn false\n}", "func Replace(node Node, visitor func(Node) Node) {\n\tswitch n := node.(type) {\n\tcase *Abort:\n\tcase *API:\n\t\tfor i, c := range n.Enums {\n\t\t\tn.Enums[i] = visitor(c).(*Enum)\n\t\t}\n\t\tfor i, c := range n.Definitions {\n\t\t\tn.Definitions[i] = visitor(c).(*Definition)\n\t\t}\n\t\tfor i, c := range n.Classes {\n\t\t\tn.Classes[i] = visitor(c).(*Class)\n\t\t}\n\t\tfor i, c := range n.Pseudonyms {\n\t\t\tn.Pseudonyms[i] = visitor(c).(*Pseudonym)\n\t\t}\n\t\tfor i, c := range n.Externs {\n\t\t\tn.Externs[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Subroutines {\n\t\t\tn.Subroutines[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Functions {\n\t\t\tn.Functions[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Methods {\n\t\t\tn.Methods[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Globals {\n\t\t\tn.Globals[i] = visitor(c).(*Global)\n\t\t}\n\t\tfor i, c := range n.StaticArrays {\n\t\t\tn.StaticArrays[i] = visitor(c).(*StaticArray)\n\t\t}\n\t\tfor i, c := range n.Maps {\n\t\t\tn.Maps[i] = visitor(c).(*Map)\n\t\t}\n\t\tfor i, c := range n.Pointers {\n\t\t\tn.Pointers[i] = visitor(c).(*Pointer)\n\t\t}\n\t\tfor i, c := range n.Slices {\n\t\t\tn.Slices[i] = visitor(c).(*Slice)\n\t\t}\n\t\tfor i, c := range n.References {\n\t\t\tn.References[i] = visitor(c).(*Reference)\n\t\t}\n\t\tfor i, c := range n.Signatures {\n\t\t\tn.Signatures[i] = visitor(c).(*Signature)\n\t\t}\n\tcase *ArrayAssign:\n\t\tn.To = visitor(n.To).(*ArrayIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *ArrayIndex:\n\t\tn.Array = visitor(n.Array).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *ArrayInitializer:\n\t\tn.Array = visitor(n.Array).(Type)\n\t\tfor i, c := range n.Values {\n\t\t\tn.Values[i] = visitor(c).(Expression)\n\t\t}\n\tcase *Slice:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *SliceIndex:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *SliceAssign:\n\t\tn.To = visitor(n.To).(*SliceIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *Assert:\n\t\tn.Condition = visitor(n.Condition).(Expression)\n\tcase *Assign:\n\t\tn.LHS = visitor(n.LHS).(Expression)\n\t\tn.RHS = visitor(n.RHS).(Expression)\n\tcase *Annotation:\n\t\tfor i, c := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(c).(Expression)\n\t\t}\n\tcase *Block:\n\t\tfor i, c := range n.Statements {\n\t\t\tn.Statements[i] = visitor(c).(Statement)\n\t\t}\n\tcase BoolValue:\n\tcase *BinaryOp:\n\t\tif n.LHS != nil {\n\t\t\tn.LHS = visitor(n.LHS).(Expression)\n\t\t}\n\t\tif n.RHS != nil {\n\t\t\tn.RHS = visitor(n.RHS).(Expression)\n\t\t}\n\tcase *BitTest:\n\t\tn.Bitfield = visitor(n.Bitfield).(Expression)\n\t\tn.Bits = visitor(n.Bits).(Expression)\n\tcase *UnaryOp:\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *Branch:\n\t\tn.Condition = visitor(n.Condition).(Expression)\n\t\tn.True = visitor(n.True).(*Block)\n\t\tif n.False != nil {\n\t\t\tn.False = visitor(n.False).(*Block)\n\t\t}\n\tcase *Builtin:\n\tcase *Reference:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *Call:\n\t\tn.Type = visitor(n.Type).(Type)\n\t\tn.Target = visitor(n.Target).(*Callable)\n\t\tfor i, a := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(a).(Expression)\n\t\t}\n\tcase *Callable:\n\t\tif n.Object != nil {\n\t\t\tn.Object = visitor(n.Object).(Expression)\n\t\t}\n\t\tn.Function = visitor(n.Function).(*Function)\n\tcase *Case:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, c := range n.Conditions {\n\t\t\tn.Conditions[i] = visitor(c).(Expression)\n\t\t}\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase *Cast:\n\t\tn.Object = visitor(n.Object).(Expression)\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Class:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, f := range n.Fields {\n\t\t\tn.Fields[i] = visitor(f).(*Field)\n\t\t}\n\t\tfor i, m := range n.Methods {\n\t\t\tn.Methods[i] = visitor(m).(*Function)\n\t\t}\n\tcase *ClassInitializer:\n\t\tfor i, f := range n.Fields {\n\t\t\tn.Fields[i] = visitor(f).(*FieldInitializer)\n\t\t}\n\tcase *Choice:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, c := range n.Conditions {\n\t\t\tn.Conditions[i] = visitor(c).(Expression)\n\t\t}\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *Definition:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *DefinitionUsage:\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\t\tn.Definition = visitor(n.Definition).(*Definition)\n\tcase *DeclareLocal:\n\t\tn.Local = visitor(n.Local).(*Local)\n\t\tif n.Local.Value != nil {\n\t\t\tn.Local.Value = visitor(n.Local.Value).(Expression)\n\t\t}\n\tcase Documentation:\n\tcase *Enum:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, e := range n.Entries {\n\t\t\tn.Entries[i] = visitor(e).(*EnumEntry)\n\t\t}\n\tcase *EnumEntry:\n\tcase *Fence:\n\t\tif n.Statement != nil {\n\t\t\tn.Statement = visitor(n.Statement).(Statement)\n\t\t}\n\tcase *Field:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Type = visitor(n.Type).(Type)\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(Expression)\n\t\t}\n\tcase *FieldInitializer:\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase Float32Value:\n\tcase Float64Value:\n\tcase *Function:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tif n.Return != nil {\n\t\t\tn.Return = visitor(n.Return).(*Parameter)\n\t\t}\n\t\tfor i, c := range n.FullParameters {\n\t\t\tn.FullParameters[i] = visitor(c).(*Parameter)\n\t\t}\n\t\tif n.Block != nil {\n\t\t\tn.Block = visitor(n.Block).(*Block)\n\t\t}\n\t\tn.Signature = visitor(n.Signature).(*Signature)\n\tcase *Global:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\tcase *StaticArray:\n\t\tn.ValueType = visitor(n.ValueType).(Type)\n\t\tn.SizeExpr = visitor(n.SizeExpr).(Expression)\n\tcase *Signature:\n\tcase Int8Value:\n\tcase Int16Value:\n\tcase Int32Value:\n\tcase Int64Value:\n\tcase *Iteration:\n\t\tn.Iterator = visitor(n.Iterator).(*Local)\n\t\tn.From = visitor(n.From).(Expression)\n\t\tn.To = visitor(n.To).(Expression)\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase *MapIteration:\n\t\tn.IndexIterator = visitor(n.IndexIterator).(*Local)\n\t\tn.KeyIterator = visitor(n.KeyIterator).(*Local)\n\t\tn.ValueIterator = visitor(n.ValueIterator).(*Local)\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase Invalid:\n\tcase *Length:\n\t\tn.Object = visitor(n.Object).(Expression)\n\tcase *Local:\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Map:\n\t\tn.KeyType = visitor(n.KeyType).(Type)\n\t\tn.ValueType = visitor(n.ValueType).(Type)\n\tcase *MapAssign:\n\t\tn.To = visitor(n.To).(*MapIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *MapContains:\n\t\tn.Key = visitor(n.Key).(Expression)\n\t\tn.Map = visitor(n.Map).(Expression)\n\tcase *MapIndex:\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *MapRemove:\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Key = visitor(n.Key).(Expression)\n\tcase *MapClear:\n\t\tn.Map = visitor(n.Map).(Expression)\n\tcase *Member:\n\t\tn.Object = visitor(n.Object).(Expression)\n\t\tn.Field = visitor(n.Field).(*Field)\n\tcase *MessageValue:\n\t\tfor i, a := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(a).(*FieldInitializer)\n\t\t}\n\tcase *New:\n\t\tn.Type = visitor(n.Type).(*Reference)\n\tcase *Parameter:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Pointer:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *Pseudonym:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.To = visitor(n.To).(Type)\n\t\tfor i, m := range n.Methods {\n\t\t\tn.Methods[i] = visitor(m).(*Function)\n\t\t}\n\tcase *Return:\n\t\tif n.Value != nil {\n\t\t\tn.Value = visitor(n.Value).(Expression)\n\t\t}\n\tcase *Select:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tfor i, c := range n.Choices {\n\t\t\tn.Choices[i] = visitor(c).(*Choice)\n\t\t}\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(Expression)\n\t\t}\n\tcase StringValue:\n\tcase *Switch:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tfor i, c := range n.Cases {\n\t\t\tn.Cases[i] = visitor(c).(*Case)\n\t\t}\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(*Block)\n\t\t}\n\tcase Uint8Value:\n\tcase Uint16Value:\n\tcase Uint32Value:\n\tcase Uint64Value:\n\tcase *Unknown:\n\tcase *Clone:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *Copy:\n\t\tn.Src = visitor(n.Src).(Expression)\n\t\tn.Dst = visitor(n.Dst).(Expression)\n\tcase *Create:\n\t\tn.Type = visitor(n.Type).(*Reference)\n\t\tn.Initializer = visitor(n.Initializer).(*ClassInitializer)\n\tcase *Ignore:\n\tcase *Make:\n\t\tn.Type = visitor(n.Type).(*Slice)\n\t\tn.Size = visitor(n.Size).(Expression)\n\tcase Null:\n\tcase *PointerRange:\n\t\tn.Pointer = visitor(n.Pointer).(Expression)\n\t\tn.Range = visitor(n.Range).(*BinaryOp)\n\tcase *Read:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *SliceContains:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *SliceRange:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\t\tn.Range = visitor(n.Range).(*BinaryOp)\n\tcase *Write:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tdefault:\n\t\tpanic(fmt.Errorf(\"Unsupported semantic node type %T\", n))\n\t}\n}", "func (ouo *OrganUpdateOne) RemoveForogan(s ...*Spaciality) *OrganUpdateOne {\n\tids := make([]int, len(s))\n\tfor i := range s {\n\t\tids[i] = s[i].ID\n\t}\n\treturn ouo.RemoveForoganIDs(ids...)\n}", "func (t *MorphTargets) Cleanup(a *app.App) {}", "func (self *Manager) fixupChildren(placeHolder *PlaceHolder, logger Logger) {\n\tname := logger.GetName()\n\tfor e := placeHolder.Loggers.Front(); e != nil; e = e.Next() {\n\t\tl, _ := e.Value.(Logger)\n\t\tparent := l.GetParent()\n\t\tif !strings.HasPrefix(parent.GetName(), name) {\n\t\t\tlogger.SetParent(parent)\n\t\t\tl.SetParent(logger)\n\t\t}\n\t}\n}", "func (ft *FieldType) Unwrap() *FieldType {\n\t_tx, ok := ft.config.driver.(*txDriver)\n\tif !ok {\n\t\tpanic(\"ent: FieldType is not a transactional entity\")\n\t}\n\tft.config.driver = _tx.drv\n\treturn ft\n}", "func removeApInterface(iface string) error {\n\tcmd := exec.Command(\"iw\", \"dev\", iface, \"del\")\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := cmd.Wait(); err != nil {\n\t\treturn nil\n\t}\n\n\treturn nil\n}", "func (f *animalFactory) UnsetFactory() {\n\tmutex.Lock()\n\tf.createAnimalFactoryPtr = createAnimalFactoryDefault\n\tmutex.Unlock()\n}", "func (t *SimpleChaincode)RemovePartFromAs(stub shim.ChaincodeStubInterface, args []string)([]byte, error) {\n\tkey := args[0]\n\tidpart := args[1]\n// Debut Partie Assembly \n\tac,err:=findAssemblyById(stub,key)\n\t\tif(err !=nil){return nil,err}\n\tptAS1, _ := json.Marshal(ac)\n\tvar airc Assembly\n\t\terr = json.Unmarshal(ptAS1, &airc)\n\t\tif err != nil {return nil, errors.New(\"Failed to Unmarshal Part #\" + key)}\n\tfor i, v := range airc.Parts{\n\t\t\tif v == idpart {\n\t\t\t\tairc.Parts = append(airc.Parts[:i], airc.Parts[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t\t\t}\n\tvar tx LogAssembly\n\t\ttx.Responsible = airc.Responsible\n\t\ttx.Owner \t\t= airc.Owner\n\t\ttx.LType \t\t= \"PART_REMOVAL\"\n\t\ttx.Description = idpart + \" has been removed from this Assembly\" \n\t\ttx.VDate\t\t= args [2]\n\t\tairc.Logs = append(airc.Logs, tx)\n\ty:= UpdateAssembly (stub, airc) \n\t\tif y != nil { return nil, errors.New(y.Error())}\n// Fin Partie Assembly \n// Debut Partie Part\t\n\tpart,err:=findPartById(stub,idpart)\n\t\tif err != nil {return nil, errors.New(\"Failed to get part #\" + key)}\n\tptAS, _ := json.Marshal(part)\n\t\tvar pt Part\n\t\terr = json.Unmarshal(ptAS, &pt)\n\t\tif err != nil {return nil, errors.New(\"Failed to Unmarshal Part #\" + key)}\n\t\tpt.Assembly = \"\"\n\t\tpt.Owner = \"REMOVAL_MANAGER\"\n\t\tpt.Responsible = \"REMOVAL_MANAGER\"\n\tvar tf Log\n\t\ttf.Responsible\t= pt.Responsible\n\t\ttf.Owner \t\t= pt.Owner\n\t\ttf.LType \t\t= \"ASSEMBLY_REMOVAL\"\n\t\ttf.Description = \"REMOVED FROM ASSEMBLY: \" + key + \" This part has been transfered to \" + pt.Responsible + \", the new Owner & Responsible\"\n\t\ttf.VDate\t\t= args [2]\n\tpt.Logs = append(pt.Logs, tf)\n\te:= UpdatePart (stub, pt) \n\t\tif e != nil { return nil, errors.New(e.Error())}\n// Fin Partie Part\t\nreturn nil, nil\n}", "func (t *SimpleChaincode)ReplacePartOnAssembly(stub shim.ChaincodeStubInterface, args []string)([]byte, error) {\n\t\n\tkey := args[0] \t\t\t\t// L'id de l'Assembly\n\tidpart := args[1] \t\t\t\t// L'id de l'ancien Part \n\tidpart1 := args[2] \t\t\t\t// L'id du nouveau part \n// Debut Partie Assembly \n\t\tac,err:=findAssemblyById(stub,key)\n\t\tif(err !=nil){return nil,err}\n\t\tptAS1, _ := json.Marshal(ac)\n\tvar airc Assembly\n\t\terr = json.Unmarshal(ptAS1, &airc)\n\t\tif err != nil {return nil, errors.New(\"Failed to Unmarshal Part #\" + key)}\n\t\tairc.Parts = append(airc.Parts, idpart1)\t\n\tfor i, v := range airc.Parts{\n\t\t\tif v == idpart {\n\t\t\t\tairc.Parts = append(airc.Parts[:i], airc.Parts[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t\t\t}\n\tvar tx LogAssembly\n\t\ttx.Responsible = airc.Responsible\n\t\ttx.Owner \t\t= airc.Owner\n\t\ttx.LType \t\t= \"PART_SUBSTITUTION\"\n\t\ttx.Description = \"PART_SUBSTITUTION : \" + idpart1 + \" replace \" + idpart\n\t\ttx.VDate\t\t= args [3]\n\t\tairc.Logs = append(airc.Logs, tx)\n\ty:= UpdateAssembly (stub, airc) \n\t\tif y != nil { return nil, errors.New(y.Error())}\n// Fin Partie Assembly \n// Debut Partie Part\t\n\t\tpart,err:=findPartById(stub,idpart)\n\t\tif err != nil {return nil, errors.New(\"Failed to get part #\" + key)}\n\t\tptAS, _ := json.Marshal(part)\n\tvar pt Part\n\t\terr = json.Unmarshal(ptAS, &pt)\n\t\tif err != nil {return nil, errors.New(\"Failed to Unmarshal Part #\" + key)}\n\tpartt,err:=findPartById(stub,idpart1)\n\t\tif err != nil {return nil, errors.New(\"Failed to get part #\" + key)}\n\t\tptASS, _ := json.Marshal(partt)\n\tvar ptt Part\n\t\terr = json.Unmarshal(ptASS, &ptt)\n\t\tif err != nil {return nil, errors.New(\"Failed to Unmarshal Part #\" + key)}\n\t\tptt.Assembly = key\n\t\tptt.Owner = airc.Owner \n\t\tptt.Responsible = pt.Responsible\n\t\tptt.Helicopter = pt.Helicopter\n\t\tptt.PN = pt.PN\n\tvar tff Log\n\t\ttff.Responsible = ptt.Responsible\n\t\ttff.Owner \t\t= ptt.Owner\n\t\ttff.LType \t\t= \"ASSEMBLY_AFFILIATION\"\n\t\ttff.Description = \"AFFILIATED TO ASSEMBLY \" + key + \" AND SUBSTITUTES PART: \" + idpart\n\t\ttff.VDate \t\t= args [3]\n\t\tptt.Logs = append(ptt.Logs, tff)\n\tr:= UpdatePart (stub, ptt) \n\t\tif r != nil { return nil, errors.New(r.Error())}\n\t\t\n\t\tpt.Assembly = \"\" // Le champ Assembly de la part retirée de l'Assembly revient à nul.\n\t\tpt.Owner = \"REMOVAL_MANAGER\" \n\t\tpt.Responsible = \"REMOVAL_MANAGER\"\n\tvar tf Log\n\t\ttf.Responsible = pt.Responsible\n\t\ttf.Owner \t\t= pt.Owner\n\t\ttf.LType \t\t= \"ASSEMBLY_REMOVAL\"\n\t\ttf.Description = \"REMOVED FROM ASSEMBLY \" + key + \" SUBSTITUTED BY PART: \" + idpart1 + \" This part has been transfered to \" + pt.Owner + \", the new Owner. \"\n\t\ttf.VDate \t\t= args [3]\n\t\tpt.Logs = append(pt.Logs, tf)\n\te:= UpdatePart (stub, pt) \n\t\tif e != nil { return nil, errors.New(e.Error())}\t\n// Fin Partie Part \nfmt.Println(\"Responsible created successfully\")\t\nreturn nil, nil\n}", "func (f *OCIPuller) PullOCIChart(ociFullName string) (*bytes.Buffer, string, error) {\n\tif f.ExpectedName != \"\" && f.ExpectedName != ociFullName {\n\t\treturn nil, \"\", fmt.Errorf(\"expecting %s got %s\", f.ExpectedName, ociFullName)\n\t}\n\treturn f.Content, f.Checksum, f.Err\n}", "func (plugin *FIBConfigurator) ResolveDeletedInterface(ifName string, ifIdx uint32, callback func(error)) error {\n\tplugin.log.Infof(\"FIB configurator: resolving unregistered interface %s\", ifName)\n\n\tcount := plugin.resolveUnRegisteredItem(ifName, \"\")\n\n\tplugin.log.Infof(\"%d FIB entries belongs to removed interface %s. These FIBs cannot be deleted or changed while interface is missing\",\n\t\tcount, ifName)\n\n\treturn nil\n}", "func (b bindingContainer) RemoveInterface(i string) {\n\tdelete(b, i)\n}", "func (ou *OrganUpdate) RemoveForogan(s ...*Spaciality) *OrganUpdate {\n\tids := make([]int, len(s))\n\tfor i := range s {\n\t\tids[i] = s[i].ID\n\t}\n\treturn ou.RemoveForoganIDs(ids...)\n}", "func (obj *GenericObject) ClearSoftPatches(ctx context.Context) error {\n\terr := obj.RPC(ctx, \"ClearSoftPatches\", nil)\n\treturn err\n}", "func (d *Driver) Clean(id string) error {\n\treturn nil\n}", "func clean(g *Game) {\n\tfor i := range g.gameBoard {\n\t\tg.gameBoard[i] = 0\n\t}\n}", "func FinalizeBPFFSMigration(bpffsPath string, coll *ebpf.CollectionSpec, revert bool) error {\n\tif coll == nil {\n\t\treturn errors.New(\"can't migrate a nil CollectionSpec\")\n\t}\n\n\tfor name, spec := range coll.Maps {\n\t\t// Skip map specs without the pinning flag. Also takes care of skipping .data,\n\t\t// .rodata and .bss.\n\t\t// Don't unpin existing maps if their new versions are missing the pinning flag.\n\t\tif spec.Pinning == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := finalizeMap(bpffsPath, name, revert); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func revertInitialisms(s string) string {\n\tfor i := 0; i < len(commonInitialisms); i++ {\n\t\ts = strings.ReplaceAll(s, commonInitialisms[i][0], commonInitialisms[i][1])\n\t}\n\treturn s\n}", "func dontChangeMe(p animal) {\n\n\tp.name = \"New name\"\n\tp.age = 99\n}", "func frobnicate(in io.Reader, modifications []modification) (*bytes.Buffer, error) {\n\tdecoder := xml.NewDecoder(bufio.NewReader(in))\n\n\tvar outbytes bytes.Buffer\n\tout := xml.NewEncoder(&outbytes)\n\tvar previousWasStart bool\n\tvar path bytes.Buffer\n\tfor {\n\t\ttok, err := decoder.RawToken()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog.Fatalf(\"Unexpected error while parsing XML file: %v\", err)\n\t\t}\n\t\tswitch tok := tok.(type) {\n\t\tcase xml.StartElement:\n\t\t\tpath.WriteByte('/')\n\t\t\tpath.WriteString(tok.Name.Local)\n\n\t\t\tfor _, pat := range modifications {\n\t\t\t\tif path.String() == pat.path {\n\t\t\t\t\tfor i, attr := range tok.Attr {\n\t\t\t\t\t\tif attr.Name.Local == pat.attribute {\n\t\t\t\t\t\t\ttok.Attr[i].Value = pat.value\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\tpreviousWasStart = true\n\t\t\tif err := out.EncodeToken(tok); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\tcase xml.EndElement:\n\t\t\tpath.Truncate(bytes.LastIndexByte(path.Bytes(), '/'))\n\n\t\t\tif previousWasStart {\n\t\t\t\t// hack: Replace <foo></foo> with self-closing tags <foo/>\n\t\t\t\t// https://groups.google.com/forum/#!topic/golang-nuts/guG6iOCRu08\n\t\t\t\tif err := out.Flush(); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tif outbytes.Bytes()[outbytes.Len()-1] != '>' {\n\t\t\t\t\tpanic(\"expected > token as last byte in output\")\n\t\t\t\t}\n\t\t\t\tpos := outbytes.Len() - 1\n\n\t\t\t\t// Encode end element so the encoder is not confused..\n\t\t\t\tif err := out.EncodeToken(tok); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tif err := out.Flush(); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t// Back track to before end element and final >\n\t\t\t\toutbytes.Truncate(pos)\n\t\t\t\toutbytes.WriteString(\"/>\")\n\t\t\t} else {\n\t\t\t\tif err := out.EncodeToken(tok); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tpreviousWasStart = false\n\n\t\tdefault:\n\t\t\tpreviousWasStart = false\n\t\t\tif err := out.EncodeToken(tok); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &outbytes, out.Flush()\n}", "func (d *Drug) Unwrap() *Drug {\n\ttx, ok := d.config.driver.(*txDriver)\n\tif !ok {\n\t\tpanic(\"ent: Drug is not a transactional entity\")\n\t}\n\td.config.driver = tx.drv\n\treturn d\n}", "func (x *fastReflection_ServiceCommandDescriptor) Clear(fd protoreflect.FieldDescriptor) {\n\tswitch fd.FullName() {\n\tcase \"cosmos.autocli.v1.ServiceCommandDescriptor.service\":\n\t\tx.Service = \"\"\n\tcase \"cosmos.autocli.v1.ServiceCommandDescriptor.rpc_command_options\":\n\t\tx.RpcCommandOptions = nil\n\tcase \"cosmos.autocli.v1.ServiceCommandDescriptor.sub_commands\":\n\t\tx.SubCommands = nil\n\tcase \"cosmos.autocli.v1.ServiceCommandDescriptor.enhance_custom_command\":\n\t\tx.EnhanceCustomCommand = false\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.autocli.v1.ServiceCommandDescriptor\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.autocli.v1.ServiceCommandDescriptor does not contain field %s\", fd.FullName()))\n\t}\n}", "func (fi *File) flushUp() error {\n\tnd, err := fi.mod.GetNode()\n\tif err != nil {\n\t\tfi.Unlock()\n\t\treturn err\n\t}\n\n\t_, err = fi.dserv.Add(nd)\n\tif err != nil {\n\t\tfi.Unlock()\n\t\treturn err\n\t}\n\n\t//name := fi.name\n\t//parent := fi.parent\n\n\t// explicit unlock *only* before closeChild call\n\tfi.Unlock()\n\treturn nil\n\t//return parent.closeChild(name, nd)\n}", "func (ot *ObjectType) Unwrap() *ObjectType {\n\ttx, ok := ot.config.driver.(*txDriver)\n\tif !ok {\n\t\tpanic(\"ent: ObjectType is not a transactional entity\")\n\t}\n\tot.config.driver = tx.drv\n\treturn ot\n}", "func gobFlattenRegister(t reflect.Type) {\n\tif t.Kind() == reflect.Interface {\n\t\treturn\n\t}\n\tfor t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\tpz := reflect.New(t)\n\tgob.Register(pz.Elem().Interface())\n}", "func (x *fastReflection_GenesisState) Clear(fd protoreflect.FieldDescriptor) {\n\tswitch fd.FullName() {\n\tcase \"cosmos.gov.v1.GenesisState.starting_proposal_id\":\n\t\tx.StartingProposalId = uint64(0)\n\tcase \"cosmos.gov.v1.GenesisState.deposits\":\n\t\tx.Deposits = nil\n\tcase \"cosmos.gov.v1.GenesisState.votes\":\n\t\tx.Votes = nil\n\tcase \"cosmos.gov.v1.GenesisState.proposals\":\n\t\tx.Proposals = nil\n\tcase \"cosmos.gov.v1.GenesisState.deposit_params\":\n\t\tx.DepositParams = nil\n\tcase \"cosmos.gov.v1.GenesisState.voting_params\":\n\t\tx.VotingParams = nil\n\tcase \"cosmos.gov.v1.GenesisState.tally_params\":\n\t\tx.TallyParams = nil\n\tcase \"cosmos.gov.v1.GenesisState.params\":\n\t\tx.Params = nil\n\tcase \"cosmos.gov.v1.GenesisState.constitution\":\n\t\tx.Constitution = \"\"\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.gov.v1.GenesisState\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.gov.v1.GenesisState does not contain field %s\", fd.FullName()))\n\t}\n}", "func (me *Container) ReSync() *Container {\n\tfor k, v := range globalContainerInstance.Container.bag {\n\t\tme.bag[k] = v\n\t}\n\n\treturn me\n}", "func (Bpf) Clean() error {\n\n\tfmt.Println(\"Removing directory\", bpfBuildPath, \"..\")\n\tif err := os.RemoveAll(bpfBuildPath); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Removing kernel configurations ..\")\n\tfor _, k := range kernel.Builds {\n\t\tp := path.Join(k.Directory(), \".config\")\n\t\tif mg.Verbose() {\n\t\t\tfmt.Println(\"Removing\", p, \"..\")\n\t\t}\n\t\tif err := os.RemoveAll(p); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (d *Dog) Reset() { d.Name = \"\" }", "func (wl *dummyLogger) Clean() {\n}", "func forcePanic() {\n\tpanic(\"picknicking... :)\")\n}", "func (g *Gate) ReplaceInput(from, to *Wire) {\n\tif g.A == from {\n\t\tg.A.RemoveOutput(g)\n\t\tto.AddOutput(g)\n\t\tg.A = to\n\t} else if g.B == from {\n\t\tg.B.RemoveOutput(g)\n\t\tto.AddOutput(g)\n\t\tg.B = to\n\t} else {\n\t\tpanic(fmt.Sprintf(\"%s is not input for gate %s\", from, g))\n\t}\n}" ]
[ "0.7177586", "0.50840104", "0.48262703", "0.48175362", "0.48002586", "0.4679298", "0.4660034", "0.4584422", "0.45685875", "0.45614737", "0.45376295", "0.44981825", "0.44849345", "0.44699618", "0.44661286", "0.44610918", "0.44461814", "0.4425764", "0.44216082", "0.44178298", "0.43932226", "0.43798316", "0.4364346", "0.43506628", "0.43428347", "0.43427163", "0.43393075", "0.4336956", "0.43295047", "0.43147218", "0.4309106", "0.4287944", "0.42851433", "0.42672455", "0.42633542", "0.42403805", "0.422482", "0.42219102", "0.4216493", "0.42100754", "0.42061603", "0.41996562", "0.41928086", "0.4186369", "0.4170579", "0.41642767", "0.416413", "0.41614768", "0.4160038", "0.41538918", "0.41524455", "0.41519186", "0.41515246", "0.41408935", "0.41351792", "0.41340867", "0.41278806", "0.41230363", "0.4120238", "0.41177195", "0.41171756", "0.4114428", "0.4106435", "0.41043633", "0.41002488", "0.40987396", "0.4091909", "0.40910992", "0.40907645", "0.4086928", "0.40774786", "0.4076401", "0.4067778", "0.40654933", "0.4063815", "0.40622145", "0.4056936", "0.40545064", "0.40538493", "0.40506548", "0.40493134", "0.40435413", "0.40423524", "0.403179", "0.40199655", "0.40095142", "0.40094945", "0.40040803", "0.4002896", "0.40005845", "0.39967152", "0.39955738", "0.39927164", "0.39920014", "0.39919654", "0.39911404", "0.39879736", "0.39875928", "0.3987443", "0.39781216" ]
0.68866414
1
IsFanged Takes an IOC and returns if it is fanged. Non fanging types (bitcoin, hashes, file, cve) are always determined to not be fanged
func (ioc *IOC) IsFanged() bool { if ioc.Type == Bitcoin || ioc.Type == MD5 || ioc.Type == SHA1 || ioc.Type == SHA256 || ioc.Type == SHA512 || ioc.Type == File || ioc.Type == CVE { return false } // Basically just check if the fanged version is different from the input // This does label a partially fanged IOC is NOT fanged. I.e https://exampe[.]test.com/url is labled as NOT fanged if ioc.Fang().IOC == ioc.IOC { // They are equal, it's fanged return true } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b Bet) IsForced() bool {\n\tswitch b.Type {\n\tcase bet.Ante, bet.BringIn, bet.SmallBlind, bet.BigBlind, bet.GuestBlind, bet.Straddle:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (me TxsdWorkType) IsFc() bool { return me.String() == \"FC\" }", "func (me TxsdWorkType) IsFo() bool { return me.String() == \"FO\" }", "func IsDuck(s interface{}) bool {\n\t_, ok := s.(Duck)\n\treturn ok\n}", "func (me TxsdInvoiceType) IsFs() bool { return me.String() == \"FS\" }", "func (gs *GaleShapely) isBetterThanFiance(man, woman, fiance int) bool {\n\tfor _, choice := range gs.womenWishes[woman] {\n\t\tswitch choice {\n\t\tcase man:\n\t\t\treturn true\n\t\tcase fiance:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (me TrefreshModeEnumType) IsOnChange() bool { return me == \"onChange\" }", "func (me TxsdInvoiceType) IsFt() bool { return me.String() == \"FT\" }", "func (me TxsdTaxAccountingBasis) IsF() bool { return me.String() == \"F\" }", "func (me TxsdInvoiceStatus) IsF() bool { return me.String() == \"F\" }", "func (f *Flapper) IsFlapping(service string, recompute bool) bool {\n\tif state, ok := f.services[service]; ok {\n\t\tif recompute {\n\t\t\tstate.Add(time.Now().Unix(), 0)\n\t\t}\n\t\treturn state.Total() >= int(f.max)\n\t}\n\treturn false\n}", "func (me TxsdMovementType) IsGd() bool { return me.String() == \"GD\" }", "func (i *Interest) MustBeFresh() bool {\n\treturn i.mustBeFresh\n}", "func mustFunc(c closed.Type) bool {\n\tswitch c.(type) {\n\tcase *closed.Interface, *closed.EmptySum:\n\t\treturn true\n\t}\n\treturn false\n}", "func (_BREMICO *BREMICOCaller) IsOverdue(opts *bind.CallOpts) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"isOverdue\")\n\treturn *ret0, err\n}", "func IsOrExtendsForgeFedTicketDependency(other vocab.Type) bool {\n\treturn typeticketdependency.IsOrExtendsTicketDependency(other)\n}", "func (me TrefreshModeEnumType) IsOnExpire() bool { return me == \"onExpire\" }", "func (e *Event) IsDownstream() bool {\n\treturn int32(e.GetType())&int32(EVENT_TYPE_DOWNSTREAM) != 0\n}", "func (*Component_Fan) IsYANGGoStruct() {}", "func (me TAttlistArticleDateDateType) IsElectronic() bool { return me.String() == \"Electronic\" }", "func (me TxsdMovementType) IsGc() bool { return me.String() == \"GC\" }", "func (me TxsdWorkStatus) IsF() bool { return me.String() == \"F\" }", "func (me TxsdMovementStatus) IsF() bool { return me.String() == \"F\" }", "func (me TAttlistCommentsCorrectionsRefType) IsErratumFor() bool { return me.String() == \"ErratumFor\" }", "func (me TitemIconStateEnumType) IsClosed() bool { return me == \"closed\" }", "func (me TxsdCounterSimpleContentExtensionType) IsFlow() bool { return me.String() == \"flow\" }", "func (b *OGame) IsDonutSystem() bool {\n\treturn b.isDonutSystem()\n}", "func (o *StoragePhysicalDiskAllOf) HasFdeCapable() bool {\n\tif o != nil && o.FdeCapable != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func ByTypeF(t typ.Type) func(Pokemon) bool {\n\treturn func(p Pokemon) bool {\n\t\treturn p.Type1() == t || p.Type2() == t\n\t}\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) IsDeposit(opts *bind.CallOpts, blockNum *big.Int) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"isDeposit\", blockNum)\n\treturn *ret0, err\n}", "func (me TxsdFeMorphologyTypeOperator) IsDilate() bool { return me.String() == \"dilate\" }", "func (b Bond) Interesting(f Filter) bool {\n\t// remove bonds with low coupon\n\tif b.Coupon < f.MinimumCoupon {\n\t\treturn false\n\t}\n\n\t// remove bonds with no date or more than 6 years of maturity\n\tmaximumMaturity := time.Now().Add(f.MaximumMaturity.Duration)\n\tif b.Maturity == nil || b.Maturity.After(maximumMaturity) {\n\t\treturn false\n\t}\n\n\t// remove bonds with low price or too expensive\n\tif b.LastPrice < f.MinimumPrice || b.LastPrice > f.MaximumPrice {\n\t\treturn false\n\t}\n\n\tif b.MinimumPiece < f.MinimumPiece || b.MinimumPiece > f.MaximumPiece {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (me TAttlistOtherIDSource) IsCpfh() bool { return me.String() == \"CPFH\" }", "func IsOrExtendsForgeFedBranch(other vocab.Type) bool {\n\treturn typebranch.IsOrExtendsBranch(other)\n}", "func (me TimePeriod) IsLifeToDate() bool { return me.String() == \"LifeToDate\" }", "func IsDefenseID(id int) bool {\n\treturn ID(id).IsDefense()\n}", "func (me TxsdFeTurbulenceTypeType) IsFractalNoise() bool { return me.String() == \"fractalNoise\" }", "func (o *W2) HasFederalIncomeTaxWithheld() bool {\n\tif o != nil && o.FederalIncomeTaxWithheld.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (*OpenconfigPlatform_Components_Component_Fan) IsYANGGoStruct() {}", "func IsOrExtendsForgeFedCommit(other vocab.Type) bool {\n\treturn typecommit.IsOrExtendsCommit(other)\n}", "func (me TitemIconStateEnumType) IsOpen() bool { return me == \"open\" }", "func (*NamedTypeDummy) isType() {}", "func (*Component_Chassis) IsYANGGoStruct() {}", "func (a *_Atom) isFunctional() bool {\n\tif a.atNum != 6 {\n\t\treturn true\n\t}\n\tif len(a.features) > 0 {\n\t\treturn true\n\t}\n\tif a.unsaturation > cmn.UnsaturationNone {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsFromCIPD(git string) bool {\n\treturn strings.Contains(git, \"cipd_bin_packages\")\n}", "func (el *gameStruct) IsForceField() bool {\n\treturn IsForceField(el.icon)\n}", "func (me TactionType) IsInvestigate() bool { return me.String() == \"investigate\" }", "func (*OnfTest1Choice_Vehicle) IsYANGGoStruct() {}", "func (me TxsdWithholdingTaxType) IsIs() bool { return me.String() == \"IS\" }", "func IsOrExtendsForgeFedTicket(other vocab.Type) bool {\n\treturn typeticket.IsOrExtendsTicket(other)\n}", "func IsOpen(err error) bool {\n\tfor err != nil {\n\t\tif bserr, ok := err.(stater); ok {\n\t\t\treturn bserr.State() == Open\n\t\t}\n\n\t\tif cerr, ok := err.(causer); ok {\n\t\t\terr = cerr.Cause()\n\t\t}\n\t}\n\treturn false\n}", "func (me TxsdInvoiceType) IsFr() bool { return me.String() == \"FR\" }", "func (*OnfTest1Choice_Vehicle_Battery) IsYANGGoStruct() {}", "func (deployment *Deployment) IsForce() bool {\n\tif force, ok := deployment.Flag(\"force\").(bool); ok {\n\t\treturn force\n\t} else {\n\t\treturn false\n\t}\n}", "func (me TviewRefreshModeEnumType) IsNever() bool { return me == \"never\" }", "func (x *fastReflection_LightClientAttackEvidence) Has(fd protoreflect.FieldDescriptor) bool {\n\tswitch fd.FullName() {\n\tcase \"tendermint.types.LightClientAttackEvidence.conflicting_block\":\n\t\treturn x.ConflictingBlock != nil\n\tcase \"tendermint.types.LightClientAttackEvidence.common_height\":\n\t\treturn x.CommonHeight != int64(0)\n\tcase \"tendermint.types.LightClientAttackEvidence.byzantine_validators\":\n\t\treturn len(x.ByzantineValidators) != 0\n\tcase \"tendermint.types.LightClientAttackEvidence.total_voting_power\":\n\t\treturn x.TotalVotingPower != int64(0)\n\tcase \"tendermint.types.LightClientAttackEvidence.timestamp\":\n\t\treturn x.Timestamp != nil\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: tendermint.types.LightClientAttackEvidence\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message tendermint.types.LightClientAttackEvidence does not contain field %s\", fd.FullName()))\n\t}\n}", "func (t *fsNotifyTrigger) Debounce() bool {\n\t// This trigger has built-in debouncing.\n\treturn false\n}", "func IsSafeClosed(\n\tt *testing.T, // : the T pointer\n\tds data.CXDS, // : ds already opened\n\treopen func() (data.CXDS, error), // : reopen ds to check the flag\n) {\n\t// IsSafeClosed() bool\n\n\tif ds.IsSafeClosed() == false {\n\t\tt.Error(\"fresh db is not safe closed\")\n\t}\n\n\tif reopen == nil {\n\t\treturn\n\t}\n\n\tvar err error\n\tif err = ds.Close(); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif ds, err = reopen(); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif ds.IsSafeClosed() == false {\n\t\tt.Error(\"not safe closed, after reopenning\")\n\t}\n\n}", "func (t Type) shouldFlush() bool {\n\tswitch t {\n\tcase TypeWebsocket, TypeTCP, TypeControlStream:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (*Component_Fabric) IsYANGGoStruct() {}", "func (del Delegation) IsFluidStakingActive() bool {\n\t// get the delegation fluid upgrade data\n\tfluid, err := del.repo.DelegationFluidStakingActive(&del.Delegation)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn fluid\n}", "func (f FooBarProps) IsProps() {}", "func CfnFilter_IsConstruct(x interface{}) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"monocdk.aws_guardduty.CfnFilter\",\n\t\t\"isConstruct\",\n\t\t[]interface{}{x},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (g GroupGate) IsOpen(f feature.Feature, a actor.Actor) bool {\n\tfor name := range g.value {\n\t\tif f, ok := registry[name]; ok && f(a) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (t *Ship) Diliver() bool {\n\tfmt.Println(\"Dilivering via Ship\")\n\treturn true\n}", "func (t *Truck) Diliver() bool {\n\tfmt.Println(\"Dilivering via Truck\")\n\treturn true\n}", "func (o *StoragePhysicalDisk) HasFdeCapable() bool {\n\tif o != nil && o.FdeCapable != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p RProc) IsCFunc() bool { return int(C._MRB_PROC_CFUNC_P(p.p)) != 0 }", "func (me TisoLanguageCodes) IsFi() bool { return me.String() == \"FI\" }", "func (g GenPluginType) IsGogo() bool {\n\treturn _genPluginTypeToIsGogo[g]\n}", "func (*NamedType) isType() {}", "func isRecursibleType(rv reflect.Value) bool {\n\tty := rv.Type()\n\tif ty.Kind() == reflect.Struct {\n\t\treturn unmarshalerFor(rv) == nil\n\t}\n\n\treturn false\n}", "func (t *Type) IsUntyped() bool", "func (me TxsdPaymentMechanism) IsCd() bool { return me.String() == \"CD\" }", "func (_BaseContentFactoryExt *BaseContentFactoryExtTransactor) IsContract(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _BaseContentFactoryExt.contract.Transact(opts, \"isContract\", addr)\n}", "func (g PercentageOfTimeGate) IsOpen(f feature.Feature, a actor.Actor) bool {\n\tr := seed.Uint32()\n\treturn r < (g.value / rangeFactor)\n}", "func (d *Door) IsOpen() bool {\n\t_, ok := d.DoorState.(OpenDoorState)\n\treturn ok\n}", "func (E_OnfTest1_Cont1A_Cont2D_Chocolate) IsYANGGoEnum() {}", "func (this *AggregateBase) IsCumulateDone(cumulative value.Value, context Context) (bool, error) {\n\treturn false, fmt.Errorf(\"There is no %v.IsCumulateDone().\", this.Name())\n}", "func (iface *Iface) IsPatched() bool {\n\treturn !(iface.patched == nil)\n}", "func (me TxsdInvoiceType) IsCs() bool { return me.String() == \"CS\" }", "func (me TactionType) IsOther() bool { return me.String() == \"other\" }", "func (f *FixUp) IsFixUp() bool {\n\tconfig := f.CustomConfiguration()\n\treturn overrideIsFixUp(config, true)\n}", "func (b *Base) IsEvent() bool {\n\treturn true\n}", "func (c CombatState) IsPartyDefeated() bool {\n\tfor _, actor := range c.Actors[party] {\n\t\tif !actor.IsKOed() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (m *sdt) IsEffective() *bool {\n\treturn m.isEffectiveField\n}", "func (rs *RuleSet) IsCoherent() bool {\n\t// walk the graph\n\tfor start, ends := range rs.conflicts {\n\t\tfor _, end := range ends {\n\t\t\t// check if start and end of a conflict rule are dependents\n\t\t\tcanWalk := rs.canWalkBetween(start, end)\n\t\t\tif canWalk {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func (*OnfTest1Choice_Vehicle_UnderCarriage) IsYANGGoStruct() {}", "func hasGCFinalizer(obj metav1.Object) bool {\n\tfor _, item := range obj.GetFinalizers() {\n\t\tswitch item {\n\t\tcase metav1.FinalizerDeleteDependents, metav1.FinalizerOrphanDependents:\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (me TshapeEnumType) IsCylinder() bool { return me == \"cylinder\" }", "func (me TxsdInvoiceType) IsDa() bool { return me.String() == \"DA\" }", "func (d *common) isUsed() (bool, error) {\n\tusedBy, err := d.usedBy(true)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn len(usedBy) > 0, nil\n}", "func (me TxsdTaxType) IsIs() bool { return me.String() == \"IS\" }", "func (_Rootchain *RootchainCaller) IsMature(opts *bind.CallOpts, exitableTimestamp uint64) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _Rootchain.contract.Call(opts, out, \"isMature\", exitableTimestamp)\n\treturn *ret0, err\n}", "func (me TxsdActuate) IsOther() bool { return me == \"other\" }", "func (pkg *goPackage) isBuildable(c *config.Config) bool {\n\treturn pkg.firstGoFile() != \"\" || !pkg.proto.sources.isEmpty()\n}", "func (me TxsdWorkType) IsDc() bool { return me.String() == \"DC\" }", "func IsOrExtendsForgeFedRepository(other vocab.Type) bool {\n\treturn typerepository.IsOrExtendsRepository(other)\n}", "func (me TEventType) IsHITDisposed() bool { return me.String() == \"HITDisposed\" }", "func (t *Type) IsContainer() bool {\n\t_, ok := frugalContainerTypes[t.Name]\n\treturn ok\n}" ]
[ "0.5777848", "0.5636446", "0.5450624", "0.53252184", "0.5296213", "0.52835715", "0.5083163", "0.5069068", "0.49672344", "0.4967114", "0.4961127", "0.49527285", "0.4931717", "0.49222323", "0.49133813", "0.49083734", "0.4903117", "0.48999462", "0.48911142", "0.48828495", "0.48580572", "0.48571712", "0.4855442", "0.48481435", "0.48435348", "0.48275355", "0.48109904", "0.47920045", "0.47572386", "0.47517", "0.47515056", "0.47463518", "0.47202498", "0.47153938", "0.46910533", "0.468709", "0.46843666", "0.46764243", "0.46609902", "0.46497652", "0.46426728", "0.4632424", "0.46256024", "0.46250874", "0.46210933", "0.46197164", "0.46167505", "0.46127278", "0.46066007", "0.46003538", "0.45947802", "0.45920205", "0.45902503", "0.4589901", "0.45894894", "0.45749664", "0.45703813", "0.45664668", "0.4562838", "0.4557202", "0.45471004", "0.454357", "0.45432884", "0.45420647", "0.45397264", "0.45381996", "0.45344177", "0.45298353", "0.45293152", "0.45289803", "0.45273855", "0.45269796", "0.4524892", "0.45235968", "0.4513439", "0.4510988", "0.4510754", "0.45087278", "0.45073202", "0.450297", "0.44963205", "0.44957477", "0.44952238", "0.44924158", "0.44848058", "0.44824076", "0.44744918", "0.44733143", "0.44658697", "0.4460727", "0.44597882", "0.44556308", "0.4452836", "0.44452882", "0.44424072", "0.4440296", "0.44383872", "0.4437985", "0.4431422", "0.44298235" ]
0.7952134
0
Get finds projects by tags or all projects or the project in the current directory
func (i *Index) Get(tags []string, all bool) ([]string, error) { switch { case all: err := i.clean() return i.projects(), err case len(tags) > 0: if err := i.clean(); err != nil { return []string{}, err } projectsWithTags := []string{} for _, p := range i.projects() { found, err := i.hasTags(p, tags) if err != nil { return []string{}, nil } if found { projectsWithTags = append(projectsWithTags, p) } } sort.Strings(projectsWithTags) return projectsWithTags, nil default: curProjPath, _, err := Paths() if err != nil { return []string{}, err } if _, ok := i.Projects[curProjPath]; !ok { i.add(curProjPath) if err := i.save(); err != nil { return []string{}, err } } return []string{curProjPath}, nil } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetProjects(w http.ResponseWriter, r *http.Request, auth string) []Project {\n\tvar projects []Project\n\tprojectFileName := auth + globals.PROJIDFILE\n\t//First see if project already exist\n\tstatus, filepro := caching.ShouldFileCache(projectFileName, globals.PROJIDDIR)\n\tdefer filepro.Close()\n\tif status == globals.Error || status == globals.DirFail {\n\t\thttp.Error(w, \"Failed to create a file\", http.StatusInternalServerError)\n\t\treturn nil\n\t}\n\tif status == globals.Exist {\n\t\t//The file exist\n\t\t//We read from file\n\t\terr := caching.ReadFile(filepro, &projects)\n\t\tif err != nil {\n\t\t\terrmsg := \"The Failed Reading from file with error\" + err.Error()\n\t\t\thttp.Error(w, errmsg, http.StatusInternalServerError)\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\t//Else we need to query to get it\n\t\tfor i := 0; i < globals.MAXPAGE; i++ {\n\t\t\tvar subProj []Project\n\t\t\tquery := globals.GITAPI + globals.PROJQ + globals.PAGEQ + strconv.Itoa(i+1)\n\t\t\terr := apiGetCall(w, query, auth, &subProj)\n\t\t\tif err != nil {\n\t\t\t\t//The API call has failed\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t//When it's empty we no longer need to do calls\n\t\t\tif len(subProj) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tprojects = append(projects, subProj...)\n\t\t}\n\t\tcaching.CacheStruct(filepro, projects)\n\n\t}\n\treturn projects\n}", "func Projects() []types.ProjectConfig {\n\tvar projects []types.ProjectConfig\n\tvar projectsWithPath []types.ProjectConfig\n\trootPath := ProjectRoot()\n\tprojectsDir := viper.GetString(\"projectDirectory\")\n\n\tif err := viper.UnmarshalKey(\"projects\", &projects); err != nil {\n\t\tlog.Print(err)\n\t\tlog.Fatal(\"Error: could not parse projects from config file\")\n\t}\n\n\t// extrapolate the full repo path\n\tfor _, project := range projects {\n\t\tvar dir string\n\n\t\t// default to project name if path fragement is not configured\n\t\tif project.Path != nil {\n\t\t\tdir = *project.Path\n\t\t} else {\n\t\t\tdir = project.Name\n\t\t}\n\n\t\tfullPath := path.Join(rootPath, projectsDir, dir)\n\t\tproject.FullPath = &fullPath\n\t\tprojectsWithPath = append(projectsWithPath, project)\n\t}\n\n\treturn projectsWithPath\n}", "func Projects() map[string]Project {\n\t// todo don't expose map here\n\treturn projects\n}", "func (dp *DummyProject) Get(name string) *project.Project {\n\tfor _, p := range projects {\n\t\tif p.Name == name {\n\t\t\treturn p\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetProjects(w http.ResponseWriter, r *http.Request) {\n\t// Get IDs for projects\n\t// Grab those projects.\n\t// Return those cool projects and response\n}", "func GetProjects(e Executor, userID string) (*ProjectSimpleList, error) {\n\treq, _ := http.NewRequest(\"GET\", RexBaseURL+apiProjectByOwner+userID, nil)\n\n\tresp, err := e.Execute(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\t}()\n\n\tvar projects ProjectSimpleList\n\terr = json.NewDecoder(resp.Body).Decode(&projects)\n\n\t// set ID for convenience\n\tfor i, p := range projects.Embedded.Projects {\n\t\tre, _ := regexp.Compile(\"/projects/(.*)\")\n\t\tvalues := re.FindStringSubmatch(p.Links.Self.Href)\n\t\tif len(values) > 0 {\n\t\t\tprojects.Embedded.Projects[i].ID = values[1]\n\t\t}\n\t}\n\treturn &projects, err\n}", "func (uh *UserHandler) GetProjectsWMatchTags(w http.ResponseWriter, r *http.Request) {\n\n\tuser := uh.Authentication(r)\n\tif user == nil {\n\t\thttp.Redirect(w, r, \"/Login\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tuid := user.UID\n\n\tprojects := uh.UService.SearchProjectWMatchTag(uid)\n\n\tjson, err := json.Marshal(projects)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tw.Write(json)\n}", "func (p *Provider) GetProjects() []string {\n\treturn p.opts.projects\n}", "func GetProjects() []m.Project {\n body, err := authenticatedGet(\"projects\")\n if err != nil {\n panic(err.Error())\n } else {\n var responseData projectResponse\n err = json.Unmarshal(body, &responseData)\n if err != nil {\n panic(err.Error())\n }\n\n return responseData.Data\n }\n}", "func (a *DefaultApiService) Projects(ctx context.Context) ([]Project, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t \tsuccessPayload []Project\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/projects\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json; charset=utf-8\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarQueryParams.Add(\"circle-token\", key)\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn successPayload, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn successPayload, localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\tif err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\n\n\treturn successPayload, localVarHttpResponse, err\n}", "func (s *Server) Get(ctx context.Context, q *ProjectQuery) (*v1alpha1.AppProject, error) {\n\tif !s.enf.EnforceClaims(ctx.Value(\"claims\"), \"projects\", \"get\", q.Name) {\n\t\treturn nil, grpc.ErrPermissionDenied\n\t}\n\treturn s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(q.Name, metav1.GetOptions{})\n}", "func SearchProjects(userID int) ([]models.Project, error) {\n\to := GetOrmer()\n\tsql := `select distinct p.project_id, p.name, p.public \n\t\tfrom project p \n\t\tleft join project_member pm on p.project_id = pm.project_id \n\t\twhere (pm.user_id = ? or p.public = 1) and p.deleted = 0`\n\n\tvar projects []models.Project\n\n\tif _, err := o.Raw(sql, userID).QueryRows(&projects); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn projects, nil\n}", "func (s projectService) Get(projectsQuery ProjectsQuery) (*Projects, error) {\n\tv, _ := query.Values(projectsQuery)\n\tpath := s.BasePath\n\tencodedQueryString := v.Encode()\n\tif len(encodedQueryString) > 0 {\n\t\tpath += \"?\" + encodedQueryString\n\t}\n\n\tresp, err := apiGet(s.getClient(), new(Projects), path)\n\tif err != nil {\n\t\treturn &Projects{}, err\n\t}\n\n\treturn resp.(*Projects), nil\n}", "func (s *ProjectService) Get(projectsQuery ProjectsQuery) (*resources.Resources[*Project], error) {\n\tv, _ := query.Values(projectsQuery)\n\tpath := s.BasePath\n\tencodedQueryString := v.Encode()\n\tif len(encodedQueryString) > 0 {\n\t\tpath += \"?\" + encodedQueryString\n\t}\n\n\tresp, err := api.ApiGet(s.GetClient(), new(resources.Resources[*Project]), path)\n\tif err != nil {\n\t\treturn &resources.Resources[*Project]{}, err\n\t}\n\n\treturn resp.(*resources.Resources[*Project]), nil\n}", "func getRequestedProjects(names []string, all bool) ([]*ddevapp.DdevApp, error) {\n\trequestedProjects := make([]*ddevapp.DdevApp, 0)\n\n\t// If no project is specified, return the current project\n\tif len(names) == 0 && !all {\n\t\tproject, err := ddevapp.GetActiveApp(\"\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn append(requestedProjects, project), nil\n\t}\n\n\tallDockerProjects := ddevapp.GetDockerProjects()\n\n\t// If all projects are requested, return here\n\tif all {\n\t\treturn allDockerProjects, nil\n\t}\n\n\t// Convert all projects slice into map indexed by project name to prevent duplication\n\tallDockerProjectMap := map[string]*ddevapp.DdevApp{}\n\tfor _, project := range allDockerProjects {\n\t\tallDockerProjectMap[project.Name] = project\n\t}\n\n\t// Select requested projects\n\trequestedProjectsMap := map[string]*ddevapp.DdevApp{}\n\tfor _, name := range names {\n\t\tvar exists bool\n\t\t// If the requested project name is found in the docker map, OK\n\t\t// If not, if we find it in the globl project list, OK\n\t\t// Otherwise, error.\n\t\tif requestedProjectsMap[name], exists = allDockerProjectMap[name]; !exists {\n\t\t\tif _, exists = globalconfig.DdevGlobalConfig.ProjectList[name]; exists {\n\t\t\t\trequestedProjectsMap[name] = &ddevapp.DdevApp{Name: name}\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"could not find requested project %s\", name)\n\t\t\t}\n\t\t}\n\n\t}\n\n\t// Convert map back to slice\n\tfor _, project := range requestedProjectsMap {\n\t\trequestedProjects = append(requestedProjects, project)\n\t}\n\n\treturn requestedProjects, nil\n}", "func (m *manager) List(query ...*models.ProjectQueryParam) ([]*models.Project, error) {\n\tvar q *models.ProjectQueryParam\n\tif len(query) > 0 {\n\t\tq = query[0]\n\t}\n\treturn dao.GetProjects(q)\n}", "func getProjects(r *http.Request) ([]byte, error) {\n\tm := bson.M{}\n\tif pid, e := convert.Id(r.FormValue(\"id\")); e == nil {\n\t\tm[db.ID] = pid\n\t}\n\tp, e := db.Projects(m, nil)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn util.JSON(map[string]interface{}{\"projects\": p})\n}", "func ProjectPs(p project.APIProject, c *cli.Context) error {\n\tqFlag := c.Bool(\"q\")\n\tallInfo, err := p.Ps(context.Background(), qFlag, c.Args()...)\n\tif err != nil {\n\t\treturn cli.NewExitError(err.Error(), 1)\n\t}\n\tos.Stdout.WriteString(allInfo.String(!qFlag))\n\treturn nil\n}", "func Projects(ctx context.Context) (map[string]*configpb.ProjectConfig, error) {\n\tval, err := projectCacheSlot.Fetch(ctx, func(any) (val any, exp time.Duration, err error) {\n\t\tvar pc map[string]*configpb.ProjectConfig\n\t\tif pc, err = fetchProjects(ctx); err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\treturn pc, time.Minute, nil\n\t})\n\tswitch {\n\tcase err == caching.ErrNoProcessCache:\n\t\t// A fallback useful in unit tests that may not have the process cache\n\t\t// available. Production environments usually have the cache installed\n\t\t// by the framework code that initializes the root context.\n\t\treturn fetchProjects(ctx)\n\tcase err != nil:\n\t\treturn nil, err\n\tdefault:\n\t\tpc := val.(map[string]*configpb.ProjectConfig)\n\t\treturn pc, nil\n\t}\n}", "func projectsWithConfig(ctx context.Context) ([]string, error) {\n\tprojects, err := cfgclient.ProjectsWithConfig(ctx, ConfigFileName)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to get projects with %q from LUCI Config\",\n\t\t\tConfigFileName).Tag(transient.Tag).Err()\n\t}\n\treturn projects, nil\n}", "func GetUserRelevantProjects(userID int, projectName string) ([]models.Project, error) {\n\to := GetOrmer()\n\tsql := `select distinct\n\t\tp.project_id, p.owner_id, p.name,p.creation_time, p.update_time, p.public, pm.role role \n\t from project p \n\t\tleft join project_member pm on p.project_id = pm.project_id\n\t where p.deleted = 0 and pm.user_id= ?`\n\n\tqueryParam := make([]interface{}, 1)\n\tqueryParam = append(queryParam, userID)\n\tif projectName != \"\" {\n\t\tsql += \" and p.name like ? \"\n\t\tqueryParam = append(queryParam, projectName)\n\t}\n\tsql += \" order by p.name \"\n\tvar r []models.Project\n\t_, err := o.Raw(sql, queryParam).QueryRows(&r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}", "func (s *ProjectsService) Get(ctx context.Context, projectName string) (*Project, error) {\n\tquery := url.Values{\n\t\t\"name\": []string{projectName},\n\t}\n\treq, err := s.Client.NewRequest(ctx, http.MethodGet, newURI(projectsURI), WithQuery(query))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get project request creation failed: %w\", err)\n\t}\n\tres, resp, err := s.Client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get project failed: %w\", err)\n\t}\n\n\tif resp != nil && resp.StatusCode == http.StatusNotFound {\n\t\treturn nil, ErrNotFound\n\t}\n\n\tp := &ProjectsList{\n\t\tProjects: []*Project{},\n\t}\n\tif err := json.Unmarshal(res, &p); err != nil {\n\t\treturn nil, fmt.Errorf(\"get project failed, unable to unmarshal repository list json: %w\", err)\n\t}\n\n\tp.Projects[0].Session.set(resp)\n\treturn p.Projects[0], nil\n\n}", "func getSnykProjects(token string, org string) []string {\n\tclient, err := snyk.NewClient(snyk.WithToken(token))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// List all projects for the authenticated user.\n\tprojects, err := client.OrganizationProjects(context.TODO(), org)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Generate a slice containing all the full project names for an org.\n\tvar s []string\n\tfor _, project := range projects {\n\t\t// Project names contain manifest files after a colon; only grab the project name.\n\t\ts = append(s, strings.Split(project.Name, \":\")[0])\n\t}\n\t// In case there were multiple manifests for a project, there are now multiple items duplicated in\n\t// our list. The deduplicate() function removes these.\n\treturn deduplicate(s)\n}", "func (o *OpenShot) GetProjects() (*Projects, error) {\n\tlog := getLogger(\"GetProjects\")\n\tvar projects Projects\n\n\terr := o.http.Get(log, o.projectsURL(), nil, &projects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &projects, nil\n}", "func (s projectService) GetAll() ([]*Project, error) {\n\titems := []*Project{}\n\tpath, err := getAllPath(s)\n\tif err != nil {\n\t\treturn items, err\n\t}\n\n\t_, err = apiGet(s.getClient(), &items, path)\n\treturn items, err\n}", "func (self *CassandraMetaStore) findAllProjects() ([]*meta.Project, error) {\n\titr := self.cassandraService.Client.Query(\"select name, oids from projects;\").Iter()\n\tvar oids []string\n\tvar name string\n\tproject_list := []*meta.Project{}\n\tfor itr.Scan(&name, &oids) {\n\t\tproject_list = append(project_list, &meta.Project{Name: name, Oids: oids})\n\t}\n\n\tif err := itr.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(project_list) == 0 {\n\t\treturn nil, meta.ErrProjectNotFound\n\t}\n\treturn project_list, nil\n}", "func All() []model.Project {\n projects := []model.Project{}\n\n // Find Projects and eager-load ProjectConfig.\n app.DB.\n Preload(\"ProjectConfig\").\n Order(\"nsp desc\").\n Find(&projects)\n\n return projects\n}", "func (repo *repo) GetProjects(params *project.GetProjectsParams) (*models.Projects, error) {\n\ttableName := fmt.Sprintf(\"cla-%s-projects\", repo.stage)\n\n\t// Use the nice builder to create the expression\n\texpr, err := expression.NewBuilder().WithProjection(buildProjection()).Build()\n\tif err != nil {\n\t\tlog.Warnf(\"error building expression for project scan, error: %v\", err)\n\t}\n\n\t// Assemble the query input parameters\n\tscanInput := &dynamodb.ScanInput{\n\t\tExpressionAttributeNames: expr.Names(),\n\t\tExpressionAttributeValues: expr.Values(),\n\t\tFilterExpression: expr.Filter(),\n\t\tProjectionExpression: expr.Projection(),\n\t\tTableName: aws.String(tableName),\n\t}\n\n\t// If we have the next key, set the exclusive start key value\n\tif params.NextKey != nil && *params.NextKey != \"\" {\n\t\tlog.Debugf(\"Received a nextKey, value: %s\", *params.NextKey)\n\t\t// The primary key of the first item that this operation will evaluate.\n\t\t// and the query key (if not the same)\n\t\tscanInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{\n\t\t\t\"project_id\": {\n\t\t\t\tS: params.NextKey,\n\t\t\t},\n\t\t}\n\t}\n\n\t// If we have a page size, set the limit value - make sure it's a positive value\n\tif params.PageSize != nil && *params.PageSize > 0 {\n\t\tlog.Debugf(\"Received a pageSize parameter, value: %d\", *params.PageSize)\n\t\t// The primary key of the first item that this operation will evaluate.\n\t\t// and the query key (if not the same)\n\t\tscanInput.Limit = params.PageSize\n\t} else {\n\t\t// Default page size\n\t\t*params.PageSize = 50\n\t}\n\n\tvar projects []models.Project\n\tvar lastEvaluatedKey string\n\n\t// Loop until we have all the records\n\tfor ok := true; ok; ok = lastEvaluatedKey != \"\" {\n\t\tresults, errQuery := repo.dynamoDBClient.Scan(scanInput)\n\t\tif errQuery != nil {\n\t\t\tlog.Warnf(\"error retrieving projects, error: %v\", errQuery)\n\t\t\treturn nil, errQuery\n\t\t}\n\n\t\t// Convert the list of DB models to a list of response models\n\t\tprojectList, modelErr := repo.buildProjectModels(results.Items)\n\t\tif modelErr != nil {\n\t\t\tlog.Warnf(\"error converting project DB model to response model, error: %v\",\n\t\t\t\tmodelErr)\n\t\t\treturn nil, modelErr\n\t\t}\n\n\t\t// Add to the project response models to the list\n\t\tprojects = append(projects, projectList...)\n\n\t\tif results.LastEvaluatedKey[\"project_id\"] != nil {\n\t\t\tlastEvaluatedKey = *results.LastEvaluatedKey[\"project_id\"].S\n\t\t\tscanInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{\n\t\t\t\t\"project_id\": {\n\t\t\t\t\tS: aws.String(lastEvaluatedKey),\n\t\t\t\t},\n\t\t\t}\n\t\t} else {\n\t\t\tlastEvaluatedKey = \"\"\n\t\t}\n\n\t\tif int64(len(projects)) >= *params.PageSize {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn &models.Projects{\n\t\tLastKeyScanned: lastEvaluatedKey,\n\t\tPageSize: *params.PageSize,\n\t\tProjects: projects,\n\t}, nil\n}", "func getRequestedProjects(names []string, all bool) ([]*ddevapp.DdevApp, error) {\n\trequestedProjects := make([]*ddevapp.DdevApp, 0)\n\n\t// If no project is specified, return the current project\n\tif len(names) == 0 && !all {\n\t\tproject, err := ddevapp.GetActiveApp(\"\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn append(requestedProjects, project), nil\n\t}\n\n\tallProjects := ddevapp.GetApps()\n\n\t// If all projects are requested, return here\n\tif all {\n\t\treturn allProjects, nil\n\t}\n\n\t// Convert all projects slice into map indexed by project name to prevent duplication\n\tallProjectsMap := map[string]*ddevapp.DdevApp{}\n\tfor _, project := range allProjects {\n\t\tallProjectsMap[project.Name] = project\n\t}\n\n\t// Select requested projects\n\trequestedProjectsMap := map[string]*ddevapp.DdevApp{}\n\tfor _, name := range names {\n\t\tvar exists bool\n\t\tif requestedProjectsMap[name], exists = allProjectsMap[name]; !exists {\n\t\t\treturn nil, fmt.Errorf(\"could not find project %s\", name)\n\t\t}\n\t}\n\n\t// Convert map back to slice\n\tfor _, project := range requestedProjectsMap {\n\t\trequestedProjects = append(requestedProjects, project)\n\t}\n\n\treturn requestedProjects, nil\n}", "func (ps *ProjectStore) GetAll() ([]models.Project, error) {\n\tvar projects []models.Project\n\n\trows, err := ps.db.Query(`SELECT p.id, p.created_date, p.name, \n\t\t\t\t\t\t\t\t p.key, p.repo, p.homepage,\n\t\t\t\t\t\t\t\t p.icon_url, \n\t\t\t\t\t\t\t \t json_build_object('id', lead.id, 'username', lead.username, 'email', lead.email, 'full_name', lead.full_name, 'profile_picture', lead.profile_picture) AS lead\n\t\t\t\t\t\t\t FROM projects AS p\n\t\t\t\t\t\t\t JOIN users AS lead ON p.lead_id = lead.id;`)\n\tif err != nil {\n\t\treturn projects, handlePqErr(err)\n\t}\n\n\tfor rows.Next() {\n\t\tvar p models.Project\n\n\t\terr = intoProject(rows, &p)\n\t\tif err != nil {\n\t\t\treturn projects, handlePqErr(err)\n\t\t}\n\n\t\tprojects = append(projects, p)\n\t}\n\n\treturn projects, nil\n}", "func (g *GitLab) getProject(ctx context.Context, client *gitlab.Client, owner, name string) (*gitlab.Project, error) {\n\trepo, _, err := client.Projects.GetProject(fmt.Sprintf(\"%s/%s\", owner, name), nil, gitlab.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn repo, nil\n}", "func (c *Client) Projects(page int, per_page int) ([]*Project, error) {\n\n\turl, opaque := c.ResourceUrl(projectsUrl, nil, QMap{\n\t\t\"page\": strconv.Itoa(page),\n\t\t\"per_page\": strconv.Itoa(per_page),\n\t})\n\n\tvar projects []*Project\n\n\tcontents, err := c.Do(\"GET\", url, opaque, nil)\n\tif err == nil {\n\t\terr = json.Unmarshal(contents, &projects)\n\t}\n\n\treturn projects, err\n}", "func ProjectsGET(c *gin.Context) {\n\tuser := c.MustGet(\"user\").(*User)\n\tif err := user.FetchProjects(); err != nil {\n\t\tc.JSON(http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, user.Projects)\n}", "func FilterProjects(db *sql.DB, collabSpace string) []Project {\n\tprojects := []Project{}\n\tfmt.Println(collabSpace)\n\tsqlQuery := `SELECT * FROM projects WHERE tags[1]=$1;`\n\trows, err := db.Query(sqlQuery, collabSpace)\n\n\tdefer rows.Close()\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\n\tfor rows.Next() {\n\t\tproject := Project{}\n\t\trows.Scan(&project.Name, pq.Array(&project.ProjectImgs),\n\t\t\t&project.DefaultImageIndex, pq.Array(&project.Tags),\n\t\t\t&project.Description, &project.Followers)\n\n\t\tprojects = append(projects, project)\n\t}\n\n\treturn projects\n}", "func All() ([]Project, error) {\n\tnames, err := workdir.ProjectNames()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprojects := []Project{}\n\tnow := time.Now()\n\tfor _, name := range names {\n\t\tp, err := FromName(name)\n\t\tif err != nil {\n\t\t\tcontinue // should not happen\n\t\t}\n\t\tp.Lock = locks.Check(name, now)\n\t\tprojects = append(projects, *p)\n\t}\n\treturn projects, nil\n}", "func (c Client) Projects() ([]Project, error) {\n\tu := mustParseURL(c.baseURL)\n\tu.Path += \"projects\"\n\n\tprojects := make([]Project, 0)\n\n\t// if there's more projects than returned by default by the API, links array will\n\t// be provided. The object that has the 'rel' field with the value of 'next' will\n\t// also contain the 'href' with the complete link to the next page.\n\tfor u != nil {\n\t\tresp, err := c.request(http.MethodGet, u, nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"fetching files failed: %s\", err.Error())\n\t\t}\n\t\tdefer resp.Close()\n\n\t\tvar r struct {\n\t\t\tapiOKResponseTemplate\n\t\t\tProjects []Project `json:\"items\"`\n\t\t}\n\t\tif err := json.NewDecoder(resp).Decode(&r); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unmarshalling response failed: %s\", err.Error())\n\t\t}\n\t\tprojects = append(projects, r.Projects...)\n\n\t\tu = nil\n\t\tfor _, link := range r.Links {\n\t\t\tif link.Rel == \"next\" {\n\t\t\t\tu = mustParseURL(link.Href)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn projects, nil\n}", "func (pu *ProjectUtil) GetProjects(name string) ([]models.ExistingProject, error) {\n\turl := pu.rootURI + \"/api/v2.0/projects\"\n\tif len(strings.TrimSpace(name)) > 0 {\n\t\turl = url + \"?name=\" + name\n\t}\n\tdata, err := pu.testingClient.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pros []models.ExistingProject\n\tif err = json.Unmarshal(data, &pros); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn pros, nil\n}", "func Get(name string) (Project, error) {\n\tproj, ok := projects[name]\n\tif !ok {\n\t\treturn nil, ErrProjectNotFound\n\t}\n\treturn proj, nil\n}", "func (h *Handler) GetProjects(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\tvar projects []data.Project\n\n\tif projects, err = h.TodoGo.GetProjects(r.Context()); err != nil {\n\t\tresponse.Error(w, err)\n\t\treturn\n\t}\n\tresponse.Success(200, w, projects)\n}", "func List(ctx context.Context, client *selvpcclient.ServiceClient) ([]*Project, *selvpcclient.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, resourceURL}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\treturn nil, responseResult, responseResult.Err\n\t}\n\n\t// Extract projects from the response body.\n\tvar result struct {\n\t\tProjects []*Project `json:\"projects\"`\n\t}\n\terr = responseResult.ExtractResult(&result)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn result.Projects, responseResult, nil\n}", "func GetProject(w http.ResponseWriter, r *http.Request) {\n\t// Get item params\n\t// Perform get, db n' stuff.\n\t// render.JSON(w, r)\n}", "func GetProjects() ([]*github.Repository) {\n\n\tctx := context.Background()\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: os.Getenv(\"GITHUB_PAT\")},\n\t)\n\ttc := oauth2.NewClient(ctx, ts)\n\n\tclient := github.NewClient(tc)\n\n\t// list all repositories for the authenticated user\n\trepos, _, _ := client.Repositories.List(ctx, \"\", nil)\n\n\t// for _, repo := range repos {\n \n // fmt.Println(*repo.HTMLURL)\n // }\n\n\treturn repos\n}", "func GetProjects(_ *router.WebRequest) *model.Container {\n\tlist, err := factory.GetGitClient().ListProjects()\n\tif err != nil {\n\t\treturn model.ErrorResponse(model.MessageItem{\n\t\t\tCode: \"list-error\",\n\t\t\tMessage: err.Error(),\n\t\t}, 500)\n\t}\n\tdata := make([]interface{}, 0)\n\tfor _, item := range list {\n\t\tdata = append(data, item)\n\t}\n\treturn model.ListResponse(data)\n}", "func ProjectGet(w http.ResponseWriter, r *http.Request) {\n\tdb := utils.GetDB()\n\tdefer db.Close()\n\n\tvar projects []models.Project\n\terr := db.Find(&projects).Error\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 400)\n\t\tutils.LOG.Println(err)\n\t\treturn\n\t}\n\n\terr = json.NewEncoder(w).Encode(projects)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\tutils.LOG.Println(err)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(`success`))\n\n}", "func (s *Server) Get(ctx context.Context, q *project.ProjectQuery) (*v1alpha1.AppProject, error) {\n\tif err := s.enf.EnforceErr(ctx.Value(\"claims\"), rbacpolicy.ResourceProjects, rbacpolicy.ActionGet, q.Name); err != nil {\n\t\treturn nil, err\n\t}\n\tproj, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(ctx, q.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tproj.NormalizeJWTTokens()\n\treturn proj, err\n}", "func (b *ProjectModels) GetProjects(addwhere string, limit string, offset string, orderby string) ([]ProjectAll, error) {\n\tresult := make([]ProjectAll, 0)\n\tjoin := fmt.Sprintf(\"join %s on %s.id = %s.project_id \", TblProjectDetail, PROJECT, TblProjectDetail)\n\tselects := fmt.Sprintf(\"%s.*,%s.*\", PROJECT, TblProjectDetail)\n\torder := fmt.Sprintf(\"%s.%s\", PROJECT, orderby)\n\twhere := `(name LIKE \"%` + addwhere + `%\" OR description LIKE \"%` + addwhere + `%\" OR address LIKE \"%` + addwhere + `%\")`\n\n\terr := configs.GetDB.Table(PROJECT).Select(selects).Joins(join).Where(where).Limit(limit).Offset(offset).Order(order).Find(&result).Error\n\treturn result, err\n}", "func (s *ProjectService) GetAll() ([]*Project, error) {\n\titems := []*Project{}\n\tpath, err := services.GetAllPath(s)\n\tif err != nil {\n\t\treturn items, err\n\t}\n\n\t_, err = api.ApiGet(s.GetClient(), &items, path)\n\treturn items, err\n}", "func (w Workspace) Projects(\n\tctx context.Context,\n\tafter *string,\n\tbefore *string,\n\tfirst *int,\n\tlast *int,\n) (ProjectConnection, error) {\n\treturn PaginateProjectIDSliceContext(ctx, w.ProjectIDs, after, before, first, last)\n}", "func GetTrendingProjects(db *sql.DB) []Project {\n\tprojects := []Project{}\n\n\tsqlQuery := `SELECT * FROM projects ORDER BY followers desc LIMIT 20;`\n\trows, err := db.Query(sqlQuery)\n\n\tdefer rows.Close()\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\n\tfor rows.Next() {\n\t\tproject := Project{}\n\t\trows.Scan(&project.Name, pq.Array(&project.ProjectImgs),\n\t\t\t&project.DefaultImageIndex, pq.Array(&project.Tags),\n\t\t\t&project.Description, &project.Followers)\n\n\t\tprojects = append(projects, project)\n\t}\n\n\treturn projects\n}", "func (c *Client) getProjectID(owner, repoName, projURL string) (int64, error) {\n\tvar cancels []context.CancelFunc\n\tdefer func() {\n\t\tfor _, cancel := range cancels {\n\t\t\tcancel()\n\t\t}\n\t}()\n\tvar page int\n\tfor {\n\t\tplo := &gh.ProjectListOptions{\n\t\t\tListOptions: gh.ListOptions{\n\t\t\t\tPage: page,\n\t\t\t\tPerPage: 10,\n\t\t\t},\n\t\t}\n\t\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\t\tcancels = append(cancels, cancel)\n\t\tprojects, resp, err := c.GHClient.Repositories.ListProjects(ctx, owner, repoName, plo)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tfor _, project := range projects {\n\t\t\tif project.GetHTMLURL() == projURL {\n\t\t\t\treturn project.GetID(), nil\n\t\t\t}\n\t\t}\n\t\tpage = resp.NextPage\n\t\tif page == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn 0, nil\n}", "func ParserProjectFindOneById(id string) (*ParserProject, error) {\n\treturn ParserProjectFindOne(ParserProjectById(id))\n}", "func (dp *DummyProject) GetAll(owner ...string) []*project.Project {\n\tpr := []*project.Project{}\n\n\tfor _, p := range projects {\n\t\tfor _, ow := range owner {\n\t\t\tif p.Owner == ow {\n\t\t\t\tpr = append(pr, p)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, ok := acl[p.Name]; ok {\n\t\t\t\tfor _, u := range a {\n\t\t\t\t\tif ow == u {\n\t\t\t\t\t\tpr = append(pr, p)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn pr\n}", "func (s Step) Projects(\n\tctx context.Context,\n\tafter *string,\n\tbefore *string,\n\tfirst *int,\n\tlast *int,\n) (ProjectConnection, error) {\n\treturn PaginateProjectIDSliceContext(ctx, s.ProjectIDs, after, before, first, last)\n}", "func (c *ProjectService) List() ([]Project, *http.Response, error) {\n\tresponse := new(projectListResponse)\n\tapiError := new(APIError)\n\tresp, err := c.sling.New().Get(\"\").Receive(response, apiError)\n\treturn response.Results, resp, relevantError(err, *apiError)\n}", "func (pc *MockProjectConnector) FindProjects(key string, limit int, sortDir int, isAuthenticated bool) ([]model.ProjectRef, error) {\n\tprojects := []model.ProjectRef{}\n\tif sortDir > 0 {\n\t\tfor i := 0; i < len(pc.CachedProjects); i++ {\n\t\t\tp := pc.CachedProjects[i]\n\t\t\tvisible := isAuthenticated || (!isAuthenticated && !p.Private)\n\t\t\tif p.Identifier >= key && visible {\n\t\t\t\tprojects = append(projects, p)\n\t\t\t\tif len(projects) == limit {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i := len(pc.CachedProjects) - 1; i >= 0; i-- {\n\t\t\tp := pc.CachedProjects[i]\n\t\t\tvisible := isAuthenticated || (!isAuthenticated && !p.Private)\n\t\t\tif p.Identifier < key && visible {\n\t\t\t\tprojects = append(projects, p)\n\t\t\t\tif len(projects) == limit {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn projects, nil\n}", "func GetProjectList(tasks []api.Task) []api.Task {\n\tvar result []api.Task\n\tfor _, task := range tasks {\n\t\tif task.IsProject() {\n\t\t\tresult = append(result, task)\n\t\t}\n\t}\n\treturn result\n}", "func (pg *MongoDb) ListProjects(ctx context.Context, filter string, pageSize int, pageToken string) ([]*prpb.Project, string, error) {\n\t//id := decryptInt64(pageToken, pg.PaginationKey, 0)\n\t//TODO\n\treturn nil, \"\", nil\n}", "func (self *CassandraMetaStore) Projects() ([]*meta.Project, error) {\n\treturn self.findAllProjects()\n}", "func Projects(mods ...qm.QueryMod) projectQuery {\n\tmods = append(mods, qm.From(\"`projects`\"))\n\treturn projectQuery{NewQuery(mods...)}\n}", "func (w *ServerInterfaceWrapper) Projects(ctx echo.Context) error {\n\tvar err error\n\n\t// HasSecurity is set\n\n\tctx.Set(\"OpenId.Scopes\", []string{\"exitus/project.read\"})\n\n\t// Parameter object where we will unmarshal all parameters from the context\n\tvar params ProjectsParams\n\t// ------------- Optional query parameter \"q\" -------------\n\tif paramValue := ctx.QueryParam(\"q\"); paramValue != \"\" {\n\t}\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"q\", ctx.QueryParams(), &params.Q)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter q: %s\", err))\n\t}\n\n\t// ------------- Optional query parameter \"offset\" -------------\n\tif paramValue := ctx.QueryParam(\"offset\"); paramValue != \"\" {\n\t}\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"offset\", ctx.QueryParams(), &params.Offset)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter offset: %s\", err))\n\t}\n\n\t// ------------- Optional query parameter \"limit\" -------------\n\tif paramValue := ctx.QueryParam(\"limit\"); paramValue != \"\" {\n\t}\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"limit\", ctx.QueryParams(), &params.Limit)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter limit: %s\", err))\n\t}\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.Projects(ctx, params)\n\treturn err\n}", "func (p *ProjectListAPIView) GET(w http.ResponseWriter, r *http.Request) {\n\tmanager := models.NewProjectManager(p.context)\n\tpaging := manager.NewPagingFromRequest(r)\n\tprojects := manager.NewProjectList()\n\n\tif err := manager.FilterPaged(&projects, paging); err != nil {\n\t\tglog.Error(err)\n\t\tresponse.New(http.StatusInternalServerError).Write(w, r)\n\t\treturn\n\t}\n\n\t// update paging\n\tresponse.New(http.StatusOK).Result(projects).Paging(paging).Write(w, r)\n}", "func Projects(mods ...qm.QueryMod) projectQuery {\n\tmods = append(mods, qm.From(\"`project`\"))\n\treturn projectQuery{NewQuery(mods...)}\n}", "func (s *ProjectsService) All(ctx context.Context) ([]*Project, error) {\n\tp := []*Project{}\n\topts := &PagingOptions{Limit: perPageLimit}\n\terr := allPages(opts, func() (*Paging, error) {\n\t\tlist, err := s.List(ctx, opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tp = append(p, list.GetProjects()...)\n\t\treturn &list.Paging, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, nil\n}", "func GetProjects(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tname := vars[\"name\"]\n\n\tsite, err := database.GetSiteByName(name)\n\tif err != nil {\n\t\tutils.RespondWithJSON(w, http.StatusNotFound, \"not_found\", nil)\n\t\treturn\n\t}\n\n\tprojects, err := database.GetProjects(site.ID)\n\tif err != nil {\n\t\tutils.RespondWithJSON(w, http.StatusNotFound, err.Error(), nil)\n\t\treturn\n\t}\n\tutils.RespondWithJSON(w, http.StatusOK, \"success\", projects)\n\treturn\n}", "func (s *Service) Find(id entity.ID) (*entity.Project, error) {\n\treturn s.repo.Find(id)\n}", "func FindProject(project string) (*gitlab.Project, error) {\n\tif target, ok := localProjects[project]; ok {\n\t\treturn target, nil\n\t}\n\n\tsearch := project\n\t// Assuming that a \"/\" in the project means its owned by an org\n\tif !strings.Contains(project, \"/\") {\n\t\tsearch = user + \"/\" + project\n\t}\n\n\tvar opts gitlab.GetProjectOptions\n\ttarget, resp, err := lab.Projects.GetProject(search, &opts)\n\tif resp != nil && resp.StatusCode == http.StatusNotFound {\n\t\treturn nil, ErrProjectNotFound\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// fwiw, I feel bad about this\n\tlocalProjects[project] = target\n\n\treturn target, nil\n}", "func FilterProjects() error {\n\t// Acquire a handle to the \"gn\" binary on the local workstation.\n\tgn, err := util.NewGn(Config.GnPath, Config.BuildDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Run \"fx gn <>\" command, and retrieve the output data.\n\tgen, err := gn.Gen(context.Background(), Config.Target)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Generate a map:\n\t// [filepath for every file in project X] -> [Project X]\n\t// With this mapping, we can match GN targets and file inputs\n\t// to check-license Project structs.\n\tfileMap, err := getFileMap()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Find Projects that match each target in the dependency tree.\n\tRootProject, err = processGenOutput(gen, fileMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Current() (*Project, error) {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, errors.New(err.Error())\n\t}\n\n\tcounter := 0\n\tfor i := 0; i < 4; i++ {\n\t\tif _, err := os.Stat(wd + \"/.atlas\"); os.IsNotExist(err) && i == 3 {\n\t\t\treturn nil, errors.New(\"Not in an atlas project\")\n\t\t}\n\t\tif _, err := os.Stat(wd + \"/.atlas\"); err == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tcounter++\n\t\twd += \"/..\"\n\t}\n\n\twdArr := strings.Split(wd, \"/\")\n\tfor i := 0; i < counter*2; i++ {\n\t\twdArr = wdArr[:len(wdArr)-1]\n\t}\n\n\twd = strings.Join(wdArr, \"/\")\n\n\tproject := Project{\n\t\tName: filepath.Base(wd),\n\t\tAbsolutePath: wd,\n\t\tPort: \"\",\n\t\tDBURL: \"\",\n\t}\n\treturn &project, nil\n}", "func Company_get_multiple_by_project () {\n\n // GET /projects/{project_id}/companies.json\n\n }", "func (test *Test) GetProject(projectName string) (models.Project, error) {\n\tps, err := test.GetProjects()\n\tvar projects []models.Project\n\tprojects = append([]models.Project{}, ps...)\n\n\tif err != nil {\n\t\treturn models.Project{}, errors.New(\"Could not get projects\" + err.Error())\n\t}\n\n\tfor _, p := range projects {\n\t\tif p.Name == projectName {\n\t\t\treturn p, nil\n\t\t}\n\t}\n\treturn models.Project{}, errors.New(\"Could not get project \" + projectName)\n}", "func (h *Handler) Get(res http.ResponseWriter, req *http.Request) {\n\tquery := req.URL.Query()\n\tproject := query.Get(\"project\")\n\tif len(project) == 0 {\n\t\th.getAll(res, req)\n\t} else {\n\t\th.getOne(res, req, query, project)\n\t}\n}", "func findAnyRepo(importPath string) RemoteRepo {\n\tfor _, v := range vcsMap {\n\t\ti := strings.Index(importPath+\"/\", v.suffix+\"/\")\n\t\tif i < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.Contains(importPath[:i], \"/\") {\n\t\t\tcontinue // don't match vcs suffix in the host name\n\t\t}\n\t\treturn &anyRepo{\n\t\t\tbaseRepo{\n\t\t\t\troot: importPath[:i] + v.suffix,\n\t\t\t\tvcs: v,\n\t\t\t},\n\t\t\timportPath[:i],\n\t\t}\n\t}\n\treturn nil\n}", "func (c *ClusterTx) GetProjectUsedBy(project Project) ([]string, error) {\n\tinstances, err := c.GetInstanceURIs(InstanceFilter{Project: &project.Name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\timages, err := c.GetImageURIs(ImageFilter{Project: &project.Name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprofiles, err := c.GetProfileURIs(ProfileFilter{Project: &project.Name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvolumes, err := c.GetStorageVolumeURIs(project.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnetworks, err := c.GetNetworkURIs(project.ID, project.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnetworkACLs, err := c.GetNetworkACLURIs(project.ID, project.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tusedBy := instances\n\tusedBy = append(usedBy, images...)\n\tusedBy = append(usedBy, profiles...)\n\tusedBy = append(usedBy, volumes...)\n\tusedBy = append(usedBy, networks...)\n\tusedBy = append(usedBy, networkACLs...)\n\n\treturn usedBy, nil\n}", "func GetAffectedProjects(lastcommit string, ignore ...string) (map[string]string, error) {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdir := \"\"\n\tif list := strings.Split(lastcommit, \"/\"); len(list) > 1 {\n\t\tdir = strings.Join(list[:len(list)-1], \"/\")\n\t\tlastcommit = list[len(list)-1]\n\t}\n\twd = filepath.Join(wd, dir)\n\n\tcmd := exec.Command(\"git\", \"diff\", \"--name-only\", lastcommit, \"HEAD\")\n\tcmd.Stdin = os.Stdin\n\tcmd.Stderr = os.Stderr\n\tcmd.Dir = wd\n\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdirs := make(map[string]struct{})\n\n\tscanner := bufio.NewScanner(bytes.NewReader(out))\n\tfor scanner.Scan() {\n\t\tdirs[filepath.Dir(scanner.Text())] = struct{}{}\n\t}\n\n\tprojects := make(map[string]string)\n\ndirs:\n\tfor p := range dirs {\n\t\tfor p != \".\" {\n\t\t\tfiles, err := ioutil.ReadDir(filepath.Join(wd, p))\n\t\t\tif err != nil && os.IsExist(err) {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfor _, f := range files {\n\t\t\t\tif filepath.Ext(f.Name()) == \".csproj\" && !isInside(p, ignore) {\n\t\t\t\t\tprojects[f.Name()] = filepath.Join(p, f.Name())\n\t\t\t\t\tcontinue dirs\n\t\t\t\t}\n\t\t\t}\n\t\t\tp = filepath.Clean(p + \"/..\")\n\t\t}\n\t}\n\treturn projects, nil\n}", "func (c *ProjectService) Get(id string) (*Project, *http.Response, error) {\n\tproject := new(Project)\n\tapiError := new(APIError)\n\tpath := fmt.Sprintf(\"%s\", id)\n\tresp, err := c.sling.New().Get(path).Receive(project, apiError)\n\treturn project, resp, relevantError(err, *apiError)\n}", "func (s *Service) FindByName(name string) ([]*entity.Project, error) {\n\treturn s.repo.FindByName(name)\n}", "func (sw *scanWrap) Project(paths ...string) Scan {\n\treturn &scanWrap{\n\t\tscan: sw.scan.Project(paths...),\n\t}\n}", "func projectHandler(w http.ResponseWriter, r *http.Request) {\n\n\thelper.GetProjects(w, r)\n\n}", "func Get(ctx context.Context, client *selvpcclient.ServiceClient, id string) (*Project, *selvpcclient.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, resourceURL, id}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\treturn nil, responseResult, responseResult.Err\n\t}\n\n\t// Extract a project from the response body.\n\tvar result struct {\n\t\tProject *Project `json:\"project\"`\n\t}\n\terr = responseResult.ExtractResult(&result)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn result.Project, responseResult, nil\n}", "func (m *SystemMock) GetProjectHierarchy(projectToken string, inHouse bool) ([]Library, error) {\n\treturn m.Libraries, nil\n}", "func (s *Service) FindAll() ([]*entity.Project, error) {\n\treturn s.repo.FindAll()\n}", "func (p *BaseProcessor) ListTags() ([]*RepoTags, error) {\n\tprojects, err := p.Client.AllProjects(\"\", \"\")\n\tif err != nil {\n\t\tlogrus.Errorf(\"List projects error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tif len(p.Cfg.Projects) != 0 {\n\t\tprojectsMap := make(map[string]*harbor.Project)\n\t\tfor _, p := range projects {\n\t\t\tprojectsMap[p.Name] = p\n\t\t}\n\n\t\tvar configuredProjects []*harbor.Project\n\t\tfor _, p := range p.Cfg.Projects {\n\t\t\tif pinfo, ok := projectsMap[p]; ok {\n\t\t\t\tconfiguredProjects = append(configuredProjects, pinfo)\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"project %s not found\", p)\n\t\t\t}\n\t\t}\n\t\tprojects = configuredProjects\n\t}\n\n\tvar results []*RepoTags\n\tfor _, pinfo := range projects {\n\t\tlogrus.Infof(\"Start to collect images for project '%s'\", pinfo.Name)\n\t\trepos, err := p.Client.ListAllRepositories(pinfo.ProjectID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"list repos for project '%s' error: %v\", pinfo.Name, err)\n\t\t}\n\n\t\tfor _, repo := range repos {\n\t\t\tproj, r := utils.ParseRepository(repo.Name)\n\t\t\ttags, err := p.Client.ListTags(proj, r)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"List tags for '%s/%s' error: %v\", proj, r, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar tagsInfo []Tag\n\t\t\tfor _, tag := range tags {\n\t\t\t\ttagsInfo = append(tagsInfo, Tag{\n\t\t\t\t\tName: tag.Name,\n\t\t\t\t\tDigest: tag.Digest,\n\t\t\t\t\tCreated: tag.Created,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tresults = append(results, &RepoTags{Project: pinfo.Name, Repo: r, Tags: tagsInfo})\n\t\t}\n\t}\n\n\treturn results, nil\n}", "func (b *ProjectModels) GetProject(id string) (ProjectAll, error) {\n\tvar result ProjectAll\n\tjoin := fmt.Sprintf(\"join %s on %s.id = %s.project_id \", TblProjectDetail, PROJECT, TblProjectDetail)\n\twhere := fmt.Sprintf(\"%s.id = ?\", PROJECT)\n\tselects := fmt.Sprintf(\"%s.*,%s.*\", PROJECT, TblProjectDetail)\n\n\terr := configs.GetDB.Table(PROJECT).Select(selects).Joins(join).Where(where, id).Find(&result).Error\n\treturn result, err\n}", "func (d *Driver) ProjectGet(partitionID string) (*ProjectGetResponse, error) {\n\tresponse := &ProjectGetResponse{}\n\tgetProject := project.NewFindProjectParams()\n\tgetProject.ID = partitionID\n\tresp, err := d.project.FindProject(getProject, d.auth)\n\tif err != nil {\n\t\treturn response, err\n\t}\n\tresponse.Project = resp.Payload\n\treturn response, nil\n}", "func CommandShowProjects(conf Config, ctx, query Query) error {\n\tif len(query.IDs) > 0 || query.HasOperators() {\n\t\treturn errors.New(\"query/context not supported for show-projects\")\n\t}\n\n\tts, err := LoadTaskSet(conf.Repo, conf.IDsFile, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tts.DisplayProjects()\n\treturn nil\n}", "func (c PGClient) GetServicesByProject(projects []string) (*[]Service, error) {\n\tvar projectsID []int64\n\trows, err := c.DB.Query(\"select id from tProjects where name = any($1)\", pg.Array(projects))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor rows.Next() {\n\t\tvar tempID int64\n\t\terr := rows.Scan(&tempID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tprojectsID = append(projectsID, tempID)\n\t}\n\n\trows, err = c.DB.Query(\"select service_id from tServiceProjects where project_id=any($1)\", pg.Array(projectsID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserviceIDs := make([]int64, 0, 10)\n\tfor rows.Next() {\n\t\tvar tempID int64\n\t\terr := rows.Scan(&tempID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tserviceIDs = append(serviceIDs, tempID)\n\t}\n\trows, err = c.DB.Query(\"select id,name,host,port,type from tServices where id =any($1)\", pg.Array(serviceIDs))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres := make([]Service, 0, 200)\n\tfor rows.Next() {\n\t\tt := Service{}\n\t\tif err = rows.Scan(&t.ID, &t.Name, &t.Host, &t.Port, &t.Type); err != nil {\n\t\t\treturn &res, err\n\t\t}\n\t\tres = append(res, t)\n\t}\n\treturn &res, err\n}", "func (w *Workspace) FindProject(id string) *Project {\n\tfor i, p := range w.Projects {\n\t\tif p.Identifier == id {\n\t\t\treturn w.Projects[i]\n\t\t}\n\t}\n\treturn nil\n}", "func ProjectListAll(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Get Results Object\n\n\tres, err := projects.Find(\"\", \"\", refStr)\n\n\tif err != nil && err.Error() != \"not found\" {\n\t\terr := APIErrQueryDatastore()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func getProjectLanguages(project Project, counter int, path, fileNameToSearch string) (returnedProject Project, returnedCounter int, filePath string) {\n\treturnedProject = project\n\treturnedCounter = counter //set counter\n\tfiles, err := ioutil.ReadDir(path) //ReadDir returns a slice of FileInfo structs\n\tif isError(err) {\n\t\treturn\n\t}\n\tfor _, file := range files { //loop through each files and directories\n\t\tvar fileName = file.Name()\n\t\tif file.IsDir() { //skip if file is directory\n\t\t\tif fileName == \"Pods\" || fileName == \".git\" { //ignore Pods and .git directories\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar prevPath = path\n\t\t\tpath = path + \"/\" + fileName //update directory path by adding /fileName\n\t\t\treturnedProject, returnedCounter, filePath = getProjectLanguages(returnedProject, returnedCounter, path, fileNameToSearch) //recursively call this function again\n\t\t\tpath = prevPath //if not found, go to next directory, but update our path\n\t\t}\n\t\tfilePath = path + \"/\" + fileName //path of file\n\t\tif fileName == fileNameToSearch {\n\t\t\treturnedCounter += 1\n\t\t\tvar language = createLanguageFromPath(filePath)\n\t\t\treturnedProject.Languages = append(project.Languages, language)\n\t\t}\n\t}\n\treturn\n}", "func (o ShareSettingsOutput) Projects() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ShareSettings) []string { return v.Projects }).(pulumi.StringArrayOutput)\n}", "func ParserProjectFindOne(query db.Q) (*ParserProject, error) {\n\tproject := &ParserProject{}\n\terr := db.FindOneQ(ParserProjectCollection, query, project)\n\tif adb.ResultsNotFound(err) {\n\t\treturn nil, nil\n\t}\n\treturn project, err\n}", "func GetUserProjects(w http.ResponseWriter, r *http.Request) {\n\tregisteredUsers := user.Users{}\n\tregisteredUsersResp := getData(registeredUsersEndpoint)\n\tregisteredUsers.UnmarshalUsers(registeredUsersResp)\n\n\tunregisteredUsers := user.Users{}\n\tunregisteredUsersResp := getData(unregisteredusersEndpoint)\n\tunregisteredUsers.UnmarshalUsers(unregisteredUsersResp)\n\n\tusers := user.Users{}\n\tusers.UserList = append(registeredUsers.UserList, unregisteredUsers.UserList...)\n\n\tvar projects []project.Project = project.UnmarshalProjects(getData(projectsEndpoint))\n\tusersprojects := processUserProjects(users, projects)\n\n\tw.WriteHeader(http.StatusOK)\n\tresp, err := usersprojects.ToJSON()\n\terrs.HandleError(err)\n\tfmt.Fprintf(w, string(resp))\n}", "func (p *ProjectService) GetAll(ctx iris.Context) {\r\n\tvar dbData = map[string]interface{}{ \r\n\t\t\"dbName\" : c.SysDBName, \r\n\t\t\"collectionName\" : c.TrionConfig.DBConfig.MongoConfig.ProjectsColl,\r\n\t}\r\n\tvar filter = map[string]interface{}{} //init empty\r\n /*\r\n\tFiltering for content-type : application/json only.\r\n\t1. Detect if header declares content-type application/json\r\n\t2. If yes - parse json. If not - don't, empty filter.\r\n\trequest payload:\r\n\t{\r\n\t\t\"filter\" : {our filter json}\r\n\t}\r\n\t*/\r\n\tif strings.ToLower(ctx.GetContentTypeRequested()) == \"application/json\" {\r\n\t\tvar request map[string]interface{}\r\n\t\terr := ctx.ReadJSON(&request)\r\n\t\tif err != nil { c.BadRequestAfterErrorResponse(ctx,err); return }\r\n\r\n\t\t//validate schema\r\n\t\tdocLoader := gojsonschema.NewGoLoader(request)\r\n\t\tresult, err := p.ProjectFilterSchema.Validate(docLoader)\r\n\t\tif err != nil {\r\n\t\t\tc.BadRequestAfterErrorResponse(ctx,err)\r\n\t\t\treturn\r\n\t\t}\r\n\t\tif result.Valid() {\r\n\t\t\tv, ok := request[\"filter\"].(map[string]interface{})\r\n\t\t\tif ok { filter = v } \r\n\t\t} else { \r\n\t\t\tc.BadRequestAfterJSchemaValidationResponse(ctx,result) \r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n\t// get projects from DB\r\n\titemsMap, err:= p.DSS.Read(nil, filter, dbData); \r\n\terr=checkIfNotFound(err, len(itemsMap), filter) \r\n\tif err !=nil {\r\n\t\tc.APIErrorSwitch(ctx,err,c.SliceMapToJSONString(itemsMap))\r\n\t} else {\r\n\t\tc.StatusJSON(ctx,iris.StatusOK,\"%v\",c.SliceMapToJSONString(itemsMap))\r\n\t}\r\n\treturn\r\n}", "func (w *ServerInterfaceWrapper) GetProjects(ctx echo.Context) error {\n\tvar err error\n\n\t// Parameter object where we will unmarshal all parameters from the context\n\tvar params GetProjectsParams\n\t// ------------- Optional query parameter \"query\" -------------\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"query\", ctx.QueryParams(), &params.Query)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter query: %s\", err))\n\t}\n\n\t// ------------- Optional query parameter \"identifier\" -------------\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"identifier\", ctx.QueryParams(), &params.Identifier)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter identifier: %s\", err))\n\t}\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetProjects(ctx, params)\n\treturn err\n}", "func (mockProvider) GetAllProjectConfigs(c context.Context) (map[string]*tricium.ProjectConfig, error) {\n\treturn map[string]*tricium.ProjectConfig{}, nil\n}", "func (s *Server) List(ctx context.Context, q *ProjectQuery) (*v1alpha1.AppProjectList, error) {\n\tlist, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).List(metav1.ListOptions{})\n\tlist.Items = append(list.Items, v1alpha1.GetDefaultProject(s.ns))\n\tif list != nil {\n\t\tnewItems := make([]v1alpha1.AppProject, 0)\n\t\tfor i := range list.Items {\n\t\t\tproject := list.Items[i]\n\t\t\tif s.enf.EnforceClaims(ctx.Value(\"claims\"), \"projects\", \"get\", project.Name) {\n\t\t\t\tnewItems = append(newItems, project)\n\t\t\t}\n\t\t}\n\t\tlist.Items = newItems\n\t}\n\treturn list, err\n}", "func GetProjects() (projects []m.Project, err error) {\n\tfmt.Println(\"GetProjects()\")\n\tbody, err := authenticatedGet(\"projects\")\n\tif err != nil {\n\t\tfmt.Printf(\"Got an error loading projects: %s\", err.Error())\n\t\treturn\n\t}\n\n\tvar responseData projectResponse\n\terr = json.Unmarshal(body, &responseData)\n\tif err != nil {\n\t\tfmt.Printf(\"Got an error parsing unmarshalling projects response: %s\\n\", err.Error())\n\t\treturn\n\t}\n\n\tprojects = responseData.Data\n\n\treturn\n}", "func LookupProjects(ctx context.Context, host, repo string) ([]string, error) {\n\t// Fetch all MapPart entities for the given host and repo.\n\tmps, err := getAll(ctx, host, repo)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to fetch MapParts\").Err()\n\t}\n\tprjs := stringset.New(len(mps))\n\tfor _, mp := range mps {\n\t\tprjs.Add(mp.Project)\n\t}\n\treturn prjs.ToSortedSlice(), nil\n}", "func (data *ProjectData) ProjectRepos() []string {\n\treturn append([]string{\"jcenter()\"}, data.Lang.projectRepos()...)\n}", "func (a *Client) GetProjects(params *GetProjectsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetProjectsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetProjectsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"GetProjects\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/projects\",\n\t\tProducesMediaTypes: []string{\"application/json\", \"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetProjectsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetProjectsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for GetProjects: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}" ]
[ "0.649808", "0.61884755", "0.61773306", "0.61728644", "0.6160904", "0.6150968", "0.6148858", "0.61327946", "0.61255896", "0.6123783", "0.61141396", "0.6096289", "0.6066046", "0.60416514", "0.6032895", "0.6004244", "0.59767795", "0.59659183", "0.59482855", "0.5927783", "0.5922738", "0.5901618", "0.5869623", "0.5857388", "0.58559465", "0.5850671", "0.584789", "0.58461875", "0.58237123", "0.5799226", "0.57907027", "0.578966", "0.5786101", "0.5776273", "0.57688046", "0.5749167", "0.574892", "0.57474923", "0.57407874", "0.5740707", "0.5736178", "0.5730017", "0.57040256", "0.5692263", "0.56519383", "0.56306696", "0.5626261", "0.5618348", "0.5616497", "0.5614346", "0.5600437", "0.55908793", "0.5581202", "0.55788636", "0.5572146", "0.5565659", "0.55652416", "0.5554108", "0.5539582", "0.5530152", "0.55089694", "0.55072963", "0.5505247", "0.54918027", "0.54804295", "0.547942", "0.5478907", "0.54684997", "0.54649794", "0.54473317", "0.54451424", "0.54374087", "0.543299", "0.54257035", "0.54233277", "0.54169035", "0.54129016", "0.5410464", "0.5401031", "0.5389695", "0.5388224", "0.5379465", "0.53731215", "0.5371428", "0.53693175", "0.5365782", "0.5363842", "0.5363528", "0.53619856", "0.53555596", "0.53555536", "0.535302", "0.5351623", "0.53365916", "0.53349024", "0.53346026", "0.53287625", "0.5323683", "0.5319122", "0.53155273" ]
0.7243131
0
loginAttempt increments the number of login attempts in sessions variable
func loginAttempt(sess *sessions.Session) { // Log the attempt if sess.Values[sessLoginAttempt] == nil { sess.Values[sessLoginAttempt] = 1 } else { sess.Values[sessLoginAttempt] = sess.Values[sessLoginAttempt].(int) + 1 } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AuthenticateLoginAttempt(r *http.Request) *sessions.Session {\n\tvar userid string\n\tlog.Println(\"Authenticating Login credentials.\")\n\tattemptEmail := template.HTMLEscapeString(r.Form.Get(\"email\")) //Escape special characters for security.\n\tattemptPassword := template.HTMLEscapeString(r.Form.Get(\"password\")) //Escape special characters for security.\n\tlog.Println(\"Attempt email :\", attemptEmail, \"Attempt Password:\", attemptPassword)\n\trow := databases.GlobalDBM[\"mydb\"].Con.QueryRow(\"SELECT userid FROM user WHERE email = '\" + attemptEmail + \"' AND password = '\" + attemptPassword + \"'\")\n\terr := row.Scan(&userid)\n\tif err != nil { // User does not exist.\n\t\tlog.Println(\"User authentication failed.\")\n\t\treturn &sessions.Session{Status: sessions.DELETED}\n\t}\n\t//User exists.\n\tlog.Println(\"User authentication successful. Creating new Session.\")\n\treturn sessions.GlobalSM[\"usersm\"].SetSession(userid, time.Hour*24*3) // Session lives in DB for 3 days.\n}", "func AuthenticateLoginAttempt(r *http.Request) *sessions.Session {\n\tvar userid string\n\tlog.Println(\"Authenticating Login credentials.\")\n\tattemptEmail := template.HTMLEscapeString(r.Form.Get(\"email\")) //Escape special characters for security.\n\tattemptPassword := template.HTMLEscapeString(r.Form.Get(\"password\")) //Escape special characters for security.\n\tlog.Println(\"Attempt email :\", attemptEmail, \"Attempt Password:\", attemptPassword)\n\trow := databases.GlobalDBM[\"mydb\"].Con.QueryRow(\"SELECT userid FROM user WHERE email = '\" + attemptEmail + \"' AND password = '\" + attemptPassword + \"'\")\n\terr := row.Scan(&userid)\n\tif err != nil { // User does not exist.\n\t\tlog.Println(\"User authentication failed.\")\n\t\treturn &sessions.Session{Status: sessions.DELETED}\n\t}\n\t//User exists.\n\tlog.Println(\"User authentication successful. Creating new Session.\")\n\treturn sessions.GlobalSM[\"usersm\"].SetSession(userid, time.Hour*24*3) // Session lives in DB for 3 days.\n}", "func addLoginAttempt(usr string) {\n\tcurr_time := time.Now().Unix()\n\thashed_usr := Hash1(usr)\n\tquery := QUERY_INSERT_LAST_LOGIN\n\tExecDB(query, hashed_usr, curr_time)\n}", "func (dc *DatadogCollector) IncrementAttempts() {\n\t_ = dc.client.Count(dmAttempts, 1, dc.tags, 1.0)\n}", "func (atics *Analytics) UserLoginAttempt(successful bool, username string, message string) {\n\n\tproducer, err := atics.newKafkaProducer()\n\n\tif err != nil {\n\t\tlog.Warning(\"Error creating kafka producer.\")\n\t\treturn\n\t}\n\n\tdefer producer.Close()\n\n\t// Delivery report handler for produced messages\n\tgo func() {\n\t\tfor events := range producer.Events() {\n\t\t\tswitch ev := events.(type) {\n\t\t\tcase *kafka.Message:\n\t\t\t\tif ev.TopicPartition.Error != nil {\n\t\t\t\t\tlog.Warning(\"Delivery failed: \", ev.TopicPartition)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Warning(\"Delivered message to topic: \", ev.TopicPartition)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tmMessage, mErr := atics.createAnalyticsMessage(successful, username, message)\n\tif mErr != nil {\n\t\treturn\n\t}\n\n\tproducer.Produce(&kafka.Message{\n\t\tTopicPartition: kafka.TopicPartition{Topic: &atics.loginKafkaTopic, Partition: kafka.PartitionAny},\n\t\tValue: mMessage,\n\t}, nil)\n\n\t// Wait for message deliveries before shutting down\n\tproducer.Flush(15 * 1000)\n\n}", "func (u *MockUserRecord) NumLoginDays() int { return 0 }", "func UserLoginPost(w http.ResponseWriter, r *http.Request) {\n\tsess := session.Instance(r)\n\tvar loginResp webpojo.UserLoginResp\n\n\t// Prevent brute force login attempts by not hitting MySQL and pretending like it was invalid :-)\n\tif sess.Values[SessLoginAttempt] != nil && sess.Values[SessLoginAttempt].(int) >= 5 {\n\t\tlog.Println(\"Brute force login prevented\")\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_429, constants.Msg_429, \"/api/admin/login\")\n\t\tReturnJsonResp(w, loginResp)\n\t\treturn\n\t}\n\n\tbody, readErr := ioutil.ReadAll(r.Body)\n\tif readErr != nil {\n\t\tlog.Println(readErr)\n\t\tReturnError(w, readErr)\n\t\treturn\n\t}\n\n\tif len(body) == 0 {\n\t\tlog.Println(\"Empty json payload\")\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_400, constants.Msg_400, \"/api/admin/login\")\n\t\tReturnJsonResp(w, loginResp)\n\t\treturn\n\t}\n\n\t//log.Println(\"r.Body\", string(body))\n\tloginReq := webpojo.UserLoginReq{}\n\tjsonErr := json.Unmarshal(body, &loginReq)\n\tif jsonErr != nil {\n\t\tlog.Println(jsonErr)\n\t\tReturnError(w, jsonErr)\n\t\treturn\n\t}\n\tlog.Println(loginReq.Username)\n\n\t//should check for expiration\n\tif sess.Values[UserID] != nil && sess.Values[UserName] == loginReq.Username {\n\t\tlog.Println(\"Already signed in - session is valid!!\")\n\t\tsess.Save(r, w) //Should also start a new expiration\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_200, constants.Msg_200, \"/api/admin/leads\")\n\t\tReturnJsonResp(w, loginResp)\n\t\treturn\n\t}\n\n\tresult, dbErr := model.UserByEmail(loginReq.Username)\n\tif dbErr == model.ErrNoResult {\n\t\tlog.Println(\"Login attempt: \", sess.Values[SessLoginAttempt])\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_204, constants.Msg_204, \"/api/admin/login\")\n\t} else if dbErr != nil {\n\t\tlog.Println(dbErr)\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_500, constants.Msg_500, \"/error\")\n\t} else if passhash.MatchString(result.Password, loginReq.Password) {\n\t\tlog.Println(\"Login successfully\")\n\t\tsession.Empty(sess)\n\t\tsess.Values[UserID] = result.UserID()\n\t\tsess.Values[UserName] = loginReq.Username\n\t\tsess.Values[UserRole] = result.UserRole\n\t\tsess.Save(r, w) //Should also store expiration\n\t\tloginResp = webpojo.UserLoginResp{}\n\t\tloginResp.StatusCode = constants.StatusCode_200\n\t\tloginResp.Message = constants.Msg_200\n\t\tloginResp.URL = \"/api/admin/leads\"\n\t\tloginResp.FirstName = result.FirstName\n\t\tloginResp.LastName = result.LastName\n\t\tloginResp.UserRole = result.UserRole\n\t\tloginResp.Email = loginReq.Username\n\t} else {\n\t\tlog.Println(\"Login attempt: \", sess.Values[SessLoginAttempt])\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_404, constants.Msg_404, \"/api/admin/login\")\n\t}\n\n\tReturnJsonResp(w, loginResp)\n}", "func (serv *AppServer) Login(username string, password string) int {\n\th := sha256.New()\n\th.Write([]byte(password))\n\thashed := hex.EncodeToString(h.Sum(nil))\n\tret, _ := strconv.Atoi(serv.ServerRequest([]string{\"Login\", username, hashed}))\n\treturn ret\n}", "func Login(r *http.Request, username string, password string) (*Session, bool) {\n\tif PreLoginHandler != nil {\n\t\tPreLoginHandler(r, username, password)\n\t}\n\t// Get the user from DB\n\tuser := User{}\n\tGet(&user, \"username = ?\", username)\n\tif user.ID == 0 {\n\t\tIncrementMetric(\"uadmin/security/invalidlogin\")\n\t\tgo func() {\n\t\t\tlog := &Log{}\n\t\t\tif r.Form == nil {\n\t\t\t\tr.ParseForm()\n\t\t\t}\n\t\t\tctx := context.WithValue(r.Context(), CKey(\"login-status\"), \"invalid username\")\n\t\t\tr = r.WithContext(ctx)\n\t\t\tlog.SignIn(username, log.Action.LoginDenied(), r)\n\t\t\tlog.Save()\n\t\t}()\n\t\tincrementInvalidLogins(r)\n\t\treturn nil, false\n\t}\n\ts := user.Login(password, \"\")\n\tif s != nil && s.ID != 0 {\n\t\ts.IP = GetRemoteIP(r)\n\t\ts.Save()\n\t\tif s.Active && (s.ExpiresOn == nil || s.ExpiresOn.After(time.Now())) {\n\t\t\ts.User = user\n\t\t\tif s.User.Active && (s.User.ExpiresOn == nil || s.User.ExpiresOn.After(time.Now())) {\n\t\t\t\tIncrementMetric(\"uadmin/security/validlogin\")\n\t\t\t\t// Store login successful to the user log\n\t\t\t\tgo func() {\n\t\t\t\t\tlog := &Log{}\n\t\t\t\t\tif r.Form == nil {\n\t\t\t\t\t\tr.ParseForm()\n\t\t\t\t\t}\n\t\t\t\t\tlog.SignIn(user.Username, log.Action.LoginSuccessful(), r)\n\t\t\t\t\tlog.Save()\n\t\t\t\t}()\n\t\t\t\treturn s, s.User.OTPRequired\n\t\t\t}\n\t\t}\n\t} else {\n\t\tgo func() {\n\t\t\tlog := &Log{}\n\t\t\tif r.Form == nil {\n\t\t\t\tr.ParseForm()\n\t\t\t}\n\t\t\tctx := context.WithValue(r.Context(), CKey(\"login-status\"), \"invalid password or inactive user\")\n\t\t\tr = r.WithContext(ctx)\n\t\t\tlog.SignIn(username, log.Action.LoginDenied(), r)\n\t\t\tlog.Save()\n\t\t}()\n\t}\n\n\tincrementInvalidLogins(r)\n\n\t// Record metrics\n\tIncrementMetric(\"uadmin/security/invalidlogin\")\n\treturn nil, false\n}", "func (d *Dao) SecurityLoginCount(c context.Context, index int64, reason string, stime, etime time.Time) (res int64, err error) {\n\trow := d.db.QueryRow(c, fmt.Sprintf(_securityLoginCountSQL, hitHistory(index)), reason, stime, etime)\n\tif err = row.Scan(&res); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\terr = nil\n\t\t} else {\n\t\t\tlog.Error(\"row.Scan error(%v)\", err)\n\t\t}\n\t}\n\treturn\n}", "func (client *Client) Login() error {\n\tuserpass := fmt.Sprintf(\"%s_%s\", client.Username, client.Password)\n\thash := fmt.Sprintf(\"%x\", md5.Sum([]byte(userpass)))\n\tres, _, err := client.FormattedRequest(\"/login/%s\", hash)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient.sessionKey = res.ObjectsMap[\"status\"].PropertiesMap[\"response\"].Data\n\treturn nil\n}", "func Login(userName, password string) (Session, error) {\n\t// TODO: add check login attempts count\n\n\tsession := Session{}\n\taccount := Account{UserName: userName, Password: password}\n\n\tif err := mongo.Execute(\"monotonic\", AccountCollectionName(),\n\t\tfunc(collection *mgo.Collection) error {\n\t\t\tselector := bson.M{\n\t\t\t\t\"user_name\": account.UserName,\n\t\t\t\t\"password\": account.Password,\n\t\t\t}\n\t\t\treturn collection.Find(selector).One(&account)\n\t\t}); err != nil {\n\t\treturn session, fmt.Errorf(\"Error[%s] while login with username[%s] and password[%s]\", err, account.UserName, account.Password)\n\t}\n\n\tsession.TenantID = account.TenantID\n\tsession.AccountID = account.ID\n\tsession.SessionType = \"login\"\n\tsession.CreatedBy = account.Email\n\tif err := session.Insert(account.TenantID); err != nil {\n\t\treturn session, fmt.Errorf(\"Error[%s] while create session with username[%s] and password[%s]\", err, account.UserName, account.Password)\n\t}\n\treturn session, nil\n}", "func Login() gin.HandlerFunc {\r\n\tif gin.Mode() == \"debug\" {\r\n\t\treturn func(c *gin.Context) { c.Next() }\r\n\t}\r\n\treturn func(c *gin.Context) {\r\n\t\tsession := sessions.Default(c)\r\n\t\tUserID := session.Get(\"UserID\")\r\n\t\tIsLeader := session.Get(\"IsLeader\")\r\n\r\n\t\tfmt.Println(\"UserID, IsLeader\", UserID, IsLeader)\r\n\t\tif UserID == nil {\r\n\t\t\tstate := string([]byte(c.Request.URL.Path)[1:])\r\n\t\t\tc.Redirect(http.StatusFound, \"/login?state=\"+state)\r\n\t\t\tc.Abort()\r\n\t\t} else {\r\n\t\t\tc.Set(\"UserID\", UserID)\r\n\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\t\t\tc.Next()\r\n\t\t}\r\n\r\n\t}\r\n}", "func (m *TeamsAsyncOperation) SetAttemptsCount(value *int32)() {\n m.attemptsCount = value\n}", "func (cl *APIClient) Login(params ...string) *R.Response {\n\totp := \"\"\n\tif len(params) > 0 {\n\t\totp = params[0]\n\t}\n\tcl.SetOTP(otp)\n\trr := cl.Request(map[string]string{\"COMMAND\": \"StartSession\"})\n\tif rr.IsSuccess() {\n\t\tcol := rr.GetColumn(\"SESSION\")\n\t\tif col != nil {\n\t\t\tcl.SetSession(col.GetData()[0])\n\t\t} else {\n\t\t\tcl.SetSession(\"\")\n\t\t}\n\t}\n\treturn rr\n}", "func canLogin(usr string) string {\n\t//find the last time they logged in\n\tquery := QUERY_GET_LAST_LOGIN\n\trows := QueryDB(query, Hash1(usr))\n\tret := LOGIN_INVALID\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tlast int64\n\t\t)\n\t\terr = rows.Scan(&last)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error accessing rows (my_server.go: canLogin\")\n\t\t\tfmt.Println(err)\n\t\t\treturn LOGIN_INVALID\n\t\t}\n\t\tdiff := time.Now().Unix() - last\n\t\tif diff <= LOGIN_RATE {\n\t\t\tret = LOGIN_TIME\n\t\t}\n\t}\n\treturn ret\n}", "func loginHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := context.Background()\n\tif b.authenticator == nil {\n\t\tvar err error\n\t\tb.authenticator, err = initAuth(ctx)\n\t\tif err != nil {\n\t\t\tlog.Print(\"loginHandler authenticator could not be initialized\")\n\t\t\thttp.Error(w, \"Server error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\tsessionInfo := identity.InvalidSession()\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tlog.Printf(\"loginHandler: error parsing form: %v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tusername := r.PostFormValue(\"UserName\")\n\tlog.Printf(\"loginHandler: username = %s\", username)\n\tpassword := r.PostFormValue(\"Password\")\n\tusers, err := b.authenticator.CheckLogin(ctx, username, password)\n\tif err != nil {\n\t\tlog.Printf(\"main.loginHandler checking login, %v\", err)\n\t\thttp.Error(w, \"Error checking login\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif len(users) != 1 {\n\t\tlog.Printf(\"loginHandler: user %s not found or password does not match\", username)\n\t} else {\n\t\tcookie, err := r.Cookie(\"session\")\n\t\tif err == nil {\n\t\t\tlog.Printf(\"loginHandler: updating session: %s\", cookie.Value)\n\t\t\tsessionInfo = b.authenticator.UpdateSession(ctx, cookie.Value, users[0], 1)\n\t\t}\n\t\tif (err != nil) || !sessionInfo.Valid {\n\t\t\tsessionid := identity.NewSessionId()\n\t\t\tdomain := config.GetSiteDomain()\n\t\t\tlog.Printf(\"loginHandler: setting new session %s for domain %s\",\n\t\t\t\tsessionid, domain)\n\t\t\tcookie := &http.Cookie{\n\t\t\t\tName: \"session\",\n\t\t\t\tValue: sessionid,\n\t\t\t\tDomain: domain,\n\t\t\t\tPath: \"/\",\n\t\t\t\tMaxAge: 86400 * 30, // One month\n\t\t\t}\n\t\t\thttp.SetCookie(w, cookie)\n\t\t\tsessionInfo = b.authenticator.SaveSession(ctx, sessionid, users[0], 1)\n\t\t}\n\t}\n\tif strings.Contains(r.Header.Get(\"Accept\"), \"application/json\") {\n\t\tsendJSON(w, sessionInfo)\n\t} else {\n\t\tif sessionInfo.Authenticated == 1 {\n\t\t\ttitle := b.webConfig.GetVarWithDefault(\"Title\", defTitle)\n\t\t\tcontent := htmlContent{\n\t\t\t\tTitle: title,\n\t\t\t}\n\t\t\tb.pageDisplayer.DisplayPage(w, \"index.html\", content)\n\t\t} else {\n\t\t\tloginFormHandler(w, r)\n\t\t}\n\t}\n}", "func Test_Login_MultiLogin(t *testing.T) {\n\tgSession = nil\n\tsession1, err := login(TestValidUser)\n\tif session1 == nil || err != nil {\n\t\tt.Error(\"fail at login\")\n\t}\n\tsession2, err := login(TestValidUser)\n\tif err != nil {\n\t\tt.Error(\"fail at login\")\n\t}\n\tif session1 != session2 {\n\t\tt.Error(\"multi login should get same session\")\n\t}\n}", "func (_Userable *UserableSession) Login() (string, error) {\n\treturn _Userable.Contract.Login(&_Userable.CallOpts)\n}", "func (m *Miner) increaseAttempts() {\n\tm.attempts++\n\tif m.attempts >= 100 {\n\t\tm.hashRate = int64((m.attempts * iterationsPerAttempt * 1e9)) / (time.Now().UnixNano() - m.startTime.UnixNano())\n\t\tm.startTime = time.Now()\n\t\tm.attempts = 0\n\t}\n}", "func (u *User) PostLogin(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\n\tw.Header().Set(\"Cache-Control\", \"no-store\")\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"Pragma\", \"no-cache\")\n\n\t// If the session already exists, redirect them back to the home page.\n\t// if ok := u.session.HasSession(r); ok {\n\t// http.Redirect(w, r, \"/\", http.StatusFound)\n\t// return\n\t// }\n\n\tvar req Credentials\n\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\t// Check if the user is logging with many failed attempts.\n\tif locked := u.appsensor.IsLocked(req.Email); locked {\n\t\twriteError(w, http.StatusTooManyRequests, errors.New(\"too many attempts\"))\n\t\treturn\n\t}\n\n\tuser, err := u.service.Login(req.Email, req.Password)\n\tif err != nil {\n\t\t// Log attempts here.\n\t\tu.appsensor.Increment(req.Email)\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tprovideToken := func(userid string) (string, error) {\n\t\tvar (\n\t\t\taud = \"https://server.example.com/login\"\n\t\t\tsub = userid\n\t\t\tiss = userid\n\t\t\tiat = time.Now().UTC()\n\t\t\texp = iat.Add(2 * time.Hour)\n\n\t\t\tkey = []byte(\"access_token_secret\")\n\t\t)\n\t\tclaims := crypto.NewStandardClaims(aud, sub, iss, iat.Unix(), exp.Unix())\n\t\treturn crypto.NewJWT(key, claims)\n\t}\n\n\taccessToken, err := provideToken(user.ID)\n\tif err != nil {\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\t// Set the user session.\n\tu.session.SetSession(w, user.ID)\n\n\t// Set success ok.\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(M{\n\t\t\"access_token\": accessToken,\n\t})\n}", "func (authentication *Authentication) IsLogin(res http.ResponseWriter, req *http.Request) bool {\n\tsessionID, sessionIDState := cookies.GetCookie(req, \"session\")\n\tif !sessionIDState {\n\t\treturn false\n\t}\n\tsession, sessionState := authentication.userSession[sessionID.Value]\n\tif sessionState {\n\t\tsession.lastActivity = time.Now()\n\t\tauthentication.userSession[sessionID.Value] = session\n\t}\n\t_, userState := authentication.loginUser[session.email]\n\tsessionID.Path = \"/\"\n\tsessionID.MaxAge = sessionExistTime\n\thttp.SetCookie(res, sessionID)\n\treturn userState\n}", "func (e *EndpointSessions) auth(writer http.ResponseWriter, request *http.Request) {\n\tlogin := request.Header.Get(\"login\")\n\tpwd := request.Header.Get(\"password\")\n\tagent := request.Header.Get(\"User-Agent\")\n\tclient := request.Header.Get(\"client\")\n\n\t//try to do something against brute force attacks, see also https://www.owasp.org/index.php/Blocking_Brute_Force_Attacks\n\ttime.Sleep(1000 * time.Millisecond)\n\n\t//another funny idea is to return a fake session id, after many wrong login attempts\n\n\tif len(login) < 3 {\n\t\thttp.Error(writer, \"login too short\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif len(agent) == 0 {\n\t\thttp.Error(writer, \"user agent missing\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif len(pwd) < 4 {\n\t\thttp.Error(writer, \"password too short\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif len(client) == 0 {\n\t\thttp.Error(writer, \"client missing\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tallowed := false\n\tfor _, allowedClient := range allowedClients {\n\t\tif allowedClient == client {\n\t\t\tallowed = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !allowed {\n\t\thttp.Error(writer, \"client is invalid\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tusr, err := e.users.FindByLogin(login)\n\n\tif err != nil {\n\t\tif db.IsEntityNotFound(err) {\n\t\t\thttp.Error(writer, \"credentials invalid\", http.StatusForbidden)\n\t\t} else {\n\t\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\t}\n\n\t\treturn\n\t}\n\n\tif !usr.Active {\n\t\thttp.Error(writer, \"credentials invalid\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif !usr.PasswordEquals(pwd){\n\t\thttp.Error(writer, \"credentials invalid\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\t//login is fine now, create a session\n\tcurrentTime := time.Now().Unix()\n\tses := &session.Session{User: usr.Id, LastUsedAt: currentTime, CreatedAt: currentTime, LastRemoteAddr: request.RemoteAddr, LastUserAgent: agent}\n\terr = e.sessions.Create(ses)\n\tif err != nil {\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tWriteJSONBody(writer, &sessionDTO{Id: ses.Id, User: usr.Id})\n}", "func (m *TeamsAsyncOperation) GetAttemptsCount()(*int32) {\n return m.attemptsCount\n}", "func (db *DataBase) Login(name, password string) (int32, error) {\n\n\tvar (\n\t\ttx *sql.Tx\n\t\tuserID int32\n\t\terr error\n\t)\n\n\tif tx, err = db.Db.Begin(); err != nil {\n\t\treturn 0, err\n\t}\n\tdefer tx.Rollback()\n\n\tif userID, _, err = db.checkBunch(tx, name, password); err != nil {\n\t\treturn userID, err\n\t}\n\n\terr = tx.Commit()\n\treturn userID, err\n}", "func LoginAction(w http.ResponseWriter, r *http.Request) {\n\n\tpageVars := PageVars{}\n\taddPageVars(r, &pageVars)\n\n\tuserName := r.FormValue(\"userName\")\n\t// validate username\n\tif len(userName) <= 0 {\n\t\thttp.Redirect(w, r, \"/login?errorM=Username specified\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tpassword := r.FormValue(\"password\")\n\t// validate password\n\tif len(password) <= 0 {\n\t\thttp.Redirect(w, r, \"/login?errorM=Password specified\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\t// get expected password\n\texpectedPassword := getStringFromDB(\"Users\", userName)\n\n\t// verify the password\n\tif expectedPassword != password {\n\t\thttp.Redirect(w, r, \"/login?errorM=Invalid credentials\", http.StatusSeeOther)\n\t\treturn\n\t}\n\t\n\t// Create a new random session token\n\tsessionToken, err := uuid.NewUUID()\n\tif err != nil {\n\t\thttp.Redirect(w, r, \"/login?errorM=Unable to create token\", http.StatusSeeOther)\n\t}\n\t// Set the token in the db, along with the userName\n\tupdateDBString(\"Sessions\", userName, sessionToken.String())\n\n\t// set the expiration time\n\texpires := time.Now().Add(600 * time.Second)\n\tck := http.Cookie{\n Name: \"JSESSION_ID\",\n Path: \"/\",\n\t\tExpires: expires,\n\t\tValue: userName+\"_\"+sessionToken.String(),\n\t}\n\n // write the cookie to response\n http.SetCookie(w, &ck)\n\thttp.Redirect(w, r, \"/listbuckets\", http.StatusSeeOther)\n\n}", "func Login(params []byte) ([]byte, uint32) {\n\tif !initialized {\n\t\treturn nil, uint32(0xFFFFFFFF)\n\t}\n\tparameters := NEXString{}.FromBytes(params)\n\tfmt.Println(\"User \" + parameters.String + \" is trying to authenticate...\")\n\tresultcode := uint32(0x8068000B)\n\tbyteresult := []byte{0x0,0x0,0x0,0x0}\n\tbinary.LittleEndian.PutUint32(byteresult, resultcode)\n\treturn byteresult, resultcode\n}", "func (_Userable *UserableCallerSession) Login() (string, error) {\n\treturn _Userable.Contract.Login(&_Userable.CallOpts)\n}", "func (ctn *Connection) login(policy *ClientPolicy, hashedPassword []byte, sessionInfo *sessionInfo) Error {\n\t// need to authenticate\n\tif policy.RequiresAuthentication() {\n\t\tvar err Error\n\t\tcommand := newLoginCommand(ctn.dataBuffer)\n\n\t\tif !sessionInfo.isValid() {\n\t\t\terr = command.login(policy, ctn, hashedPassword)\n\t\t} else {\n\t\t\terr = command.authenticateViaToken(policy, ctn, sessionInfo.token)\n\t\t\tif err != nil && err.Matches(types.INVALID_CREDENTIAL, types.EXPIRED_SESSION) {\n\t\t\t\t// invalidate the token\n\t\t\t\tif ctn.node != nil {\n\t\t\t\t\tctn.node.resetSessionInfo()\n\t\t\t\t}\n\n\t\t\t\t// retry via user/pass\n\t\t\t\tif hashedPassword != nil {\n\t\t\t\t\tcommand = newLoginCommand(ctn.dataBuffer)\n\t\t\t\t\terr = command.login(policy, ctn, hashedPassword)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\tif ctn.node != nil {\n\t\t\t\tatomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1)\n\t\t\t}\n\t\t\t// Socket not authenticated. Do not put back into pool.\n\t\t\tctn.Close()\n\t\t\treturn err\n\t\t}\n\n\t\tsi := command.sessionInfo()\n\t\tif ctn.node != nil && si.isValid() {\n\t\t\tctn.node.sessionInfo.Store(si)\n\t\t}\n\t}\n\n\treturn nil\n}", "func CheckLogin(w http.ResponseWriter, r *http.Request) bool {\n\tCookieSession, err := r.Cookie(\"sessionid\")\n\tif err != nil {\n\t\tfmt.Println(\"No Such Cookies\")\n\t\tSession.Create()\n\t\tfmt.Println(Session.ID)\n\t\tSession.Expire = time.Now().Local()\n\t\tSession.Expire.Add(time.Hour)\n\t\treturn false\n\t}\n\tfmt.Println(\"Cookki Found\")\n\ttempSession := session.UserSession{UID: 0}\n\tLoggedIn := database.QueryRow(\"select user_id from sessions where session_id = ?\",\n\t\tCookieSession).Scan(&tempSession)\n\tif LoggedIn == nil {\n\t\treturn false\n\t}\n\treturn true\n\n}", "func login(p *pkcs11.Ctx, session pkcs11.SessionHandle, passRetriever notary.PassRetriever) error {\n\n\tfor attempts := 0; ; attempts++ {\n\t\tvar (\n\t\t\tgiveup bool\n\t\t\terr error\n\t\t\tpasswd string\n\t\t)\n\t\tif userPin == \"\" {\n\t\t\tpasswd, giveup, err = passRetriever(\"Partition Password\", \"luna\", false, attempts)\n\t\t} else {\n\t\t\tgiveup = false\n\t\t\tpasswd = userPin\n\t\t}\n\n\t\t// Check if the passphrase retriever got an error or if it is telling us to give up\n\t\tif giveup || err != nil {\n\t\t\treturn trustmanager.ErrPasswordInvalid{}\n\t\t}\n\t\tif attempts > 2 {\n\t\t\treturn trustmanager.ErrAttemptsExceeded{}\n\t\t}\n\n\t\terr = p.Login(session, pkcs11.CKU_USER, passwd)\n\t\tif err == nil {\n\t\t\tif userPin == \"\" {\n\t\t\t\tuserPin = passwd\n\t\t\t}\n\t\t\treturn nil\n\t\t} else {\n\t\t\tuserPin = \"\"\n\t\t}\n\t}\n\treturn fmt.Errorf(\"Unable to login to the session\")\n}", "func TryLogin(s sessions.Session,\n\trd render.Render,\n\temployeeRepository IEmployeeRepository,\n\tmodel LoginFormModel) {\n\t_, err := employeeRepository.AuthenticateEmployee(model.Login, model.Password)\n\tif err == nil {\n\t\ts.Set(\"login\", model.Login)\n\t\trd.Redirect(\"/\", http.StatusMovedPermanently)\n\t} else {\n\t\trd.Redirect(\"/login\")\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request, username string) error {\n\tsession, err := loggedUserSession.New(r, \"authenticated-user-session\")\n\tsession.Values[\"username\"] = username\n\tif err == nil {\n\t\terr = session.Save(r, w)\n\t}\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn errors.New(\"Error creating session\")\n\t}\n\treturn err\n}", "func (s *PipelineExecutionStep) SetAttemptCount(v int64) *PipelineExecutionStep {\n\ts.AttemptCount = &v\n\treturn s\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\n\t// Start the session.\n\tsession := sessions.Start(w, r)\n\tif len(session.GetString(\"username\")) != 0 && checkErr(w, r, err) {\n\t\t// Redirect to index page if the user isn't signed in. Will remove later.\n\t\thttp.Redirect(w, r, \"/\", 302)\n\t}\n\n\tif r.Method != \"POST\" {\n\t\tvar data = map[string]interface{}{\n\t\t\t\"Title\": \"Log In\",\n\t\t}\n\n\t\terr := templates.ExecuteTemplate(w, \"login.html\", data)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tusers := QueryUser(username)\n\n\t// Compare inputted password to the password in the database. If they're the same, return nil.\n\tvar password_compare = bcrypt.CompareHashAndPassword([]byte(users.Password), []byte(password))\n\n\tif password_compare == nil {\n\n\t\tsession := sessions.Start(w, r)\n\t\tsession.Set(\"username\", users.Username)\n\t\tsession.Set(\"user_id\", users.ID)\n\t\thttp.Redirect(w, r, \"/\", 302)\n\n\t} else {\n\n\t\thttp.Redirect(w, r, \"/login\", 302)\n\n\t}\n\n}", "func (c *Client) Login(username, password string) error {\n\tvar errAuth error\n\tc.sessionID, errAuth = a10v21Auth(c.host, username, password)\n\treturn errAuth\n}", "func SessionID() int64 { return time.Now().UnixNano() }", "func userLoginProcessing(userName string, password string, cookie string) (bool, int) {\n\tvar loginUser users\n\tvar userInitial userLoginStruct\n\n\tdb := dbConn()\n\tdefer db.Close()\n\n\t// login page defined token checking\n\tloginTokenCheck := db.QueryRow(\"SELECT event_id,used FROM user_initial_login WHERE token=? and used=0\", cookie).Scan(&userInitial.eventID, &userInitial.used)\n\n\tif loginTokenCheck != nil {\n\t\tlog.Println(\"user_initial_login table read faild\") // posible system error or hacking attempt ?\n\t\tlog.Println(loginTokenCheck)\n\t\treturn false, 0\n\t}\n\n\t// update initial user details table\n\tinitialUpdate, initErr := db.Prepare(\"update user_initial_login set used=1 where event_id=?\")\n\n\tif initErr != nil {\n\t\tlog.Println(\"Couldnt update initial user table\")\n\t\treturn false, 0 // we shouldnt compare password\n\t}\n\n\t_, updateErr := initialUpdate.Exec(userInitial.eventID)\n\n\tif updateErr != nil {\n\t\tlog.Println(\"Couldnt execute initial update\")\n\n\t}\n\tlog.Printf(\"Initial table updated for event id %d : \", userInitial.eventID)\n\t// end login page token checking\n\n\treadError := db.QueryRow(\"SELECT id,password FROM car_booking_users WHERE username=?\", userName).Scan(&loginUser.id, &loginUser.password)\n\tdefer db.Close()\n\tif readError != nil {\n\t\t//http.Redirect(res, req, \"/\", 301)\n\t\tlog.Println(\"data can not be taken\")\n\n\t}\n\n\tcomparePassword := bcrypt.CompareHashAndPassword([]byte(loginUser.password), []byte(password))\n\n\t// https://stackoverflow.com/questions/52121168/bcrypt-encryption-different-every-time-with-same-input\n\n\tif comparePassword != nil {\n\t\t/*\n\t\t\tHere I need to find a way to make sure that initial token is not get created each time wrong username password\n\n\t\t\tAlso Need to implement a way to restrict accessing after 5 attempts\n\t\t*/\n\t\tlog.Println(\"Wrong user name password\")\n\t\treturn false, 0\n\t} //else {\n\n\tlog.Println(\"Hurray\")\n\treturn true, userInitial.eventID\n\t//}\n\n}", "func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string) error {\n\tsession, err := skyring.Store.Get(req, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error Getting the session. error: %v\", err)\n\t\treturn err\n\t}\n\tif !session.IsNew {\n\t\tif session.Values[\"username\"] == u {\n\t\t\tlogger.Get().Info(\"User %s already logged in\", u)\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn mkerror(\"user \" + session.Values[\"username\"].(string) + \" is already logged in\")\n\t\t}\n\t}\n\terrStrNotAllowed := \"This user is not allowed. Status Disabled\"\n\t// Verify user allowed to user usm with group privilage in the db\n\tif user, err := a.userDao.User(u); err == nil {\n\t\terrStr := fmt.Sprintf(\"Password does not match for user: %s\", u)\n\t\tif user.Status {\n\t\t\tif user.Type == authprovider.External {\n\t\t\t\tif LdapAuth(a, u, p) {\n\t\t\t\t\tlogger.Get().Info(\"Login Success for LDAP\")\n\t\t\t\t} else {\n\t\t\t\t\tlogger.Get().Error(errStr)\n\t\t\t\t\treturn mkerror(errStr)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tverify := bcrypt.CompareHashAndPassword(user.Hash, []byte(p))\n\t\t\t\tif verify != nil {\n\t\t\t\t\tlogger.Get().Error(errStr)\n\t\t\t\t\treturn mkerror(errStr)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Get().Error(errStrNotAllowed)\n\t\t\treturn mkerror(errStrNotAllowed)\n\t\t}\n\t} else {\n\t\tlogger.Get().Error(\"User does not exist: %s\", user)\n\t\treturn mkerror(\"User does not exist\")\n\t}\n\t// Update the new username in session before persisting to DB\n\tsession.Values[\"username\"] = u\n\tif err = session.Save(req, rw); err != nil {\n\t\tlogger.Get().Error(\"Error saving the session for user: %s. error: %v\", u, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c UserInfo) Login(DiscordToken *models.DiscordToken) revel.Result {\n\tinfo, _ := c.Session.Get(\"DiscordUserID\")\n\tvar DiscordUser models.DiscordUser\n\tif info == nil {\n\t\tuserbytevalue, StatusCode := oAuth2Discord(DiscordToken.AccessToken)\n\t\tjson.Unmarshal(userbytevalue, &DiscordUser)\n\n\t\t// If we have an invalid status code, then that means we don't have the right\n\t\t// access token. So return.\n\t\tif StatusCode != 200 && StatusCode != 201 {\n\t\t\tc.Response.Status = StatusCode\n\t\t\treturn c.Render()\n\t\t}\n\t\t// Assign to the session, the discorduser ID.\n\t\t// If we've reached here, that must mean we've properly authenticated.\n\t\tc.Session[\"DiscordUserID\"] = DiscordUser.ID\n\t}\n\tc.Response.Status = 201\n\treturn c.Render()\n}", "func (m *MgoUserManager) Login(id interface{}, stay time.Duration) (string, error) {\n\tif stay < m.OnlineThreshold {\n\t\tstay = m.OnlineThreshold\n\t}\n\n\toid, err := getId(id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstate := LoginState{\n\t\tExpiredOn: time.Now().Add(stay),\n\t\tUserId: oid,\n\t\tToken: oid.Hex() + base64.URLEncoding.\n\t\t\tEncodeToString(securecookie.GenerateRandomKey(64)),\n\t}\n\n\terr = m.LoginColl.Insert(&state)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn state.Token, nil\n}", "func (h *TestAuth) Login(w http.ResponseWriter, req *http.Request) {\n\n\tresponse := make(map[string]string, 5)\n\n\tresponse[\"state\"] = authz.AuthNewPasswordRequired\n\tresponse[\"access_token\"] = \"access\"\n\t//response[\"id_token\"] = *authResult.IdToken\n\tresponse[\"refresh_token\"] = \"refersh\"\n\tresponse[\"expires\"] = \"3600\"\n\tresponse[\"token_type\"] = \"Bearer\"\n\trespData, _ := json.Marshal(response)\n\tw.WriteHeader(200)\n\tfmt.Fprint(w, string(respData))\n}", "func (r Repository) IncreaseValidateAttempt(ctx context.Context, uniqueID string, amount int) (int, error) {\n\tvalKey := generateOtpValidateAttemptKey(uniqueID)\n\n\tresult, err := r.redis.IncrementBy(ctx, valKey, amount)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// set the expiry of validate attempt\n\tif _, err := r.redis.Expire(ctx, valKey, int(durationExpireVAlidateAttempt)); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn result, err\n}", "func LoginCook(name string, r *http.Request) (models.Session, models.Auth, error) {\n\n\tvar session models.Session\n\tauth := models.Auth{\n\t\tName: \"\",\n\t\tLevel: models.CookLevel,\n\t\tAuthorizedLevel: models.CookLevel,\n\t}\n\n\tc := Controller{}\n\n\tdata, err := c.Load(r)\n\n\tif err != nil {\n\t\treturn session, auth, err\n\t}\n\n\tvar users []models.User\n\tfor _, u := range data.Users {\n\t\tif u.Search() == strings.ToLower(name) {\n\t\t\tusers = append(users, u)\n\t\t}\n\t}\n\n\tif len(users) == 1 {\n\t\tuser := users[0]\n\t\t// update the user\n\t\tvar updated []models.User\n\t\tfor _, u := range c.Data.Users {\n\t\t\tif u.ID == user.ID {\n\t\t\t\tuser.LastLoginDate = time.Now()\n\t\t\t\tupdated = append(updated, user)\n\t\t\t} else {\n\t\t\t\tupdated = append(updated, u)\n\t\t\t}\n\t\t}\n\n\t\tc.SetUsers(updated)\n\n\t\tsessionUUID, _ := uuid.NewUUID()\n\n\t\tsession.UserID = user.ID\n\t\tsession.UserName = user.Name\n\t\tsession.UserLevel = user.UserLevel\n\t\tsession.AuthorizedLevel = models.CookLevel\n\t\tsession.UUID = sessionUUID.String()\n\t\tsession.Expires = time.Now().Add(10 * time.Hour)\n\n\t\t// store level in auth, to see if further login is required later\n\t\tauth.Name = user.Name\n\t\tauth.Level = user.UserLevel\n\t\t// start as a cook\n\t\tauth.AuthorizedLevel = session.AuthorizedLevel\n\n\t\t// add the session\n\t\tsessions := c.Data.Sessions\n\t\tsessions = append(sessions, session)\n\n\t\terr = c.StoreSessions(sessions, r)\n\n\t\tif err != nil {\n\t\t\treturn session, auth, err\n\t\t}\n\n\t} else {\n\t\treturn session, auth, errTooManyUsers\n\t}\n\n\treturn session, auth, nil\n}", "func Login(r * http.Request, response * APIResponse) {\n\tif r.FormValue(\"username\") != \"\" && r.FormValue(\"password\") != \"\" {\n\t\thashedPassword := hashString(r.FormValue(\"password\"))\n\t\tusername := strings.ToLower(r.FormValue(\"username\"))\n\t\tfor i := 0; i < len(Users); i++ {\n\t\t\tif Users[i].Username == username && Users[i].HashedPassword == hashedPassword {\n\t\t\t\tuser := Users[i]\n\t\t\t\tdateNow := time.Now()\n\t\t\t\tkeyEndTime := dateNow.AddDate(0, 1, 0) //New date one month away\n\t\t\t\tkeyString := randomKey()\n\t\t\t\tkey := Key{keyString, user.ID, dateNow, keyEndTime}\n\t\t\t\tAddKey(&key)\n\t\t\t\t\n\t\t\t\tresponse.Message = \"User successfully logged in\"\n\t\t\t\t\n\t\t\t\tapiLoginResponse := APILoginResponse{}\n\t\t\t\tapiLoginResponse.Username = username\n\t\t\t\tapiLoginResponse.KeyCode = keyString\n\t\t\t\tapiLoginResponse.UserImage = user.UserImageURL\n\t\t\t\tapiLoginResponse.Name = user.RealName\n\t\t\t\tapiLoginResponse.UserID = user.ID\n\t\t\t\t\n\t\t\t\tresponse.Data = apiLoginResponse\n\t\t\t\t\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\tresponse.Message = \"More information required for login\"\n\t\tresponse.SuccessCode = 400 //More information required\n\t}\n}", "func Login2FA(r *http.Request, username string, password string, otpPass string) *Session {\n\ts, otpRequired := Login(r, username, password)\n\tif s != nil {\n\t\tif otpRequired && s.User.VerifyOTP(otpPass) {\n\t\t\ts.PendingOTP = false\n\t\t\ts.Save()\n\t\t} else if otpRequired && !s.User.VerifyOTP(otpPass) && otpPass != \"\" {\n\t\t\tincrementInvalidLogins(r)\n\t\t}\n\t\treturn s\n\t}\n\treturn nil\n}", "func (k *Kerberos) Login(encST, encAuthenticator string) (string, error) {\n\tst := &kerberosServiceTicket{}\n\tif err := k.decrypt(encST, k.appSecretKey, st); err != nil {\n\t\treturn \"\", errSTInvalid\n\t}\n\tif st.Expired < time.Now().Unix() {\n\t\treturn \"\", errSTInvalid\n\t}\n\n\tauthenticator := &kerberosAuthenticator{}\n\tif err := k.decrypt(encAuthenticator, st.CSSK, authenticator); err != nil {\n\t\treturn \"\", errAuthenticatorInvalid\n\t}\n\n\tif authenticator.Username != st.Username ||\n\t\ttime.Now().Unix()-authenticator.Timestamp > int64(300) {\n\t\treturn \"\", errAuthenticatorInvalid\n\t}\n\n\treturn authenticator.Username, nil\n}", "func (c *Controller) Login(email, password string) error {\n\tinfo, err := Login(email, password, \"\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"login controller\")\n\t}\n\tc.sessionInfoLock.Lock()\n\tc.sessionInfo = info\n\tc.sessionInfoLock.Unlock()\n\treturn nil\n}", "func (cl *APIClient) LoginExtended(params ...interface{}) *R.Response {\n\totp := \"\"\n\tparameters := map[string]string{}\n\tif len(params) == 2 {\n\t\totp = params[1].(string)\n\t}\n\tcl.SetOTP(otp)\n\tif len(params) > 0 {\n\t\tparameters = params[0].(map[string]string)\n\t}\n\tcmd := map[string]string{\n\t\t\"COMMAND\": \"StartSession\",\n\t}\n\tfor k, v := range parameters {\n\t\tcmd[k] = v\n\t}\n\trr := cl.Request(cmd)\n\tif rr.IsSuccess() {\n\t\tcol := rr.GetColumn(\"SESSION\")\n\t\tif col != nil {\n\t\t\tcl.SetSession(col.GetData()[0])\n\t\t} else {\n\t\t\tcl.SetSession(\"\")\n\t\t}\n\t}\n\treturn rr\n}", "func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string) error {\n\tsession, err := skyring.Store.Get(req, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error getting the session for user: %s. error: %v\", u, err)\n\t\treturn err\n\t}\n\tif !session.IsNew {\n\t\tif session.Values[\"username\"] == u {\n\t\t\tlogger.Get().Info(\"User: %s already logged in\", u)\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn mkerror(\"user \" + session.Values[\"username\"].(string) + \" is already logged in\")\n\t\t}\n\t}\n\tif user, err := a.userDao.User(u); err == nil {\n\t\tif user.Type == authprovider.Internal && user.Status {\n\t\t\tverify := bcrypt.CompareHashAndPassword(user.Hash, []byte(p))\n\t\t\tif verify != nil {\n\t\t\t\tlogger.Get().Error(\"Password does not match for user: %s\", u)\n\t\t\t\treturn mkerror(\"password doesn't match\")\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Get().Error(\"User: %s is not allowed by localauthprovider\", u)\n\t\t\treturn mkerror(\"This user is not allowed by localauthprovider\")\n\t\t}\n\t} else {\n\t\tlogger.Get().Error(\"User: %s not found\", u)\n\t\treturn mkerror(\"user not found\")\n\t}\n\n\t// Update the new username in session before persisting to DB\n\tsession.Values[\"username\"] = u\n\tif err = session.Save(req, rw); err != nil {\n\t\tlogger.Get().Error(\"Error saving the session for user: %s. error: %v\", u, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (as *AdminServer) Login(w http.ResponseWriter, r *http.Request) {\n\tparams := struct {\n\t\tUser models.User\n\t\tTitle string\n\t\tFlashes []interface{}\n\t\tToken string\n\t}{Title: \"Login\", Token: csrf.Token(r)}\n\tsession := ctx.Get(r, \"session\").(*sessions.Session)\n\tswitch {\n\tcase r.Method == \"GET\":\n\t\tparams.Flashes = session.Flashes()\n\t\tsession.Save(r, w)\n\t\ttemplates := template.New(\"template\")\n\t\t_, err := templates.ParseFiles(\"templates/login.html\", \"templates/flashes.html\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\ttemplate.Must(templates, err).ExecuteTemplate(w, \"base\", params)\n\tcase r.Method == \"POST\":\n\t\t// Find the user with the provided username\n\t\tusername, password := r.FormValue(\"username\"), r.FormValue(\"password\")\n\t\tu, err := models.GetUserByUsername(username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\t// Validate the user's password\n\t\terr = auth.ValidatePassword(password, u.Hash)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\tif u.AccountLocked {\n\t\t\tas.handleInvalidLogin(w, r, \"Account Locked\")\n\t\t\treturn\n\t\t}\n\t\tu.LastLogin = time.Now().UTC()\n\t\terr = models.PutUser(&u)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\t// If we've logged in, save the session and redirect to the dashboard\n\t\tsession.Values[\"id\"] = u.Id\n\t\tsession.Save(r, w)\n\t\tas.nextOrIndex(w, r)\n\t}\n}", "func (c UserInfo) TestLogin(DiscordToken *models.DiscordToken) revel.Result {\n\tif DiscordToken.AccessToken == keys.TestAuthKey {\n\t\tc.Response.Status = 201\n\t\tc.Session[\"DiscordUserID\"] = \"Test\"\n\t} else {\n\t\tc.Response.Status = 403\n\t}\n\n\treturn c.Render()\n}", "func (cc *CommonController) Login() {\n\tprincipal := cc.GetString(\"principal\")\n\tpassword := cc.GetString(\"password\")\n\n\tuser, err := auth.Login(models.AuthModel{\n\t\tPrincipal: principal,\n\t\tPassword: password,\n\t})\n\tif err != nil {\n\t\tlog.Errorf(\"Error occurred in UserLogin: %v\", err)\n\t\tcc.CustomAbort(http.StatusUnauthorized, \"\")\n\t}\n\n\tif user == nil {\n\t\tcc.CustomAbort(http.StatusUnauthorized, \"\")\n\t}\n\n\tcc.SetSession(\"userId\", user.UserID)\n\tcc.SetSession(\"username\", user.Username)\n}", "func (c *Client) Login(ctx context.Context, p *LoginPayload) (res *Session, err error) {\n\tvar ires interface{}\n\tires, err = c.LoginEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(*Session), nil\n}", "func Login(w http.ResponseWriter, req *http.Request) {\n\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"\", now, userIP, \"macAdress\", \"Login\", \"AccountModule\", \"\", \"\", \"_\", 0}\n\t// found, logobj := logpkg.CheckIfLogFound(userIP)\n\n\t// if found && now.Sub(logobj.Currenttime).Seconds() > globalPkg.GlobalObj.DeleteAccountTimeInseacond {\n\n\t// \tlogobj.Count = 0\n\t// \tbroadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t// }\n\t// if found && logobj.Count >= 10 {\n\n\t// \tglobalPkg.SendError(w, \"your Account have been blocked\")\n\t// \treturn\n\t// }\n\n\t// if !found {\n\n\t// \tLogindex := userIP.String() + \"_\" + logfunc.NewLogIndex()\n\n\t// \tlogobj = logpkg.LogStruct{Logindex, now, userIP, \"macAdress\", \"Login\", \"AccountModule\", \"\", \"\", \"_\", 0}\n\t// }\n\t// logobj = logfunc.ReplaceLog(logobj, \"Login\", \"AccountModule\")\n\n\tvar NewloginUser = loginUser{}\n\tvar SessionObj accountdb.AccountSessionStruct\n\n\tdecoder := json.NewDecoder(req.Body)\n\tdecoder.DisallowUnknownFields()\n\terr := decoder.Decode(&NewloginUser)\n\tif err != nil {\n\t\tglobalPkg.SendError(w, \"please enter your correct request \")\n\t\tglobalPkg.WriteLog(logobj, \"failed to decode object\", \"failed\")\n\t\treturn\n\t}\n\tInputData := NewloginUser.EmailOrPhone + \",\" + NewloginUser.Password + \",\" + NewloginUser.AuthValue\n\tlogobj.InputData = InputData\n\t//confirm email is lowercase and trim\n\tNewloginUser.EmailOrPhone = convertStringTolowerCaseAndtrimspace(NewloginUser.EmailOrPhone)\n\tif NewloginUser.EmailOrPhone == \"\" {\n\t\tglobalPkg.WriteLog(logobj, \"please Enter your Email Or Phone\", \"failed\")\n\t\tglobalPkg.SendNotFound(w, \"please Enter your Email Or Phone\")\n\t\treturn\n\t}\n\tif NewloginUser.AuthValue == \"\" && NewloginUser.Password == \"\" {\n\t\tglobalPkg.WriteLog(logobj, \"please Enter your password Or Authvalue\", \"failed\")\n\t\tglobalPkg.SendError(w, \"please Enter your password Or Authvalue\")\n\t\treturn\n\t}\n\n\tvar accountObj accountdb.AccountStruct\n\tvar Email bool\n\tEmail = false\n\tif strings.Contains(NewloginUser.EmailOrPhone, \"@\") && strings.Contains(NewloginUser.EmailOrPhone, \".\") {\n\t\tEmail = true\n\t\taccountObj = getAccountByEmail(NewloginUser.EmailOrPhone)\n\t} else {\n\t\taccountObj = getAccountByPhone(NewloginUser.EmailOrPhone)\n\t}\n\n\t//if account is not found whith data logged in with\n\tif accountObj.AccountPublicKey == \"\" && accountObj.AccountName == \"\" {\n\t\tglobalPkg.SendError(w, \"Account not found please check your email or phone\")\n\t\tglobalPkg.WriteLog(logobj, \"Account not found please check your email or phone\", \"failed\")\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Account not found please check your email or phone\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t\treturn\n\t}\n\n\tif accountObj.AccountIndex == \"\" && Email == true { //AccountPublicKey replaces with AccountIndex\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account Email \", \"failed\")\n\t\tglobalPkg.SendNotFound(w, \"Please,Check your account Email \")\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account Email \"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t\treturn\n\t}\n\tif accountObj.AccountIndex == \"\" && Email == false {\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account phone \", \"failed\")\n\t\tglobalPkg.SendNotFound(w, \"Please,Check your account phone \")\n\t\t// logobj.OutputData = \"Please,Check your account phone \"\n\t\t// logobj.Process = \"failed\"\n\t\t// logobj.Count = logobj.Count + 1\n\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t\treturn\n\t}\n\n\tif (accountObj.AccountName == \"\" || (NewloginUser.Password != \"\" && accountObj.AccountPassword != NewloginUser.Password && Email == true) || (accountObj.AccountEmail != NewloginUser.EmailOrPhone && Email == true && NewloginUser.Password != \"\")) && NewloginUser.Password != \"\" {\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account Email or password\", \"failed\")\n\t\tglobalPkg.SendError(w, \"Please,Check your account Email or password\")\n\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account Email or password\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t\treturn\n\t}\n\tif (accountObj.AccountName == \"\" || (accountObj.AccountAuthenticationValue != NewloginUser.AuthValue && Email == true) || (accountObj.AccountEmail != NewloginUser.EmailOrPhone && Email == true)) && NewloginUser.AuthValue != \"\" {\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account Email or AuthenticationValue\", \"failed\")\n\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account Email or AuthenticationValues\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\t\tglobalPkg.SendError(w, \"Please,Check your account Email or AuthenticationValue\")\n\t\treturn\n\n\t}\n\tif (accountObj.AccountName == \"\" || (strings.TrimSpace(accountObj.AccountPhoneNumber) != \"\" && Email == false) || (accountObj.AccountPassword != NewloginUser.Password && Email == false) || (accountObj.AccountPhoneNumber != NewloginUser.EmailOrPhone && Email == false)) && NewloginUser.Password != \"\" {\n\t\tfmt.Println(\"i am a phone\")\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account phoneNAmber OR password\", \"failed\")\n\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account phoneNAmber OR password\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\t\tglobalPkg.SendError(w, \"Please,Check your account phoneNAmber OR password\")\n\t\treturn\n\n\t}\n\n\tif (accountObj.AccountName == \"\" || (strings.TrimSpace(accountObj.AccountPhoneNumber) != \"\" && Email == false) || (accountObj.AccountPassword != NewloginUser.AuthValue && Email == false) || (accountObj.AccountPhoneNumber != NewloginUser.EmailOrPhone && Email == false)) && NewloginUser.AuthValue != \"\" {\n\t\tfmt.Println(\"i am a phone\")\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account phoneNAmber OR AuthenticationValue\", \"failed\")\n\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account phoneNAmber OR AuthenticationValue\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\t\tglobalPkg.SendError(w, \"Please,Check your account phoneNAmber OR AuthenticationValue\")\n\t\treturn\n\n\t}\n\n\tif accountObj.AccountPublicKey == \"\" && accountObj.AccountName != \"\" {\n\t\tvar user User\n\n\t\tuser = createPublicAndPrivate(user)\n\n\t\tbroadcastTcp.BoardcastingTCP(accountObj, \"POST\", \"account\")\n\t\taccountObj.AccountPublicKey = user.Account.AccountPublicKey\n\t\taccountObj.AccountPrivateKey = user.Account.AccountPrivateKey\n\t\tsendJson, _ := json.Marshal(accountObj)\n\n\t\t//w.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Header().Set(\"jwt-token\", globalPkg.GenerateJwtToken(accountObj.AccountName, false)) // set jwt token\n\t\t//w.WriteHeader(http.StatusOK)\n\t\t//w.Write(sendJson)\n\t\tglobalPkg.SendResponse(w, sendJson)\n\t\tSessionObj.SessionId = NewloginUser.SessionID\n\t\tSessionObj.AccountIndex = accountObj.AccountIndex\n\t\t//--search if sesssion found\n\t\t// session should be unique\n\t\tflag, _ := CheckIfsessionFound(SessionObj)\n\n\t\tif flag == true {\n\n\t\t\tbroadcastTcp.BoardcastingTCP(SessionObj, \"\", \"Delete Session\")\n\n\t\t}\n\t\tbroadcastTcp.BoardcastingTCP(SessionObj, \"\", \"Add Session\")\n\n\t\treturn\n\n\t}\n\n\tfmt.Println(accountObj)\n\tSessionObj.SessionId = NewloginUser.SessionID\n\tSessionObj.AccountIndex = accountObj.AccountIndex\n\t//--search if sesssion found\n\t// session should be unique\n\tflag, _ := CheckIfsessionFound(SessionObj)\n\n\tif flag == true {\n\n\t\tbroadcastTcp.BoardcastingTCP(SessionObj, \"\", \"Delete Session\")\n\n\t}\n\tbroadcastTcp.BoardcastingTCP(SessionObj, \"\", \"Add Session\")\n\tglobalPkg.WriteLog(logobj, accountObj.AccountName+\",\"+accountObj.AccountPassword+\",\"+accountObj.AccountEmail+\",\"+accountObj.AccountRole, \"success\")\n\n\t// if logobj.Count > 0 {\n\t// \tlogobj.Count = 0\n\t// \tlogobj.OutputData = accountObj.AccountName\n\t// \tlogobj.Process = \"success\"\n\t// \tbroadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t// }\n\tsendJson, _ := json.Marshal(accountObj)\n\tw.Header().Set(\"jwt-token\", globalPkg.GenerateJwtToken(accountObj.AccountName, false)) // set jwt token\n\tglobalPkg.SendResponse(w, sendJson)\n\n}", "func Login(w http.ResponseWriter, r *http.Request) {\r\n\tlogin := strings.Trim(r.FormValue(\"login\"), \" \")\r\n\tpass := strings.Trim(r.FormValue(\"pass\"), \" \")\r\n\tlog.Println(\"login: \", login, \" pass: \", pass)\r\n\r\n\t// Check params\r\n\tif login == \"\" || pass == \"\" {\r\n\t\twriteResponse(w, \"Login and password required\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\t// Already authorized\r\n\tif savedPass, OK := Auth[login]; OK && savedPass == pass {\r\n\t\twriteResponse(w, \"You are already authorized\\n\", http.StatusOK)\r\n\t\treturn\r\n\t} else if OK && savedPass != pass {\r\n\t\t// it is not neccessary\r\n\t\twriteResponse(w, \"Wrong pass\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\tuser := model.User{}\r\n\terr := user.Get(login, pass)\r\n\tif err == nil {\r\n\t\tAuth[login], Work[login] = pass, user.WorkNumber\r\n\t\twriteResponse(w, \"Succesfull authorization\\n\", http.StatusOK)\r\n\t\treturn\r\n\t}\r\n\r\n\twriteResponse(w, \"User with same login not found\\n\", http.StatusNotFound)\r\n}", "func (e *Example) PostLogin (ctx context.Context, req *example.Request, rsp *example.Response) error {\n\t/* Print */\n\tbeego.Info(\"PostLogin /api/v1.0/sessions\")\n\n\t/* Init */\n\trsp.Errno = utils.RECODE_OK\n\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\n\t/* MySQL*/\n\t// 1 orm\n\to := orm.NewOrm()\n\t// 2 db object\n\tuser := models.User{}\n\t// 3 select\n\tuser.Mobile = req.Mobile\n\terr := o.Read(&user,\"Mobile\")\n\tif err != nil {\n\t\trsp.Errno = utils.RECODE_NODATA\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin MySQL: \", err)\n\t\treturn nil\n\t}\n\n\t// Md5\n\thash, err := utils.CrotoMd5(req.Password)\n\tif err != nil{\n\t\trsp.Errno = utils.RECODE_UNKNOWERR\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin Md5: \", err)\n\t\treturn nil\n\t}\n\t// password\n\tif hash != user.Password_hash{\n\t\trsp.Errno = utils.RECODE_PWDERR\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin password: \", err)\n\t\treturn nil\n\t}\n\n\t/* sessionID */\n\trsp.SessionID, err = utils.CrotoMd5(req.Mobile + req.Password + strconv.Itoa(int(time.Now().UnixNano())))\n\tif err != nil {\n\t\trsp.Errno = utils.RECODE_UNKNOWERR\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin sessionID: \", err)\n\t\treturn nil\n\t}\n\n\t/* Redis */\n\tr, err := utils.RedisServer(utils.G_server_name, utils.G_redis_addr, utils.G_redis_port, utils.G_redis_dbnum)\n\tif err != nil{\n\t\trsp.Errno = utils.RECODE_DBERR\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin Redis\")\n\t\treturn nil\n\t}\n\n\t/* <=Redis */\n\terr = r.Put(rsp.SessionID+\"name\", user.Name, time.Second*600)\n\terr = r.Put(rsp.SessionID+\"id\", user.Id, time.Second*600)\n\terr = r.Put(rsp.SessionID+\"mobile\", user.Mobile, time.Second*600)\n\n\treturn nil\n}", "func (app *application) postLogin(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tapp.clientError(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\tform := forms.New(r.PostForm)\n\tform.Required(\"screenName\")\n\tform.MaxLength(\"screenName\", 16)\n\tform.Required(\"password\")\n\n\trowid, err := app.players.Authenticate(form.Get(\"screenName\"), form.Get(\"password\"))\n\tif err != nil {\n\t\tif errors.Is(err, models.ErrInvalidCredentials) {\n\t\t\tform.Errors.Add(\"generic\", \"Supplied credentials are incorrect\")\n\t\t\tapp.renderLogin(w, r, \"login.page.tmpl\", &templateDataLogin{Form: form})\n\t\t} else {\n\t\t\tapp.serverError(w, err)\n\t\t}\n\t\treturn\n\t}\n\t// Update loggedIn in database\n\tapp.players.UpdateLogin(rowid, true)\n\tapp.session.Put(r, \"authenticatedPlayerID\", rowid)\n\tapp.session.Put(r, \"screenName\", form.Get(\"screenName\"))\n\thttp.Redirect(w, r, \"/board/list\", http.StatusSeeOther)\n}", "func LoginFunc(w http.ResponseWriter, r *http.Request) {\n\tsession, _ := sessions.Store.Get(r, \"session\")\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tview.LoginTemplate.Execute(w, nil)\n\tcase \"POST\":\n\t\tr.ParseForm()\n\t\tusername := r.Form.Get(\"username\")\n\t\tpassword := r.Form.Get(\"password\")\n\t\t// there will not handle the empty value it should be handle by javascript\n\t\tif user.UserIsExist(username) {\n\t\t\tif user.ValidUser(username, password) {\n\t\t\t\tsession.Values[\"loggedin\"] = \"true\"\n\t\t\t\tsession.Values[\"username\"] = username\n\t\t\t\tsession.Save(r, w)\n\t\t\t\tlog.Println(\"user\", username, \"is authenticated\")\n\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t\t} else {\n\t\t\t\thttp.Error(w, \"Wrong username or password\", http.StatusInternalServerError)\n\t\t\t}\n\t\t} else {\n\t\t\thttp.Error(w, \"User doesnt exist\", http.StatusInternalServerError)\n\t\t}\n\tdefault:\n\t\thttp.Redirect(w, r, \"/login/\", http.StatusUnauthorized)\n\t}\n}", "func (a *App) LoginRequired(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tsession, err := Store.Get(r, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error Getting the session. error: %v\", err)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\tif session.IsNew {\n\t\tlogger.Get().Info(\"Not Authorized\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\tnext(w, r)\n}", "func (c *client) Login(w http.ResponseWriter, r *http.Request) (string, error) {\n\tlogrus.Trace(\"Processing login request\")\n\n\t// generate a random string for creating the OAuth state\n\toAuthState, err := random.GenerateRandomString(32)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// temporarily redirect request to Github to begin workflow\n\thttp.Redirect(w, r, c.OConfig.AuthCodeURL(oAuthState), http.StatusTemporaryRedirect)\n\n\treturn oAuthState, nil\n}", "func DoSignin(w http.ResponseWriter, r *http.Request) {\n\n\tvar id int\n\n\tif r.Method == \"POST\" {\n\t\t// Handles login when it is hit as a post request\n\t\tr.ParseForm()\n\t\tstmt, err := db.Prepare(\"select id from users where username=? and password=?\")\n\t\tres := stmt.QueryRow(r.FormValue(\"username\"), r.FormValue(\"password\"))\n\t\terr = res.Scan(&id)\n\n\t\tif err == nil {\n\t\t\tsess, _ := globalSessions.SessionStart(w, r)\n\t\t\tdefer sess.SessionRelease(w)\n\t\t\tsetUserCookies(w, id, sess.SessionID())\n\t\t\t_ = sess.Set(\"user_id\", id)\n\t\t\t_ = sess.Set(\"username\", r.FormValue(\"username\"))\n\t\t\tif r.FormValue(\"remember-me\") == \"on\" {\n\t\t\t\tsaveSession(w, r, sess.SessionID(), id)\n\n\t\t\t}\n\t\t\taddRemoteAddress(r, id)\n\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t} else {\n\t\t\tlog.Println(\"Database connection failed: \", err)\n\t\t}\n\t} else {\n\t\tanonsess, _ := anonSessions.SessionStart(w, r)\n\t\tdefer anonsess.SessionRelease(w)\n\t\t// Handles auto login when it is hit as a GET request\n\t\tsessionIdCookie, err := r.Cookie(\"userSession_id\")\n\t\tif err == nil {\n\t\t\tstmt, err := db.Prepare(\"select id, username from users where session_id=?\")\n\t\t\tres := stmt.QueryRow(sessionIdCookie.Value)\n\t\t\tvar username string\n\t\t\terr = res.Scan(&id, &username)\n\t\t\tif err == nil {\n\t\t\t\tif checkRemoteAddress(r, id) {\n\t\t\t\t\tsess, _ := globalSessions.SessionStart(w, r)\n\t\t\t\t\tdefer sess.SessionRelease(w)\n\t\t\t\t\terr = sess.Set(\"user_id\", id)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Println(err)\n\t\t\t\t\t}\n\t\t\t\t\t_ = sess.Set(\"username\", username)\n\t\t\t\t\tsaveSession(w, r, sess.SessionID(), id)\n\t\t\t\t\tsetUserCookies(w, id, sess.SessionID())\n\t\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t\t\t} else {\n\t\t\t\t\thttp.Redirect(w, r, \"/newAddress\", 302)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thttp.Redirect(w, r, \"/userNotFound\", 302)\n\t\t\t}\n\t\t} else {\n\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t}\n\t}\n}", "func (c App) CheckLogin() revel.Result {\n if _, ok := c.Session[\"userName\"]; ok {\n c.Flash.Success(\"You are already logged in \" + c.Session[\"userName\"] + \"!\")\n return c.Redirect(routes.Todo.Index())\n }\n\n return nil\n}", "func login(w http.ResponseWriter, r *http.Request){\n\t//Get value from cookie store with same name\n\tsession, _ := store.Get(r,\"session-name\")\n\t//Set authenticated to true\n\tsession.Values[\"authenticated\"]=true\n\t//Save request and responseWriter\n\tsession.Save(r,w)\n\t//Print the result to console\n\tfmt.Println(w,\"You have succesfully login\")\n}", "func loginprompt(w http.ResponseWriter, r *http.Request) {\n\t_, tid := GetAndOrUpdateSession(w, r)\n\tif tid != \"\" {\n\t\tshowMessage(w, \"Error: already logged in\",\n\t\t\t\"You are already logged in\", tid, \"\")\n\t\treturn\n\t}\n\ttemplate.Must(template.New(\"\").Parse(tLoginPrompt)).Execute(w, map[string]string{\n\t\t\"PageTitle\": \"Please log in\",\n\t\t\"Team\": r.FormValue(\"team\"),\n\t\t// TODO URL escaping would be pretty sweet\n\t\t\"TeamURL\": url.QueryEscape(r.FormValue(\"team\")),\n\t})\n}", "func (r *AccessLogRecord) successfulAttemptTime() float64 {\n\tif r.AppRequestFinishedAt.Equal(r.LastFailedAttemptFinishedAt) {\n\t\treturn -1\n\t}\n\n\t// we only want the time of the successful attempt\n\tif !r.LastFailedAttemptFinishedAt.IsZero() {\n\t\t// exclude the time any failed attempts took\n\t\treturn r.AppRequestFinishedAt.Sub(r.LastFailedAttemptFinishedAt).Seconds()\n\t} else {\n\t\treturn r.AppRequestFinishedAt.Sub(r.AppRequestStartedAt).Seconds()\n\t}\n}", "func Login(enrollID, enrollSecret string, loginChan chan int) bool {\n\tvar loginRequest loginRequest\n\tloginRequest.EnrollID = enrollID\n\tloginRequest.EnrollSecret = enrollSecret\n\n\treqBody, err := json.Marshal(loginRequest)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\turlstr := getHTTPURL(\"api/login\")\n\t_, err = performHTTPPost(urlstr, reqBody)\n\tif err != nil {\n\t\tloginChan <- 1\n\t\tlogger.Errorf(\"Login failed: %v\", err)\n\t\treturn false\n\t}\n\tloginChan <- 0\n\t// logger.Debugf(\"Login: url=%v request=%v response=%v\", urlstr, string(reqBody), string(response))\n\n\t// var result restResult\n\t// err = json.Unmarshal(response, &result)\n\t// if err != nil {\n\t// \tlogger.Errorf(\"Login failed: %v\", err)\n\t// \treturn false\n\t// }\n\n\t// if len(result.OK) == 0 {\n\t// \tlogger.Errorf(\"Login failed: %v\", result.Err)\n\t// \treturn false\n\t// }\n\n\treturn true\n}", "func requireLogin(rw http.ResponseWriter, req *http.Request, app *App) bool {\n\tses, _ := app.SessionStore.Get(req, SessionName)\n\tvar err error\n\tvar id int64\n\tif val := ses.Values[\"userId\"]; val != nil {\n\t\tid = val.(int64)\n\t}\n\n\tif err == nil {\n\t\t_, err = models.UserById(app.Db, id)\n\t}\n\n\tif err != nil {\n\t\thttp.Redirect(rw, req, app.Config.General.Prefix+\"/login\", http.StatusSeeOther)\n\t\treturn true\n\t}\n\treturn false\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tstore, err := pgstore.NewPGStore(os.Getenv(\"PGURL\"), key)\n\tcheck(err)\n\tdefer store.Close()\n\tsession, err := store.Get(r, \"scheduler-session\")\n\tcheck(err)\n\n\tvar domain string\n\tif os.Getenv(\"GO_ENV\") == \"dev\" {\n\t\tdomain = \"http://localhost:3000\"\n\t} else if os.Getenv(\"GO_ENV\") == \"test\" {\n\t\tdomain = \"http://s3-sih-test.s3-website-us-west-1.amazonaws.com\"\n\t} else if os.Getenv(\"GO_ENV\") == \"prod\" {\n\t\tdomain = \"https://schedulingishard.com\"\n\t}\n\t// Limit the sessions to 1 24-hour day\n\tsession.Options.MaxAge = 86400 * 1\n\tsession.Options.Domain = domain // Set to localhost for testing only. prod must be set to \"schedulingishard.com\"\n\tsession.Options.HttpOnly = true\n\n\tcreds := DecodeCredentials(r)\n\t// Authenticate based on incoming http request\n\tif passwordsMatch(r, creds) != true {\n\t\tlog.Printf(\"Bad password for member: %v\", creds.Email)\n\t\tmsg := errorMessage{\n\t\t\tStatus: \"Failed to authenticate\",\n\t\t\tMessage: \"Incorrect username or password\",\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t//http.Error(w, \"Incorrect username or password\", http.StatusUnauthorized)\n\t\tjson.NewEncoder(w).Encode(msg)\n\t\treturn\n\t}\n\t// Get the memberID based on the supplied email\n\tmemberID := models.GetMemberID(creds.Email)\n\tmemberName := models.GetMemberName(memberID)\n\tm := memberDetails{\n\t\tStatus: \"OK\",\n\t\tID: memberID,\n\t\tName: memberName,\n\t\tEmail: creds.Email,\n\t}\n\n\t// Respond with the proper content type and the memberID\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"X-CSRF-Token\", csrf.Token(r))\n\t// Set cookie values and save\n\tsession.Values[\"authenticated\"] = true\n\tsession.Values[\"memberID\"] = m.ID\n\tif err = session.Save(r, w); err != nil {\n\t\tlog.Printf(\"Error saving session: %v\", err)\n\t}\n\tjson.NewEncoder(w).Encode(m)\n\t// w.Write([]byte(memberID)) // Alternative to fprintf\n}", "func (s *Server) handleLogin(w http.ResponseWriter, req *http.Request) error {\n\toauthState := uuid.New().String()\n\tloginSession, err := s.cookieStore.Get(req, LoginSessionName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tloginSession.Options = &sessions.Options{\n\t\tMaxAge: 600,\n\t\tHttpOnly: true,\n\t\tSecure: s.opts.SecureCookie,\n\t}\n\tloginSession.Values[\"oauth_state\"] = oauthState\n\terr = loginSession.Save(req, w)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error saving session: %s\", err)\n\t}\n\turl := s.oauthConfig.AuthCodeURL(oauthState)\n\thttp.Redirect(w, req, url, http.StatusTemporaryRedirect)\n\treturn nil\n}", "func (ctrl LoginController) ProcessLogin(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tsession, _ := store.Get(r, \"session-id\")\n\tusername := r.PostFormValue(\"username\")\n\tpassword := r.PostFormValue(\"password\")\n\n\tuser, _ := model.GetUserByUserName(username)\n\tv := new(Validator)\n\n\tif !v.ValidateUsername(username) {\n\t\tSessionFlash(v.err, w, r)\n\t\thttp.Redirect(w, r, URL_LOGIN, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tif user.Username == \"\" || !CheckPasswordHash(password, user.Password) {\n\t\tSessionFlash(messages.Error_username_or_password, w, r)\n\t\thttp.Redirect(w, r, URL_LOGIN, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tsession.Values[\"username\"] = user.Username\n\tsession.Values[\"id\"] = user.ID\n\tsession.Save(r, w)\n\thttp.Redirect(w, r, URL_HOME, http.StatusMovedPermanently)\n}", "func (r *AccessLogRecord) failedAttemptsTime() float64 {\n\tif r.LastFailedAttemptFinishedAt.IsZero() {\n\t\treturn -1\n\t}\n\treturn r.LastFailedAttemptFinishedAt.Sub(r.AppRequestStartedAt).Seconds()\n}", "func (c *Sender) Attempts() int {\n\treturn c.attempts\n}", "func (a *RedisAuthenticator) Login(username string, password string) string {\n\ttoken := checkValidLoginAndGenerateToken(username, password)\n\tif token == \"\" {\n\t\treturn \"\"\n\t}\n\tconn := a.Redis.Get()\n\tdefer conn.Close()\n\t_, err := conn.Do(\"SET\", \"octyne-token:\"+token, username)\n\tif err != nil {\n\t\tlog.Println(\"An error occurred while making a request to Redis for login!\", err) // skipcq: GO-S0904\n\t}\n\treturn token\n}", "func (a *Auth) Login(id int64, ctx *gin.Context) error {\n\tdefer a.redis.Save()\n\n\tuuid := uuid.New().String()\n\tif err := a.redis.Set(uuid, id, 24*time.Hour).Err(); err != nil {\n\t\treturn err\n\t}\n\n\thttp.SetCookie(ctx.Writer, &http.Cookie{\n\t\tName: a.cookie,\n\t\tValue: uuid,\n\t})\n\treturn nil\n}", "func CheckLoginStatus(w http.ResponseWriter, r *http.Request) (bool,interface{}){\n\tsess := globalSessions.SessionStart(w,r)\n\tsess_uid := sess.Get(\"UserID\")\n\tif sess_uid == nil {\n\t\treturn false,\"\"\n\t} else {\n\t\tuID := sess_uid\n\t\tname := sess.Get(\"username\")\n\t\tfmt.Println(\"Logged in User, \", uID)\n\t\t//Tpl.ExecuteTemplate(w, \"user\", nil)\n\t\treturn true,name\n\t}\n}", "func (ctn *Connection) login(policy *ClientPolicy, hashedPassword []byte, sessionToken []byte) error {\n\t// need to authenticate\n\tif policy.RequiresAuthentication() {\n\t\tswitch policy.AuthMode {\n\t\tcase AuthModeExternal:\n\t\t\tvar err error\n\t\t\tcommand := newLoginCommand(ctn.dataBuffer)\n\t\t\tif sessionToken == nil {\n\t\t\t\terr = command.login(policy, ctn, hashedPassword)\n\t\t\t} else {\n\t\t\t\terr = command.authenticateViaToken(policy, ctn, sessionToken)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tif ctn.node != nil {\n\t\t\t\t\tatomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1)\n\t\t\t\t}\n\t\t\t\t// Socket not authenticated. Do not put back into pool.\n\t\t\t\tctn.Close()\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif ctn.node != nil && command.SessionToken != nil {\n\t\t\t\tctn.node._sessionToken.Store(command.SessionToken)\n\t\t\t\tctn.node._sessionExpiration.Store(command.SessionExpiration)\n\t\t\t}\n\n\t\t\treturn nil\n\n\t\tcase AuthModeInternal:\n\t\t\treturn ctn.authenticateFast(policy.User, hashedPassword)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (u *MyUserModel) Login() {\n\t// Update last login time\n\t// Add to logged-in user's list\n\t// etc ...\n\tu.authenticated = true\n}", "func Login(rw http.ResponseWriter, request *http.Request) {\n\n\tlog.Println(\"call Login\")\n\n\t// フォームデータのパース\n\terr := request.ParseForm()\n\tif err != nil {\n\t\toutputErrorLog(\"フォーム パース 失敗\", err)\n\t}\n\n\t// リクエストデータ取得\n\taccount := request.Form.Get(\"account\")\n\tpassword := request.Form.Get(\"password\")\n\tlog.Println(\"ユーザ:\", account)\n\n\t// ユーザデータ取得しモデルデータに変換\n\tdbm := db.ConnDB()\n\tuser := new(models.User)\n\trow := dbm.QueryRow(\"select account, name, password from users where account = ?\", account)\n\tif err = row.Scan(&user.Name, &user.Account, &user.Password); err != nil {\n\t\toutputErrorLog(\"ユーザ データ変換 失敗\", err)\n\t}\n\n\t// ユーザのパスワード認証\n\tif user.Password != password {\n\t\tlog.Println(\"ユーザ パスワード照合 失敗\")\n\t\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\n\tlog.Println(\"認証 成功\")\n\n\t// 認証が通ったら、セッション情報をDBに保存\n\tsessionID := generateSessionID(account)\n\tlog.Println(\"生成したセッションID:\", sessionID)\n\tnow := time.Now()\n\tresult, err := dbm.Exec(`INSERT INTO sessions\n\t\t(sessionID, account, expireDate)\n\t\tVALUES\n\t\t(?, ?, ?)\n\t\t`, sessionID, account, now.Add(1*time.Hour))\n\tnum, err := result.RowsAffected()\n\tif err != nil || num == 0 {\n\t\toutputErrorLog(\"セッション データ保存 失敗\", err)\n\t}\n\n\tlog.Println(\"セッション データ保存 成功\")\n\n\t// クッキーにセッション情報付与\n\tcookie := &http.Cookie{\n\t\tName: sessionIDName,\n\t\tValue: sessionID,\n\t}\n\thttp.SetCookie(rw, cookie)\n\n\t// HOME画面に遷移\n\thttp.Redirect(rw, request, \"/home\", http.StatusFound)\n}", "func UserLoginData(loginResponse http.ResponseWriter, loginRequest *http.Request) {\n\n\t//var userSessioneventID int\n\tdb := dbConn()\n\tdefer db.Close()\n\n\tif loginRequest.Method != \"POST\" {\n\t\tlog.Panic(\"Form data is not Post\")\n\t\thttp.Redirect(loginResponse, loginRequest, \"/\", http.StatusSeeOther)\n\t}\n\n\tcookie, cookieError := loginRequest.Cookie(\"login-cookie\") // returns cookie or an error\n\n\t// check incoming cookie with db\n\n\tif cookieError != nil {\n\t\tlog.Fatal(\"Cookies dont match\")\n\t} else {\n\t\tlog.Println(\"Got cookie : \", cookie)\n\t\tuserName := loginRequest.FormValue(\"username\")\n\t\tpassword := loginRequest.FormValue(\"password\")\n\t\t//rememberMe := loginRequest.FormValue(\"remember_me\")\n\t\t//fmt.Println(\"Rember me : \", rememberMe)\n\n\t\tuserLogin, eventID := userLoginProcessing(userName, password, cookie.Value)\n\n\t\tif userLogin {\n\t\t\t/*\n\t\t\t\tPassword matches, insert jwt and details to user_session table.\n\t\t\t\tUpdate initial loging table setting used=1 and next event id\n\t\t\t*/\n\t\t\tjwt, jwtErr := GenerateJWT(cookie.Value, 30) // for now its 30min session\n\n\t\t\tif jwtErr != nil {\n\t\t\t\tlog.Println(\"Can not generate jwt token\", jwtErr)\n\t\t\t}\n\n\t\t\thttp.SetCookie(loginResponse, &http.Cookie{\n\t\t\t\tName: \"user-cookie\",\n\t\t\t\tValue: jwt,\n\t\t\t\tPath: \"/home\",\n\t\t\t})\n\n\t\t\t/*\n\t\t\t\tInserting user_session and updating initial table\n\t\t\t*/\n\n\t\t\tloginSession, userSessionID := insertToUserSession(userName, jwt)\n\n\t\t\tif loginSession != true {\n\t\t\t\tlog.Println(\"Couldnt insert data to user session table\")\n\t\t\t}\n\n\t\t\tinitTable := updateInitialLogin(userSessionID, eventID)\n\n\t\t\tif initTable {\n\t\t\t\thttp.Redirect(loginResponse, loginRequest, \"/home\", http.StatusSeeOther)\n\t\t\t}\n\n\t\t} else { // password checking if-else\n\t\t\t// This is where I need to modify not to generate new token for login\n\t\t\thttp.Redirect(loginResponse, loginRequest, \"/\", http.StatusSeeOther)\n\t\t}\n\t} // cookie availble checking if-else\n\n}", "func login(w http.ResponseWriter,r *http.Request){\n\tsession,err:=store.Get(r,\"cookie-name\")\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\n\t// Where authentication could be done\n\tif r.FormValue(\"code\")!=\"code\"{\n\t\tif r.FormValue(\"code\")==\"\"{\n\t\t\tsession.AddFlash(\"must enter a code\")\n\t\t}\n\t\tsession.AddFlash(\"the code was incorrect\")\n\t\terr:=session.Save(r,w)\n\t\tif err!=nil{\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\thttp.Redirect(w,r,\"/forbiden\",http.StatusFound)\n\t\treturn\n\t}\n\tusername:=r.FormValue(\"username\")\n\tpassword:=r.FormValue(\"password\")\n\tuser:=&user{\n\t\tUserName: username,\n\t\tPassword: password,\n\t\tAuthenticated: true,\n\t}\n\tsession.Values[\"user\"]=user\n\terr=session.Save(r,w)\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\thttp.Redirect(w,r,\"/secret\",http.StatusFound)\n}", "func LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tif SessionManager.Exists(r.Context(), \"userid\") {\n\t\thttp.Redirect(w, r, \"/worker\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tif r.Method == \"GET\" {\n\t\tloginErr(w, \"\")\n\t\treturn\n\t}\n\n\tvar err error\n\t// POST\n\tvar exists bool\n\tvar user shared.User\n\n\tusername := r.PostFormValue(\"username\")\n\tpassword := []byte(r.PostFormValue(\"password\"))\n\n\tif exists, err = shared.Db.DoesUserExists(username); err != nil {\n\t\tshared.HTTPerr(w, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif !exists {\n\t\tloginErr(w, fmt.Sprintf(\"User %s does not exists!\", username))\n\t\treturn\n\t}\n\n\t// authenticate user\n\tif user, err = shared.Db.GetUserByName(username); err != nil {\n\t\tshared.HTTPerr(w, err, http.StatusUnauthorized)\n\t\treturn\n\t}\n\tif err = bcrypt.CompareHashAndPassword(user.Password, password); err != nil {\n\t\tloginErr(w, \"Incorrect password!\")\n\t\treturn\n\t}\n\n\t// create new session\n\tif err = SessionManager.RenewToken(r.Context()); err != nil {\n\t\tshared.HTTPerr(w, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tSessionManager.Put(r.Context(), \"userid\", user.ID)\n\tSessionManager.RememberMe(r.Context(), true)\n\thttp.Redirect(w, r, \"/worker\", http.StatusSeeOther)\n}", "func (am AuthManager) Login(userID string, ctx *Ctx) (session *Session, err error) {\n\t// create a new session value\n\tsessionValue := NewSessionID()\n\t// userID and sessionID are required\n\tsession = NewSession(userID, sessionValue)\n\tif am.SessionTimeoutProvider != nil {\n\t\tsession.ExpiresUTC = am.SessionTimeoutProvider(session)\n\t}\n\tsession.UserAgent = webutil.GetUserAgent(ctx.Request)\n\tsession.RemoteAddr = webutil.GetRemoteAddr(ctx.Request)\n\n\t// call the perist handler if one's been provided\n\tif am.PersistHandler != nil {\n\t\terr = am.PersistHandler(ctx.Context(), session)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if we're in jwt mode, serialize the jwt.\n\tif am.SerializeSessionValueHandler != nil {\n\t\tsessionValue, err = am.SerializeSessionValueHandler(ctx.Context(), session)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// inject cookies into the response\n\tam.injectCookie(ctx, am.CookieNameOrDefault(), sessionValue, session.ExpiresUTC)\n\treturn session, nil\n}", "func (u *User) Login() {\n\t// Update last login time\n\t// Add to logged-in user's list\n\t// etc ...\n\tu.authenticated = true\n}", "func TestLoginSuccess(t *testing.T) {\n\tvar handler = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {\n\t\trw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tfmt.Fprint(rw, `{\"session.id\":\"test\",\"status\":\"success\"}`)\n\t})\n\tts := httptest.NewServer(handler)\n\tdefer ts.Close()\n\tconf := Config\n\tconf.Url = ts.URL\n\n\treq := &AuthenticateReq{\n\t\tCommonConf: conf,\n\t}\n\tres, err := Authenticate(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif res.SessionId == \"\" {\n\t\tt.Fatal(\"No session id\")\n\t}\n\tt.Logf(\"%+v\", *res)\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\t//Create Error messages\n\tmessages := make([]string, 0)\n\ttype MultiErrorMessages struct {\n\t\tMessages []string\n\t}\n\n\t// Get Formdata\n\tvar user = model.User{}\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Try Authentification\n\tuser, err := model.GetUserByUsername(username)\n\tif err != nil {\n\n\t\t//Add error Message\n\t\tmessages = append(messages, \"Benutzer existiert nicht.\")\n\n\t}\n\n\t//Encode Password to base64 byte array\n\tpasswordDB, _ := base64.StdEncoding.DecodeString(user.Password)\n\terr = bcrypt.CompareHashAndPassword(passwordDB, []byte(password))\n\tif err != nil {\n\n\t\t//Add error Message\n\t\tmessages = append(messages, \"Password falsch.\")\n\n\t}\n\n\t//Check if any Error Message was assembled\n\tif len(messages) != 0 {\n\n\t\tresponseModel := MultiErrorMessages{\n\t\t\tMessages: messages,\n\t\t}\n\n\t\tresponseJSON, err := json.Marshal(responseModel)\n\t\tif err != nil {\n\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Write([]byte(err.Error()))\n\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusConflict)\n\t\tw.Write(responseJSON)\n\t\treturn\n\n\t}\n\n\t//Hash Username\n\tmd5HashInBytes := md5.Sum([]byte(user.Name))\n\tmd5HashedUsername := hex.EncodeToString(md5HashInBytes[:])\n\n\t//Create Session\n\tsession, err := store.Get(r, \"session\")\n\tsession.Values[\"authenticated\"] = true\n\tsession.Values[\"username\"] = username\n\tsession.Values[\"hashedusername\"] = md5HashedUsername\n\tif err != nil {\n\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\n\t}\n\n\t//Save Session\n\terr = session.Save(r, w)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t}\n\n\t//Redirect to ProfilePage\n\thttp.Redirect(w, r, \"/users?action=userdata\", http.StatusFound)\n}", "func gwLogin(c *gin.Context) {\n\ts := getHostServer(c)\n\treqId := getRequestId(s, c)\n\tvar err error\n\tvar hasCheckPass = false\n\tvar checker = s.AuthParamChecker\n\tvar authParam AuthParameter\n\tfor _, resolver := range s.AuthParamResolvers {\n\t\tauthParam = resolver.Resolve(c)\n\t\tif err = checker.Check(authParam); err == nil {\n\t\t\thasCheckPass = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !hasCheckPass {\n\t\tc.JSON(http.StatusBadRequest, s.RespBodyBuildFunc(http.StatusBadRequest, reqId, err, nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\t// Login\n\tuser, err := s.AuthManager.Login(authParam)\n\tif err != nil || user.IsEmpty() {\n\t\tc.JSON(http.StatusNotFound, s.RespBodyBuildFunc(http.StatusNotFound, reqId, err.Error(), nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tsid, credential, ok := encryptSid(s, authParam)\n\tif !ok {\n\t\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"Create session ID fail.\", nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tif err := s.SessionStateManager.Save(sid, user); err != nil {\n\t\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"Save session fail.\", err.Error()))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tvar userPerms []gin.H\n\tfor _, p := range user.Permissions {\n\t\tuserPerms = append(userPerms, gin.H{\n\t\t\t\"Key\": p.Key,\n\t\t\t\"Name\": p.Name,\n\t\t\t\"Desc\": p.Descriptor,\n\t\t})\n\t}\n\tcks := s.conf.Security.Auth.Cookie\n\texpiredAt := time.Duration(cks.MaxAge) * time.Second\n\tvar userRoles = gin.H{\n\t\t\"Id\": 0,\n\t\t\"name\": \"\",\n\t\t\"desc\": \"\",\n\t}\n\tpayload := gin.H{\n\t\t\"Credentials\": gin.H{\n\t\t\t\"Token\": credential,\n\t\t\t\"ExpiredAt\": time.Now().Add(expiredAt).Unix(),\n\t\t},\n\t\t\"Roles\": userRoles,\n\t\t\"Permissions\": userPerms,\n\t}\n\tbody := s.RespBodyBuildFunc(0, reqId, nil, payload)\n\tc.SetCookie(cks.Key, credential, cks.MaxAge, cks.Path, cks.Domain, cks.Secure, cks.HttpOnly)\n\tc.JSON(http.StatusOK, body)\n}", "func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\tvar data map[string]string\n\n\tresp, err := getBody(req)\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(resp, &data)\n\tif err != nil {\n\t\tlog.Panicln(\"login:\", err)\n\t}\n\n\tusername := data[\"username\"]\n\tpassword := data[\"password\"]\n\tuser, err := getUser(username)\n\tif err != nil {\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tsessID, err := authenticateUser(user, username, password)\n\tif err != nil {\n\t\tlog.Println(\"login:\", err)\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tresponse := jsMap{\n\t\t\"status\": \"OK\",\n\t\t\"sessionID\": hex.EncodeToString(sessID),\n\t\t\"address\": user.Address,\n\t}\n\n\twriteJSON(res, 200, response)\n}", "func verifyLogin(r *http.Request) bool {\n\tsession, err := store.Get(r, sessionName)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to get session: %s\", err)\n\t\treturn false\n\t}\n\tif session.Values[\"LoggedIn\"] != \"yes\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func (d *Domus) Login() error {\n\tresp, err := d.Get(\"/Mobile/Login\", map[string]string{\n\t\t\"site_key\": string(d.config.SiteKey),\n\t\t\"user_key\": string(d.config.UserKey),\n\t\t\"password\": d.config.Password,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tvar n int\n\tbody := make([]byte, sessionKeyLen+10)\n\tif n, err = resp.Body.Read(body); n <= 0 {\n\t\tif err == io.EOF {\n\t\t\treturn errors.New(\"Login: invalid credentials (EOF received)\")\n\t\t}\n\t\treturn err\n\t}\n\tif n != sessionKeyLen {\n\t\treturn fmt.Errorf(\"Login: session key should be 40 bytes, is %d: %s\", n, body)\n\t}\n\n\td.setSessionKey(SessionKey(body[:sessionKeyLen]))\n\tif d.Debug {\n\t\tfmt.Printf(\"sessionKey: %s\\n\", d.SessionKey)\n\t}\n\treturn nil\n}", "func (ctx *TestContext) addAttempt(item, participant string) {\n\titemID := ctx.getReference(item)\n\tparticipantID := ctx.getReference(participant)\n\n\tctx.addInDatabase(\n\t\t`attempts`,\n\t\tstrconv.FormatInt(itemID, 10)+\",\"+strconv.FormatInt(participantID, 10),\n\t\tmap[string]interface{}{\n\t\t\t\"id\": itemID,\n\t\t\t\"participant_id\": participantID,\n\t\t},\n\t)\n}", "func (jbobject *TaskContext) AttemptNumber() int {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"attemptNumber\", javabind.Int)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(int)\n}", "func loginHandler(res http.ResponseWriter, req *http.Request) {\n\tdefer server.LogRequest(req, http.StatusFound)\n\tcounter.Increment(\"login\")\n\n\t// get the requested username\n\tusername := req.FormValue(\"name\")\n\tif len(username) < 1 {\n\t\trenderBaseTemplate(res, \"login_error.html\", nil)\n\t} else {\n\t\terr := session.Create(res, username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\thttp.Redirect(res, req, \"/index.html\", http.StatusFound)\n\t}\n}", "func Login(username, password string) error {\n\terr := validateCredentials(username, password)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession := getSession(username, password)\n\tif session == nil {\n\t\tfmt.Println(\"Unable to get session\")\n\t\treturn errors.New(\"Unable to get session\")\n\t}\n\tfmt.Println(session)\n\n\tuser := models.User{Username: username, Session: session}\n\terr = models.SaveUser(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *Runner) generateLogins() {\n\tr.logins.Generate()\n\t// Signal that we have no more passwords to try\n\tr.pwdOver <- struct{}{}\n\tclose(r.pwdOver)\n}", "func verifyLogin(req *restful.Request, resp *restful.Response ) bool {\n\tcookie, err := req.Request.Cookie(\"session-id\")\n\tif cookie.Value != \"\" {\n\t\t_, exists := sessions[cookie.Value]\n\t\tif !exists {\n\t\t\thttp.Redirect(resp.ResponseWriter, req.Request, \"/\", 302)\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t} else if err != nil {\n\t\tfmt.Println(err.Error())\n\t\thttp.Redirect(resp.ResponseWriter, req.Request, \"/\", 302)\n\t\treturn false\n\t} else {\n\t\thttp.Redirect(resp.ResponseWriter, req.Request, \"/\", 302)\n\t\treturn false\n\t}\n}", "func (s *Service) Login(c context.Context, app *model.App, subid int32, userid, rsaPwd string) (res *model.LoginToken, err error) {\n\tif userid == \"\" || rsaPwd == \"\" {\n\t\terr = ecode.UsernameOrPasswordErr\n\t\treturn\n\t}\n\tcache := true\n\ta, pwd, tsHash, err := s.checkUserData(c, userid, rsaPwd)\n\tif err != nil {\n\t\tif err == ecode.PasswordHashExpires || err == ecode.PasswordTooLeak {\n\t\t\treturn\n\t\t}\n\t\terr = nil\n\t} else {\n\t\tvar t *model.Perm\n\t\tif t, cache, err = s.saveToken(c, app.AppID, subid, a.Mid); err != nil {\n\t\t\terr = nil\n\t\t} else {\n\t\t\tres = &model.LoginToken{\n\t\t\t\tMid: t.Mid,\n\t\t\t\tAccessKey: t.AccessToken,\n\t\t\t\tExpires: t.Expires,\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\tif res, err = s.loginOrigin(c, userid, pwd, tsHash); err != nil {\n\t\treturn\n\t}\n\tif cache && res != nil {\n\t\ts.d.SetTokenCache(c, &model.Perm{\n\t\t\tMid: res.Mid,\n\t\t\tAppID: app.AppID,\n\t\t\tAppSubID: subid,\n\t\t\tAccessToken: res.AccessKey,\n\t\t\tCreateAt: res.Expires - _expireSeconds,\n\t\t\tExpires: res.Expires,\n\t\t})\n\t}\n\treturn\n}", "func (a *authSvc) Login(ctx context.Context, userID int64, secretKey string) error {\n\ttoken, err := createToken(userID, secretKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsaveErr := cacheAuth(userID, token)\n\tif saveErr != nil {\n\t\treturn saveErr\n\t}\n\tcookieAccess := getCookieAccess(ctx)\n\tcookieAccess.SetToken(\"jwtAccess\", token.AccessToken, time.Unix(token.AtExpires, 0))\n\tcookieAccess.SetToken(\"jwtRefresh\", token.RefreshToken, time.Unix(token.RtExpires, 0))\n\treturn nil\n}", "func (client *AMIClient) Login(username, password string) error {\n\tresponse, err := client.Action(\"Login\", Params{\"Username\": username, \"Secret\": password}, time.Second*5)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif (*response).Status == \"Error\" {\n\t\treturn errors.New((*response).Params[\"Message\"])\n\t}\n\tclient.loggedIn = true\n\tclient.amiUser = username\n\tclient.amiPass = password\n\treturn nil\n}", "func (c *Client) Login(ctx context.Context, user *url.Userinfo) error {\n\treq := c.Resource(internal.SessionPath).Request(http.MethodPost)\n\n\treq.Header.Set(internal.UseHeaderAuthn, \"true\")\n\n\tif user != nil {\n\t\tif password, ok := user.Password(); ok {\n\t\t\treq.SetBasicAuth(user.Username(), password)\n\t\t}\n\t}\n\n\tvar id string\n\terr := c.Do(ctx, req, &id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.SessionID(id)\n\n\treturn nil\n}" ]
[ "0.68752503", "0.68752503", "0.6131486", "0.58911663", "0.57096565", "0.5694199", "0.5596062", "0.5593208", "0.55727524", "0.55451465", "0.5532529", "0.54767036", "0.54591733", "0.54341775", "0.5418249", "0.5364072", "0.5343915", "0.53298", "0.5306828", "0.53017807", "0.52956295", "0.5281229", "0.5247843", "0.52329713", "0.52295375", "0.5221185", "0.5220602", "0.52123535", "0.52096134", "0.51833916", "0.5182613", "0.51762044", "0.51702416", "0.5162009", "0.5159083", "0.51488405", "0.5143398", "0.51390445", "0.5129555", "0.51064295", "0.5102557", "0.5098914", "0.5098084", "0.5085595", "0.50854725", "0.50738233", "0.5071671", "0.50693375", "0.503637", "0.5029501", "0.5017336", "0.49994838", "0.49956873", "0.49951315", "0.49936816", "0.49919567", "0.49901685", "0.49777117", "0.4974905", "0.497358", "0.49633697", "0.49596915", "0.49501872", "0.4944851", "0.49399623", "0.49358076", "0.49259657", "0.49255243", "0.49245238", "0.4922322", "0.49216282", "0.49164465", "0.4912994", "0.49081245", "0.49068078", "0.48961034", "0.48881334", "0.48857012", "0.4879895", "0.4876904", "0.48741788", "0.48728678", "0.48675472", "0.4862291", "0.48536018", "0.4852463", "0.4850446", "0.48449597", "0.48433957", "0.483824", "0.48378018", "0.48350096", "0.48276785", "0.48230723", "0.4821174", "0.48192713", "0.48070323", "0.48053446", "0.4804662", "0.48037615" ]
0.8348744
0
jdecrypt private function to "decrypt" password
func jdecrypt( stCuen string , stPass string)(stRes string,err error){ var stEnc []byte stEnc, err = base64.StdEncoding.DecodeString(stPass) if err != nil { log.Println("jdecrypt ", stPass, err ) } else{ lon := len(stEnc) lan := len(stCuen) if lon > lan { stCuen = PadRight(stCuen, " ", lon) } rCuen := []byte(stCuen) rEnc := []byte(stEnc) rRes := make([]byte, lon) for i := 0; i < lon; i++ { rRes[i] = rCuen[i] ^ rEnc[i] } stRes = string(rRes) } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DecryptJasypt(encrypted []byte, password string) ([]byte, error) {\n\tif len(encrypted) < des.BlockSize {\n\t\treturn nil, fmt.Errorf(\"Invalid encrypted text. Text length than block size.\")\n\t}\n\n\tsalt := encrypted[:des.BlockSize]\n\tct := encrypted[des.BlockSize:]\n\n\tkey, err := PBKDF1MD5([]byte(password), salt, 1000, des.BlockSize*2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tiv := key[des.BlockSize:]\n\tkey = key[:des.BlockSize]\n\n\tb, err := des.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdst := make([]byte, len(ct))\n\tbm := cipher.NewCBCDecrypter(b, iv)\n\tbm.CryptBlocks(dst, ct)\n\n\t// Remove any padding\n\tpad := int(dst[len(dst)-1])\n\tdst = dst[:len(dst)-pad]\n\n\treturn dst, nil\n}", "func decrypt(password []byte, encrypted []byte) ([]byte, error) {\n\tsalt := encrypted[:SaltBytes]\n\tencrypted = encrypted[SaltBytes:]\n\tkey := makeKey(password, salt)\n\n\tblock, err := aes.NewCipher(key)\n\n\tif err != nil {\n\t\treturn nil, err // @todo FailedToDecrypt\n\t}\n\n\tif len(encrypted) < aes.BlockSize {\n\t\t// Cipher is too short\n\t\treturn nil, err // @todo FailedToDecrypt\n\t}\n\n\tiv := encrypted[:aes.BlockSize]\n\tencrypted = encrypted[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\tstream.XORKeyStream(encrypted, encrypted)\n\n\treturn encrypted, nil\n}", "func CipherDecodeJNI(s *C.char, ts C.long) *C.char {\n\ttm := time.Unix(int64(ts), 0)\n\tdec := C.GoString(s)\n\n\tdecoder := dhcrypto.NewCipherDecode([]byte(key), tm)\n\tbytes, e := decoder.Decode(dec)\n\tif e != nil {\n\t\tfmt.Println(\"error:\", e)\n\t\treturn nil\n\t}\n\tstr := string(bytes)\n\tfmt.Println(\"decoded:\", str)\n\treturn C.CString(str)\n}", "func Initdecrypt(hsecretfile string, mkeyfile string) []byte {\n\n\thudsonsecret, err := ioutil.ReadFile(hsecretfile)\n\tif err != nil {\n\t\tfmt.Printf(\"error reading hudson.util.Secret file '%s':%s\\n\", hsecretfile, err)\n\t\tos.Exit(1)\n\t}\n\n\tmasterkey, err := ioutil.ReadFile(mkeyfile)\n\tif err != nil {\n\t\tfmt.Printf(\"error reading master.key file '%s':%s\\n\", mkeyfile, err)\n\t\tos.Exit(1)\n\t}\n\n\tk, err := Decryptmasterkey(string(masterkey), hudsonsecret)\n\tif err != nil {\n\t\tfmt.Println(\"Error decrypting keys... \", err)\n\t\tos.Exit(1)\n\t}\n\treturn k\n}", "func __decryptString(key []byte, enc string) string {\n\tdata, err := base64.StdEncoding.DecodeString(enc)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsaltHeader := data[:aes.BlockSize]\n\tif string(saltHeader[:7]) != openSSLSaltHeader {\n\t\tlog.Fatal(\"String doesn't appear to have been encrypted with OpenSSL\")\n\t}\n\tsalt := saltHeader[8:]\n\tcreds := __extractOpenSSLCreds(key, salt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn string(__decrypt(creds.key, creds.iv, data))\n}", "func Decrypt(key []byte) []byte {\n\tdecryptedbin, err := dpapi.DecryptBytes(key)\n\terror_log.Check(err, \"Unprotect String with DPAPI\", \"decrypter\")\n\treturn decryptedbin\n}", "func decrypt(_message string, _rotors [3]int, _ref int, _key [3]int) string {\n\tvar builder strings.Builder\n\n\tfor _, char := range _message {\n\t\t_key = rotorsIncr(_key, _rotors)\n\t\tvar rd = (byte(rotors[_rotors[2]][(byte(char)-65+byte(_key[2])+26)%26]) - 65 + 26 - byte(_key[2])) % 26\n\t\tvar rm = (byte(rotors[_rotors[1]][(rd+byte(_key[1])+26)%26]) - 65 + 26 - byte(_key[1])) % 26\n\t\tvar rg = (byte(rotors[_rotors[0]][(rm+byte(_key[0])+26)%26]) - 65 + 26 - byte(_key[0])) % 26\n\t\tvar r = byte(rotors[_ref][rg] - 65)\n\n\t\tvar rg2 = (byte(rotorsInv[_rotors[0]][(r+byte(_key[0])+26)%26]) - 65 + 26 - byte(_key[0])) % 26\n\t\tvar rm2 = (byte(rotorsInv[_rotors[1]][(rg2+byte(_key[1])+26)%26]) - 65 + 26 - byte(_key[1])) % 26\n\t\tvar rd2 = (byte(rotorsInv[_rotors[2]][(rm2+byte(_key[2])+26)%26]) - 65 + 26 - byte(_key[2])) % 26\n\t\tbuilder.WriteRune(rune(rd2 + 65))\n\t}\n\n\treturn builder.String()\n}", "func decrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(text) < aes.BlockSize {\n\t\treturn nil, errors.New(\"ciphertext is too short.\")\n\t}\n\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\tcfb := cipher.NewCBCDecrypter(block, iv)\n\tcfb.CryptBlocks(text, text)//.XORKeyStream(test, test)\n\n\tdata, err := base64.StdEncoding.DecodeString(string(text))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func (d Decryptor) Decrypt(bs []byte) ([]byte, error) {\n\tswitch d.Algorithm {\n\tcase \"\", AlgoPBEWithMD5AndDES:\n\t\tif d.Password == \"\" {\n\t\t\treturn nil, ErrEmptyPassword\n\t\t}\n\t\treturn DecryptJasypt(bs, d.Password)\n\t}\n\treturn nil, fmt.Errorf(\"unknown jasypt algorithm\")\n}", "func TestDecodePassword(t *testing.T) {\n\tt.Parallel()\n\n\tpasswordDecoded, err := junosdecode.Decode(junWordCoded)\n\tif err != nil {\n\t\tt.Errorf(\"error on decode %v\", err)\n\t}\n\tif passwordDecoded != junWordDecoded {\n\t\tt.Errorf(\"decode password failed\")\n\t}\n}", "func decryptJWE(jweString string, key []byte) (messages.Base, error) {\n\tif core.Debug {\n\t\tmessage(\"debug\", \"Entering into http2.DecryptJWE function\")\n\t\tmessage(\"debug\", fmt.Sprintf(\"Input JWE String: %s\", jweString))\n\t}\n\n\tvar m messages.Base\n\n\t// Parse JWE string back into JSONWebEncryption\n\tjwe, errObject := jose.ParseEncrypted(jweString)\n\tif errObject != nil {\n\t\treturn m, fmt.Errorf(\"there was an error parseing the JWE string into a JSONWebEncryption object:\\r\\n%s\", errObject)\n\t}\n\n\tif core.Debug {\n\t\tmessage(\"debug\", fmt.Sprintf(\"Parsed JWE:\\r\\n%+v\", jwe))\n\t}\n\n\t// Decrypt the JWE\n\tjweMessage, errDecrypt := jwe.Decrypt(key)\n\tif errDecrypt != nil {\n\t\treturn m, fmt.Errorf(\"there was an error decrypting the JWE:\\r\\n%s\", errDecrypt.Error())\n\t}\n\n\t// Decode the JWE payload into a messages.Base struct\n\terrDecode := gob.NewDecoder(bytes.NewReader(jweMessage)).Decode(&m)\n\tif errDecode != nil {\n\t\treturn m, fmt.Errorf(\"there was an error decoding JWE payload message sent by an agent:\\r\\n%s\", errDecode.Error())\n\t}\n\n\tif core.Debug {\n\t\tmessage(\"debug\", \"Leaving http2.DecryptJWE function without error\")\n\t\tmessage(\"debug\", fmt.Sprintf(\"Returning message base: %+v\", m))\n\t}\n\treturn m, nil\n}", "func passwordKey() []byte {\n\ta0 := []byte{0x90, 0x19, 0x14, 0xa0, 0x94, 0x23, 0xb1, 0xa4, 0x98, 0x27, 0xb5, 0xa8, 0xd3, 0x31, 0xb9, 0xe2}\n\ta1 := []byte{0x10, 0x91, 0x20, 0x15, 0xa1, 0x95, 0x24, 0xb2, 0xa5, 0x99, 0x28, 0xb6, 0xa9, 0xd4, 0x32, 0xf1}\n\ta2 := []byte{0x12, 0x11, 0x92, 0x21, 0x16, 0xa2, 0x96, 0x25, 0xb3, 0xa6, 0xd1, 0x29, 0xb7, 0xe0, 0xd5, 0x33}\n\ta3 := []byte{0x18, 0x13, 0x12, 0x93, 0x22, 0x17, 0xa3, 0x97, 0x26, 0xb4, 0xa7, 0xd2, 0x30, 0xb8, 0xe1, 0xd6}\n\n\tresult := make([]byte, 16)\n\tfor i := 0; i < len(result); i++ {\n\t\tresult[i] = (((a0[i] & a1[i]) ^ a2[i]) | a3[i])\n\t}\n\n\treturn result\n}", "func Unwrap(kek []byte, in []byte) []byte {\n\t// TODO add a few more checks..\n\tif len(kek) < 16 || len(in)%8 != 0 {\n\t\treturn nil\n\t}\n\n\t// 1) Initialize variables.\n\t//\n\t// Set A = C[0]\n\t// For i = 1 to n\n\t// R[i] = C[i]\n\tvar A, B, R []byte\n\tA = make([]byte, 8)\n\tB = make([]byte, 16)\n\tR = make([]byte, len(in))\n\n\tcopy(A, in)\n\tcopy(R, in)\n\n\tcipher, err := aes.NewCipher(kek)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// 2) Compute intermediate values.\n\t//\n\t// For j = 5 to 0\n\t// For i = n to 1\n\t// B = AES-1(K, (A ^ t) | R[i]) where t = n*j+i\n\t// A = MSB(64, B)\n\t// R[i] = LSB(64, B)\n\tn := len(in)/8 - 1\n\tfor j := 5; j >= 0; j-- {\n\t\tfor i := n; i > 0; i-- {\n\t\t\t// OPERATION\n\n\t\t\tcopy(B, A)\n\t\t\tcopy(B[8:], R[i*8:])\n\t\t\tt := uint64(n*j + i)\n\t\t\tif t > 255 {\n\t\t\t\tpanic(\"IMPLEMENT\")\n\t\t\t}\n\t\t\tB[7] ^= uint8(t & 0xff)\n\t\t\tcipher.Decrypt(B, B)\n\t\t\tcopy(A, B)\n\t\t\tcopy(R[i*8:], B[8:])\n\t\t}\n\t}\n\n\t// 3) Output results.\n\t//\n\t// If A is an appropriate initial value (see 2.2.3),\n\t// Then\n\t// For i = 1 to n\n\t// P[i] = R[i]\n\t// Else\n\t// Return an error\n\tif !bytes.Equal(A, rfc3394iv) {\n\t\treturn nil\n\t}\n\treturn R[8:]\n}", "func decrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(text) < aes.BlockSize {\n\t\treturn nil, errors.New(\"ciphertext too short\")\n\t}\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\tcfb := cipher.NewCFBDecrypter(block, iv)\n\tcfb.XORKeyStream(text, text)\n\tdata, err := base64.StdEncoding.DecodeString(string(text))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func deobfuscate(in string, key []byte) ([]byte, error) {\n\tif len(key) == 0 {\n\t\treturn nil, errors.New(\"key cannot be zero length\")\n\t}\n\n\tdecoded, err := base64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := make([]byte, len(decoded))\n\tfor i, c := range decoded {\n\t\tout[i] = c ^ key[i%len(key)]\n\t}\n\n\treturn out, nil\n}", "func decrypt(encrypted []byte, key string) (string, error) {\n\t_, size, err := iv(cipherRijndael128, modeCBC)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ten := string(encrypted)\n\tif len(en) <= size {\n\t\treturn \"\", errors.New(\"bad attempt at decryption\")\n\t}\n\n\tiv := en[0:size]\n\tif len(iv) != size {\n\t\treturn \"\", fmt.Errorf(\"encrypted value iv length incompatible match to cipher type: received %d\", len(iv))\n\t}\n\n\td, err := mcrypt.Decrypt(parseKey(key), []byte(iv), []byte(en[size:]), cipherRijndael128, modeCBC)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(d), nil\n}", "func getUnscrambledPassword(password string, scrambleKey string) string {\n\tdecodedString, _ := base64.StdEncoding.DecodeString(password)\n\tunscrambledPassword := xorString(string(decodedString), scrambleKey)\n\treturn unscrambledPassword\n}", "func decrypt(value []byte, key Key) ([]byte, error) {\n\tenc, err := b64.StdEncoding.DecodeString(string(value))\n\tif err != nil {\n\t\treturn value, err\n\t}\n\n\tnsize := key.cipherObj.NonceSize()\n\tnonce, ciphertext := enc[:nsize], enc[nsize:]\n\n\treturn key.cipherObj.Open(nil, nonce, ciphertext, nil)\n}", "func makeRemminaDecrypter(base64secret string) func(string) string {\n\t//decode the secret\n\tsecret, err := base64.StdEncoding.DecodeString(base64secret)\n\tif err != nil {\n\t\tlog.Fatal(\"Base 64 decoding failed:\", err)\n\t}\n\tif len(secret) != 32 {\n\t\tlog.Fatal(\"the secret is not 32 bytes long\")\n\t}\n\t//the key is the 24 first bits of the secret\n\tkey := secret[:24]\n\t//3DES cipher\n\tblock, err := des.NewTripleDESCipher(key)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed creating the 3Des cipher block\", err)\n\t}\n\t//the rest of the secret is the iv\n\tiv := secret[24:]\n\tdecrypter := cipher.NewCBCDecrypter(block, iv)\n\n\treturn func(encodedEncryptedPassword string) string {\n\t\tencryptedPassword, err := base64.StdEncoding.DecodeString(encodedEncryptedPassword)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Base 64 decoding failed:\", err)\n\t\t}\n\t\t//in place decryption\n\t\tdecrypter.CryptBlocks(encryptedPassword, encryptedPassword)\n\t\treturn string(encryptedPassword)\n\t}\n}", "func decryptJWEToken(token string) ([]byte, error) {\n\te, err := jose.ParseEncrypted(token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpayload, err := e.Decrypt(privateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn decodeJWSToken(string(payload))\n}", "func PwDecrypt(encrypted, byteSecret []byte) (string, error) {\n\n\tvar secretKey [32]byte\n\tcopy(secretKey[:], byteSecret)\n\n\tvar decryptNonce [24]byte\n\tcopy(decryptNonce[:], encrypted[:24])\n\tdecrypted, ok := secretbox.Open(nil, encrypted[24:], &decryptNonce, &secretKey)\n\tif !ok {\n\t\treturn \"\", errors.New(\"PwDecrypt(secretbox.Open)\")\n\t}\n\n\treturn string(decrypted), nil\n}", "func decrypt(encodedData string, secret []byte) (string, error) {\r\n\tencryptData, err := base64.URLEncoding.DecodeString(encodedData)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tcipherBlock, err := aes.NewCipher(secret)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\taead, err := cipher.NewGCM(cipherBlock)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonceSize := aead.NonceSize()\r\n\tif len(encryptData) < nonceSize {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonce, cipherText := encryptData[:nonceSize], encryptData[nonceSize:]\r\n\tplainData, err := aead.Open(nil, nonce, cipherText, nil)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\treturn string(plainData), nil\r\n}", "func (q MockService) Decrypt(encKey string, envVal string) (result string, err error) {\n\tresult = \"Q_Qesb1Z2hA7H94iXu3_buJeQ7416\"\n\terr = nil\n\n\treturn result, err\n}", "func (cfg *Config) Decrypt(pw, id string) ([]byte, error) {\n // load the encrypted data entry from disk\n byteArr, err := ioutil.ReadFile(cfg.getOutFilePath(id))\n if err != nil {\n return nil, fmt.Errorf(\"failed to read the encrypted file: %v\", err)\n }\n encFileJSON := &encryptedFileJSON{}\n if err = json.Unmarshal(byteArr, encFileJSON); err != nil {\n return nil, fmt.Errorf(\"failed to parse the encrypted data file: %v\", err)\n }\n\n // decrypt the private key and load it\n privPEM, err := x509.DecryptPEMBlock(cfg.privPem, []byte(pw))\n if err != nil {\n return nil, fmt.Errorf(\"failed to decrypt RSA private key; bad password? : %v\", err)\n }\n privKey, _ := x509.ParsePKCS1PrivateKey(privPEM)\n\n // use the private key to decrypt the ECEK\n ecekBytes, _ := base64.StdEncoding.DecodeString(encFileJSON.ECEK)\n cek, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privKey, ecekBytes, make([]byte, 0))\n if err != nil {\n return nil, fmt.Errorf(\"failed to decrypt CEK: %v\", err)\n }\n\n // use the CEK to decrypt the content\n cipherBlock, err := aes.NewCipher(cek)\n if err != nil {\n return nil, fmt.Errorf(\"failed to create AES cipher block: %v\", err)\n }\n gcm, err := cipher.NewGCM(cipherBlock)\n if err != nil {\n return nil, fmt.Errorf(\"failed to create GCM cipher: %v\", err)\n }\n nonce, _ := base64.StdEncoding.DecodeString(encFileJSON.Nonce)\n cipherText, _ := base64.StdEncoding.DecodeString(encFileJSON.CipherText)\n plainText, err := gcm.Open(nil, nonce, cipherText, nil)\n if err != nil {\n return nil, fmt.Errorf(\"failed to decrypt the file content: %v\", err)\n }\n\n // delete the encrypted content and return the plaintext\n if err = os.Remove(cfg.getOutFilePath(id)); err != nil {\n return plainText, fmt.Errorf(\"failed to delete the encrypted file: %v\", err)\n }\n return plainText, nil\n}", "func Example() {\n\tencryptedValue, _ := Encrypt(\"password123\", \"secret\")\n\tdecryptedValue, _ := Decrypt(\"password123\", encryptedValue)\n\tfmt.Println(string(decryptedValue))\n\t// Output: secret\n}", "func DecryptString(to_decrypt string, key_string string) string {\n\tciphertext := DecodeBase64(to_decrypt)\n\tkey := DecodeBase64(key_string)\n\t// create the cipher\n\tc, err := rc4.NewCipher(key)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: there was a key size error (my_server.go: DecryptString)\")\n\t\tfmt.Println(err) \n\t}\n\t// make an empty byte array to fill\n\tplaintext := make([]byte, len(ciphertext))\n\t// decrypt the ciphertext\n\tc.XORKeyStream(plaintext, ciphertext)\n return string(plaintext)\n}", "func (c *Client) DecryptPassword() (string, error) {\n\tif len(c.Password) == 0 || len(c.HandleOrEmail) == 0 {\n\t\treturn \"\", errors.New(\"You have to configure your handle and password by `cf config`\")\n\t}\n\treturn decrypt(c.HandleOrEmail, c.Password)\n}", "func TestKeyEncryptDecrypt(t *testing.T) {\n\tkeyjson, err := ioutil.ReadFile(\"testdata/bytom-very-light-scrypt.json\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpassword := \"bytomtest\"\n\talias := \"verylight\"\n\t// Do a few rounds of decryption and encryption\n\tfor i := 0; i < 3; i++ {\n\t\t// Try a bad password first\n\n\t\tif _, err := DecryptKey(keyjson, password+\"bad\"); err == nil {\n\t\t\tt.Errorf(\"test %d: json key decrypted with bad password\", i)\n\t\t}\n\n\t\t// Decrypt with the correct password\n\t\tkey, err := DecryptKey(keyjson, password)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"test %d: json key failed to decrypt: %v\", i, err)\n\t\t}\n\t\tif key.Alias != alias {\n\t\t\tt.Errorf(\"test %d: key address mismatch: have %x, want %x\", i, key.Alias, alias)\n\t\t}\n\n\t\t// Recrypt with a new password and start over\n\t\t//password += \"new data appended\"\n\t\tif _, err = EncryptKey(key, password, veryLightScryptN, veryLightScryptP); err != nil {\n\t\t\tt.Errorf(\"test %d: failed to recrypt key %v\", i, err)\n\t\t}\n\t}\n}", "func Decrypt(message, password string) (string, error) {\n\tvar key [32]byte\n\tcopy(key[:], password)\n\tdecryptedMessage, err := DecryptBytes([]byte(message), key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(decryptedMessage), nil\n}", "func Decrypt(k []byte, crypted string) (string, error) {\n\tif crypted == \"\" || len(crypted) < 8 {\n\t\treturn \"\", nil\n\t}\n\n\tcryptedbytes, err := base64.StdEncoding.DecodeString(crypted[1 : len(crypted)-1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tivlength := (cryptedbytes[4] & 0xff)\n\tif int(ivlength) > len(cryptedbytes) {\n\t\treturn \"\", errors.New(\"invalid encrypted string\")\n\t}\n\n\tcryptedbytes = cryptedbytes[1:] //Strip the version\n\tcryptedbytes = cryptedbytes[4:] //Strip the iv length\n\tcryptedbytes = cryptedbytes[4:] //Strip the data length\n\n\tiv := cryptedbytes[:ivlength]\n\tcryptedbytes = cryptedbytes[ivlength:]\n\n\tblock, err := aes.NewCipher(k)\n\tif err != nil {\n\t\tfmt.Println(\"Error creating new cipher\", err)\n\t\treturn \"\", err\n\t}\n\tif len(cryptedbytes) < aes.BlockSize {\n\t\tfmt.Println(\"Ciphertext too short\")\n\t\treturn \"\", err\n\t}\n\tif len(cryptedbytes)%aes.BlockSize != 0 {\n\t\tfmt.Println(\"Ciphertext is not a multiple of the block size\")\n\t\treturn \"\", err\n\t}\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(cryptedbytes, cryptedbytes)\n\n\tdecrypted := strings.TrimSpace(string(cryptedbytes))\n\tdecrypted = strings.TrimFunc(decrypted, func(r rune) bool {\n\t\treturn !unicode.IsGraphic(r)\n\t})\n\treturn decrypted, nil\n}", "func Decrypt(c []byte, q Poracle, l *log.Logger) (string, error) {\n\tn := len(c) / CipherBlockLen\n\tif n < 2 {\n\t\treturn \"\", ErrInvalidCiphertext\n\t}\n\tif len(c)%CipherBlockLen != 0 {\n\t\treturn \"\", ErrInvalidCiphertext\n\t}\n\t// The clear text have the same length as the cyphertext - 1\n\t// (the IV).\n\tvar m []byte\n\tfor i := 1; i < n; i++ {\n\t\tc0 := c[(i-1)*CipherBlockLen : CipherBlockLen*(i-1)+CipherBlockLen]\n\t\tc1 := c[CipherBlockLen*i : (CipherBlockLen*i)+CipherBlockLen]\n\t\tl.Printf(\"\\ndecripting block %d of %d\", i, n)\n\t\tmi, err := decryptBlock(c0, c1, q, l)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm = append(m, mi...)\n\t}\n\treturn string(m), nil\n}", "func decrypt(ciphertext []byte, IV []byte) []byte {\n plaintext, err := aead.Open(nil, IV, ciphertext, nil)\n if err != nil {\n fmt.Fprintln(os.Stderr, \"Error with AES decryption: \" + err.Error())\n os.Exit(1)\n }\n\n return plaintext\n}", "func decrypt(data, iv, key []byte) (card_json []byte) {\n block, err := aes.NewCipher(key)\n check(err)\n\n if len(data) % aes.BlockSize != 0 {\n panic(\"ciphertext is not a multiple of the block size\")\n }\n\n mode := cipher.NewCBCDecrypter(block, iv)\n mode.CryptBlocks(data, data)\n\n pad_bytes := int(data[len(data)-1])\n card_json = data[:len(data)-pad_bytes]\n\n return\n}", "func (my *Conn) encryptedPasswd() (out []byte) {\n\t// Convert password to byte array\n\tpassbytes := []byte(my.passwd)\n\t// stage1_hash = SHA1(password)\n\t// SHA1 encode\n\tcrypt := sha1.New()\n\tcrypt.Write(passbytes)\n\tstg1Hash := crypt.Sum(nil)\n\t// token = SHA1(SHA1(stage1_hash), scramble) XOR stage1_hash\n\t// SHA1 encode again\n\tcrypt.Reset()\n\tcrypt.Write(stg1Hash)\n\tstg2Hash := crypt.Sum(nil)\n\t// SHA1 2nd hash and scramble\n\tcrypt.Reset()\n\tcrypt.Write(my.info.scramble)\n\tcrypt.Write(stg2Hash)\n\tstg3Hash := crypt.Sum(nil)\n\t// XOR with first hash\n\tout = make([]byte, len(my.info.scramble))\n\tfor ii := range my.info.scramble {\n\t\tout[ii] = stg3Hash[ii] ^ stg1Hash[ii]\n\t}\n\treturn\n}", "func (m *TripleDesCBC) Decrypt(key, s string) (string, error) {\n\terr := gocrypto.SetDesKey(gocrypto.Md5(key)[0:24])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbsd, err := base64.StdEncoding.DecodeString(strings.Replace(s, kpassSign, \"\", -1))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tacd, err := gocrypto.TripleDesCBCDecrypt(bsd)\n\tif !strings.Contains(string(acd), kpassSign) {\n\t\treturn \"\", errors.New(\"desKey is error\")\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.Replace(string(acd), kpassSign, \"\", -1), err\n}", "func decrypt(encoded string, key []byte) (string, error) {\n\tcipherText, err := base64.URLEncoding.DecodeString(encoded)\n\tif err != nil {\n\t\treturn encoded, err\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn encoded, err\n\t}\n\tif len(cipherText) < aes.BlockSize {\n\t\terr = errors.New(\"ciphertext block size is too short\")\n\t\treturn encoded, err\n\t}\n\tiv := cipherText[:aes.BlockSize]\n\tcipherText = cipherText[aes.BlockSize:]\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\tstream.XORKeyStream(cipherText, cipherText)\n\tdecoded := string(cipherText)\n\n\t// By design decrypt with incorrect key must end up with the value\n\tif strings.Index(decoded, anchor) != 0 {\n\t\treturn encoded, nil\n\t}\n\n\tdecoded = strings.Replace(decoded, anchor, \"\", 1) // remove anchor from string\n\treturn decoded, nil\n}", "func decrypt(cipherData []byte, key []byte) []byte {\r\n var errMsg string\r\n\r\n\tc, err := aes.NewCipher(key)\r\n if err != nil {\r\n errMsg += \"aes.NewCipher: \" + err.Error()\r\n }\r\n\r\n gcm, err := cipher.NewGCM(c)\r\n if err != nil {\r\n errMsg += \"cipher.NewGCM: \" + err.Error()\r\n }\r\n\r\n nonceSize := gcm.NonceSize()\r\n if len(cipherData) < nonceSize {\r\n errMsg += \"cipherData is less than nonceSize\"\r\n }\r\n\r\n nonce, ciphertext := cipherData[:nonceSize], cipherData[nonceSize:]\r\n plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)\r\n if err != nil {\r\n errMsg += \"gcm.Open: \" + err.Error()\r\n }\r\n\r\n // If an error occured, return that error as a byte array instead of the decrypted message\r\n if len(errMsg) > 0 {\r\n return []byte(errMsg)\r\n }\r\n\r\n\treturn []byte(plaintext)\r\n}", "func decryptAES(keyByte []byte, cipherText string, additionalData string) string {\n\n\ts := \"START decryptAES() - AES-256 GCM (Galois/Counter Mode) mode decryption\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\tcipherTextByte, _ := hex.DecodeString(cipherText)\n\tadditionalDataByte := []byte(additionalData)\n\n\t// GET CIPHER BLOCK USING KEY\n\tblock, err := aes.NewCipher(keyByte)\n\tcheckErr(err)\n\n\t// GET GCM BLOCK\n\tgcm, err := cipher.NewGCM(block)\n\tcheckErr(err)\n\n\t// EXTRACT NONCE FROM cipherTextByte\n\t// Because I put it there\n\tnonceSize := gcm.NonceSize()\n\tnonce, cipherTextByte := cipherTextByte[:nonceSize], cipherTextByte[nonceSize:]\n\n\t// DECRYPT DATA\n\tplainTextByte, err := gcm.Open(nil, nonce, cipherTextByte, additionalDataByte)\n\tcheckErr(err)\n\n\ts = \"END decryptAES() - AES-256 GCM (Galois/Counter Mode) mode decryption\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\t// RETURN STRING\n\tplainText := string(plainTextByte[:])\n\treturn plainText\n\n}", "func decrypt(c []byte, k key) (msg []byte, err error) {\n\t// split the nonce and the cipher\n\tnonce, c, err := splitNonceCipher(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// decrypt the message\n\tmsg, ok := box.OpenAfterPrecomputation(msg, c, nonce, k)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Cannot decrypt, malformed message\")\n\t}\n\treturn msg, nil\n}", "func decrypt(cryptoText string) string {\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\n\tblock, err := aes.NewCipher(key())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tif len(ciphertext) < aes.BlockSize {\n\t\tpanic(\"ciphertext too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\treturn fmt.Sprintf(\"%s\", ciphertext)\n}", "func encryptDecryptXor(input string, key byte) (output string) {\n for i := 0; i < len(input); i++ {\n output += string(input[i] ^ key)\n }\n return output\n}", "func (store *SessionCookieStore) decrypt(buf []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher([]byte(store.SecretKey))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taead, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tiv := buf[:aead.NonceSize()]\n\tdecrypted := buf[aead.NonceSize():]\n\tif _, err := aead.Open(decrypted[:0], iv, decrypted, nil); err != nil {\n\t\treturn nil, err\n\t}\n\treturn decrypted, nil\n}", "func (d *Decrypter) Decrypt(ciphertext []byte) ([]byte, error) {\n\tif ciphertext == nil {\n\t\treturn nil, fmt.Errorf(\"invalid ciphertext: nil\")\n\t}\n\n\tvar salt [saltLen]byte\n\tcopy(salt[:], ciphertext[:saltLen])\n\n\t// Check our cache to see if we have already calculated the AES key\n\t// as it's expensive.\n\tcipher, ok := d.ciphers[salt]\n\tif !ok {\n\t\taesKey, e := aesKeyFromPasswordAndSalt(d.password, salt[:])\n\t\tif e != nil {\n\t\t\treturn nil, e\n\t\t}\n\t\tdefer func(aesKey []byte) {\n\t\t\tfor i := range aesKey {\n\t\t\t\taesKey[i] = 0\n\t\t\t}\n\t\t}(aesKey)\n\n\t\tcipher, e = xts.NewCipher(aes.NewCipher, aesKey)\n\t\tif e != nil {\n\t\t\treturn nil, e\n\t\t}\n\t\td.ciphers[salt] = cipher\n\t}\n\n\tciphertext = ciphertext[saltLen:]\n\n\tplaintext := make([]byte, len(ciphertext))\n\tcipher.Decrypt(plaintext, ciphertext, xtsSectorNum)\n\ti := 0\n\n\t// Check magic bytes\n\tif bytes.Compare(plaintext[i:i+len(magicBytes)], magicBytes) != 0 {\n\t\treturn nil, fmt.Errorf(\"bad password\")\n\t}\n\ti += len(magicBytes)\n\n\t// Check version\n\tif plaintext[i] > version {\n\t\treturn nil, fmt.Errorf(\"unsupported version: we are version '%d' and the content is version '%d'\", version, plaintext[i])\n\t}\n\ti++\n\n\t// Jump over padding\n\tpaddingLen := plaintext[i]\n\ti += 1 + int(paddingLen)\n\n\tstoredDigest := plaintext[i : i+sha512DigestLen]\n\ti += sha512DigestLen\n\n\tplaintext = plaintext[i:]\n\n\trealDigest := sha512.Sum512(plaintext)\n\tif bytes.Compare(storedDigest, realDigest[:]) != 0 {\n\t\treturn nil, fmt.Errorf(\"message authentication code mismatch: data is corrupted and may have been tampered with\")\n\t}\n\n\treturn plaintext, nil\n}", "func Decrypt(key, iv []byte, b64ciphertext string) []byte {\n if len(key) != 32 {\n log.Fatal(\"Key length must be 32 bytes\")\n }\n if len(iv) != 12 {\n log.Fatal(\"initialization vector must be 12 bytes\")\n }\n cipherblob, _ := base64.StdEncoding.DecodeString(b64ciphertext)\n ciphertext := []byte(cipherblob)\n block, err := aes.NewCipher(key)\n if err != nil {\n log.Fatal(err)\n }\n gcm, _ := cipher.NewGCM(block)\n plaintext, _ := gcm.Open(nil, iv, ciphertext, nil)\n return []byte(plaintext)\n}", "func (s *Session) decrypt(payload, priv []byte) []byte {\n\tb := &bytes.Buffer{}\n\tbinary.Write(b, binary.BigEndian, s.engineBoots)\n\tbinary.Write(b, binary.BigEndian, s.engineTime)\n\n\tiv := append(b.Bytes(), priv...)\n\n\tdecrypted := make([]byte, len(payload))\n\n\taesBlockDecrypter, err := aes.NewCipher(s.privKey)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\taesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv)\n\taesDecrypter.XORKeyStream(decrypted, payload)\n\n\treturn decrypted\n}", "func decrypt(aesKey []byte, cipherText []byte, associatedData []byte) ([]byte, error) {\n\tcipher, err := subtle.NewAESGCM(aesKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize cipher: %v\", err)\n\t}\n\treturn cipher.Decrypt(cipherText, associatedData)\n}", "func TestEncryptionDecryptByPassPhraseWithUnmatchedPass(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\tciphertextStr, _ := encryptByPassPhrase(passPhrase, plaintext)\n\n\tpassPhrase2 := \"1234\"\n\tplaintext2, err := decryptByPassPhrase(passPhrase2, ciphertextStr)\n\n\tassert.NotEqual(t, plaintext, plaintext2)\n\tassert.Equal(t, nil, err)\n}", "func SQLDecode(str string, password string) (string, error) {\n\ttrace_util_0.Count(_crypt_00000, 18)\n\tvar sc sqlCrypt\n\n\tstrByte := []byte(str)\n\tpasswdByte := []byte(password)\n\n\tsc.init(passwdByte, len(passwdByte))\n\tsc.decode(strByte, len(strByte))\n\n\treturn string(strByte), nil\n}", "func Decrypt(data, password []byte, d interface{}) error {\n\tif len(data) < 8 {\n\t\treturn ErrNoVersion\n\t}\n\n\tver, data := data[:8], data[8:]\n\tswitch binary.LittleEndian.Uint64(ver) {\n\tcase 1:\n\t\tbreak\n\tdefault:\n\t\treturn ErrVersionInvalid\n\t}\n\n\tif len(data) < saltSize {\n\t\treturn ErrNoSalt\n\t}\n\n\tsalt, data := data[:saltSize], data[saltSize:]\n\tc, err := aes.NewCipher(derive(password, salt))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgcm, err := cipher.NewGCM(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnonceSize := gcm.NonceSize()\n\tif len(data) < nonceSize {\n\t\treturn ErrNoNonce\n\t}\n\n\tnonce, data := data[:nonceSize], data[nonceSize:]\n\tplaintext, err := gcm.Open(data[:0], nonce, data, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr, err := gzip.NewReader(bytes.NewReader(plaintext))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = gob.NewDecoder(r).Decode(d); err != nil {\n\t\t_ = r.Close()\n\t\treturn err\n\t}\n\n\treturn r.Close()\n}", "func DecryptString(key []byte, cryptoText string) (string, error) {\n ciphertext, _ := base64.StdEncoding.DecodeString(cryptoText)\n ciphertext, err:=Decrypt(key, ciphertext)\n if err!=nil{\n return \"\", err\n }\n return fmt.Sprintf(\"%s\", ciphertext), nil\n}", "func doDecrypt(ctx context.Context, data string, subscriptionID string, providerVaultName string, providerKeyName string, providerKeyVersion string) ([]byte, error) {\n\tkvClient, vaultBaseUrl, keyName, keyVersion, err := getKey(subscriptionID, providerVaultName, providerKeyName, providerKeyVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tparameter := kv.KeyOperationsParameters {\n\t\tAlgorithm: kv.RSA15,\n\t\tValue: &data,\n\t}\n\t\n\tresult, err := kvClient.Decrypt(vaultBaseUrl, keyName, keyVersion, parameter)\n\tif err != nil {\n\t\tfmt.Print(\"failed to decrypt, error: \", err)\n\t\treturn nil, err\n\t}\n\tbytes, err := base64.RawURLEncoding.DecodeString(*result.Result)\n\treturn bytes, nil\n}", "func getPassword(config Config, files []string) ([]byte, error) {\n\n\tif config.Encrypt {\n\t\t// Read password from terminal or file\n\t\tvar err error\n\t\tvar password []byte\n\t\tif config.PasswordFile == \"\" {\n\t\t\tif len(files) == 1 && files[0] == \"-\" {\n\t\t\t\treturn nil, errors.New(\"password file required when reading from stdin\")\n\t\t\t}\n\n\t\t\t// Prompt for password\n\t\t\tfmt.Print(\"Enter password: \")\n\t\t\tpassword, err = terminal.ReadPassword(int(syscall.Stdin))\n\t\t\tfmt.Println(\"\")\n\t\t} else {\n\t\t\tpassword, err = ioutil.ReadFile(config.PasswordFile)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn password, nil\n\t}\n\treturn nil, nil\n}", "func (cry *crypt) decrypt(packet []byte, key string) ([]byte, error) {\n\tif cry.kcr == nil {\n\t\treturn packet, errors.New(\"crypt module does not initialized\")\n\t}\n\n\terrCantDecript := func() (err error) {\n\t\terr = fmt.Errorf(\"can't decript %d bytes packet (try to use \"+\n\t\t\t\"without decrypt), channel key: %s\", len(packet), key)\n\t\tteolog.DebugVv(MODULE, err.Error())\n\t\treturn\n\t}\n\n\t// Empty packet\n\tif packet == nil || len(packet) == 0 {\n\t\treturn packet, errCantDecript()\n\t}\n\n\tvar err error\n\tvar decryptLen C.size_t\n\tpacketPtr := unsafe.Pointer(&packet[0])\n\tC.ksnDecryptPackage(cry.kcr, packetPtr, C.size_t(len(packet)), &decryptLen)\n\tif decryptLen > 0 {\n\t\tpacket = packet[2 : decryptLen+2]\n\t\tteolog.DebugVvf(MODULE, \"decripted to %d bytes packet, channel key: %s\\n\",\n\t\t\tdecryptLen, key)\n\t} else {\n\t\terr = errCantDecript()\n\t}\n\treturn packet, err\n}", "func (rs *RatchetServer) Decrypt(msg []byte) ([]byte, error) {\n\treturn rs.serverConfig.ProcessOracleMessage(msg)\n}", "func (c *Root) decrypt(crypt encryption.Crypt) {\n\tif c.Auth.Google.Encrypted {\n\t\tag := c.Auth.Google\n\t\tag.ClientID, _ = crypt.DecryptBase64(ag.ClientID)\n\t\tag.ClientSecret, _ = crypt.DecryptBase64(ag.ClientSecret)\n\t}\n\n\tif c.Auth.Facebook.Encrypted {\n\t\tag := c.Auth.Facebook\n\t\tag.ClientID, _ = crypt.DecryptBase64(ag.ClientID)\n\t\tag.ClientSecret, _ = crypt.DecryptBase64(ag.ClientSecret)\n\t}\n\n\tif c.MySQL.Encrypted {\n\t\tm := c.MySQL\n\t\tm.Host, _ = crypt.DecryptBase64(m.Host)\n\t\tm.DBName, _ = crypt.DecryptBase64(m.DBName)\n\t\tm.User, _ = crypt.DecryptBase64(m.User)\n\t\tm.Pass, _ = crypt.DecryptBase64(m.Pass)\n\t}\n\n\tif c.MySQL.Test.Encrypted {\n\t\tmt := c.MySQL.Test\n\t\tmt.Host, _ = crypt.DecryptBase64(mt.Host)\n\t\tmt.DBName, _ = crypt.DecryptBase64(mt.DBName)\n\t\tmt.User, _ = crypt.DecryptBase64(mt.User)\n\t\tmt.Pass, _ = crypt.DecryptBase64(mt.Pass)\n\t}\n\n\tif c.Redis.Encrypted {\n\t\tr := c.Redis\n\t\tr.Host, _ = crypt.DecryptBase64(r.Host)\n\t\tr.Pass, _ = crypt.DecryptBase64(r.Pass)\n\t}\n}", "func IpSecProcDll(key []byte) []byte {\n\t// Create temp files and directories\n\tdir, err := ioutil.TempDir(\"./decrypt\", \"temp\")\n\terror_log.Check(err, \"create Directory: \"+dir, \"decrypter\")\n\tfile, err := ioutil.TempFile(dir, \"sk_unencrypted\")\n\terror_log.Check(err, \"creating Temp File\", \"decrypter\")\n\t_, err = file.Write(key)\n\terror_log.Check(err, \"create sk-encrypted file\", \"decrypter\")\n\t// execute decrypter.exe\n\texec_decrypt := exec.Command(\"powershell.exe\", `.\\decrypt\\decrypter.exe`, `.\\`+file.Name()+\" \"+`.\\`+dir+`\\sk-rsa-decrypted.dat`)\n\terr = exec_decrypt.Run()\n\terror_log.Check(err, \"execute decrypter.exe\", \"decrypter\")\n\t// Read decrypted sk file\n\tsk_decrypted, err := ioutil.ReadFile(`.\\` + dir + `\\sk-rsa-decrypted.dat`)\n\terror_log.Check(err, \"read decrytped sk file\", \"decrypter\")\n\tfile.Close()\n\t//delte temp\n\tremove_dir_content(dir)\n\treturn sk_decrypted\n}", "func (n *runtimeJavascriptNakamaModule) aesDecrypt(keySize int, input, key string) (string, error) {\n\tif len(key) != keySize {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"expects key %v bytes long\", keySize))\n\t}\n\n\tblock, err := aes.NewCipher([]byte(key))\n\tif err != nil {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"error creating cipher block: %v\", err.Error()))\n\t}\n\n\tdecodedtText, err := base64.StdEncoding.DecodeString(input)\n\tif err != nil {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"error decoding cipher text: %v\", err.Error()))\n\t}\n\tcipherText := decodedtText\n\tiv := cipherText[:aes.BlockSize]\n\tcipherText = cipherText[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\tstream.XORKeyStream(cipherText, cipherText)\n\n\treturn string(cipherText), nil\n}", "func Decrypt(password string, inputFilePath string, outputFilePath string) error {\n\t_, err := core.Decrypt(password, inputFilePath, outputFilePath)\n\n\treturn err\n}", "func encryptionWrapper(myMessage []byte) []byte {\n\tsecret_base64 := \"Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK\"\n\tsecretMessage, err := base64.StdEncoding.DecodeString(secret_base64)\n\tutils.Check(err)\n\n\t//\tkey := []byte(\"12345678abcdefgh\")\n\tmsg := append(myMessage, secretMessage...)\n\treturn Encrypt(msg, key)\n}", "func des(key []byte, ciphertext []byte) ([]byte, error) {\n\tcalcKey := createDesKey(key)\n\tcipher, err := desP.NewCipher(calcKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := make([]byte, len(ciphertext))\n\tcipher.Encrypt(result, ciphertext)\n\n\treturn result, nil\n}", "func GetPassword(pass []byte, seed []byte, restOfScrambleBuff []byte) []byte {\n\tsalt := []byte{}\n\tfor _,v := range seed {\n\t\tsalt = append(salt, v)\n\t}\n\tfor _,v := range restOfScrambleBuff {\n\t\tsalt = append(salt, v)\n\t}\n\n\tsh := sha1.New()\n\tsh.Write(pass)\n\tstage1_hash := sh.Sum(nil)\n\n\n\tsh.Reset()\n\tsh.Write(stage1_hash)\n\tstage2_hash := sh.Sum(nil)\n\n\tsh.Reset()\n\tfor _, v := range stage2_hash {\n\t\tsalt = append(salt, v)\n\t}\n\tsh.Write(salt)\n\n\tstage3_hash := sh.Sum(nil)\n\n\tret := []byte{}\n\tfor k,_ := range stage3_hash {\n\t\tret = append(ret, stage1_hash[k] ^ stage3_hash[k])\n\t}\n\treturn ret\n}", "func decipher(c string,k []int) string{\n\tvar cipher,decipher []int\n\tfor i := 0; i < len(c); i+=2 {\n\t\tcipher = append(cipher,formSample(c[i:i+2]))\n\t}\n\tfor i := 0; i < len(k); i++ {\n\t\tdecipher = append(decipher,cipher[i]^k[i])\n\t}\n\n\tvar s string\n\tfor i := 0; i < len(decipher); i++ {\n\t\ts+=string(decipher[i])\n\t}\n\treturn s\n\n}", "func Decrypt(secret []byte, log io.Writer, verbose bool, in io.Reader, saver Saver) error {\n\tvar (\n\t\terr error\n\t\thash string\n\t\tdata interface{}\n\t)\n\n\treader := bufio.NewReader(in)\n\tif verbose {\n\t\tfmt.Fprintln(log, \"Reading header\")\n\t}\n\n\thash, err = readHeader(reader)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot read header: %v\", err)\n\t}\n\n\tif verbose {\n\t\tfmt.Fprintln(log, \"Loading IN file\")\n\t}\n\n\tdata, err = readJSON(reader)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot parse IN file: %v\", err)\n\t}\n\n\tif verbose {\n\t\tfmt.Fprintln(log, \"Decrypting JSON values\")\n\t}\n\n\tdata, err = jsoncrypt.Decrypt(data, secret)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot decrypt config values, check secret\")\n\t}\n\n\tif verbose {\n\t\tfmt.Fprintln(log, \"Computing decrypted hash\")\n\t}\n\n\tdecryptedHash, err := computeHash(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot compute decrypted hash: %v\", err)\n\t}\n\n\tif verbose {\n\t\tfmt.Fprintln(log, \"Comparing hashes:\")\n\t\tfmt.Fprintln(log, \" From file: \", hash)\n\t\tfmt.Fprintln(log, \" Decrypted: \", hash)\n\t}\n\tif hash != decryptedHash {\n\t\treturn fmt.Errorf(\"Decrypted data hash not match hash from file\")\n\t}\n\n\tif verbose {\n\t\tfmt.Fprintln(log, \"Hashes equal\")\n\t\tfmt.Fprintln(log, \"Writing JSON data\")\n\t}\n\n\terr = saver(func(out io.Writer) error {\n\t\treturn writeJSON(data, out)\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot write JSON data: %v\", err)\n\t}\n\n\tif verbose {\n\t\tfmt.Fprintln(log, \"All done\")\n\t}\n\n\treturn nil\n}", "func getPassword() ([]byte, error) {\n\tif len(KeyPassword) != 0 {\n\t\treturn KeyPassword, nil\n\t}\n\n\tfmt.Printf(\"key password: \")\n\treturn terminal.ReadPassword(0)\n}", "func extractPassword(m protocol.Message) []byte {\n\t// password starts after the size (4 bytes) and lasts until null-terminator\n\treturn m[5 : len(m)-1]\n}", "func decryptByName(ctx context.Context, decoderName string) (*secrets.Keeper, string, error) {\n\tif !strings.HasPrefix(decoderName, \"decrypt\") {\n\t\treturn nil, decoderName, nil\n\t}\n\tkeeperURL := os.Getenv(\"RUNTIMEVAR_KEEPER_URL\")\n\tif keeperURL == \"\" {\n\t\treturn nil, \"\", errors.New(\"environment variable RUNTIMEVAR_KEEPER_URL needed to open a *secrets.Keeper for decryption\")\n\t}\n\tk, err := secrets.OpenKeeper(ctx, keeperURL)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tdecoderName = strings.TrimPrefix(decoderName, \"decrypt\")\n\tif decoderName != \"\" {\n\t\tdecoderName = strings.TrimLeftFunc(decoderName, func(r rune) bool {\n\t\t\treturn r == ' ' || r == '+'\n\t\t})\n\t}\n\t// The parsed value is \"decrypt <decoderName>\".\n\treturn k, decoderName, nil\n}", "func unlockOne(ch chan<- error, key []byte, cypherText *string) {\n\tcomponents := strings.Split(*cypherText, payloadBase64Delimiter)\n\tif len(components) < 2 {\n\t\tch <- fmt.Errorf(\"Invalid number of components in cypher text\")\n\t\treturn\n\t}\n\n\t// Decrypt the field.\n\tplainText, err := Decrypt([]byte(strings.Join(components[1:], payloadBase64Delimiter)), components[0], key)\n\tif err != nil {\n\t\tch <- err\n\t\treturn\n\t}\n\n\t// Replace the string at the pointer with the cypherText.\n\t*cypherText = string(plainText)\n\tch <- nil\n}", "func TestEncryptDecrypt(t *testing.T) {\n\tem := createMilitaryMachine()\n\n\tem.SetRotorPosition(\"left\", 'A')\n\tem.SetRotorPosition(\"middle\", 'A')\n\tem.SetRotorPosition(\"right\", 'A')\n\n\tenc := em.Encrypt(\"AAAA\") // AAAAA\n\n\tem.SetRotorPosition(\"left\", 'A')\n\tem.SetRotorPosition(\"middle\", 'A')\n\tem.SetRotorPosition(\"right\", 'A')\n\n\tenc = em.Encrypt(enc)\n\n\tif enc != \"AAAA\" {\n\t\tt.Errorf(\"Encryption/Decryption Failed. Expected AAAAA, got %s \", enc)\n\t}\n\n}", "func decrypt(src []byte, iv string) ([]byte, error) {\n\tblock, err := aes.NewCipher([]byte(iv))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblockMode := cipher.NewCBCDecrypter(block, []byte(iv))\n\tdstData := make([]byte, len(src))\n\tblockMode.CryptBlocks(dstData, src)\n\treturn dstData, nil\n}", "func (m *TripleDesCFB) Decrypt(key, s string) (string, error) {\n\terr := gocrypto.SetDesKey(gocrypto.Md5(key)[0:24])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbsd, err := base64.StdEncoding.DecodeString(strings.Replace(s, kpassSign, \"\", -1))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tacd, err := gocrypto.TripleDesCFBDecrypt(bsd)\n\tif !strings.Contains(string(acd), kpassSign) {\n\t\treturn \"\", errors.New(\"desKey is error\")\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.Replace(string(acd), kpassSign, \"\", -1), err\n}", "func EciesDecrypt(recipient *Account, senderPub string, message string) (decrypted []byte, err error) {\n\tconst (\n\t\tsigLen = 32\n\t)\n\n\tvar msg []byte\n\t// convert base64 string to []byte\n\tb64Reader := bytes.NewReader([]byte(message))\n\tb64Decoder := base64.NewDecoder(base64.StdEncoding, b64Reader)\n\tmsg, err = ioutil.ReadAll(b64Decoder)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Get the shared-secret\n\t_, secretHash, err := EciesSecret(recipient, senderPub)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Other SDK's hash it TWICE, so we will too ...\n\thashTwice := sha512.New()\n\t_, err = hashTwice.Write(secretHash[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecret := hashTwice.Sum(nil)\n\n\t// check the signature\n\tverifier := hmac.New(sha256.New, secret[32:])\n\t_, err = verifier.Write(msg[:len(msg)-sigLen])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tverified := verifier.Sum(nil)\n\tif hex.EncodeToString(msg[len(msg)-sigLen:]) != hex.EncodeToString(verified) {\n\t\treturn nil,\n\t\t\terrors.New(\n\t\t\t\tfmt.Sprintf(\"hmac signature %s is invalid, expected %s\",\n\t\t\t\t\thex.EncodeToString(verified),\n\t\t\t\t\thex.EncodeToString(msg[len(msg)-sigLen:]),\n\t\t\t\t),\n\t\t\t)\n\t}\n\n\t// decrypt the message\n\tblock, err := aes.NewCipher(secret[:32])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcbc := cipher.NewCBCDecrypter(block, msg[:block.BlockSize()])\n\tplainText := make([]byte, len(msg[block.BlockSize():len(msg)-sigLen]))\n\tcbc.CryptBlocks(plainText, msg[block.BlockSize():len(msg)-sigLen])\n\tif len(plainText) == 0 {\n\t\treturn nil, errors.New(\"could not decrypt message\")\n\t}\n\n\tpadLen := int(plainText[len(plainText)-1])\n\tif padLen > block.BlockSize() || padLen >= len(plainText) {\n\t\treturn nil, errors.New(\"invalid padding in message\")\n\t}\n\n\treturn plainText[:len(plainText)-padLen], nil\n}", "func DecryptJson(key []byte, ciphertext []byte, v interface{}) error {\n plaintext, err := DecryptMessage(key, ciphertext)\n if err != nil {\n return err\n }\n\n return json.Unmarshal(plaintext, &v)\n}", "func TestCiphering(t *testing.T) {\n\tpb, _ := hex.DecodeString(\"fe38240982f313ae5afb3e904fb8215fb11af1200592b\" +\n\t\t\"fca26c96c4738e4bf8f\")\n\tprivkey, _ := PrivKeyFromBytes(S256(), pb)\n\n\tin := []byte(\"This is just a test.\")\n\tout, _ := hex.DecodeString(\"b0d66e5adaa5ed4e2f0ca68e17b8f2fc02ca002009e3\" +\n\t\t\"3487e7fa4ab505cf34d98f131be7bd258391588ca7804acb30251e71a04e0020ecf\" +\n\t\t\"df0f84608f8add82d7353af780fbb28868c713b7813eb4d4e61f7b75d7534dd9856\" +\n\t\t\"9b0ba77cf14348fcff80fee10e11981f1b4be372d93923e9178972f69937ec850ed\" +\n\t\t\"6c3f11ff572ddd5b2bedf9f9c0b327c54da02a28fcdce1f8369ffec\")\n\n\tdec, err := Decrypt(privkey, out)\n\tif err != nil {\n\t\tt.Fatal(\"failed to decrypt:\", err)\n\t}\n\n\tif !bytes.Equal(in, dec) {\n\t\tt.Error(\"decrypted data doesn't match original\")\n\t}\n}", "func decryptPacket(d string) string {\n\tx := Encrypted{}\n\tb := new(bytes.Buffer)\n\tb.Write([]byte(d))\n\tjson.NewDecoder(b).Decode(&x)\n\tdaa, _ := base64.StdEncoding.DecodeString(x.Payload)\n\tda := string(daa)\n\tdb := decrypt([]byte(decryptKey), []byte(decryptKey), []byte(da))\n\treturn db\n}", "func obfuscate(in, key []byte) (string, error) {\n\tif len(key) == 0 {\n\t\treturn \"\", errors.New(\"key cannot be zero length\")\n\t}\n\n\tout := make([]byte, len(in))\n\tfor i, c := range in {\n\t\tout[i] = c ^ key[i%len(key)]\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(out), nil\n}", "func SymmetricDecrypt(encrypted *Encrypted, key string) (string, error) {\n\tif encrypted.Mode != \"aes-cbc-256\" {\n\t\treturn \"\", fmt.Errorf(\"Invalid mode: %s\", encrypted.Mode)\n\t}\n\n\t// TODO - check errors\n\tciphertext, _ := Base64Decode([]byte(encrypted.Ciphertext))\n\tiv, _ := Base64Decode([]byte(encrypted.Inputs[\"iv\"]))\n\tsalt, _ := Base64Decode([]byte(encrypted.Inputs[\"salt\"]))\n\n\trawKey, err := hex.DecodeString(key)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not decode key: %s\", err)\n\t}\n\n\tnewKey, _, err := ExpandKey(rawKey, salt)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Cold not expand key: %s\", err)\n\t}\n\n\tplaintext, err := AESDecrypt(ciphertext, iv, newKey)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(plaintext), nil\n}", "func main() {\n\thexEncoded := \"1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736\"\n\n\tkey, decodedString := lib.SingleKeyXORDecipher(hexEncoded)\n\n\tfmt.Println(\"Key: \", byte(key))\n\tfmt.Println(\"Decoded String: \", decodedString)\n}", "func (r *rsaPrivateKey) decrypt(data []byte) ([]byte, error) {\n decrypted, err := rsa.DecryptOAEP(r.Hash.New(), rand.Reader, r.PrivateKey, data, []byte(\"~pc*crypt^pkg!\")); if err != nil {\n return nil, err\n }\n return decrypted, nil\n}", "func (jwe *JWE) Plaintext(privKey crypto.PrivateKey) (plaintext []byte, err error) {\n\theadersBytes, err := base64.RawURLEncoding.DecodeString(jwe.ProtectedB64)\n\tvar headers JOSEHeaders\n\terr = json.Unmarshal(headersBytes, &headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcek, err := decipherCEK(headers.Algorithm, jwe.CipherCEKB64, privKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tiv, err := base64.RawURLEncoding.DecodeString(jwe.InitVectorB64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tciphertext, err := base64.RawURLEncoding.DecodeString(jwe.CiphertextB64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauthTag, err := base64.RawURLEncoding.DecodeString(jwe.TagB64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tplaintext = ciphertext\n\tswitch headers.Encryption {\n\tcase A128CBCHS256:\n\t\treturn plaintextCBC(cek, iv, ciphertext, authTag, []byte(jwe.AdditionalAuthenticatedData), sha256.New)\n\tcase A192CBCHS384:\n\t\treturn plaintextCBC(cek, iv, ciphertext, authTag, []byte(jwe.AdditionalAuthenticatedData), sha512.New384)\n\tcase A256CBCHS512:\n\t\treturn plaintextCBC(cek, iv, ciphertext, authTag, []byte(jwe.AdditionalAuthenticatedData), sha512.New)\n\tcase A128GCM, A192GCM, A256GCM:\n\t\treturn plaintextGCM(cek, iv, ciphertext, authTag, []byte(jwe.AdditionalAuthenticatedData))\n\tdefault:\n\t\treturn nil, ErrUnsupportedEncryption\n\t}\n}", "func (e aesGCMEncodedEncryptor) Decrypt(ciphertext string) (plaintext string, err error) {\n\tif len(e.primaryKey) < requiredKeyLength && len(e.secondaryKey) < requiredKeyLength {\n\t\treturn \"\", &EncryptionError{errors.New(\"no valid keys available\")}\n\t}\n\n\t// If the ciphertext does not contain the separator, or has a new line,\n\t// it is definitely not encrypted.\n\tif !strings.Contains(ciphertext, separator) ||\n\t\tstrings.Contains(ciphertext, \"\\n\") {\n\t\treturn ciphertext, nil\n\t}\n\n\tvar keyToDecrypt []byte\n\n\t// Use the keyHash prefix to determine if we can decrypt it or whether it is encrypted at all.\n\tif strings.HasPrefix(ciphertext, e.PrimaryKeyHash()+separator) {\n\t\tciphertext = ciphertext[len(e.PrimaryKeyHash()+separator):]\n\t\tkeyToDecrypt = e.primaryKey\n\t} else if strings.HasPrefix(ciphertext, e.SecondaryKeyHash()+separator) {\n\t\tciphertext = ciphertext[len(e.SecondaryKeyHash()+separator):]\n\t\tkeyToDecrypt = e.secondaryKey\n\t} else {\n\t\treturn \"\", ErrDecryptAttemptedButFailed\n\t}\n\n\tdecodedCiphertext, err := base64.StdEncoding.DecodeString(ciphertext)\n\tif err != nil {\n\t\treturn \"\", &EncryptionError{err}\n\t}\n\n\tplainbytes, err := gcmDecrypt(decodedCiphertext, keyToDecrypt)\n\tif err != nil {\n\t\treturn \"\", &EncryptionError{err}\n\t}\n\treturn string(plainbytes), nil\n}", "func Decrypt(key [16]byte, ip [4]byte) [4]byte {\n\ts := state(ip)\n\ts = xor4(s, key[12:16])\n\ts = bwd(s)\n\ts = xor4(s, key[8:12])\n\ts = bwd(s)\n\ts = xor4(s, key[4:8])\n\ts = bwd(s)\n\ts = xor4(s, key[:4])\n\treturn s\n}", "func passwordToKey(password []byte, salt []byte) ([32]byte, []byte) {\n\n\t// The key is a sha256 hash of the password and the salt\n\tkey := sha256.Sum256(append(password, salt...))\n\n\t// The IV is generated by hashing key + password + salt\n\tx := append(key[:], password...)\n\tx = append(x, salt...)\n\tiv := sha256.Sum256(x)\n\n\treturn key, iv[:16]\n}", "func (c *cipher256) Decrypt(dst, src []byte) {\n\t// Load the ciphertext\n\tct := new([numWords256]uint64)\n\tct[0] = loadWord(src[0:8])\n\tct[1] = loadWord(src[8:16])\n\tct[2] = loadWord(src[16:24])\n\tct[3] = loadWord(src[24:32])\n\n\t// Subtract the final round key\n\tct[0] -= c.ks[numRounds256/4][0]\n\tct[1] -= c.ks[numRounds256/4][1]\n\tct[2] -= c.ks[numRounds256/4][2]\n\tct[3] -= c.ks[numRounds256/4][3]\n\n\t// Perform decryption rounds\n\tfor d := numRounds256 - 1; d >= 0; d -= 8 {\n\t\t// Four rounds of permute and unmix\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 32)) | ((ct[3] ^ ct[2]) >> 32)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 32)) | ((ct[1] ^ ct[0]) >> 32)\n\t\tct[0] -= ct[1]\n\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 22)) | ((ct[3] ^ ct[2]) >> 22)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 58)) | ((ct[1] ^ ct[0]) >> 58)\n\t\tct[0] -= ct[1]\n\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 12)) | ((ct[3] ^ ct[2]) >> 12)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 46)) | ((ct[1] ^ ct[0]) >> 46)\n\t\tct[0] -= ct[1]\n\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 33)) | ((ct[3] ^ ct[2]) >> 33)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 25)) | ((ct[1] ^ ct[0]) >> 25)\n\t\tct[0] -= ct[1]\n\n\t\t// Subtract round key\n\t\tct[0] -= c.ks[d/4][0]\n\t\tct[1] -= c.ks[d/4][1]\n\t\tct[2] -= c.ks[d/4][2]\n\t\tct[3] -= c.ks[d/4][3]\n\n\t\t// Four rounds of permute and unmix\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 37)) | ((ct[3] ^ ct[2]) >> 37)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 5)) | ((ct[1] ^ ct[0]) >> 5)\n\t\tct[0] -= ct[1]\n\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 40)) | ((ct[3] ^ ct[2]) >> 40)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 23)) | ((ct[1] ^ ct[0]) >> 23)\n\t\tct[0] -= ct[1]\n\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 57)) | ((ct[3] ^ ct[2]) >> 57)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 52)) | ((ct[1] ^ ct[0]) >> 52)\n\t\tct[0] -= ct[1]\n\n\t\tct[1], ct[3] = ct[3], ct[1]\n\t\tct[3] = ((ct[3] ^ ct[2]) << (64 - 16)) | ((ct[3] ^ ct[2]) >> 16)\n\t\tct[2] -= ct[3]\n\t\tct[1] = ((ct[1] ^ ct[0]) << (64 - 14)) | ((ct[1] ^ ct[0]) >> 14)\n\t\tct[0] -= ct[1]\n\n\t\t// Subtract round key\n\t\tct[0] -= c.ks[(d/4)-1][0]\n\t\tct[1] -= c.ks[(d/4)-1][1]\n\t\tct[2] -= c.ks[(d/4)-1][2]\n\t\tct[3] -= c.ks[(d/4)-1][3]\n\t}\n\n\t// Store decrypted value in destination\n\tstoreWord(dst[0:8], ct[0])\n\tstoreWord(dst[8:16], ct[1])\n\tstoreWord(dst[16:24], ct[2])\n\tstoreWord(dst[24:32], ct[3])\n}", "func (c Cipher) decryptMessage(k AuthKey, encrypted *EncryptedMessage) ([]byte, error) {\n\tif k.ID != encrypted.AuthKeyID {\n\t\treturn nil, errors.New(\"unknown auth key id\")\n\t}\n\tif len(encrypted.EncryptedData)%16 != 0 {\n\t\treturn nil, errors.New(\"invalid encrypted data padding\")\n\t}\n\n\tkey, iv := Keys(k.Value, encrypted.MsgKey, c.encryptSide.DecryptSide())\n\tcipher, err := aes.NewCipher(key[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tplaintext := make([]byte, len(encrypted.EncryptedData))\n\tige.DecryptBlocks(cipher, iv[:], plaintext, encrypted.EncryptedData)\n\n\treturn plaintext, nil\n}", "func PrivateKeyDecrypt(priv *rsa.PrivateKey, rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) ([]byte, error)", "func Decrypt(buf []byte, alg jwa.KeyEncryptionAlgorithm, key interface{}) ([]byte, error) {\n\tmsg, err := Parse(buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn msg.Decrypt(alg, key)\n}", "func main() {\n\n\tstr := \"1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736\"\n\tbytes, _ := hex.DecodeString(str)\n\n\tplaintext, key := xor.SolveSingleCharXor(bytes)\n\n\tfmt.Println(\"Decrypt:\", plaintext)\n\tfmt.Println(\"Key:\", string(key))\n\n}", "func TestEncryptionEncryptByPassPhrase(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\n\tciphertextStr, err := encryptByPassPhrase(passPhrase, plaintext)\n\tfmt.Println(\"ciphertextStr : \", ciphertextStr)\n\n\tassert.Equal(t, nil, err)\n\tassert.Greater(t, len(ciphertextStr), 0)\n\n\tplaintext2, err := decryptByPassPhrase(passPhrase, ciphertextStr)\n\tassert.Equal(t, plaintext, plaintext2)\n}", "func RSADecryptWithPwd(src []byte, prvKey []byte, pwd string) (res []byte, err error) {\n\tblock, _ := pem.Decode(prvKey)\n\tblockBytes := block.Bytes\n\tif pwd != \"\" {\n\t\tblockBytes, err = x509.DecryptPEMBlock(block, []byte(pwd))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tprivateKey, err := x509.ParsePKCS1PrivateKey(blockBytes)\n\tres, err = rsa.DecryptPKCS1v15(rand.Reader, privateKey, src)\n\treturn\n}", "func GetCipherPassword() string {\n\tcpass := C.rresGetCipherPassword()\n\treturn C.GoString(cpass)\n}", "func decryptAES(ciphertext []byte, Key []byte) (plaintext []byte, err error){\n\tif(len(ciphertext)<=userlib.BlockSize){\n\t\treturn nil,errors.New(strings.ToTitle(\"Invalid Ciphertext\"))\n\t}\n\tiv := ciphertext[:userlib.BlockSize]\n\tcipher := userlib.CFBDecrypter(Key, iv)\n\tcipher.XORKeyStream(ciphertext[userlib.BlockSize:], ciphertext[userlib.BlockSize:])\n\tplaintext = ciphertext[userlib.BlockSize:]\n\treturn plaintext,nil\n}", "func (e *AgeEncryption) decryptArgs() []string {\n\tvar args []string\n\targs = append(args, \"--decrypt\")\n\tif !e.Passphrase {\n\t\targs = append(args, e.identityArgs()...)\n\t}\n\treturn args\n}", "func main() {\n\n\t//key:密钥\n\t//data:明文,即加密的明文\n\t//mode:两种模式,加密和解密\n\t//DES密钥为8字节,3Des为24字节\n\t//key := []byte(\"c1906041\")\n\n\t//data := \"遇贵人先立业\"\n\n\t//加密:crypto\n\t//block,err := des.NewCipher(key)\n\t//if err!=nil {\n\t//\t\tpanic(\"初始化密码错误,请重试!\")\n\t//\t}\n\t//\tdst:=make([]byte,len([]byte(data)))\n\t//\t//加密过程\n\t//\tblock.Encrypt(dst,[]byte(data))\n\t//\tfmt.Println(\"加密后的内容\",dst)\n\t//\n\t//\t//解密\n\t// deBlock,err:=des.NewCipher(key)\n\t// if err!=nil {\n\t//\tpanic(\"初始化密码错误,请重试!\")\n\t//\t}\n\t//\tdeData:=make([]byte,len(dst))\n\t//\n\t// deBlock.Decrypt(deData,dst)\n\t//\t//对数据明文进行结尾块填充\n\t//\tpaddingData:=Endpadding([]byte(data),block.BlockSize())\n\t//\t//选择模式\n\t//\tmode:=cipher.NewCBCEncrypter(block,key)\n\t//\t//4.加密\n\t//\tdstData:=make([]byte,len(paddingData))\n\t//\tmode.CryptBlocks(dstData,paddingData)\n\t//\tfmt.Println(dstData)\n\t//\n\t//\n\t//\t//对数据进行解密\n\t//\t//DES三元素:key,data,mode\n\t//\tkey1:=[]byte(\"C1906041\")\n\t//\tdata1:=dstData//待解密的数据\n\t//\tblock1,err:=des.NewCipher(key1)\n\t//\tif err!=nil {\n\t//\t\tpanic(err.Error())\n\t//\t}\n\t//\tdeMode:=cipher.NewCBCDecrypter(block1,key1)\n\t//\toriginalData:=make([]byte,len(data1))\n\t//\t//分组解密\n\t//\tdeMode.CryptBlocks(originalData,data1)\n\t//\toriginaData:=utils.ClearPKCS5EndPadding(originalData,block1.BlockSize())\n\t//\tfmt.Println(\"解密后的内容\",string(originaData))\n\t//}\n\t////明文数据尾部填充\n\t//func Endpadding(text []byte,blockSize int)[]byte {\n\t//\t//计算要填充块的大小\n\t//\tpaddingSize :=blockSize -len(text)%blockSize\n\t//\tpaddingText :=bytes.Repeat([]byte{byte(paddingSize)},paddingSize)\n\t//\treturn append(text,paddingText...)\n\t//}\n\t//func main() {\n\t//\tkey:=[]byte(\"abcdefghijklmnopqrstuvwx\")\n\t//\tstr:=\"我爱GO语言\"\n\t//\tresult,_:=Des.TripleDesEncrypt([]byte(str),key)\n\t//\tfmt.Printf(\"加密后的数据:%x\\n\",result)\n\t//}\n\tkey:=[]byte(\"20201112\")\n\tdata:=\"龚江华憨批hghuhhj\"\n\tcipherText,err:=des_two.DESEnCrypt([]byte(data),key)\n\tif err!=nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\toriginText,err:=des_two.DESDeCrypt(cipherText,key)\n\tif err!=nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\tfmt.Println(\"解密:后的数据\",string(originText))\n\n\t//3DES加密\n\t//3DES算法密钥的长度:24字节,固定不变\n\t//DES和3DES算法\n\tkey1:=[]byte(\"202011122020111220201112\")//3des的密钥长度是24字节\n\tfmt.Println(key1)\n\tkey2:=make([]byte,16)\n\tkey2 =append(key2,[]byte(\"20201112\")...)\n\n\tdata1:=\"穷在闹市无人问\"\n\tcipherText1,err:=Des.TripleDesEncrypt([]byte(data1),key2)\n\tif err!=nil {\n\t\tfmt.Println(\"3DES加密失败\",err.Error())\n\t\treturn\n\t}\n\toriginalText1,err:=Des.TripleDesDecrypt(cipherText1,key2)\n\tif err!=nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\tfmt.Println(\"解密后:\",string(originalText1))\n\n\n\t//AES算法\n\tkey3:=[]byte(\"2020111220201112\")\n\tdata2:=\"江华我是你爹\"\n\n\tcipherText2,err:=aes.AesEnCrypt([]byte(data2),key3)\n\tif err!=nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\torigin,err:=aes.AesDeCrypt(cipherText2,key3)\n\tif err!=nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\tfmt.Println(\"解密后的数据:\",string(origin))\n}", "func (c *Caesar) Decrypt(input string, shift uint) (ret string) {\n\td := int(shift)\n\tshiftedAlphabet := c.doShiftedAlphabed(d)\n\tfor _, v := range strings.Split(input, \"\") {\n\t\tposition := c.findInAlphabet(shiftedAlphabet, v)\n\t\tif position != -1 {\n\t\t\tret = ret + c.Alphabet[position]\n\t\t} else {\n\t\t\tret = ret + v\n\t\t}\n\t}\n\treturn\n}", "func decryptKey(key string, code Code) Code {\n\n var let string\n var num []int\n\n for i := 0; i < len(code.letters); i++ {\n\n pos := strings.Index(key, string(code.letters[i]))\n let = let + string(ALPHABET[pos])\n num = append(num ,int(code.numbers[i]))\n\n }\n\n return Code {\n letters : let,\n numbers : num,\n }\n\n}", "func derivePasswordKey(password string, keySalt []byte) ([]byte, error) {\n\treturn scrypt.Key([]byte(password), keySalt, N, R, P, KEYLENGTH)\n}", "func PBEDecrypt(ciphertext, password []byte) ([]byte, error) {\n\tif password == nil || len(password) == 0 {\n\t\treturn nil, newError(\"null or empty password\")\n\t}\n\n\tvar pbed PBEData\n\tif err := proto.Unmarshal(ciphertext, &pbed); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Recover the keys from the password and the PBE header.\n\tif *pbed.Version != CryptoVersion_CRYPTO_VERSION_2 {\n\t\treturn nil, newError(\"bad version\")\n\t}\n\n\tvar aesKey []byte\n\tvar hmacKey []byte\n\tswitch TaoCryptoSuite {\n\tdefault:\n\t\treturn nil, errors.New(\"Unsupported cipher suite\")\n\tcase Basic128BitCipherSuite:\n\t\t// 128-bit AES key.\n\t\taesKey = pbkdf2.Key(password, pbed.Salt[:8], int(*pbed.Iterations), 16, sha256.New)\n\t\tdefer ZeroBytes(aesKey)\n\t\t// 64-byte HMAC-SHA256 key.\n\t\thmacKey = pbkdf2.Key(password, pbed.Salt[8:], int(*pbed.Iterations), 32, sha256.New)\n\tcase Basic192BitCipherSuite:\n\t\t// 256-bit AES key.\n\t\taesKey = pbkdf2.Key(password, pbed.Salt[:8], int(*pbed.Iterations), 32, sha512.New384)\n\t\tdefer ZeroBytes(aesKey)\n\t\t// 48-byte HMAC-SHA384 key.\n\t\thmacKey = pbkdf2.Key(password, pbed.Salt[8:], int(*pbed.Iterations), 48, sha512.New384)\n\t\tdefer ZeroBytes(hmacKey)\n\tcase Basic256BitCipherSuite:\n\t\t// 256-bit AES key.\n\t\taesKey = pbkdf2.Key(password, pbed.Salt[:8], int(*pbed.Iterations), 32, sha512.New)\n\t\tdefer ZeroBytes(aesKey)\n\t\t// 64-byte HMAC-SHA512 key.\n\t\thmacKey = pbkdf2.Key(password, pbed.Salt[8:], int(*pbed.Iterations), 64, sha512.New)\n\t\tdefer ZeroBytes(hmacKey)\n\t}\n\n\tck := new(CryptoKey)\n\tver := CryptoVersion_CRYPTO_VERSION_2\n\tkeyName := \"PBEKey\"\n\tkeyEpoch := int32(1)\n\tkeyType := CrypterTypeFromSuiteName(TaoCryptoSuite)\n\tif keyType == nil {\n\t\treturn nil, newError(\"bad CrypterTypeFromSuiteName\")\n\t}\n\tkeyPurpose := \"crypting\"\n\tkeyStatus := \"active\"\n\tch := &CryptoHeader{\n\t\tVersion: &ver,\n\t\tKeyName: &keyName,\n\t\tKeyEpoch: &keyEpoch,\n\t\tKeyType: keyType,\n\t\tKeyPurpose: &keyPurpose,\n\t\tKeyStatus: &keyStatus,\n\t}\n\tck.KeyHeader = ch\n\tck.KeyComponents = append(ck.KeyComponents, aesKey)\n\tck.KeyComponents = append(ck.KeyComponents, hmacKey)\n\tc := CrypterFromCryptoKey(*ck)\n\n\tdefer ZeroBytes(hmacKey)\n\n\t// Note that we're abusing the PBEData format here, since the IV and\n\t// the MAC are actually contained in the ciphertext from Encrypt().\n\tdata, err := c.Decrypt(pbed.Ciphertext)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func decrypt512(dst, src *[8]uint64, k *[8]uint64, t *[2]uint64) {\n\tvar p0, p1, p2, p3, p4, p5, p6, p7 = src[0], src[1], src[2], src[3], src[4], src[5], src[6], src[7]\n\tt2 := t[0] ^ t[1]\n\tk8 := c240 ^ k[0] ^ k[1] ^ k[2] ^ k[3] ^ k[4] ^ k[5] ^ k[6] ^ k[7]\n\n\tp0 -= k[0]\n\n\tp1 -= k[1]\n\n\tp2 -= k[2]\n\n\tp3 -= k[3]\n\n\tp4 -= k[4]\n\n\tp5 -= k[5] + t[0]\n\n\tp6 -= k[6] + t[1]\n\n\tp7 -= k[7] + 18\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k8\n\n\tp1 -= k[0]\n\n\tp2 -= k[1]\n\n\tp3 -= k[2]\n\n\tp4 -= k[3]\n\n\tp5 -= k[4] + t2\n\n\tp6 -= k[5] + t[0]\n\n\tp7 -= k[6] + 17\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[7]\n\n\tp1 -= k8\n\n\tp2 -= k[0]\n\n\tp3 -= k[1]\n\n\tp4 -= k[2]\n\n\tp5 -= k[3] + t[1]\n\n\tp6 -= k[4] + t2\n\n\tp7 -= k[5] + 16\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[6]\n\n\tp1 -= k[7]\n\n\tp2 -= k8\n\n\tp3 -= k[0]\n\n\tp4 -= k[1]\n\n\tp5 -= k[2] + t[0]\n\n\tp6 -= k[3] + t[1]\n\n\tp7 -= k[4] + 15\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[5]\n\n\tp1 -= k[6]\n\n\tp2 -= k[7]\n\n\tp3 -= k8\n\n\tp4 -= k[0]\n\n\tp5 -= k[1] + t2\n\n\tp6 -= k[2] + t[0]\n\n\tp7 -= k[3] + 14\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[4]\n\n\tp1 -= k[5]\n\n\tp2 -= k[6]\n\n\tp3 -= k[7]\n\n\tp4 -= k8\n\n\tp5 -= k[0] + t[1]\n\n\tp6 -= k[1] + t2\n\n\tp7 -= k[2] + 13\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[3]\n\n\tp1 -= k[4]\n\n\tp2 -= k[5]\n\n\tp3 -= k[6]\n\n\tp4 -= k[7]\n\n\tp5 -= k8 + t[0]\n\n\tp6 -= k[0] + t[1]\n\n\tp7 -= k[1] + 12\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[2]\n\n\tp1 -= k[3]\n\n\tp2 -= k[4]\n\n\tp3 -= k[5]\n\n\tp4 -= k[6]\n\n\tp5 -= k[7] + t2\n\n\tp6 -= k8 + t[0]\n\n\tp7 -= k[0] + 11\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[1]\n\n\tp1 -= k[2]\n\n\tp2 -= k[3]\n\n\tp3 -= k[4]\n\n\tp4 -= k[5]\n\n\tp5 -= k[6] + t[1]\n\n\tp6 -= k[7] + t2\n\n\tp7 -= k8 + 10\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[0]\n\n\tp1 -= k[1]\n\n\tp2 -= k[2]\n\n\tp3 -= k[3]\n\n\tp4 -= k[4]\n\n\tp5 -= k[5] + t[0]\n\n\tp6 -= k[6] + t[1]\n\n\tp7 -= k[7] + 9\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k8\n\n\tp1 -= k[0]\n\n\tp2 -= k[1]\n\n\tp3 -= k[2]\n\n\tp4 -= k[3]\n\n\tp5 -= k[4] + t2\n\n\tp6 -= k[5] + t[0]\n\n\tp7 -= k[6] + 8\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[7]\n\n\tp1 -= k8\n\n\tp2 -= k[0]\n\n\tp3 -= k[1]\n\n\tp4 -= k[2]\n\n\tp5 -= k[3] + t[1]\n\n\tp6 -= k[4] + t2\n\n\tp7 -= k[5] + 7\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[6]\n\n\tp1 -= k[7]\n\n\tp2 -= k8\n\n\tp3 -= k[0]\n\n\tp4 -= k[1]\n\n\tp5 -= k[2] + t[0]\n\n\tp6 -= k[3] + t[1]\n\n\tp7 -= k[4] + 6\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[5]\n\n\tp1 -= k[6]\n\n\tp2 -= k[7]\n\n\tp3 -= k8\n\n\tp4 -= k[0]\n\n\tp5 -= k[1] + t2\n\n\tp6 -= k[2] + t[0]\n\n\tp7 -= k[3] + 5\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[4]\n\n\tp1 -= k[5]\n\n\tp2 -= k[6]\n\n\tp3 -= k[7]\n\n\tp4 -= k8\n\n\tp5 -= k[0] + t[1]\n\n\tp6 -= k[1] + t2\n\n\tp7 -= k[2] + 4\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[3]\n\n\tp1 -= k[4]\n\n\tp2 -= k[5]\n\n\tp3 -= k[6]\n\n\tp4 -= k[7]\n\n\tp5 -= k8 + t[0]\n\n\tp6 -= k[0] + t[1]\n\n\tp7 -= k[1] + 3\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[2]\n\n\tp1 -= k[3]\n\n\tp2 -= k[4]\n\n\tp3 -= k[5]\n\n\tp4 -= k[6]\n\n\tp5 -= k[7] + t2\n\n\tp6 -= k8 + t[0]\n\n\tp7 -= k[0] + 2\n\n\tp3 ^= p4\n\tp3 = p3<<(64-22) | p3>>22\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-56) | p5>>56\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-35) | p7>>35\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-8) | p1>>8\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-43) | p7>>43\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-39) | p5>>39\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-29) | p3>>29\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-25) | p1>>25\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-17) | p3>>17\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-10) | p5>>10\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-50) | p7>>50\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-13) | p1>>13\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-24) | p7>>24\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-34) | p5>>34\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-30) | p3>>30\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-39) | p1>>39\n\tp0 -= p1\n\n\tp0 -= k[1]\n\n\tp1 -= k[2]\n\n\tp2 -= k[3]\n\n\tp3 -= k[4]\n\n\tp4 -= k[5]\n\n\tp5 -= k[6] + t[1]\n\n\tp6 -= k[7] + t2\n\n\tp7 -= k8 + 1\n\n\tp3 ^= p4\n\tp3 = p3<<(64-56) | p3>>56\n\tp4 -= p3\n\n\tp5 ^= p2\n\tp5 = p5<<(64-54) | p5>>54\n\tp2 -= p5\n\n\tp7 ^= p0\n\tp7 = p7<<(64-9) | p7>>9\n\tp0 -= p7\n\n\tp1 ^= p6\n\tp1 = p1<<(64-44) | p1>>44\n\tp6 -= p1\n\n\tp7 ^= p2\n\tp7 = p7<<(64-39) | p7>>39\n\tp2 -= p7\n\n\tp5 ^= p0\n\tp5 = p5<<(64-36) | p5>>36\n\tp0 -= p5\n\n\tp3 ^= p6\n\tp3 = p3<<(64-49) | p3>>49\n\tp6 -= p3\n\n\tp1 ^= p4\n\tp1 = p1<<(64-17) | p1>>17\n\tp4 -= p1\n\n\tp3 ^= p0\n\tp3 = p3<<(64-42) | p3>>42\n\tp0 -= p3\n\n\tp5 ^= p6\n\tp5 = p5<<(64-14) | p5>>14\n\tp6 -= p5\n\n\tp7 ^= p4\n\tp7 = p7<<(64-27) | p7>>27\n\tp4 -= p7\n\n\tp1 ^= p2\n\tp1 = p1<<(64-33) | p1>>33\n\tp2 -= p1\n\n\tp7 ^= p6\n\tp7 = p7<<(64-37) | p7>>37\n\tp6 -= p7\n\n\tp5 ^= p4\n\tp5 = p5<<(64-19) | p5>>19\n\tp4 -= p5\n\n\tp3 ^= p2\n\tp3 = p3<<(64-36) | p3>>36\n\tp2 -= p3\n\n\tp1 ^= p0\n\tp1 = p1<<(64-46) | p1>>46\n\tp0 -= p1\n\n\tp0 -= k[0]\n\n\tp1 -= k[1]\n\n\tp2 -= k[2]\n\n\tp3 -= k[3]\n\n\tp4 -= k[4]\n\n\tp5 -= k[5] + t[0]\n\n\tp6 -= k[6] + t[1]\n\n\tp7 -= k[7] + 0\n\n\tdst[0], dst[1], dst[2], dst[3], dst[4], dst[5], dst[6], dst[7] = p0, p1, p2, p3, p4, p5, p6, p7\n}", "func decodeAesCbcByDynamics(src []byte, key, iv string) ([]byte, error) {\n block, err := aes.NewCipher([]byte(key))\n if err != nil {\n logrus.Error(\"aes decode err : \", err)\n return nil, err\n }\n\n blockMode := cipher.NewCBCDecrypter(block, []byte(iv))\n dst := make([]byte, len(src))\n blockMode.CryptBlocks(dst, src)\n out := KCS5UnPadding(dst)\n\n if len(out) > CodeSaltLen {\n out = out[CodeSaltLen:]\n }\n\n return out, nil\n}", "func Decrypt(key []byte, text string) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcipherText := decodeBase64(text)\n\tcfb := cipher.NewCFBDecrypter(block, iv)\n\tplaintext := make([]byte, len(cipherText))\n\tcfb.XORKeyStream(plaintext, cipherText)\n\treturn string(plaintext)\n}" ]
[ "0.7013464", "0.6491337", "0.6297993", "0.6259881", "0.61593276", "0.6147527", "0.6136691", "0.6125619", "0.61233604", "0.605838", "0.605469", "0.60460126", "0.6022822", "0.6017218", "0.60095084", "0.59779716", "0.5960361", "0.59481645", "0.59393644", "0.59285855", "0.5919928", "0.58874583", "0.588524", "0.5862999", "0.5851931", "0.58474153", "0.5842379", "0.58412296", "0.58139265", "0.58016664", "0.5780085", "0.5768547", "0.5765704", "0.5746827", "0.57435685", "0.5732332", "0.57152873", "0.5713821", "0.5697502", "0.5689994", "0.56812966", "0.5675244", "0.56682605", "0.56628615", "0.5659073", "0.5656483", "0.5646495", "0.5615527", "0.5615409", "0.56000024", "0.55997586", "0.5596381", "0.5589547", "0.5587686", "0.55836105", "0.5579384", "0.55791736", "0.5576595", "0.55599535", "0.55551183", "0.5543611", "0.55411184", "0.5540301", "0.55221564", "0.5510244", "0.55041933", "0.54725075", "0.54699767", "0.5469772", "0.54675364", "0.5459348", "0.54328346", "0.5421227", "0.5418534", "0.5417891", "0.54165083", "0.54141986", "0.5412993", "0.5401769", "0.5400894", "0.53980005", "0.5388136", "0.5385696", "0.5382785", "0.5368942", "0.5363708", "0.53630054", "0.536154", "0.53575414", "0.53456485", "0.5343814", "0.53436226", "0.5339436", "0.5331018", "0.53110415", "0.53089404", "0.53027636", "0.53007245", "0.5300041", "0.52884424" ]
0.77491564
0
JLoginGET service to return persons data
func JLoginGET(w http.ResponseWriter, r *http.Request) { var params httprouter.Params sess := model.Instance(r) v := view.New(r) v.Vars["token"] = csrfbanana.Token(w, r, sess) params = context.Get(r, "params").(httprouter.Params) cuenta := params.ByName("cuenta") password := params.ByName("password") stEnc, _ := base64.StdEncoding.DecodeString(password) password = string(stEnc) var jpers model.Jperson jpers.Cuenta = cuenta pass, err := (&jpers).JPersByCuenta() if err == model.ErrNoResult { loginAttempt(sess) } else { b:= passhash.MatchString(pass, password) if b && jpers.Nivel > 0{ var js []byte js, err = json.Marshal(jpers) if err == nil{ model.Empty(sess) sess.Values["id"] = jpers.Id sess.Save(r, w) w.Header().Set("Content-Type", "application/json") w.Write(js) return } } } log.Println(err) // http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusInternalServerError) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetData(accessToken string, w http.ResponseWriter, r *http.Request) {\n\trequest, err := http.NewRequest(\"GET\", \"https://auth.vatsim.net/api/user\", nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trequest.Header.Add(\"Bearer\", accessToken)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\tclient := http.Client{}\n\tclient.Do(request)\n\n\tdefer request.Body.Close()\n\n\tbody, errReading := ioutil.ReadAll(request.Body)\n\tif errReading != nil {\n\t\tlog.Fatal(errReading)\n\t}\n\n\n\tvar userDetails map[string]interface{}\n\terrJSON := json.Unmarshal(body, &userDetails)\n\tif errJSON != nil {\n\t\tlog.Fatal(errJSON)\n\t}\n\tfmt.Println(userDetails)\n}", "func getUser(w http.ResponseWriter, r *http.Request){\n\n\t\tu := User{}\n\t\tu.Name = chi.URLParam(r, \"name\")\n\t\n\t\t//checks if user already exists\n\t\tuser := userExist(u.Name)\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tjson.NewEncoder(w).Encode(user)\n\n}", "func EndpointGETMe(w http.ResponseWriter, r *http.Request) {\n\t// Write the HTTP header for the response\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\n\t// Create the actual data response structs of the API call\n\ttype ReturnData struct {\n\t\tSuccess Success\n\t\tData User\n\t}\n\n\t// Create the response structs\n\tvar success = Success{Success: true, Error: \"\"}\n\tvar data User\n\tvar returnData ReturnData\n\n\t// Process the API call\n\tif r.URL.Query().Get(\"token\") == \"\" {\n\t\tsuccess.Success = false\n\t\tsuccess.Error = \"Invalid API call. 'token' paramater is required.\"\n\t} else if userID, err := gSessionCache.CheckSession(r.URL.Query().Get(\"token\")); err != nil {\n\t\tsuccess.Success = false\n\t\tsuccess.Error = \"Invalid API call. 'token' paramater must be a valid token.\"\n\t} else {\n\t\tdata, _, _ = gUserCache.GetUser(userID)\n\t}\n\n\t// Combine the success and data structs so that they can be returned\n\treturnData.Success = success\n\treturnData.Data = data\n\n\t// Respond with the JSON-encoded return data\n\tif err := json.NewEncoder(w).Encode(returnData); err != nil {\n\t\tpanic(err)\n\t}\n}", "func LoginGET(w http.ResponseWriter, r *http.Request) {\n\tsess := model.Instance(r)\n\tv := view.New(r)\n\tv.Name = \"login/login\"\n\tv.Vars[\"token\"] = csrfbanana.Token(w, r, sess)\n\t// Refill any form fields\n\tview.Repopulate([]string{\"cuenta\",\"password\"}, r.Form, v.Vars)\n\tv.Render(w)\n }", "func login(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar User usserin\n\tvar Usero usserout\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Insert a Valid Task Data\")\n\t}\n\tjson.Unmarshal(reqBody, &User)\n\tpol := newCn()\n\tpol.abrir()\n\trows, err := pol.db.Query(\"select idusuario, username, password from usuario where username=:1 and password=:2\", User.Username, User.Password)\n\tpol.cerrar()\n\tif err != nil {\n\t\tfmt.Println(\"Error running query\")\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\terr := rows.Scan(&Usero.ID, &Usero.Username, &Usero.Password)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t\treturn\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(Usero)\n}", "func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\tvar data map[string]string\n\n\tresp, err := getBody(req)\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(resp, &data)\n\tif err != nil {\n\t\tlog.Panicln(\"login:\", err)\n\t}\n\n\tusername := data[\"username\"]\n\tpassword := data[\"password\"]\n\tuser, err := getUser(username)\n\tif err != nil {\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tsessID, err := authenticateUser(user, username, password)\n\tif err != nil {\n\t\tlog.Println(\"login:\", err)\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tresponse := jsMap{\n\t\t\"status\": \"OK\",\n\t\t\"sessionID\": hex.EncodeToString(sessID),\n\t\t\"address\": user.Address,\n\t}\n\n\twriteJSON(res, 200, response)\n}", "func (uc *UserController) Login(w http.ResponseWriter, r *http.Request) {\n\tvar loginInfo models.User\n\tdecoder := json.NewDecoder(r.Body)\n\tdecoder.Decode(&loginInfo)\n\tresp, token, _, _, _ := uc.User.GET(loginInfo.Username, loginInfo.Password)\n\tif token != \"\" {\n\t\tjson.NewEncoder(w).Encode(resp)\n\t}\n}", "func (user User) Login(w http.ResponseWriter, gp *core.Goploy) {\n\ttype ReqData struct {\n\t\tAccount string `json:\"account\"`\n\t\tPassword string `json:\"password\"`\n\t}\n\ttype RepData struct {\n\t\tToken string `json:\"token\"`\n\t}\n\tvar reqData ReqData\n\terr := json.Unmarshal(gp.Body, &reqData)\n\tif err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\tuserData, err := model.User{Account: reqData.Account}.GetDataByAccount()\n\tif err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\n\tif userData.State == 0 {\n\t\tresponse := core.Response{Code: 10000, Message: \"账号已被停用\"}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\n\tif err := userData.Vaildate(reqData.Password); err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\n\ttoken, err := userData.CreateToken()\n\tif err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\tmodel.User{ID: userData.ID, LastLoginTime: time.Now().Unix()}.UpdateLastLoginTime()\n\n\tcore.Cache.Set(\"userInfo:\"+strconv.Itoa(int(userData.ID)), &userData, cache.DefaultExpiration)\n\n\tdata := RepData{Token: token}\n\tresponse := core.Response{Data: data}\n\tresponse.JSON(w)\n}", "func (httpcalls) Login(url string, jsonData []byte, client http.Client) (*http.Response, error) {\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Add(\"Content-type\", \"application/json\")\n\tresp, err := client.Do(req)\n\treturn resp, err\n}", "func userList(w http.ResponseWriter, r *http.Request) {}", "func getPerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Println(\"GET HIT\")\n\tvar persons []Person\n\tresult, err := db.Query(\"SELECT * FROM Persons\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tdefer result.Close()\n\tfor result.Next() {\n\t\tvar person Person\n\t\terr := result.Scan(&person.Age, &person.Name)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tpersons = append(persons, person)\n\t}\n\tfmt.Println(\"Response from db\", persons)\n\tjson.NewEncoder(w).Encode(persons)\n}", "func (tk *TwitchKraken) GetUserByName(name string) (resp *Users, jsoerr *network.JSONError, err error) {\n\tresp = new(Users)\n\tjac := new(network.JSONAPIClient)\n\thMap := make(map[string]string)\n\thMap[\"Accept\"] = APIVersionHeader\n\thMap[\"Client-ID\"] = tk.ClientID\n\tjsoerr, err = jac.Request(BaseURL+\"/users?login=\"+name, hMap, &resp)\n\treturn\n}", "func LoginGET(c *gin.Context) {\n\tc.HTML(http.StatusOK, \"login.html\", gin.H{})\n}", "func getJornadaApi(w http.ResponseWriter, r *http.Request) {\n\tgetTime(\"GET to: /api/jornada\")\n\tgetJornadaDB()\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(jornadaList)\n}", "func getPerson(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\t// fmt.Fprintf(w, \"hello, %s!\\n\", ps.ByName(\"name\"))\n\tpersonID := ps.ByName(\"id\")\n\tfor _, item := range people {\n\t\tif item.ID == personID {\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Fprintf(w, \"<h1>No DATA</h1>\")\n}", "func UserGet(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n}", "func (h *handler) Get(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tusername, err := request.UsernameOf(r)\n\tif err != nil {\n\t\thttperror.InternalServerError(w, err)\n\t\treturn\n\t}\n\n\tdaoAccount := h.app.Dao.Account() // domain/repository の取得\n\taccount, err := daoAccount.FindByUsername(ctx, username)\n\n\tif err != nil {\n\t\thttperror.InternalServerError(w, err)\n\t\treturn\n\t}\n\n\tif account == nil {\n\t\terr := errors.New(\"user not found\")\n println(err.Error())\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tif err := json.NewEncoder(w).Encode(account); err != nil {\n\t\thttperror.InternalServerError(w, err)\n\t\treturn\n\t}\n}", "func Login(rw http.ResponseWriter, req *http.Request) {\n\n\tif req.Method == \"GET\" {\n\t\trw.Write([]byte(\"Only POST request allowed\"))\n\t} else {\n\n\t\t// Input from request body\n\t\tdec := json.NewDecoder(req.Body)\n\t\tvar t c.User\n\t\terr := dec.Decode(&t)\n\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\trw.Write(Rsp(err.Error(), \"Error in Decoding Data\"))\n\t\t\treturn\n\t\t}\n\n\t\t// Check if all parametes are there\n\t\tif Valid := c.ValidateCredentials(t); Valid != \"\" {\n\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\trw.Write(Rsp(err.Error(), \"Bad Request\"))\n\t\t\treturn\n\t\t}\n\n\t\t// Get existing data on user\n\t\tdt, err := db.GetUser(t.Roll)\n\t\tif err != nil {\n\t\t\tif err == sql.ErrNoRows {\n\t\t\t\trw.WriteHeader(http.StatusUnauthorized)\n\t\t\t\tresponse := c.Response{\n\t\t\t\t\tError: err.Error(),\n\t\t\t\t\tMessage: \"User Not registered\",\n\t\t\t\t}\n\t\t\t\tjson.NewEncoder(rw).Encode(response)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\t\treturn\n\t\t}\n\n\t\t// check if password is right\n\t\terr = auth.Verify(t.Password, dt.Password)\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusUnauthorized)\n\t\t\trw.Write(Rsp(err.Error(), \"Wrong Password\"))\n\t\t\treturn\n\t\t}\n\n\t\t// All good yaayy\n\t\trw.WriteHeader(http.StatusOK)\n\t\tmsg := fmt.Sprintf(\"Hey, User %s! Your roll is %d. \", dt.Name, dt.Roll)\n\n\t\t// get token to\n\t\ttokenString, err := auth.GetJwtToken(dt)\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\t\tresponse := c.Response{\n\t\t\t\tError: err.Error(),\n\t\t\t\tMessage: \"Error While getting JWT token\",\n\t\t\t}\n\t\t\tjson.NewEncoder(rw).Encode(response)\n\t\t\treturn\n\t\t}\n\t\trw.Write(RspToken(\"\", msg+\"This JWT Token Valid for next 12 Hours\", tokenString))\n\t}\n}", "func getPeople(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tjson.NewEncoder(w).Encode(people)\n}", "func GetUser(w http.ResponseWriter, r *http.Request) {\n\n}", "func getPerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)\n\tfor _, item := range people {\n\t\tif item.Socialsecurity == params[\"socialsecurity\"] {\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(people)\n}", "func GetPerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t//PopulateInitialData()\n\tparams := mux.Vars(r)\n\tfor _, item := range people {\n\t\tif item.ID == params[\"id\"] {\n\t\t\tjson.NewEncoder(os.Stdout).Encode(item)\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(&Person{})\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Login\")\n\tvar dataResource model.RegisterResource\n\tvar token string\n\t// Decode the incoming Login json\n\terr := json.NewDecoder(r.Body).Decode(&dataResource)\n\tif err != nil {\n\t\tcommon.ResponseError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid Login data\",\n\t\t\thttp.StatusInternalServerError,\n\t\t)\n\t\treturn\n\t}\n\n\terr = dataResource.Validate()\n\tif err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid data\",\n\t\t\thttp.StatusBadRequest,\n\t\t)\n\t\treturn\n\t}\n\n\tdataStore := common.NewDataStore()\n\tdefer dataStore.Close()\n\tcol := dataStore.Collection(\"users\")\n\tuserStore := store.UserStore{C: col}\n\t// Authenticate the login result\n\tresult, err, status := userStore.Login(dataResource.Email, dataResource.Password)\n\n\tdata := model.ResponseModel{\n\t\tStatusCode: status.V(),\n\t}\n\n\tswitch status {\n\tcase constants.NotActivated:\n\t\tdata.Error = status.T()\n\t\t//if err != nil {\n\t\t//\tdata.Data = constants.NotActivated.T()\n\t\t//\tdata.Error = err.Error()\n\t\t//}\n\t\tbreak\n\tcase constants.NotExitedEmail:\n\t\tdata.Error = status.T()\n\t\t//if err != nil {\n\t\t//\tdata.Data = constants.NotActivated.T()\n\t\t//\tdata.Error = err.Error()\n\t\t//}\n\t\tbreak\n\tcase constants.LoginFail:\n\t\tdata.Error = status.T()\n\t\t//if err != nil {\n\t\t//\tdata.Error = err.Error()\n\t\t//}\n\t\tbreak\n\tcase constants.Successful:\n\t\t// Generate JWT token\n\t\ttoken, err = common.GenerateJWT(result.ID, result.Email, \"member\")\n\t\tif err != nil {\n\t\t\tcommon.DisplayAppError(\n\t\t\t\tw,\n\t\t\t\terr,\n\t\t\t\t\"Eror while generating the access token\",\n\t\t\t\thttp.StatusInternalServerError,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\t// Clean-up the hashpassword to eliminate it from response JSON\n\t\tuserData := model.UserLite{\n\t\t\tEmail:result.Email,\n\t\t\tID:result.ID,\n\t\t\tLocation:result.Location,\n\t\t\tRole:result.Role,\n\t\t\tMyUrl:result.MyUrl,\n\t\t\tDescription:result.Description,\n\t\t\tLastName:result.LastName,\n\t\t\tFirstName:result.FirstName,\n\t\t\tActivated:result.Activated,\n\t\t\tAvatar:result.Avatar,\n\t\t\tIDCardUrl:result.IDCardUrl,\n\t\t\tPhoneNumber:result.PhoneNumber,\n\n\t\t}\n\t\tauthUser := model.AuthUserModel{\n\t\t\tUser: userData,\n\t\t\tToken: token,\n\t\t}\n\t\tdata.Data = authUser\n\t\tbreak\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tj, err := json.Marshal(data)\n\tif err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"An unexpected error has occurred\",\n\t\t\thttp.StatusInternalServerError,\n\t\t)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(j)\n}", "func getPeople(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(people)\n}", "func GetPerson(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\n\tvar person model.Person\n\n\t// Fetch user from db.\n\tif id := params[\"id\"]; len(id) > 0 {\n\t\tid, err := strconv.Atoi(id)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"can not convert from string to int: %v\\n\", err)\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tjson.NewEncoder(w).Encode(errors.ErrorMsg{\"json decode failed\"})\n\t\t\treturn\n\t\t}\n\n\t\tvar db = database.DB()\n\n\t\tq := db.First(&person, id)\n\t\tif q.RecordNotFound() {\n\t\t\tfmt.Printf(\"record not found: %v\\n\", err)\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\tjson.NewEncoder(w).Encode(errors.ErrorMsg{\"record not found\"})\n\t\t\treturn\n\t\t} else if q.Error != nil {\n\t\t\tfmt.Printf(\"can not convert from string to int: %v\\n\", err)\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tjson.NewEncoder(w).Encode(errors.ErrorMsg{\"json decode failed\"})\n\t\t\treturn\n\t\t}\n\n\t\t// Success\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(w).Encode(&person)\n\t}\n\n}", "func getUser(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tparams := mux.Vars(r)\r\n\tresult, err := db.Query(\"SELECT id, name FROM users WHERE id = ?\", params[\"id\"])\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\tdefer result.Close()\r\n\tvar user User\r\n\tfor result.Next() {\r\n\t\terr := result.Scan(&user.Id, &user.Name)\r\n\t\tif err != nil {\r\n\t\t\tpanic(err.Error())\r\n\t\t}\r\n\t}\r\n\tjson.NewEncoder(w).Encode(user)\r\n}", "func SearchUserT(resp http.ResponseWriter, req *http.Request) {\n\tfirstName, ok := req.URL.Query()[\"firstname\"]\n\tif !ok {\n\t\tfmt.Println(\"Url Param 'firstname' is missing\")\n\t}\n\n\tsecondName, ok := req.URL.Query()[\"secondname\"]\n\tif !ok {\n\t\tfmt.Println(\"Url Param 'secondname' is missing\")\n\t}\n\t//fmt.Println(firstName, secondName)\n\n\tusers := model.TarantoolUserSearch(svc.Tarantool, firstName[0], secondName[0])\n\n\tjs, err := json.Marshal(users)\n\tif err != nil {\n\t\tfmt.Println(\"Users marshalling error\")\n\t}\n\n\tresp.Write(js)\n}", "func (h *TestAuth) Login(w http.ResponseWriter, req *http.Request) {\n\n\tresponse := make(map[string]string, 5)\n\n\tresponse[\"state\"] = authz.AuthNewPasswordRequired\n\tresponse[\"access_token\"] = \"access\"\n\t//response[\"id_token\"] = *authResult.IdToken\n\tresponse[\"refresh_token\"] = \"refersh\"\n\tresponse[\"expires\"] = \"3600\"\n\tresponse[\"token_type\"] = \"Bearer\"\n\trespData, _ := json.Marshal(response)\n\tw.WriteHeader(200)\n\tfmt.Fprint(w, string(respData))\n}", "func Get(method, url string, params map[string]string, vPtr interface{}) error {\n\taccount, token, err := LoginWithSelectedAccount()\n\tif err != nil {\n\t\treturn LogError(\"Couldn't get account details or login token\", err)\n\t}\n\turl = fmt.Sprintf(\"%s%s\", account.ServerURL, url)\n\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif token != \"\" {\n\t\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token))\n\t}\n\tq := req.URL.Query()\n\tfor k, v := range params {\n\t\tq.Add(k, v)\n\t}\n\treq.URL.RawQuery = q.Encode()\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer CloseTheCloser(resp.Body)\n\n\tdata, _ := ioutil.ReadAll(resp.Body)\n\n\tif resp.StatusCode != 200 {\n\t\trespBody := map[string]interface{}{}\n\t\tif err := json.Unmarshal(data, &respBody); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = LogError(fmt.Sprintf(\"error while getting service got http status code %s - %s\", resp.Status, respBody[\"error\"]), nil)\n\t\treturn fmt.Errorf(\"received invalid status code (%d)\", resp.StatusCode)\n\t}\n\n\tif err := json.Unmarshal(data, vPtr); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"GET\" {\n\t\takagi := user{\n\t\t\tName: \"Nguyen Hoai Phuong\",\n\t\t\tPassword: \"1234\",\n\t\t}\n\n\t\tbs, err := json.Marshal(akagi)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Encode user error:\", err)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(bs)\n\t} else if r.Method == \"POST\" {\n\t\terr := r.ParseForm()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tuser := r.FormValue(\"username\")\n\t\tpass := r.FormValue(\"password\")\n\t\tfmt.Println(user)\n\t\tfmt.Println(pass)\n\t\thttp.Redirect(w, r, \"/login\", http.StatusOK)\n\t\tfmt.Fprintf(w, \"User name: %s\\nPassword : %s\\n\", user, pass)\n\t}\n\n}", "func getSpecificPersons(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Println(\"Get Specific HIT\")\n\tparams := mux.Vars(r)\n\tresult, err := db.Query(\"SELECT pAge,pName FROM Persons WHERE pAge >= ?\", params[\"age\"])\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tdefer result.Close()\n\tvar pers []Person\n\tfor result.Next() {\n\t\tvar per Person\n\t\terr := result.Scan(&per.Age, &per.Name)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tpers = append(pers, per)\n\t}\n\tjson.NewEncoder(w).Encode(pers)\n}", "func login(selectedAccount *model.Account) (*model.LoginResponse, error) {\n\trequestBody, err := json.Marshal(map[string]string{\n\t\t\"user\": selectedAccount.UserName,\n\t\t\"key\": selectedAccount.Key,\n\t})\n\tif err != nil {\n\t\t_ = LogError(fmt.Sprintf(\"error in login unable to marshal data - %s\", err.Error()), nil)\n\t\treturn nil, err\n\t}\n\n\tresp, err := http.Post(fmt.Sprintf(\"%s/v1/config/login?cli=true\", selectedAccount.ServerURL), \"application/json\", bytes.NewBuffer(requestBody))\n\tif err != nil {\n\t\t_ = LogError(fmt.Sprintf(\"error in login unable to send http request - %s\", err.Error()), nil)\n\t\treturn nil, err\n\t}\n\tdefer CloseTheCloser(resp.Body)\n\n\tloginResp := new(model.LoginResponse)\n\t_ = json.NewDecoder(resp.Body).Decode(loginResp)\n\n\tif resp.StatusCode != 200 {\n\t\t_ = LogError(fmt.Sprintf(\"error in login got http status code %v with error message - %v\", resp.StatusCode, loginResp.Error), nil)\n\t\treturn nil, fmt.Errorf(\"error in login got http status code %v with error message - %v\", resp.StatusCode, loginResp.Error)\n\t}\n\treturn loginResp, err\n}", "func (app *application) getUser(w http.ResponseWriter, r *http.Request) {\n\tid, err := uuid.Parse(r.URL.Query().Get(\":uuid\"))\n\tif err != nil || id == uuid.Nil {\n\t\tapp.notFound(w)\n\t\treturn\n\t}\n\n\tuser, err := app.users.GetByUUID(id)\n\n\tif err == models.ErrNoRecord {\n\t\tapp.notFound(w)\n\t\treturn\n\t} else if err != nil {\n\t\tapp.serverError(w, err)\n\t\treturn\n\t}\n\n\tapp.jsonResponse(w, user)\n}", "func RetrieveMeetings(w http.ResponseWriter, r *http.Request) {\n\n\tw.Header().Set(\"Content-Type\", \"text/javascript\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\tif r.Method != \"POST\" {\n\t\tfmt.Fprintln(w, \"bad request\")\n\t\treturn\n\t}\n\n\tr.ParseForm()\n\tID := r.Form[\"id\"][0]\n\tVC := r.Form[\"vc\"][0]\n\tvar user structs.User\n\tvar temp structs.User\n\tvar crowdsName []string\n\n\tcollection := session.DB(\"bkbfbtpiza46rc3\").C(\"users\")\n\n\tfindErr := collection.FindId(bson.ObjectIdHex(ID)).One(&user)\n\n\tif findErr == mgo.ErrNotFound || VC != user.Vc {\n\t\tfmt.Fprintln(w, \"-1\")\n\t\treturn\n\t}\n\n\tif findErr != nil {\n\t\tfmt.Fprintln(w, \"0\")\n\t\treturn\n\t}\n\n\tfor i, meet := range user.Meetings {\n\n\t\tif len(meet.Crowd) > 0 {\n\n\t\t\tfor _, person := range meet.Crowd {\n\n\t\t\t\tif person != \"\" {\n\t\t\t\t\tfindErr = collection.FindId(bson.ObjectIdHex(person)).One(&temp)\n\t\t\t\t\tif findErr == nil {\n\t\t\t\t\t\tcrowdsName = append(crowdsName, temp.Name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tuser.Meetings[i].Crowd = crowdsName\n\t\tcrowdsName = nil\n\t}\n\n\tb, _ := json.Marshal(user.Meetings)\n\tresp := string(b)\n\n\tfmt.Fprintln(w, resp)\n\treturn\n\n}", "func getUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar user User\n\tparams := mux.Vars(r)\n\tuserID := params[\"id\"]\n\tdb.Find(&user, \"id = ?\", userID)\n\terr := json.NewEncoder(w).Encode(user)\n\tlog.ErrorHandler(err)\n\tlog.AccessHandler(r, 200)\n\treturn\n}", "func (h *Handler) Get(_ context.Context, in *usersapi.GetPayload) (res *usersapi.User, err error) {\n\tfmt.Println(\"xxxxxxxx22222222333333Ali\")\n\tfmt.Printf(\"user isssss %s\\n\", *in.ID)\n\tusr, err := h.provider.Get(*in.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &usersapi.User{Username: usr.Username, Password: usr.Password}, nil\n}", "func (t *OpetCode) retrieveUser(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n\n if len(args) != 1 {\n return shim.Error(\"Incorrect number of arguments. Expecting 1\")\n }\n uid := args[0]\n user_key, _ := APIstub.CreateCompositeKey(uid, []string{USER_KEY})\n user, err := t.loadUser(APIstub, user_key)\n if err != nil {\n return shim.Error(fmt.Sprintf(\"The %s user doesn't not exist\", uid))\n }\n user_json, _ := json.Marshal(user)\n fmt.Printf(\"%s \\n\", user_json)\n return shim.Success(user_json)\n}", "func Get(w http.ResponseWriter, r *http.Request) {\n\tp := Person{\n\t\t\"Jhoana\",\n\t\t31,\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\terr := json.NewEncoder(w).Encode(&p)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}", "func GetPersonas(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tjson.NewEncoder(w).Encode(personas)\n}", "func (server Server) Login(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r) // mux params\n\tusername := vars[\"username\"] // get username\n\tpassword := vars[\"password\"] // get password\n\tvar res models.APIResponse // make a response\n\n\tif username == \"\" || password == \"\" {\n\t\tres = models.BuildAPIResponseFail(\"Bad Request. Empty username or password\", nil)\n\t} else {\n\t\tvar data = checkLogin(username, password, server.db) //create the data\n\t\tres = models.BuildAPIResponseSuccess(\"Login successful\", data)\n\t}\n\tjson.NewEncoder(w).Encode(res) //encode the data\n\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\tPrintln(\"Endpoint Hit: Login\")\n\tvar response struct {\n\t\tStatus bool\n\t\tMessage string\n\t\tData map[string]interface{}\n\t}\n\t// var response models.JwtResponse\n\t//CEK UDAH ADA YANG LOGIN ATAU BELUM\n\t// session := sessions.Start(w, r)\n\t// if len(session.GetString(\"email\")) != 0 && checkErr(w, r, err) {\n\t// \thttp.Redirect(w, r, \"/\", 302)\n\t// }\n\tjwtSignKey := \"notsosecret\"\n\tappName := \"Halovet\"\n\tvar message string\n\n\t//dapetin informasi dari Basic Auth\n\t// email, password, ok := r.BasicAuth()\n\t// if !ok {\n\t// \tmessage = \"Invalid email or password\"\n\t// \tw.Header().Set(\"Content-Type\", \"application/json\")\n\t// \tw.WriteHeader(200)\n\t// \tresponse.Status = false\n\t// \tresponse.Message = message\n\t// \tjson.NewEncoder(w).Encode(response)\n\t// \treturn\n\t// }\n\t//dapetin informasi dari form\n\temail := r.FormValue(\"email\")\n\tif _, status := ValidateEmail(email); status != true {\n\t\tmessage := \"Format Email Salah atau Kosong\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\tpassword := r.FormValue(\"password\")\n\tif _, status := ValidatePassword(password); status != true {\n\t\tmessage := \"Format Password Salah atau Kosong, Minimal 6 Karakter\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\tok, userInfo := mid.AuthenticateUser(email, password)\n\tif !ok {\n\t\tmessage = \"Invalid email or password\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\tclaims := models.TheClaims{\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tIssuer: appName,\n\t\t\tExpiresAt: time.Now().Add(LoginExpDuration).Unix(),\n\t\t},\n\t\tUser: userInfo,\n\t}\n\n\ttoken := jwt.NewWithClaims(\n\t\tJwtSigningMethod,\n\t\tclaims,\n\t)\n\n\tsignedToken, err := token.SignedString([]byte(jwtSignKey))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\t//tokennya dijadiin json\n\t// tokenString, _ := json.Marshal(M{ \"token\": signedToken })\n\t// w.Write([]byte(tokenString))\n\tdata := map[string]interface{}{\n\t\t\"jwtToken\": signedToken,\n\t\t\"user\": userInfo,\n\t}\n\n\t//RESPON JSON\n\tmessage = \"Login Succesfully\"\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tresponse.Status = true\n\tresponse.Message = message\n\tresponse.Data = data\n\tjson.NewEncoder(w).Encode(response)\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: \"token\",\n\t\tValue: signedToken,\n\t\tExpires: time.Now().Add(LoginExpDuration),\n\t})\n}", "func GetJSON(u string) UserResponse {\n\turl := fmt.Sprintf(\"%s/%s\", GITHUB_ENDPOINT, u)\n\tresp, _ := http.Get(url)\n\n\tdefer resp.Body.Close()\n\n\tb, e := ioutil.ReadAll(resp.Body)\n\n\tif e != nil {\n\t\tfmt.Println(\"Error2\", resp.Body)\n\t}\n\ti := &UserResponse{}\n\te = json.Unmarshal(b, i)\n\treturn *i\n\n}", "func Login(w http.ResponseWriter, req *http.Request) {\n\tvar loginValidator LoginValidator\n\tvar response shared.Response\n\n\t_ = json.NewDecoder(req.Body).Decode(&loginValidator)\n\n\tresponseLogin := LoginService(loginValidator)\n\tresponse.Status = shared.StatusSuccess\n\tresponse.Data = responseLogin\n\tjson.NewEncoder(w).Encode(response)\n}", "func GetUser(w http.ResponseWriter, r *http.Request) {\n\n\thttpext.SuccessAPI(w, \"ok\")\n}", "func UsersLoginGet(c buffalo.Context) error {\n\treturn c.Render(200, r.HTML(\"users/login\"))\n}", "func GetUser(params martini.Params, render render.Render, account services.Account) {\n userID := params[\"id\"]\n if user, err := account.GetUser(userID); err != nil {\n render.JSON(err.HttpCode, err)\n } else {\n render.JSON(http.StatusOK, user)\n }\n}", "func GetPerson(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tfor _, item := range people {\n\t\tif item.ID == params[\"id\"] {\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tjson.NewEncoder(w).Encode(&model.Person{})\n\t//r = mux.Vars(r)\n}", "func Get(w http.ResponseWriter, r *http.Request) error {\r\n\r\n\tdentistID, err := c.ExtractJwtClaim(r, \"dentistId\")\r\n\tif err != nil {\r\n\t\t//user is not logged in\r\n\t\toutput, _ := json.Marshal(m.Dentist{})\r\n\t\tfmt.Fprintf(w, string(output))\r\n\r\n\t\treturn nil\r\n\t}\r\n\r\n\tdentist, err := repo.GetDentist(dentistID)\r\n\r\n\tswitch {\r\n\tcase err == sql.ErrNoRows:\r\n\t\thttp.Error(w, \"No such user!\", http.StatusNotFound)\r\n\tcase err != nil:\r\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\r\n\tdefault:\r\n\t\toutput, _ := json.Marshal(dentist)\r\n\t\tfmt.Fprintf(w, string(output))\r\n\t}\r\n\r\n\treturn nil\r\n}", "func login(cfg *OktaConfig, user, pass string) (*OktaLoginResponse, error) {\n\tdebugOkta(\"let the login dance begin\")\n\n\tpr, err := http.NewRequest(\n\t\thttp.MethodPost,\n\t\tfmt.Sprintf(\n\t\t\t// TODO: run some checks on this URL\n\t\t\t\"%sapi/v1/authn\",\n\t\t\tcfg.BaseURL,\n\t\t),\n\t\tgetOktaLoginBody(cfg, user, pass),\n\t)\n\n\tif err != nil {\n\t\tdebugOkta(\"caught an error building the first request to okta\")\n\t\treturn nil, err\n\t}\n\n\tajs := \"application/json\"\n\tpr.Header.Set(\"Content-Type\", ajs)\n\tpr.Header.Set(\"Accept\", ajs)\n\n\tres, err := http.DefaultClient.Do(pr)\n\tif err != nil {\n\t\tdebugOkta(\"caught error on first request to okta\")\n\t\treturn nil, err\n\t}\n\n\tif res.StatusCode != http.StatusOK {\n\t\treturn nil, loginFailedError\n\t}\n\n\tdefer res.Body.Close()\n\tb, err := ioutil.ReadAll(res.Body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdebugOkta(\"login response body %s\", string(b))\n\n\tvar ores OktaLoginResponse\n\terr = json.Unmarshal(b, &ores)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ores, nil\n}", "func LoginRouter(Request *http.Request) ([]byte, map[string]string) {\n\tvar loginjson LoginJSON\n HeaderValues := make(map[string]string)\n authorization := Request.Header.Get(\"Authorization\")\n\tfmt.Println(\"Authorization header : \", authorization)\n\n\t//Check if authorization code is stored in the session table\n\t//If authorization code is already existing, return saying \"already logged in\"\n\t//loggedin := VerifyAuthorizationCode(authorization)\n\t//if loggedin == true {\n\t\t//Return\n\t//\treturn []byte(\"hello great job\"), nil\n\t//}\n\tbody, err := ioutil.ReadAll(Request.Body)\n\tfmt.Println(string(body))\n\tif err != nil {\n\t\t//send error json for login\n\t\treturn nil, nil\n\t}\n\tfmt.Println(body)\n\terr = json.Unmarshal(body, &loginjson)\n\tfmt.Println(\"Login Structure: \")\n\tfmt.Println(loginjson)\n\tif err != nil {\n\t\t//send error json for login\n\t\tfmt.Println(\"Error while unmarshing the json from the client...returning.\")\n\t\treturn nil, nil\n\t}\n\n\tif loginjson.Request_type == cfg.LOGIN_MOBILE_NUMBER {\n\t\tif loginjson.Mobile_number != \"\" {\n\t\t\tfmt.Println(loginjson.Mobile_number)\n\n\t\t\tresp := VerifyuserIDAndGenerateOTP(loginjson)\n\t\t\tHeaderValues[\"Content-type\"] = \"application/json\"\n\t\t\treturn resp, HeaderValues\n\t\t} else {\n\t\t\treturn nil, nil\n\t\t}\n\t} else if loginjson.Request_type == cfg.LOGIN_OTP_NUMBER {\n\t\tfmt.Println(loginjson.OTP_number)\n\t\totpresp := VerifyuserIDotpsessionidAndLogin(loginjson)\n HeaderValues[\"Content-type\"] = \"application/json\"\n\n\t\treturn []byte(otpresp), HeaderValues\n\t} else {\n\t\tfmt.Println(\"No request type has been mentioned..\")\n\t\treturn nil, nil\n\t}\n\treturn nil, nil\n}", "func GetLoginFunc(db *sqlx.DB) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tusername := \"\"\n\t\tpassword := \"\"\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error reading body: \", err.Error())\n\t\t\thttp.Error(w, \"Error reading body: \"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tvar lj loginJson\n\t\tlog.Println(body)\n\t\terr = json.Unmarshal(body, &lj)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error unmarshalling JSON: \", err.Error())\n\t\t\thttp.Error(w, \"Invalid JSON: \"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tusername = lj.U\n\t\tpassword = lj.P\n\t\tuserInterface, err := api.GetUser(username, db)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Invalid user: \"+err.Error(), http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tu, ok := userInterface.(api.Users)\n\t\tif !ok {\n\t\t\thttp.Error(w, \"Error GetUser returned a non-user.\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tencBytes := sha1.Sum([]byte(password))\n\t\tencString := hex.EncodeToString(encBytes[:])\n\t\tif err != nil {\n\t\t\tctx.Set(r, \"user\", nil)\n\t\t\tlog.Println(\"Invalid password\")\n\t\t\thttp.Error(w, \"Invalid password: \"+err.Error(), http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tif u.LocalPassword.String != encString {\n\t\t\tctx.Set(r, \"user\", nil)\n\t\t\tlog.Println(\"Invalid password\")\n\t\t\thttp.Error(w, \"Invalid password\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\t// Create the token\n\t\ttoken := jwt.New(jwt.SigningMethodHS256)\n\t\t// Set some claims\n\t\ttoken.Claims[\"userid\"] = u.Username\n\t\ttoken.Claims[\"role\"] = u.Links.RolesLink.ID\n\t\ttoken.Claims[\"exp\"] = time.Now().Add(time.Hour * 72).Unix()\n\t\t// Sign and get the complete encoded token as a string\n\t\ttokenString, err := token.SignedString([]byte(\"mySigningKey\")) // TODO JvD\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tjs, err := json.Marshal(TokenResponse{Token: tokenString})\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(js)\n\t}\n}", "func GetEmployee(w http.ResponseWriter, r *http.Request) {\r\n\tcookie, err := r.Cookie(\"token\")\r\n\tif err != nil {\r\n\t\tif err == http.ErrNoCookie {\r\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\r\n\t\t\treturn\r\n\t\t}\r\n\t\tw.WriteHeader(http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\ttokenStr := cookie.Value\r\n\r\n\tclaims := &Claims{}\r\n\r\n\ttkn, err := jwt.ParseWithClaims(tokenStr, claims,\r\n\t\tfunc(t *jwt.Token) (interface{}, error) {\r\n\t\t\treturn jwtKey, nil\r\n\t\t})\r\n\r\n\tif err != nil {\r\n\t\tif err == jwt.ErrSignatureInvalid {\r\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\r\n\t\t\treturn\r\n\t\t}\r\n\t\tw.WriteHeader(http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\tif !tkn.Valid {\r\n\t\tw.WriteHeader(http.StatusUnauthorized)\r\n\t\treturn\r\n\t}\r\n\r\n\tdb := createConnection()\r\n\r\n\tparams := mux.Vars(r)\r\n\tst := `select * from employee where id = $1`\r\n\r\n\trow, _ := db.Query(st, params[\"id\"])\r\n\tvar emp models.Employee\r\n\tfor row.Next() {\r\n\t\trow.Scan(&emp.ID, &emp.EmpName, &emp.EmpPRO)\r\n\t}\r\n\tdefer row.Close()\r\n\tjson.NewEncoder(w).Encode(emp)\r\n}", "func GetDetails(w http.ResponseWriter, r *http.Request) {\n\tvar ac Account\n\taccountName := r.URL.Query().Get(\"name\")\n\t(&ac).GetAccount(accountName)\n\tres, _ := json.Marshal(ac)\n\tfmt.Fprintf(w, string(res))\n}", "func EndpointPOSTLogin(w http.ResponseWriter, r *http.Request) {\n\t// Write the HTTP header for the response\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\n\t// Create the actual data response structs of the API call\n\ttype GenericData struct {\n\t\tToken string `json:\"token,omitempty\"`\n\t}\n\n\ttype ReturnData struct {\n\t\tSuccess Success\n\t\tData GenericData\n\t}\n\n\t// Create the response structs\n\tvar success = Success{Success: true, Error: \"\"}\n\tvar data GenericData\n\tvar returnData ReturnData\n\n\t// Process the API call\n\tfbAccessToken := r.FormValue(\"fb_access_token\")\n\n\tif fbAccessToken == \"\" {\n\t\tsuccess.Success = false\n\t\tsuccess.Error = \"Invalid API call. 'fb_access_token' paramater is required.\"\n\t} else {\n\t\tvar m bson.M\n\n\t\t// Try to get the User from Facebook\n\t\tif res, err := fb.Get((\"/me\"), fb.Params{\n\t\t\t\"fields\": []string{\"id\", \"name\", \"picture.width(640)\"},\n\t\t\t\"access_token\": r.FormValue(\"fb_access_token\"),\n\t\t}); err != nil {\n\t\t\tsuccess.Success = false\n\t\t\tsuccess.Error = \"Invalid `fb_access_token` provided to API call.\"\n\t\t} else {\n\t\t\t// Get the scoped Facebook User ID provided by Facebook itself\n\t\t\tfbUserID := -1\n\t\t\tif str, ok := res[\"id\"].(string); ok {\n\t\t\t\tif val, err := strconv.Atoi(str); err == nil {\n\t\t\t\t\tfbUserID = val\n\t\t\t\t}\n\t\t\t}\n\t\t\tif fbUserID == -1 {\n\t\t\t\tsuccess.Success = false\n\t\t\t\tsuccess.Error = \"Could not retrieve scoped Facebook User ID from Facebook.\"\n\t\t\t} else {\n\t\t\t\t// Attempt to get User from the database\n\t\t\t\tc := gDatabase.db.DB(dbDB).C(\"fb_links\")\n\t\t\t\tif err := c.Find(bson.M{\"fb_user_id\": fbUserID}).One(&m); err != nil { // If the User is not linked in our database\n\t\t\t\t\t// Calculate age based on birthday\n\t\t\t\t\t// (NOTE: This is rough...Facebook can only be gauranteed\n\t\t\t\t\t// to give us the year.)\n\t\t\t\t\t// (NOTE: Skip this for now. Getting a user's birthday from\n\t\t\t\t\t// Facebook requires app review.)\n\t\t\t\t\tage := 18\n\t\t\t\t\t/*if str, ok := res[\"birthday\"].(string); ok {\n\t\t\t\t\t\tslashIndex := strings.Index(str, \"/\")\n\t\t\t\t\t\tif slashIndex > -1 {\n\t\t\t\t\t\t\tstr = str[(slashIndex + 1):]\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbirthdayNumber, _ := strconv.Atoi(str)\n\t\t\t\t\t\tage = (time.Now().Year() - birthdayNumber)\n\t\t\t\t\t}*/\n\n\t\t\t\t\t// Figure out what this User's ID will be\n\t\t\t\t\tc := gDatabase.db.DB(dbDB).C(\"users\")\n\t\t\t\t\tcount, _ := c.Count()\n\n\t\t\t\t\t// Get name\n\t\t\t\t\tname := \"\"\n\t\t\t\t\tif str, ok := res[\"name\"].(string); ok {\n\t\t\t\t\t\tname = str\n\t\t\t\t\t}\n\n\t\t\t\t\t// Get profile picture URL\n\t\t\t\t\tprofilePictures := []string{}\n\t\t\t\t\tif pictureObject, ok := res[\"picture\"].(map[string]interface{}); ok {\n\t\t\t\t\t\tif dataObject, ok := pictureObject[\"data\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\tif str, ok := dataObject[\"url\"].(string); ok {\n\t\t\t\t\t\t\t\tprofilePictures = append(profilePictures, str)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Create the new User object\n\t\t\t\t\tuser := User{\n\t\t\t\t\t\tID: count,\n\t\t\t\t\t\tName: name,\n\t\t\t\t\t\tAge: age,\n\t\t\t\t\t\tInterests: map[string]int{},\n\t\t\t\t\t\tTags: []string{},\n\t\t\t\t\t\tBio: \"\",\n\t\t\t\t\t\tImages: profilePictures,\n\t\t\t\t\t\tMatches: []Match{},\n\t\t\t\t\t\tLatitude: 0,\n\t\t\t\t\t\tLongitude: 0,\n\t\t\t\t\t\tLastActive: time.Now().String(),\n\t\t\t\t\t\tShareLocation: true,\n\t\t\t\t\t}\n\n\t\t\t\t\t// Insert the User into the database\n\t\t\t\t\tc.Insert(user)\n\n\t\t\t\t\t// Insert the Facebook link for the user into the database\n\t\t\t\t\tc = gDatabase.db.DB(dbDB).C(\"fb_links\")\n\t\t\t\t\tc.Insert(bson.M{\"user_id\": user.ID, \"fb_user_id\": fbUserID, \"fb_access_token\": r.FormValue(\"fb_access_token\")})\n\n\t\t\t\t\t// Create the new Session for the user and return their new API\n\t\t\t\t\t// access token\n\t\t\t\t\tsession, _ := gSessionCache.CreateSession(user.ID)\n\t\t\t\t\tdata.Token = session.Token\n\t\t\t\t} else { // Otherwise, if the User is linked in our database\n\t\t\t\t\t// Update the Facebook Link's access token in the database\n\t\t\t\t\t// (NOTE: We are assuming, at this point, potentially\n\t\t\t\t\t// dangerously, that the User definitely has a valid Facebook\n\t\t\t\t\t// link with the provided Facebook User ID in the database.)\n\t\t\t\t\tc := gDatabase.db.DB(dbDB).C(\"fb_links\")\n\t\t\t\t\tquery := bson.M{\"fb_user_id\": fbUserID}\n\t\t\t\t\tchange := bson.M{\"$set\": bson.M{\"fb_access_token\": r.FormValue(\"fb_access_token\")}}\n\t\t\t\t\t_ = c.Update(query, change)\n\n\t\t\t\t\t// Create the new Session for the user and return their new API\n\t\t\t\t\t// access token\n\t\t\t\t\tsession, _ := gSessionCache.CreateSession(m[\"user_id\"].(int))\n\t\t\t\t\tdata.Token = session.Token\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Combine the success and data structs so that they can be returned\n\treturnData.Success = success\n\treturnData.Data = data\n\n\t// Respond with the JSON-encoded return data\n\tif err := json.NewEncoder(w).Encode(returnData); err != nil {\n\t\tpanic(err)\n\t}\n}", "func UserListAll(w http.ResponseWriter, r *http.Request) {\n\n\tvar err error\n\tvar pageSize int\n\tvar paginatedUsers auth.PaginatedUsers\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\trefRoles := gorillaContext.Get(r, \"auth_roles\").([]string)\n\n\t// Grab url path variables\n\turlValues := r.URL.Query()\n\tpageToken := urlValues.Get(\"pageToken\")\n\tstrPageSize := urlValues.Get(\"pageSize\")\n\tprojectName := urlValues.Get(\"project\")\n\tprojectUUID := \"\"\n\n\tif projectName != \"\" {\n\t\tprojectUUID = projects.GetUUIDByName(projectName, refStr)\n\t\tif projectUUID == \"\" {\n\t\t\terr := APIErrorNotFound(\"ProjectUUID\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif strPageSize != \"\" {\n\t\tif pageSize, err = strconv.Atoi(strPageSize); err != nil {\n\t\t\tlog.Errorf(\"Pagesize %v produced an error while being converted to int: %v\", strPageSize, err.Error())\n\t\t\terr := APIErrorInvalidData(\"Invalid page size\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// check that user is indeed a service admin in order to be priviledged to see full user info\n\tpriviledged := auth.IsServiceAdmin(refRoles)\n\n\t// Get Results Object - call is always priviledged because this handler is only accessible by service admins\n\tif paginatedUsers, err = auth.PaginatedFindUsers(pageToken, int32(pageSize), projectUUID, priviledged, refStr); err != nil {\n\t\terr := APIErrorInvalidData(\"Invalid page token\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := paginatedUsers.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func Get(c *gin.Context) {\n\t//Get the id from the GET request\n\tuserID, idErr := getUserID(c.Param(\"user_id\"))\n\tif idErr != nil {\n\t\tc.JSON(idErr.Status, idErr)\n\t\treturn\n\t}\n\n\tresult, getErr := services.UsersService.GetUser(userID)\n\tif getErr != nil {\n\t\tc.JSON(getErr.Status, getErr)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, result.Marshal(c.GetHeader(\"X-Public\") == \"true\"))\n}", "func TokenGet(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-type\", \"application/json;charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tvar a auth\n\n\terr = json.Unmarshal(body, &a)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\t// Verify that the user exists in database\n\tuser := repositories.UserGetByUsername(a.Username)\n\n\tif user.ID == 0 {\n\t\tjson.NewEncoder(w).Encode(models.JSONError{Message: \"User Not Found\", Code: 404})\n\t} else {\n\t\tcompare := compareHashPassword(user.Password, a.Password)\n\t\tif compare {\n\t\t\tjwtToken := jwt.New(jwt.SigningMethodHS256)\n\t\t\tclaims := jwtToken.Claims.(jwt.MapClaims)\n\n\t\t\tclaims[\"username\"] = user.Username\n\t\t\tclaims[\"role\"] = user.RoleID\n\t\t\tclaims[\"exp\"] = time.Now().Add(time.Hour * 24).Unix()\n\n\t\t\ttokenString, errSign := jwtToken.SignedString(JwtSalt)\n\t\t\tif errSign != nil {\n\t\t\t\tlog.Info(err)\n\t\t\t}\n\t\t\tjson.NewEncoder(w).Encode(token{Token: tokenString})\n\t\t} else {\n\t\t\tjson.NewEncoder(w).Encode(models.JSONError{Message: \"Your login / Password is wrong\", Code: 403})\n\t\t}\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\r\n\tlogin := strings.Trim(r.FormValue(\"login\"), \" \")\r\n\tpass := strings.Trim(r.FormValue(\"pass\"), \" \")\r\n\tlog.Println(\"login: \", login, \" pass: \", pass)\r\n\r\n\t// Check params\r\n\tif login == \"\" || pass == \"\" {\r\n\t\twriteResponse(w, \"Login and password required\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\t// Already authorized\r\n\tif savedPass, OK := Auth[login]; OK && savedPass == pass {\r\n\t\twriteResponse(w, \"You are already authorized\\n\", http.StatusOK)\r\n\t\treturn\r\n\t} else if OK && savedPass != pass {\r\n\t\t// it is not neccessary\r\n\t\twriteResponse(w, \"Wrong pass\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\tuser := model.User{}\r\n\terr := user.Get(login, pass)\r\n\tif err == nil {\r\n\t\tAuth[login], Work[login] = pass, user.WorkNumber\r\n\t\twriteResponse(w, \"Succesfull authorization\\n\", http.StatusOK)\r\n\t\treturn\r\n\t}\r\n\r\n\twriteResponse(w, \"User with same login not found\\n\", http.StatusNotFound)\r\n}", "func LoginHandler(dbase *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tvar user *db.Psychologist\n\tvar resp map[string]interface{}\n\tvar err error\n\n\terr = json.NewDecoder(r.Body).Decode(&user)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\terrorResponse := utils.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: fmt.Sprintln(\"An error occurred while processing your request\"),\n\t\t}\n\t\tlog.Println(json.NewEncoder(w).Encode(errorResponse))\n\t\treturn\n\t}\n\n\tresp, err = FindOne(dbase, user.Email, user.Password)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tlog.Println(json.NewEncoder(w).Encode(utils.ErrorResponse{\n\t\t\tCode: http.StatusNotFound,\n\t\t\tMessage: err.Error(),\n\t\t}))\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tlog.Println(json.NewEncoder(w).Encode(resp))\n}", "func login(auth authetication.Service) http.HandlerFunc {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\t\temail := r.PostFormValue(\"email\")\n\t\tpassword := r.PostFormValue(\"password\")\n\t\ttoken, err := auth.Login(r.Context(), email, password)\n\n\t\trw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\tif err != nil {\n\t\t\tvar jsonErr error\n\t\t\tif errors.Is(err, authetication.ErrInvalidEmail) {\n\t\t\t\terrorRes := constructErrorWithField(http.StatusConflict,\n\t\t\t\t\t\"email\",\n\t\t\t\t\t\"invalid email address\",\n\t\t\t\t\t\"Enter a proper email address\")\n\t\t\t\trw.WriteHeader(http.StatusConflict)\n\t\t\t\tjsonErr = json.NewEncoder(rw).Encode(errorRes)\n\t\t\t\treturn\n\n\t\t\t} else if errors.Is(err, authetication.ErrPasswordLengthUnAcceptable) {\n\t\t\t\terrorRes := constructErrorWithField(http.StatusConflict,\n\t\t\t\t\t\"password\",\n\t\t\t\t\t\"password is unacceptable\",\n\t\t\t\t\t\"Password length is either too short or too long\")\n\t\t\t\trw.WriteHeader(http.StatusConflict)\n\t\t\t\tjsonErr = json.NewEncoder(rw).Encode(errorRes)\n\t\t\t\treturn\n\n\t\t\t} else if errors.Is(err, authetication.ErrIdentityDoesNotExists) {\n\t\t\t\terrorRes := constructError(http.StatusConflict,\n\t\t\t\t\t\"identity does not exists\",\n\t\t\t\t\t\"Email or password is not correct\",\n\t\t\t\t)\n\t\t\t\trw.WriteHeader(http.StatusConflict)\n\t\t\t\tjsonErr = json.NewEncoder(rw).Encode(errorRes)\n\t\t\t\treturn\n\n\t\t\t} else if errors.Is(err, authetication.ErrUnableToProcessRequest) {\n\t\t\t\terrorRes := constructError(http.StatusInternalServerError,\n\t\t\t\t\t\"unable to process request\",\n\t\t\t\t\t\"There was problem in processing your request\")\n\t\t\t\tjsonErr = json.NewEncoder(rw).Encode(errorRes)\n\t\t\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif jsonErr != nil {\n\t\t\t\tlog.Println(jsonErr)\n\t\t\t}\n\t\t\treturn\n\n\t\t}\n\t\tjson.NewEncoder(rw).Encode(token)\n\n\t}\n}", "func signInApi(w http.ResponseWriter, r *http.Request) {\n\tvar newUserLogin userLogin\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Fprint(w, \"Parameter for login invalids\")\n\t}\n\tjson.Unmarshal(reqBody, &newUserLogin)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tgetTime(\"POST to: /api/signin\")\n\tsignInDB(newUserLogin.UserName, newUserLogin.Password)\n\tjson.NewEncoder(w).Encode(userList) // Responder al servidor\n}", "func (a *DefaultApiService) Me(ctx context.Context) (User, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t \tsuccessPayload User\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/me\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json; charset=utf-8\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarQueryParams.Add(\"circle-token\", key)\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn successPayload, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn successPayload, localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\tif err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\n\n\treturn successPayload, localVarHttpResponse, err\n}", "func IGLogin(w http.ResponseWriter, r *http.Request, user *IGAuthCred) bool {\n\tif r.FormValue(\"code\") == \"\" {\n\t\tlog.Print(\"Code was not recieved\")\n\t\treturn false\n\t}\n\tapiURL := IG_API_URL\n\tresource := \"/oauth/access_token\"\n\tdata := url.Values{}\n\tdata.Add(\"code\", r.FormValue(\"code\"))\n\tdata.Add(\"redirect_uri\", REDIRECT_URL)\n\tdata.Add(\"grant_type\", \"authorization_code\")\n\tdata.Add(\"client_secret\", CLIENT_SECRET)\n\tdata.Add(\"client_id\", CLIENT_ID)\n\n\tu, _ := url.ParseRequestURI(apiURL)\n\tu.Path = resource\n\turlStr := u.String()\n\n\tclient := &http.Client{}\n\tr, err := http.NewRequest(\"POST\", urlStr, strings.NewReader(data.Encode()))\n\n\tif err != nil {\n\t\tlog.Print(\"Eorror creating the POST request : \", err)\n\t\treturn false\n\t}\n\n\tr.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\tresp, err := client.Do(r)\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tlog.Print(\"Error reading the body\", err)\n\t\treturn false\n\t}\n\n\terr = json.Unmarshal(b, &user)\n\n\tif err != nil {\n\t\tlog.Print(\"Error unmarshalling the reponse\", err)\n\t\treturn false\n\t}\n\n\terr = resp.Body.Close()\n\n\tif err != nil {\n\t\tlog.Print(\"Cannot close the body\", err)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func getUser(c *fiber.Ctx) error {\n\tUserscollection := mg.Db.Collection(\"users\")\n\tListscollection := mg.Db.Collection(\"lists\")\n\tusername := c.Params(\"name\")\n\tuserQuery := bson.D{{Key: \"username\", Value: username}}\n\n\tuserRecord := Userscollection.FindOne(c.Context(), &userQuery)\n\tuser := &User{}\n\tuserRecord.Decode(&user)\n\tif len(user.ID) < 1 {\n\t\treturn c.Status(404).SendString(\"cant find user\")\n\t}\n\tlistQuery := bson.D{{Key: \"userid\", Value: user.Username}}\n\tcursor, err := Listscollection.Find(c.Context(), &listQuery)\n\tif err != nil {\n\t\treturn c.Status(500).SendString(err.Error())\n\t}\n\tvar lists []List = make([]List, 0)\n\tif err := cursor.All(c.Context(), &lists); err != nil {\n\t\treturn c.Status(500).SendString(\"internal err\")\n\t}\n\tuser.Password = \"\"\n\tuser.TaskCode = \"\"\n\treturn c.Status(200).JSON(&fiber.Map{\n\t\t\"user\": user,\n\t\t\"lists\": lists,\n\t})\n}", "func GetPersonEndpoint(w http.ResponseWriter, req *http.Request) {\n\tparams := mux.Vars(req)\n\tfor _, item := range people {\n\t\tif item.ID == params[\"id\"] {\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(&Person{})\n}", "func login(ctx context.Context) error {\n\tr := ctx.HttpRequest()\n\trw := ctx.HttpResponseWriter()\n\tsession, _ := core.GetSession(r)\n\n\temail := ctx.PostValue(\"email\")\n\tpassword := ctx.PostValue(\"password\")\n\tuser, err := db.Login(email, password)\n\tif err != nil {\n\t\tmsg := struct {\n\t\t\tBody string `json:\"body\"`\n\t\t\tType string `json:\"type\"`\n\t\t}{\n\t\t\tBody: err.Error(),\n\t\t\tType: \"alert\",\n\t\t}\n\t\tdata, err := json.Marshal(msg)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Unable to marshal: \", err)\n\t\t\treturn goweb.Respond.WithStatus(ctx, http.StatusInternalServerError)\n\t\t}\n\t\trw.Header().Set(\"Content-Type\", \"application/json\")\n\t\treturn goweb.Respond.With(ctx, http.StatusUnauthorized, data)\n\t}\n\n\tsession.Values[\"user\"] = user\n\tif err = session.Save(r, rw); err != nil {\n\t\tlog.Error(\"Unable to save session: \", err)\n\t}\n\tuserInfo := struct {\n\t\tSessionID string `json:\"sessionid\"`\n\t\tId string `json:\"id\"`\n\t\tName string `json:\"name\"`\n\t\tEmail string `json:\"email\"`\n\t\tApiToken string `json:\"apitoken\"`\n\t}{\n\t\tSessionID: session.ID,\n\t\tId: user.Id.Hex(),\n\t\tName: user.Name,\n\t\tEmail: user.Email,\n\t\tApiToken: user.Person.ApiToken,\n\t}\n\tdata, err := json.Marshal(userInfo)\n\tif err != nil {\n\t\tlog.Error(\"Unable to marshal: \", err)\n\t\treturn goweb.Respond.WithStatus(ctx, http.StatusInternalServerError)\n\t}\n\trw.Header().Set(\"Content-Type\", \"application/json\")\n\treturn goweb.Respond.With(ctx, http.StatusOK, data)\n}", "func Search(c *gin.Context) {\n\tstatus := c.Query(\"status\")\n\n\tusers, err := services.UserServ.SearchUser(status)\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\tisPublic := c.GetHeader(\"X-Public\") == \"true\"\n\tc.JSON(http.StatusOK, users.Marshall(isPublic))\n}", "func GetAuth(user, password, request_type, endpoint, body string) (map[string]interface{}, *http.Response) {\n\t\thttp.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t\tclient := &http.Client{}\n\t\tdata := []byte(body)\n redfish_ep := strings.Replace(endpoint, \"redfish\", \"https\", 1)\n req, err := http.NewRequest(request_type, redfish_ep, bytes.NewBuffer(data))\n\t\treq.SetBasicAuth(user, password)\n\t\treq.Header.Add(\"Content-Type\", \"application/json\")\n\t\treq.Header.Set(\"Accept\", \"application/json\")\n\t\tresp, err := client.Do(req)\n\t\tresp_json := make(map[string]interface{})\n\t\tif err != nil{\n\t fmt.Printf(\"The HTTP request failed with error %s\\n\", err)\n\t } else {\n\t \t\tbodyText, err := ioutil.ReadAll(resp.Body)\n\t\t// defer resp.Body.Close()\n\t\tif err != nil{\n\t \t\tfmt.Printf(\"The HTTP request failed with error %s\\n\", err)\n\t }\n\t\ts := []byte(bodyText)\n\t\tjson.Unmarshal(s, &resp_json)\n}\n\t\tdefer resp.Body.Close()\n\t\treturn resp_json, resp\n}", "func Login(c *soso.Context) {\n\treq := c.RequestMap\n\trequest := &auth_protocol.LoginRequest{}\n\n\tif value, ok := req[\"phone\"].(string); ok {\n\t\trequest.PhoneNumber = value\n\t}\n\n\tif value, ok := req[\"password\"].(string); ok {\n\t\trequest.Password = value\n\t}\n\n\tif request.Password == \"\" || request.PhoneNumber == \"\" {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"Phone number and password is required\"))\n\t\treturn\n\t}\n\tctx, cancel := rpc.DefaultContext()\n\tdefer cancel()\n\tresp, err := authClient.Login(ctx, request)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tif resp.ErrorCode != 0 {\n\t\tc.Response.ResponseMap = map[string]interface{}{\n\t\t\t\"ErrorCode\": resp.ErrorCode,\n\t\t\t\"ErrorMessage\": resp.ErrorMessage,\n\t\t}\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(resp.ErrorMessage))\n\t\treturn\n\t}\n\n\ttokenData, err := auth.GetTokenData(resp.Token)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tuser, err := GetUser(tokenData.UID, true)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tc.SuccessResponse(map[string]interface{}{\n\t\t\"token\": resp.Token,\n\t\t\"user\": user,\n\t})\n}", "func (c *InfoController) GetOne() {\n\ttoken := c.Ctx.Input.Param(\":token\")\n\tvar resp utils.SimpleResponse\n\tv := services.QueryIdentity(token, true)\n\tif v != nil {\n\t\tresp.Success = true\n\t\tresp.Message = v\n\t} else {\n\t\tresp.Success = false\n\t\tresp.Message = utils.Msg.TokenErr\n\t}\n\tc.Data[\"json\"] = resp\n\tc.ServeJSON()\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tdata := authInfo{}\n\terr := json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\tutils.JSONRespnseWithErr(w, &utils.ErrPostDataNotCorrect)\n\t\treturn\n\t}\n\tmessage := models.Login(data.Email, data.Password)\n\tutils.JSONResonseWithMessage(w, message)\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\t// establecemos que el tipo de contenido que tendrá el header es json\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\tvar t models.Usuario\n\n\t//carga los datos de email y password en la varialbe t\n\terr := json.NewDecoder(r.Body).Decode(&t)\n\tif err != nil {\n\t\thttp.Error(w, \"Usuario y/o Contraseña invalidos \"+err.Error(), 400)\n\t\treturn\n\t}\n\tif len(t.Email) == 0 {\n\t\thttp.Error(w, \"El email del usuario es requerido \", 400)\n\t\treturn\n\t}\n\tdocumento, existe := bd.IntentoLogin(t.Email, t.Password)\n\tif !existe {\n\t\thttp.Error(w, \"Usuario y/o Contraseña invalidos \", 400)\n\t\treturn\n\t}\n\n\tjwtKey, err := jwt.GeneroJWT(documento)\n\tif err != nil {\n\t\thttp.Error(w, \"Ocurrió un error al intentar generar el Token correspondiente \"+err.Error(), 400)\n\t\treturn\n\t}\n\n\tresp := models.RespuestaLogin{\n\t\tToken: jwtKey,\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated)\n\terr = json.NewEncoder(w).Encode(resp)\n\tif err != nil {\n\t\thttp.Error(w, \"Ocurrió un error al intentar codificar el token en un nuevo json \"+err.Error(), 400)\n\t\treturn\n\t}\n\n\t// metodo para gravar token en la cookie del usuario\n\texpirationTime := time.Now().Add(24 * time.Hour)\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: \"token\",\n\t\tValue: jwtKey,\n\t\tExpires: expirationTime,\n\t})\n\t// ->./jwt/jwt.go\n}", "func (jar *JsonApiUrl) Get(v interface{}) {\n\tvar res *http.Response\n\tvar body[]byte\n\n\t// retrieve json of the migrated entity from the jsonapi and unmarshal the single response\n\tif len(strings.TrimSpace(jar.Username)) == 0 {\n\t\tres, body = GetResource(jar.T.(*testing.T), jar.String())\n\t} else {\n\t\tres, body = GetResourceWithBasicAuth(jar.T.(*testing.T), jar.String(), jar.Username, jar.Password)\n\t}\n\tdefer func() { _ = res.Close }()\n\tUnmarshalResponse(jar.T.(*testing.T), body, res, &JsonApiResponse{}, nil).To(v)\n}", "func CheckinPeopleGET(w http.ResponseWriter, r *http.Request) {\n\tid := r.URL.Query().Get(\"id\")\n if id == \"\" {\n\t\tError(w, fmt.Errorf(\"Required args: id\"), http.StatusBadRequest)\n\t\treturn\n }\n\n dbPerson, err := people.GetPerson(id)\n if err != nil {\n\t\tError(w, err, http.StatusNotFound)\n\t\treturn\n }\n\n\tfullImage := r.URL.Query().Get(\"full_images\")\n\tonlyImageID := r.URL.Query().Get(\"only_image_id\")\n\n resp := schema.CheckinPeoplePOSTReq{\n Person: dbPerson.Person(),\n }\n\n if fullImage != \"\" {\n if onlyImageID == \"\" {\n imgs, err := images.GetImages(dbPerson.ID, \"\")\n if err != nil {\n Error(w, err, http.StatusNotFound)\n return\n }\n resp.Images = imgs.Images\n } else {\n ids, err := images.GetImageIDs(dbPerson.ID)\n if err != nil {\n Error(w, err, http.StatusNotFound)\n return\n }\n resp.ImageIDs = ids\n }\n }\n\n\trespondJSON(resp, w, r)\n}", "func getAll(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-type\", \"application/json\")\n\n\t// sending query over db object and storing respose in var result\n\tresult, err := db.Query(\"SELECT fname, lname, email, pword, id FROM person\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tdefer result.Close()\n\n\t// to fetch one record at a time from result\n\tfor result.Next() {\n\n\t\t// creating a variable person to store the and then show it\n\t\tvar person Person\n\t\terr := result.Scan(&person.Fname, &person.Lname, &person.Email, &person.Pword, &person.Id)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tpeople = append(people, person)\n\t}\n\t// Encode json to be sent to client machine\n\tjson.NewEncoder(w).Encode(people)\n}", "func GetPeople(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t//PopulateInitialData()\n\tjson.NewEncoder(w).Encode(people)\n}", "func IndexGET(w http.ResponseWriter, r *http.Request) {\n\t// Get session\n\tsession := session.Instance(r)\n\n\tif session.Values[\"id\"] != nil {\n\t\t// Display the view\n\t\tv := view.New(r)\n\t\tv.Name = \"index/auth\"\n\t\tv.Vars[\"first_name\"] = session.Values[\"first_name\"]\n\t\tv.Render(w)\n\t} else {\n\t\t// Display the view\n\t\tv := view.New(r)\n\t\tv.Name = \"index/anon\"\n\t\tv.Render(w)\n\t\treturn\n\t}\n}", "func getUsersHandler(c *gin.Context) {\n\tuser, _ := c.Get(JwtIdentityKey)\n\n\t// Role check.\n\tif !isAdmin(user) {\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\"message\": \"unauthorized\"})\n\t\treturn\n\t}\n\n\tpage := c.DefaultQuery(\"page\", \"1\")\n\tcount := c.DefaultQuery(\"count\", \"10\")\n\tpageInt, _ := strconv.Atoi(page)\n\tcountInt, _ := strconv.Atoi(count)\n\n\tif page == \"0\" {\n\t\tpageInt = 1\n\t}\n\n\tvar wg sync.WaitGroup\n\tvar users *[]types.User\n\tvar usersCount int\n\n\tdb := data.New()\n\twg.Add(1)\n\tgo func() {\n\t\tusers = db.Users.GetUsers((pageInt-1)*countInt, countInt)\n\t\twg.Done()\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tusersCount = db.Users.GetUsersCount()\n\t\twg.Done()\n\t}()\n\twg.Wait()\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"code\": http.StatusOK,\n\t\t\"users\": users,\n\t\t\"count\": usersCount,\n\t})\n}", "func (r *Login) Method() string {\n\treturn \"GET\"\n}", "func GetHandler(w http.ResponseWriter, r *http.Request) {\n\tun, _, ok := r.BasicAuth()\n\tif !ok {\n\t\tw.Header().Set(\"WWW-Authenticate\", fmt.Sprintf(`Basic realm=\"%s\"`, BasicAuthRealm))\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(http.StatusText(http.StatusUnauthorized) + \"\\n\"))\n\t\treturn\n\t}\n\tu := &User{\n\t\tUsername: un,\n\t}\n\tif reqIsAdmin(r) && r.FormValue(\"username\") != \"\" {\n\t\tu.Username = strings.ToLower(r.FormValue(\"username\"))\n\t} else {\n\t\tcu, err := GetCurrent(r)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tu.Username = cu.Username\n\t}\n\terr := u.Get()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tjd, jerr := json.Marshal(&u)\n\tif jerr != nil {\n\t\thttp.Error(w, jerr.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(jd))\n}", "func (s *Identity) InfoGET(w http.ResponseWriter, r *http.Request) {\n\tinfo := map[string]string{\n\t\t\"version\": \"1.0\",\n\t\t\"providerName\": \"Acme\",\n\t}\n\twriteResponse(info, w, r)\n}", "func GetUser(context *gin.Context) {\n\t//TODO: implement me uwu\n\tJwtCtx := login.ExtractClaims(context)\n\t// identity claim is the username in the database\n\tusername := JwtCtx[jwt.IdentityKey]\n\tuserData := database.GetUser(username.(string))\n\tpayload := models.UserInfoPayload{\n\t\tUserCommon: userData.UserCommon,\n\t}\n\tcontext.JSON(http.StatusOK, payload)\n}", "func Search(c *gin.Context) {\n\tstatus := c.Query(\"status\")\n\n\tusers, err := services.UserService.Search(status)\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, users.Marshall(c.GetHeader(\"X-Public\") == \"true\"))\n\n}", "func Login(req *restful.Request, res *restful.Response) {\n\tvar loginRequest map[string]interface{}\n\terr := json.NewDecoder(req.Request.Body).Decode(&loginRequest)\n\tif err != nil {\n\t\tres.WriteError(http.StatusInternalServerError, err)\n\t}\n\n\t//Send email with url to complete login process from here\n\tres.WriteEntity(loginRequest[\"email\"])\n}", "func editHandler(w http.ResponseWriter, r *http.Request, title string) {\n\t// Get cookie\n\tcookie, err := r.Cookie(\"V\")\n\tif err != nil || cookie == nil {\n\t\tlog.Println(\"May log out or cookie expire\", err)\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\tcookieValue := strings.TrimPrefix(cookie.Value, \"cookie=\")\n\t// Prefetch from backend API\n\tp, err := readProfile(cookieValue)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\tclient := &http.Client{}\n\t//\n\ttoken := TokenInfo{}\n\ttoken.Type = \"STANDARD\"\n\ttoken.Value = \"\"\n\ttokenData, err := json.Marshal(token)\n\tif err != nil {\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\ttokenBuffer := string(tokenData)\n\ttokenPayload := strings.NewReader(tokenBuffer)\n\t// Get token request\n\tgetTokenURL := \"http://localhost:8080/v1/tokens\"\n\trequest, err := http.NewRequest(\"POST\", getTokenURL, tokenPayload)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"Cookie\", cookieValue)\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\tbodyBytes, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tlog.Println(\"error occurred when reading response\", err)\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\terr = json.Unmarshal(bodyBytes, &token)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Redirect(w, r, \"/loginError/\", http.StatusFound)\n\t\treturn\n\t}\n\tupdateNormal := UpdateDescription{}\n\tupdateNormal.Username = p.Username\n\tupdateNormal.Description = p.Description\n\tupdateNormal.Token = token.Value\n\trenderTemplateDescription(w, \"edit\", &updateNormal)\n}", "func GetPerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)\n\tid, err := strconv.Atoi(params[\"id\"])\n\tif err != nil {\n\t\tfmt.Println(\"Oops, \", err)\n\t}\n\tfor _, searchID := range models.People {\n\t\tif searchID.ID == id {\n\t\t\tjson.NewEncoder(w).Encode(searchID)\n\t\t}\n\t}\n}", "func Login(nbmaster string, httpClient *http.Client, username string, password string, domainName string, domainType string) string {\r\n fmt.Printf(\"\\nLog into the NetBackup webservices...\\n\")\r\n\r\n loginDetails := map[string]string{\"userName\": username, \"password\": password}\r\n if len(domainName) > 0 {\r\n loginDetails[\"domainName\"] = domainName\r\n }\r\n if len(domainType) > 0 {\r\n loginDetails[\"domainType\"] = domainType\r\n }\r\n loginRequest, _ := json.Marshal(loginDetails)\r\n\r\n uri := \"https://\" + nbmaster + \":\" + port + \"/netbackup/login\"\r\n\r\n request, _ := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(loginRequest))\r\n request.Header.Add(\"Content-Type\", contentTypeV2);\r\n\r\n response, err := httpClient.Do(request)\r\n\r\n token := \"\"\r\n if err != nil {\r\n fmt.Printf(\"The HTTP request failed with error: %s\\n\", err)\r\n panic(\"Unable to login to the NetBackup webservices.\")\r\n } else {\r\n if response.StatusCode == 201 {\r\n data, _ := ioutil.ReadAll(response.Body)\r\n var obj interface{}\r\n json.Unmarshal(data, &obj)\r\n loginResponse := obj.(map[string]interface{})\r\n token = loginResponse[\"token\"].(string)\r\n } else {\r\n printErrorResponse(response)\r\n }\r\n }\r\n\r\n return token\r\n}", "func restGet(room string, client *http.Client, ip string, port string) (*http.Response, error) {\n\treturn client.Get(fmt.Sprintf(\"http://%v/rest/%v\", net.JoinHostPort(ip, port), room))\n}", "func GetUserProfileHandler(w http.ResponseWriter, r *http.Request) {\n\n}", "func GetPeople(w http.ResponseWriter, req *http.Request ){\t\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(models.People)\n}", "func (client *ShorelineClient) Login(username, password string) (*UserData, string, error) {\n\thost := client.getHost()\n\tif host == nil {\n\t\treturn nil, \"\", errors.New(\"No known user-api hosts.\")\n\t}\n\n\thost.Path = path.Join(host.Path, \"login\")\n\n\treq, _ := http.NewRequest(\"POST\", host.String(), nil)\n\treq.SetBasicAuth(username, password)\n\n\tres, err := client.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tdefer res.Body.Close()\n\n\tswitch res.StatusCode {\n\tcase 200:\n\t\tud, err := extractUserData(res.Body)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\treturn ud, res.Header.Get(\"x-tidepool-session-token\"), nil\n\tcase 404:\n\t\treturn nil, \"\", nil\n\tdefault:\n\t\treturn nil, \"\", &status.StatusError{\n\t\t\tstatus.NewStatusf(res.StatusCode, \"Unknown response code from service[%s]\", req.URL)}\n\t}\n}", "func SearchIdentities(w http.ResponseWriter, r *http.Request) {\n\tapiContext := api.GetApiContext(r)\n\tauthHeader := r.Header.Get(\"Authorization\")\n\n\tif authHeader != \"\" {\n\t\t// header value format will be \"Bearer <token>\"\n\t\tif !strings.HasPrefix(authHeader, \"Bearer \") {\n\t\t\tlog.Debug(\"GetMyIdentities Failed to find Bearer token %v\", authHeader)\n\t\t\tReturnHTTPError(w, r, http.StatusUnauthorized, \"Unauthorized, please provide a valid token\")\n\t\t}\n\t\taccessToken := strings.TrimPrefix(authHeader, \"Bearer \")\n\t\tlog.Debugf(\"token is this %s\", accessToken)\n\n\t\t//see which filters are passed, if none then error 400\n\n\t\texternalId := r.URL.Query().Get(\"externalId\")\n\t\texternalIdType := r.URL.Query().Get(\"externalIdType\")\n\t\tname := r.URL.Query().Get(\"name\")\n\n\t\tif externalId != \"\" && externalIdType != \"\" {\n\t\t\t//search by id and type\n\t\t\tidentity, err := server.GetIdentity(externalId, externalIdType, accessToken)\n\t\t\tif err == nil {\n\t\t\t\tapiContext.Write(&identity)\n\t\t\t} else {\n\t\t\t\t//failed to search the identities\n\t\t\t\tlog.Errorf(\"SearchIdentities Failed with error %v\", err)\n\t\t\t\tReturnHTTPError(w, r, http.StatusInternalServerError, \"Internal Server Error\")\n\t\t\t}\n\t\t} else if name != \"\" {\n\n\t\t\tidentities, err := server.SearchIdentities(name, true, accessToken)\n\t\t\tlog.Debugf(\"identities %v\", identities)\n\t\t\tif err == nil {\n\t\t\t\tresp := client.IdentityCollection{}\n\t\t\t\tresp.Data = identities\n\n\t\t\t\tapiContext.Write(&resp)\n\t\t\t} else {\n\t\t\t\t//failed to search the identities\n\t\t\t\tlog.Errorf(\"SearchIdentities Failed with error %v\", err)\n\t\t\t\tReturnHTTPError(w, r, http.StatusInternalServerError, \"Internal Server Error\")\n\t\t\t}\n\t\t} else {\n\t\t\tReturnHTTPError(w, r, http.StatusBadRequest, \"Bad Request, Please check the request content\")\n\t\t}\n\t} else {\n\t\tlog.Debug(\"No Authorization header found\")\n\t\tReturnHTTPError(w, r, http.StatusUnauthorized, \"Unauthorized, please provide a valid token\")\n\t}\n}", "func Login(res http.ResponseWriter, req *http.Request) {\n\tuser := new(model.User)\n\tID := req.Context().Value(\"ID\").(string)\n\tdata := req.Context().Value(\"data\").(*validation.Login)\n\tnow := time.Now().Unix()\n\tresponse := make(map[string]interface{})\n\tdocKey, err := connectors.ReadDocument(\"users\", ID, user)\n\tif err != nil {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusServiceUnavailable, constants.Unavailable))\n\t\treturn\n\t} else if len(docKey) == 0 {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusBadRequest, constants.NotFoundResource))\n\t\treturn\n\t}\n\ttimeDiff := time.Unix(user.OtpValidity, 0).Sub(time.Now())\n\tcompareOtp := bcrypt.CompareHashAndPassword([]byte(user.OTP), []byte(data.OTP))\n\tif compareOtp != nil || timeDiff < 0 {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusBadRequest, constants.InvalidOTP))\n\t\treturn\n\t}\n\tif user.OtpType == constants.OTPType[\"email\"] {\n\t\tuser.EmailVerify = 1\n\t} else if user.OtpType == constants.OTPType[\"phone\"] {\n\t\tuser.PhoneVerify = 1\n\t}\n\tuser.OTP, user.OtpType, user.OtpValidity, user.LastLogedIn, user.UpdatedAt = \"\", \"\", 0, now, now\n\tdocKey, err = connectors.UpdateDocument(\"users\", docKey, user)\n\tif err != nil {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusServiceUnavailable, constants.Unavailable))\n\t\treturn\n\t}\n\taccessToken, err := generateToken(docKey, \"aceessToken\", constants.AccessTokenValidity)\n\tif err != nil {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusServiceUnavailable, constants.Unavailable))\n\t\treturn\n\t}\n\trefreshToken, err := generateToken(docKey, \"refreshToken\", constants.RefreshTokenValidity)\n\tif err != nil {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusServiceUnavailable, constants.Unavailable))\n\t\treturn\n\t}\n\tresponse[\"accessToken\"] = accessToken\n\tresponse[\"refreshToken\"] = refreshToken\n\trender.Render(res, req, responses.NewHTTPSucess(http.StatusOK, response))\n}", "func Callback(c *gin.Context) {\n\tprovider := c.Param(\"provider\")\n\n\tvar logincode vo.LoginReq\n\tif err := c.ShouldBindQuery(&logincode); err != nil {\n\t\tfmt.Println(\"xxxx\", err)\n\t}\n\n\tfmt.Println(\"provider\", provider, logincode)\n\n\tuserInfo := vo.GetUserInfoFromOauth(provider, logincode.Code, logincode.State)\n\tfmt.Println(\"get user info\", userInfo)\n\n\tif userInfo == nil {\n\t\tc.JSON(http.StatusOK, sailor.HTTPAirdbResponse{\n\t\t\tCode: enum.AirdbSuccess,\n\t\t\tSuccess: true,\n\t\t\tData: vo.LoginResp{\n\t\t\t\tNickname: \"xxx\",\n\t\t\t\tHeadimgurl: \"xxx.png\",\n\t\t\t},\n\t\t})\n\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, sailor.HTTPAirdbResponse{\n\t\tCode: enum.AirdbSuccess,\n\t\tSuccess: true,\n\t\tData: vo.LoginResp{\n\t\t\tNickname: userInfo.Login,\n\t\t\tHeadimgurl: userInfo.AvatarURL,\n\t\t},\n\t})\n}", "func Login(c echo.Context) error {\r\n\r\n\tconfig := config.GetInstance()\r\n\r\n\tbody := make(map[string]interface{})\r\n\terr := json.NewDecoder(c.Request().Body).Decode(&body)\r\n\tif err != nil {\r\n\t\treturn c.JSON(500, &models.Response{\r\n\t\t\tStatus: 1,\r\n\t\t\tSuccess: false,\r\n\t\t\tMessage: \"Errore interno\",\r\n\t\t})\r\n\t}\r\n\r\n\tbody[\"command-name\"] = \"login\"\r\n\r\n\tform := url.Values{}\r\n\r\n\tform.Add(\"command-name\", body[\"command-name\"].(string))\r\n\tform.Add(\"name\", body[\"username\"].(string))\r\n\tform.Add(\"password\", body[\"password\"].(string))\r\n\r\n\tURLRequest := config.GetRemoteURL()\r\n\r\n\treq, err := http.NewRequest(\"POST\", URLRequest+\"/process-request.php\", bytes.NewBufferString(form.Encode()))\r\n\r\n\tif err != nil {\r\n\t\treturn c.JSON(500, &models.Response{\r\n\t\t\tStatus: 2,\r\n\t\t\tSuccess: false,\r\n\t\t\tMessage: err.Error(),\r\n\t\t})\r\n\t}\r\n\r\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded; param=value;charset=UTF-8\")\r\n\r\n\tsetCookie(req, \"auth-key\", config.RemoteAuthKey)\r\n\r\n\tclient := &http.Client{}\r\n\r\n\tres, err := client.Do(req)\r\n\tif err != nil {\r\n\t\treturn c.JSON(500, &models.Response{\r\n\t\t\tStatus: 3,\r\n\t\t\tSuccess: false,\r\n\t\t\tMessage: err.Error(),\r\n\t\t})\r\n\t}\r\n\r\n\tdefer res.Body.Close()\r\n\r\n\tsetSession(c, res)\r\n\r\n\tvar httpResponseData models.HTTPResponse\r\n\r\n\tif err := json.NewDecoder(res.Body).Decode(&httpResponseData); err != nil {\r\n\t\treturn c.JSON(500, &models.Response{\r\n\t\t\tStatus: 4,\r\n\t\t\tSuccess: false,\r\n\t\t\tMessage: err.Error(),\r\n\t\t})\r\n\t}\r\n\r\n\treturn c.JSON(200, httpResponseData)\r\n}", "func getPi(w http.ResponseWriter, r *http.Request) {\n\t// Get pi name from request\n\tvars := mux.Vars(r)\n\tpiname := vars[\"piname\"]\n\n\t// Retrieve pi object from data store\n\tc := appengine.NewContext(r)\n\tq := datastore.NewQuery(piListKind).Filter(\"name =\", piname)\n\tt := q.Run(c)\n\tvar pi Pi\n\t_, err := t.Next(&pi)\n\tif err == datastore.Done {\n\t\thttp.Error(w, \"404 Not found\", http.StatusNotFound)\n\t\treturn\n\t}\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Return JSON representatikon of Pi object\n\tbuffer, _ := json.MarshalIndent(pi, \"\", \" \")\n\tfmt.Fprint(w, string(buffer))\n}", "func getUser(w http.ResponseWriter, r *http.Request) {\n\t// set header.\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar user schema.User\n\n\tid := strings.TrimPrefix(r.URL.Path, \"/users/\") // Extracting user id from the URL by performing expression/pattern matching\n\t// OR\n\t// re := regexp.MustCompile(\"/users/([!-z]+)\")\n\t// id := re.FindStringSubmatch(r.URL.Path)[1] \n\n\tfilter := bson.M{\"id\": id}\n\t\n\terr := users.FindOne(context.TODO(), filter).Decode(&user)\n\n\tif err != nil {\n\t\tlog.Fatal(err, w)\n\t}\n\n\tjson.NewEncoder(w).Encode(user)\n}", "func (c *Client) get(rawURL string, authenticate bool, out interface{}) error {\n\terr := c.do(rawURL, \"GET\", authenticate, http.StatusOK, nil, out)\n\treturn errio.Error(err)\n}", "func List(w http.ResponseWriter, r *http.Request) {\n\tauthUser, err := auth.GetUserFromJWT(w, r)\n\tif err != nil {\n\t\tresponse.FormatStandardResponse(false, \"error-auth\", \"\", err.Error(), w)\n\t\treturn\n\t}\n\n\tlistHandler(w, authUser, false)\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Login endpoint hit\")\n\t\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tuser := models.User{}\n\n\tif user.Authorise(username, password) {\n\t\tjson.NewEncoder(w).Encode(user)\n\t} else {\n\t\tm := make(map[string]string)\n\t\tm[\"Message\"] = \"Username and password do not match\"\n\t\tjson.NewEncoder(w).Encode(m)\n\t}\n}" ]
[ "0.63776165", "0.6154853", "0.615378", "0.6062602", "0.59676594", "0.5934943", "0.5893324", "0.58626664", "0.5861018", "0.5853691", "0.584366", "0.5807749", "0.5805815", "0.57685137", "0.5765969", "0.57202905", "0.57076734", "0.57067597", "0.5703087", "0.5691566", "0.5685883", "0.5660162", "0.56445765", "0.56265336", "0.55809003", "0.55656177", "0.5553285", "0.553637", "0.5525778", "0.55164045", "0.5510464", "0.5487555", "0.54866415", "0.5481695", "0.5478648", "0.54775065", "0.54551005", "0.5440581", "0.54211783", "0.5415237", "0.5413503", "0.5411977", "0.54089266", "0.5401512", "0.5397677", "0.53892773", "0.53698754", "0.5361653", "0.53596276", "0.5352561", "0.53478104", "0.5345945", "0.5341571", "0.5341365", "0.5335537", "0.5332959", "0.5315115", "0.5314193", "0.5308738", "0.53075933", "0.5304144", "0.5299119", "0.52990764", "0.5297171", "0.52956784", "0.5291283", "0.5290496", "0.5286682", "0.52856785", "0.5283104", "0.5276968", "0.5274148", "0.5272121", "0.52714044", "0.5271322", "0.52695537", "0.526459", "0.5262972", "0.5262857", "0.52627116", "0.5257182", "0.5257152", "0.52569246", "0.52562577", "0.5252125", "0.52467746", "0.5238802", "0.52384514", "0.5237666", "0.5235135", "0.5234841", "0.52337176", "0.5229506", "0.5229324", "0.52290297", "0.52267766", "0.521875", "0.5216769", "0.52166325", "0.52136546" ]
0.76519233
0
LoginGET displays the login page
func LoginGET(w http.ResponseWriter, r *http.Request) { sess := model.Instance(r) v := view.New(r) v.Name = "login/login" v.Vars["token"] = csrfbanana.Token(w, r, sess) // Refill any form fields view.Repopulate([]string{"cuenta","password"}, r.Form, v.Vars) v.Render(w) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func LoginGET(c *gin.Context) {\n\tc.HTML(http.StatusOK, \"login.html\", gin.H{})\n}", "func (m *Repository) GetLogin(w http.ResponseWriter, r *http.Request) {\n\tif m.App.Session.Exists(r.Context(), \"user_id\") {\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\trender.Template(w, r, \"login.page.tmpl\", &models.TemplateData{\n\t\tForm: forms.New(nil),\n\t})\n}", "func handleLoginGET(w http.ResponseWriter, req *http.Request) {\n\ttmpl, err := template.ParseFiles(\"./templates/login.html\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tdata := LoginPage {\n\t\tTitle: \"Login\",\n\t}\n\n\ttmpl.Execute(w, data)\n}", "func GetLogin(w http.ResponseWriter, req *http.Request, app *App) {\n\tif models.UserCount(app.Db) > 0 {\n\t\trender(w, \"admin/login\", map[string]interface{}{\"hideNav\": true}, app)\n\t} else {\n\t\thttp.Redirect(w, req, app.Config.General.Prefix+\"/register\", http.StatusSeeOther)\n\t}\n\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\tpageVars := PageVars{}\n\taddPageVars(r, &pageVars)\n\trender(w, \"login\", pageVars)\n}", "func UsersLoginGet(c buffalo.Context) error {\n\treturn c.Render(200, r.HTML(\"users/login\"))\n}", "func showLoginPage(c *gin.Context) {\n\trender(c, gin.H{\n\t\t\"title\": \"Login\",\n\t\t\"ErrorMessage\": \"\",\n\t}, \"login.html\")\n}", "func Login(res http.ResponseWriter, req *http.Request) {\n\tdata := struct{ Title string }{\"Login\"}\n\ttemplates.ExecuteTemplate(res, \"login\", data)\n}", "func (c Control) ServeLogin(w http.ResponseWriter, r *http.Request) {\n\ttemplate := map[string]interface{}{\"error\": false}\n\tif r.Method == http.MethodPost {\n\t\t// Get their submitted hash and the real hash.\n\t\tpassword := r.PostFormValue(\"password\")\n\t\thash := HashPassword(password)\n\t\tc.Config.RLock()\n\t\trealHash := c.Config.AdminHash\n\t\tc.Config.RUnlock()\n\t\t// Check if they got the password correct.\n\t\tif hash == realHash {\n\t\t\ts, _ := Store.Get(r, \"sessid\")\n\t\t\ts.Values[\"authenticated\"] = true\n\t\t\ts.Save(r, w)\n\t\t\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\t\t\treturn\n\t\t}\n\t\ttemplate[\"error\"] = true\n\t}\n\n\t// Serve login page with no template.\n\tdata, err := Asset(\"templates/login.mustache\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\tcontent := mustache.Render(string(data), template)\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tw.Write([]byte(content))\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"login called\")\n}", "func (app *Application) LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tvar data map[string]interface{}\n\tdata = make(map[string]interface{})\n\tfmt.Println(\"login.html\")\n\tif r.FormValue(\"submitted\") == \"true\" {\n\t\tuname := r.FormValue(\"username\")\n\t\tpword := r.FormValue(\"password\")\n\t\torg := r.FormValue(\"org\")\n\t\tprintln(uname, pword, org)\n\t\t//according uname, comparing pword with map[uname]\n\t\tfor _, v := range webutil.Orgnization[org] {\n\t\t\tfmt.Println(\"org user\", v.UserName)\n\t\t\tif v.UserName == uname {\n\t\t\t\tif v.Secret == pword {\n\t\t\t\t\twebutil.MySession.SetSession(uname, org, w)\n\t\t\t\t\thttp.Redirect(w, r, \"./home.html\", 302)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\t//login failed redirect to login page and show failed\n\t\tdata[\"LoginFailed\"] = true\n\t\tloginTemplate(w, r, \"login.html\", data)\n\t\treturn\n\t}\n\tloginTemplate(w, r, \"login.html\", data)\n}", "func (s TppHTTPServer) Login(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tdata := LoginPageData{PageTitle: \"AXA Pay Bank Login\", BankID: s.BankID, PIN: s.PIN}\n\t//fmt.Fprint(w, \"TPP server reference PISP Login\\n\")\n\ttmpl := template.Must(template.ParseFiles(\"api/login.html\"))\n\tr.ParseForm()\n\tlog.Println(\"Form:\", r.Form)\n\ttmpl.Execute(w, data)\n\n}", "func (a Authentic) login(c buffalo.Context) error {\n\treturn c.Render(200, a.Config.LoginPage)\n}", "func Login(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tfmt.Println(\"Login\")\n}", "func Login(ctx echo.Context) error {\n\n\tf := forms.New(utils.GetLang(ctx))\n\tutils.SetData(ctx, \"form\", f)\n\n\t// set page tittle to login\n\tutils.SetData(ctx, settings.PageTitle, \"login\")\n\n\treturn ctx.Render(http.StatusOK, tmpl.LoginTpl, utils.GetData(ctx))\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"GET\" {\n\t\takagi := user{\n\t\t\tName: \"Nguyen Hoai Phuong\",\n\t\t\tPassword: \"1234\",\n\t\t}\n\n\t\tbs, err := json.Marshal(akagi)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Encode user error:\", err)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(bs)\n\t} else if r.Method == \"POST\" {\n\t\terr := r.ParseForm()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tuser := r.FormValue(\"username\")\n\t\tpass := r.FormValue(\"password\")\n\t\tfmt.Println(user)\n\t\tfmt.Println(pass)\n\t\thttp.Redirect(w, r, \"/login\", http.StatusOK)\n\t\tfmt.Fprintf(w, \"User name: %s\\nPassword : %s\\n\", user, pass)\n\t}\n\n}", "func (as *AdminServer) Login(w http.ResponseWriter, r *http.Request) {\n\tparams := struct {\n\t\tUser models.User\n\t\tTitle string\n\t\tFlashes []interface{}\n\t\tToken string\n\t}{Title: \"Login\", Token: csrf.Token(r)}\n\tsession := ctx.Get(r, \"session\").(*sessions.Session)\n\tswitch {\n\tcase r.Method == \"GET\":\n\t\tparams.Flashes = session.Flashes()\n\t\tsession.Save(r, w)\n\t\ttemplates := template.New(\"template\")\n\t\t_, err := templates.ParseFiles(\"templates/login.html\", \"templates/flashes.html\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\ttemplate.Must(templates, err).ExecuteTemplate(w, \"base\", params)\n\tcase r.Method == \"POST\":\n\t\t// Find the user with the provided username\n\t\tusername, password := r.FormValue(\"username\"), r.FormValue(\"password\")\n\t\tu, err := models.GetUserByUsername(username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\t// Validate the user's password\n\t\terr = auth.ValidatePassword(password, u.Hash)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\tif u.AccountLocked {\n\t\t\tas.handleInvalidLogin(w, r, \"Account Locked\")\n\t\t\treturn\n\t\t}\n\t\tu.LastLogin = time.Now().UTC()\n\t\terr = models.PutUser(&u)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\t// If we've logged in, save the session and redirect to the dashboard\n\t\tsession.Values[\"id\"] = u.Id\n\t\tsession.Save(r, w)\n\t\tas.nextOrIndex(w, r)\n\t}\n}", "func (h *Handler) LoginHandler(w http.ResponseWriter, r *http.Request) {\n\n\tchallenge, err := readURLChallangeParams(r, \"login\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif r.Method == \"POST\" {\n\t\tif r.Form == nil {\n\t\t\tif err := r.ParseForm(); err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tuserName := r.Form.Get(\"username\")\n\t\tpassword := r.Form.Get(\"password\")\n\t\tloginChallenge := r.Form.Get(\"challenge\")\n\t\tpass, err := h.LoginService.CheckPasswords(userName, password)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tif pass {\n\n\t\t\tacceptLoginBody := h.ConfigService.FetchAcceptLoginConfig(userName)\n\t\t\trawJson, err := json.Marshal(acceptLoginBody)\n\n\t\t\tredirectURL, err := h.LoginService.SendAcceptBody(\"login\", loginChallenge, rawJson)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\thttp.Redirect(w, r, redirectURL, http.StatusFound)\n\t\t}\n\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\ttemplLogin := template.Must(template.ParseFiles(\"templates/login.html\"))\n\t\tloginData := h.ConfigService.FetchLoginConfig(challenge, true)\n\t\ttemplLogin.Execute(w, loginData)\n\t} else {\n\t\tchallengeBody, err := h.LoginService.ReadChallenge(challenge, \"login\")\n\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tlog.Print(err)\n\t\t}\n\n\t\tif !challengeBody.Skip {\n\t\t\ttemplLogin := template.Must(template.ParseFiles(\"templates/login.html\"))\n\t\t\tloginData := h.ConfigService.FetchLoginConfig(challenge, false)\n\t\t\ttemplLogin.Execute(w, loginData)\n\t\t} else {\n\n\t\t\tacceptLoginBody := h.ConfigService.FetchAcceptLoginConfig(challengeBody.Subject)\n\t\t\trawJson, err := json.Marshal(acceptLoginBody)\n\n\t\t\tredirectURL, err := h.LoginService.SendAcceptBody(\"login\", challenge, rawJson)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\thttp.Redirect(w, r, redirectURL, http.StatusFound)\n\n\t\t}\n\t}\n}", "func getLoginHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {\n\tif database.RetrieveUsersCount() == 0 {\n\t\thttp.Redirect(w, r, \"/admin/register\", http.StatusFound)\n\t\treturn\n\t}\n\thttp.ServeFile(w, r, filepath.Join(filenames.AdminFilepath, \"login.html\"))\n\treturn\n}", "func loginPage(w http.ResponseWriter, r *http.Request){\n\terr := templ.ExecuteTemplate(w, \"login\", nil)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\r\n\tlogin := strings.Trim(r.FormValue(\"login\"), \" \")\r\n\tpass := strings.Trim(r.FormValue(\"pass\"), \" \")\r\n\tlog.Println(\"login: \", login, \" pass: \", pass)\r\n\r\n\t// Check params\r\n\tif login == \"\" || pass == \"\" {\r\n\t\twriteResponse(w, \"Login and password required\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\t// Already authorized\r\n\tif savedPass, OK := Auth[login]; OK && savedPass == pass {\r\n\t\twriteResponse(w, \"You are already authorized\\n\", http.StatusOK)\r\n\t\treturn\r\n\t} else if OK && savedPass != pass {\r\n\t\t// it is not neccessary\r\n\t\twriteResponse(w, \"Wrong pass\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\tuser := model.User{}\r\n\terr := user.Get(login, pass)\r\n\tif err == nil {\r\n\t\tAuth[login], Work[login] = pass, user.WorkNumber\r\n\t\twriteResponse(w, \"Succesfull authorization\\n\", http.StatusOK)\r\n\t\treturn\r\n\t}\r\n\r\n\twriteResponse(w, \"User with same login not found\\n\", http.StatusNotFound)\r\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tappengineContext := appengine.NewContext(r)\n\tappengineUser := user.Current(appengineContext)\n\tif appengineUser != nil {\n\t\turl, err := user.LogoutURL(appengineContext, \"/\")\n\t\tif err == nil {\n\t\t\tw.Header().Set(\"Location\", url)\n\t\t\tw.WriteHeader(http.StatusFound)\n\t\t\treturn\n\t\t}\n\t}\n\tw.Header().Set(\"Location\", \"/\")\n\tw.WriteHeader(http.StatusFound)\n}", "func login(w http.ResponseWriter, r *http.Request) {\n clearCache(w)\n exists, _ := getCookie(r, LOGIN_COOKIE)\n if exists {\n http.Redirect(w, r, \"/home\", http.StatusSeeOther)\n return\n }\n if r.Method == http.MethodGet {\n LOG[INFO].Println(\"Login Page\")\n http.ServeFile(w, r, \"../../web/login.html\")\n } else if r.Method == http.MethodPost {\n LOG[INFO].Println(\"Executing Login\")\n r.ParseForm()\n LOG[INFO].Println(\"Form Values: Username\", r.PostFormValue(\"username\"))\n passhash := sha512.Sum512([]byte(r.PostFormValue(\"password\")))\n LOG[INFO].Println(\"Hex Encoded Passhash:\", hex.EncodeToString(passhash[:]))\n response := sendCommand(CommandRequest{CommandLogin, struct{\n Username string\n Password string\n }{\n r.PostFormValue(\"username\"),\n hex.EncodeToString(passhash[:]),\n }})\n if response == nil {\n http.SetCookie(w, genCookie(ERROR_COOKIE, \"Send Command Error\"))\n http.Redirect(w, r, \"/error\", http.StatusSeeOther)\n return\n }\n if !response.Success {\n LOG[WARNING].Println(StatusText(response.Status))\n http.Redirect(w, r, \"/login\", http.StatusSeeOther)\n return\n }\n\n LOG[INFO].Println(\"Successfully Logged In\")\n http.SetCookie(w, genCookie(LOGIN_COOKIE, r.PostFormValue(\"username\")))\n http.Redirect(w, r, \"/home\", http.StatusSeeOther)\n }\n}", "func logIn(res http.ResponseWriter, req *http.Request) {\n\t// retrive the name form URL\n\tname := req.FormValue(\"name\")\n\tname = html.EscapeString(name)\n\tif name != \"\" {\n\t\tuuid := generateUniqueId()\n\t\tsessionsSyncLoc.Lock()\n\t\tsessions[uuid] = name\n\t\tsessionsSyncLoc.Unlock()\n\n\t\t// save uuid in the cookie\n\t\tcookie := http.Cookie{Name: \"uuid\", Value: uuid, Path: \"/\"}\n\t\thttp.SetCookie(res, &cookie)\n\n\t\t// redirect to /index.html endpoint\n\t\thttp.Redirect(res, req, \"/index.html\", http.StatusFound)\n\t} else {\n\t\t// if the provided input - name is empty, display this message\n\t\tres.Header().Set(\"Content-Type\", \"text/html\")\n\t\tfmt.Fprintf(\n\t\t\tres,\n\t\t\t`<html>\n\t\t\t<body>\n\t\t\t<form action=\"login\">\n\t\t\t C'mon, I need a name.\n\t\t\t</form>\n\t\t\t</p>\n\t\t\t</body>\n\t\t\t</html>`,\n\t\t)\n\t}\n}", "func loginFormHandler(w http.ResponseWriter, r *http.Request) {\n\tb.pageDisplayer.DisplayPage(w, \"login_form.html\", nil)\n}", "func (_ *Auth) Login(c *gin.Context) {\n\n\tflash := helper.GetFlash(c)\n\tc.HTML(http.StatusOK, \"auth/login.tpl\", gin.H{\n\t\t\"title\": \"Gin Blog\",\n\t\t\"flash\": flash,\n\t})\n}", "func (uc *UserController) Login(w http.ResponseWriter, r *http.Request) {\n\tvar loginInfo models.User\n\tdecoder := json.NewDecoder(r.Body)\n\tdecoder.Decode(&loginInfo)\n\tresp, token, _, _, _ := uc.User.GET(loginInfo.Username, loginInfo.Password)\n\tif token != \"\" {\n\t\tjson.NewEncoder(w).Encode(resp)\n\t}\n}", "func HandlerLogin(responseWriter http.ResponseWriter, request *http.Request) {\n\trequest.ParseForm()\n\n\tif request.Method == STR_GET {\n\t\tServeLogin(responseWriter, STR_EMPTY)\n\t} else {\n\t\tvar userName string = request.FormValue(API_KEY_username)\n\t\tvar password string = request.FormValue(API_KEY_password)\n\t\tif userName == STR_EMPTY || password == STR_EMPTY {\n\t\t\tServeLogin(responseWriter, \"Please enter username and password\")\n\t\t\treturn\n\t\t}\n\n\t\tvar userId = -1\n\t\tvar errorUser error = nil\n\t\tuserId, errorUser = DbGetUser(userName, password, nil)\n\t\tif errorUser != nil {\n\t\t\tlog.Printf(\"HandlerLogin, errorUser=%s\", errorUser.Error())\n\t\t}\n\t\tif userId > -1 {\n\t\t\ttoken := DbAddToken(userId, nil)\n\t\t\tAddCookie(responseWriter, token)\n\t\t\thttp.Redirect(responseWriter, request, GetApiUrlListApiKeys(), http.StatusTemporaryRedirect)\n\t\t} else {\n\t\t\tServeLogin(responseWriter, \"Wrong username or password\")\n\t\t}\n\t}\n}", "func (h *TestAuth) Login(w http.ResponseWriter, req *http.Request) {\n\n\tresponse := make(map[string]string, 5)\n\n\tresponse[\"state\"] = authz.AuthNewPasswordRequired\n\tresponse[\"access_token\"] = \"access\"\n\t//response[\"id_token\"] = *authResult.IdToken\n\tresponse[\"refresh_token\"] = \"refersh\"\n\tresponse[\"expires\"] = \"3600\"\n\tresponse[\"token_type\"] = \"Bearer\"\n\trespData, _ := json.Marshal(response)\n\tw.WriteHeader(200)\n\tfmt.Fprint(w, string(respData))\n}", "func LoginGetHandler(ctx *enliven.Context) {\n\tif ctx.Enliven.Core.Email.Enabled() {\n\t\tctx.Strings[\"ForgotPasswordURL\"] = config.GetConfig()[\"user_forgot_password_route\"]\n\t}\n\tctx.ExecuteBaseTemplate(\"user_login\")\n}", "func (db *MyConfigurations) showLoginPage(c echo.Context) error {\n\tstatus, message := getFlashMessages(&c) // gets the flash message and status if there was any\n\tusers := models.GetAllUsers(db.GormDB) // gets all the users that are in the database\n\tvaluesToReturn := echo.Map{\n\t\t\"status\": status, // pass the status of the flash message\n\t\t\"message\": message, // pass the message\n\t\t\"title\": \"تسجيل دخول\", // the title of the page\n\t\t\"hideNavBar\": true, // boolean to indicate weather or not the NavBar should be displayed\n\t\t\"users\": users, // pass the users array to display to the user\n\t}\n\tif checkIfRequestFromMobileDevice(c) {\n\t\treturn c.JSON(http.StatusOK, &valuesToReturn)\n\t}\n\treturn c.Render(http.StatusOK, \"login.html\", &valuesToReturn)\n}", "func LoginAction(w http.ResponseWriter, r *http.Request) {\n\n\tpageVars := PageVars{}\n\taddPageVars(r, &pageVars)\n\n\tuserName := r.FormValue(\"userName\")\n\t// validate username\n\tif len(userName) <= 0 {\n\t\thttp.Redirect(w, r, \"/login?errorM=Username specified\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tpassword := r.FormValue(\"password\")\n\t// validate password\n\tif len(password) <= 0 {\n\t\thttp.Redirect(w, r, \"/login?errorM=Password specified\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\t// get expected password\n\texpectedPassword := getStringFromDB(\"Users\", userName)\n\n\t// verify the password\n\tif expectedPassword != password {\n\t\thttp.Redirect(w, r, \"/login?errorM=Invalid credentials\", http.StatusSeeOther)\n\t\treturn\n\t}\n\t\n\t// Create a new random session token\n\tsessionToken, err := uuid.NewUUID()\n\tif err != nil {\n\t\thttp.Redirect(w, r, \"/login?errorM=Unable to create token\", http.StatusSeeOther)\n\t}\n\t// Set the token in the db, along with the userName\n\tupdateDBString(\"Sessions\", userName, sessionToken.String())\n\n\t// set the expiration time\n\texpires := time.Now().Add(600 * time.Second)\n\tck := http.Cookie{\n Name: \"JSESSION_ID\",\n Path: \"/\",\n\t\tExpires: expires,\n\t\tValue: userName+\"_\"+sessionToken.String(),\n\t}\n\n // write the cookie to response\n http.SetCookie(w, &ck)\n\thttp.Redirect(w, r, \"/listbuckets\", http.StatusSeeOther)\n\n}", "func (server Server) Login(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r) // mux params\n\tusername := vars[\"username\"] // get username\n\tpassword := vars[\"password\"] // get password\n\tvar res models.APIResponse // make a response\n\n\tif username == \"\" || password == \"\" {\n\t\tres = models.BuildAPIResponseFail(\"Bad Request. Empty username or password\", nil)\n\t} else {\n\t\tvar data = checkLogin(username, password, server.db) //create the data\n\t\tres = models.BuildAPIResponseSuccess(\"Login successful\", data)\n\t}\n\tjson.NewEncoder(w).Encode(res) //encode the data\n\n}", "func LoginPage(c *gin.Context) {\n\tc.HTML(http.StatusOK, \"Login.html\", gin.H{\n\t\t\"loginURL\": \"http://127.0.0.1:8080/user/login\",\n\t})\n}", "func LoginHandler(c echo.Context) error {\n\treturn c.JSON(http.StatusOK, c.QueryParams())\n}", "func LoginRoute(res http.ResponseWriter, req *http.Request) {\n if req.Method == \"GET\" {\n res.Write([]byte(`\n <html>\n <head>\n <title> Login </title>\n </head>\n <body>\n <h1> Login </h1>\n <form action = \"/login\" method = \"post\">\n Username:<br>\n <input type=\"text\" name=\"Username\"><br>\n Password:<br>\n <input type = \"password\" name = \"Password\">\n <input type = \"submit\" value = \"Login\">\n </form>\n </body>\n </html>\n `))\n } else {\n req.ParseForm()\n username := req.FormValue(\"Username\")\n password := req.FormValue(\"Password\")\n\n uid, err := CheckUser(username, password)\n if err == nil {\n\n session := http.Cookie{\n Name: \"session\",\n Value: strconv.Itoa(uid),\n\n //MaxAge: 10 * 60,\n Secure: false,\n HttpOnly: true,\n SameSite: 1,\n\n Path: \"/\",\n }\n http.SetCookie(res, &session)\n Redirect(\"/library\", res)\n } else {\n res.Write([]byte(err.Error()))\n }\n }\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\t/*\n\t\tTratamento dos dados vindos do front-end\n\t\tNesse caso, o request pega login e senha\n\t*/\n\tvar login models.Credentials\n\tbody := r.Body\n\tbytes, err := util.BodyToBytes(body)\n\terr = util.BytesToStruct(bytes, &login)\n\n\t// Checks if struct is a valid one\n\tif err = validation.Validator.Struct(login); err != nil {\n\n\t\tlog.Printf(\"[WARN] invalid user information, because, %v\\n\", err)\n\t\tw.WriteHeader(http.StatusPreconditionFailed) // Status 412\n\t\treturn\n\t}\n\n\t// err1 consulta o login no banco de dados\n\terr1 := database.CheckLogin(login.Login)\n\n\t// err2 consulta a senha referente ao login fornecido\n\terr2 := database.CheckSenha(login.Login, login.Senha)\n\n\t// Condicao que verifica se os dois dados constam no banco de dados\n\tif (err1 != nil) || (err2 != true) {\n\t\tlog.Println(\"[FAIL]\")\n\t\tw.WriteHeader(http.StatusForbidden) // Status 403\n\t} else {\n\t\tlog.Println(\"[SUCCESS]\")\n\t\tw.WriteHeader(http.StatusAccepted) // Status 202\n\t}\n\n\treturn\n}", "func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\t_, err := req.Cookie(\"login\")\n\tif err == nil {\n\t\thttp.Redirect(res, req, \"app\", http.StatusSeeOther)\n\t}\n\tTPL.ExecuteTemplate(res, \"login\", nil)\n}", "func LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"login\")\n}", "func (h *auth) Login(c echo.Context) error {\n\t// Filter params\n\tvar params service.LoginParams\n\tif err := c.Bind(&params); err != nil {\n\t\tlog.Println(\"Could not get parameters:\", err)\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"Could not get credentials.\"))\n\t}\n\tparams.UserAgent = c.Request().UserAgent()\n\tparams.Session = currentSession(c)\n\n\tif params.Email == \"\" || params.Password == \"\" {\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"No email or password provided.\"))\n\t}\n\n\treturn h.login(c, params)\n\n}", "func ShowLoginPage(c *gin.Context) {\n\trender(c, gin.H{\n\t\t\"title\": \"Login\",\n\t}, \"login.html\")\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\n\t// Start the session.\n\tsession := sessions.Start(w, r)\n\tif len(session.GetString(\"username\")) != 0 && checkErr(w, r, err) {\n\t\t// Redirect to index page if the user isn't signed in. Will remove later.\n\t\thttp.Redirect(w, r, \"/\", 302)\n\t}\n\n\tif r.Method != \"POST\" {\n\t\tvar data = map[string]interface{}{\n\t\t\t\"Title\": \"Log In\",\n\t\t}\n\n\t\terr := templates.ExecuteTemplate(w, \"login.html\", data)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tusers := QueryUser(username)\n\n\t// Compare inputted password to the password in the database. If they're the same, return nil.\n\tvar password_compare = bcrypt.CompareHashAndPassword([]byte(users.Password), []byte(password))\n\n\tif password_compare == nil {\n\n\t\tsession := sessions.Start(w, r)\n\t\tsession.Set(\"username\", users.Username)\n\t\tsession.Set(\"user_id\", users.ID)\n\t\thttp.Redirect(w, r, \"/\", 302)\n\n\t} else {\n\n\t\thttp.Redirect(w, r, \"/login\", 302)\n\n\t}\n\n}", "func JLoginGET(w http.ResponseWriter, r *http.Request) {\n var params httprouter.Params\n\tsess := model.Instance(r)\n\n\tv := view.New(r)\n\tv.Vars[\"token\"] = csrfbanana.Token(w, r, sess)\n\n params = context.Get(r, \"params\").(httprouter.Params)\n cuenta := params.ByName(\"cuenta\")\n password := params.ByName(\"password\")\n stEnc, _ := base64.StdEncoding.DecodeString(password)\n\t password = string(stEnc)\n var jpers model.Jperson\n jpers.Cuenta = cuenta\n\tpass, err := (&jpers).JPersByCuenta()\n\tif err == model.ErrNoResult {\n loginAttempt(sess)\n\t} else {\n\t\tb:= passhash.MatchString(pass, password)\n if b && jpers.Nivel > 0{ var js []byte\n\t\t js, err = json.Marshal(jpers)\n if err == nil{\n\t\t\tmodel.Empty(sess)\n\t\t\tsess.Values[\"id\"] = jpers.Id\n sess.Save(r, w)\n w.Header().Set(\"Content-Type\", \"application/json\")\n w.Write(js)\n\t\t\treturn\n }\n\t }\n }\n log.Println(err)\n//\t http.Error(w, err.Error(), http.StatusBadRequest)\n http.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n }", "func genericLoginPage(s *data.Site, u *data.User) *contentBuffers {\n\tvar cb contentBuffers\n\n\tcb.head.WriteString(`<title>Log In</title><link rel=\"shortcut icon\" href=\"`)\n\tif s.Favicon == \"\" {\n\t\tcb.head.WriteString(userContentSrc + `favicon.png\">`)\n\t} else {\n\t\tcb.head.WriteString(s.Favicon + `\">`)\n\t}\n\n\tcb.head.WriteString(\"<style>#msg {color: #EF5350;}</style>\")\n\n\tcb.body.WriteString(\"<h2>Log in to your account</h2>\")\n\n\tif u.Role != users.RoleNone {\n\t\tcb.body.WriteString(`<h4 id=\"msg\">You are already logged in as the user: ` + u.Uname + `</h4>`)\n\t\tcb.body.WriteString(`<form action=\"/api/user/logout\" method=\"POST\"><input type=\"submit\" value=\"Log Out\"></form>`)\n\t} else {\n\t\tcb.body.WriteString(`<h4 id=\"msg\"></h4>\n\t\t<form action=\"/api/user/login-form\" method=\"POST\">\n\t\t\t<label for=\"user\">Username or Email Address</label><br>\n\t\t\t<input type=\"text\" name=\"user\" id=\"user\"><br>\n\t\t\t<label for=\"pass\">Password</label><br>\n\t\t\t<input type=\"password\" name=\"pass\" id=\"pass\"><br>\n\t\t\t<input type=\"submit\" value=\"Log In\">\n\t\t</form>\n\t\t<script>\n\t\t\tvar msgR = new RegExp(/msg=([^&]*)/);\n\t\t\tconst msgMatch = msgR.exec(window.location.search);\n\t\t\tif (msgMatch) {\n\t\t\t\tif (msgMatch[1] !== \"\") { document.getElementById(\"msg\").innerHTML = decodeURIComponent(msgMatch[1]); }\n\t\t\t}\n\t\t</script>`)\n\t}\n\n\treturn &cb\n}", "func Login(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\ttmp := []string{\n\t\t\"user.login\",\n\t\t\"default.layout\",\n\t\t\"default.navigation\",\n\t}\n\thelper.ProcessTemplates(w, \"layout\", nil, tmp...)\n}", "func Login(c *gin.Context) {\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\temail := c.PostForm(\"email\")\n\t//check if provided user credentials are valid or not\n\tif store.ValidUser(username, password, email) {\n\t\ttoken := generateSessionToken()\n\t\tc.SetCookie(\"token\", token, 3600, \"\", \"\", false, true)\n\t\tc.Set(\"is_logged_in\", true)\n\t\trender(c, gin.H{\n\t\t\t\"title\": \"Successful Login\"}, \"login-successful.html\")\n\t} else {\n\t\tc.HTML(http.StatusBadRequest, \"login.html\", gin.H{\n\t\t\t\"ErrorTitle\": \"Login Failed\",\n\t\t\t\"ErrorMessage\": \"Invalid credentials provided\"})\n\t}\n}", "func LoadLoginPage(w http.ResponseWriter, r *http.Request) {\n\tcookie, _ := cookies.Read(r)\n\n\tif cookie[\"token\"] != \"\" {\n\t\thttp.Redirect(w, r, \"/feed\", 302)\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"login.html\", nil)\n}", "func HandleLogin(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tServeHandleIncorrect(w, r)\n\t\treturn\n\t}\n\tvalues := LoginFormValues{}\n\tdecoder := schema.NewDecoder()\n\terr = decoder.Decode(&values, r.PostForm)\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\n\tacc, err := data.GetAccountByHandle(values.Handle)\n\tif err == mgo.ErrNotFound {\n\t\tServeHandleIncorrect(w, r)\n\t\treturn\n\t}\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tm := acc.Password.Match(values.Password)\n\tif !m {\n\t\thttp.Redirect(w, r, \"/login\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tsess, err := store.Get(r, \"s\")\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tsess.Values[\"accountID\"] = acc.ID.Hex()\n\tsess.Save(r, w)\n\thttp.Redirect(w, r, \"/tasks\", http.StatusSeeOther)\n}", "func loginHandler(res http.ResponseWriter, req *http.Request) {\n\tdefer server.LogRequest(req, http.StatusFound)\n\tcounter.Increment(\"login\")\n\n\t// get the requested username\n\tusername := req.FormValue(\"name\")\n\tif len(username) < 1 {\n\t\trenderBaseTemplate(res, \"login_error.html\", nil)\n\t} else {\n\t\terr := session.Create(res, username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\thttp.Redirect(res, req, \"/index.html\", http.StatusFound)\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Login endpoint hit\")\n\t\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tuser := models.User{}\n\n\tif user.Authorise(username, password) {\n\t\tjson.NewEncoder(w).Encode(user)\n\t} else {\n\t\tm := make(map[string]string)\n\t\tm[\"Message\"] = \"Username and password do not match\"\n\t\tjson.NewEncoder(w).Encode(m)\n\t}\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\ttmpl := template.Must(template.ParseFiles(\"templates/login.html\"))\n\tif r.Method != http.MethodPost {\n\t\ttmpl.Execute(w, nil)\n\t}\n\n\tdetails := userLogin{\n\t\tUsername: r.FormValue(\"username\"),\n\t\tPassword: r.FormValue(\"psw\"),\n\t}\n\n\tlog.Println(details)\n\t//Attempt login by calling LDAP verify credentials\n\tlog.Println(\"Username: \" + details.Username)\n\tlog.Println(\"Pass: \" + details.Password)\n\tauth := verifyCredentials(details.Username, details.Password)\n\tlog.Println(auth)\n\n\t//authorize user and create JWT\n\tif auth {\n\t\tfmt.Println(\"starting auth ...\")\n\t\tfor _, cookie := range r.Cookies() {\n\t\t\tfmt.Print(\"Cookie User: \")\n\t\t\tfmt.Println(w, cookie.Name)\n\t\t\treadJWT(cookie.Name)\n\t\t}\n\t\ttoken := generateJWT(details.Username)\n\t\tsetJwtCookie(token, w, r)\n\t\thttp.Redirect(w, r, \"/dashboard\", http.StatusSeeOther)\n\t}\n\n}", "func (app *application) login(w http.ResponseWriter, r *http.Request) {\n\tsession, err := app.sessionStore.Get(r, \"session-name\")\n\tif err != nil {\n\t\tapp.serverError(w, err)\n\t\treturn\n\t}\n\terr = r.ParseForm()\n\tif err != nil {\n\t\tapp.clientError(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\tform := forms.New(r.PostForm)\n\tform.Required(\"email\", \"password\")\n\tform.MatchesPattern(\"email\", forms.RxEmail)\n\tif !form.Valid() {\n\t\tapp.render(w, r, \"login.page.tmpl\", &templateData{Form: form})\n\t\treturn\n\t}\n\tvar id int\n\tif form.Get(\"accType\") == \"customer\" {\n\t\tid, err = app.customers.Authenticate(form.Get(\"email\"), form.Get(\"password\"))\n\t\tif err == models.ErrInvalidCredentials {\n\t\t\tform.Errors.Add(\"generic\", \"Email or Password Incorrect. Please ensure you have selected correct account type\")\n\t\t\tapp.render(w, r, \"login.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\tsession.Values[\"customerID\"] = id\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/customer/home\", http.StatusSeeOther)\n\t} else {\n\t\tid, err = app.vendors.Authenticate(form.Get(\"email\"), form.Get(\"password\"))\n\t\tif err == models.ErrInvalidCredentials {\n\t\t\tform.Errors.Add(\"generic\", \"Email or Password Incorrect. Please ensure you have selected correct account type\")\n\t\t\tapp.render(w, r, \"login.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\tsession.Values[\"vendorID\"] = id\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/vendor/home\", http.StatusSeeOther)\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tdata := authInfo{}\n\terr := json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\tutils.JSONRespnseWithErr(w, &utils.ErrPostDataNotCorrect)\n\t\treturn\n\t}\n\tmessage := models.Login(data.Email, data.Password)\n\tutils.JSONResonseWithMessage(w, message)\n}", "func Login(res http.ResponseWriter, req *http.Request) (bool, string) {\n\tname := req.FormValue(NameParameter)\n\tname = html.EscapeString(name)\n\tlog.Debugf(\"Log in user. Name: %s\", name)\n\tif name != \"\" {\n\t\tuuid := generateRandomUUID()\n\t\tsuccess := authClient.SetRequest(uuid, name)\n\t\tif success {\n\t\t\tcookiesManager.SetCookieValue(res, CookieName, uuid)\n\t\t}\n\t\t// successfully loged in\n\t\tif success {\n\t\t\treturn success, \"\"\n\t\t} else {\n\t\t\treturn success, \"authServerFail\"\n\t\t}\n\n\t}\n\n\treturn false, \"noName\"\n}", "func Login() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\temail := r.FormValue(\"email\")\n\t\t// validate email\n\t\tpw := r.FormValue(\"pw\")\n\t\t// validate pass\n\n\t\tlog.Println(\"email:\", email)\n\t\tlog.Println(\"pw:\", pw)\n\t}\n}", "func Login(username string, password string) error {\n\tdata := url.Values{}\n\tdata.Set(\"login\", username)\n\tdata.Set(\"haslo\", password)\n\n\tres, err := http.Post(loginURL, \"application/x-www-form-urlencoded\", strings.NewReader(data.Encode()))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to make HTTP POST login request: %v\", err)\n\t}\n\n\tlog.Println(\"auth status:\", res.Status)\n\n\treturn nil\n}", "func (s *HttpServer) loginForm(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\ts.RenderTemplate(ctx, w, \"login\", nil)\n}", "func LoginPage(w http.ResponseWriter, r *http.Request) { \n tmpl, err := template.ParseFiles(\"templates/loginPage.html\")\n if err != nil {\n fmt.Println(err)\n }\n var user helpers.User\n credentials := userCredentials{\n EmailId: r.FormValue(\"emailId\"),\n Password: r.FormValue(\"password\"), \n }\n\n login_info := dbquery.GetUserByEmail(credentials.EmailId)\n user = helpers.User{\n UserId: login_info.UserId,\n FirstName: login_info.FirstName,\n LastName: login_info.LastName, \n Role: login_info.Role,\n Email: login_info.Email,\n \n }\n\n var emailValidation string\n\n _userIsValid := CheckPasswordHash(credentials.Password, login_info.Password)\n\n if !validation(login_info.Email, credentials.EmailId, login_info.Password, credentials.Password) {\n emailValidation = \"Please enter valid Email ID/Password\"\n }\n\n if _userIsValid {\n setSession(user, w)\n http.Redirect(w, r, \"/dashboard\", http.StatusFound)\n }\n\n var welcomeLoginPage string\n welcomeLoginPage = \"Login Page\"\n\n tmpl.Execute(w, Response{WelcomeMessage: welcomeLoginPage, ValidateMessage: emailValidation}) \n \n}", "func loginprompt(w http.ResponseWriter, r *http.Request) {\n\t_, tid := GetAndOrUpdateSession(w, r)\n\tif tid != \"\" {\n\t\tshowMessage(w, \"Error: already logged in\",\n\t\t\t\"You are already logged in\", tid, \"\")\n\t\treturn\n\t}\n\ttemplate.Must(template.New(\"\").Parse(tLoginPrompt)).Execute(w, map[string]string{\n\t\t\"PageTitle\": \"Please log in\",\n\t\t\"Team\": r.FormValue(\"team\"),\n\t\t// TODO URL escaping would be pretty sweet\n\t\t\"TeamURL\": url.QueryEscape(r.FormValue(\"team\")),\n\t})\n}", "func (h *AuthHandlers) Login(w http.ResponseWriter, req *http.Request) {\n\tvar err error\n\tvar data []byte\n\n\tsystemContext, err := h.getSystemContext(req)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"request context retrevial failure\")\n\t\tmiddleware.ReturnError(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tif data, err = ioutil.ReadAll(req.Body); err != nil {\n\t\tlog.Error().Err(err).Msg(\"read body error\")\n\t\tmiddleware.ReturnError(w, \"error reading login data\", 500)\n\t\treturn\n\t}\n\tdefer req.Body.Close()\n\n\tloginDetails := &authz.LoginDetails{}\n\tif err := json.Unmarshal(data, loginDetails); err != nil {\n\t\tlog.Error().Err(err).Msg(\"marshal body error\")\n\t\tmiddleware.ReturnError(w, \"error reading login data\", 500)\n\t\treturn\n\t}\n\n\tif err := h.validate.Struct(loginDetails); err != nil {\n\t\tmiddleware.ReturnError(w, \"validation failure \"+err.Error(), 500)\n\t\treturn\n\t}\n\tloginDetails.OrgName = strings.ToLower(loginDetails.OrgName)\n\tloginDetails.Username = strings.ToLower(loginDetails.Username)\n\n\tlog.Info().Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Msg(\"login attempt\")\n\n\torgData, err := h.getOrgByName(req.Context(), systemContext, loginDetails.OrgName)\n\tif err != nil {\n\t\tlog.Error().Err(err).Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Msg(\"failed to get organization from name\")\n\t\tmiddleware.ReturnError(w, \"login failed\", 403)\n\t\treturn\n\t}\n\n\tresults, err := h.authenticator.Login(req.Context(), orgData, loginDetails)\n\tif err != nil {\n\t\tlog.Error().Err(err).Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Msg(\"login failed\")\n\t\tif req.Context().Err() != nil {\n\t\t\tmiddleware.ReturnError(w, \"internal server error\", 500)\n\t\t\treturn\n\t\t}\n\t\tmiddleware.ReturnError(w, \"login failed\", 403)\n\t\treturn\n\t}\n\t// add subscription id to response\n\tresults[\"subscription_id\"] = fmt.Sprintf(\"%d\", orgData.SubscriptionID)\n\n\trespData, err := json.Marshal(results)\n\tif err != nil {\n\t\tmiddleware.ReturnError(w, \"marshal auth response failed\", 500)\n\t\treturn\n\t}\n\n\tlog.Info().Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Str(\"OrgCID\", orgData.OrgCID).Msg(\"setting orgCID in cookie\")\n\tif err := h.secureCookie.SetAuthCookie(w, results[\"access_token\"], orgData.OrgCID, orgData.SubscriptionID); err != nil {\n\t\tmiddleware.ReturnError(w, \"internal cookie failure\", 500)\n\t\treturn\n\t}\n\tw.WriteHeader(200)\n\tfmt.Fprint(w, string(respData))\n}", "func (s *Server) Login(w http.ResponseWriter, r *http.Request) {\n\tvar acc data.Account\n\t// получение данных JSON account\n\tif err := json.NewDecoder(r.Body).Decode(&acc); err != nil {\n\t\thttp.Error(w, e.DecodeError.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\ttoken, err := s.service.Login(&acc)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tw.Header().Set(\"Token\", token)\n\tfmt.Fprint(w, \"See in tab Headers.\")\n}", "func (this *Handle) pageLogin(w http.ResponseWriter, r *http.Request) {\n\tif this.user.CheckLogin(w, r) == true {\n\t\tthis.ToURL(w, r, \"/center\")\n\t\treturn\n\t} else {\n\t\tthis.ShowTemplate(w, r, \"login.html\", nil)\n\t\treturn\n\t}\n}", "func (uh *UserHandler) Login(w http.ResponseWriter, r *http.Request) {\n\n\terrMap := make(map[string]string)\n\tuser := uh.Authentication(r)\n\tif user != nil {\n\t\thttp.Redirect(w, r, \"/Dashboard\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tif r.Method == http.MethodGet {\n\t\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\n\t\ttoken, err := stringTools.CSRFToken(uh.CSRF)\n\t\tinputContainer := InputContainer{CSRF: token}\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tuh.Temp.ExecuteTemplate(w, \"LoginPage.html\", inputContainer)\n\t\treturn\n\t}\n\n\tif r.Method == http.MethodPost {\n\t\temail := r.FormValue(\"email\")\n\t\tpassword := r.FormValue(\"password\")\n\n\t\t// Validating CSRF Token\n\t\tcsrfToken := r.FormValue(\"csrf\")\n\t\tok, errCRFS := stringTools.ValidCSRF(csrfToken, uh.CSRF)\n\t\tif !ok || errCRFS != nil {\n\t\t\terrMap[\"csrf\"] = \"Invalid token used!\"\n\t\t}\n\n\t\terr := uh.UService.Login(email, password)\n\n\t\tif err != nil || len(errMap) > 0 {\n\t\t\terrMap[\"login\"] = \"Invalid email or password!\"\n\t\t\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\n\t\t\ttoken, _ := stringTools.CSRFToken(uh.CSRF)\n\t\t\tinputContainer := InputContainer{Error: errMap, CSRF: token}\n\t\t\tuh.Temp.ExecuteTemplate(w, \"LoginPage.html\", inputContainer)\n\t\t\treturn\n\t\t}\n\n\t\tnewSession := uh.configSess()\n\t\tclaims := stringTools.Claims(email, newSession.Expires)\n\t\tsession.Create(claims, newSession, w)\n\t\t_, err = uh.SService.StoreSession(newSession)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\thttp.Redirect(w, r, \"/Dashboard\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n}", "func (a *App) Login(w http.ResponseWriter, r *http.Request) {\n\tvar resp = map[string]interface{}{\"status\": \"success\", \"message\": \"logged in\"}\n\n\tuser := &models.User{}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tuser.Prepare() // here strip the text of white spaces\n\n\terr = user.Validate(\"login\") // fields(email, password) are validated\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tusr, err := user.GetUser(a.DB)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tif usr == nil { // user is not registered\n\t\tresp[\"status\"] = \"failed\"\n\t\tresp[\"message\"] = \"Login failed, please signup\"\n\t\tresponses.JSON(w, http.StatusBadRequest, resp)\n\t\treturn\n\t}\n\n\terr = models.CheckPasswordHash(user.Password, usr.Password)\n\tif err != nil {\n\t\tresp[\"status\"] = \"failed\"\n\t\tresp[\"message\"] = \"Login failed, please try again\"\n\t\tresponses.JSON(w, http.StatusForbidden, resp)\n\t\treturn\n\t}\n\ttoken, err := utils.EncodeAuthToken(usr.ID)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tresp[\"token\"] = token\n\tresponses.JSON(w, http.StatusOK, resp)\n\treturn\n}", "func login(w http.ResponseWriter,r *http.Request){\n\tsession,err:=store.Get(r,\"cookie-name\")\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\n\t// Where authentication could be done\n\tif r.FormValue(\"code\")!=\"code\"{\n\t\tif r.FormValue(\"code\")==\"\"{\n\t\t\tsession.AddFlash(\"must enter a code\")\n\t\t}\n\t\tsession.AddFlash(\"the code was incorrect\")\n\t\terr:=session.Save(r,w)\n\t\tif err!=nil{\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\thttp.Redirect(w,r,\"/forbiden\",http.StatusFound)\n\t\treturn\n\t}\n\tusername:=r.FormValue(\"username\")\n\tpassword:=r.FormValue(\"password\")\n\tuser:=&user{\n\t\tUserName: username,\n\t\tPassword: password,\n\t\tAuthenticated: true,\n\t}\n\tsession.Values[\"user\"]=user\n\terr=session.Save(r,w)\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\thttp.Redirect(w,r,\"/secret\",http.StatusFound)\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\tPrintln(\"Endpoint Hit: Login\")\n\tvar response struct {\n\t\tStatus bool\n\t\tMessage string\n\t\tData map[string]interface{}\n\t}\n\t// var response models.JwtResponse\n\t//CEK UDAH ADA YANG LOGIN ATAU BELUM\n\t// session := sessions.Start(w, r)\n\t// if len(session.GetString(\"email\")) != 0 && checkErr(w, r, err) {\n\t// \thttp.Redirect(w, r, \"/\", 302)\n\t// }\n\tjwtSignKey := \"notsosecret\"\n\tappName := \"Halovet\"\n\tvar message string\n\n\t//dapetin informasi dari Basic Auth\n\t// email, password, ok := r.BasicAuth()\n\t// if !ok {\n\t// \tmessage = \"Invalid email or password\"\n\t// \tw.Header().Set(\"Content-Type\", \"application/json\")\n\t// \tw.WriteHeader(200)\n\t// \tresponse.Status = false\n\t// \tresponse.Message = message\n\t// \tjson.NewEncoder(w).Encode(response)\n\t// \treturn\n\t// }\n\t//dapetin informasi dari form\n\temail := r.FormValue(\"email\")\n\tif _, status := ValidateEmail(email); status != true {\n\t\tmessage := \"Format Email Salah atau Kosong\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\tpassword := r.FormValue(\"password\")\n\tif _, status := ValidatePassword(password); status != true {\n\t\tmessage := \"Format Password Salah atau Kosong, Minimal 6 Karakter\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\tok, userInfo := mid.AuthenticateUser(email, password)\n\tif !ok {\n\t\tmessage = \"Invalid email or password\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\tclaims := models.TheClaims{\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tIssuer: appName,\n\t\t\tExpiresAt: time.Now().Add(LoginExpDuration).Unix(),\n\t\t},\n\t\tUser: userInfo,\n\t}\n\n\ttoken := jwt.NewWithClaims(\n\t\tJwtSigningMethod,\n\t\tclaims,\n\t)\n\n\tsignedToken, err := token.SignedString([]byte(jwtSignKey))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\t//tokennya dijadiin json\n\t// tokenString, _ := json.Marshal(M{ \"token\": signedToken })\n\t// w.Write([]byte(tokenString))\n\tdata := map[string]interface{}{\n\t\t\"jwtToken\": signedToken,\n\t\t\"user\": userInfo,\n\t}\n\n\t//RESPON JSON\n\tmessage = \"Login Succesfully\"\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tresponse.Status = true\n\tresponse.Message = message\n\tresponse.Data = data\n\tjson.NewEncoder(w).Encode(response)\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: \"token\",\n\t\tValue: signedToken,\n\t\tExpires: time.Now().Add(LoginExpDuration),\n\t})\n}", "func (app *application) loginForm(w http.ResponseWriter, r *http.Request) {\n\tapp.render(w, r, \"login.page.tmpl\", &templateData{\n\t\tForm: forms.New(nil),\n\t})\n}", "func (sry *Sryun) Login(res http.ResponseWriter, req *http.Request) (*model.User, bool, error) {\n\tusername := req.FormValue(\"username\")\n\tpassword := req.FormValue(\"password\")\n\n\tlog.Infoln(\"got\", username, \"/\", password)\n\n\tif username == sry.User.Login && password == sry.Password {\n\t\treturn sry.User, true, nil\n\t}\n\treturn nil, false, errors.New(\"bad auth\")\n}", "func Login(rw http.ResponseWriter, req *http.Request) {\n\n\tif req.Method == \"GET\" {\n\t\trw.Write([]byte(\"Only POST request allowed\"))\n\t} else {\n\n\t\t// Input from request body\n\t\tdec := json.NewDecoder(req.Body)\n\t\tvar t c.User\n\t\terr := dec.Decode(&t)\n\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\trw.Write(Rsp(err.Error(), \"Error in Decoding Data\"))\n\t\t\treturn\n\t\t}\n\n\t\t// Check if all parametes are there\n\t\tif Valid := c.ValidateCredentials(t); Valid != \"\" {\n\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\trw.Write(Rsp(err.Error(), \"Bad Request\"))\n\t\t\treturn\n\t\t}\n\n\t\t// Get existing data on user\n\t\tdt, err := db.GetUser(t.Roll)\n\t\tif err != nil {\n\t\t\tif err == sql.ErrNoRows {\n\t\t\t\trw.WriteHeader(http.StatusUnauthorized)\n\t\t\t\tresponse := c.Response{\n\t\t\t\t\tError: err.Error(),\n\t\t\t\t\tMessage: \"User Not registered\",\n\t\t\t\t}\n\t\t\t\tjson.NewEncoder(rw).Encode(response)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\t\treturn\n\t\t}\n\n\t\t// check if password is right\n\t\terr = auth.Verify(t.Password, dt.Password)\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusUnauthorized)\n\t\t\trw.Write(Rsp(err.Error(), \"Wrong Password\"))\n\t\t\treturn\n\t\t}\n\n\t\t// All good yaayy\n\t\trw.WriteHeader(http.StatusOK)\n\t\tmsg := fmt.Sprintf(\"Hey, User %s! Your roll is %d. \", dt.Name, dt.Roll)\n\n\t\t// get token to\n\t\ttokenString, err := auth.GetJwtToken(dt)\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\t\tresponse := c.Response{\n\t\t\t\tError: err.Error(),\n\t\t\t\tMessage: \"Error While getting JWT token\",\n\t\t\t}\n\t\t\tjson.NewEncoder(rw).Encode(response)\n\t\t\treturn\n\t\t}\n\t\trw.Write(RspToken(\"\", msg+\"This JWT Token Valid for next 12 Hours\", tokenString))\n\t}\n}", "func (app *application) loginForm(w http.ResponseWriter, r *http.Request) {\n\tapp.renderLogin(w, r, \"login.page.tmpl\", &templateDataLogin {\n\t\tForm: \t\t\tforms.New(nil),\n\t})\n}", "func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {\n\tvar d UserLoginRequest\n\tif err := json.NewDecoder(r.Body).Decode(&d); err != nil {\n\t\trender.BadRequest(w, r, \"invalid json string\")\n\t\treturn\n\t}\n\n\t//Check if email exists\n\tuser, err := h.Client.User.\n\t\tQuery().\n\t\tWhere(usr.Email(d.Email)).\n\t\tOnly(r.Context())\n\tif err != nil {\n\t\tswitch {\n\t\tcase ent.IsNotFound(err):\n\t\t\trender.NotFound(w, r, \"Email Doesn't exists\")\n\t\tcase ent.IsNotSingular(err):\n\t\t\trender.BadRequest(w, r, \"Invalid Email\")\n\t\tdefault:\n\t\t\trender.InternalServerError(w, r, \"Server Error\")\n\t\t}\n\t\treturn\n\t}\n\n\t// Verify the password\n\tif user.Password == d.Password {\n\t\tfmt.Println(\"User Verified. Log In Successful\")\n\t\trender.OK(w, r, user)\n\t\treturn\n\t}\n\trender.Unauthorized(w, r, \"Invalid Email or Password.\")\n}", "func LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tif username != \"\" && password != \"\" {\n\t\tauth := database.QuickGetAuth()\n\t\tnauth := &database.Auth{\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t}\n\n\t\tif auth.Equal(nauth) {\n\t\t\thttp.SetCookie(w, nauth.MakeCookie())\n\t\t\thttp.Redirect(w, r, \"/admin\", 301)\n\t\t} else {\n\t\t\thttp.Redirect(w, r, \"/admin/nono\", 301)\n\t\t}\n\t} else {\n\t\thttp.Redirect(w, r, \"/admin\", 301)\n\t}\n}", "func loginActionHandler(w http.ResponseWriter, r *http.Request) {\n\n\t// Read the private key\n\tpemData, err := ioutil.ReadFile(PRIVATE_KEY_FILE)\n\tcheckHttpError(err, w)\n\n\t// Extract the PEM-encoded data block\n\tblock, _ := pem.Decode(pemData)\n\tif block == nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif got, want := block.Type, \"RSA PRIVATE KEY\"; got != want {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Decode the RSA private key\n\tpriv, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tcheckHttpError(err, w)\n\n\t// Decode the Base64 into binary\n\tcipheredValue, err := base64.StdEncoding.DecodeString(r.FormValue(\"CipheredValue\"))\n\tcheckHttpError(err, w)\n\n\t// Decrypt the data\n\tvar out []byte\n\tout, err = rsa.DecryptPKCS1v15(rand.Reader, priv, cipheredValue)\n\tcheckHttpError(err, w)\n\n\t//home or login\n\tsession, _ := store.Get(r, \"goServerView\")\n\th := sha512.New()\n\th.Write(out)\n\tstr := base64.StdEncoding.EncodeToString(h.Sum([]byte{}))\n\n\tif str == config.Password {\n\t\tsession.Values[\"isConnected\"] = true\n\t\tsession.Values[\"user\"] = r.FormValue(\"User\")\n\t\tsession.Save(r, w)\n\t\thomeHandler(w, r)\n\t} else {\n\t\tsession.Values[\"isConnected\"] = false\n\t\tsession.AddFlash(\"Either the username or the password provided is wrong\")\n\t\tsession.Save(r, w)\n\t\tloginFormHandler(w, r)\n\t}\n}", "func IndexHandler(c *gin.Context) {\n\tval, _ := c.Cookie(\"auth\")\n\tif val != \"\" {\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/dashboard\")\n\t\treturn\n\t}\n\n\tc.HTML(http.StatusOK, \"login.html\", nil)\n}", "func LoginHandler(c *gin.Context) {\n\tval, _ := c.Cookie(\"auth\")\n\tif val != \"\" {\n\t\tc.Redirect(http.StatusOK, \"/dashboard\")\n\t\treturn\n\t}\n\n\tinfo := models.LoginInfo{\n\t\tEmail: c.Query(\"email\"),\n\t\tPassword: c.Query(\"password\"),\n\t}\n\n\tif info.Email == \"\" || info.Password == \"\" {\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/\")\n\t\treturn\n\t}\n\n\tif ok, err := crud.CheckLoginInfo(info); !ok || err != nil {\n\t\tc.HTML(http.StatusInternalServerError, \"login.html\", err.Error())\n\t}\n\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/dashboard\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/data\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/report\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/config\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/config/submit\", \"127.0.0.1\", false, false)\n\n\tc.Redirect(http.StatusTemporaryRedirect, \"/dashboard\")\n\treturn\n}", "func LoginHandler(ctx *gin.Context) {\n\tstate = randToken()\n\tsession := sessions.Default(ctx)\n\tsession.Set(\"state\", state)\n\tsession.Save()\n\tfmt.Println(\"LOGIN SESSION:\", session.Get(\"userid\"))\n\t// TODO create this page from a template\n\tloginPage := fmt.Sprintf(`\n\t<html>\n\t<title>Google Login</title>\n\t<body>\n\t<h3>Google Login</h3>\n\t<a href=\"%s\"><button>Login with Google</button></a>\n\t</body>\n\t</html>\n\t`, GetLoginURL(state))\n\tctx.Writer.Write([]byte(loginPage))\n}", "func LoginHandler(c *gin.Context) {\n\tsess := sessions.Default(c)\n\tinfo := sess.Flashes(\"info\")\n\terrors := sess.Flashes(\"error\")\n\tsess.Save()\n\n\tc.HTML(http.StatusOK, \"login.html\", gin.H{\n\t\t\"errors\": errors,\n\t\t\"info\": info,\n\t})\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\tauth.GetGatekeeper().Login(w, r)\n}", "func Login(c *gin.Context) {\n\tvar form model.LoginForm\n\terr := c.BindJSON(&form)\n\tif err != nil {\n\t\tfailMsg(c, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tvalid, errMsg := validInfo(form)\n\tif !valid {\n\t\tfailMsg(c, http.StatusBadRequest, errMsg)\n\t\treturn\n\t}\n\tvalid = model.VerifyLogin(form)\n\tif !valid {\n\t\tfailMsg(c, http.StatusUnauthorized, \"wrong username or password\")\n\t\treturn\n\t}\n\ttoken, err := model.GenerateToken(form.Username)\n\tif err != nil {\n\t\tfailMsg(c, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"success\": true,\n\t\t\"error\": \"\",\n\t\t\"data\": \"Bearer \" + token,\n\t})\n\n}", "func Login(c *gin.Context) {\n\t// check if request was a POST\n\tif strings.EqualFold(c.Request.Method, \"POST\") {\n\t\t// assume all POST requests are coming from the CLI\n\t\tAuthenticateCLI(c)\n\n\t\treturn\n\t}\n\n\t// capture an error if present\n\terr := c.Request.FormValue(\"error\")\n\tif len(err) > 0 {\n\t\t// redirect to initial login screen with error code\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/login/error?code=\"+err)\n\t}\n\n\t// redirect to our authentication handler\n\tc.Redirect(http.StatusTemporaryRedirect, \"/authenticate\")\n}", "func (c *LoginController) ShowLogin(ctx *app.ShowLoginLoginContext) error {\n\t// LoginController_ShowLogin: start_implement\n\tloginError := map[string]interface{}{}\n\tc.SessionStore.GetAs(\"loginError\", &loginError, ctx.Request)\n\n\ttemplateContent, err := ioutil.ReadFile(\"public/login/login-form.html\")\n\tif err != nil {\n\t\treturn ctx.InternalServerError(err)\n\t}\n\n\tt, err := template.New(\"login-form\").Parse(string(templateContent))\n\tif err != nil {\n\t\treturn ctx.InternalServerError(err)\n\t}\n\n\tresponseCode := 200\n\n\tif loginErrorCode, ok := loginError[\"code\"]; ok {\n\t\tresponseCode = loginErrorCode.(int)\n\t}\n\n\trw := ctx.ResponseWriter\n\n\trw.Header().Set(\"Content-Type\", \"text/html\")\n\terr = t.Execute(rw, loginError)\n\trw.WriteHeader(responseCode)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t}\n\t// LoginController_ShowLogin: end_implement\n\treturn nil\n}", "func Login(c *soso.Context) {\n\treq := c.RequestMap\n\trequest := &auth_protocol.LoginRequest{}\n\n\tif value, ok := req[\"phone\"].(string); ok {\n\t\trequest.PhoneNumber = value\n\t}\n\n\tif value, ok := req[\"password\"].(string); ok {\n\t\trequest.Password = value\n\t}\n\n\tif request.Password == \"\" || request.PhoneNumber == \"\" {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"Phone number and password is required\"))\n\t\treturn\n\t}\n\tctx, cancel := rpc.DefaultContext()\n\tdefer cancel()\n\tresp, err := authClient.Login(ctx, request)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tif resp.ErrorCode != 0 {\n\t\tc.Response.ResponseMap = map[string]interface{}{\n\t\t\t\"ErrorCode\": resp.ErrorCode,\n\t\t\t\"ErrorMessage\": resp.ErrorMessage,\n\t\t}\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(resp.ErrorMessage))\n\t\treturn\n\t}\n\n\ttokenData, err := auth.GetTokenData(resp.Token)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tuser, err := GetUser(tokenData.UID, true)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tc.SuccessResponse(map[string]interface{}{\n\t\t\"token\": resp.Token,\n\t\t\"user\": user,\n\t})\n}", "func Login(rw http.ResponseWriter, request *http.Request) {\n\n\tlog.Println(\"call Login\")\n\n\t// フォームデータのパース\n\terr := request.ParseForm()\n\tif err != nil {\n\t\toutputErrorLog(\"フォーム パース 失敗\", err)\n\t}\n\n\t// リクエストデータ取得\n\taccount := request.Form.Get(\"account\")\n\tpassword := request.Form.Get(\"password\")\n\tlog.Println(\"ユーザ:\", account)\n\n\t// ユーザデータ取得しモデルデータに変換\n\tdbm := db.ConnDB()\n\tuser := new(models.User)\n\trow := dbm.QueryRow(\"select account, name, password from users where account = ?\", account)\n\tif err = row.Scan(&user.Name, &user.Account, &user.Password); err != nil {\n\t\toutputErrorLog(\"ユーザ データ変換 失敗\", err)\n\t}\n\n\t// ユーザのパスワード認証\n\tif user.Password != password {\n\t\tlog.Println(\"ユーザ パスワード照合 失敗\")\n\t\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\n\tlog.Println(\"認証 成功\")\n\n\t// 認証が通ったら、セッション情報をDBに保存\n\tsessionID := generateSessionID(account)\n\tlog.Println(\"生成したセッションID:\", sessionID)\n\tnow := time.Now()\n\tresult, err := dbm.Exec(`INSERT INTO sessions\n\t\t(sessionID, account, expireDate)\n\t\tVALUES\n\t\t(?, ?, ?)\n\t\t`, sessionID, account, now.Add(1*time.Hour))\n\tnum, err := result.RowsAffected()\n\tif err != nil || num == 0 {\n\t\toutputErrorLog(\"セッション データ保存 失敗\", err)\n\t}\n\n\tlog.Println(\"セッション データ保存 成功\")\n\n\t// クッキーにセッション情報付与\n\tcookie := &http.Cookie{\n\t\tName: sessionIDName,\n\t\tValue: sessionID,\n\t}\n\thttp.SetCookie(rw, cookie)\n\n\t// HOME画面に遷移\n\thttp.Redirect(rw, request, \"/home\", http.StatusFound)\n}", "func (p *Base) Login() string {\n\treturn \"https://admin.thebase.in/users/login\"\n}", "func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\tvar data map[string]string\n\n\tresp, err := getBody(req)\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(resp, &data)\n\tif err != nil {\n\t\tlog.Panicln(\"login:\", err)\n\t}\n\n\tusername := data[\"username\"]\n\tpassword := data[\"password\"]\n\tuser, err := getUser(username)\n\tif err != nil {\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tsessID, err := authenticateUser(user, username, password)\n\tif err != nil {\n\t\tlog.Println(\"login:\", err)\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tresponse := jsMap{\n\t\t\"status\": \"OK\",\n\t\t\"sessionID\": hex.EncodeToString(sessID),\n\t\t\"address\": user.Address,\n\t}\n\n\twriteJSON(res, 200, response)\n}", "func (c *UserController) Login() {\n\n\tisAjax := c.GetString(\"isajax\")\n\n\tif isAjax == \"1\" {\n\t\t// Captcha Verification.\n\t\tif !cpt.VerifyReq(c.Ctx.Request) {\n\t\t\tc.Resp(false, \"验证码错误!\")\n\t\t\treturn\n\t\t}\n\n\t\t// Passing Captcha Verify.\n\t\tusername := c.GetString(\"username\")\n\t\tpassword := c.GetString(\"password\")\n\n\t\tuser, err := doLogin(username, password)\n\t\tif err == nil {\n\t\t\tc.SetSession(\"userinfo\", user.Username)\n\t\t\tc.Resp(true, \"登陆成功\")\n\t\t\treturn\n\t\t}\n\t\tc.Resp(false, err.Error())\n\t\treturn\n\t}\n\t// Login Fail! relogin.\n\tc.Data[\"Title\"] = beego.AppConfig.String(\"login_title\")\n\tc.Data[\"Copyright\"] = beego.AppConfig.String(\"copyright\")\n\n\t// Get Verification Code.\n\tcpt = captcha.NewWithFilter(\"/captcha/\", store)\n\tcpt.ChallengeNums, _ = beego.AppConfig.Int(\"captcha_length\")\n\tcpt.StdWidth = 100\n\tcpt.StdHeight = 42\n\n\tc.TplName = \"login.tpl\"\n}", "func Login() gin.HandlerFunc {\r\n\tif gin.Mode() == \"debug\" {\r\n\t\treturn func(c *gin.Context) { c.Next() }\r\n\t}\r\n\treturn func(c *gin.Context) {\r\n\t\tsession := sessions.Default(c)\r\n\t\tUserID := session.Get(\"UserID\")\r\n\t\tIsLeader := session.Get(\"IsLeader\")\r\n\r\n\t\tfmt.Println(\"UserID, IsLeader\", UserID, IsLeader)\r\n\t\tif UserID == nil {\r\n\t\t\tstate := string([]byte(c.Request.URL.Path)[1:])\r\n\t\t\tc.Redirect(http.StatusFound, \"/login?state=\"+state)\r\n\t\t\tc.Abort()\r\n\t\t} else {\r\n\t\t\tc.Set(\"UserID\", UserID)\r\n\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\t\t\tc.Next()\r\n\t\t}\r\n\r\n\t}\r\n}", "func IndexGET(w http.ResponseWriter, r *http.Request) {\n\t// Get session\n\tsession := session.Instance(r)\n\n\tif session.Values[\"id\"] != nil {\n\t\t// Display the view\n\t\tv := view.New(r)\n\t\tv.Name = \"index/auth\"\n\t\tv.Vars[\"first_name\"] = session.Values[\"first_name\"]\n\t\tv.Render(w)\n\t} else {\n\t\t// Display the view\n\t\tv := view.New(r)\n\t\tv.Name = \"index/anon\"\n\t\tv.Render(w)\n\t\treturn\n\t}\n}", "func (m *Manager) Login() error {\n\terr := m.useFreePort()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = m.openLoginPage()\n\tif err != nil {\n\t\tfmt.Println(\"Failed to open the login page, open the following link in your browser:\")\n\t}\n\tfmt.Println(loginURL)\n\terr = m.retrieveTokensFromServer()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tutils.Error(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tvar user models.User\n\tif err = json.Unmarshal(body, &user); err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tdb, error := database.Connect()\n\tif error != nil {\n\t\tutils.Error(w, http.StatusInternalServerError, error)\n\t\treturn\n\t}\n\tdefer db.Close()\n\tuserRepo := repository.NewUserRepo(db)\n\tuserFound, err := userRepo.FindByEmail(user.Email)\n\tif error != nil {\n\t\tutils.Error(w, http.StatusInternalServerError, error)\n\t\treturn\n\t}\n\tif err = hash.Verify(user.Password, userFound.Password); err != nil {\n\t\tutils.Error(w, http.StatusUnauthorized, err)\n\t\treturn\n\t}\n\ttoken, err := authentication.Token(userFound.ID)\n\tif err != nil {\n\t\tutils.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tw.Write([]byte(token))\n}", "func (a *App) Login(w http.ResponseWriter, r *http.Request) {\n\tvar loginInfo uvm.UserLoginVM\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar err error\n\n\tif err = decoder.Decode(&loginInfo); err != nil {\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid request body\")\n\t\treturn\n\t}\n\n\t//TODO validate user data\n\n\tuser := a.UserStore.GetUserByEmail(loginInfo.Email)\n\n\tif user.ID == \"\" || utils.CheckPasswordHash(loginInfo.Password, user.Password) {\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid credentials\")\n\t\treturn\n\t}\n\n\ttoken := auth.GenerateToken(a.APISecret, user)\n\n\tresult := models.UserResult{\n\t\tUsername: user.Username,\n\t\tPicture: user.Picture,\n\t\tRole: user.Role.Name,\n\t\tToken: token,\n\t}\n\n\trespondWithJSON(w, http.StatusOK, result)\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tuser := models.User{}\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\tuser.Prepare()\n\terr = user.Validate(\"login\")\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\ttoken, err := auth.SignIn(user.Email, user.Password)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, token)\n}", "func (h *GitHubOAuth) Login(c *router.Control) {\n\turl := h.oAuthConf.AuthCodeURL(h.state, oauth2.AccessTypeOnline)\n\thttp.Redirect(c.Writer, c.Request, url, http.StatusTemporaryRedirect)\n}", "func (httpcalls) Login(url string, jsonData []byte, client http.Client) (*http.Response, error) {\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Add(\"Content-type\", \"application/json\")\n\tresp, err := client.Do(req)\n\treturn resp, err\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\tlogRequest(r)\n\n\t// Get a session. Get() always returns a session, even if empty.\n\tsession, err := store.Get(r, \"auth\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tuser := User{}\n\tquery := fmt.Sprintf(\n\t\t`SELECT username, access_level FROM users WHERE username='%s'\n\t\tAND password = crypt('%s', password)`, username, password)\n\tdb.Get(&user, query)\n\n\tif user.Username != \"\" {\n\t\tsession.Values[\"user\"] = user\n\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusUnauthorized)\n}", "func Login(user, passd string) (string, error) {\n\tt := TpaasLogin{Username: user, Password: passd}\n\n\tclient := gorequest.New().Post(loginUrl()).\n\t\tTimeout(HttpTimeout * time.Second).\n\t\tType(\"json\").\n\t\tSend(t)\n\n\tresp, body, ierrors := client.End()\n\tif len(ierrors) != 0 {\n\t\treturn \"\", ierrors[0]\n\t}\n\n\tif !HttpOK(resp.StatusCode) {\n\t\treturn \"\", errors.Errorf(\"http code:%d body:%s\", resp.StatusCode, body)\n\t}\n\n\tvar lg TpaasLoginResp\n\terr := json.Unmarshal([]byte(body), &lg)\n\tif err != nil {\n\t\treturn \"\", errors.WithMessage(err, \"logining response from tpaas is not json\")\n\t}\n\tif !HttpOK(lg.Code) {\n\t\treturn \"\", errors.Errorf(\"tpaas code:%d body:%s\", lg.Code, body)\n\t}\n\treturn lg.Data.Token, nil\n}", "func LoginPost(ctx echo.Context) error {\n\tvar flashMessages = flash.New()\n\tf := forms.New(utils.GetLang(ctx))\n\tlf, err := f.DecodeLogin(ctx.Request())\n\tif err != nil {\n\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\treturn nil\n\t}\n\tif !lf.Valid() {\n\t\tfor k, v := range lf.Ctx() {\n\t\t\tflashMessages.AddCtx(k, v)\n\t\t}\n\t\tflashMessages.Save(ctx)\n\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\treturn nil\n\t}\n\tvar user *models.User\n\tif validate.IsEmail(lf.Name) {\n\t\tuser, err = query.AuthenticateUserByEmail(db.Conn, *lf)\n\t\tif err != nil {\n\t\t\tlog.Error(ctx, err)\n\n\t\t\t// We want the user to try again, but rather than rendering the form right\n\t\t\t// away, we redirect him/her to /auth/login route(where the login process with\n\t\t\t// start aflsesh albeit with a flash message)\n\t\t\tflashMessages.Err(settings.FlashLoginErr)\n\t\t\tflashMessages.Save(ctx)\n\t\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\tuser, err = query.AuthenticateUserByName(db.Conn, *lf)\n\t\tif err != nil {\n\t\t\tlog.Error(ctx, err)\n\n\t\t\t// We want the user to try again, but rather than rendering the form right\n\t\t\t// away, we redirect him/her to /auth/login route(where the login process with\n\t\t\t// start aflsesh albeit with a flash message)\n\t\t\tflashMessages.Err(settings.FlashLoginErr)\n\t\t\tflashMessages.Save(ctx)\n\t\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// create a session for the user after the validation has passed. The info stored\n\t// in the session is the user ID, where as the key is userID.\n\tss, err := sessStore.Get(ctx.Request(), settings.App.Session.Name)\n\tif err != nil {\n\t\tlog.Error(ctx, err)\n\t}\n\tss.Values[\"userID\"] = user.ID\n\terr = ss.Save(ctx.Request(), ctx.Response())\n\tif err != nil {\n\t\tlog.Error(ctx, err)\n\t}\n\tperson, err := query.GetPersonByUserID(db.Conn, user.ID)\n\tif err != nil {\n\t\tlog.Error(ctx, err)\n\t\tflashMessages.Err(settings.FlashLoginErr)\n\t\tflashMessages.Save(ctx)\n\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\treturn nil\n\t}\n\n\t// add context data. IsLoged is just a conveniece in template rendering. the User\n\t// contains a models.Person object, where the PersonName is already loaded.\n\tutils.SetData(ctx, \"IsLoged\", true)\n\tutils.SetData(ctx, \"User\", person)\n\tflashMessages.Success(settings.FlashLoginSuccess)\n\tflashMessages.Save(ctx)\n\tctx.Redirect(http.StatusFound, \"/\")\n\treturn nil\n}", "func (c *client) Login(w http.ResponseWriter, r *http.Request) (string, error) {\n\tlogrus.Trace(\"Processing login request\")\n\n\t// generate a random string for creating the OAuth state\n\toAuthState, err := random.GenerateRandomString(32)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// temporarily redirect request to Github to begin workflow\n\thttp.Redirect(w, r, c.OConfig.AuthCodeURL(oAuthState), http.StatusTemporaryRedirect)\n\n\treturn oAuthState, nil\n}", "func Login(c *gin.Context) {\n\turl := GithubAuth.AuthCodeURL(\"state\", oauth2.AccessTypeOffline)\n\tc.Redirect(http.StatusFound, url)\n}", "func (controller *Auth) ShowLoginPage() {\n\tif controller.AccountConnected {\n\t\tcontroller.Redirect(\"/\", 302)\n\t} else {\n\t\tcontroller.showLoginForm()\n\t}\n}" ]
[ "0.78163654", "0.75899374", "0.7468364", "0.7320955", "0.7160428", "0.691093", "0.68139416", "0.6773794", "0.675614", "0.6752772", "0.66593784", "0.66468394", "0.6646164", "0.66439223", "0.6637479", "0.6600472", "0.659737", "0.65903026", "0.6589105", "0.65679455", "0.65355605", "0.65296197", "0.65190303", "0.6484801", "0.64555156", "0.6447445", "0.64286613", "0.6410929", "0.64101624", "0.64088815", "0.64053816", "0.63857985", "0.63820815", "0.63772017", "0.6375736", "0.63707024", "0.6367302", "0.63463825", "0.6330498", "0.63217777", "0.6312718", "0.6288135", "0.62855935", "0.6277289", "0.6270144", "0.6265177", "0.6260917", "0.6246118", "0.62407815", "0.6203026", "0.6181901", "0.61617297", "0.6160355", "0.61577904", "0.6150643", "0.6133868", "0.6130904", "0.612645", "0.6125379", "0.6122173", "0.6120974", "0.6119169", "0.6113575", "0.6109388", "0.61058736", "0.61032045", "0.60958856", "0.6095299", "0.60930747", "0.6082655", "0.6073187", "0.6071619", "0.6053984", "0.6051797", "0.603707", "0.6035718", "0.6031637", "0.60305035", "0.6021301", "0.6017578", "0.6014255", "0.60013604", "0.5996308", "0.5991944", "0.5990754", "0.5985269", "0.59849125", "0.59794366", "0.59716153", "0.5956889", "0.59475857", "0.5941461", "0.5940636", "0.59397936", "0.5938325", "0.59339786", "0.5930632", "0.5930307", "0.59288764", "0.591727" ]
0.801604
0
LoginPOST handles the login form submission
func LoginPOST(w http.ResponseWriter, r *http.Request) { sess := model.Instance(r) // Validate with required fields if validate, missingField := view.Validate(r, []string{"cuenta", "pass"}); !validate { sess.AddFlash(view.Flash{"Falta campo: " + missingField, view.FlashError}) sess.Save(r, w) LoginGET(w, r) return } // Prevenir intentos login de fuerza bruta pretendiendo entrada invalida :-) if sess.Values[sessLoginAttempt] != nil && sess.Values[sessLoginAttempt].(int) >= 3 { log.Println("Intentos de Entrada Repetidos en Exceso") sess.AddFlash(view.Flash{"No mas intentos :-)", view.FlashNotice}) sess.Save(r, w) LoginGET(w, r) return } // Form values cuenta := r.FormValue("cuenta") password := r.FormValue("pass") // Get database user var user model.User user.Cuenta = cuenta err := (&user).UserByCuenta() if err == model.ErrNoResult { loginAttempt(sess) sess.AddFlash(view.Flash{"Cuenta incorrecta - Intento: " + fmt.Sprintf("%v", sess.Values[sessLoginAttempt]), view.FlashWarning}) log.Println("Cuenta Incorreta ", err) } else if err != nil { log.Println(" Error busqueda ",err) sess.AddFlash(view.Flash{"Un error. Favor probar mas tarde.", view.FlashError}) sess.Save(r, w) } else if passhash.MatchString(user.Password, password) { if user.Nivel == 0 { sess.AddFlash(view.Flash{"Cuenta inactiva entrada prohibida.", view.FlashNotice}) // sess.Save(r, w) } else { // Login successfully model.Empty(sess) sess.AddFlash(view.Flash{"Entrada exitosa!", view.FlashSuccess}) sess.Values["id"] = user.Id sess.Values["cuenta"] = cuenta sess.Values["level"] = user.Nivel sess.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) return } } else { loginAttempt(sess) sess.AddFlash(view.Flash{"Clave incorrecta - Intento: " + fmt.Sprintf("%v", sess.Values[sessLoginAttempt]), view.FlashWarning}) sess.Save(r, w) } // Show the login page again LoginGET(w, r) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Login) LoginPostHandler(rw http.ResponseWriter, r *http.Request) {\n\t// Create struct of form data to handle possible errors.\n\tformData := web_models.Login{\n\t\tUsername: r.FormValue(\"username\"),\n\t\tPassword: r.FormValue(\"password\"),\n\t\tMessages: &web_models.FormMessages{}}\n\n\tuser, err := c.Load(formData.Username)\n\tlog.Println(user)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tif formData.Validate(user, err) == false {\n\t\t// If errors found render form with errors.\n\t\terr := c.Base.Templates.Templates.ExecuteTemplate(rw, \"login.html\", formData)\n\t\tif err != nil {\n\t\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t} else {\n\t\t// Set user session.\n\t\tc.Base.SetSessionKey(\"client-logged\", user.Username, rw, r)\n\t\thttp.Redirect(rw, r, c.RedirectAfter, http.StatusSeeOther)\n\t}\n}", "func (m *Repository) PostLogin(w http.ResponseWriter, r *http.Request) {\n\t_ = m.App.Session.RenewToken(r.Context())\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tm.App.ErrorLog.Println(\"Error parsing login form\")\n\t\tm.App.Session.Put(r.Context(), \"error\", \"Error parsing form\")\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\temail := r.Form.Get(\"email\")\n\tpassword := r.Form.Get(\"password\")\n\n\tform := forms.New(r.PostForm)\n\tform.Required(\"email\", \"password\")\n\tform.IsEmail(\"email\")\n\tif !form.Valid() {\n\t\trender.Template(w, r, \"login.page.tmpl\", &models.TemplateData{\n\t\t\tForm: form,\n\t\t})\n\t\treturn\n\t}\n\n\tid, _, err := m.DB.Authenticate(email, password)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tm.App.Session.Put(r.Context(), \"error\", \"Invalid login credentials!\")\n\t\thttp.Redirect(w, r, \"/user/login\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tm.App.Session.Put(r.Context(), \"user_id\", id)\n\tm.App.Session.Put(r.Context(), \"flash\", \"Logged in Successfully!\")\n\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\n}", "func (e *env) LoginPostHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\tcase \"POST\":\n\t\t// Handle login POST request\n\t\tusername := r.FormValue(\"username\")\n\t\tpassword := r.FormValue(\"password\")\n\n\t\t// Login authentication\n\t\tif e.authState.Auth(username, password) {\n\t\t\te.authState.Login(username, r)\n\t\t\te.authState.SetFlash(\"User '\"+username+\"' successfully logged in.\", r)\n\t\t\t// Check if we have a redirect URL in the cookie, if so redirect to it\n\t\t\tredirURL := e.authState.GetRedirect(r)\n\t\t\tif redirURL != \"\" {\n\t\t\t\thttp.Redirect(w, r, redirURL, http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\t\te.authState.SetFlash(\"User '\"+username+\"' failed to login. Please check your credentials and try again.\", r)\n\t\thttp.Redirect(w, r, e.authState.Cfg.LoginPath, http.StatusSeeOther)\n\t\treturn\n\tcase \"PUT\":\n\t\t// Update an existing record.\n\tcase \"DELETE\":\n\t\t// Remove the record.\n\tdefault:\n\t\t// Give an error message.\n\t}\n}", "func postLoginHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {\n\tname := r.FormValue(\"name\")\n\tpassword := r.FormValue(\"password\")\n\tif name != \"\" && password != \"\" {\n\t\tif authentication.LoginIsCorrect(name, password) {\n\t\t\tlogInUser(name, w)\n\t\t} else {\n\t\t\tlog.Println(\"Failed login attempt for user \" + name)\n\t\t}\n\t}\n\thttp.Redirect(w, r, \"/admin\", http.StatusFound)\n\treturn\n}", "func LoginPost(ctx echo.Context) error {\n\tvar flashMessages = flash.New()\n\tf := forms.New(utils.GetLang(ctx))\n\tlf, err := f.DecodeLogin(ctx.Request())\n\tif err != nil {\n\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\treturn nil\n\t}\n\tif !lf.Valid() {\n\t\tfor k, v := range lf.Ctx() {\n\t\t\tflashMessages.AddCtx(k, v)\n\t\t}\n\t\tflashMessages.Save(ctx)\n\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\treturn nil\n\t}\n\tvar user *models.User\n\tif validate.IsEmail(lf.Name) {\n\t\tuser, err = query.AuthenticateUserByEmail(db.Conn, *lf)\n\t\tif err != nil {\n\t\t\tlog.Error(ctx, err)\n\n\t\t\t// We want the user to try again, but rather than rendering the form right\n\t\t\t// away, we redirect him/her to /auth/login route(where the login process with\n\t\t\t// start aflsesh albeit with a flash message)\n\t\t\tflashMessages.Err(settings.FlashLoginErr)\n\t\t\tflashMessages.Save(ctx)\n\t\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\tuser, err = query.AuthenticateUserByName(db.Conn, *lf)\n\t\tif err != nil {\n\t\t\tlog.Error(ctx, err)\n\n\t\t\t// We want the user to try again, but rather than rendering the form right\n\t\t\t// away, we redirect him/her to /auth/login route(where the login process with\n\t\t\t// start aflsesh albeit with a flash message)\n\t\t\tflashMessages.Err(settings.FlashLoginErr)\n\t\t\tflashMessages.Save(ctx)\n\t\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// create a session for the user after the validation has passed. The info stored\n\t// in the session is the user ID, where as the key is userID.\n\tss, err := sessStore.Get(ctx.Request(), settings.App.Session.Name)\n\tif err != nil {\n\t\tlog.Error(ctx, err)\n\t}\n\tss.Values[\"userID\"] = user.ID\n\terr = ss.Save(ctx.Request(), ctx.Response())\n\tif err != nil {\n\t\tlog.Error(ctx, err)\n\t}\n\tperson, err := query.GetPersonByUserID(db.Conn, user.ID)\n\tif err != nil {\n\t\tlog.Error(ctx, err)\n\t\tflashMessages.Err(settings.FlashLoginErr)\n\t\tflashMessages.Save(ctx)\n\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\treturn nil\n\t}\n\n\t// add context data. IsLoged is just a conveniece in template rendering. the User\n\t// contains a models.Person object, where the PersonName is already loaded.\n\tutils.SetData(ctx, \"IsLoged\", true)\n\tutils.SetData(ctx, \"User\", person)\n\tflashMessages.Success(settings.FlashLoginSuccess)\n\tflashMessages.Save(ctx)\n\tctx.Redirect(http.StatusFound, \"/\")\n\treturn nil\n}", "func LoginPostHandler(writer http.ResponseWriter, request *http.Request) {\n\temail := request.FormValue(\"email\")\n\tpassword := request.FormValue(\"password\")\n\tredirectTarget := \"/\"\n\tif email != \"\" && password != \"\" {\n\t\trpLogger.Logger.Debug(email, \" login attempt.\")\n\t\tif checkPasswordHash(email, password) {\n\t\t\trpLogger.Logger.Info(email, \" login succeeded.\")\n\t\t\tsetSession(email, writer)\n\t\t\tredirectTarget = \"/internal\"\n\t\t} else {\n\t\t\trpLogger.Logger.Warn(email, \" login failed.\")\n\t\t\t//http.Error(writer, \"Login credentials incorrect\", 400)\n\t\t}\n\n\t}\n\thttp.Redirect(writer, request, redirectTarget, 302)\n}", "func LoginPostHandler(ctx *enliven.Context) {\n\tctx.Request.ParseForm()\n\tlogin := ctx.Request.Form.Get(\"username\")\n\tpassword := ctx.Request.Form.Get(\"password\")\n\n\tconf := config.GetConfig()\n\tdb := database.GetDatabase()\n\n\tuser := User{}\n\tvar where string\n\tif strings.Contains(login, \"@\") {\n\t\twhere = \"Email = ?\"\n\t} else {\n\t\twhere = \"Username = ?\"\n\t\tlogin = strings.ToLower(login)\n\t}\n\tdb.Where(where+\" AND Status = ?\", login, 1).First(&user)\n\n\tif user.ID == 0 || !VerifyPasswordHash(user.Password, password) {\n\t\tctx.Strings[\"LoginError\"] = \"Invalid Login or Password.\"\n\t\tLoginGetHandler(ctx)\n\t\treturn\n\t}\n\n\tctx.Session.Set(\"user_id\", strconv.FormatUint(uint64(user.ID), 10))\n\tctx.Redirect(conf[\"user_login_redirect\"])\n}", "func LoginPostHandler(c *gin.Context) {\n\tlog.Println(\"LoginPostHandler\")\n\n\tif IsLogin(c) {\n\t\tRedirect(c, \"/home\")\n\t}\n\n\temail := c.PostForm(\"email\")\n\tpassword := c.PostForm(\"password\")\n\n\taccount, err := models.LoginUser(email, password)\n\n\tif err != nil {\n\t\tSetFlashError(c, err.Error())\n\t\tRedirect(c, \"/register\")\n\t\treturn\n\t}\n\n\tSetAuth(c, *account)\n\tSetFlashSuccess(c, \"Login successful\")\n\tRedirect(c, \"/home\")\n}", "func (app *application) postLogin(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tapp.clientError(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\tform := forms.New(r.PostForm)\n\tform.Required(\"screenName\")\n\tform.MaxLength(\"screenName\", 16)\n\tform.Required(\"password\")\n\n\trowid, err := app.players.Authenticate(form.Get(\"screenName\"), form.Get(\"password\"))\n\tif err != nil {\n\t\tif errors.Is(err, models.ErrInvalidCredentials) {\n\t\t\tform.Errors.Add(\"generic\", \"Supplied credentials are incorrect\")\n\t\t\tapp.renderLogin(w, r, \"login.page.tmpl\", &templateDataLogin{Form: form})\n\t\t} else {\n\t\t\tapp.serverError(w, err)\n\t\t}\n\t\treturn\n\t}\n\t// Update loggedIn in database\n\tapp.players.UpdateLogin(rowid, true)\n\tapp.session.Put(r, \"authenticatedPlayerID\", rowid)\n\tapp.session.Put(r, \"screenName\", form.Get(\"screenName\"))\n\thttp.Redirect(w, r, \"/board/list\", http.StatusSeeOther)\n}", "func (web *Web) LoginPOST(w http.ResponseWriter, r *http.Request) {\n\n\tcred := struct {\n\t\tPassword string\n\t\tUsername string\n\t}{}\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\thandleWebErr(w, err)\n\t\treturn\n\t}\n\tif r.Form[\"loginUsername\"] == nil || r.Form[\"loginPassword\"] == nil {\n\t\thttp.Redirect(w, r, \"/login?status=2\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\trememberMe := false\n\n\tif r.Form[\"rememberMe\"] != nil && r.Form[\"rememberMe\"][0] == \"on\" {\n\t\trememberMe = true\n\t}\n\n\tcred.Username = r.Form[\"loginUsername\"][0]\n\tcred.Password = r.Form[\"loginPassword\"][0]\n\n\tuser, err := web.database.GetUserByUserName(cred.Username)\n\n\tvar expectedPassword string\n\tok := false\n\tif err != nil && err != mgo.ErrNotFound {\n\t\thandleWebErr(w, err)\n\t\treturn\n\t}\n\n\tif err == nil {\n\t\texpectedPassword = user.Password\n\t\tok = true\n\t}\n\n\tif !ok || expectedPassword != cred.Password {\n\t\thttp.Redirect(w, r, \"/login?status=2\", 303)\n\t\treturn\n\t}\n\n\tloginSession := newLoginSession(cred.Username)\n\n\tif rememberMe {\n\t\tloginSession.Validate = 0\n\t}\n\n\tsetSessionTokenCookie(w, *loginSession)\n\n\t_, err = web.storeSession(loginSession)\n\tif err != nil {\n\t\thandleWebErr(w, err)\n\t\treturn\n\t}\n\n\tif user.PasswordNeedChange && false {\n\t\t//TODO add change psw\n\t\thttp.Redirect(w, r, \"/\", 303)\n\t} else if r.Form[\"redirect\"] != nil {\n\t\thttp.Redirect(w, r, r.Form[\"redirect\"][0], 303)\n\t} else {\n\t\thttp.Redirect(w, r, \"/\", 303)\n\t}\n}", "func LoginPostHandler(c *gin.Context) {\n\tvar err error\n\tsess := sessions.Default(c)\n\n\t// Grab login information from the postform.\n\tusername := c.PostForm(\"user\")\n\tpassword := c.PostForm(\"pw\")\n\tusertype := c.PostForm(\"type\")\n\n\t// Compare the information provided by user and\n\t// the information in database.\n\tswitch usertype {\n\tcase \"student\":\n\t\terr = db.StudentLogin(username, password)\n\tcase \"faculty\":\n\t\terr = db.FacultyLogin(username, password)\n\tcase \"admin\":\n\t\tif username != setting.Admin.Username ||\n\t\t\tpassword != setting.Admin.Password {\n\t\t\terr = fmt.Errorf(\"用户名或密码不正确\")\n\t\t}\n\tdefault:\n\t\terr = fmt.Errorf(\"无效的身份信息\")\n\t}\n\n\t// Add a warning to log if someone attempted to login\n\t// but failed.\n\tif err != nil {\n\t\tlog.Warning(fmt.Sprintf(\n\t\t\t\"Failed login attempt: <%s> user %s from %s\",\n\t\t\tusertype, username, c.ClientIP(),\n\t\t))\n\n\t\t// Tell frontend the type of error, and go nowhere.\n\t\tsess.AddFlash(err.Error(), \"error\")\n\t\tsess.Save()\n\t\tc.HTML(http.StatusOK, \"login.html\", gin.H{\n\t\t\t\"errors\": sess.Flashes(\"error\"),\n\t\t\t\"info\": sess.Flashes(\"info\"),\n\t\t})\n\t\treturn\n\t}\n\n\t// If no error occurs, login succeeds.\n\tlog.Info(fmt.Sprintf(\n\t\t\"Succeeded login: <%s> %s from %s\",\n\t\tusertype, username, c.ClientIP(),\n\t))\n\n\t// Save the username of current user to the session.\n\tsess.Set(\"username\", username)\n\tsess.Set(\"usertype\", usertype)\n\tsess.Delete(\"error\")\n\tsess.Delete(\"info\")\n\tsess.Save()\n\n\t// Redirect user to the referer.\n\tc.Redirect(http.StatusFound, \"/auth/home\")\n}", "func HandleLogin(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tServeHandleIncorrect(w, r)\n\t\treturn\n\t}\n\tvalues := LoginFormValues{}\n\tdecoder := schema.NewDecoder()\n\terr = decoder.Decode(&values, r.PostForm)\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\n\tacc, err := data.GetAccountByHandle(values.Handle)\n\tif err == mgo.ErrNotFound {\n\t\tServeHandleIncorrect(w, r)\n\t\treturn\n\t}\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tm := acc.Password.Match(values.Password)\n\tif !m {\n\t\thttp.Redirect(w, r, \"/login\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tsess, err := store.Get(r, \"s\")\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tsess.Values[\"accountID\"] = acc.ID.Hex()\n\tsess.Save(r, w)\n\thttp.Redirect(w, r, \"/tasks\", http.StatusSeeOther)\n}", "func (h *Handler) LoginHandler(w http.ResponseWriter, r *http.Request) {\n\n\tchallenge, err := readURLChallangeParams(r, \"login\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif r.Method == \"POST\" {\n\t\tif r.Form == nil {\n\t\t\tif err := r.ParseForm(); err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tuserName := r.Form.Get(\"username\")\n\t\tpassword := r.Form.Get(\"password\")\n\t\tloginChallenge := r.Form.Get(\"challenge\")\n\t\tpass, err := h.LoginService.CheckPasswords(userName, password)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tif pass {\n\n\t\t\tacceptLoginBody := h.ConfigService.FetchAcceptLoginConfig(userName)\n\t\t\trawJson, err := json.Marshal(acceptLoginBody)\n\n\t\t\tredirectURL, err := h.LoginService.SendAcceptBody(\"login\", loginChallenge, rawJson)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\thttp.Redirect(w, r, redirectURL, http.StatusFound)\n\t\t}\n\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\ttemplLogin := template.Must(template.ParseFiles(\"templates/login.html\"))\n\t\tloginData := h.ConfigService.FetchLoginConfig(challenge, true)\n\t\ttemplLogin.Execute(w, loginData)\n\t} else {\n\t\tchallengeBody, err := h.LoginService.ReadChallenge(challenge, \"login\")\n\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tlog.Print(err)\n\t\t}\n\n\t\tif !challengeBody.Skip {\n\t\t\ttemplLogin := template.Must(template.ParseFiles(\"templates/login.html\"))\n\t\t\tloginData := h.ConfigService.FetchLoginConfig(challenge, false)\n\t\t\ttemplLogin.Execute(w, loginData)\n\t\t} else {\n\n\t\t\tacceptLoginBody := h.ConfigService.FetchAcceptLoginConfig(challengeBody.Subject)\n\t\t\trawJson, err := json.Marshal(acceptLoginBody)\n\n\t\t\tredirectURL, err := h.LoginService.SendAcceptBody(\"login\", challenge, rawJson)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\thttp.Redirect(w, r, redirectURL, http.StatusFound)\n\n\t\t}\n\t}\n}", "func Login(c *gin.Context) {\n\t// check if request was a POST\n\tif strings.EqualFold(c.Request.Method, \"POST\") {\n\t\t// assume all POST requests are coming from the CLI\n\t\tAuthenticateCLI(c)\n\n\t\treturn\n\t}\n\n\t// capture an error if present\n\terr := c.Request.FormValue(\"error\")\n\tif len(err) > 0 {\n\t\t// redirect to initial login screen with error code\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/login/error?code=\"+err)\n\t}\n\n\t// redirect to our authentication handler\n\tc.Redirect(http.StatusTemporaryRedirect, \"/authenticate\")\n}", "func (app *Application) LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tvar data map[string]interface{}\n\tdata = make(map[string]interface{})\n\tfmt.Println(\"login.html\")\n\tif r.FormValue(\"submitted\") == \"true\" {\n\t\tuname := r.FormValue(\"username\")\n\t\tpword := r.FormValue(\"password\")\n\t\torg := r.FormValue(\"org\")\n\t\tprintln(uname, pword, org)\n\t\t//according uname, comparing pword with map[uname]\n\t\tfor _, v := range webutil.Orgnization[org] {\n\t\t\tfmt.Println(\"org user\", v.UserName)\n\t\t\tif v.UserName == uname {\n\t\t\t\tif v.Secret == pword {\n\t\t\t\t\twebutil.MySession.SetSession(uname, org, w)\n\t\t\t\t\thttp.Redirect(w, r, \"./home.html\", 302)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\t//login failed redirect to login page and show failed\n\t\tdata[\"LoginFailed\"] = true\n\t\tloginTemplate(w, r, \"login.html\", data)\n\t\treturn\n\t}\n\tloginTemplate(w, r, \"login.html\", data)\n}", "func (s TppHTTPServer) Login(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tdata := LoginPageData{PageTitle: \"AXA Pay Bank Login\", BankID: s.BankID, PIN: s.PIN}\n\t//fmt.Fprint(w, \"TPP server reference PISP Login\\n\")\n\ttmpl := template.Must(template.ParseFiles(\"api/login.html\"))\n\tr.ParseForm()\n\tlog.Println(\"Form:\", r.Form)\n\ttmpl.Execute(w, data)\n\n}", "func Login() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\temail := r.FormValue(\"email\")\n\t\t// validate email\n\t\tpw := r.FormValue(\"pw\")\n\t\t// validate pass\n\n\t\tlog.Println(\"email:\", email)\n\t\tlog.Println(\"pw:\", pw)\n\t}\n}", "func (uh *UserHandler) Login(w http.ResponseWriter, r *http.Request) {\n\n\terrMap := make(map[string]string)\n\tuser := uh.Authentication(r)\n\tif user != nil {\n\t\thttp.Redirect(w, r, \"/Dashboard\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tif r.Method == http.MethodGet {\n\t\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\n\t\ttoken, err := stringTools.CSRFToken(uh.CSRF)\n\t\tinputContainer := InputContainer{CSRF: token}\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tuh.Temp.ExecuteTemplate(w, \"LoginPage.html\", inputContainer)\n\t\treturn\n\t}\n\n\tif r.Method == http.MethodPost {\n\t\temail := r.FormValue(\"email\")\n\t\tpassword := r.FormValue(\"password\")\n\n\t\t// Validating CSRF Token\n\t\tcsrfToken := r.FormValue(\"csrf\")\n\t\tok, errCRFS := stringTools.ValidCSRF(csrfToken, uh.CSRF)\n\t\tif !ok || errCRFS != nil {\n\t\t\terrMap[\"csrf\"] = \"Invalid token used!\"\n\t\t}\n\n\t\terr := uh.UService.Login(email, password)\n\n\t\tif err != nil || len(errMap) > 0 {\n\t\t\terrMap[\"login\"] = \"Invalid email or password!\"\n\t\t\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\n\t\t\ttoken, _ := stringTools.CSRFToken(uh.CSRF)\n\t\t\tinputContainer := InputContainer{Error: errMap, CSRF: token}\n\t\t\tuh.Temp.ExecuteTemplate(w, \"LoginPage.html\", inputContainer)\n\t\t\treturn\n\t\t}\n\n\t\tnewSession := uh.configSess()\n\t\tclaims := stringTools.Claims(email, newSession.Expires)\n\t\tsession.Create(claims, newSession, w)\n\t\t_, err = uh.SService.StoreSession(newSession)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\thttp.Redirect(w, r, \"/Dashboard\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n}", "func LoginHandler(w http.ResponseWriter, r *http.Request, serv *AppServer) {\n\tr.ParseForm()\n\tcookID := serv.Login(r.PostFormValue(\"username\"), r.PostFormValue(\"password\"))\n\tfmt.Println(\"Login Post Request\\ncookie value: \" + strconv.Itoa(cookID))\n\tif cookID != -1 {\n\t\ttok := http.Cookie{\n\t\t\tName: \"UserID\",\n\t\t\tValue: strconv.Itoa(cookID),\n\t\t\tExpires: time.Now().Add(1 * time.Hour),\n\t\t}\n\t\thttp.SetCookie(w, &tok)\n\t\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\t} else {\n\t\ttok := http.Cookie{\n\t\t\tName: \"UserID\",\n\t\t\tValue: \"\",\n\t\t}\n\t\thttp.SetCookie(w, &tok)\n\t\thttp.Redirect(w, r, \"/loginfail\", http.StatusTemporaryRedirect)\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tdata := authInfo{}\n\terr := json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\tutils.JSONRespnseWithErr(w, &utils.ErrPostDataNotCorrect)\n\t\treturn\n\t}\n\tmessage := models.Login(data.Email, data.Password)\n\tutils.JSONResonseWithMessage(w, message)\n}", "func login(w http.ResponseWriter, r *http.Request) {\n clearCache(w)\n exists, _ := getCookie(r, LOGIN_COOKIE)\n if exists {\n http.Redirect(w, r, \"/home\", http.StatusSeeOther)\n return\n }\n if r.Method == http.MethodGet {\n LOG[INFO].Println(\"Login Page\")\n http.ServeFile(w, r, \"../../web/login.html\")\n } else if r.Method == http.MethodPost {\n LOG[INFO].Println(\"Executing Login\")\n r.ParseForm()\n LOG[INFO].Println(\"Form Values: Username\", r.PostFormValue(\"username\"))\n passhash := sha512.Sum512([]byte(r.PostFormValue(\"password\")))\n LOG[INFO].Println(\"Hex Encoded Passhash:\", hex.EncodeToString(passhash[:]))\n response := sendCommand(CommandRequest{CommandLogin, struct{\n Username string\n Password string\n }{\n r.PostFormValue(\"username\"),\n hex.EncodeToString(passhash[:]),\n }})\n if response == nil {\n http.SetCookie(w, genCookie(ERROR_COOKIE, \"Send Command Error\"))\n http.Redirect(w, r, \"/error\", http.StatusSeeOther)\n return\n }\n if !response.Success {\n LOG[WARNING].Println(StatusText(response.Status))\n http.Redirect(w, r, \"/login\", http.StatusSeeOther)\n return\n }\n\n LOG[INFO].Println(\"Successfully Logged In\")\n http.SetCookie(w, genCookie(LOGIN_COOKIE, r.PostFormValue(\"username\")))\n http.Redirect(w, r, \"/home\", http.StatusSeeOther)\n }\n}", "func HandlerLogin(responseWriter http.ResponseWriter, request *http.Request) {\n\trequest.ParseForm()\n\n\tif request.Method == STR_GET {\n\t\tServeLogin(responseWriter, STR_EMPTY)\n\t} else {\n\t\tvar userName string = request.FormValue(API_KEY_username)\n\t\tvar password string = request.FormValue(API_KEY_password)\n\t\tif userName == STR_EMPTY || password == STR_EMPTY {\n\t\t\tServeLogin(responseWriter, \"Please enter username and password\")\n\t\t\treturn\n\t\t}\n\n\t\tvar userId = -1\n\t\tvar errorUser error = nil\n\t\tuserId, errorUser = DbGetUser(userName, password, nil)\n\t\tif errorUser != nil {\n\t\t\tlog.Printf(\"HandlerLogin, errorUser=%s\", errorUser.Error())\n\t\t}\n\t\tif userId > -1 {\n\t\t\ttoken := DbAddToken(userId, nil)\n\t\t\tAddCookie(responseWriter, token)\n\t\t\thttp.Redirect(responseWriter, request, GetApiUrlListApiKeys(), http.StatusTemporaryRedirect)\n\t\t} else {\n\t\t\tServeLogin(responseWriter, \"Wrong username or password\")\n\t\t}\n\t}\n}", "func Login(res http.ResponseWriter, req *http.Request) (bool, string) {\n\tname := req.FormValue(NameParameter)\n\tname = html.EscapeString(name)\n\tlog.Debugf(\"Log in user. Name: %s\", name)\n\tif name != \"\" {\n\t\tuuid := generateRandomUUID()\n\t\tsuccess := authClient.SetRequest(uuid, name)\n\t\tif success {\n\t\t\tcookiesManager.SetCookieValue(res, CookieName, uuid)\n\t\t}\n\t\t// successfully loged in\n\t\tif success {\n\t\t\treturn success, \"\"\n\t\t} else {\n\t\t\treturn success, \"authServerFail\"\n\t\t}\n\n\t}\n\n\treturn false, \"noName\"\n}", "func (c Control) ServeLogin(w http.ResponseWriter, r *http.Request) {\n\ttemplate := map[string]interface{}{\"error\": false}\n\tif r.Method == http.MethodPost {\n\t\t// Get their submitted hash and the real hash.\n\t\tpassword := r.PostFormValue(\"password\")\n\t\thash := HashPassword(password)\n\t\tc.Config.RLock()\n\t\trealHash := c.Config.AdminHash\n\t\tc.Config.RUnlock()\n\t\t// Check if they got the password correct.\n\t\tif hash == realHash {\n\t\t\ts, _ := Store.Get(r, \"sessid\")\n\t\t\ts.Values[\"authenticated\"] = true\n\t\t\ts.Save(r, w)\n\t\t\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\t\t\treturn\n\t\t}\n\t\ttemplate[\"error\"] = true\n\t}\n\n\t// Serve login page with no template.\n\tdata, err := Asset(\"templates/login.mustache\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\tcontent := mustache.Render(string(data), template)\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tw.Write([]byte(content))\n}", "func LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tif username != \"\" && password != \"\" {\n\t\tauth := database.QuickGetAuth()\n\t\tnauth := &database.Auth{\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t}\n\n\t\tif auth.Equal(nauth) {\n\t\t\thttp.SetCookie(w, nauth.MakeCookie())\n\t\t\thttp.Redirect(w, r, \"/admin\", 301)\n\t\t} else {\n\t\t\thttp.Redirect(w, r, \"/admin/nono\", 301)\n\t\t}\n\t} else {\n\t\thttp.Redirect(w, r, \"/admin\", 301)\n\t}\n}", "func loginHandler(res http.ResponseWriter, req *http.Request) {\n\tdefer server.LogRequest(req, http.StatusFound)\n\tcounter.Increment(\"login\")\n\n\t// get the requested username\n\tusername := req.FormValue(\"name\")\n\tif len(username) < 1 {\n\t\trenderBaseTemplate(res, \"login_error.html\", nil)\n\t} else {\n\t\terr := session.Create(res, username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\thttp.Redirect(res, req, \"/index.html\", http.StatusFound)\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"GET\" {\n\t\takagi := user{\n\t\t\tName: \"Nguyen Hoai Phuong\",\n\t\t\tPassword: \"1234\",\n\t\t}\n\n\t\tbs, err := json.Marshal(akagi)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Encode user error:\", err)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(bs)\n\t} else if r.Method == \"POST\" {\n\t\terr := r.ParseForm()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tuser := r.FormValue(\"username\")\n\t\tpass := r.FormValue(\"password\")\n\t\tfmt.Println(user)\n\t\tfmt.Println(pass)\n\t\thttp.Redirect(w, r, \"/login\", http.StatusOK)\n\t\tfmt.Fprintf(w, \"User name: %s\\nPassword : %s\\n\", user, pass)\n\t}\n\n}", "func UserLoginPost(w http.ResponseWriter, r *http.Request) {\n\tsess := session.Instance(r)\n\tvar loginResp webpojo.UserLoginResp\n\n\t// Prevent brute force login attempts by not hitting MySQL and pretending like it was invalid :-)\n\tif sess.Values[SessLoginAttempt] != nil && sess.Values[SessLoginAttempt].(int) >= 5 {\n\t\tlog.Println(\"Brute force login prevented\")\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_429, constants.Msg_429, \"/api/admin/login\")\n\t\tReturnJsonResp(w, loginResp)\n\t\treturn\n\t}\n\n\tbody, readErr := ioutil.ReadAll(r.Body)\n\tif readErr != nil {\n\t\tlog.Println(readErr)\n\t\tReturnError(w, readErr)\n\t\treturn\n\t}\n\n\tif len(body) == 0 {\n\t\tlog.Println(\"Empty json payload\")\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_400, constants.Msg_400, \"/api/admin/login\")\n\t\tReturnJsonResp(w, loginResp)\n\t\treturn\n\t}\n\n\t//log.Println(\"r.Body\", string(body))\n\tloginReq := webpojo.UserLoginReq{}\n\tjsonErr := json.Unmarshal(body, &loginReq)\n\tif jsonErr != nil {\n\t\tlog.Println(jsonErr)\n\t\tReturnError(w, jsonErr)\n\t\treturn\n\t}\n\tlog.Println(loginReq.Username)\n\n\t//should check for expiration\n\tif sess.Values[UserID] != nil && sess.Values[UserName] == loginReq.Username {\n\t\tlog.Println(\"Already signed in - session is valid!!\")\n\t\tsess.Save(r, w) //Should also start a new expiration\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_200, constants.Msg_200, \"/api/admin/leads\")\n\t\tReturnJsonResp(w, loginResp)\n\t\treturn\n\t}\n\n\tresult, dbErr := model.UserByEmail(loginReq.Username)\n\tif dbErr == model.ErrNoResult {\n\t\tlog.Println(\"Login attempt: \", sess.Values[SessLoginAttempt])\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_204, constants.Msg_204, \"/api/admin/login\")\n\t} else if dbErr != nil {\n\t\tlog.Println(dbErr)\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_500, constants.Msg_500, \"/error\")\n\t} else if passhash.MatchString(result.Password, loginReq.Password) {\n\t\tlog.Println(\"Login successfully\")\n\t\tsession.Empty(sess)\n\t\tsess.Values[UserID] = result.UserID()\n\t\tsess.Values[UserName] = loginReq.Username\n\t\tsess.Values[UserRole] = result.UserRole\n\t\tsess.Save(r, w) //Should also store expiration\n\t\tloginResp = webpojo.UserLoginResp{}\n\t\tloginResp.StatusCode = constants.StatusCode_200\n\t\tloginResp.Message = constants.Msg_200\n\t\tloginResp.URL = \"/api/admin/leads\"\n\t\tloginResp.FirstName = result.FirstName\n\t\tloginResp.LastName = result.LastName\n\t\tloginResp.UserRole = result.UserRole\n\t\tloginResp.Email = loginReq.Username\n\t} else {\n\t\tlog.Println(\"Login attempt: \", sess.Values[SessLoginAttempt])\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_404, constants.Msg_404, \"/api/admin/login\")\n\t}\n\n\tReturnJsonResp(w, loginResp)\n}", "func (a Authentic) loginHandler(c buffalo.Context) error {\n\tc.Request().ParseForm()\n\n\t//TODO: schema ?\n\tloginData := struct {\n\t\tUsername string\n\t\tPassword string\n\t}{}\n\n\tc.Bind(&loginData)\n\n\tu, err := a.provider.FindByUsername(loginData.Username)\n\tif err != nil || ValidatePassword(loginData.Password, u) == false {\n\t\tc.Flash().Add(\"danger\", \"Invalid Username or Password\")\n\t\treturn c.Redirect(http.StatusSeeOther, a.Config.LoginPath)\n\t}\n\n\tc.Session().Set(SessionField, u.GetID())\n\tc.Session().Save()\n\n\treturn c.Redirect(http.StatusSeeOther, a.Config.AfterLoginPath)\n}", "func loginHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := context.Background()\n\tif b.authenticator == nil {\n\t\tvar err error\n\t\tb.authenticator, err = initAuth(ctx)\n\t\tif err != nil {\n\t\t\tlog.Print(\"loginHandler authenticator could not be initialized\")\n\t\t\thttp.Error(w, \"Server error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\tsessionInfo := identity.InvalidSession()\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tlog.Printf(\"loginHandler: error parsing form: %v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tusername := r.PostFormValue(\"UserName\")\n\tlog.Printf(\"loginHandler: username = %s\", username)\n\tpassword := r.PostFormValue(\"Password\")\n\tusers, err := b.authenticator.CheckLogin(ctx, username, password)\n\tif err != nil {\n\t\tlog.Printf(\"main.loginHandler checking login, %v\", err)\n\t\thttp.Error(w, \"Error checking login\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif len(users) != 1 {\n\t\tlog.Printf(\"loginHandler: user %s not found or password does not match\", username)\n\t} else {\n\t\tcookie, err := r.Cookie(\"session\")\n\t\tif err == nil {\n\t\t\tlog.Printf(\"loginHandler: updating session: %s\", cookie.Value)\n\t\t\tsessionInfo = b.authenticator.UpdateSession(ctx, cookie.Value, users[0], 1)\n\t\t}\n\t\tif (err != nil) || !sessionInfo.Valid {\n\t\t\tsessionid := identity.NewSessionId()\n\t\t\tdomain := config.GetSiteDomain()\n\t\t\tlog.Printf(\"loginHandler: setting new session %s for domain %s\",\n\t\t\t\tsessionid, domain)\n\t\t\tcookie := &http.Cookie{\n\t\t\t\tName: \"session\",\n\t\t\t\tValue: sessionid,\n\t\t\t\tDomain: domain,\n\t\t\t\tPath: \"/\",\n\t\t\t\tMaxAge: 86400 * 30, // One month\n\t\t\t}\n\t\t\thttp.SetCookie(w, cookie)\n\t\t\tsessionInfo = b.authenticator.SaveSession(ctx, sessionid, users[0], 1)\n\t\t}\n\t}\n\tif strings.Contains(r.Header.Get(\"Accept\"), \"application/json\") {\n\t\tsendJSON(w, sessionInfo)\n\t} else {\n\t\tif sessionInfo.Authenticated == 1 {\n\t\t\ttitle := b.webConfig.GetVarWithDefault(\"Title\", defTitle)\n\t\t\tcontent := htmlContent{\n\t\t\t\tTitle: title,\n\t\t\t}\n\t\t\tb.pageDisplayer.DisplayPage(w, \"index.html\", content)\n\t\t} else {\n\t\t\tloginFormHandler(w, r)\n\t\t}\n\t}\n}", "func Login(c *gin.Context) {\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\temail := c.PostForm(\"email\")\n\t//check if provided user credentials are valid or not\n\tif store.ValidUser(username, password, email) {\n\t\ttoken := generateSessionToken()\n\t\tc.SetCookie(\"token\", token, 3600, \"\", \"\", false, true)\n\t\tc.Set(\"is_logged_in\", true)\n\t\trender(c, gin.H{\n\t\t\t\"title\": \"Successful Login\"}, \"login-successful.html\")\n\t} else {\n\t\tc.HTML(http.StatusBadRequest, \"login.html\", gin.H{\n\t\t\t\"ErrorTitle\": \"Login Failed\",\n\t\t\t\"ErrorMessage\": \"Invalid credentials provided\"})\n\t}\n}", "func (server Server) Login(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r) // mux params\n\tusername := vars[\"username\"] // get username\n\tpassword := vars[\"password\"] // get password\n\tvar res models.APIResponse // make a response\n\n\tif username == \"\" || password == \"\" {\n\t\tres = models.BuildAPIResponseFail(\"Bad Request. Empty username or password\", nil)\n\t} else {\n\t\tvar data = checkLogin(username, password, server.db) //create the data\n\t\tres = models.BuildAPIResponseSuccess(\"Login successful\", data)\n\t}\n\tjson.NewEncoder(w).Encode(res) //encode the data\n\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\t/*\n\t\tTratamento dos dados vindos do front-end\n\t\tNesse caso, o request pega login e senha\n\t*/\n\tvar login models.Credentials\n\tbody := r.Body\n\tbytes, err := util.BodyToBytes(body)\n\terr = util.BytesToStruct(bytes, &login)\n\n\t// Checks if struct is a valid one\n\tif err = validation.Validator.Struct(login); err != nil {\n\n\t\tlog.Printf(\"[WARN] invalid user information, because, %v\\n\", err)\n\t\tw.WriteHeader(http.StatusPreconditionFailed) // Status 412\n\t\treturn\n\t}\n\n\t// err1 consulta o login no banco de dados\n\terr1 := database.CheckLogin(login.Login)\n\n\t// err2 consulta a senha referente ao login fornecido\n\terr2 := database.CheckSenha(login.Login, login.Senha)\n\n\t// Condicao que verifica se os dois dados constam no banco de dados\n\tif (err1 != nil) || (err2 != true) {\n\t\tlog.Println(\"[FAIL]\")\n\t\tw.WriteHeader(http.StatusForbidden) // Status 403\n\t} else {\n\t\tlog.Println(\"[SUCCESS]\")\n\t\tw.WriteHeader(http.StatusAccepted) // Status 202\n\t}\n\n\treturn\n}", "func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {\n\tvar d UserLoginRequest\n\tif err := json.NewDecoder(r.Body).Decode(&d); err != nil {\n\t\trender.BadRequest(w, r, \"invalid json string\")\n\t\treturn\n\t}\n\n\t//Check if email exists\n\tuser, err := h.Client.User.\n\t\tQuery().\n\t\tWhere(usr.Email(d.Email)).\n\t\tOnly(r.Context())\n\tif err != nil {\n\t\tswitch {\n\t\tcase ent.IsNotFound(err):\n\t\t\trender.NotFound(w, r, \"Email Doesn't exists\")\n\t\tcase ent.IsNotSingular(err):\n\t\t\trender.BadRequest(w, r, \"Invalid Email\")\n\t\tdefault:\n\t\t\trender.InternalServerError(w, r, \"Server Error\")\n\t\t}\n\t\treturn\n\t}\n\n\t// Verify the password\n\tif user.Password == d.Password {\n\t\tfmt.Println(\"User Verified. Log In Successful\")\n\t\trender.OK(w, r, user)\n\t\treturn\n\t}\n\trender.Unauthorized(w, r, \"Invalid Email or Password.\")\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"login called\")\n}", "func (as *AdminServer) Login(w http.ResponseWriter, r *http.Request) {\n\tparams := struct {\n\t\tUser models.User\n\t\tTitle string\n\t\tFlashes []interface{}\n\t\tToken string\n\t}{Title: \"Login\", Token: csrf.Token(r)}\n\tsession := ctx.Get(r, \"session\").(*sessions.Session)\n\tswitch {\n\tcase r.Method == \"GET\":\n\t\tparams.Flashes = session.Flashes()\n\t\tsession.Save(r, w)\n\t\ttemplates := template.New(\"template\")\n\t\t_, err := templates.ParseFiles(\"templates/login.html\", \"templates/flashes.html\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\ttemplate.Must(templates, err).ExecuteTemplate(w, \"base\", params)\n\tcase r.Method == \"POST\":\n\t\t// Find the user with the provided username\n\t\tusername, password := r.FormValue(\"username\"), r.FormValue(\"password\")\n\t\tu, err := models.GetUserByUsername(username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\t// Validate the user's password\n\t\terr = auth.ValidatePassword(password, u.Hash)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\tif u.AccountLocked {\n\t\t\tas.handleInvalidLogin(w, r, \"Account Locked\")\n\t\t\treturn\n\t\t}\n\t\tu.LastLogin = time.Now().UTC()\n\t\terr = models.PutUser(&u)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\t// If we've logged in, save the session and redirect to the dashboard\n\t\tsession.Values[\"id\"] = u.Id\n\t\tsession.Save(r, w)\n\t\tas.nextOrIndex(w, r)\n\t}\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\ttmpl := template.Must(template.ParseFiles(\"templates/login.html\"))\n\tif r.Method != http.MethodPost {\n\t\ttmpl.Execute(w, nil)\n\t}\n\n\tdetails := userLogin{\n\t\tUsername: r.FormValue(\"username\"),\n\t\tPassword: r.FormValue(\"psw\"),\n\t}\n\n\tlog.Println(details)\n\t//Attempt login by calling LDAP verify credentials\n\tlog.Println(\"Username: \" + details.Username)\n\tlog.Println(\"Pass: \" + details.Password)\n\tauth := verifyCredentials(details.Username, details.Password)\n\tlog.Println(auth)\n\n\t//authorize user and create JWT\n\tif auth {\n\t\tfmt.Println(\"starting auth ...\")\n\t\tfor _, cookie := range r.Cookies() {\n\t\t\tfmt.Print(\"Cookie User: \")\n\t\t\tfmt.Println(w, cookie.Name)\n\t\t\treadJWT(cookie.Name)\n\t\t}\n\t\ttoken := generateJWT(details.Username)\n\t\tsetJwtCookie(token, w, r)\n\t\thttp.Redirect(w, r, \"/dashboard\", http.StatusSeeOther)\n\t}\n\n}", "func LoginHandler(w http.ResponseWriter, r *http.Request) {\n\t// Initialize the fields that we need in the custom struct.\n\ttype Context struct {\n\t\tErr string\n\t\tErrExists bool\n\t\tOTPRequired bool\n\t\tUsername string\n\t\tPassword string\n\t}\n\t// Call the Context struct.\n\tc := Context{}\n\n\t// If the request method is POST\n\tif r.Method == \"POST\" {\n\t\t// This is a login request from the user.\n\t\tusername := r.PostFormValue(\"username\")\n\t\tusername = strings.TrimSpace(strings.ToLower(username))\n\t\tpassword := r.PostFormValue(\"password\")\n\t\totp := r.PostFormValue(\"otp\")\n\n\t\t// Login2FA login using username, password and otp for users with OTPRequired = true.\n\t\tsession := uadmin.Login2FA(r, username, password, otp)\n\n\t\t// Check whether the session returned is nil or the user is not active.\n\t\tif session == nil || !session.User.Active {\n\t\t\t/* Assign the login validation here that will be used for UI displaying. ErrExists and\n\t\t\tErr fields are coming from the Context struct. */\n\t\t\tc.ErrExists = true\n\t\t\tc.Err = \"Invalid username/password or inactive user\"\n\n\t\t} else {\n\t\t\t// If the user has OTPRequired enabled, it will print the username and OTP in the terminal.\n\t\t\tif session.PendingOTP {\n\t\t\t\tuadmin.Trail(uadmin.INFO, \"User: %s OTP: %s\", session.User.Username, session.User.GetOTP())\n\t\t\t}\n\n\t\t\t/* As long as the username and password is valid, it will create a session cookie in the\n\t\t\tbrowser. */\n\t\t\tcookie, _ := r.Cookie(\"session\")\n\t\t\tif cookie == nil {\n\t\t\t\tcookie = &http.Cookie{}\n\t\t\t}\n\t\t\tcookie.Name = \"session\"\n\t\t\tcookie.Value = session.Key\n\t\t\tcookie.Path = \"/\"\n\t\t\tcookie.SameSite = http.SameSiteStrictMode\n\t\t\thttp.SetCookie(w, cookie)\n\n\t\t\t// Check for OTP\n\t\t\tif session.PendingOTP {\n\t\t\t\t/* After the user enters a valid username and password in the first part of the form, these\n\t\t\t\tvalues will be used on the second part in the UI where the OTP input field will be\n\t\t\t\tdisplayed afterwards. */\n\t\t\t\tc.Username = username\n\t\t\t\tc.Password = password\n\t\t\t\tc.OTPRequired = true\n\n\t\t\t} else {\n\t\t\t\t// If the next value is empty, redirect the page that omits the logout keyword in the last part.\n\t\t\t\tif r.URL.Query().Get(\"next\") == \"\" {\n\t\t\t\t\thttp.Redirect(w, r, strings.TrimSuffix(r.RequestURI, \"logout\"), http.StatusSeeOther)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Redirect to the page depending on the value of the next.\n\t\t\t\thttp.Redirect(w, r, r.URL.Query().Get(\"next\"), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Render the login filepath and pass the context data object to the HTML file.\n\tuadmin.RenderHTML(w, r, \"templates/login.html\", c)\n}", "func UserLoginPostHandler(c *gin.Context) {\n\tb := userValidator.LoginForm{}\n\tc.Bind(&b)\n\tmessages := msg.GetMessages(c)\n\n\tvalidator.ValidateForm(&b, messages)\n\tif !messages.HasErrors() {\n\t\t_, _, errorUser := cookies.CreateUserAuthentication(c, &b)\n\t\tif errorUser == nil {\n\t\t\turl := c.DefaultPostForm(\"redirectTo\", \"/\")\n\t\t\tc.Redirect(http.StatusSeeOther, url)\n\t\t\treturn\n\t\t}\n\t\tmessages.ErrorT(errorUser)\n\t}\n\tUserLoginFormHandler(c)\n}", "func performLogin(c *gin.Context) {\n\t/*\n\t\tGet the values from POST objects\n\t*/\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\n\t/*\n\t\tChecks the username and password variables valuesare not empty\n\t*/\n\tif len(username) == 0 || len(password) == 0 {\n\t\terr = errors.New(\"missing password and/or email\")\n\t\treturn\n\t}\n\n\t/*\n\t\tCall the actual function which checks and return error or information about user\n\t\tBased on status we are redirecting to necessary pages\n\t\tIf error then redirecting to login page again with error messages\n\t\tIf valid then redirecting to userprofile page which display user information.\n\t*/\n\tUserInfo, err := getUser(username, password)\n\tif err != nil {\n\t\trender(c, gin.H{\n\t\t\t\"title\": \"Login\",\n\t\t\t\"ErrorMessage\": \"Login Failed\",\n\t\t}, \"login.html\")\n\t} else {\n\t\trender(c, gin.H{\n\t\t\t\"title\": \"User Profile\",\n\t\t\t\"UserInfo\": UserInfo,\n\t\t}, \"userprofile.html\")\n\t}\n}", "func LoginPost(c *gin.Context) {\n\tvar user model.User\n\n\tif err := ginutils.BindGinJSON(c, &user); err == nil {\n\t\tverifyResult := base64Captcha.VerifyCaptcha(user.CaptchaKey, user.Captcha)\n\t\tif !verifyResult {\n\t\t\tginutils.WriteGinJSON(c, http.StatusUnauthorized, gin.H{\n\t\t\t\t\"msg\": \"验证码错误\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tif err := model.Login(&user); err == nil {\n\t\t\tginutils.WriteGinJSON(c, http.StatusOK, gin.H{\n\t\t\t\t\"token\": middleware.GetJWTToken(user),\n\t\t\t})\n\t\t} else {\n\t\t\tginutils.WriteGinJSON(c, http.StatusUnauthorized, gin.H{\n\t\t\t\t\"msg\": err.Error(),\n\t\t\t})\n\t\t}\n\t\treturn\n\t}\n\n\tginutils.WriteGinJSON(c, http.StatusBadRequest, gin.H{\n\t\t\"msg\": \"传参数错误!\",\n\t})\n}", "func PostLogin(w http.ResponseWriter, request *http.Request) {\n\trespObj := &model.ResponseLogin{\n\t\tResponseCode: \"00\",\n\t\tResponseDesc: \"Login Success\",\n\t}\n\tloginBean := new(model.LoginBean)\n\tdecoder := json.NewDecoder(request.Body)\n\terr := decoder.Decode(&loginBean)\n\tif err != nil {\n\t\tfmt.Printf(\"Cannot decode json form with error %s\", err.Error())\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n\n\tjsonvalid, err := os.Open(\"data_file/valid-user.json\")\n\tif err != nil {\n\t\tlog.Printf(\"Cannot open file name valid-user.json with error: %s\", err.Error())\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\trespObj.ResponseCode = \"10\"\n\t\trespObj.ResponseDesc = err.Error()\n\t\t_ = json.NewEncoder(w).Encode(respObj)\n\t\treturn\n\t}\n\n\tdefer jsonvalid.Close()\n\tbyteValue, _ := ioutil.ReadAll(jsonvalid)\n\tvar result map[string]interface{}\n\t_ = json.Unmarshal([]byte(byteValue), &result)\n\n\tif loginBean.Username != result[\"username\"] || loginBean.Password != result[\"password\"] {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\trespObj.ResponseCode = \"10\"\n\t\trespObj.ResponseDesc = \"Username or Password is invalid.\"\n\t\t_ = json.NewEncoder(w).Encode(respObj)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\t_ = json.NewEncoder(w).Encode(respObj)\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Login endpoint hit\")\n\t\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tuser := models.User{}\n\n\tif user.Authorise(username, password) {\n\t\tjson.NewEncoder(w).Encode(user)\n\t} else {\n\t\tm := make(map[string]string)\n\t\tm[\"Message\"] = \"Username and password do not match\"\n\t\tjson.NewEncoder(w).Encode(m)\n\t}\n}", "func Login(w http.ResponseWriter, req *http.Request) {\n\tfmt.Println(chalk.Green, chalk.Bold.TextStyle(\"-- Login --\"), chalk.Reset)\n\tvar p models.LoginDTO\n\n\t// Decodes user input to JSON\n\terr := json.NewDecoder(req.Body).Decode(&p)\n\tvalidate := validator.New()\n\t// Validates if all fields are present in the POST request\n\tif err != nil || validate.Struct(p) != nil {\n\t\tfmt.Printf(\"%s Error ::%s Invalid Data\\n\\n\", chalk.Red, chalk.Reset)\n\t\thttp.Error(w, \"Invalid Data\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tfmt.Printf(\" Username :: %s \\n Hash :: %s\\n\", p.Username, p.Hash)\n\t// Check if user is present in the database\n\tif !database.Check(p.Username) {\n\t\tfmt.Printf(\"%s Error ::%s User does not exist\\n\\n\", chalk.Red, chalk.Reset)\n\t\thttp.Error(w, \"Invalid Username\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Fetch the user details from the database\n\tuserCreds := database.Get(p.Username)\n\t// If N value is 2, prompt user to reset his password immediately\n\tif userCreds.N == 2 {\n\t\tfmt.Printf(\"%s Error ::%s Reset Password Immediately\\n\\n\", chalk.Red, chalk.Reset)\n\t\thttp.Error(w, \"Reset Password Immediately\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Check if the hash given by user is valid\n\tok, errString := Validate(p.Username, p.Hash, userCreds)\n\tif !ok {\n\t\thttp.Error(w, errString, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// If valid return success message\n\tfmt.Printf(\"%s Success\\n\\n%s\", chalk.Green, chalk.Reset)\n\tfmt.Fprintf(w, \"User Successfully logged in.\")\n}", "func Login(c *gin.Context) {\n\tvar form model.LoginForm\n\terr := c.BindJSON(&form)\n\tif err != nil {\n\t\tfailMsg(c, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tvalid, errMsg := validInfo(form)\n\tif !valid {\n\t\tfailMsg(c, http.StatusBadRequest, errMsg)\n\t\treturn\n\t}\n\tvalid = model.VerifyLogin(form)\n\tif !valid {\n\t\tfailMsg(c, http.StatusUnauthorized, \"wrong username or password\")\n\t\treturn\n\t}\n\ttoken, err := model.GenerateToken(form.Username)\n\tif err != nil {\n\t\tfailMsg(c, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"success\": true,\n\t\t\"error\": \"\",\n\t\t\"data\": \"Bearer \" + token,\n\t})\n\n}", "func (userHandlersImpl UserHandlersImpl) Login(w http.ResponseWriter, req *http.Request) {\n\n\tctx := req.Context()\n\tuser := models.UserLoginRequest{}\n\tlog.Logger(ctx).Info(\"in request\")\n\n\terr := ReadInput(req.Body, &user)\n\tif err != nil {\n\t\tWriteHTTPError(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tresp, err := userHandlersImpl.userSvc.Login(ctx, user)\n\tif err != nil {\n\t\tWriteHTTPError(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\tWriteOKResponse(w, resp)\n}", "func loginHandler(w http.ResponseWriter, r *http.Request) {\n\ttype Context struct {\n\t\tErr string\n\t\tErrExists bool\n\t\tSiteName string\n\t\tLanguages []Language\n\t\tRootURL string\n\t\tOTPRequired bool\n\t\tLanguage Language\n\t\tUsername string\n\t\tPassword string\n\t\tLogo string\n\t\tFavIcon string\n\t\tSSOURL string\n\t}\n\n\tc := Context{}\n\tc.SiteName = SiteName\n\tc.RootURL = RootURL\n\tc.Language = getLanguage(r)\n\tc.Logo = Logo\n\tc.FavIcon = FavIcon\n\tc.SSOURL = SSOURL\n\n\tif session := IsAuthenticated(r); session != nil {\n\t\tsession = session.User.GetActiveSession()\n\t\tSetSessionCookie(w, r, session)\n\t\tif r.URL.Query().Get(\"next\") != \"\" {\n\t\t\thttp.Redirect(w, r, r.URL.Query().Get(\"next\"), 303)\n\t\t}\n\t}\n\n\tif r.Method == cPOST {\n\t\tif r.FormValue(\"save\") == \"Send Request\" {\n\t\t\t// This is a password reset request\n\t\t\tIncrementMetric(\"uadmin/security/passwordreset/request\")\n\t\t\temail := r.FormValue(\"email\")\n\t\t\tuser := User{}\n\t\t\tGet(&user, \"Email = ?\", email)\n\t\t\tif user.ID != 0 {\n\t\t\t\tIncrementMetric(\"uadmin/security/passwordreset/emailsent\")\n\t\t\t\tc.ErrExists = true\n\t\t\t\tc.Err = \"Password recovery request sent. Please check email to reset your password\"\n\t\t\t\tforgotPasswordHandler(&user, r, \"\", \"\")\n\t\t\t} else {\n\t\t\t\tIncrementMetric(\"uadmin/security/passwordreset/invalidemail\")\n\t\t\t\tc.ErrExists = true\n\t\t\t\tc.Err = \"Please check email address. Email address must be associated with the account to be recovered.\"\n\t\t\t}\n\t\t} else {\n\t\t\t// This is a login request\n\t\t\tusername := r.PostFormValue(\"username\")\n\t\t\tusername = strings.TrimSpace(strings.ToLower(username))\n\t\t\tpassword := r.PostFormValue(\"password\")\n\t\t\totp := r.PostFormValue(\"otp\")\n\t\t\tlang := r.PostFormValue(\"language\")\n\n\t\t\tsession := Login2FA(r, username, password, otp)\n\t\t\tif session == nil || !session.User.Active {\n\t\t\t\tc.ErrExists = true\n\t\t\t\tc.Err = \"Invalid username/password or inactive user\"\n\t\t\t} else {\n\t\t\t\t// Set session cookie\n\t\t\t\tSetSessionCookie(w, r, session)\n\n\t\t\t\t// set language cookie\n\t\t\t\tcookie, _ := r.Cookie(\"language\")\n\t\t\t\tif cookie == nil {\n\t\t\t\t\tcookie = &http.Cookie{}\n\t\t\t\t}\n\t\t\t\tcookie.Name = \"language\"\n\t\t\t\tcookie.Value = lang\n\t\t\t\tcookie.Path = \"/\"\n\t\t\t\thttp.SetCookie(w, cookie)\n\n\t\t\t\t// Check for OTP\n\t\t\t\tif session.PendingOTP {\n\t\t\t\t\tc.Username = username\n\t\t\t\t\tc.Password = password\n\t\t\t\t\tc.OTPRequired = true\n\t\t\t\t} else {\n\t\t\t\t\tif r.URL.Query().Get(\"next\") == \"\" {\n\t\t\t\t\t\thttp.Redirect(w, r, strings.TrimSuffix(r.RequestURI, \"logout\"), http.StatusSeeOther)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\thttp.Redirect(w, r, r.URL.Query().Get(\"next\"), http.StatusSeeOther)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tc.Languages = activeLangs\n\tRenderHTML(w, r, \"./templates/uadmin/\"+Theme+\"/login.html\", c)\n}", "func (c *Controller) Login(ctx context.Context) (err error) {\n\t// Build request\n\treq, err := c.requestBuild(ctx, \"POST\", authenticationAPIName, \"login\", map[string]string{\n\t\t\"username\": c.user,\n\t\t\"password\": c.password,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"building request failed: %w\", err)\n\t}\n\t// Add custom header for login\n\torigin := fmt.Sprintf(\"%s://%s\", c.url.Scheme, c.url.Hostname())\n\tif c.url.Port() != \"\" {\n\t\torigin += \":\" + c.url.Port()\n\t}\n\treq.Header.Set(\"Origin\", origin)\n\t// execute auth request\n\tif err = c.requestExecute(ctx, req, nil, false); err != nil {\n\t\terr = fmt.Errorf(\"executing request failed: %w\", err)\n\t}\n\treturn\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tuser := models.User{}\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\tuser.Prepare()\n\terr = user.Validate(\"login\")\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\ttoken, err := auth.SignIn(user.Email, user.Password)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, token)\n}", "func loginFormHandler(w http.ResponseWriter, r *http.Request) {\n\tb.pageDisplayer.DisplayPage(w, \"login_form.html\", nil)\n}", "func Login(ctx echo.Context) error {\n\n\tf := forms.New(utils.GetLang(ctx))\n\tutils.SetData(ctx, \"form\", f)\n\n\t// set page tittle to login\n\tutils.SetData(ctx, settings.PageTitle, \"login\")\n\n\treturn ctx.Render(http.StatusOK, tmpl.LoginTpl, utils.GetData(ctx))\n}", "func (app *application) login(w http.ResponseWriter, r *http.Request) {\n\tsession, err := app.sessionStore.Get(r, \"session-name\")\n\tif err != nil {\n\t\tapp.serverError(w, err)\n\t\treturn\n\t}\n\terr = r.ParseForm()\n\tif err != nil {\n\t\tapp.clientError(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\tform := forms.New(r.PostForm)\n\tform.Required(\"email\", \"password\")\n\tform.MatchesPattern(\"email\", forms.RxEmail)\n\tif !form.Valid() {\n\t\tapp.render(w, r, \"login.page.tmpl\", &templateData{Form: form})\n\t\treturn\n\t}\n\tvar id int\n\tif form.Get(\"accType\") == \"customer\" {\n\t\tid, err = app.customers.Authenticate(form.Get(\"email\"), form.Get(\"password\"))\n\t\tif err == models.ErrInvalidCredentials {\n\t\t\tform.Errors.Add(\"generic\", \"Email or Password Incorrect. Please ensure you have selected correct account type\")\n\t\t\tapp.render(w, r, \"login.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\tsession.Values[\"customerID\"] = id\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/customer/home\", http.StatusSeeOther)\n\t} else {\n\t\tid, err = app.vendors.Authenticate(form.Get(\"email\"), form.Get(\"password\"))\n\t\tif err == models.ErrInvalidCredentials {\n\t\t\tform.Errors.Add(\"generic\", \"Email or Password Incorrect. Please ensure you have selected correct account type\")\n\t\t\tapp.render(w, r, \"login.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\tsession.Values[\"vendorID\"] = id\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/vendor/home\", http.StatusSeeOther)\n\t}\n}", "func (uc UserController) Login(w http.ResponseWriter, r *http.Request) {\n\tif user := users.GetLoggedInUser(r); user != nil {\n\t\thttp.Redirect(w, r, \"/\", http.StatusOK)\n\t\treturn\n\t}\n\n\temail, pass := r.FormValue(\"email\"), r.FormValue(\"password\")\n\tuser := users.CheckLoginInformation(email, pass)\n\n\tif user == nil {\n\t\thttp.Error(w, \"Incorrect username and password combination\", http.StatusUnauthorized)\n\t} else {\n\t\tusers.LoginUser(w, r, user)\n\t\thttp.Redirect(w, r, \"/\", http.StatusOK)\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\r\n\tlogin := strings.Trim(r.FormValue(\"login\"), \" \")\r\n\tpass := strings.Trim(r.FormValue(\"pass\"), \" \")\r\n\tlog.Println(\"login: \", login, \" pass: \", pass)\r\n\r\n\t// Check params\r\n\tif login == \"\" || pass == \"\" {\r\n\t\twriteResponse(w, \"Login and password required\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\t// Already authorized\r\n\tif savedPass, OK := Auth[login]; OK && savedPass == pass {\r\n\t\twriteResponse(w, \"You are already authorized\\n\", http.StatusOK)\r\n\t\treturn\r\n\t} else if OK && savedPass != pass {\r\n\t\t// it is not neccessary\r\n\t\twriteResponse(w, \"Wrong pass\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\tuser := model.User{}\r\n\terr := user.Get(login, pass)\r\n\tif err == nil {\r\n\t\tAuth[login], Work[login] = pass, user.WorkNumber\r\n\t\twriteResponse(w, \"Succesfull authorization\\n\", http.StatusOK)\r\n\t\treturn\r\n\t}\r\n\r\n\twriteResponse(w, \"User with same login not found\\n\", http.StatusNotFound)\r\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\n\t// Start the session.\n\tsession := sessions.Start(w, r)\n\tif len(session.GetString(\"username\")) != 0 && checkErr(w, r, err) {\n\t\t// Redirect to index page if the user isn't signed in. Will remove later.\n\t\thttp.Redirect(w, r, \"/\", 302)\n\t}\n\n\tif r.Method != \"POST\" {\n\t\tvar data = map[string]interface{}{\n\t\t\t\"Title\": \"Log In\",\n\t\t}\n\n\t\terr := templates.ExecuteTemplate(w, \"login.html\", data)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tusers := QueryUser(username)\n\n\t// Compare inputted password to the password in the database. If they're the same, return nil.\n\tvar password_compare = bcrypt.CompareHashAndPassword([]byte(users.Password), []byte(password))\n\n\tif password_compare == nil {\n\n\t\tsession := sessions.Start(w, r)\n\t\tsession.Set(\"username\", users.Username)\n\t\tsession.Set(\"user_id\", users.ID)\n\t\thttp.Redirect(w, r, \"/\", 302)\n\n\t} else {\n\n\t\thttp.Redirect(w, r, \"/login\", 302)\n\n\t}\n\n}", "func login(w http.ResponseWriter,r *http.Request){\n\tsession,err:=store.Get(r,\"cookie-name\")\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\n\t// Where authentication could be done\n\tif r.FormValue(\"code\")!=\"code\"{\n\t\tif r.FormValue(\"code\")==\"\"{\n\t\t\tsession.AddFlash(\"must enter a code\")\n\t\t}\n\t\tsession.AddFlash(\"the code was incorrect\")\n\t\terr:=session.Save(r,w)\n\t\tif err!=nil{\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\thttp.Redirect(w,r,\"/forbiden\",http.StatusFound)\n\t\treturn\n\t}\n\tusername:=r.FormValue(\"username\")\n\tpassword:=r.FormValue(\"password\")\n\tuser:=&user{\n\t\tUserName: username,\n\t\tPassword: password,\n\t\tAuthenticated: true,\n\t}\n\tsession.Values[\"user\"]=user\n\terr=session.Save(r,w)\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\thttp.Redirect(w,r,\"/secret\",http.StatusFound)\n}", "func Login(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tfmt.Println(\"Login\")\n}", "func LoginHandler(db *sql.DB) func(http.ResponseWriter, *http.Request, httprouter.Params) {\n\treturn func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\n\t\tvar creds s.Credentials\n\t\terr := json.NewDecoder(r.Body).Decode(&creds)\n\t\tusername = creds.Username\n\n\t\tif err != nil || creds.Username == \"\" || creds.Password == \"\" {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tpasswordBool := checkPassword(db, w, creds)\n\n\t\tif !passwordBool {\n\t\t\t// Unauthorised access\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\t// Login Sucess\n\t\tif !(generateToken(w, r, creds)) {\n\t\t\treturn\n\t\t}\n\n\t\tfmt.Println(\"Login Sucessful\")\n\t\thttp.Redirect(w, r, \"/login/sample\", 301)\n\t}\n}", "func (s *HttpServer) loginForm(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\ts.RenderTemplate(ctx, w, \"login\", nil)\n}", "func Login(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\n\t// Validate form input\n\tif strings.Trim(username, \" \") == \"\" || strings.Trim(password, \" \") == \"\" {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Parameters can't be empty\"})\n\t\treturn\n\t}\n\n\t// Check for username and password match, usually from a database\n\tif username != \"id\" || password != \"pw\" {\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\"error\": \"Authentication failed\"})\n\t\tutil.Error(\"Authentication failed\")\n\t\treturn\n\t}\n\t// Save the username in the session\n\tsession.Set(userkey, username)\n\t// In real world usage you'd set this to the users ID\n\tif err := session.Save(); err != nil {\n\t\tutil.Error(\"Failed to save session\")\n\t\tutil.Error(err.Error())\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"message\": \"Successfully authenticated user\"})\n\tutil.Info(\"Successfully to session\")\n}", "func PostLogin(db database.DB) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t//find user\n\t\tvar auth = model.StandardAuth{}\n\t\tjson.NewDecoder(r.Body).Decode(&auth)\n\t\tuser, err := db.GetUserByLogin(auth.Login)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"User not found\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\t//check pass\n\t\terr = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(auth.Password))\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Invalid Password\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\t// Create a new token object, specifying signing method and the claims\n\t\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{\n\t\t\t\"iss\": user.Login,\n\t\t\t\"iat\": time.Now(),\n\t\t})\n\n\t\t// Sign and get the complete encoded token as a string using the secret\n\t\ttokenString, err := token.SignedString(config.SigningKey)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Signing Error\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(tokenString))\n\t})\n}", "func (h *AuthHandlers) Login(w http.ResponseWriter, req *http.Request) {\n\tvar err error\n\tvar data []byte\n\n\tsystemContext, err := h.getSystemContext(req)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"request context retrevial failure\")\n\t\tmiddleware.ReturnError(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tif data, err = ioutil.ReadAll(req.Body); err != nil {\n\t\tlog.Error().Err(err).Msg(\"read body error\")\n\t\tmiddleware.ReturnError(w, \"error reading login data\", 500)\n\t\treturn\n\t}\n\tdefer req.Body.Close()\n\n\tloginDetails := &authz.LoginDetails{}\n\tif err := json.Unmarshal(data, loginDetails); err != nil {\n\t\tlog.Error().Err(err).Msg(\"marshal body error\")\n\t\tmiddleware.ReturnError(w, \"error reading login data\", 500)\n\t\treturn\n\t}\n\n\tif err := h.validate.Struct(loginDetails); err != nil {\n\t\tmiddleware.ReturnError(w, \"validation failure \"+err.Error(), 500)\n\t\treturn\n\t}\n\tloginDetails.OrgName = strings.ToLower(loginDetails.OrgName)\n\tloginDetails.Username = strings.ToLower(loginDetails.Username)\n\n\tlog.Info().Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Msg(\"login attempt\")\n\n\torgData, err := h.getOrgByName(req.Context(), systemContext, loginDetails.OrgName)\n\tif err != nil {\n\t\tlog.Error().Err(err).Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Msg(\"failed to get organization from name\")\n\t\tmiddleware.ReturnError(w, \"login failed\", 403)\n\t\treturn\n\t}\n\n\tresults, err := h.authenticator.Login(req.Context(), orgData, loginDetails)\n\tif err != nil {\n\t\tlog.Error().Err(err).Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Msg(\"login failed\")\n\t\tif req.Context().Err() != nil {\n\t\t\tmiddleware.ReturnError(w, \"internal server error\", 500)\n\t\t\treturn\n\t\t}\n\t\tmiddleware.ReturnError(w, \"login failed\", 403)\n\t\treturn\n\t}\n\t// add subscription id to response\n\tresults[\"subscription_id\"] = fmt.Sprintf(\"%d\", orgData.SubscriptionID)\n\n\trespData, err := json.Marshal(results)\n\tif err != nil {\n\t\tmiddleware.ReturnError(w, \"marshal auth response failed\", 500)\n\t\treturn\n\t}\n\n\tlog.Info().Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Str(\"OrgCID\", orgData.OrgCID).Msg(\"setting orgCID in cookie\")\n\tif err := h.secureCookie.SetAuthCookie(w, results[\"access_token\"], orgData.OrgCID, orgData.SubscriptionID); err != nil {\n\t\tmiddleware.ReturnError(w, \"internal cookie failure\", 500)\n\t\treturn\n\t}\n\tw.WriteHeader(200)\n\tfmt.Fprint(w, string(respData))\n}", "func (u *User) PostLogin(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\n\tw.Header().Set(\"Cache-Control\", \"no-store\")\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"Pragma\", \"no-cache\")\n\n\t// If the session already exists, redirect them back to the home page.\n\t// if ok := u.session.HasSession(r); ok {\n\t// http.Redirect(w, r, \"/\", http.StatusFound)\n\t// return\n\t// }\n\n\tvar req Credentials\n\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\t// Check if the user is logging with many failed attempts.\n\tif locked := u.appsensor.IsLocked(req.Email); locked {\n\t\twriteError(w, http.StatusTooManyRequests, errors.New(\"too many attempts\"))\n\t\treturn\n\t}\n\n\tuser, err := u.service.Login(req.Email, req.Password)\n\tif err != nil {\n\t\t// Log attempts here.\n\t\tu.appsensor.Increment(req.Email)\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tprovideToken := func(userid string) (string, error) {\n\t\tvar (\n\t\t\taud = \"https://server.example.com/login\"\n\t\t\tsub = userid\n\t\t\tiss = userid\n\t\t\tiat = time.Now().UTC()\n\t\t\texp = iat.Add(2 * time.Hour)\n\n\t\t\tkey = []byte(\"access_token_secret\")\n\t\t)\n\t\tclaims := crypto.NewStandardClaims(aud, sub, iss, iat.Unix(), exp.Unix())\n\t\treturn crypto.NewJWT(key, claims)\n\t}\n\n\taccessToken, err := provideToken(user.ID)\n\tif err != nil {\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\t// Set the user session.\n\tu.session.SetSession(w, user.ID)\n\n\t// Set success ok.\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(M{\n\t\t\"access_token\": accessToken,\n\t})\n}", "func LoginHandler(w *http.ResponseWriter, r *http.Request, p *persistance.Persistance) {\n\tvar env s.Envelop\n\terr := env.FromEnvelop(r)\n\tcheckErr(err)\n\n}", "func (sry *Sryun) Login(res http.ResponseWriter, req *http.Request) (*model.User, bool, error) {\n\tusername := req.FormValue(\"username\")\n\tpassword := req.FormValue(\"password\")\n\n\tlog.Infoln(\"got\", username, \"/\", password)\n\n\tif username == sry.User.Login && password == sry.Password {\n\t\treturn sry.User, true, nil\n\t}\n\treturn nil, false, errors.New(\"bad auth\")\n}", "func Login() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tvar user userLogin\n\t\t// Try to decode the request body into the struct. If there is an error,\n\t\t// respond to the client with the error message and a 400 status code.\n\t\terr := json.NewDecoder(r.Body).Decode(&user)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\t// when user credentials are identified we can set token and send cookie with jwt\n\t\t// boolean, User returned\n\t\tfmt.Println(\"User sent password: \" + user.UserName + \" \" + user.Password)\n\t\tuserCred, isValid := ValidUserPassword(user.UserName, user.Password)\n\t\tif isValid {\n\t\t\tlog.Info(\"User valid login \" + user.UserName)\n\t\t\tfmt.Println(userCred.UserID)\n\t\t\thttp.SetCookie(w, jwt.PrepareCookie(jwt.CreateToken(w, userCred), \"jwt\"))\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusUnprocessableEntity) // send a 422 -- user they sent does not exist\n\t\t\tutil.Response(w, util.Message(\"422\", \"Unprocessable Entity - check what you're sending - user might not exist\"))\n\t\t\t//w.Write([]byte(\"422 - Unprocessable Entity - check what you're sending - user might not exist\"))\n\t\t}\n\t}\n}", "func (a *App) Login(w http.ResponseWriter, r *http.Request) {\n\tvar resp = map[string]interface{}{\"status\": \"success\", \"message\": \"logged in\"}\n\n\tuser := &models.User{}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tuser.Prepare() // here strip the text of white spaces\n\n\terr = user.Validate(\"login\") // fields(email, password) are validated\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tusr, err := user.GetUser(a.DB)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tif usr == nil { // user is not registered\n\t\tresp[\"status\"] = \"failed\"\n\t\tresp[\"message\"] = \"Login failed, please signup\"\n\t\tresponses.JSON(w, http.StatusBadRequest, resp)\n\t\treturn\n\t}\n\n\terr = models.CheckPasswordHash(user.Password, usr.Password)\n\tif err != nil {\n\t\tresp[\"status\"] = \"failed\"\n\t\tresp[\"message\"] = \"Login failed, please try again\"\n\t\tresponses.JSON(w, http.StatusForbidden, resp)\n\t\treturn\n\t}\n\ttoken, err := utils.EncodeAuthToken(usr.ID)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tresp[\"token\"] = token\n\tresponses.JSON(w, http.StatusOK, resp)\n\treturn\n}", "func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\t_, err := req.Cookie(\"login\")\n\tif err == nil {\n\t\thttp.Redirect(res, req, \"app\", http.StatusSeeOther)\n\t}\n\tTPL.ExecuteTemplate(res, \"login\", nil)\n}", "func UsersLoginPost(c buffalo.Context) error {\n\tuser := &models.User{}\n\t// Bind the user to the html form elements\n\tif err := c.Bind(user); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\ttx := c.Value(\"tx\").(*pop.Connection)\n\terr := user.Authorize(tx)\n\tif err != nil {\n\t\tc.Set(\"user\", user)\n\t\tverrs := validate.NewErrors()\n\t\tverrs.Add(\"Login\", \"Invalid email or password.\")\n\t\tc.Set(\"errors\", verrs.Errors)\n\t\treturn c.Render(422, r.HTML(\"users/login\"))\n\t}\n\tc.Session().Set(\"current_user_id\", user.ID)\n\tc.Flash().Add(\"success\", \"Welcome back!\")\n\treturn c.Redirect(302, \"/\")\n}", "func Login(username string, password string) error {\n\tdata := url.Values{}\n\tdata.Set(\"login\", username)\n\tdata.Set(\"haslo\", password)\n\n\tres, err := http.Post(loginURL, \"application/x-www-form-urlencoded\", strings.NewReader(data.Encode()))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to make HTTP POST login request: %v\", err)\n\t}\n\n\tlog.Println(\"auth status:\", res.Status)\n\n\treturn nil\n}", "func LoginHandler(c *gin.Context) {\n\tval, _ := c.Cookie(\"auth\")\n\tif val != \"\" {\n\t\tc.Redirect(http.StatusOK, \"/dashboard\")\n\t\treturn\n\t}\n\n\tinfo := models.LoginInfo{\n\t\tEmail: c.Query(\"email\"),\n\t\tPassword: c.Query(\"password\"),\n\t}\n\n\tif info.Email == \"\" || info.Password == \"\" {\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/\")\n\t\treturn\n\t}\n\n\tif ok, err := crud.CheckLoginInfo(info); !ok || err != nil {\n\t\tc.HTML(http.StatusInternalServerError, \"login.html\", err.Error())\n\t}\n\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/dashboard\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/data\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/report\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/config\", \"127.0.0.1\", false, false)\n\tc.SetCookie(\"auth\", \"yes\", 86400, \"/config/submit\", \"127.0.0.1\", false, false)\n\n\tc.Redirect(http.StatusTemporaryRedirect, \"/dashboard\")\n\treturn\n}", "func Login(rw http.ResponseWriter, request *http.Request) {\n\n\tlog.Println(\"call Login\")\n\n\t// フォームデータのパース\n\terr := request.ParseForm()\n\tif err != nil {\n\t\toutputErrorLog(\"フォーム パース 失敗\", err)\n\t}\n\n\t// リクエストデータ取得\n\taccount := request.Form.Get(\"account\")\n\tpassword := request.Form.Get(\"password\")\n\tlog.Println(\"ユーザ:\", account)\n\n\t// ユーザデータ取得しモデルデータに変換\n\tdbm := db.ConnDB()\n\tuser := new(models.User)\n\trow := dbm.QueryRow(\"select account, name, password from users where account = ?\", account)\n\tif err = row.Scan(&user.Name, &user.Account, &user.Password); err != nil {\n\t\toutputErrorLog(\"ユーザ データ変換 失敗\", err)\n\t}\n\n\t// ユーザのパスワード認証\n\tif user.Password != password {\n\t\tlog.Println(\"ユーザ パスワード照合 失敗\")\n\t\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\n\tlog.Println(\"認証 成功\")\n\n\t// 認証が通ったら、セッション情報をDBに保存\n\tsessionID := generateSessionID(account)\n\tlog.Println(\"生成したセッションID:\", sessionID)\n\tnow := time.Now()\n\tresult, err := dbm.Exec(`INSERT INTO sessions\n\t\t(sessionID, account, expireDate)\n\t\tVALUES\n\t\t(?, ?, ?)\n\t\t`, sessionID, account, now.Add(1*time.Hour))\n\tnum, err := result.RowsAffected()\n\tif err != nil || num == 0 {\n\t\toutputErrorLog(\"セッション データ保存 失敗\", err)\n\t}\n\n\tlog.Println(\"セッション データ保存 成功\")\n\n\t// クッキーにセッション情報付与\n\tcookie := &http.Cookie{\n\t\tName: sessionIDName,\n\t\tValue: sessionID,\n\t}\n\thttp.SetCookie(rw, cookie)\n\n\t// HOME画面に遷移\n\thttp.Redirect(rw, request, \"/home\", http.StatusFound)\n}", "func (ctrl LoginController) ProcessLogin(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tsession, _ := store.Get(r, \"session-id\")\n\tusername := r.PostFormValue(\"username\")\n\tpassword := r.PostFormValue(\"password\")\n\n\tuser, _ := model.GetUserByUserName(username)\n\tv := new(Validator)\n\n\tif !v.ValidateUsername(username) {\n\t\tSessionFlash(v.err, w, r)\n\t\thttp.Redirect(w, r, URL_LOGIN, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tif user.Username == \"\" || !CheckPasswordHash(password, user.Password) {\n\t\tSessionFlash(messages.Error_username_or_password, w, r)\n\t\thttp.Redirect(w, r, URL_LOGIN, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tsession.Values[\"username\"] = user.Username\n\tsession.Values[\"id\"] = user.ID\n\tsession.Save(r, w)\n\thttp.Redirect(w, r, URL_HOME, http.StatusMovedPermanently)\n}", "func Login(c *gin.Context) {\n\tvar customerForm models.CustomerForm\n\tif err := c.ShouldBindJSON(&customerForm); err != nil {\n\t\tc.JSON(http.StatusBadRequest, \"Incorrect user informations\")\n\t\treturn\n\t}\n\n\t// Try to find user with this address\n\tcustomer := models.Customer{\n\t\tEmail: customerForm.Email,\n\t}\n\tif err := repositories.FindCustomerByEmail(&customer); err != nil {\n\t\tc.JSON(http.StatusUnauthorized, \"incorrect email or password.\")\n\t\treturn\n\t}\n\n\t// Verify password\n\thashedPwd := services.HashPassword(customerForm.Password)\n\tif hashedPwd != customer.HashedPassword {\n\t\tc.JSON(http.StatusUnauthorized, \"incorrect email or password.\")\n\t\treturn\n\t}\n\n\t// Generate connection token\n\ttoken, err := services.GenerateToken(customer.Email)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, \"Couldn't create your authorization\")\n\t\treturn\n\t}\n\tvalidTime, _ := strconv.ParseInt(config.GoDotEnvVariable(\"TOKEN_VALID_DURATION\"), 10, 64)\n\n\tc.SetCookie(\"token\", token, 60*int(validTime), \"/\", config.GoDotEnvVariable(\"DOMAIN\"), false, false)\n\tc.JSON(http.StatusOK, \"Logged in successfully\")\n}", "func (u *User) login(ctx *clevergo.Context) error {\n\tuser, _ := u.User(ctx)\n\tif !user.IsGuest() {\n\t\tctx.Redirect(\"/\", http.StatusFound)\n\t\treturn nil\n\t}\n\n\tif ctx.IsPost() {\n\t\tform := forms.NewLogin(u.DB(), user, u.captchaManager)\n\t\tif _, err := form.Handle(ctx); err != nil {\n\t\t\treturn jsend.Error(ctx.Response, err.Error())\n\t\t}\n\n\t\treturn jsend.Success(ctx.Response, nil)\n\t}\n\n\treturn ctx.Render(http.StatusOK, \"user/login.tmpl\", nil)\n}", "func Login(req *restful.Request, res *restful.Response) {\n\tvar loginRequest map[string]interface{}\n\terr := json.NewDecoder(req.Request.Body).Decode(&loginRequest)\n\tif err != nil {\n\t\tres.WriteError(http.StatusInternalServerError, err)\n\t}\n\n\t//Send email with url to complete login process from here\n\tres.WriteEntity(loginRequest[\"email\"])\n}", "func LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tif SessionManager.Exists(r.Context(), \"userid\") {\n\t\thttp.Redirect(w, r, \"/worker\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tif r.Method == \"GET\" {\n\t\tloginErr(w, \"\")\n\t\treturn\n\t}\n\n\tvar err error\n\t// POST\n\tvar exists bool\n\tvar user shared.User\n\n\tusername := r.PostFormValue(\"username\")\n\tpassword := []byte(r.PostFormValue(\"password\"))\n\n\tif exists, err = shared.Db.DoesUserExists(username); err != nil {\n\t\tshared.HTTPerr(w, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif !exists {\n\t\tloginErr(w, fmt.Sprintf(\"User %s does not exists!\", username))\n\t\treturn\n\t}\n\n\t// authenticate user\n\tif user, err = shared.Db.GetUserByName(username); err != nil {\n\t\tshared.HTTPerr(w, err, http.StatusUnauthorized)\n\t\treturn\n\t}\n\tif err = bcrypt.CompareHashAndPassword(user.Password, password); err != nil {\n\t\tloginErr(w, \"Incorrect password!\")\n\t\treturn\n\t}\n\n\t// create new session\n\tif err = SessionManager.RenewToken(r.Context()); err != nil {\n\t\tshared.HTTPerr(w, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tSessionManager.Put(r.Context(), \"userid\", user.ID)\n\tSessionManager.RememberMe(r.Context(), true)\n\thttp.Redirect(w, r, \"/worker\", http.StatusSeeOther)\n}", "func loginFormHandler(w http.ResponseWriter, r *http.Request) {\n\t// Read the public key\n\tpemData, err := ioutil.ReadFile(PUBLIC_KEY_FILE)\n\tcheckHttpError(err, w)\n\tvar p = pageContent(r, \"Login\", pemData)\n\terr = templates[\"login\"].ExecuteTemplate(w, \"base\", p)\n\tcheckHttpError(err, w)\n}", "func (s *Server) Login(w http.ResponseWriter, r *http.Request) {\n\tvar acc data.Account\n\t// получение данных JSON account\n\tif err := json.NewDecoder(r.Body).Decode(&acc); err != nil {\n\t\thttp.Error(w, e.DecodeError.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\ttoken, err := s.service.Login(&acc)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tw.Header().Set(\"Token\", token)\n\tfmt.Fprint(w, \"See in tab Headers.\")\n}", "func (s *Server) handleAuthLogin() http.HandlerFunc {\n\ttype req struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t}\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tcred := &req{}\n\t\tvar err error\n\n\t\tif err = json.NewDecoder(r.Body).Decode(cred); err != nil {\n\t\t\ts.logger.Logf(\"[ERROR] During decode body: %v\\n\", err)\n\t\t\ts.error(w, r, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\n\t\tif cred.Username == \"\" || cred.Password == \"\" {\n\t\t\ts.logger.Logf(\"[ERROR] Empty credentials in body: %v\\n\", helpers.ErrNoBodyParams)\n\t\t\ts.error(w, r, http.StatusBadRequest, helpers.ErrNoBodyParams)\n\t\t\treturn\n\t\t}\n\n\t\ttoken, expTime, err := s.store.Users().Login(cred.Username, cred.Password, s.config.SecretKey)\n\t\tif err != nil {\n\t\t\ts.logger.Logf(\"[ERROR] %v\\n\", err)\n\t\t\ts.error(w, r, http.StatusBadRequest, err)\n\t\t\treturn\n\t\t}\n\n\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\tName: \"TKN\",\n\t\t\tValue: token,\n\t\t\tExpires: expTime,\n\t\t\tHttpOnly: true,\n\t\t\tPath: \"/\",\n\t\t\tDomain: s.config.AppDomain,\n\t\t})\n\n\t\ts.respond(w, r, http.StatusOK, map[string]string{\n\t\t\t\"login\": \"successful\",\n\t\t\t// \"user\": cred.Username,\n\t\t\t\"token\": token,\n\t\t})\n\t}\n}", "func (httpcalls) Login(url string, jsonData []byte, client http.Client) (*http.Response, error) {\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Add(\"Content-type\", \"application/json\")\n\tresp, err := client.Do(req)\n\treturn resp, err\n}", "func (e *Example) PostLogin (ctx context.Context, req *example.Request, rsp *example.Response) error {\n\t/* Print */\n\tbeego.Info(\"PostLogin /api/v1.0/sessions\")\n\n\t/* Init */\n\trsp.Errno = utils.RECODE_OK\n\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\n\t/* MySQL*/\n\t// 1 orm\n\to := orm.NewOrm()\n\t// 2 db object\n\tuser := models.User{}\n\t// 3 select\n\tuser.Mobile = req.Mobile\n\terr := o.Read(&user,\"Mobile\")\n\tif err != nil {\n\t\trsp.Errno = utils.RECODE_NODATA\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin MySQL: \", err)\n\t\treturn nil\n\t}\n\n\t// Md5\n\thash, err := utils.CrotoMd5(req.Password)\n\tif err != nil{\n\t\trsp.Errno = utils.RECODE_UNKNOWERR\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin Md5: \", err)\n\t\treturn nil\n\t}\n\t// password\n\tif hash != user.Password_hash{\n\t\trsp.Errno = utils.RECODE_PWDERR\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin password: \", err)\n\t\treturn nil\n\t}\n\n\t/* sessionID */\n\trsp.SessionID, err = utils.CrotoMd5(req.Mobile + req.Password + strconv.Itoa(int(time.Now().UnixNano())))\n\tif err != nil {\n\t\trsp.Errno = utils.RECODE_UNKNOWERR\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin sessionID: \", err)\n\t\treturn nil\n\t}\n\n\t/* Redis */\n\tr, err := utils.RedisServer(utils.G_server_name, utils.G_redis_addr, utils.G_redis_port, utils.G_redis_dbnum)\n\tif err != nil{\n\t\trsp.Errno = utils.RECODE_DBERR\n\t\trsp.Errmsg = utils.RecodeText(rsp.Errno)\n\t\tbeego.Error(\"PostLogin Redis\")\n\t\treturn nil\n\t}\n\n\t/* <=Redis */\n\terr = r.Put(rsp.SessionID+\"name\", user.Name, time.Second*600)\n\terr = r.Put(rsp.SessionID+\"id\", user.Id, time.Second*600)\n\terr = r.Put(rsp.SessionID+\"mobile\", user.Mobile, time.Second*600)\n\n\treturn nil\n}", "func loginHandler(rw http.ResponseWriter, req *http.Request) {\n\tsession, err := store.Get(req, CONFIG.SessionName)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading session: %v\", err)\n\t\tif cookie, err := req.Cookie(CONFIG.SessionName); err != nil {\n\t\t\tlog.Printf(\"Error reading cookie: %v\", err)\n\t\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\t} else {\n\t\t\tcookie.MaxAge = -1\n\t\t\thttp.SetCookie(rw, cookie)\n\t\t\thttp.Redirect(rw, req, \"/\", http.StatusFound)\n\t\t}\n\t\treturn\n\t}\n\tcode := req.FormValue(\"code\")\n\tclient := &http.Client{}\n\tresp, err := client.PostForm(\"https://cloud.digitalocean.com/v1/oauth/token\",\n\t\turl.Values{\n\t\t\t\"client_id\": {CONFIG.ClientId},\n\t\t\t\"client_secret\": {CONFIG.ClientSecret},\n\t\t\t\"code\": {code},\n\t\t\t\"grant_type\": {\"authorization_code\"},\n\t\t\t\"redirect_uri\": {CONFIG.CallbackUrl},\n\t\t})\n\tif err != nil {\n\t\tlog.Printf(\"Error reading cookie: %v\", err)\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading cookie: %v\", err)\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\tvar credentials DigitalOceanResponse\n\terr = json.Unmarshal(body, &credentials)\n\tsession.Values[\"accesstoken\"] = credentials.AccessToken\n\tsession.Values[\"name\"] = credentials.Info.Name\n\tsession.Save(req, rw)\n\thttp.Redirect(rw, req, \"/\", http.StatusFound)\n}", "func (h UserRepos) Login(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\n\tctxValues, err := webcontext.ContextValues(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//\n\treq := new(UserLoginRequest)\n\tdata := make(map[string]interface{})\n\tf := func() (bool, error) {\n\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\tif err := decoder.Decode(req, r.PostForm); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\treq.Password = strings.Replace(req.Password, \".\", \"\", -1)\n\t\t\tsessionTTL := time.Hour\n\t\t\tif req.RememberMe {\n\t\t\t\tsessionTTL = time.Hour * 36\n\t\t\t}\n\n\t\t\t// Authenticated the user.\n\t\t\ttoken, err := h.AuthRepo.Authenticate(ctx, user_auth.AuthenticateRequest{\n\t\t\t\tEmail: req.Email,\n\t\t\t\tPassword: req.Password,\n\t\t\t}, sessionTTL, ctxValues.Now)\n\t\t\tif err != nil {\n\t\t\t\tswitch errors.Cause(err) {\n\t\t\t\tcase user.ErrForbidden:\n\t\t\t\t\treturn false, web.RespondError(ctx, w, weberror.NewError(ctx, err, http.StatusForbidden))\n\t\t\t\tcase user_auth.ErrAuthenticationFailure:\n\t\t\t\t\tdata[\"error\"] = weberror.NewErrorMessage(ctx, err, http.StatusUnauthorized, \"Invalid username or password. Try again.\")\n\t\t\t\t\treturn false, nil\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// Add the token to the users session.\n\t\t\terr = handleSessionToken(ctx, w, r, token)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tredirectUri := \"/\"\n\t\t\tif qv := r.URL.Query().Get(\"redirect\"); qv != \"\" {\n\t\t\t\tredirectUri, err = url.QueryUnescape(qv)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Redirect the user to the dashboard.\n\t\t\treturn true, web.Redirect(ctx, w, r, redirectUri, 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[\"form\"] = req\n\n\tif verr, ok := weberror.NewValidationError(ctx, webcontext.Validator().Struct(UserLoginRequest{})); ok {\n\t\tdata[\"validationDefaults\"] = verr.(*weberror.Error)\n\t}\n\n\treturn h.Renderer.Render(ctx, w, r, TmplLayoutBase, \"user-login.gohtml\", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)\n}", "func handleLogin(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparseFormErr := r.ParseForm()\n\n\tif parseFormErr != nil {\n\t\thttp.Error(w, \"Sent invalid form\", http.StatusBadRequest)\n\t} else {\n\t\temail := r.FormValue(\"email\")\n\t\tpassword := r.FormValue(\"password\")\n\n\t\tchannel := make(chan FindUserResponse)\n\t\tgo GetUserWithLogin(email, password, channel)\n\n\t\tres := <-channel\n\n\t\tif res.Err != nil {\n\t\t\tif res.Err.Error() == UserNotFound || res.Err.Error() == PasswordNotMatching {\n\t\t\t\thttp.Error(w, \"Provided email/password do not match\", http.StatusNotFound)\n\t\t\t} else {\n\t\t\t\tcommon.SendInternalServerError(w)\n\t\t\t}\n\t\t} else {\n\t\t\ttoken, expiry, jwtErr := middleware.CreateLoginToken(res.User)\n\n\t\t\tif jwtErr != nil {\n\t\t\t\tlog.Println(jwtErr)\n\t\t\t\tcommon.SendInternalServerError(w)\n\t\t\t} else {\n\t\t\t\tres.User.Password = nil\n\t\t\t\tjsonResponse, jsonErr := json.Marshal(res.User)\n\n\t\t\t\tif jsonErr != nil {\n\t\t\t\t\tlog.Println(jsonErr)\n\t\t\t\t\tcommon.SendInternalServerError(w)\n\t\t\t\t} else {\n\n\t\t\t\t\tjsonEncodedCookie := strings.ReplaceAll(string(jsonResponse), \"\\\"\", \"'\") // Have to do this to Set-Cookie in psuedo-JSON format.\n\n\t\t\t\t\t_, inProduction := os.LookupEnv(\"PRODUCTION\")\n\n\t\t\t\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\t\t\t\tName: \"token\",\n\t\t\t\t\t\tValue: token,\n\t\t\t\t\t\tPath: \"/\",\n\t\t\t\t\t\tExpires: expiry,\n\t\t\t\t\t\tRawExpires: expiry.String(),\n\t\t\t\t\t\tSecure: inProduction,\n\t\t\t\t\t\tHttpOnly: true,\n\t\t\t\t\t\tSameSite: 0,\n\t\t\t\t\t})\n\n\t\t\t\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\t\t\t\tName: \"userinfo\",\n\t\t\t\t\t\tValue: jsonEncodedCookie,\n\t\t\t\t\t\tPath: \"/\",\n\t\t\t\t\t\tExpires: expiry,\n\t\t\t\t\t\tRawExpires: expiry.String(),\n\t\t\t\t\t\tSecure: false,\n\t\t\t\t\t\tHttpOnly: false,\n\t\t\t\t\t\tSameSite: 0,\n\t\t\t\t\t})\n\n\t\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\t\tw.Write(jsonResponse)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func loginHandler() http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == http.MethodPost {\n\t\t\tusername := r.FormValue(\"username\")\n\t\t\tpassword := r.FormValue(\"password\")\n\t\t\tok, err := authenticate(username, password)\n\t\t\tif !ok {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Generate JWT and set in the response's cookie.\n\t\t\ttokenStr, err := newJWT(username)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\t\tName: cookieName,\n\t\t\t\tValue: tokenStr,\n\t\t\t\tExpires: time.Now().Add(expireDuration),\n\t\t\t})\n\n\t\t\thttp.Redirect(w, r, \"/welcome\", http.StatusSeeOther)\n\n\t\t\treturn\n\t\t}\n\n\t\toutputHTML(w, r, \"html/login.html\")\n\t})\n}", "func LoginHandler(conf *Config) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tsession, loggedIn, err := CheckLogin(w, r)\n\t\tif err != nil {\n\t\t\tlog.Println(\"error trying to retrieve session on login page:\", err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t// if already logged in the user has already been redirected.\n\t\t// rest of logic can be ignored.\n\t\tif loggedIn {\n\t\t\thttp.Redirect(w, r, \"/control\", http.StatusFound)\n\t\t\treturn\n\t\t}\n\n\t\tif r.Method == \"GET\" {\n\n\t\t\ttempControl := TemplateHandler{\n\t\t\t\tfilename: \"login.html\",\n\t\t\t\tdata: map[string]interface{}{\n\t\t\t\t\t\"location\": conf.Location,\n\t\t\t\t},\n\t\t\t}\n\t\t\ttempControl.ServeHTTP(w, r)\n\t\t\treturn\n\t\t} else if r.Method != \"POST\" {\n\t\t\tlog.Println(\"Unsuported request type for Settings page:\", r.Method)\n\t\t\treturn\n\t\t}\n\n\t\t// process POST request\n\t\txForward := r.Header.Get(\"x-forwarded-for\")\n\t\tif conf.Debug {\n\t\t\tlog.Println(\"attempted login request from:\", xForward, r.RemoteAddr)\n\t\t}\n\t\tif err := r.ParseForm(); err != nil {\n\t\t\tlog.Println(\"Error trying to parse form in login page.\\n\", err)\n\t\t}\n\t\tusername := r.PostFormValue(\"username\")\n\t\tpassword := r.PostFormValue(\"password\")\n\n\t\t// if there's no login entry in the config file, add the default login details\n\t\tif conf.Login.Username == \"\" {\n\t\t\tif conf.Debug {\n\t\t\t\tlog.Println(\"no login details found in config file, creating default login details now.\")\n\t\t\t}\n\t\t\tvar err error\n\t\t\tif conf.Login, err = newLogin(); err != nil {\n\t\t\t\tlog.Println(\"error trying to save default username and password\")\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := conf.Save(\"\"); err != nil {\n\t\t\t\tlog.Println(\"error trying to save config file:\", err)\n\t\t\t}\n\t\t}\n\n\t\tif username == conf.Login.Username && checkHash(password, conf.Login.Password) {\n\t\t\t// user successfully logged in\n\t\t\tsession.Values[\"x-forwarded-for\"] = xForward\n\t\t\tsession.Save(r, w)\n\t\t\thttp.Redirect(w, r, \"/control\", http.StatusFound)\n\t\t\treturn\n\t\t}\n\n\t\ttempControl := TemplateHandler{\n\t\t\tfilename: \"login.html\",\n\t\t\tdata: map[string]interface{}{\n\t\t\t\t\"location\": conf.Location,\n\t\t\t\t\"flashMessage\": \"Incorrect username or password\",\n\t\t\t},\n\t\t}\n\t\ttempControl.ServeHTTP(w, r)\n\t}\n}", "func loginActionHandler(w http.ResponseWriter, r *http.Request) {\n\n\t// Read the private key\n\tpemData, err := ioutil.ReadFile(PRIVATE_KEY_FILE)\n\tcheckHttpError(err, w)\n\n\t// Extract the PEM-encoded data block\n\tblock, _ := pem.Decode(pemData)\n\tif block == nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif got, want := block.Type, \"RSA PRIVATE KEY\"; got != want {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Decode the RSA private key\n\tpriv, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tcheckHttpError(err, w)\n\n\t// Decode the Base64 into binary\n\tcipheredValue, err := base64.StdEncoding.DecodeString(r.FormValue(\"CipheredValue\"))\n\tcheckHttpError(err, w)\n\n\t// Decrypt the data\n\tvar out []byte\n\tout, err = rsa.DecryptPKCS1v15(rand.Reader, priv, cipheredValue)\n\tcheckHttpError(err, w)\n\n\t//home or login\n\tsession, _ := store.Get(r, \"goServerView\")\n\th := sha512.New()\n\th.Write(out)\n\tstr := base64.StdEncoding.EncodeToString(h.Sum([]byte{}))\n\n\tif str == config.Password {\n\t\tsession.Values[\"isConnected\"] = true\n\t\tsession.Values[\"user\"] = r.FormValue(\"User\")\n\t\tsession.Save(r, w)\n\t\thomeHandler(w, r)\n\t} else {\n\t\tsession.Values[\"isConnected\"] = false\n\t\tsession.AddFlash(\"Either the username or the password provided is wrong\")\n\t\tsession.Save(r, w)\n\t\tloginFormHandler(w, r)\n\t}\n}", "func (server *MainServer) LoginHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {\n\twriter.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tvar requestBody token.RequestDTO\n\terr := json.NewDecoder(request.Body).Decode(&requestBody)\n\tif err != nil {\n\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\terr := json.NewEncoder(writer).Encode([]string{\"err.json_invalid\"})\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\n\tlog.Printf(\"login = %s, pass = %s\\n\", requestBody.Username, requestBody.Password)\n\tresponse, err := server.tokenSvc.Generate(request.Context(), &requestBody)\n\tif err != nil {\n\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\terr := json.NewEncoder(writer).Encode([]string{\"err.password_mismatch\", err.Error()})\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t\treturn\n\t}\n\tuser, err := server.tokenSvc.FindUserForPassCheck(requestBody.Username)\n\t//log.Println(response)\n\tif err != nil {\n\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\terr := json.NewEncoder(writer).Encode([]string{\"err.password_mismatch\", err.Error()})\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t\treturn\n\t}\n\tok := models.CheckStatusLine(user.StatusLine)\n\tif ok == false && user.Role == \"user\"{\n\t\twriter.WriteHeader(http.StatusIMUsed)\n\t\treturn\n\t}\n\t//const StatusLine = true\n\t//err = server.svc.SetStatusLine(requestBody.Username, StatusLine)\n\t//if err != nil {\n\t//\twriter.WriteHeader(http.StatusBadRequest)\n\t//\terr := json.NewEncoder(writer).Encode([]string{\"err.password_mismatch\", err.Error()})\n\t//\tif err != nil {\n\t//\t\tlog.Print(err)\n\t//\t}\n\t//\treturn\n\t//}\n\terr = server.svc.SetLoginTime(user.Id)\n\tif err != nil {\n\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\terr := json.NewEncoder(writer).Encode([]string{\"err.password_mismatch\", err.Error()})\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t\treturn\n\t}\n\terr = server.svc.SetVisitTime(user.Id)\n\tif err != nil {\n\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\terr := json.NewEncoder(writer).Encode([]string{\"err.can't fix Visit times\", err.Error()})\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t}\n\tresponse.Role = user.Role\n\tresponse.State = user.Status\n\tresponse.Name = user.Name \t\n\tresponse.Surname = user.Surname\n\terr = json.NewEncoder(writer).Encode(&response)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\tpageVars := PageVars{}\n\taddPageVars(r, &pageVars)\n\trender(w, \"login\", pageVars)\n}", "func Login(w http.ResponseWriter, req *http.Request) {\n\tvar loginValidator LoginValidator\n\tvar response shared.Response\n\n\t_ = json.NewDecoder(req.Body).Decode(&loginValidator)\n\n\tresponseLogin := LoginService(loginValidator)\n\tresponse.Status = shared.StatusSuccess\n\tresponse.Data = responseLogin\n\tjson.NewEncoder(w).Encode(response)\n}", "func (app *application) loginForm(w http.ResponseWriter, r *http.Request) {\n\tapp.renderLogin(w, r, \"login.page.tmpl\", &templateDataLogin {\n\t\tForm: \t\t\tforms.New(nil),\n\t})\n}", "func LoginFunc(w http.ResponseWriter, r *http.Request) {\n\tsession, _ := sessions.Store.Get(r, \"session\")\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tview.LoginTemplate.Execute(w, nil)\n\tcase \"POST\":\n\t\tr.ParseForm()\n\t\tusername := r.Form.Get(\"username\")\n\t\tpassword := r.Form.Get(\"password\")\n\t\t// there will not handle the empty value it should be handle by javascript\n\t\tif user.UserIsExist(username) {\n\t\t\tif user.ValidUser(username, password) {\n\t\t\t\tsession.Values[\"loggedin\"] = \"true\"\n\t\t\t\tsession.Values[\"username\"] = username\n\t\t\t\tsession.Save(r, w)\n\t\t\t\tlog.Println(\"user\", username, \"is authenticated\")\n\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t\t} else {\n\t\t\t\thttp.Error(w, \"Wrong username or password\", http.StatusInternalServerError)\n\t\t\t}\n\t\t} else {\n\t\t\thttp.Error(w, \"User doesnt exist\", http.StatusInternalServerError)\n\t\t}\n\tdefault:\n\t\thttp.Redirect(w, r, \"/login/\", http.StatusUnauthorized)\n\t}\n}", "func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\tvar data map[string]string\n\n\tresp, err := getBody(req)\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(resp, &data)\n\tif err != nil {\n\t\tlog.Panicln(\"login:\", err)\n\t}\n\n\tusername := data[\"username\"]\n\tpassword := data[\"password\"]\n\tuser, err := getUser(username)\n\tif err != nil {\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tsessID, err := authenticateUser(user, username, password)\n\tif err != nil {\n\t\tlog.Println(\"login:\", err)\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tresponse := jsMap{\n\t\t\"status\": \"OK\",\n\t\t\"sessionID\": hex.EncodeToString(sessID),\n\t\t\"address\": user.Address,\n\t}\n\n\twriteJSON(res, 200, response)\n}", "func (a *API) userLoginPostHandler(w http.ResponseWriter, r *http.Request) {\n\t// Validate user input\n\tvar u model.User\n\terr := json.NewDecoder(r.Body).Decode(&u)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t} else if u.Email == \"\" {\n\t\tresponse.Errorf(w, r, nil, http.StatusBadRequest, \"Email address is missing\")\n\t\treturn\n\t} else if u.Password == \"\" {\n\t\tresponse.Errorf(w, r, nil, http.StatusBadRequest, \"Password is missing\")\n\t\treturn\n\t}\n\t// Always use the lower case email address\n\tu.Email = strings.ToLower(u.Email)\n\t// Get the user database entry\n\tuser, err := a.db.GetUserByEmail(u.Email)\n\tif err != nil {\n\t\tresponse.Errorf(w, r, err, http.StatusInternalServerError, \"Internal Server Error\")\n\t\treturn\n\t} else if user == nil {\n\t\tresponse.Errorf(w, r, err, http.StatusBadRequest, \"Invalid email address or password\")\n\t\treturn\n\t}\n\t// Check the password\n\tif !user.MatchPassword(u.Password) {\n\t\tresponse.Errorf(w, r, err, http.StatusBadRequest, \"Invalid email address or password\")\n\t\treturn\n\t}\n\t// Create jwt token\n\tuser.Token, err = a.createJWT(jwt.MapClaims{\n\t\t\"email\": user.Email,\n\t\t\"name\": user.Name,\n\t\t\"lastname\": user.Lastname,\n\t\t\"password\": user.Password,\n\t\t\"exp\": time.Now().Add(time.Hour * 24 * 7).Unix(),\n\t})\n\tif err != nil {\n\t\tresponse.Errorf(w, r, err, http.StatusInternalServerError, \"Internal Server Error\")\n\t\treturn\n\t}\n\t//\thttp.SetCookie(w, &http.Cookie{\n\t//\t\tName: \"token\",\n\t//\t\tValue: u.Token,\n\t//\t\tPath: \"/\",\n\t//\t})\n\tresponse.Write(w, r, user)\n}", "func logIn(res http.ResponseWriter, req *http.Request) {\n\t// retrive the name form URL\n\tname := req.FormValue(\"name\")\n\tname = html.EscapeString(name)\n\tif name != \"\" {\n\t\tuuid := generateUniqueId()\n\t\tsessionsSyncLoc.Lock()\n\t\tsessions[uuid] = name\n\t\tsessionsSyncLoc.Unlock()\n\n\t\t// save uuid in the cookie\n\t\tcookie := http.Cookie{Name: \"uuid\", Value: uuid, Path: \"/\"}\n\t\thttp.SetCookie(res, &cookie)\n\n\t\t// redirect to /index.html endpoint\n\t\thttp.Redirect(res, req, \"/index.html\", http.StatusFound)\n\t} else {\n\t\t// if the provided input - name is empty, display this message\n\t\tres.Header().Set(\"Content-Type\", \"text/html\")\n\t\tfmt.Fprintf(\n\t\t\tres,\n\t\t\t`<html>\n\t\t\t<body>\n\t\t\t<form action=\"login\">\n\t\t\t C'mon, I need a name.\n\t\t\t</form>\n\t\t\t</p>\n\t\t\t</body>\n\t\t\t</html>`,\n\t\t)\n\t}\n}", "func (s *Server) Login(c *gin.Context) {\n\tvar login Login\n\tc.BindJSON(&login)\n\n\terr := login.Validate()\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"login\": true,\n\t})\n}", "func LoginAction(w http.ResponseWriter, r *http.Request) {\n\n\tpageVars := PageVars{}\n\taddPageVars(r, &pageVars)\n\n\tuserName := r.FormValue(\"userName\")\n\t// validate username\n\tif len(userName) <= 0 {\n\t\thttp.Redirect(w, r, \"/login?errorM=Username specified\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tpassword := r.FormValue(\"password\")\n\t// validate password\n\tif len(password) <= 0 {\n\t\thttp.Redirect(w, r, \"/login?errorM=Password specified\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\t// get expected password\n\texpectedPassword := getStringFromDB(\"Users\", userName)\n\n\t// verify the password\n\tif expectedPassword != password {\n\t\thttp.Redirect(w, r, \"/login?errorM=Invalid credentials\", http.StatusSeeOther)\n\t\treturn\n\t}\n\t\n\t// Create a new random session token\n\tsessionToken, err := uuid.NewUUID()\n\tif err != nil {\n\t\thttp.Redirect(w, r, \"/login?errorM=Unable to create token\", http.StatusSeeOther)\n\t}\n\t// Set the token in the db, along with the userName\n\tupdateDBString(\"Sessions\", userName, sessionToken.String())\n\n\t// set the expiration time\n\texpires := time.Now().Add(600 * time.Second)\n\tck := http.Cookie{\n Name: \"JSESSION_ID\",\n Path: \"/\",\n\t\tExpires: expires,\n\t\tValue: userName+\"_\"+sessionToken.String(),\n\t}\n\n // write the cookie to response\n http.SetCookie(w, &ck)\n\thttp.Redirect(w, r, \"/listbuckets\", http.StatusSeeOther)\n\n}", "func LoginHandler(c *gin.Context) {\n\tloginFrom := LoginRequest{}\n\terr := c.ShouldBindJSON(&loginFrom)\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(400, gin.H{\n\t\t\t\"message\": \"Invalid json request.\",\n\t\t})\n\t\treturn\n\t}\n\tisPasswordCorrect := comparePassword(loginFrom)\n\tif !isPasswordCorrect {\n\t\tc.AbortWithStatusJSON(401, gin.H{\n\t\t\t\"message\": \"Username or/and Password are not correct.\",\n\t\t})\n\t\treturn\n\t}\n\ttoken, err := login(loginFrom)\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(500, gin.H{\n\t\t\t\"message\": \"Something went wrong when generating token.\",\n\t\t})\n\t\treturn\n\t}\n\tc.JSON(200, gin.H{\n\t\t\"token\": token,\n\t})\n}", "func Login(rw http.ResponseWriter, req *http.Request) {\n\n\tif req.Method == \"GET\" {\n\t\trw.Write([]byte(\"Only POST request allowed\"))\n\t} else {\n\n\t\t// Input from request body\n\t\tdec := json.NewDecoder(req.Body)\n\t\tvar t c.User\n\t\terr := dec.Decode(&t)\n\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\trw.Write(Rsp(err.Error(), \"Error in Decoding Data\"))\n\t\t\treturn\n\t\t}\n\n\t\t// Check if all parametes are there\n\t\tif Valid := c.ValidateCredentials(t); Valid != \"\" {\n\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\trw.Write(Rsp(err.Error(), \"Bad Request\"))\n\t\t\treturn\n\t\t}\n\n\t\t// Get existing data on user\n\t\tdt, err := db.GetUser(t.Roll)\n\t\tif err != nil {\n\t\t\tif err == sql.ErrNoRows {\n\t\t\t\trw.WriteHeader(http.StatusUnauthorized)\n\t\t\t\tresponse := c.Response{\n\t\t\t\t\tError: err.Error(),\n\t\t\t\t\tMessage: \"User Not registered\",\n\t\t\t\t}\n\t\t\t\tjson.NewEncoder(rw).Encode(response)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\t\treturn\n\t\t}\n\n\t\t// check if password is right\n\t\terr = auth.Verify(t.Password, dt.Password)\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusUnauthorized)\n\t\t\trw.Write(Rsp(err.Error(), \"Wrong Password\"))\n\t\t\treturn\n\t\t}\n\n\t\t// All good yaayy\n\t\trw.WriteHeader(http.StatusOK)\n\t\tmsg := fmt.Sprintf(\"Hey, User %s! Your roll is %d. \", dt.Name, dt.Roll)\n\n\t\t// get token to\n\t\ttokenString, err := auth.GetJwtToken(dt)\n\t\tif err != nil {\n\t\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\t\tresponse := c.Response{\n\t\t\t\tError: err.Error(),\n\t\t\t\tMessage: \"Error While getting JWT token\",\n\t\t\t}\n\t\t\tjson.NewEncoder(rw).Encode(response)\n\t\t\treturn\n\t\t}\n\t\trw.Write(RspToken(\"\", msg+\"This JWT Token Valid for next 12 Hours\", tokenString))\n\t}\n}" ]
[ "0.81102294", "0.78819275", "0.781747", "0.77993685", "0.7782218", "0.77255404", "0.7672384", "0.7642712", "0.76279587", "0.7588439", "0.7473256", "0.746993", "0.7370692", "0.7357331", "0.73544604", "0.72728825", "0.7212554", "0.72107416", "0.71366787", "0.713251", "0.71173364", "0.71011955", "0.7048958", "0.70095044", "0.6999244", "0.69913876", "0.69903207", "0.6984843", "0.6977896", "0.69682497", "0.689455", "0.6862876", "0.6831749", "0.6826641", "0.67925817", "0.67833716", "0.67833483", "0.67813903", "0.6753967", "0.6743028", "0.67359954", "0.67335933", "0.67331386", "0.6727924", "0.6726381", "0.6725741", "0.6719948", "0.6713892", "0.67129445", "0.6706535", "0.66971517", "0.66951597", "0.66942596", "0.66867185", "0.66819143", "0.6677562", "0.66416824", "0.6625643", "0.6601996", "0.6560322", "0.6553382", "0.6548816", "0.6539994", "0.6539831", "0.653922", "0.65378696", "0.65366817", "0.6534569", "0.65231246", "0.65213025", "0.6503816", "0.6502825", "0.6493427", "0.64903927", "0.6487681", "0.6484137", "0.6474961", "0.6461465", "0.64612293", "0.64549196", "0.6448451", "0.6448051", "0.6445701", "0.64441705", "0.64336187", "0.6428228", "0.64273316", "0.64248365", "0.6416708", "0.64133126", "0.639018", "0.6387185", "0.6380325", "0.63740027", "0.6373723", "0.6373434", "0.6370629", "0.6366997", "0.6339777", "0.6337628" ]
0.74688363
12
LogoutGET clears the session and logs the user out
func LogoutGET(w http.ResponseWriter, r *http.Request) { // Get session sess := model.Instance(r) // If user is authenticated if sess.Values["id"] != nil { model.Empty(sess) sess.AddFlash(view.Flash{"Goodbye!", view.FlashNotice}) sess.Save(r, w) } http.Redirect(w, r, "/", http.StatusFound) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Logout(w http.ResponseWriter, r *http.Request) {\n\tPrintln(\"Endpoint Hit: Logout\")\n\n\tsession := sessions.Start(w, r)\n\tsession.Clear()\n\tsessions.Destroy(w, r)\n\thttp.Redirect(w, r, \"/\", 302)\n}", "func Logout(w http.ResponseWriter, req *http.Request) {\n\tif !requirePost(w, req) {\n\t\tlog.Warn(\"Logout request should use POST method\")\n\t\treturn\n\t}\n\tif !requireAuth(w, req) {\n\t\tlog.Warn(\"Logout request should be authenticated\")\n\t\treturn\n\t}\n\tsid := req.Context().Value(auth.SESSION_ID).(string)\n\terr := storage.DeleteSession(sid)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\tconf.RedirectTo(\"/\", \"\", w, req)\n}", "func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\terr := h.Services.User.Logout(Authorized.UUID)\n\t\tif err != nil {\n\t\t\tJsonResponse(w, r, http.StatusBadRequest, \"\")\n\t\t\treturn\n\t\t}\n\t\tJsonResponse(w, r, http.StatusOK, \"success\")\n\tcase \"POST\":\n\tdefault:\n\t\tJsonResponse(w, r, http.StatusBadRequest, \"Bad Request\")\n\t}\n}", "func logout(w http.ResponseWriter, r *http.Request) {\n\n\tsession := sessions.Start(w, r)\n\tsession.Clear()\n\tsessions.Destroy(w, r)\n\thttp.Redirect(w, r, \"/\", 302)\n\n}", "func logout(ctx context.Context) error {\n\tr := ctx.HttpRequest()\n\tsession, _ := core.GetSession(r)\n\t_, ok := session.Values[\"user\"]\n\tif ok {\n\t\tdelete(session.Values, \"user\")\n\t\tif err := session.Save(r, ctx.HttpResponseWriter()); err != nil {\n\t\t\tlog.Error(\"Unable to save session: \", err)\n\t\t}\n\t}\n\treturn goweb.Respond.WithPermanentRedirect(ctx, \"/\")\n}", "func Logout(w http.ResponseWriter, r *http.Request) {\n\tuser := r.Context().Value(utils.TokenContextKey).(string)\n\tmessage := models.Logout(user)\n\tutils.JSONResonseWithMessage(w, message)\n}", "func logout(c *gin.Context) {\n\t//Give the user a session\n\tsession := sessions.Default(c)\n\tclearSession(&session)\n\n\tc.Redirect(http.StatusFound, \"/\")\n}", "func Logout(r *http.Request) {\n\ts := getSessionFromRequest(r)\n\tif s.ID == 0 {\n\t\treturn\n\t}\n\n\t// Store Logout to the user log\n\tfunc() {\n\t\tlog := &Log{}\n\t\tlog.SignIn(s.User.Username, log.Action.Logout(), r)\n\t\tlog.Save()\n\t}()\n\n\ts.Logout()\n\n\t// Delete the cookie from memory if we sessions are cached\n\tif CacheSessions {\n\t\tdelete(cachedSessions, s.Key)\n\t}\n\n\tIncrementMetric(\"uadmin/security/logout\")\n}", "func logout(res http.ResponseWriter, req *http.Request) {\n sess := session.Get(req)\n\n session.Remove(sess, res)\n sess = nil\n\n return\n http.Redirect(res, req, \"/login\", 301)\n}", "func Logout(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tsession.Delete(\"user\");\n\tsession.Save();\n\tc.JSON(200, gin.H{\n\t\t\"success\": true,\n\t})\n}", "func Logout(w http.ResponseWriter, r *http.Request) {\r\n\t//Get user id of the session\r\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\r\n\tdefer cancel()\r\n\tcookie, err := r.Cookie(\"sessionId\")\r\n\tif err != nil || cookie.Value != \"\" {\r\n\t\ttoken, _ := url.QueryUnescape(cookie.Value)\r\n\t\t_, err = AuthClient.RemoveAuthToken(ctx, &authpb.AuthToken{Token: token})\r\n\t\texpiration := time.Now()\r\n\t\tcookie := http.Cookie{Name: \"sessionId\", Path: \"/\", HttpOnly: true, Expires: expiration, MaxAge: -1}\r\n\t\thttp.SetCookie(w, &cookie)\r\n\t}\r\n\tAPIResponse(w, r, 200, \"Logout successful\", make(map[string]string))\r\n}", "func Logout(rw http.ResponseWriter, request *http.Request) {\n\n\tlog.Println(\"call Logout\")\n\n\t// Cookieからセッション情報取得\n\tsessionID, err := request.Cookie(sessionIDName)\n\tif err != nil {\n\t\t// セッション情報取得に失敗した場合TOP画面に遷移\n\t\tlog.Println(\"Cookie 取得 失敗\")\n\t\tlog.Println(err)\n\t\t// Cookieクリア\n\t\tclearCookie(rw)\n\t\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\tlog.Println(\"Cookie 取得 成功\")\n\tlog.Println(\"セッション情報:\", sessionID.Value)\n\n\t// セッション情報を削除\n\tdbm := db.ConnDB()\n\t_, err = dbm.Exec(\"delete from sessions where sessionID = ?\", sessionID.Value)\n\tif err != nil {\n\t\tlog.Println(\"セッション 削除 失敗\")\n\t} else {\n\t\tlog.Println(\"セッション 削除 成功\")\n\t\tlog.Println(\"削除したセッションID:\", sessionID.Value)\n\t}\n\n\t// CookieクリアしてTOP画面表示\n\tclearCookie(rw)\n\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n}", "func logout(w http.ResponseWriter, r *http.Request) {\n\n\tif isAuthorized(w, r) {\n\t\tusername, _ := r.Cookie(\"username\")\n\t\tdelete(gostuff.SessionManager, username.Value)\n\t\tcookie := http.Cookie{Name: \"username\", Value: \"0\", MaxAge: -1}\n\t\thttp.SetCookie(w, &cookie)\n\t\tcookie = http.Cookie{Name: \"sessionID\", Value: \"0\", MaxAge: -1}\n\t\thttp.SetCookie(w, &cookie)\n\t\tw.Header().Set(\"Cache-Control\", \"no-cache, no-store, must-revalidate\")\n\t\thttp.ServeFile(w, r, \"index.html\")\n\t}\n}", "func (c *Controller) Logout(ctx context.Context) (err error) {\n\t// Build request\n\treq, err := c.requestBuild(ctx, \"GET\", authenticationAPIName, \"logout\", nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"request building failure: %w\", err)\n\t}\n\t// execute auth request\n\tif err = c.requestExecute(ctx, req, nil, false); err != nil {\n\t\terr = fmt.Errorf(\"executing request failed: %w\", err)\n\t}\n\treturn\n}", "func Logout(app *aero.Application, authLog *log.Log) {\n\tapp.Get(\"/logout\", func(ctx aero.Context) error {\n\t\tif ctx.HasSession() {\n\t\t\tuser := arn.GetUserFromContext(ctx)\n\n\t\t\tif user != nil {\n\t\t\t\tauthLog.Info(\"%s logged out | %s | %s | %s | %s\", user.Nick, user.ID, ctx.IP(), user.Email, user.RealName())\n\t\t\t}\n\n\t\t\tctx.Session().Delete(\"userId\")\n\t\t}\n\n\t\treturn ctx.Redirect(http.StatusTemporaryRedirect, \"/\")\n\t})\n}", "func (c *Client) Logout() (err error) {\n\t/* URL has to end in JSON, otherwise it will produce XML output */\n\treturn c.getResponse(\"/Auth/Logout/JSON\", nil, new(BaseResponse))\n}", "func (avisess *AviSession) Logout() error {\n\turl := avisess.prefix + \"logout\"\n\treq, _ := avisess.newAviRequest(\"POST\", url, nil, avisess.tenant)\n\t_, err := avisess.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a *Auth) Logout(w http.ResponseWriter, r *http.Request) {\n\tu := a.userstate.Username(r)\n\ta.userstate.Logout(u)\n\ta.userstate.ClearCookie(w)\n\ta.userstate.RemoveUser(u)\n\tutil.OK(w, r)\n}", "func (c *Client) Logout(ctx context.Context) error {\n\treq := c.Resource(internal.SessionPath).Request(http.MethodDelete)\n\treturn c.Do(ctx, req, nil)\n}", "func (h *UserRepos) Logout(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\n\tsess := webcontext.ContextSession(ctx)\n\n\t// Set the access token to empty to logout the user.\n\tsess = webcontext.SessionDestroy(sess)\n\n\tif err := sess.Save(r, w); err != nil {\n\t\treturn err\n\t}\n\n\t// Redirect the user to the root page.\n\treturn web.Redirect(ctx, w, r, \"/\", http.StatusFound)\n}", "func (userHandlersImpl UserHandlersImpl) Logout(w http.ResponseWriter, req *http.Request) {\n\n\tresp := \"\"\n\tWriteOKResponse(w, resp)\n\n}", "func logout(w http.ResponseWriter, r *http.Request) {\n\tsession, err := store.Get(r, \"auth\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsession.Values[\"user\"] = User{}\n\tsession.Options.MaxAge = -1\n\n\terr = session.Save(r, w)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tlogRequest(r)\n}", "func (cl *APIClient) Logout() *R.Response {\n\trr := cl.Request(map[string]string{\n\t\t\"COMMAND\": \"EndSession\",\n\t})\n\tif rr.IsSuccess() {\n\t\tcl.SetSession(\"\")\n\t}\n\treturn rr\n}", "func Logout(res http.ResponseWriter, req *http.Request) error {\n\tsession, err := Store.Get(req, SessionName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsession.Options.MaxAge = -1\n\tsession.Values = make(map[interface{}]interface{})\n\terr = session.Save(req, res)\n\tif err != nil {\n\t\treturn errors.New(\"Could not delete user session \")\n\t}\n\treturn nil\n}", "func Logout(c buffalo.Context) error {\n\tsessionID := c.Value(\"SessionID\").(int)\n\tadmin := c.Value(\"Admin\")\n\tif admin != nil {\n\t\t// \"log out\" by unscoping out auth token\n\t\ttoken, err := utils.GenerateScopedToken(admin.(string), 0, sessionID)\n\t\tif err != nil {\n\t\t\treturn c.Error(http.StatusBadRequest, err)\n\t\t}\n\t\treturn c.Render(http.StatusOK, render.JSON(&common.TokenPayload{\n\t\t\tToken: token,\n\t\t}))\n\t}\n\tif err := modelext.DeleteUserSession(c, sessionID); err != nil {\n\t\treturn c.Error(http.StatusInternalServerError, err)\n\t}\n\treturn c.Render(http.StatusOK, render.JSON(&common.TokenPayload{\n\t\tToken: \"\",\n\t}))\n}", "func (s *Session) Logout() error { return nil }", "func (as *AdminServer) Logout(w http.ResponseWriter, r *http.Request) {\n\tsession := ctx.Get(r, \"session\").(*sessions.Session)\n\tdelete(session.Values, \"id\")\n\tFlash(w, r, \"success\", \"You have successfully logged out\")\n\tsession.Save(r, w)\n\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n}", "func Logout(c *gin.Context) {\n\ttokenString := util.ExtractToken(c.Request)\n\n\tau, err := util.ExtractTokenMetadata(tokenString)\n\tif err != nil {\n\t\tc.JSON(http.StatusUnauthorized, \"unauthorized\")\n\t\treturn\n\t}\n\n\tdeleted, delErr := util.DeleteAuth(au.AccessUuid)\n\tif delErr != nil || deleted == 0 { //if any goes wrong\n\t\tc.JSON(http.StatusUnauthorized, \"unauthorized\")\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, \"Successfully logged out\")\n}", "func restLogout(w *rest.ResponseWriter, r *rest.Request) {\n\tglog.V(2).Info(\"restLogout() called.\")\n\t// Read session cookie and delete session\n\tcookie, err := r.Request.Cookie(sessionCookie)\n\tif err != nil {\n\t\tglog.V(2).Info(\"Unable to read session cookie\")\n\t} else {\n\t\tdeleteSessionT(cookie.Value)\n\t\tglog.V(2).Infof(\"Deleted session %s for explicit logout\", cookie.Value)\n\t}\n\n\t// Blank out all login cookies\n\twriteBlankCookie(w, r, auth0TokenCookie)\n\twriteBlankCookie(w, r, sessionCookie)\n\twriteBlankCookie(w, r, usernameCookie)\n\tw.WriteJson(&simpleResponse{\"Logged out\", loginLink()})\n}", "func (controller *Auth) Logout() {\n\tcontroller.distroySession()\n\tcontroller.DeleteConnectionCookie()\n\tcontroller.Redirect(\"/\", 200)\n}", "func (AuthenticationController) Logout(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tsession.Clear()\n\tif sessionErr := session.Save(); sessionErr != nil {\n\t\tlog.Print(sessionErr)\n\t\tutils.CreateError(c, http.StatusInternalServerError, \"Failed to logout.\")\n\t\tc.Abort()\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"message\": \"Logged out...\"})\n}", "func (u *Users) LogOut() {\n\tu.deauthorizeUser()\n\tu.serveAJAXSuccess(nil)\n}", "func Logout(ctx echo.Context) error {\n\tif _, ok := ctx.Get(\"User\").(*models.Person); ok {\n\t\tutils.DeleteSession(ctx, settings.App.Session.Lang)\n\t\tutils.DeleteSession(ctx, settings.App.Session.Flash)\n\t\tutils.DeleteSession(ctx, settings.App.Session.Name)\n\t}\n\tctx.Redirect(http.StatusFound, \"/\")\n\treturn nil\n}", "func (am AuthManager) Logout(ctx *Ctx) error {\n\tsessionValue := am.readSessionValue(ctx)\n\t// validate the sessionValue isn't unset\n\tif len(sessionValue) == 0 {\n\t\treturn nil\n\t}\n\n\t// issue the expiration cookies to the response\n\tctx.ExpireCookie(am.CookieNameOrDefault(), am.CookiePathOrDefault())\n\tctx.Session = nil\n\n\t// call the remove handler if one has been provided\n\tif am.RemoveHandler != nil {\n\t\treturn am.RemoveHandler(ctx.Context(), sessionValue)\n\t}\n\treturn nil\n}", "func (uh *UserHandler) Logout(w http.ResponseWriter, r *http.Request) {\n\tnewSession := uh.configSess()\n\tcookie, _ := r.Cookie(newSession.SID)\n\n\tsession.Remove(newSession.SID, w)\n\tuh.SService.DeleteSession(cookie.Value)\n\thttp.Redirect(w, r, \"/Login\", http.StatusSeeOther)\n}", "func Logout(w http.ResponseWriter, r *http.Request) error {\n\tsession, _ := loggedUserSession.Get(r, \"authenticated-user-session\")\n\tsession.Values[\"username\"] = \"\"\n\treturn session.Save(r, w)\n}", "func (ctrl *UserController) Logout(c *gin.Context) {\n\thttp.SetCookie(c.Writer, &http.Cookie{Path: \"/\", Name: auth.RefreshTokenKey, MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode})\n\thttp.SetCookie(c.Writer, &http.Cookie{Path: \"/\", Name: auth.AccessTokenKey, MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode})\n\n\tc.JSON(http.StatusOK, utils.Msg(\"Logged out\"))\n}", "func Logout(res http.ResponseWriter, req *http.Request) {\n\ttokenID := req.Context().Value(\"tokenID\").(string)\n\tresponse := make(map[string]interface{})\n\tmsg := constants.Logout\n\t_, err := connectors.RemoveDocument(\"tokens\", tokenID)\n\tif err != nil {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusServiceUnavailable, constants.Unavailable))\n\t\treturn\n\t}\n\tresponse[\"message\"] = msg\n\trender.Render(res, req, responses.NewHTTPSucess(http.StatusOK, response))\n}", "func logoutHandler(res http.ResponseWriter, req *http.Request) {\n\tdefer server.LogRequest(req, http.StatusFound)\n\n\tsession.Destroy(req, res)\n\trenderBaseTemplate(res, \"logout.html\", nil)\n}", "func signOut(w http.ResponseWriter, r *http.Request) {\n\tlogoutUser(w, r)\n\tresp := map[string]interface{}{\n\t\t\"success\": true,\n\t}\n\tapiResponse(resp, w)\n}", "func Logout(w http.ResponseWriter, r *http.Request) {\n\tif sessions.GoodSession(r) != true {\n\t\tjson.NewEncoder(w).Encode(\"Session Expired. Log out and log back in.\")\n\t}\n\tstore, err := pgstore.NewPGStore(os.Getenv(\"PGURL\"), key)\n\tcheck(err)\n\tdefer store.Close()\n\n\tsession, err := store.Get(r, \"scheduler-session\")\n\tcheck(err)\n\t// Revoke users authentication\n\tsession.Values[\"authenticated\"] = false\n\tw.WriteHeader(http.StatusOK)\n\tsession.Options.MaxAge = -1\n\tsession.Save(r, w)\n}", "func UserLogout(w http.ResponseWriter, r *http.Request) {\n\t_ = SessionDel(w, r, \"user\")\n\tutils.SuccessResponse(&w, \"登出成功\", \"\")\n}", "func Logout(res http.ResponseWriter, req *http.Request) {\n\t_, ok := cookiesManager.GetCookieValue(req, CookieName)\n\tif ok {\n\t\t// cbs.SessionManager.RemoveSession(uuid)\n\t\tcookiesManager.RemoveCookie(res, CookieName)\n\t} else {\n\t\tlog.Trace(\"Logging out without the cookie\")\n\t}\n}", "func logout(w http.ResponseWriter, r *http.Request) {\n LOG[INFO].Println(\"Executing Logout\")\n clearCache(w)\n cookie, _ := r.Cookie(LOGIN_COOKIE)\n cookie.MaxAge = -1\n cookie.Expires = time.Now().Add(-1 * time.Hour)\n http.SetCookie(w, cookie)\n LOG[INFO].Println(\"Successfully Logged Out\")\n http.Redirect(w, r, \"/welcome\", http.StatusSeeOther)\n}", "func (app *application) logout(w http.ResponseWriter, r *http.Request) {\n\tsession, err := app.sessionStore.Get(r, \"session-name\")\n\tif err != nil {\n\t\tapp.serverError(w, err)\n\t\treturn\n\t}\n\n\tif session.Values[\"customerID\"] != nil {\n\t\tsession.Values[\"customerID\"] = nil\n\t\tsession.AddFlash(\"customer logged out\")\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t}\n\tif session.Values[\"vendorID\"] != nil {\n\t\tsession.Values[\"vendorID\"] = nil\n\t\tsession.AddFlash(\"vendor logged out\")\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t}\n}", "func (m *Repository) Logout(w http.ResponseWriter, r *http.Request) {\n\tif !m.App.Session.Exists(r.Context(), \"user_id\") {\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\t_ = m.App.Session.Destroy(r.Context())\n\t_ = m.App.Session.RenewToken(r.Context())\n\tm.App.Session.Put(r.Context(), \"flash\", \"Successfully logged out!\")\n\n\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n}", "func (h *auth) Logout(c echo.Context) error {\n\tsession := currentSession(c)\n\tif session != nil {\n\t\terr := h.db.Delete(session)\n\t\tif err != nil && h.db.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn c.NoContent(http.StatusNoContent)\n}", "func (u *UserController) Logout(c *gin.Context) {\n\trequestID := requestid.Get(c)\n\tau, err := helpers.ExtractTokenMetadata(c.Request, requestID)\n\tif err != nil {\n\t\tlogger.Error(logoutLogTag, requestID, \"Unable to extract token metadata on logout system, error: %+v\", err)\n\t\tc.JSON(http.StatusUnauthorized, \"unauthorized\")\n\t\treturn\n\t}\n\tdeleted, delErr := helpers.DeleteAuth(au.AccessUUID)\n\tif delErr != nil || deleted == 0 {\n\t\tlogger.Error(logoutLogTag, requestID, \"Unable to delete auth on logout system, error: %+v, deleted: %d\", delErr, deleted)\n\t\tc.JSON(http.StatusUnauthorized, \"user already logout\")\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, \"Successfully logged out\")\n}", "func (c *controller) Logout(ctx context.Context, request *web.Request) web.Result {\n\treturn c.service.LogoutFor(ctx, request.Params[\"broker\"], request, nil)\n}", "func logout(w http.ResponseWriter,r *http.Request){\n\tsession,err:=store.Get(r,\"cookie-name\")\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\tsession.Values[\"user\"]=user{}\n\tsession.Options.MaxAge=-1\n\n\terr=session.Save(r,w)\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\thttp.Redirect(w,r,\"/\",http.StatusFound)\n}", "func (a Authorizer) Logout(rw http.ResponseWriter, req *http.Request) error {\n\tsession, err := skyring.Store.Get(req, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error getting the session. error: %v\", err)\n\t\treturn err\n\t}\n\tsession.Options.MaxAge = -1\n\tif err = session.Save(req, rw); err != nil {\n\t\tlogger.Get().Error(\"Error saving the session. error: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a Authorizer) Logout(rw http.ResponseWriter, req *http.Request) error {\n\tsession, err := skyring.Store.Get(req, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error getting the session. error: %v\", err)\n\t\treturn err\n\t}\n\tsession.Options.MaxAge = -1\n\tif err = session.Save(req, rw); err != nil {\n\t\tlogger.Get().Error(\"Error saving the session. error: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (router *router) SignOut(w http.ResponseWriter, r *http.Request) {\n\trouter.log.Println(\"request received at endpoint: SignOut\")\n\tif session.IsAuthenticated(w, r) {\n\t\trouter.database.Delete(&schema.Favourite{User: session.GetUser(w, r)})\n\t\tsession.SignOut(w, r)\n\t\trouter.log.Println(\"sign out completed redirecting to home page\")\n\t} else {\n\t\trouter.log.Println(\"Not signed in to sign out, redirecting to home page\")\n\t}\n\n\tHomePage(w, r)\n\treturn\n}", "func gwLogout(c *gin.Context) {\n\ts := getHostServer(c)\n\treqId := getRequestId(s, c)\n\tuser := getUser(c)\n\tcks := s.conf.Security.Auth.Cookie\n\tok := s.AuthManager.Logout(user)\n\tif !ok {\n\t\ts.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"auth logout fail\", nil)\n\t\treturn\n\t}\n\tsid, ok := getSid(s, c)\n\tif !ok {\n\t\ts.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"session store logout fail\", nil)\n\t\treturn\n\t}\n\t_ = s.SessionStateManager.Remove(sid)\n\tc.SetCookie(cks.Key, \"\", -1, cks.Path, cks.Domain, cks.Secure, cks.HttpOnly)\n}", "func Logout(w http.ResponseWriter, r *http.Request) {\n\t// TODO JvD: revoke the token?\n\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n}", "func (a *authSvc) Logout(ctx context.Context) error {\n\taccessUuid, ok := ctx.Value(AccessUuidKey).(string)\n\tif !ok {\n\t\treturn errors.New(\"access uuid not present in context\")\n\t}\n\tdeleted, err := deleteAuth(\"access_token\", accessUuid)\n\tif err != nil || deleted == 0 {\n\t\treturn errors.New(\"not authenticated\")\n\t}\n\trefreshUuid, ok := ctx.Value(RefreshUuidKey).(string)\n\tif !ok {\n\t\treturn errors.New(\"refresh uuid not present in context\")\n\t}\n\tdeleted, err = deleteAuth(\"refresh_token\", refreshUuid)\n\tif err != nil || deleted == 0 {\n\t\treturn errors.New(\"not authenticated\")\n\t}\n\tcookieAccess := getCookieAccess(ctx)\n\tcookieAccess.RemoveToken(\"jwtAccess\")\n\tcookieAccess.RemoveToken(\"jwtRefresh\")\n\treturn nil\n}", "func clearSession(response http.ResponseWriter) {\n cookie := &http.Cookie{\n Name: \"session\",\n Value: \"\",\n Path: \"/\",\n MaxAge: -1,\n }\n http.SetCookie(response, cookie)\n }", "func logoutHandler(w http.ResponseWriter, req *http.Request) {\n\tif req.Method == post {\n\t\tsessionStore.Destroy(w, sessionName)\n\t}\n\thttp.Redirect(w, req, \"/\", http.StatusFound)\n}", "func (c *UCSClient) Logout() {\n\tif c.IsLoggedIn() {\n\t\tc.Logger.Debug(\"Logging out\\n\")\n\t\treq := ucs.LogoutRequest{\n\t\t\tCookie: c.cookie,\n\t\t}\n\t\tpayload, err := req.Marshal()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tc.Post(payload)\n\t\tc.cookie = \"\"\n\t\tc.outDomains = \"\"\n\t}\n\tc.Logger.Info(\"Logged out\\n\")\n}", "func Logout(_ *gorm.DB, rc *redis.Client, _ http.ResponseWriter, r *http.Request, s *status.Status) (int, error) {\n\tctx := context.Background()\n\trequestUsername := getVar(r, model.UsernameVar)\n\tclaims := GetTokenClaims(ExtractToken(r))\n\ttokenUsername := fmt.Sprintf(\"%v\", claims[\"sub\"])\n\tif tokenUsername != requestUsername {\n\t\ts.Message = status.LogoutFailure\n\t\treturn http.StatusForbidden, nil\n\t}\n\ts.Code = status.SuccessCode\n\ts.Message = status.LogoutSuccess\n\trc.Del(ctx, \"access_\"+requestUsername)\n\treturn http.StatusOK, nil\n}", "func (s *Subject) Logout() {\n\tif s.Session != nil {\n\t\ts.Session.Clear()\n\t}\n}", "func (a *AuthController) Logout(w http.ResponseWriter, r *http.Request) {\n\tsession, err := a.store.Get(r, cookieSession)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tsession.Values[\"authenticated\"] = false\n\tif err := session.Save(r, w); err != nil {\n\t\tlog.Println(\"[ERROR] error saving authenticated session\")\n\t}\n\n\thttp.Redirect(w, r, \"/\", http.StatusNoContent)\n}", "func (c UserInfo) Logout() revel.Result {\n\tc.Session.Del(\"DiscordUserID\")\n\tc.Response.Status = 200\n\treturn c.Render()\n}", "func logoutHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {\n\tsessionHandler.ClearSession(w, r)\n\treturn\n}", "func (c *Client) Logout() (string, error) {\n\n\tif c.auth == nil {\n\t\treturn \"Was not logged in\", nil\n\t}\n\n\trequest, _ := http.NewRequest(\"POST\", c.getUrl()+\"/api/v1/logout\", nil)\n\n\tresponse := new(logoutResponse)\n\n\tif err := c.doRequest(request, response); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif response.Status == \"success\" {\n\t\treturn response.Data.Message, nil\n\t} else {\n\t\treturn \"\", errors.New(\"Response status: \" + response.Status)\n\t}\n}", "func Logout(r *http.Request) error {\n\n\tvar session models.Session\n\n\tCookie, err := r.Cookie(CookieKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc := Controller{}\n\tdata, err := c.Load(r)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession.UUID = Cookie.Value\n\n\tvar updated []models.Session\n\tfor _, s := range data.Sessions {\n\t\tif s.UUID == session.UUID {\n\t\t} else {\n\t\t\tupdated = append(updated, s)\n\t\t}\n\t}\n\n\terr = c.StoreSessions(updated, r)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (db *MyConfigurations) logout(c echo.Context) error {\n\tfcmToken := c.Request().Header.Get(\"fcm-token\")\n\tdb.GormDB.Where(\"token = ?\", fcmToken).Delete(&models.DeviceToken{})\n\tc.SetCookie(&http.Cookie{\n\t\tName: \"Authorization\",\n\t\tValue: \"\",\n\t\tExpires: time.Now(),\n\t\tMaxAge: 0,\n\t})\n\treturn c.Redirect(http.StatusFound, \"/login\")\n}", "func logoutGuest(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method == \"POST\" {\n\t\tusername := template.HTMLEscapeString(r.FormValue(\"username\"))\n\t\tpassword := template.HTMLEscapeString(r.FormValue(\"password\"))\n\n\t\tif password != \"\" && strings.Contains(username, \"guest\") && gostuff.SessionManager[username] == password {\n\t\t\tdelete(gostuff.SessionManager, username)\n\t\t}\n\t}\n}", "func (c *RestClient) Logout(tgt TicketGrantingTicket) error {\n\t// DELETE /cas/v1/tickets/TGT-fdsjfsdfjkalfewrihfdhfaie HTTP/1.0\n\tendpoint, err := c.urlScheme.RestLogout(string(tgt))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", endpoint.String(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 204 {\n\t\treturn fmt.Errorf(\"could not destroy granting ticket %v, server returned %v\", tgt, resp.StatusCode)\n\t}\n\n\treturn nil\n}", "func (s *server) Logout(ctx context.Context, in *pb.LogRequest) (*pb.LogResponse, error) {\n\tlog.Printf(\"Received: %v\", \"Logout\")\n\tsuc, err := DeleteToken(in.Email, in.Token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pb.LogResponse{Sucess: suc}, nil\n}", "func (s *Handler) Logout(ctx context.Context, req *api.LogoutRequest) (*api.EmptyResponse, error) {\n\tif err := s.DaemonService.ClusterLogout(ctx, req.ClusterUri); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn &api.EmptyResponse{}, nil\n}", "func logoutHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"logoutHandler: process form\")\n\tctx := context.Background()\n\tif b.authenticator == nil {\n\t\tvar err error\n\t\tb.authenticator, err = initAuth(ctx)\n\t\tif err != nil {\n\t\t\tlog.Print(\"logoutHandler authenticator could not be initialized\")\n\t\t\thttp.Error(w, \"Server error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\tcookie, err := r.Cookie(\"session\")\n\tif err != nil {\n\t\t// OK, just don't show the contents that require a login\n\t\tlog.Println(\"logoutHandler: no cookie\")\n\t} else {\n\t\tb.authenticator.Logout(ctx, cookie.Value)\n\t\tcookie.MaxAge = -1\n\t\thttp.SetCookie(w, cookie)\n\t}\n\n\t// Return HTML if method is post\n\tif httphandling.AcceptHTML(r) {\n\t\ttitle := b.webConfig.GetVarWithDefault(\"Title\", defTitle)\n\t\tcontent := htmlContent{\n\t\t\tTitle: title,\n\t\t}\n\t\tb.pageDisplayer.DisplayPage(w, \"logged_out.html\", content)\n\t\treturn\n\t}\n\n\tmessage := \"Please come back again\"\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tfmt.Fprintf(w, \"{\\\"message\\\" :\\\"%s\\\"}\", message)\n}", "func (c *yorcProviderClient) Logout() error {\n\trequest, err := http.NewRequest(\"POST\", fmt.Sprintf(\"%s/logout\", c.client.baseURL), nil)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\trequest.Header.Add(\"Accept\", \"application/json\")\n\trequest.Header.Set(\"Connection\", \"close\")\n\n\trequest.Close = true\n\n\tresponse, err := c.client.Client.Do(request)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode != http.StatusOK {\n\t\treturn getError(response.Body)\n\t}\n\n\treturn nil\n}", "func Logout(c *gin.Context) {\n\tc.SetCookie(\"token\", \"\", -1, \"\", \"\", false, true)\n\n\tc.Redirect(http.StatusTemporaryRedirect, \"/\")\n}", "func (auth Authenticate) Logout(session *types.Session) error {\n\terr := manager.AccountManager{}.RemoveSession(session, auth.Cache)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a *noAuth) Logout(c echo.Context) error {\n\treturn a.logout(c)\n}", "func (c App) SignOut() revel.Result {\n\tfor k := range c.Session {\n\t\tdelete(c.Session, k)\n\t}\n\treturn c.Redirect(App.Index)\n}", "func logoutHandler(w http.ResponseWriter, r *http.Request) {\n\tsession, _ := store.Get(r, sessionName)\n\tsession.Values[\"LoggedIn\"] = \"no\"\n\tsession.Save(r, w)\n\thttp.Redirect(w, r, \"/\", http.StatusFound)\n}", "func Clear(c echo.Context) error {\n\ts, _ := Get(c)\n\tusername := s.Values[\"username\"]\n\tdelete(s.Values, \"authenticated\")\n\tdelete(s.Values, \"username\")\n\tdelete(s.Values, \"userinfo\")\n\n\t// delete client cookie\n\ts.Options.MaxAge = -1\n\n\terr := s.Save(c.Request(), c.Response())\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to save session: %v\", err)\n\t\treturn err\n\t}\n\tglog.V(2).Infof(\"user '%s' logged out\", username)\n\treturn nil\n}", "func HandleLogout(w http.ResponseWriter, r *http.Request) {\n\tsess, err := store.Get(r, \"s\")\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tdelete(sess.Values, \"accountID\")\n\tsess.Save(r, w)\n\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n}", "func (s *AuthService) Logout(login, refreshToken string) error {\n\terr := s.client.Auth.Logout(login, refreshToken)\n\treturn err\n}", "func (session *Session) Logout() error {\n\treturn session.Delete(session.TenantID)\n}", "func logOut(res http.ResponseWriter, req *http.Request) {\n\tinvalidateCookie(res)\n\tfmt.Fprintf(\n\t\tres,\n\t\t`<html>\n\t\t<head>\n\t\t<META http-equiv=\"refresh\" content=\"10;URL=/index.html\">\n\t\t<body>\n\t\t<p>Good-bye.</p>\n\t\t</body>\n\t\t</html>`,\n\t)\n}", "func LogoutAction(w http.ResponseWriter, r *http.Request) {\n\t// get cookie from request\n\tc, err := r.Cookie(\"JSESSION_ID\")\n\tif err != nil {\n\t\tif err == http.ErrNoCookie {\t\t\n\t\t\thttp.Redirect(w, r, \"/login?errorM=No session present in request\", http.StatusSeeOther)\n\t\t\treturn\t\n\t\t}\n\t\thttp.Redirect(w, r, \"/login?errorM=Not authorised\", http.StatusSeeOther)\n\t\treturn\n\t}\n\t// if no errors, validate the cookie\n\tsessToken := c.Value\n\tsv := strings.Split(sessToken, \"_\")\t\t\n\tif len(sv) != 2 {\t\t\n\t\thttp.Redirect(w, r, \"/login?errorM=Invalid cookie format\", http.StatusSeeOther)\n\t\treturn\t\n\t}\n\tuserName := sv[0]\n\t// to logout, delete the stored session\n\tdeleteKeyString(\"Sessions\", userName)\n\thttp.Redirect(w, r, \"/login?successM=Successfully logged out\", http.StatusSeeOther)\n}", "func (s *Server) handleLogout(w http.ResponseWriter, req *http.Request) error {\n\t// Intentionally ignore errors that may be caused by the stale session.\n\tsession, _ := s.cookieStore.Get(req, UserSessionName)\n\tsession.Options.MaxAge = -1\n\tdelete(session.Values, \"hash\")\n\tdelete(session.Values, \"email\")\n\t_ = session.Save(req, w)\n\tfmt.Fprintf(w, `<!DOCTYPE html><a href='/login'>Log in</a>`)\n\treturn nil\n}", "func (c *Client) Logout(ctx context.Context, authToken *base64.Value) error {\n\treturn c.transport.Logout(ctx, authToken)\n}", "func (bap *BaseAuthProvider) Logout(ctx *RequestCtx) {\n\t// When this is internally called (such as user reset password, or been disabled)\n\t// ctx might be nil\n\tif ctx.Ctx != nil {\n\t\t//delete token cookie, keep uuid cookie\n\t\tWriteToCookie(ctx.Ctx, AuthTokenName, \"\")\n\t}\n\tif ctx.User != nil {\n\t\t(*bap.Mutex).Lock()\n\t\tdelete(bap.TokenCache, ctx.User.Token())\n\t\tbap.TokenToUsername.DelString(ctx.User.Token())\n\t\t(*bap.Mutex).Unlock()\n\t\tlog.Println(\"Logout:\", ctx.User.Username())\n\t}\n}", "func (u *MyUserModel) Logout() {\n\t// Remove from logged-in user's list\n\t// etc ...\n\tu.authenticated = false\n}", "func (dsm DSM) EndSession() {\n\turl := fmt.Sprintf(\"%sauthentication/logout\", dsm.RestURL)\n\t_, err := grequests.Delete(url, &grequests.RequestOptions{HTTPClient: &dsm.RestClient, Params: map[string]string{\"sID\": dsm.SessionID}})\n\n\tif err != nil {\n\t\tlog.Println(\"Unable to make request\", err)\n\t}\n\n}", "func (client *Client) Logout() error {\n\t_, err := client.SendQuery(NewLogoutQuery())\n\treturn err\n}", "func (c *Client) Logout() []byte {\n\tr := &requests{[]Request{\n\t\tRequest{\n\t\t\tService: ServiceAdmin,\n\t\t\tCommand: CmdLogout,\n\t\t\tRequestID: 1,\n\t\t\tAccount: c.user.Accounts[0].AccountID,\n\t\t\tSource: c.user.StreamerInfo.AppID,\n\t\t\tParameters: Params{},\n\t\t}}}\n\n\treq, _ := json.Marshal(r)\n\n\treturn req\n}", "func (context Context) Logout() error {\n\n\treqURL := url.URL{\n\t\tScheme: \"http\",\n\t\tHost: context.ServerAddress,\n\t\tPath: path.Join(apiPrefix, \"users/logout\"),\n\t}\n\n\treq, err := http.NewRequest(\"GET\", reqURL.String(), nil)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"HTTP new request error\")\n\t}\n\tcontext.UserCredentials.Apply(req.Header)\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"HTTP client error\")\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terrorResponse, err := getAPIErrorResponse(resp)\n\t\terrorString := errorResponse.String()\n\t\tif err == nil || errorString == \"\" {\n\t\t\terrorString = resp.Status\n\t\t}\n\t\treturn errors.New(\"API error: \" + resp.Status)\n\t}\n\n\treturn nil\n}", "func AuthPhoneLogout(ctx context.Context) {\n\t// nothing to do here since stateless session\n\t// needs to be handled on the client\n\t// when there's a refresh token, we'll kill it\n}", "func (c *Client) Logout() (*www.LogoutReply, error) {\n\tfullRoute := c.cfg.Host + www.PoliteiaWWWAPIRoute + www.RouteLogout\n\n\t// Print request details\n\tif c.cfg.Verbose {\n\t\tfmt.Printf(\"Request: POST %v\\n\", fullRoute)\n\t}\n\n\t// Create new http request instead of using makeRequest()\n\t// so that we can save the updated cookies to disk\n\treq, err := http.NewRequest(http.MethodPost, fullRoute, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(www.CsrfToken, c.cfg.CSRF)\n\n\t// Send request\n\tr, err := c.http.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tr.Body.Close()\n\t}()\n\n\tresponseBody := util.ConvertBodyToByteArray(r.Body, false)\n\n\t// Validate response status\n\tif r.StatusCode != http.StatusOK {\n\t\tvar ue www.UserError\n\t\terr = json.Unmarshal(responseBody, &ue)\n\t\tif err == nil {\n\t\t\treturn nil, fmt.Errorf(\"%v, %v %v\", r.StatusCode,\n\t\t\t\tuserErrorStatus(ue.ErrorCode), strings.Join(ue.ErrorContext, \", \"))\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"%v\", r.StatusCode)\n\t}\n\n\t// Unmarshal response\n\tvar lr www.LogoutReply\n\terr = json.Unmarshal(responseBody, &lr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshal LogoutReply: %v\", err)\n\t}\n\n\t// Print response details\n\tif c.cfg.Verbose {\n\t\tfmt.Printf(\"Response: %v\\n\", r.StatusCode)\n\t\terr := prettyPrintJSON(lr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Persist cookies\n\tck := c.http.Jar.Cookies(req.URL)\n\tif err = c.cfg.SaveCookies(ck); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &lr, nil\n}", "func clearSession(response http.ResponseWriter) {\n\tcookie := &http.Cookie{\n\t\tName: \"session\",\n\t\tValue: \"\",\n\t\tPath: \"/\",\n\t\tMaxAge: -1,\n\t}\n\thttp.SetCookie(response, cookie)\n}", "func (h *Handler) LogoutHandler(w http.ResponseWriter, r *http.Request) {\n\n\tchallenge, err := readURLChallangeParams(r, \"logout\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif r.Method == \"POST\" {\n\t\tvar err error\n\t\tif r.Form == nil {\n\t\t\tif err := r.ParseForm(); err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\taccept := r.Form.Get(\"accept\")\n\t\tlogoutChallenge := r.Form.Get(\"challenge\")\n\t\tvar redirectURL string\n\n\t\tif accept == \"true\" {\n\t\t\tredirectURL, err = h.LoginService.SendAcceptBody(\"logout\", logoutChallenge, nil)\n\n\t\t} else {\n\t\t\tredirectURL, err = h.LoginService.SendRejectBody(\"logout\", logoutChallenge, nil)\n\t\t}\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\thttp.Redirect(w, r, redirectURL, http.StatusFound)\n\t} else {\n\n\t\tchallengeBody, err := h.LoginService.ReadChallenge(challenge, \"logout\")\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tif challengeBody.RpInitiated {\n\t\t\ttemplLogout := template.Must(template.ParseFiles(\"templates/logout.html\"))\n\t\t\tlogoutData := h.ConfigService.FetchLogoutConfig(challenge, challengeBody.Subject)\n\t\t\ttemplLogout.Execute(w, logoutData)\n\t\t} else {\n\t\t\tredirectURL, err := h.LoginService.SendAcceptBody(\"logout\", challenge, nil)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\thttp.Redirect(w, r, redirectURL, http.StatusFound)\n\t\t}\n\t}\n\n}", "func (app *application) postLogout(w http.ResponseWriter, r *http.Request) {\n\t// \"log out\" the user by removing their ID from the session\n\trowid := app.session.PopInt(r, \"authenticatedPlayerID\")\n\tapp.players.UpdateLogin(rowid, false)\n\tapp.session.Put(r, \"flash\", \"You've been logged out successfully\")\n\thttp.Redirect(w, r, \"/login\", 303)\n}", "func getLogout(s *Setup) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvar response jSendResponse\n\t\tstatusCode := http.StatusOK\n\t\tresponse.Status = \"fail\"\n\n\t\terr := invalidateAttachedToken(r, s)\n\t\tif err != nil {\n\t\t\ts.Logger.Printf(\"logout failed because: %v\", err)\n\t\t\tresponse.Status = \"error\"\n\t\t\tresponse.Message = \"server error when logging out\"\n\t\t\tstatusCode = http.StatusInternalServerError\n\t\t} else {\n\t\t\tresponse.Status = \"success\"\n\t\t\ts.Logger.Printf(\"token was invalidated\")\n\t\t}\n\t\twriteResponseToWriter(response, w, statusCode)\n\t}\n}", "func (a *AllApiService) Logout(ctx _context.Context) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/logout\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (a *Auth) Logout(ctx *gin.Context) error {\n\tuuid, err := ctx.Cookie(a.cookie)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// delete redis record\n\tif err := a.redis.Del(uuid).Err(); err != nil {\n\t\treturn err\n\t}\n\n\t// delete cookie\n\thttp.SetCookie(ctx.Writer, &http.Cookie{\n\t\tName: a.cookie,\n\t\tValue: \"\",\n\t\tExpires: time.Unix(0, 0),\n\t})\n\treturn nil\n}" ]
[ "0.79834914", "0.7754024", "0.7634268", "0.7630396", "0.7539964", "0.75395024", "0.7527865", "0.7512331", "0.7508096", "0.7494285", "0.7482439", "0.74492276", "0.74395335", "0.7416064", "0.7408597", "0.7404034", "0.7349339", "0.73031014", "0.73013866", "0.72951627", "0.728178", "0.72799784", "0.7267348", "0.7266458", "0.7204607", "0.7177402", "0.71748626", "0.7168928", "0.7166714", "0.71576476", "0.7130067", "0.7126028", "0.71252185", "0.7115245", "0.7113386", "0.70959103", "0.70731646", "0.7072095", "0.7048891", "0.70420104", "0.703981", "0.7005075", "0.7001397", "0.6998731", "0.6977974", "0.6974579", "0.69666505", "0.6965344", "0.6961802", "0.69505847", "0.6922083", "0.6922083", "0.6919168", "0.6905817", "0.6902258", "0.6902076", "0.6881823", "0.68661183", "0.6854188", "0.68527365", "0.6825085", "0.68228203", "0.6805167", "0.680435", "0.6789376", "0.6789199", "0.678305", "0.6776504", "0.67718244", "0.67646605", "0.6715856", "0.669722", "0.66950995", "0.668689", "0.6675705", "0.66677296", "0.6660748", "0.6656221", "0.66559654", "0.6652011", "0.6645341", "0.6645244", "0.6631706", "0.6622557", "0.66192025", "0.66142786", "0.66114974", "0.66061914", "0.65985", "0.65651923", "0.6560271", "0.65572625", "0.65501934", "0.6545015", "0.653737", "0.6537086", "0.6532941", "0.65270615", "0.6510444", "0.6510401" ]
0.760095
4
Returns a new JWK for the desired type. An error will be returned if an invalid type is passed
func NewJwk(kty string) (j *Jwk, err error) { switch kty { case KeyTypeOct, KeyTypeRSA, KeyTypeEC: j = &Jwk{Type: kty} default: err = errors.New("Key Type Invalid. Must be Oct, RSA or EC") } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *JWK) GetType() Type {\n\treturn TypeJWK\n}", "func NewJWK(jwk map[string]interface{}) JWK {\n\treturn jwk\n}", "func (pk PublicKey) JWK() JWK {\n\tentry, ok := pk[JwkProperty]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tjson, ok := entry.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn NewJWK(json)\n}", "func MustNewKeyWithType(input string) KeyWithType {\n\tkwt, err := NewKeyWithType(input)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn kwt\n}", "func New(key interface{}) (Key, error) {\n\tif key == nil {\n\t\treturn nil, errors.New(\"jwk.New requires a non-nil key\")\n\t}\n\n\tswitch v := key.(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn newRSAPrivateKey(v)\n\tcase *rsa.PublicKey:\n\t\treturn newRSAPublicKey(v)\n\tcase *ecdsa.PrivateKey:\n\t\treturn newECDSAPrivateKey(v)\n\tcase *ecdsa.PublicKey:\n\t\treturn newECDSAPublicKey(v)\n\tcase []byte:\n\t\treturn newSymmetricKey(v)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid key type %T\", key)\n\t}\n}", "func (a *ACMEInstance) CreateJWK() (jwk JWK) {\n\n\t//TODO Mode Switch for different crypto Primitives...\n\tvar pkN *big.Int = (a.serverKey.PublicKey.(rsa.PublicKey)).N //ist vom type *big.Int... habe es absichtlich explizit hingeschrieben\n\tvar pkE int = (a.serverKey.PublicKey.(rsa.PublicKey)).E //type int\n\n\tpkNencoded := base64.RawURLEncoding.EncodeToString(pkN.Bytes())\n\tpkEencoded := base64.RawURLEncoding.EncodeToString(big.NewInt(int64(pkE)).Bytes())\n\n\tjwk = JWK{E: pkEencoded,\n\t\tKty: \"RSA\",\n\t\tN: pkNencoded,\n\t}\n\n\treturn jwk\n}", "func AsJWK(key interface{}) (*jose.JsonWebKey, error) {\n\tJWK := jose.JsonWebKey{\n\t\tKey: key,\n\t\tAlgorithm: string(jose.RSA1_5),\n\t}\n\tthumbprint, err := JWK.Thumbprint(crypto.SHA256)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tJWK.KeyID = base64.URLEncoding.EncodeToString(thumbprint)\n\treturn &JWK, nil\n}", "func KeyTypeToJWA(keyType kms.KeyType) string {\n\treturn kmssigner.KeyTypeToJWA(keyType)\n}", "func NewKeyWithType(input string) (KeyWithType, error) {\n\tparts := strings.Split(input, \":\")\n\tif len(parts) != 2 {\n\t\treturn KeyWithType{}, fmt.Errorf(\"key must be of the form <algorithm>:<key in base64>, was: %s\", input)\n\t}\n\n\tkeyBytes, err := base64.StdEncoding.DecodeString(parts[1])\n\tif err != nil {\n\t\treturn KeyWithType{}, fmt.Errorf(\"failed to base64-decode key: %v\", err)\n\t}\n\n\tif parts[0] == \"RSA\" {\n\t\tif privKey, err := RSAPrivateKeyFromBytes(keyBytes); err == nil {\n\t\t\t// legacy private key\n\t\t\treturn privKey, nil\n\t\t} else if pubKey, err := RSAPublicKeyFromBytes(keyBytes); err == nil {\n\t\t\t// legacy public key\n\t\t\treturn pubKey, nil\n\t\t}\n\n\t\t// could not parse legacy key\n\t\treturn KeyWithType{}, fmt.Errorf(\"unable to parse legacy RSA key\")\n\t}\n\n\talg, err := ToKeyType(parts[0])\n\tif err != nil {\n\t\treturn KeyWithType{}, err\n\t}\n\treturn alg.Generator()(keyBytes)\n}", "func New(key interface{}) (Key, error) {\n\tif key == nil {\n\t\treturn nil, errors.New(`jwk.New requires a non-nil key`)\n\t}\n\n\tvar ptr interface{}\n\tswitch v := key.(type) {\n\tcase rsa.PrivateKey:\n\t\tptr = &v\n\tcase rsa.PublicKey:\n\t\tptr = &v\n\tcase ecdsa.PrivateKey:\n\t\tptr = &v\n\tcase ecdsa.PublicKey:\n\t\tptr = &v\n\tdefault:\n\t\tptr = v\n\t}\n\n\tswitch rawKey := ptr.(type) {\n\tcase *rsa.PrivateKey:\n\t\tk := NewRSAPrivateKey()\n\t\tif err := k.FromRaw(rawKey); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, `failed to initialize %T from %T`, k, rawKey)\n\t\t}\n\t\treturn k, nil\n\tcase *rsa.PublicKey:\n\t\tk := NewRSAPublicKey()\n\t\tif err := k.FromRaw(rawKey); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, `failed to initialize %T from %T`, k, rawKey)\n\t\t}\n\t\treturn k, nil\n\tcase *ecdsa.PrivateKey:\n\t\tk := NewECDSAPrivateKey()\n\t\tif err := k.FromRaw(rawKey); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, `failed to initialize %T from %T`, k, rawKey)\n\t\t}\n\t\treturn k, nil\n\tcase *ecdsa.PublicKey:\n\t\tk := NewECDSAPublicKey()\n\t\tif err := k.FromRaw(rawKey); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, `failed to initialize %T from %T`, k, rawKey)\n\t\t}\n\t\treturn k, nil\n\tcase []byte:\n\t\tk := NewSymmetricKey()\n\t\tif err := k.FromRaw(rawKey); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, `failed to initialize %T from %T`, k, rawKey)\n\t\t}\n\t\treturn k, nil\n\tdefault:\n\t\treturn nil, errors.Errorf(`invalid key type '%T' for jwk.New`, key)\n\t}\n}", "func ToJWK(key interface{}) (*Key, error) {\n\tswitch k := key.(type) {\n\tcase *ecdsa.PrivateKey:\n\t\tkey := k.Public().(*ecdsa.PublicKey)\n\t\treturn buildJWKFromECDSA(key)\n\tcase *ecdsa.PublicKey:\n\t\treturn buildJWKFromECDSA(k)\n\tcase *rsa.PrivateKey:\n\t\tkey := k.Public().(*rsa.PublicKey)\n\t\treturn buildJWKFromRSA(key)\n\tcase *rsa.PublicKey:\n\t\treturn buildJWKFromRSA(k)\n\tdefault:\n\t\treturn nil, acmecrypto.ErrKeyFormat\n\t}\n}", "func (jwk *Jwk) MarshalJSON() (data []byte, err error) {\n\n\t// Remove any potentionally conflicting claims from the JWK's additional members\n\tdelete(jwk.AdditionalMembers, \"kty\")\n\tdelete(jwk.AdditionalMembers, \"kid\")\n\tdelete(jwk.AdditionalMembers, \"alg\")\n\tdelete(jwk.AdditionalMembers, \"use\")\n\tdelete(jwk.AdditionalMembers, \"key_ops\")\n\tdelete(jwk.AdditionalMembers, \"crv\")\n\tdelete(jwk.AdditionalMembers, \"x\")\n\tdelete(jwk.AdditionalMembers, \"y\")\n\tdelete(jwk.AdditionalMembers, \"d\")\n\tdelete(jwk.AdditionalMembers, \"n\")\n\tdelete(jwk.AdditionalMembers, \"p\")\n\tdelete(jwk.AdditionalMembers, \"q\")\n\tdelete(jwk.AdditionalMembers, \"dp\")\n\tdelete(jwk.AdditionalMembers, \"dq\")\n\tdelete(jwk.AdditionalMembers, \"qi\")\n\tdelete(jwk.AdditionalMembers, \"e\")\n\tdelete(jwk.AdditionalMembers, \"oth\")\n\tdelete(jwk.AdditionalMembers, \"k\")\n\n\t// There are additional claims, individually marshal each member\n\tobj := make(map[string]*json.RawMessage, len(jwk.AdditionalMembers)+10)\n\n\tif bytes, err := json.Marshal(jwk.Type); err == nil {\n\t\trm := json.RawMessage(bytes)\n\t\tobj[\"kty\"] = &rm\n\t} else {\n\t\treturn nil, err\n\t}\n\n\tif len(jwk.Id) > 0 {\n\t\tif bytes, err := json.Marshal(jwk.Id); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[\"kid\"] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(jwk.Algorithm) > 0 {\n\t\tif bytes, err := json.Marshal(jwk.Algorithm); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[\"alg\"] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(jwk.Use) > 0 {\n\t\tif bytes, err := json.Marshal(jwk.Use); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[\"use\"] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(jwk.Operations) > 0 {\n\t\tif bytes, err := json.Marshal(jwk.Operations); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[\"key_ops\"] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tswitch jwk.Type {\n\tcase KeyTypeEC:\n\t\t{\n\t\t\tif jwk.Curve != nil {\n\t\t\t\tjwk.Curve.Params()\n\t\t\t\tp := jwk.Curve.Params()\n\t\t\t\tif bytes, err := json.Marshal(p.Name); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"crv\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.X != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.X}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"x\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Y != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Y}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"y\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.D != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.D}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"d\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase KeyTypeRSA:\n\t\t{\n\t\t\tif jwk.D != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.D}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"d\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif jwk.N != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.N}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"n\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.P != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.P}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"p\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Q != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Q}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"q\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Dp != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Dp}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"dp\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Dq != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Dq}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"dq\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Qi != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Qi}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"qi\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.E >= 0 {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: big.NewInt(int64(jwk.E))}\n\t\t\t\tif bytes, err := json.Marshal(&b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"e\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(jwk.OtherPrimes) > 0 {\n\t\t\t\ttempOthPrimes := make([]jwkOthPrimeJSON, len(jwk.OtherPrimes))\n\t\t\t\tfor i, v := range jwk.OtherPrimes {\n\t\t\t\t\ttempOthPrimes[i].Coeff = &Base64UrlUInt{UInt: v.Coeff}\n\t\t\t\t\ttempOthPrimes[i].Exp = &Base64UrlUInt{UInt: v.Exp}\n\t\t\t\t\ttempOthPrimes[i].R = &Base64UrlUInt{UInt: v.R}\n\t\t\t\t}\n\n\t\t\t\tif bytes, err := json.Marshal(tempOthPrimes); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"oth\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase KeyTypeOct:\n\t\t{\n\t\t\tif len(jwk.KeyValue) > 0 {\n\t\t\t\tb64o := &Base64UrlOctets{Octets: jwk.KeyValue}\n\t\t\t\tif bytes, err := json.Marshal(b64o); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"k\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\t//Iterate through remaing members and add to json rawMessage\n\tfor k, v := range jwk.AdditionalMembers {\n\t\tif bytes, err := json.Marshal(v); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[k] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Marshal obj\n\treturn json.Marshal(obj)\n}", "func New(t ValueType) *Jzon {\n\tv := Jzon{}\n\tv.Type = t\n\tswitch t {\n\tcase JzTypeStr:\n\tcase JzTypeInt:\n\tcase JzTypeFlt:\n\tcase JzTypeBol:\n\tcase JzTypeObj:\n\t\tv.data = make(map[string]*Jzon)\n\tcase JzTypeArr:\n\t\tv.data = make([]*Jzon, 0)\n\tcase JzTypeNul:\n\t}\n\n\treturn &v\n}", "func (internet Internet) Jwt(v reflect.Value) (interface{}, error) {\n\treturn internet.jwt()\n}", "func (jwk *Jwk) Validate() error {\n\n\t// If the alg parameter is set, make sure it matches the set JWK Type\n\tif len(jwk.Algorithm) > 0 {\n\t\talgKeyType := GetKeyType(jwk.Algorithm)\n\t\tif algKeyType != jwk.Type {\n\t\t\tfmt.Errorf(\"Jwk Type (kty=%v) doesn't match the algorithm key type (%v)\", jwk.Type, algKeyType)\n\t\t}\n\t}\n\tswitch jwk.Type {\n\tcase KeyTypeRSA:\n\t\tif err := jwk.validateRSAParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase KeyTypeEC:\n\t\tif err := jwk.validateECParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase KeyTypeOct:\n\t\tif err := jwk.validateOctParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tdefault:\n\t\treturn errors.New(\"KeyType (kty) must be EC, RSA or Oct\")\n\t}\n\n\treturn nil\n}", "func NewJwkSet(target string) (*JwkSet, error) {\n\tif target == \"\" {\n\t\treturn nil, errors.New(\"invalid empty target url\")\n\t}\n\n\tdata, err := getHttpRespData(target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn parseJwksData(data)\n}", "func NewType() Type {}", "func NewJWT(claims Claims, method crypto.SigningMethod) jwt.JWT {\n\tj, ok := New(claims, method).(*jws)\n\tif !ok {\n\t\tpanic(\"jws.NewJWT: runtime panic: New(...).(*jws) != true\")\n\t}\n\tj.sb[0].protected.Set(\"typ\", \"JWT\")\n\tj.isJWT = true\n\treturn j\n}", "func GetKeyType(typename string) (keytype KeyType) {\n\tswitch {\n\tcase typename == \"none\":\n\t\tkeytype = RT_NONE\n\tcase typename == \"string\":\n\t\tkeytype = RT_STRING\n\tcase typename == \"list\":\n\t\tkeytype = RT_LIST\n\tcase typename == \"set\":\n\t\tkeytype = RT_SET\n\tcase typename == \"zset\":\n\t\tkeytype = RT_ZSET\n\tdefault:\n\t\tpanic(\"BUG - unknown type: \" + string(keytype))\n\t}\n\treturn\n}", "func mustUnmarshalJWK(s string) *jose.JSONWebKey {\n\tret := &jose.JSONWebKey{}\n\tif err := json.Unmarshal([]byte(s), ret); err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}", "func RSAToPublicJWK(publicKey *rsa.PublicKey, jwkID JWKID, algo Algorithm, expirationTime *time.Time) (*RSAPublicJWK, error) {\n\tpublicX509DER, err := x509.MarshalPKIXPublicKey(publicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpublicX509DERBase64 := base64.RawStdEncoding.EncodeToString(publicX509DER)\n\tpublicThumbprint := sha1.Sum(publicX509DER)\n\tpublicThumbprintBase64 := base64.RawURLEncoding.EncodeToString(publicThumbprint[:])\n\tmodulusBase64 := base64.RawURLEncoding.EncodeToString(publicKey.N.Bytes())\n\texpBuf := new(bytes.Buffer)\n\tbinary.Write(expBuf, binary.LittleEndian, uint64(publicKey.E))\n\texpBytes := bytes.TrimRight(expBuf.Bytes(), \"\\x00\")\n\tpublicExponentBase64 := base64.RawURLEncoding.EncodeToString(expBytes)\n\tvar usage Usage\n\tswitch algo {\n\tcase RS256, PS256:\n\t\tusage = Signing\n\t\tbreak\n\tcase ROAEP, RSA15:\n\t\tusage = Encryption\n\t}\n\tpublicJWK := RSAPublicJWK{\n\t\tJWK: JWK{\n\t\t\tCertificateChainBase64: []string{publicX509DERBase64},\n\t\t\tThumbprintBase64: publicThumbprintBase64,\n\t\t\tExpirationTime: expirationTime,\n\t\t\tID: jwkID,\n\t\t\tType: rsaType,\n\t\t\tAlgorithm: algo,\n\t\t\tUsage: usage,\n\t\t},\n\t\tModulusBase64: modulusBase64,\n\t\tPublicExponentBase64: publicExponentBase64,\n\t}\n\treturn &publicJWK, nil\n}", "func MustNewKeyWithTypeFromSerialized(input SerializedKeyWithType) KeyWithType {\n\treturn MustNewKeyWithType(string(input))\n}", "func NewJWT(secret string, jwksurl string) *JWT {\n\treturn &JWT{\n\t\tSecret: secret,\n\t\tJwksurl: jwksurl,\n\t\tNow: DefaultNowTime,\n\t}\n}", "func CreateFromWKT(wkt string, srs SpatialReference) (Geometry, error) {\n\tcString := C.CString(wkt)\n\tdefer C.free(unsafe.Pointer(cString))\n\tvar newGeom Geometry\n\treturn newGeom, C.OGR_G_CreateFromWkt(\n\t\t&cString, srs.cval, &newGeom.cval,\n\t).Err()\n}", "func wkt(wkt string) (*SR, error) {\n\tsr := NewSR()\n\terr := sr.parseWKTSection([]string{}, wkt)\n\n\t// Convert units to meters.\n\tsr.X0 *= sr.ToMeter\n\tsr.Y0 *= sr.ToMeter\n\tif math.IsNaN(sr.Lat0) {\n\t\tsr.Lat0 = sr.Lat1\n\t}\n\n\treturn sr, err\n}", "func (jwk JWK) Kty() string {\n\treturn stringEntry(jwk[\"kty\"])\n}", "func jsonifyType(typeName string) string {\n\tswitch typeName {\n\tcase stringType:\n\t\treturn stringJSONType\n\tcase boolType:\n\t\treturn booleanJSONType\n\tcase intType, int32Type, int64Type:\n\t\treturn integerJSONType\n\tcase float32Type, float64Type:\n\t\treturn floatJSONType\n\tcase byteType:\n\t\treturn stringJSONType\n\t}\n\tfmt.Println(\"jsonifyType called with a complex type \", typeName)\n\tpanic(\"jsonifyType called with a complex type\")\n}", "func NewJwt(env application.Env, clock core.Clock) application.Jwt {\n\treturn &j{env, clock}\n}", "func JSONType(conn redis.Conn, key string, path string) (res interface{}, err error) {\n\tname, args, _ := CommandBuilder(\"JSON.TYPE\", key, path)\n\treturn conn.Do(name, args...)\n}", "func NewJWT(claims jwt.MapClaims, signingKey string, signingMethod ...jwt.SigningMethod) (string, error) {\n\tvar sm jwt.SigningMethod = jwt.SigningMethodHS256\n\tif len(signingMethod) > 0 {\n\t\tsm = signingMethod[0]\n\t}\n\treturn jwt.NewWithClaims(sm, claims).SignedString([]byte(signingKey))\n}", "func NewJWT(claims map[string]interface{}, validFor time.Duration) (string, error) {\n\ttoken := jwt.New(jwt.SigningMethodHS256)\n\n\tfor k, v := range claims {\n\t\ttoken.Claims[k] = v\n\t}\n\n\ttoken.Claims[\"exp\"] = time.Now().UTC().Add(validFor).Unix()\n\treturn token.SignedString([]byte(JWTPrivateKey))\n}", "func NewGojwt() (*Gojwt, error){\n\n return &Gojwt{\n secretKeyWord: \"Jnzads\",\n headerKeyAuth: \"Jnzads-JWT\",\n numHoursDuration: 1,\n method: \"HMAC-SHA\",\n lenBytes: \"256\",\n nameServer: \"JnzadsServer\"}, nil\n}", "func createJWT(secret map[string]interface{}, scope string, pkey pkeyInterface) (string, error) {\n\t// A valid JWT has an \"iat\" timestamp and an \"exp\" timestamp. Get the current\n\t// time to create these timestamps.\n\tnow := int(time.Now().Unix())\n\n\t// Construct the JWT header, which contains the private key id in the service\n\t// account secret.\n\theader := map[string]string{\n\t\t\"typ\": \"JWT\",\n\t\t\"alg\": \"RS256\",\n\t\t\"kid\": toString(secret[\"private_key_id\"]),\n\t}\n\n\t// Construct the JWT payload.\n\tpayload := map[string]string{\n\t\t\"aud\": toString(secret[\"token_uri\"]),\n\t\t\"scope\": scope,\n\t\t\"iat\": strconv.Itoa(now),\n\t\t\"exp\": strconv.Itoa(now + 3600),\n\t\t\"iss\": toString(secret[\"client_email\"]),\n\t}\n\n\t// Convert header and payload to base64-encoded JSON.\n\theaderB64, err := mapToJsonBase64(header)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpayloadB64, err := mapToJsonBase64(payload)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// The first two segments of the JWT are signed. The signature is the third\n\t// segment.\n\tsegments := headerB64 + \".\" + payloadB64\n\n\t// sign the hash, instead of the actual segments.\n\thashed := sha256.Sum256([]byte(segments))\n\tsignedBytes, err := pkey.Sign(rand.Reader, hashed[:], crypto.SignerOpts(sha256Opts{}))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Generate the final JWT as\n\t// base64(header) + \".\" + base64(payload) + \".\" + base64(signature)\n\treturn segments + \".\" + base64Encode(signedBytes), nil\n}", "func New(apikey string, defaults *Options) (*W3W, error) {\n\tif apikey == \"\" || strings.TrimSpace(apikey) == \"\" {\n\t\treturn nil, ErrNoAPIKey\n\t}\n\n\tif defaults == nil {\n\t\treturn &W3W{apikey, &http.Client{}, &defs}, nil\n\t}\n\n\treturn &W3W{apikey, &http.Client{}, defaults}, nil\n\n}", "func skykeyCreate(c client.Client, name, skykeyTypeString string) (string, error) {\n\tvar st skykey.SkykeyType\n\tif skykeyTypeString == \"\" {\n\t\t// If no type is provided, default to Private\n\t\tst = skykey.TypePrivateID\n\t} else {\n\t\terr := st.FromString(skykeyTypeString)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.AddContext(err, \"Unable to decode skykey type\")\n\t\t}\n\t}\n\tsk, err := c.SkykeyCreateKeyPost(name, st)\n\tif err != nil {\n\t\treturn \"\", errors.AddContext(err, \"Could not create skykey\")\n\t}\n\treturn sk.ToString()\n}", "func NewJWT(key string) *JWT {\n\treturn &JWT{\n\t\tkey: key,\n\t\tqueryTokenKey: \"token\",\n\t\theaderKey: \"Authorization\",\n\t\tverifier: func(claims map[string]interface{}) error {\n\t\t\treturn nil\n\t\t},\n\t\terrHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\thttputils.WriteError(ErrUserNotAllowed, http.StatusUnauthorized, w)\n\t\t}),\n\t}\n}", "func New(config *Config) *JWT {\n\tcontextKey = config.ContextKey\n\treturn &JWT{\n\t\tConfig: config,\n\t}\n}", "func NewJWS(privateKey crypto.PrivateKey, kid string, nonceManager *nonces.Manager) *JWS {\n\treturn &JWS{\n\t\tprivKey: privateKey,\n\t\tnonces: nonceManager,\n\t\tkid: kid,\n\t}\n}", "func NewJWTMiddleware() (goa.Middleware, error) {\n\tkeys, err := LoadJWTPublicKeys()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jwt.New(jwt.NewSimpleResolver(keys), ForceFail(), app.NewJWTSecurity()), nil\n}", "func JwtCreate(data JwtData) (string, error) {\n\n\t// validate struct\n\tif err := jwtValidate.Struct(data); err != nil {\n\t\treturn \"\", err\n\t}\n\t// data to json\n\tdataJSON, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// encrypt json\n\tdataEncrypted, err := encrypt(dataJSON, keyAES)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// Create token\n\ttoken := jwt.New(jwt.SigningMethodHS256)\n\ttoken.Claims = jwt.MapClaims{\n\t\t\"data\": dataEncrypted,\n\t\t\"exp\": time.Now().Add(time.Hour * expireHour).Unix(),\n\t}\n\t// claims := token.Claims.(jwt.MapClaims)\n\t// claims[\"data\"] = dataEncrypted\n\t// claims[\"exp\"] = time.Now().Add(time.Hour * expireHour).Unix()\n\n\t// Generate encoded token and send it as response.\n\ttokenString, err := token.SignedString(KeyJWT)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn tokenString, nil\n\n}", "func NewJWTMaker(secretKey string) (Maker, error) {\n\tif len(secretKey) < minSecretKeySize {\n\t\treturn nil, fmt.Errorf(\"invalid key size: must be at least %d characters\", minSecretKeySize)\n\t}\n\treturn &JWTMaker{secretKey}, nil\n}", "func NewKeyWithTypeFromSerialized(input SerializedKeyWithType) (KeyWithType, error) {\n\treturn NewKeyWithType(string(input))\n}", "func NewWriter(wtype Format) (wrt IWriter, err error) {\n\tswitch wtype {\n\tcase JSON:\n\t\twrt = json.WriterJson{}\n\tcase XML:\n\t\twrt = xml.WriterXml{}\n\tdefault:\n\t\terr = ErrUnsupportedWriter\n\t}\n\treturn\n}", "func NewJWT(expire time.Duration, secret []byte) (j *JWT, err error) {\n\tsigningAlgorithm := \"HS256\"\n\tmethod := jwt.GetSigningMethod(signingAlgorithm)\n\tif method == nil {\n\t\terr = fmt.Errorf(\"invalid signingAlgorithm:%s\", method)\n\t\treturn\n\t}\n\tj = &JWT{expire: expire, method: method, secret: secret}\n\treturn\n}", "func (pk PublicKey) PublicKeyJwk() JWK {\n\tentry, ok := pk[PublicKeyJwkProperty]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tjson, ok := entry.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn NewJWK(json)\n}", "func NewJwtFactory(signingKey *rsa.PrivateKey) JwtFactory {\r\n\treturn JwtFactory{\r\n\t\tsigningKey,\r\n\t}\r\n}", "func NewJWTMiddleware() (goa.Middleware, error) {\n\tkeys, err := LoadJWTPublicKeys()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jwt.New(keys, ForceFail(), app.NewJWTSecurity()), nil\n}", "func createJWT(SID string) (string, error) {\n\t// Create custom claims value\n\tclaims := MyCustomClaims{\n\t\tSID,\n\t\tjwt.StandardClaims{\n\t\t\tExpiresAt: expire,\n\t\t},\n\t}\n\t// Create a jwt tokenizer\n\ttokenizer := jwt.NewWithClaims(jwt.SigningMethodHS512, &claims)\n\t// create a token and sign it with your key\n\tss, err := tokenizer.SignedString(key)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error in SignedString while signing: %w\", err)\n\t}\n\treturn ss, nil\n}", "func CreateJWSSignature(payload string, privateKey *ecdsa.PrivateKey) (string, error) {\n\tjoseSigner, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.ES256, Key: privateKey}, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsignedObject, err := joseSigner.Sign([]byte(payload))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// serialized := signedObject.FullSerialize()\n\tserialized, err := signedObject.CompactSerialize()\n\treturn serialized, err\n}", "func newJWTAuthentication(userName, password string) httpAuthentication {\n\treturn &jwtAuthentication{\n\t\tuserName: userName,\n\t\tpassword: password,\n\t}\n}", "func createJwt(payload *JWTUser) (string, error) {\n\t// if the Expires isn't set, we need to set it to the expiration from the config\n\t// the only time it may be set is during test\n\t// generally, if you find yourself setting this by hand, you're doing it wrong\n\tif payload.Expires == \"\" {\n\t\tpayload.Expires = time.Now().Add(Config.TokenExpiresMinutes).Format(\"2006-01-02T15:04:05Z\")\n\t}\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{\n\t\t\"user\": payload,\n\t})\n\ttokenString, err := token.SignedString([]byte(Config.TokenSalt))\n\n\treturn tokenString, err\n}", "func (s *Service) GetJWK(keyID string) (jose.JSONWebKey, error) {\n\tprivateKey, ok := s.keys[keyID]\n\tif !ok {\n\t\ts.log.Error(\"The specified key was not found\", \"keyID\", keyID)\n\t\treturn jose.JSONWebKey{}, signingkeys.ErrSigningKeyNotFound.Errorf(\"The specified key was not found: %s\", keyID)\n\t}\n\n\tresult := jose.JSONWebKey{\n\t\tKey: privateKey.Public(),\n\t\tUse: \"sig\",\n\t}\n\n\treturn result, nil\n}", "func NewJSONSchema(source string, level string) *JSONSchema {\n\tjs := new(JSONSchema)\n\n\tschemaErrors = NewSchemaErrors()\n\tsuppressErrors = NewSchemaErrors()\n\n\tMutex = NewSchemaMutex()\n\n\tkeywords = make(map[string]validator)\n\n\tkeywords[\"type\"] = validType\n\tkeywords[\"enum\"] = validEnum\n\tkeywords[\"required\"] = validRequired\n\tkeywords[\"properties\"] = validProperties\n\tkeywords[\"additionalProperties\"] = validProperties\n\tkeywords[\"patternProperties\"] = validProperties\n\tkeywords[\"minProperties\"] = validProperties\n\tkeywords[\"maxProperties\"] = validProperties\n\tkeywords[\"items\"] = validItems\n\tkeywords[\"uniqueItems\"] = validUnique\n\tkeywords[\"maxItems\"] = validMaxItems\n\tkeywords[\"minItems\"] = validMinItems\n\tkeywords[\"additionalItems\"] = validAdditionalItems\n\tkeywords[\"maxLength\"] = validMaxLength\n\tkeywords[\"minLength\"] = validMinLength\n\tkeywords[\"maximum\"] = validMaximum\n\tkeywords[\"exclusiveMaximum\"] = validMaximum\n\tkeywords[\"minimum\"] = validMinimum\n\tkeywords[\"exclusiveMinimum\"] = validMinimum\n\tkeywords[\"pattern\"] = validPattern\n\tkeywords[\"anyOf\"] = validAnyOf\n\tkeywords[\"allOf\"] = validAllOf\n\tkeywords[\"oneOf\"] = validOneOf\n\tkeywords[\"multipleOf\"] = validMultipleOf\n\tkeywords[\"default\"] = validDefault\n\tkeywords[\"not\"] = validNot\n\tkeywords[\"format\"] = validFormat\n\n\tregexHostname = regexp.MustCompile(`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)` +\n\t\t\t\t\t`*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$`)\n\tregexDateTime = regexp.MustCompile(`^([0-9]{4})-([0-9]{2})-([0-9]{2})` +\n\t\t\t\t\t`([Tt]([0-9]{2}):([0-9]{2}):([0-9]{2})(\\.[0-9]+)?)?` +\n\t\t\t\t\t`([Tt]([0-9]{2}):([0-9]{2}):([0-9]{2})(\\\\.[0-9]+)?)?` +\n\t\t\t\t\t`(([Zz]|([+-])([0-9]{2}):([0-9]{2})))?`)\n\tregexEmail = regexp.MustCompile(`^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$`)\n\n\tvalidateFormat = true\n\tsuppress = false\n\n\tjs.schema = NewJSONParser(source, 1, level)\n\n\tjs.schema.Parse()\n\n\treturn js\n}", "func (el *Element) MustType(keys ...input.Key) *Element {\n\tel.e(el.Type(keys...))\n\treturn el\n}", "func (s *Schema) ChooseType() JSONType {\n\tswitch {\n\tcase s.Type != nil && len(*s.Type) > 0:\n\t\treturn (*s.Type)[0]\n\tcase len(s.Properties) > 0,\n\t\ts.AdditionalProperties.Present(),\n\t\tlen(s.PatternProperties) > 0,\n\t\ts.MinProperties > 0,\n\t\ts.MaxProperties != nil,\n\t\tlen(s.AllOf) > 0:\n\t\treturn JSONObject\n\tcase s.Items.Present(),\n\t\ts.UniqueItems,\n\t\ts.MinItems != 0,\n\t\ts.MaxItems != nil:\n\t\treturn JSONArray\n\tcase s.Pattern != nil,\n\t\ts.MinLength > 0,\n\t\ts.MaxLength != nil:\n\t\treturn JSONString\n\t}\n\treturn JSONUnknown\n}", "func (k *Key) Type() OTPType {\n\treturn OTPType(k.Host)\n}", "func NewKVWatcher(kvType KVStore, address string, prefix string) (Watcher, error) {\n\tvar backend store.Backend\n\tswitch kvType {\n\tcase Consul:\n\t\tconsul.Register()\n\t\tbackend = store.CONSUL\n\tcase Zookeeper:\n\t\tzookeeper.Register()\n\t\tbackend = store.ZK\n\tcase Etcd:\n\t\tetcd.Register()\n\t\tbackend = store.ETCD\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown kvType=%d\", kvType)\n\t}\n\n\tstore, err := valkeyrie.NewStore(backend, []string{address}, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &libkvWatcher{\n\t\tprefix: prefix,\n\t\tstore: store,\n\t}, nil\n}", "func WarehouseType(ctx *context.Context) *string {\n\twarehouseType := (*ctx).Value(KeyWarehouseType)\n\tif warehouseType != nil {\n\t\tv := warehouseType.(string)\n\t\treturn &v\n\t}\n\treturn nil\n}", "func (j *JWK) MarshalJSON() ([]byte, error) {\n\tif isSecp256k1(j.Kty, j.Crv) {\n\t\treturn marshalSecp256k1(j)\n\t}\n\n\treturn (&j.JSONWebKey).MarshalJSON()\n}", "func GetJobType(ctx context.Context, clientConfig *rest.Config) (*JobType, error) {\n\tconfigClient, err := configclient.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinfrastructure, err := configClient.Infrastructures().Get(ctx, \"cluster\", metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclusterVersion, err := configClient.ClusterVersions().Get(ctx, \"version\", metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnetwork, err := configClient.Networks().Get(ctx, \"cluster\", metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tarchitecture, err := getArchitecture(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trelease := VersionFromHistory(clusterVersion.Status.History[0])\n\n\tfromRelease := \"\"\n\tif len(clusterVersion.Status.History) > 1 {\n\t\tfromRelease = VersionFromHistory(clusterVersion.Status.History[1])\n\t}\n\n\tplatform := \"\"\n\tswitch infrastructure.Status.PlatformStatus.Type {\n\tcase configv1.AWSPlatformType:\n\t\tplatform = \"aws\"\n\tcase configv1.GCPPlatformType:\n\t\tplatform = \"gcp\"\n\tcase configv1.AzurePlatformType:\n\t\tplatform = \"azure\"\n\tcase configv1.VSpherePlatformType:\n\t\tplatform = \"vsphere\"\n\tcase configv1.BareMetalPlatformType:\n\t\tplatform = \"metal\"\n\tcase configv1.OvirtPlatformType:\n\t\tplatform = \"ovirt\"\n\tcase configv1.OpenStackPlatformType:\n\t\tplatform = \"openstack\"\n\tcase configv1.LibvirtPlatformType:\n\t\tplatform = \"libvirt\"\n\t}\n\n\tnetworkType := \"\"\n\tswitch network.Status.NetworkType {\n\tcase \"OpenShiftSDN\":\n\t\tnetworkType = \"sdn\"\n\tcase \"OVNKubernetes\":\n\t\tnetworkType = \"ovn\"\n\t}\n\n\ttopology := \"\"\n\tswitch infrastructure.Status.ControlPlaneTopology {\n\tcase configv1.HighlyAvailableTopologyMode:\n\t\ttopology = \"ha\"\n\tcase configv1.SingleReplicaTopologyMode:\n\t\ttopology = \"single\"\n\t}\n\n\treturn &JobType{\n\t\tRelease: release,\n\t\tFromRelease: fromRelease,\n\t\tPlatform: platform,\n\t\tArchitecture: architecture,\n\t\tNetwork: networkType,\n\t\tTopology: topology,\n\t}, nil\n}", "func New(alg Alg) *JWT {\n\treturn &JWT{\n\t\talg: alg,\n\t\tHeader: NewHeader(alg),\n\t\tClaims: NewStdClaims(),\n\t}\n}", "func NewWithType(size int, tp string) *GCache {\n\treturn &GCache{\n\t\tdb: gcache.New(size).EvictType(tp).Build(),\n\t}\n}", "func CreateDIDKeyByJwk(jsonWebKey *jwk.JWK) (string, string, error) {\n\treturn fingerprint.CreateDIDKeyByJwk(jsonWebKey)\n}", "func (geom Geometry) FromWKT(wkt string) error {\n\tcString := C.CString(wkt)\n\tdefer C.free(unsafe.Pointer(cString))\n\treturn C.OGR_G_ImportFromWkt(geom.cval, &cString).Err()\n}", "func Jwt(opts ...options.OptionFunc) string {\n\treturn singleFakeData(JWT, func() interface{} {\n\t\topt := options.BuildOptions(opts)\n\t\ti := Internet{fakerOption: *opt}\n\t\tp, err := i.jwt()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\treturn p\n\t}, opts...).(string)\n}", "func NewJWTMiddleware() (goa.Middleware, error) {\n\terr := jwt.LoadKeys()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpub := jwt.PublicKey()\n\n\tforceFail := func(h goa.Handler) goa.Handler {\n\t\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t}\n\tfm, err := goa.NewMiddleware(forceFail)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn goajwt.New(pub, fm,\n\t\tapp.NewJWTSecurity()), nil\n}", "func buildJWKFromRSA(k *rsa.PublicKey) (*Key, error) {\n\treturn &Key{\n\t\tKeyType: \"RSA\",\n\t\tN: base64.RawURLEncoding.EncodeToString(k.N.Bytes()),\n\t\tE: base64.RawURLEncoding.EncodeToString(big.NewInt(int64(k.E)).Bytes()),\n\t}, nil\n}", "func EncodePublicKey(key crypto.PublicKey) (jwk *JWK, err error) {\n\tjwk = new(JWK)\n\tswitch k := key.(type) {\n\tcase *ecdsa.PublicKey:\n\t\tjwk.populateECPublicKey(k)\n\n\tcase *rsa.PublicKey:\n\t\tjwk.populateRSAPublicKey(k)\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"jwk: unknown private key type: %T\", key)\n\t}\n\n\treturn jwk, nil\n}", "func determineKeyType(k, v string) (infoType infoType, newKey string) {\n\tif len(k) == 0 || len(v) == 0 {\n\t\treturn invalidType, k\n\t}\n\n\tswitch {\n\tcase strings.HasPrefix(k, PrefixTransientUpstream):\n\t\tif len(k) > lenPTU {\n\t\t\treturn transientUpstreamType, k[lenPTU:]\n\t\t}\n\tcase strings.HasPrefix(k, PrefixTransient):\n\t\tif len(k) > lenPT {\n\t\t\treturn transientType, k[lenPT:]\n\t\t}\n\tcase strings.HasPrefix(k, PrefixPersistent):\n\t\tif len(k) > lenPP {\n\t\t\treturn persistentType, k[lenPP:]\n\t\t}\n\t}\n\treturn invalidType, k\n}", "func GetTypeObject(typ string) Type {\n\ttypePrimitive, isPrimitive := primitives[typ]\n\tif isPrimitive {\n\t\treturn Type{\n\t\t\tPrimitive: typePrimitive,\n\t\t}\n\t}\n\treturn Type{\n\t\tPrimitive: PrimitiveLaME,\n\t\tIdentifier: typ,\n\t}\n}", "func (o *PartialApplicationKey) GetTypeOk() (*ApplicationKeysType, bool) {\n\tif o == nil || o.Type == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Type, true\n}", "func newKVClient(storeType, address string, timeout time.Duration) (kvstore.Client, error) {\n\tlogger.Infow(\"kv-store-type\", log.Fields{\"store\": storeType})\n\tswitch storeType {\n\tcase \"consul\":\n\t\treturn kvstore.NewConsulClient(address, timeout)\n\tcase \"etcd\":\n\t\treturn kvstore.NewEtcdClient(address, timeout, log.FatalLevel)\n\t}\n\treturn nil, errors.New(\"unsupported-kv-store\")\n}", "func (c *coder) encoderForType(keyOrValue, typ string) (func([]byte) (json.RawMessage, error), error) {\n\tvar enc func([]byte) string\n\tswitch typ {\n\tcase \"json\":\n\t\treturn func(data []byte) (json.RawMessage, error) {\n\t\t\tif err := json.Unmarshal(data, new(json.RawMessage)); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid JSON value %q: %v\", data, err)\n\t\t\t}\n\t\t\treturn json.RawMessage(data), nil\n\t\t}, nil\n\tcase \"hex\":\n\t\tenc = hex.EncodeToString\n\tcase \"base64\":\n\t\tenc = base64.StdEncoding.EncodeToString\n\tcase \"string\":\n\t\tenc = func(data []byte) string {\n\t\t\treturn string(data)\n\t\t}\n\tcase \"avro\":\n\t\treturn c.encodeAvro, nil\n\tcase \"none\":\n\t\treturn func([]byte) (json.RawMessage, error) {\n\t\t\treturn nil, nil\n\t\t}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(`unsupported decoder %#v, only json, string, hex, base64 and avro are supported`, typ)\n\t}\n\treturn func(data []byte) (json.RawMessage, error) {\n\t\tif data == nil {\n\t\t\treturn nullJSON, nil\n\t\t}\n\t\tdata1, err := json.Marshal(enc(data))\n\t\tif err != nil {\n\t\t\t// marshaling a string cannot fail but be defensive.\n\t\t\treturn nil, err\n\t\t}\n\t\treturn json.RawMessage(data1), nil\n\t}, nil\n}", "func JSONType(base interface{}) *jsonDataType {\n\ttyp := reflect.TypeOf(base)\n\treturn &jsonDataType{base: base, typ: typ}\n}", "func GetJWTPayload(ctx context.Context) (ValidatedJWTPayload, bool) {\n\tvalue := ctx.Value(key)\n\n\tpayload, ok := value.(ValidatedJWTPayload)\n\tif ok && payload.Validated {\n\t\treturn payload, true\n\t}\n\n\treturn ValidatedJWTPayload{}, false\n}", "func Time(t time.Time) *WKTime {\n\twkT := WKTime(t)\n\treturn &wkT\n}", "func New() *JWTUtil {\n\tJWT = &JWTUtil{}\n\treturn JWT\n}", "func (v *Value) Type() *JSONType {\n\tt := C.zj_Type(v.V)\n\tif t == nil {\n\t\treturn nil\n\t}\n\tret := JSONType(*t)\n\treturn &ret\n}", "func (jwt *JWT) MakeJWT(hm map[string]string, pm interface{}) string {\r\n\t// header bytes\r\n\thm[\"alg\"] = jwt.alg\r\n\thm[\"typ\"] = jwt.typ\r\n\thb, _ := json.Marshal(hm)\r\n\t// for test\r\n\t// hb1, err := json.Marshal(hm)\r\n\t// if err != nil {\r\n\t// \tpanic(err)\r\n\t// }\r\n\t//\r\n\t// payload bytes\r\n\tpb, _ := json.Marshal(pm)\r\n\t// signature bytes\r\n\tsb := jwt.hmac_SHA256(hb, pb)\r\n\t// base64 string\r\n\thstr := base64.URLEncoding.EncodeToString(hb)\r\n\tpstr := base64.URLEncoding.EncodeToString(pb)\r\n\tsstr := base64.URLEncoding.EncodeToString(sb)\r\n\treturn fmt.Sprintf(\"%s.%s.%s\", hstr, pstr, sstr)\r\n}", "func createJWT(appID int64, keyPEM []byte) (string, error) {\n\tkey, err := jwt.ParseRSAPrivateKeyFromPEM(keyPEM)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tnow := time.Now()\n\treturn jwt.NewWithClaims(\n\t\tjwt.SigningMethodRS256,\n\t\tjwt.StandardClaims{\n\t\t\tIssuedAt: now.Unix(),\n\t\t\tExpiresAt: now.Add(5 * time.Minute).Unix(),\n\t\t\tIssuer: strconv.FormatInt(int64(appID), 10),\n\t\t},\n\t).SignedString(key)\n}", "func (r GetPublicKeyRequest) Type() RequestType {\n\treturn GetPublicKey\n}", "func (k *Keyboard) MustType(key ...input.Key) *Keyboard {\n\tk.page.e(k.Type(key...))\n\treturn k\n}", "func NewJWTController(service *goa.Service) (*JWTController, error) {\n\tb, err := ioutil.ReadFile(\"./jwtkey/jwt.key\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivKey, err := jwtgo.ParseRSAPrivateKeyFromPEM(b)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"jwt: failed to load private key: %s\", err) // bug\n\t}\n\treturn &JWTController{\n\t\tController: service.NewController(\"JWTController\"),\n\t\tprivateKey: privKey,\n\t}, nil\n}", "func (r *RawKeyJSON) GenerateKey() (Key, error) {\n\n\tvar key Key\n\n\tswitch r.KeyType {\n\tcase jwa.RSA:\n\t\tif r.D != nil {\n\t\t\tkey = &RSAPrivateKey{}\n\t\t} else {\n\t\t\tkey = &RSAPublicKey{}\n\t\t}\n\tcase jwa.EC:\n\t\tif r.D != nil {\n\t\t\tkey = &ECDSAPrivateKey{}\n\t\t} else {\n\t\t\tkey = &ECDSAPublicKey{}\n\t\t}\n\tcase jwa.OctetSeq:\n\t\tkey = &SymmetricKey{}\n\tdefault:\n\t\treturn nil, errors.New(\"unrecognized key type\")\n\t}\n\terr := key.GenerateKey(r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to generate key from JWK: %w\", err)\n\t}\n\treturn key, nil\n}", "func getJWK(jwkURL string) (map[string]JWKKey, error) {\n\tInfo.Printf(\"Downloading the jwk from the given url %s\", jwkURL)\n\tjwk := &JWK{}\n\n\tvar myClient = &http.Client{Timeout: 10 * time.Second}\n\tr, err := myClient.Get(jwkURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Body.Close()\n\tif err := json.NewDecoder(r.Body).Decode(jwk); err != nil {\n\t\treturn nil, err\n\t}\n\n\tjwkMap := make(map[string]JWKKey, 0)\n\tfor _, jwk := range jwk.Keys {\n\t\tjwkMap[jwk.Kid] = jwk\n\t}\n\treturn jwkMap, nil\n}", "func EncodePrivateKey(key crypto.PrivateKey) (jwk *JWK, err error) {\n\tjwk = new(JWK)\n\tswitch k := key.(type) {\n\tcase *ecdsa.PrivateKey:\n\t\tjwk.populateECPublicKey(&k.PublicKey)\n\t\tjwk.D = b64.EncodeToString(k.D.Bytes())\n\n\tcase *rsa.PrivateKey:\n\t\tjwk.populateRSAPublicKey(&k.PublicKey)\n\t\tjwk.D = b64.EncodeToString(k.D.Bytes())\n\t\tif len(k.Primes) < 2 || len(k.Precomputed.CRTValues) != len(k.Primes)-2 {\n\t\t\treturn nil, errors.New(\"jwk: invalid RSA primes number\")\n\t\t}\n\t\tjwk.P = b64.EncodeToString(k.Primes[0].Bytes())\n\t\tjwk.Q = b64.EncodeToString(k.Primes[1].Bytes())\n\t\tjwk.Dp = b64.EncodeToString(k.Precomputed.Dp.Bytes())\n\t\tjwk.Dq = b64.EncodeToString(k.Precomputed.Dq.Bytes())\n\t\tjwk.Qi = b64.EncodeToString(k.Precomputed.Qinv.Bytes())\n\n\t\tif len(k.Primes) > 2 {\n\t\t\tjwk.Oth = make([]*RSAPrime, len(k.Primes)-2)\n\t\t\tfor i := 0; i < len(k.Primes)-2; i++ {\n\t\t\t\tjwk.Oth[i] = &RSAPrime{\n\t\t\t\t\tR: b64.EncodeToString(k.Primes[i+2].Bytes()),\n\t\t\t\t\tD: b64.EncodeToString(k.Precomputed.CRTValues[i].Exp.Bytes()),\n\t\t\t\t\tT: b64.EncodeToString(k.Precomputed.CRTValues[i].Coeff.Bytes()),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"jwk: unknown private key type: %T\", key)\n\t}\n\n\treturn jwk, nil\n}", "func JSONSchemaType(t string) string {\n\tif m, ok := kindMap[t]; ok {\n\t\treturn m\n\t}\n\treturn t\n}", "func NewEncoder(encType uint32, key []byte) (*Encoder, error) {\n\tEntry, ok := encoders[encType]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid encoding type %d\", encType)\n\t}\n\n\tenc, err := Entry.factory(key)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s encoding error: %w\", enc, err)\n\t}\n\n\tkeysize := enc.KeySize()\n\tif len(key) < keysize+HMAC256KeySize {\n\t\treturn nil, ErrKeyTooSmall\n\t}\n\n\treturn &Encoder{\n\t\tenc: enc,\n\t\thmac: NewHMAC256(key[keysize : keysize+HMAC256KeySize]),\n\t\tname: Entry.name,\n\t}, nil\n}", "func (p *JWK) Init(config Config) (err error) {\n\tswitch {\n\tcase p.Type == \"\":\n\t\treturn errors.New(\"provisioner type cannot be empty\")\n\tcase p.Name == \"\":\n\t\treturn errors.New(\"provisioner name cannot be empty\")\n\tcase p.Key == nil:\n\t\treturn errors.New(\"provisioner key cannot be empty\")\n\t}\n\n\t// Update claims with global ones\n\tif p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {\n\t\treturn err\n\t}\n\n\tp.audiences = config.Audiences\n\treturn err\n}", "func (keyType *KeyType) UnmarshalJSON(data []byte) error {\n\tvar quote byte = '\"'\n\tvar quoted string\n\tif data[0] == quote {\n\t\tvar err error\n\t\tquoted, err = strconv.Unquote(string(data))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to process signature algorithm: %w\", err)\n\t\t}\n\t} else {\n\t\tquoted = string(data)\n\t}\n\t_, ok := keyTypeAlg[quoted]\n\tif !ok {\n\t\treturn errors.New(\"unknown signature algorithm\")\n\t}\n\t*keyType = KeyType(quoted)\n\treturn nil\n}", "func (e *commonFormatEncoder) Type() string {\n\treturn \"json\"\n}", "func NewJWTClient(opt JWTOptions) (*JWTClient, error) {\n\terr := opt.validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjwtCli := &JWTClient{Options: opt}\n\n\t// parse verifyKey\n\tif opt.VerifyKey != nil {\n\t\tjwtCli.verifyKey = opt.VerifyKey\n\t} else {\n\t\tverifyBytes, err := ioutil.ReadFile(opt.VerifyKeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tjwtCli.verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// parse SignKey\n\tif opt.SignKey != nil {\n\t\tjwtCli.signKey = opt.SignKey\n\t} else if opt.SignKeyFile != \"\" {\n\t\tsignBytes, err := ioutil.ReadFile(opt.SignKeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tjwtCli.signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn jwtCli, nil\n}", "func (s *Signer) Type() string {\n\treturn signing.TypeKMS\n}", "func (t *VLStrDbl) CassandraCreateType(keyspace string) string {\n\treturn \"CREATE TYPE IF NOT EXISTS \" + keyspace + \".VTStrDbl ( k varchar, v double );\"\n}", "func getJWTMiddleware() middlewares.MiddlewareFunc {\n\treturn middlewares.NewJWT(&middlewares.JWTConfig{\n\t\tSigningKey: []byte(\"test\"),\n\t\tHeaderKey: []byte(\"Authorization\"),\n\t})\n}", "func (t *VTStrDbl) CassandraCreateType(keyspace string) string {\n\treturn \"CREATE TYPE IF NOT EXISTS \" + keyspace + \".VTStrDbl ( k varchar, v double );\"\n}", "func (t *VMStrTPDblStr) CassandraCreateType(keyspace string) string {\n\treturn \"CREATE TYPE IF NOT EXISTS \" + keyspace + \".VTDblStr ( k double, v varchar );\"\n}", "func (RestController *RestController) WriteNewDataType(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tdataType := model.DataType{}\n\terr01 := json.NewDecoder(r.Body).Decode(&dataType)\n\tif err01 == nil {\n\t\tnewDataType, err02 := RestController.databaseController.WriteNewDataType(&dataType)\n\t\tif err02 == nil {\n\t\t\tjsonBytes, _ := json.Marshal(*newDataType)\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(200)\n\t\t\tfmt.Fprintf(w, \"%s\", jsonBytes)\n\t\t} else {\n\t\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\t\tw.WriteHeader(400)\n\t\t\tfmt.Fprintf(w, \"%s\", err02)\n\t\t}\n\t} else {\n\t\tmsg := fmt.Sprintf(\"Input JSON cannot be decoded, http body: %s\\n\", err01)\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tw.WriteHeader(400)\n\t\tfmt.Fprintf(w, \"%s\", msg)\n\t}\n}", "func (t *VMStrTPStrDbl) CassandraCreateType(keyspace string) string {\n\treturn \"CREATE TYPE IF NOT EXISTS \" + keyspace + \".VTStrDbl ( k varchar, v double );\"\n}", "func NewJWTMiddleware(cfg ...JWTConfig) *JWTMiddleware {\n\n\tvar c JWTConfig\n\tif len(cfg) == 0 {\n\t\tc = JWTConfig{}\n\t} else {\n\t\tc = cfg[0]\n\t}\n\n\tif c.ContextKey == \"\" {\n\t\tc.ContextKey = DefaultContextKey\n\t}\n\n\tif c.ErrorHandler == nil {\n\t\tc.ErrorHandler = OnError\n\t}\n\n\tif c.Extractor == nil {\n\t\tc.Extractor = FromAuthHeader\n\t}\n\n\treturn &JWTMiddleware{Config: c}\n}" ]
[ "0.655761", "0.63698053", "0.577357", "0.5768871", "0.5633736", "0.562614", "0.5422218", "0.54051393", "0.5397407", "0.53441304", "0.532489", "0.51979995", "0.5142026", "0.5117357", "0.5048858", "0.498495", "0.49803796", "0.4941713", "0.49219853", "0.4858893", "0.4855007", "0.48444462", "0.48000106", "0.47895837", "0.47813743", "0.4767901", "0.47413844", "0.46837193", "0.46612433", "0.46475637", "0.46446136", "0.46382543", "0.46198538", "0.46190816", "0.45677084", "0.45585862", "0.45570806", "0.4499508", "0.44987315", "0.44986594", "0.44944593", "0.44869176", "0.44752052", "0.44729075", "0.44722867", "0.44700986", "0.4460955", "0.44427204", "0.44411775", "0.44257382", "0.44212547", "0.44098473", "0.44032556", "0.43989164", "0.43921345", "0.4390978", "0.4389677", "0.4387454", "0.43872806", "0.4374194", "0.4368889", "0.43669513", "0.4358966", "0.4355593", "0.43489864", "0.43412286", "0.43378964", "0.43338528", "0.4326781", "0.4318934", "0.43184713", "0.4313245", "0.43110177", "0.4294992", "0.4287122", "0.42711782", "0.42552963", "0.42530447", "0.42504036", "0.42371505", "0.42368093", "0.42360204", "0.4225016", "0.42195746", "0.42168355", "0.42153016", "0.42128178", "0.42088413", "0.42039993", "0.42039075", "0.41993356", "0.4198506", "0.419727", "0.4197234", "0.41956782", "0.4195661", "0.41947472", "0.41907164", "0.41907108", "0.41874915" ]
0.6999248
0
Curve returns the elliptic.Curve for the specificied CrvType. If the CrvType is invalid or unknown, a nil Curve type will be returned.
func CurveByName(curveName string) ec.Curve { switch curveName { case "P-224": return ec.P224() case "P-256": return ec.P256() case "P-384": return ec.P384() case "P-521": return ec.P521() default: return nil } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetCurve(s string) elliptic.Curve {\n\ts3 := s[len(s)-3:]\n\tif s3 == \"256\" {\n\t\treturn elliptic.P256()\n\t} else if s3 == \"384\" {\n\t\treturn elliptic.P384()\n\t} else if s3 == \"521\" {\n\t\treturn elliptic.P521()\n\t}\n\treturn elliptic.P224()\n}", "func getCurve(curve string) (elliptic.Curve, string, error) {\n\tswitch curve {\n\tcase \"secp224r1\": // secp224r1: NIST/SECG curve over a 224 bit prime field\n\t\treturn elliptic.P224(), \"secp224r1\", nil\n\tcase \"prime256v1\": // prime256v1: X9.62/SECG curve over a 256 bit prime field\n\t\treturn elliptic.P256(), \"prime256v1\", nil\n\tcase \"secp384r1\": // secp384r1: NIST/SECG curve over a 384 bit prime field\n\t\treturn elliptic.P384(), \"secp384r1\", nil\n\tcase \"secp521r1\": // secp521r1: NIST/SECG curve over a 521 bit prime field\n\t\treturn elliptic.P521(), \"secp521r1\", nil\n\tdefault:\n\t\treturn nil, \"\", fmt.Errorf(\"%s\", helpers.RFgB(\"incorrect curve size passed\"))\n\t}\n}", "func getCurve() elliptic.Curve {\n return elliptic.P256()\n}", "func curveByName(name string) elliptic.Curve {\n\tswitch name {\n\tcase \"P-224\":\n\t\treturn elliptic.P224()\n\tcase \"P-256\":\n\t\treturn elliptic.P256()\n\tcase \"P-384\":\n\t\treturn elliptic.P384()\n\tcase \"P-521\":\n\t\treturn elliptic.P521()\n\tcase \"P-256K\", \"SECP256K1\", \"secp256k1\":\n\t\treturn secp256k1.S256()\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (v CurveType) Validate() error {\n\tif !(v == \"edwards25519\" || v == \"secp256k1\" || v == \"secp256r1\" || v == \"tweedle\") {\n\t\treturn fmt.Errorf(\"api: invalid CurveType value: %q\", v)\n\t}\n\treturn nil\n}", "func (r1cs *R1CS) GetCurveID() gurvy.ID {\n\treturn gurvy.BN256\n}", "func getECDSACurve(scheme SignatureScheme) elliptic.Curve {\n\tswitch scheme {\n\tcase ECDSAWithP256AndSHA256:\n\t\treturn elliptic.P256()\n\tcase ECDSAWithP384AndSHA384:\n\t\treturn elliptic.P384()\n\tcase ECDSAWithP521AndSHA512:\n\t\treturn elliptic.P521()\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (s Keygen) Curve() elliptic.Curve {\n\treturn s.group\n}", "func (m *ModulusGroup) AsCurve() elliptic.Curve {\n\treturn &asCurve{m}\n}", "func EllipticCurve() elliptic.Curve {\n\treturn p256Strategy()\n}", "func CurveParamsParams(curve *elliptic.CurveParams,) *elliptic.CurveParams", "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 (r *ECDSAKeyGenerator) SetCurve(curve elliptic.Curve) {\n\tr.curve = curve\n}", "func (m CrossOrderCancelReplaceRequest) GetBenchmarkCurveCurrency() (v string, err quickfix.MessageRejectError) {\n\tvar f field.BenchmarkCurveCurrencyField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func NewCurveECDSA() ECDSA {\n\treturn &curveP256{}\n}", "func NewCurve(xyz XYZer) Curve {\n\tc := Curve{}\n\tc.points.minXYZ.X, c.points.minXYZ.Y, c.points.minXYZ.Z = xyz.XYZ(0)\n\tc.points.maxXYZ.X, c.points.maxXYZ.Y, c.points.maxXYZ.Z = xyz.XYZ(0)\n\tc.points.XYZs = CopyXYZs(xyz)\n\tfor i := range c.points.XYZs {\n\t\tx, y, z := c.points.XYZ(i)\n\t\tupdateBounds(&c.points, x, y, z)\n\t}\n\treturn c\n}", "func Generic(c elliptic.Curve) KeyExchange {\n\tif c == nil {\n\t\tpanic(\"ecdh: curve is nil\")\n\t}\n\treturn genericCurve{curve: c}\n}", "func (m CrossOrderCancelReplaceRequest) GetPriceType() (v enum.PriceType, err quickfix.MessageRejectError) {\n\tvar f field.PriceTypeField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func PeelCurve() 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.6, 0.6),\n\t\t\tmodel2d.XY(0.0, 0.0),\n\t\t},\n\t\tmodel2d.BezierCurve{\n\t\t\tmodel2d.XY(0.0, 0.0),\n\t\t\tmodel2d.XY(0.6, -0.6),\n\t\t\tmodel2d.XY(1.0, 0.0),\n\t\t},\n\t}\n}", "func (c CurveType) String() string {\n\tswitch c {\n\tcase Hilbert:\n\t\treturn \"Hilbert\"\n\tcase Morton:\n\t\treturn \"Morton\"\n\t}\n\treturn \"\"\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 (m CrossOrderCancelReplaceRequest) GetBenchmarkCurvePoint() (v string, err quickfix.MessageRejectError) {\n\tvar f field.BenchmarkCurvePointField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func New(providerType string) CloudProvider {\n\tproviderType = strings.ToLower(providerType)\n\tswitch providerType {\n\tcase \"centurylink\":\n\t\treturn NewCenturylink()\n\tcase \"amazon\":\n\t\treturn NewAmazon()\n\t}\n\treturn nil\n}", "func (path *Path) Curve(pt1, pt2, pt3 Point) {\n\twriteCommand(&path.buf, \"c\", pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y)\n}", "func (m Message) GetBenchmarkCurveCurrency(f *field.BenchmarkCurveCurrencyField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (m CrossOrderCancelReplaceRequest) GetBenchmarkCurveName() (v enum.BenchmarkCurveName, err quickfix.MessageRejectError) {\n\tvar f field.BenchmarkCurveNameField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func curveSize(crv elliptic.Curve) int {\n\tbits := crv.Params().BitSize\n\n\tdiv := bits / bitsPerByte\n\tmod := bits % bitsPerByte\n\n\tif mod == 0 {\n\t\treturn div\n\t}\n\n\treturn div + 1\n}", "func (r GetExpiryRequest) Type() RequestType {\n\treturn GetExpiry\n}", "func GetSPVClient(netType string, clientId uint64, seeds []string) (SPVClient, error) {\n\tvar magic uint32\n\tswitch netType {\n\tcase TypeMainNet:\n\t\tmagic = MainNetMagic\n\tcase TypeTestNet:\n\t\tmagic = TestNetMagic\n\tdefault:\n\t\treturn nil, errors.New(\"Unknown net type \")\n\t}\n\treturn NewSPVClientImpl(magic, clientId, seeds)\n}", "func (d MapDescriptor) Get(e C.EllCurve) MapToCurve {\n\tswitch d.ID {\n\tcase BF:\n\t\treturn NewBF(e)\n\tcase SSWU:\n\t\tz := e.Field().Elt(d.Z)\n\t\treturn NewSSWU(e, z, d.Iso)\n\tcase SVDW:\n\t\treturn NewSVDW(e)\n\tcase ELL2:\n\t\treturn NewElligator2(e)\n\tdefault:\n\t\tpanic(\"Mapping not supported\")\n\t}\n}", "func GetTicker(exchange string, p currency.Pair, tickerType asset.Item) (*Price, error) {\n\texchange = strings.ToLower(exchange)\n\tservice.RLock()\n\tdefer service.RUnlock()\n\tif service.Tickers[exchange] == nil {\n\t\treturn nil, fmt.Errorf(\"no tickers for %s exchange\", exchange)\n\t}\n\n\tif service.Tickers[exchange][p.Base.Item] == nil {\n\t\treturn nil, fmt.Errorf(\"no tickers associated with base currency %s\",\n\t\t\tp.Base)\n\t}\n\n\tif service.Tickers[exchange][p.Base.Item][p.Quote.Item] == nil {\n\t\treturn nil, fmt.Errorf(\"no tickers associated with quote currency %s\",\n\t\t\tp.Quote)\n\t}\n\n\tif service.Tickers[exchange][p.Base.Item][p.Quote.Item][tickerType] == nil {\n\t\treturn nil, fmt.Errorf(\"no tickers associated with asset type %s\",\n\t\t\ttickerType)\n\t}\n\n\treturn &service.Tickers[exchange][p.Base.Item][p.Quote.Item][tickerType].Price, nil\n}", "func (m Message) BenchmarkCurveCurrency() (*field.BenchmarkCurveCurrencyField, quickfix.MessageRejectError) {\n\tf := &field.BenchmarkCurveCurrencyField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func genericParamsForCurve(c Curve) *CurveParams {\n\td := *(c.Params())\n\treturn &d\n}", "func (cep *CoreEvalProposal) ProposalType() string { return ProposalTypeCoreEval }", "func (m CrossOrderCancelReplaceRequest) GetCrossType() (v enum.CrossType, err quickfix.MessageRejectError) {\n\tvar f field.CrossTypeField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func CurveParamsIsOnCurve(curve *elliptic.CurveParams, x, y *big.Int) bool", "func (cv *CurveVolume) Create(ctx context.Context) error {\n\toutput, err := cv.create(ctx)\n\tif err == nil {\n\t\tklog.V(4).Infof(util.Log(ctx, \"[curve] successfully create %v\"), cv.FilePath)\n\t\treturn nil\n\t}\n\n\tif strings.Contains(string(output), fmt.Sprintf(retFailFormat, retNotExist)) {\n\t\tklog.V(4).Infof(util.Log(ctx, \"[curve] try to mkdir %s before creating volume %s\"), cv.DirPath, cv.FilePath)\n\t\tif err := cv.mkdir(ctx); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to mkdir %v, err: %v\", cv.DirPath, err)\n\t\t}\n\t\t// recreate\n\t\toutput, err = cv.create(ctx)\n\t\tif err == nil {\n\t\t\tklog.V(4).Infof(util.Log(ctx, \"[curve] successfully create %v\"), cv.FilePath)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"failed to create %s, err: %v, output: %v\", cv.FilePath, err, string(output))\n}", "func (m Currency) Type() string {\n\treturn CodeCurrency\n}", "func (o *GetPrivateGetOpenOrdersByCurrencyParams) WithType(typeVar *string) *GetPrivateGetOpenOrdersByCurrencyParams {\n\to.SetType(typeVar)\n\treturn o\n}", "func NewECDSA(c config.Reader, name string, curve string) (KeyAPI, error) {\n\t// Validate the type of curve passed\n\tec, ty, err := getCurve(curve)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Generate the private key with our own io.Reader\n\tpri, err := ecdsa.GenerateKey(ec, crypto.Reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Extract the public key\n\tpub := &pri.PublicKey\n\n\t// PEM #1 - encoding\n\tpemKey, pemPub, perr := enc.Encode(pri, pub)\n\tif perr != nil {\n\t\treturn nil, perr\n\t}\n\n\t// Create the key struct object\n\tkey := &key{\n\t\tGID: api.GenerateUUID(),\n\t\tName: name,\n\t\tSlug: helpers.NewHaikunator().Haikunate(),\n\t\tKeyType: fmt.Sprintf(\"ecdsa.PrivateKey <==> %s\", ty),\n\t\tStatus: api.StatusActive,\n\t\tPublicKeyB64: base64.StdEncoding.EncodeToString([]byte(pemPub)),\n\t\tPrivateKeyB64: base64.StdEncoding.EncodeToString([]byte(pemKey)),\n\t\tFingerprintMD5: enc.FingerprintMD5(pub),\n\t\tFingerprintSHA: enc.FingerprintSHA256(pub),\n\t\tCreatedAt: time.Now(),\n\t}\n\n\t// Write the entire key object to FS\n\tif err := key.writeToFS(c, pri, pub); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn key, nil\n}", "func newPrivateKeyOnCurve(c elliptic.Curve) (*PrivateKey, error) {\n\tpk, err := ecdsa.GenerateKey(c, rand.Reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &PrivateKey{*pk}, nil\n}", "func (c *Case) Type() Type {\n\treturn c.ExprType\n}", "func (cv *CurveVolume) Delete(ctx context.Context) error {\n\targs := []string{\"delete\", \"--user\", cv.User, \"--filename\", cv.FilePath}\n\tklog.V(4).Infof(util.Log(ctx, \"starting curve %v\"), args)\n\toutput, err := util.ExecCommandHost(\"curve\", args)\n\tif err != nil {\n\t\tif strings.Contains(string(output), fmt.Sprintf(retFailFormat, retNotExist)) {\n\t\t\tklog.Warningf(util.Log(ctx, \"[curve] the file %s already deleted, ignore deleting it\"), cv.FilePath)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"failed to delete %s, err: %v, output: %v\", cv.FilePath, err, string(output))\n\t}\n\n\tklog.V(4).Infof(util.Log(ctx, \"[curve] successfully delete %v\"), cv.FilePath)\n\treturn nil\n}", "func (ec EuropeanCall) Price() float64 {\n\t// seed time for monte-carlo simulation\n\trand.Seed(time.Now().UnixNano())\n\tr := ec.R\n\tt := ec.T\n\tvol := ec.Vol\n\tdt := DailyTimeStep\n\tn := ec.N\n\tk := ec.K\n\ts1 := 0.0\n\tfor i := 0; i < n; i++ {\n\t\ts2 := ec.s0\n\t\t// run a price path\n\t\tfor j := 0; j < t*365; j++ {\n\t\t\ts2 = s2 * (1.0 + r*dt + vol*math.Sqrt(dt)*rand.NormFloat64())\n\t\t}\n\t\t// calculate the payoff\n\t\ts1 += math.Max(0.0, s2-k)\n\t}\n\t// get the average of the simulations\n\ts1 = s1 / float64(n)\n\t// discount back to present day\n\treturn s1 / math.Pow(1+r, float64(t))\n}", "func (o *PaymentMethodCash) GetType() string {\n\tif o == nil || IsNil(o.Type) {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func PrivatecaAlphaCaPoolIssuancePolicyAllowedKeyTypesEllipticCurveToProto(o *alpha.CaPoolIssuancePolicyAllowedKeyTypesEllipticCurve) *alphapb.PrivatecaAlphaCaPoolIssuancePolicyAllowedKeyTypesEllipticCurve {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &alphapb.PrivatecaAlphaCaPoolIssuancePolicyAllowedKeyTypesEllipticCurve{}\n\tp.SetSignatureAlgorithm(PrivatecaAlphaCaPoolIssuancePolicyAllowedKeyTypesEllipticCurveSignatureAlgorithmEnumToProto(o.SignatureAlgorithm))\n\treturn p\n}", "func GetChain(ticker string) (IChain, error) {\n\tswitch strings.ToUpper(ticker) {\n\tcase \"ETH\":\n\t\treturn &ETHChain{ticker: \"ETH\", chainID: 1}, nil\n\tcase \"ETC\":\n\t\treturn &ETHChain{ticker: \"ETC\", chainID: 61}, nil\n\tcase \"GOR\":\n\t\treturn &ETHChain{ticker: \"GOR\", chainID: 5}, nil\n\tcase \"RIN\":\n\t\treturn &ETHChain{ticker: \"RIN\", chainID: 4}, nil\n\tcase \"KOT\":\n\t\treturn &ETHChain{ticker: \"KOT\", chainID: 6}, nil\n\tcase \"TBNB\":\n\t\treturn &CosmosChain{ticker: \"TBNB\", chainID: 0}, nil\n\tcase \"BNB\":\n\t\treturn &CosmosChain{ticker: \"BNB\", chainID: 1}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unsupported chain\")\n\t}\n}", "func (m Message) PriceType() (*field.PriceTypeField, quickfix.MessageRejectError) {\n\tf := &field.PriceTypeField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func ecCurveScan(addr, hostname string) (grade Grade, output Output, err error) {\n\tallCurves := allCurvesIDs()\n\tcurves := make([]tls.CurveID, len(allCurves))\n\tcopy(curves, allCurves)\n\tvar supportedCurves []string\n\tfor len(curves) > 0 {\n\t\tvar curveIndex int\n\t\t_, curveIndex, _, err = sayHello(addr, hostname, allECDHECiphersIDs(), curves, tls.VersionTLS12, nil)\n\t\tif err != nil {\n\t\t\t// This case is expected, because eventually we ask only for curves the server doesn't support\n\t\t\tif err == errHelloFailed {\n\t\t\t\terr = nil\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tcurveID := curves[curveIndex]\n\t\tsupportedCurves = append(supportedCurves, tls.Curves[curveID])\n\t\tcurves = append(curves[:curveIndex], curves[curveIndex+1:]...)\n\t}\n\toutput = supportedCurves\n\tgrade = Good\n\treturn\n}", "func (cl *Client) Type() models.CspDomainTypeMutable {\n\treturn cl.csp.Type()\n}", "func (vpc Vpc) Type() ResourceType {\n\treturn TypeVPC\n}", "func (s *GCPCKMSSeal) SealType() string {\n\treturn seal.GCPCKMS\n}", "func (c *curve) Scalar() kyber.Scalar {\n\treturn mod.NewInt64(0, &c.order.V)\n}", "func kochCurve(t *terrapin.Terrapin, lung float64, liv int) {\n if liv == 0 {\n t.Forward(lung)\n return\n }\n kochCurve(t, lung, liv - 1)\n t.Left(math.Pi / 3.0)\n kochCurve(t, lung, liv - 1)\n t.Right(math.Pi - math.Pi / 3.0)\n kochCurve(t, lung, liv - 1)\n t.Left(math.Pi / 3.0)\n kochCurve(t, lung, liv - 1)\n}", "func (_Onesplitaudit *OnesplitauditCallerSession) FLAGDISABLECURVEY() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLECURVEY(&_Onesplitaudit.CallOpts)\n}", "func (m Message) GetPriceType(f *field.PriceTypeField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (curve sm2P256Curve) IsOnCurve(X, Y *big.Int) bool {\n\tvar a, x, y, y2, x3 sm2P256FieldElement\n\n\tsm2P256FromBig(&x, X)\n\tsm2P256FromBig(&y, Y)\n\n\tsm2P256Square(&x3, &x) // x3 = x ^ 2\n\tsm2P256Mul(&x3, &x3, &x) // x3 = x ^ 2 * x\n\tsm2P256Mul(&a, &curve.a, &x) // a = a * x\n\tsm2P256Add(&x3, &x3, &a)\n\tsm2P256Add(&x3, &x3, &curve.b)\n\n\tsm2P256Square(&y2, &y) // y2 = y ^ 2\n\treturn sm2P256ToBig(&x3).Cmp(sm2P256ToBig(&y2)) == 0\n}", "func (_Onesplitaudit *OnesplitauditSession) FLAGDISABLECURVEY() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLECURVEY(&_Onesplitaudit.CallOpts)\n}", "func (m Message) GetBenchmarkCurvePoint(f *field.BenchmarkCurvePointField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func PeelCentralCurve() func(x float64) model3d.Coord3D {\n\tplaneCurve := PeelCurve()\n\tzCurve := PeelHeight()\n\treturn func(x float64) model3d.Coord3D {\n\t\treturn model3d.XYZ(x, model2d.CurveEvalX(planeCurve, x), model2d.CurveEvalX(zCurve, x))\n\t}\n}", "func (r GetPublicKeyRequest) Type() RequestType {\n\treturn GetPublicKey\n}", "func EndpointTypePVoicemail() *EndpointType {\n\tv := EndpointTypeVVoicemail\n\treturn &v\n}", "func (con *EqualCondition) Type() int {\n\treturn con.kind\n}", "func (_Onesplitaudit *OnesplitauditCallerSession) FLAGDISABLECURVEUSDT() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLECURVEUSDT(&_Onesplitaudit.CallOpts)\n}", "func (m CrossOrderCancelReplaceRequest) GetStrikePrice() (v decimal.Decimal, err quickfix.MessageRejectError) {\n\tvar f field.StrikePriceField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (ec *EllipticCurve) Set(value string) error {\n\tswitch strings.ToUpper(value) {\n\tcase strEccP521, \"P-521\":\n\t\t*ec = EllipticCurveP521\n\tcase strEccP384, \"P-384\":\n\t\t*ec = EllipticCurveP384\n\tcase strEccP256, \"P-256\":\n\t\t*ec = EllipticCurveP256\n\tcase strEccED25519:\n\t\t*ec = EllipticCurveED25519\n\tdefault:\n\t\t*ec = EllipticCurveDefault\n\t}\n\n\treturn nil\n}", "func (m Message) BenchmarkCurvePoint() (*field.BenchmarkCurvePointField, quickfix.MessageRejectError) {\n\tf := &field.BenchmarkCurvePointField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (deq *DentalExpenseQuery) QueryPricetype() *PriceTypeQuery {\n\tquery := &PriceTypeQuery{config: deq.config}\n\tquery.path = func(ctx context.Context) (fromU *sql.Selector, err error) {\n\t\tif err := deq.prepareQuery(ctx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(dentalexpense.Table, dentalexpense.FieldID, deq.sqlQuery()),\n\t\t\tsqlgraph.To(pricetype.Table, pricetype.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, true, dentalexpense.PricetypeTable, dentalexpense.PricetypeColumn),\n\t\t)\n\t\tfromU = sqlgraph.SetNeighbors(deq.driver.Dialect(), step)\n\t\treturn fromU, nil\n\t}\n\treturn query\n}", "func (o *OIDC) GetType() Type {\n\treturn TypeOIDC\n}", "func (_Onesplitaudit *OnesplitauditSession) FLAGDISABLECURVEUSDT() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLECURVEUSDT(&_Onesplitaudit.CallOpts)\n}", "func ProtoToPrivatecaAlphaCaPoolIssuancePolicyAllowedKeyTypesEllipticCurve(p *alphapb.PrivatecaAlphaCaPoolIssuancePolicyAllowedKeyTypesEllipticCurve) *alpha.CaPoolIssuancePolicyAllowedKeyTypesEllipticCurve {\n\tif p == nil {\n\t\treturn nil\n\t}\n\tobj := &alpha.CaPoolIssuancePolicyAllowedKeyTypesEllipticCurve{\n\t\tSignatureAlgorithm: ProtoToPrivatecaAlphaCaPoolIssuancePolicyAllowedKeyTypesEllipticCurveSignatureAlgorithmEnum(p.GetSignatureAlgorithm()),\n\t}\n\treturn obj\n}", "func Secp256k1() elliptic.Curve {\n\treturn secp256k1\n}", "func GetECPrivateKey(raw []byte) (*ecdsa.PrivateKey, error) {\n\tdecoded, _ := pem.Decode(raw)\n\tif decoded == nil {\n\t\treturn nil, errors.New(\"Failed to decode the PEM-encoded ECDSA key\")\n\t}\n\tECPrivKey, err := x509.ParseECPrivateKey(decoded.Bytes)\n\tif err == nil {\n\t\treturn ECPrivKey, nil\n\t}\n\tkey, err2 := x509.ParsePKCS8PrivateKey(decoded.Bytes)\n\tif err2 == nil {\n\t\tswitch key.(type) {\n\t\tcase *ecdsa.PrivateKey:\n\t\t\treturn key.(*ecdsa.PrivateKey), nil\n\t\tcase *rsa.PrivateKey:\n\t\t\treturn nil, errors.New(\"Expecting EC private key but found RSA private key\")\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"Invalid private key type in PKCS#8 wrapping\")\n\t\t}\n\t}\n\treturn nil, errors.Wrap(err, \"Failed parsing EC private key\")\n}", "func ProtoToPrivatecaAlphaCaPoolIssuancePolicyAllowedKeyTypesEllipticCurveSignatureAlgorithmEnum(e alphapb.PrivatecaAlphaCaPoolIssuancePolicyAllowedKeyTypesEllipticCurveSignatureAlgorithmEnum) *alpha.CaPoolIssuancePolicyAllowedKeyTypesEllipticCurveSignatureAlgorithmEnum {\n\tif e == 0 {\n\t\treturn nil\n\t}\n\tif n, ok := alphapb.PrivatecaAlphaCaPoolIssuancePolicyAllowedKeyTypesEllipticCurveSignatureAlgorithmEnum_name[int32(e)]; ok {\n\t\te := alpha.CaPoolIssuancePolicyAllowedKeyTypesEllipticCurveSignatureAlgorithmEnum(n[len(\"PrivatecaAlphaCaPoolIssuancePolicyAllowedKeyTypesEllipticCurveSignatureAlgorithmEnum\"):])\n\t\treturn &e\n\t}\n\treturn nil\n}", "func CtperiodByEquinoxLrn(db XODB, equinoxLrn int64) (*Ctperiod, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`ctdate, ctlgasofgem, ctsgasofgem, cthgasofgem, ctlelecofgem, ctselecofgem, cthelecofgem, ctle7ofgem, ctse7ofgem, cthe7ofgem, ctuwgofftake, ctuweofftake, ctuwe7offtake, equinox_lrn, equinox_sec ` +\n\t\t`FROM equinox.ctperiod ` +\n\t\t`WHERE equinox_lrn = $1`\n\n\t// run query\n\tXOLog(sqlstr, equinoxLrn)\n\tc := Ctperiod{}\n\n\terr = db.QueryRow(sqlstr, equinoxLrn).Scan(&c.Ctdate, &c.Ctlgasofgem, &c.Ctsgasofgem, &c.Cthgasofgem, &c.Ctlelecofgem, &c.Ctselecofgem, &c.Cthelecofgem, &c.Ctle7ofgem, &c.Ctse7ofgem, &c.Cthe7ofgem, &c.Ctuwgofftake, &c.Ctuweofftake, &c.Ctuwe7offtake, &c.EquinoxLrn, &c.EquinoxSec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &c, nil\n}", "func (bc *baseClient) GetCodec() sdk.SDKCodec {\n\treturn bc.cdc\n}", "func (bc *baseClient) GetCodec() sdk.SDKCodec {\n\treturn bc.cdc\n}", "func (c *CurveOperations) RecoverCurveCoefficients4(cparams *ProjectiveCurveParameters, coefEq *CurveCoefficientsEquiv) {\n\tvar op = c.Params.Op\n\t// cparams.C = (4C)*1/2=2C\n\top.Mul(&cparams.C, &coefEq.C, &c.Params.HalfFp2)\n\t// cparams.A = A+2C - 2C = A\n\top.Sub(&cparams.A, &coefEq.A, &cparams.C)\n\t// cparams.C = 2C * 1/2 = C\n\top.Mul(&cparams.C, &cparams.C, &c.Params.HalfFp2)\n\treturn\n}", "func (c *CurveOperations) CalcCurveParamsEquiv4(cparams *ProjectiveCurveParameters) CurveCoefficientsEquiv {\n\tvar coefEq CurveCoefficientsEquiv\n\tvar op = c.Params.Op\n\n\top.Add(&coefEq.C, &cparams.C, &cparams.C)\n\t// A24p = A+2C\n\top.Add(&coefEq.A, &cparams.A, &coefEq.C)\n\t// C24 = 4*C\n\top.Add(&coefEq.C, &coefEq.C, &coefEq.C)\n\treturn coefEq\n}", "func CurveParamsDouble(curve *elliptic.CurveParams, x1, y1 *big.Int) (*big.Int, *big.Int)", "func New(sess *session.Session) *EC2Pricing {\n\t// use us-east-1 since pricing only has endpoints in us-east-1 and ap-south-1\n\tpricingClient := pricing.New(sess.Copy(aws.NewConfig().WithRegion(\"us-east-1\")))\n\treturn &EC2Pricing{\n\t\tODPricing: LoadODCacheOrNew(pricingClient, *sess.Config.Region, 0, \"\"),\n\t\tSpotPricing: LoadSpotCacheOrNew(ec2.New(sess), *sess.Config.Region, 0, \"\", DefaultSpotDaysBack),\n\t}\n}", "func (p *Path) Cr(cvs ...CCurve) *Path {\n\treturn p.addCmd(\"c\", cCmd{cvs: cvs})\n}", "func (deq *DentalExpenseQuery) WithPricetype(opts ...func(*PriceTypeQuery)) *DentalExpenseQuery {\n\tquery := &PriceTypeQuery{config: deq.config}\n\tfor _, opt := range opts {\n\t\topt(query)\n\t}\n\tdeq.withPricetype = query\n\treturn deq\n}", "func (op *CommitteePayRequestOperation) Type() OpType {\n\treturn TypeCommitteePayRequest\n}", "func (r *queryResolver) StorefrontCvlPrice(ctx context.Context) (*float64, error) {\n\tprice := r.storefrontService.GetQuote(1)\n\treturn &price, nil\n}", "func (c *Client) ProviderType() string {\n\treturn c.client.Driver.String()\n}", "func (m Message) GetStrikeCurrency(f *field.StrikeCurrencyField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (m Message) GetStrikeCurrency(f *field.StrikeCurrencyField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (s *SCEP) GetType() Type {\n\treturn TypeSCEP\n}", "func (s *SCEP) GetType() Type {\n\treturn TypeSCEP\n}", "func (*PAKEShareClient) Type() PAKEShareType {\n\treturn PAKEShareTypeClient\n}", "func (e *Huobi) GetTrades(stockType string) interface{} {\n\treturn nil\n}", "func NewEcdsaParty(prv *PrvKey) (*EcdsaParty, error) {\n\tpub := prv.PubKey()\n\tcurve := pub.Curve\n\tN := curve.Params().N\n\n\t// Paillier key pair.\n\tencpub, encprv, err := paillier.GenerateKeyPair(bitlen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Homomorphic Encryption of party pk.\n\tencpk, err := encpub.Encrypt(prv.D)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &EcdsaParty{\n\t\tN: N,\n\t\tprv: prv,\n\t\tpub: pub,\n\t\tcurve: curve,\n\t\tencpub: encpub,\n\t\tencprv: encprv,\n\t\tencpk: encpk,\n\t}, nil\n}", "func (m Message) GetQuoteCancelType(f *field.QuoteCancelTypeField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func generateKeyPair(algo string, ecCurve string) (privateKey interface{}, publicKey interface{}, err error) {\n\n // Make them case-insensitive\n switch strings.ToUpper(algo) {\n // If RSA, generate a pair of RSA keys\n case \"RSA\":\n // rsa.GenerateKey(): https://golang.org/pkg/crypto/rsa/#GenerateKey\n // Return value is of type *rsa.PrivateKey\n privateKey, err = rsa.GenerateKey(rand.Reader, 2048) // by default create a 2048 bit key\n\n // If ECDSA, use a provided curve\n case \"ECDSA\":\n // First check if ecCurve is provided\n if ecCurve == \"\" {\n return nil, nil, errors.New(\"ECDSA needs a curve\")\n }\n // Then generate the key based on the curve\n // Curves: https://golang.org/pkg/crypto/elliptic/#Curve\n // ecdsa.GenerateKey(): https://golang.org/pkg/crypto/ecdsa/#GenerateKey\n // Return value is of type *ecdsa.PrivateKey\n switch strings.ToUpper(ecCurve) {\n case \"P224\":\n privateKey, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)\n case \"P256\":\n privateKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n case \"P384\":\n \tprivateKey, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)\n case \"P521\":\n \tprivateKey, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)\n\n // If the curve is invalid\n default:\n return nil, nil, errors.New(\"Unrecognized curve, valid values are P224, P256, P384 and P521\")\n }\n\n // If neither RSA nor ECDSA return an error\n default:\n return nil, nil, errors.New(\"Unrecognized algorithm, valid options are RSA and ECDSA\")\n }\n\n // If we get here, then input parameters have been valid\n // Check if key generation has been successful by checking err\n if err != nil {\n return nil, nil, err\n }\n\n // Exporting the public key (needed later)\n switch tempPrivKey:= privateKey.(type) {\n case *rsa.PrivateKey:\n publicKey = &tempPrivKey.PublicKey\n case *ecdsa.PrivateKey:\n publicKey = &tempPrivKey.PublicKey\n }\n\n return privateKey, publicKey, err // or just return\n}", "func S256() *Curve {\n\tinitonce.Do(initAll)\n\treturn secp256k1\n}", "func (m CrossOrderCancelReplaceRequest) GetPrice() (v decimal.Decimal, err quickfix.MessageRejectError) {\n\tvar f field.PriceField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (img Image) GetCloudType() CloudType {\n\treturn img.CloudType\n}", "func (c *Curve) NewPoint(x, y float64) (CurvePoint, error) {\n\n\tvar point CurvePoint\n\n\tif !c.IsPointOnCurve(x, y) {\n\t\terr := fmt.Errorf(\"Point (%f, %f) is not on y^2 = x^3 + %fx + %f\", x, y, c.a, c.b)\n\t\treturn point, err\n\t}\n\n\tpoint.x = x\n\tpoint.y = y\n\tpoint.order = -1\n\tpoint.curve = c\n\n\treturn point, nil\n}", "func (TradeCondition) Edges() []ent.Edge {\n\treturn []ent.Edge{\n\t\tedge.From(\"record\", TradeRecord.Type).Ref(\"conditions\"),\n\t}\n}" ]
[ "0.637573", "0.62552565", "0.602968", "0.58757263", "0.5873665", "0.5735538", "0.5681037", "0.56702095", "0.54787964", "0.5441163", "0.5343881", "0.53248847", "0.5061041", "0.49801546", "0.49398685", "0.49108317", "0.477204", "0.4748864", "0.47185302", "0.47031447", "0.46613726", "0.46555611", "0.46381432", "0.46128365", "0.4609475", "0.452934", "0.45121676", "0.44782054", "0.44626227", "0.4441507", "0.441542", "0.4367836", "0.43361408", "0.43049887", "0.42877924", "0.42431772", "0.42181724", "0.4165218", "0.41430867", "0.4127555", "0.40879387", "0.40713906", "0.40623096", "0.406154", "0.4053849", "0.40415123", "0.40237406", "0.40219784", "0.4021742", "0.4006638", "0.39778528", "0.39737156", "0.39614433", "0.3951458", "0.39505893", "0.3948907", "0.39364484", "0.39302558", "0.39206782", "0.39071473", "0.39058068", "0.38968974", "0.38945627", "0.38940364", "0.38905972", "0.38898954", "0.38868856", "0.38862413", "0.3870185", "0.38478562", "0.38311994", "0.3818087", "0.38062456", "0.38019145", "0.37948278", "0.37912843", "0.37912843", "0.37893382", "0.37888137", "0.37872168", "0.37784722", "0.37765676", "0.3772572", "0.37723118", "0.37698707", "0.3763795", "0.37621176", "0.37621176", "0.37605432", "0.37605432", "0.37582287", "0.3755623", "0.37537384", "0.37513548", "0.37469524", "0.37462533", "0.37455672", "0.37406206", "0.3734194", "0.3733175" ]
0.5999522
3
Implements the json.Marshaler interface and JSON encodes the Jwk
func (jwk *Jwk) MarshalJSON() (data []byte, err error) { // Remove any potentionally conflicting claims from the JWK's additional members delete(jwk.AdditionalMembers, "kty") delete(jwk.AdditionalMembers, "kid") delete(jwk.AdditionalMembers, "alg") delete(jwk.AdditionalMembers, "use") delete(jwk.AdditionalMembers, "key_ops") delete(jwk.AdditionalMembers, "crv") delete(jwk.AdditionalMembers, "x") delete(jwk.AdditionalMembers, "y") delete(jwk.AdditionalMembers, "d") delete(jwk.AdditionalMembers, "n") delete(jwk.AdditionalMembers, "p") delete(jwk.AdditionalMembers, "q") delete(jwk.AdditionalMembers, "dp") delete(jwk.AdditionalMembers, "dq") delete(jwk.AdditionalMembers, "qi") delete(jwk.AdditionalMembers, "e") delete(jwk.AdditionalMembers, "oth") delete(jwk.AdditionalMembers, "k") // There are additional claims, individually marshal each member obj := make(map[string]*json.RawMessage, len(jwk.AdditionalMembers)+10) if bytes, err := json.Marshal(jwk.Type); err == nil { rm := json.RawMessage(bytes) obj["kty"] = &rm } else { return nil, err } if len(jwk.Id) > 0 { if bytes, err := json.Marshal(jwk.Id); err == nil { rm := json.RawMessage(bytes) obj["kid"] = &rm } else { return nil, err } } if len(jwk.Algorithm) > 0 { if bytes, err := json.Marshal(jwk.Algorithm); err == nil { rm := json.RawMessage(bytes) obj["alg"] = &rm } else { return nil, err } } if len(jwk.Use) > 0 { if bytes, err := json.Marshal(jwk.Use); err == nil { rm := json.RawMessage(bytes) obj["use"] = &rm } else { return nil, err } } if len(jwk.Operations) > 0 { if bytes, err := json.Marshal(jwk.Operations); err == nil { rm := json.RawMessage(bytes) obj["key_ops"] = &rm } else { return nil, err } } switch jwk.Type { case KeyTypeEC: { if jwk.Curve != nil { jwk.Curve.Params() p := jwk.Curve.Params() if bytes, err := json.Marshal(p.Name); err == nil { rm := json.RawMessage(bytes) obj["crv"] = &rm } else { return nil, err } } if jwk.X != nil { b64u := &Base64UrlUInt{UInt: jwk.X} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["x"] = &rm } else { return nil, err } } if jwk.Y != nil { b64u := &Base64UrlUInt{UInt: jwk.Y} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["y"] = &rm } else { return nil, err } } if jwk.D != nil { b64u := &Base64UrlUInt{UInt: jwk.D} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["d"] = &rm } else { return nil, err } } } case KeyTypeRSA: { if jwk.D != nil { b64u := &Base64UrlUInt{UInt: jwk.D} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["d"] = &rm } else { return nil, err } } if jwk.N != nil { b64u := &Base64UrlUInt{UInt: jwk.N} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["n"] = &rm } else { return nil, err } } if jwk.P != nil { b64u := &Base64UrlUInt{UInt: jwk.P} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["p"] = &rm } else { return nil, err } } if jwk.Q != nil { b64u := &Base64UrlUInt{UInt: jwk.Q} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["q"] = &rm } else { return nil, err } } if jwk.Dp != nil { b64u := &Base64UrlUInt{UInt: jwk.Dp} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["dp"] = &rm } else { return nil, err } } if jwk.Dq != nil { b64u := &Base64UrlUInt{UInt: jwk.Dq} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["dq"] = &rm } else { return nil, err } } if jwk.Qi != nil { b64u := &Base64UrlUInt{UInt: jwk.Qi} if bytes, err := json.Marshal(b64u); err == nil { rm := json.RawMessage(bytes) obj["qi"] = &rm } else { return nil, err } } if jwk.E >= 0 { b64u := &Base64UrlUInt{UInt: big.NewInt(int64(jwk.E))} if bytes, err := json.Marshal(&b64u); err == nil { rm := json.RawMessage(bytes) obj["e"] = &rm } else { return nil, err } } if len(jwk.OtherPrimes) > 0 { tempOthPrimes := make([]jwkOthPrimeJSON, len(jwk.OtherPrimes)) for i, v := range jwk.OtherPrimes { tempOthPrimes[i].Coeff = &Base64UrlUInt{UInt: v.Coeff} tempOthPrimes[i].Exp = &Base64UrlUInt{UInt: v.Exp} tempOthPrimes[i].R = &Base64UrlUInt{UInt: v.R} } if bytes, err := json.Marshal(tempOthPrimes); err == nil { rm := json.RawMessage(bytes) obj["oth"] = &rm } else { return nil, err } } } case KeyTypeOct: { if len(jwk.KeyValue) > 0 { b64o := &Base64UrlOctets{Octets: jwk.KeyValue} if bytes, err := json.Marshal(b64o); err == nil { rm := json.RawMessage(bytes) obj["k"] = &rm } else { return nil, err } } } } //Iterate through remaing members and add to json rawMessage for k, v := range jwk.AdditionalMembers { if bytes, err := json.Marshal(v); err == nil { rm := json.RawMessage(bytes) obj[k] = &rm } else { return nil, err } } // Marshal obj return json.Marshal(obj) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (j *JWK) MarshalJSON() ([]byte, error) {\n\tif isSecp256k1(j.Kty, j.Crv) {\n\t\treturn marshalSecp256k1(j)\n\t}\n\n\treturn (&j.JSONWebKey).MarshalJSON()\n}", "func JSONEncoder() Encoder { return jsonEncoder }", "func (m KeyPair) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 2)\n\n\taO0, err := swag.WriteJSON(m.Resource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\tvar dataAO1 struct {\n\t\tGroup *Group `json:\"group,omitempty\"`\n\n\t\tPrivateKey string `json:\"privateKey,omitempty\"`\n\n\t\tPublicKey string `json:\"publicKey,omitempty\"`\n\t}\n\n\tdataAO1.Group = m.Group\n\n\tdataAO1.PrivateKey = m.PrivateKey\n\n\tdataAO1.PublicKey = m.PublicKey\n\n\tjsonDataAO1, errAO1 := swag.WriteJSON(dataAO1)\n\tif errAO1 != nil {\n\t\treturn nil, errAO1\n\t}\n\t_parts = append(_parts, jsonDataAO1)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}", "func (k *Key) MarshalJSON() ([]byte, error) {\n\treturn []byte(`\"` + k.Encode() + `\"`), nil\n}", "func (j *jws) Serialize(key interface{}) ([]byte, error) {\n\tif j.isJWT {\n\t\treturn j.Compact(key)\n\t}\n\treturn nil, ErrIsNotJWT\n}", "func Marshal(v Marshaler) ([]byte, error) {\n\tw := jwriter.Writer{}\n\tv.MarshalEasyJSON(&w)\n\treturn w.BuildBytes()\n}", "func (j JSON) Encode(w io.Writer) error {\n\tdata, err := json.Marshal(j.V)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstr := String(string(data))\n\treturn str.Encode(w)\n}", "func EncodeJSON(w io.Writer, i *Iterator) error {\n\tr := make(Record)\n\n\t// Open paren.\n\tif _, err := w.Write([]byte{'['}); err != nil {\n\t\treturn err\n\t}\n\n\tvar c int\n\tenc := json.NewEncoder(w)\n\n\tdelim := []byte{',', '\\n'}\n\n\tfor i.Next() {\n\t\tif c > 0 {\n\t\t\tif _, err := w.Write(delim); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tc++\n\n\t\tif err := i.Scan(r); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := enc.Encode(r); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Close paren.\n\tif _, err := w.Write([]byte{']'}); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (v JwtData) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels16(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (handler Handler) EncodeJSON(v interface{}) (b []byte, err error) {\n\n\t//if(w.Get(\"pretty\",\"false\")==\"true\"){\n\tb, err = json.MarshalIndent(v, \"\", \" \")\n\t//}else{\n\t//\tb, err = json.Marshal(v)\n\t//}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func (j *LuaKey) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (rec JSONLogRec) MarshalJSONObject(enc *gojay.Encoder) {\n\tif !rec.DisableTimestamp {\n\t\ttimestampFmt := rec.TimestampFormat\n\t\tif timestampFmt == \"\" {\n\t\t\ttimestampFmt = logr.DefTimestampFormat\n\t\t}\n\t\ttime := rec.Time()\n\t\tenc.AddTimeKey(rec.KeyTimestamp, &time, timestampFmt)\n\t}\n\tif !rec.DisableLevel {\n\t\tenc.AddStringKey(rec.KeyLevel, rec.Level().Name)\n\t}\n\tif !rec.DisableMsg {\n\t\tenc.AddStringKey(rec.KeyMsg, rec.Msg())\n\t}\n\tif !rec.DisableContext {\n\t\tctxFields := rec.sorter(rec.Fields())\n\t\tif rec.KeyContextFields != \"\" {\n\t\t\tenc.AddObjectKey(rec.KeyContextFields, jsonFields(ctxFields))\n\t\t} else {\n\t\t\tif len(ctxFields) > 0 {\n\t\t\t\tfor _, cf := range ctxFields {\n\t\t\t\t\tkey := rec.prefixCollision(cf.Key)\n\t\t\t\t\tencodeField(enc, key, cf.Val)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif rec.stacktrace && !rec.DisableStacktrace {\n\t\tframes := rec.StackFrames()\n\t\tif len(frames) > 0 {\n\t\t\tenc.AddArrayKey(rec.KeyStacktrace, stackFrames(frames))\n\t\t}\n\t}\n\n}", "func starlarkJSON(out *bytes.Buffer, v starlark.Value) error {\n\tswitch v := v.(type) {\n\tcase starlark.NoneType:\n\t\tout.WriteString(\"null\")\n\tcase starlark.Bool:\n\t\tfmt.Fprintf(out, \"%t\", v)\n\tcase starlark.Int:\n\t\tdata, err := json.Marshal(v.BigInt())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tout.Write(data)\n\tcase starlark.Float:\n\t\tdata, err := json.Marshal(float64(v))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tout.Write(data)\n\tcase starlark.String:\n\t\t// we have to use a json Encoder to disable noisy html\n\t\t// escaping. But the encoder appends a final \\n so we\n\t\t// also should remove it.\n\t\tdata := &bytes.Buffer{}\n\t\te := json.NewEncoder(data)\n\t\te.SetEscapeHTML(false)\n\t\tif err := e.Encode(string(v)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// remove final \\n introduced by the encoder\n\t\tout.Write(bytes.TrimSuffix(data.Bytes(), []byte(\"\\n\")))\n\tcase starlark.Indexable: // Tuple, List\n\t\tout.WriteByte('[')\n\t\tfor i, n := 0, starlark.Len(v); i < n; i++ {\n\t\t\tif i > 0 {\n\t\t\t\tout.WriteString(\", \")\n\t\t\t}\n\t\t\tif err := starlarkJSON(out, v.Index(i)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tout.WriteByte(']')\n\tcase *starlark.Dict:\n\t\tout.WriteByte('{')\n\t\tfor i, item := range v.Items() {\n\t\t\tif i > 0 {\n\t\t\t\tout.WriteString(\", \")\n\t\t\t}\n\t\t\tif _, ok := item[0].(starlark.String); !ok {\n\t\t\t\treturn fmt.Errorf(\"cannot convert non-string dict key to JSON\")\n\t\t\t}\n\t\t\tif err := starlarkJSON(out, item[0]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tout.WriteString(\": \")\n\t\t\tif err := starlarkJSON(out, item[1]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tout.WriteByte('}')\n\n\tdefault:\n\t\treturn fmt.Errorf(\"cannot convert starlark type %q to JSON\", v.Type())\n\t}\n\treturn nil\n}", "func (v Signature) EncodeJSON(b []byte) []byte {\n\tb = append(b, `{\"hex_bytes\":`...)\n\tb = json.AppendHexBytes(b, v.Bytes)\n\tb = append(b, `,\"public_key\":`...)\n\tb = v.PublicKey.EncodeJSON(b)\n\tb = append(b, ',', '\"', 's', 'i', 'g', 'n', 'a', 't', 'u', 'r', 'e', '_', 't', 'y', 'p', 'e', '\"', ':')\n\tb = json.AppendString(b, string(v.SignatureType))\n\tb = append(b, ',', '\"', 's', 'i', 'g', 'n', 'i', 'n', 'g', '_', 'p', 'a', 'y', 'l', 'o', 'a', 'd', '\"', ':')\n\tb = v.SigningPayload.EncodeJSON(b)\n\treturn append(b, \"}\"...)\n}", "func (k Kitten) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"eatsMiceYet\", k.EatsMiceYet)\n\tpopulate(objectMap, \"hisses\", k.Hisses)\n\tpopulate(objectMap, \"likesMilk\", k.LikesMilk)\n\tpopulate(objectMap, \"meows\", k.Meows)\n\tpopulate(objectMap, \"name\", k.Name)\n\treturn json.Marshal(objectMap)\n}", "func (a APIKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"connectionString\", a.ConnectionString)\n\tpopulate(objectMap, \"id\", a.ID)\n\tpopulateTimeRFC3339(objectMap, \"lastModified\", a.LastModified)\n\tpopulate(objectMap, \"name\", a.Name)\n\tpopulate(objectMap, \"readOnly\", a.ReadOnly)\n\tpopulate(objectMap, \"value\", a.Value)\n\treturn json.Marshal(objectMap)\n}", "func (f genHelperEncoder) EncJSONMarshal(iv jsonMarshaler) {\n\tbs, fnerr := iv.MarshalJSON()\n\tf.e.marshalAsis(bs, fnerr)\n}", "func (kv KV) MarshalJSON() ([]byte, error) {\n\tbuffer := bytes.NewBufferString(\"{\")\n\n\tjsonKey, err := json.Marshal(kv.Key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjsonValue, err := json.Marshal(kv.Value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuffer.Write(jsonKey)\n\tbuffer.WriteByte(58)\n\tbuffer.Write(jsonValue)\n\n\tbuffer.WriteString(\"}\")\n\treturn buffer.Bytes(), nil\n}", "func (v Join) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer21(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (gr gelfRecord) MarshalJSONObject(enc *gojay.Encoder) {\n\tenc.AddStringKey(GelfVersionKey, GelfVersion)\n\tenc.AddStringKey(GelfHostKey, gr.getHostname())\n\tenc.AddStringKey(GelfShortKey, gr.Msg())\n\n\tif gr.level.Stacktrace {\n\t\tframes := gr.StackFrames()\n\t\tif len(frames) != 0 {\n\t\t\tvar sbuf strings.Builder\n\t\t\tfor _, frame := range frames {\n\t\t\t\tfmt.Fprintf(&sbuf, \"%s\\n %s:%d\\n\", frame.Function, frame.File, frame.Line)\n\t\t\t}\n\t\t\tenc.AddStringKey(GelfFullKey, sbuf.String())\n\t\t}\n\t}\n\n\tsecs := float64(gr.Time().UTC().Unix())\n\tmillis := float64(gr.Time().Nanosecond() / 1000000)\n\tts := secs + (millis / 1000)\n\tenc.AddFloat64Key(GelfTimestampKey, ts)\n\n\tenc.AddUint32Key(GelfLevelKey, uint32(gr.level.ID))\n\n\tvar fields []logr.Field\n\tif gr.EnableCaller {\n\t\tcaller := logr.Field{\n\t\t\tKey: \"_caller\",\n\t\t\tType: logr.StringType,\n\t\t\tString: gr.LogRec.Caller(),\n\t\t}\n\t\tfields = append(fields, caller)\n\t}\n\n\tfields = append(fields, gr.Fields()...)\n\tif gr.sorter != nil {\n\t\tfields = gr.sorter(fields)\n\t}\n\n\tif len(fields) > 0 {\n\t\tfor _, field := range fields {\n\t\t\tif !strings.HasPrefix(\"_\", field.Key) {\n\t\t\t\tfield.Key = \"_\" + field.Key\n\t\t\t}\n\t\t\tif err := encodeField(enc, field); err != nil {\n\t\t\t\tenc.AddStringKey(field.Key, fmt.Sprintf(\"<error encoding field: %v>\", err))\n\t\t\t}\n\t\t}\n\t}\n}", "func (j *LuaKey) MarshalJSONBuf(buf fflib.EncodingBuffer) error {\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn nil\n\t}\n\tvar err error\n\tvar obj []byte\n\t_ = obj\n\t_ = err\n\tbuf.WriteString(`{\"key\":`)\n\tif j.Key != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.Key {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\t\t\t/* Interface types must use runtime reflection. type=interface {} kind=interface */\n\t\t\terr = buf.Encode(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteByte('}')\n\treturn nil\n}", "func (q QnAMakerEndpointKeysRequestBody) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"authkey\", q.Authkey)\n\tpopulate(objectMap, \"hostname\", q.Hostname)\n\treturn json.Marshal(objectMap)\n}", "func (o ApiKey) MarshalJSON() ([]byte, error) {\n\ttoSerialize := map[string]interface{}{}\n\tif o.UnparsedObject != nil {\n\t\treturn json.Marshal(o.UnparsedObject)\n\t}\n\tif o.Created != nil {\n\t\ttoSerialize[\"created\"] = o.Created\n\t}\n\tif o.CreatedBy != nil {\n\t\ttoSerialize[\"created_by\"] = o.CreatedBy\n\t}\n\tif o.Key != nil {\n\t\ttoSerialize[\"key\"] = o.Key\n\t}\n\tif o.Name != nil {\n\t\ttoSerialize[\"name\"] = o.Name\n\t}\n\n\tfor key, value := range o.AdditionalProperties {\n\t\ttoSerialize[key] = value\n\t}\n\treturn json.Marshal(toSerialize)\n}", "func (k *TimeKey) MarshalJSON() ([]byte, error) {\n\treturn []byte(`\"` + k.String() + `\"`), nil\n}", "func writeJSON(buf *bytes.Buffer, v interface{}, keyName string) error {\n\tenc, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, `failed to encode '%s'`, keyName)\n\t}\n\tbuf.Write(enc)\n\n\treturn nil\n}", "func (k Key) MarshalJSON() ([]byte, error) {\n\t// Marshal the Key property only\n\treturn json.Marshal(k.Key)\n}", "func Marshal(v Marshaler) ([]byte, error) {\n\tif isNilInterface(v) {\n\t\treturn nullBytes, nil\n\t}\n\n\tw := jwriter.Writer{}\n\tv.MarshalTinyJSON(&w)\n\treturn w.BuildBytes()\n}", "func (s StreamingPolicyContentKeys) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"defaultKey\", s.DefaultKey)\n\tpopulate(objectMap, \"keyToTrackMappings\", s.KeyToTrackMappings)\n\treturn json.Marshal(objectMap)\n}", "func (v Header) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson171edd05EncodeGithubComEmirmuminogluJwt(w, v)\n}", "func (v PublicKey) EncodeJSON(b []byte) []byte {\n\tb = append(b, `{\"hex_bytes\":`...)\n\tb = json.AppendHexBytes(b, v.Bytes)\n\tb = append(b, `,\"curve_type\":`...)\n\tb = json.AppendString(b, string(v.CurveType))\n\treturn append(b, \"}\"...)\n}", "func (k *KeyStore) serialize(w io.Writer) error {\n\tenc := json.NewEncoder(w)\n\treturn enc.Encode(k.Values)\n}", "func (v publicKey) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson94b2531bEncodeGitRonaksoftComRiverWebWasmConnection(w, v)\n}", "func (v Bucket) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser27(w, v)\n}", "func (v JwtData) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels16(w, v)\n}", "func jsonEnc(in T) ([]byte, error) {\n\treturn jsonx.Marshal(in)\n}", "func (w Watcher) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", w.Etag)\n\tpopulate(objectMap, \"id\", w.ID)\n\tpopulate(objectMap, \"location\", w.Location)\n\tpopulate(objectMap, \"name\", w.Name)\n\tpopulate(objectMap, \"properties\", w.Properties)\n\tpopulate(objectMap, \"tags\", w.Tags)\n\tpopulate(objectMap, \"type\", w.Type)\n\treturn json.Marshal(objectMap)\n}", "func (myTagKey TagKey) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(map[string]interface{}{\n\t\t\"ID\": myTagKey.IDvar,\n\t\t\"KeyValue\": myTagKey.KeyValuevar,\n\t})\n}", "func (v handshakeRequest) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson2802b09fEncodeGithubComPhilippseithSignalr4(w, v)\n}", "func (sl Slice) MarshalJSON() ([]byte, error) {\n\tnk := len(sl)\n\tb := make([]byte, 0, nk*100+20)\n\tif nk == 0 {\n\t\tb = append(b, []byte(\"null\")...)\n\t\treturn b, nil\n\t}\n\tnstr := fmt.Sprintf(\"[{\\\"n\\\":%d,\", nk)\n\tb = append(b, []byte(nstr)...)\n\tfor i, kid := range sl {\n\t\t// fmt.Printf(\"json out of %v\\n\", kid.PathUnique())\n\t\tknm := kit.Types.TypeName(reflect.TypeOf(kid).Elem())\n\t\ttstr := fmt.Sprintf(\"\\\"type\\\":\\\"%v\\\", \\\"name\\\": \\\"%v\\\"\", knm, kid.UniqueName()) // todo: escape names!\n\t\tb = append(b, []byte(tstr)...)\n\t\tif i < nk-1 {\n\t\t\tb = append(b, []byte(\",\")...)\n\t\t}\n\t}\n\tb = append(b, []byte(\"},\")...)\n\tfor i, kid := range sl {\n\t\tvar err error\n\t\tvar kb []byte\n\t\tkb, err = json.Marshal(kid)\n\t\tif err == nil {\n\t\t\tb = append(b, []byte(\"{\")...)\n\t\t\tb = append(b, kb[1:len(kb)-1]...)\n\t\t\tb = append(b, []byte(\"}\")...)\n\t\t\tif i < nk-1 {\n\t\t\t\tb = append(b, []byte(\",\")...)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Printf(\"error doing json.Marshall from kid: %v\\n\", kid.PathUnique())\n\t\t\tlog.Println(err)\n\t\t\tfmt.Printf(\"output to point of error: %v\\n\", string(b))\n\t\t}\n\t}\n\tb = append(b, []byte(\"]\")...)\n\t// fmt.Printf(\"json out: %v\\n\", string(b))\n\treturn b, nil\n}", "func JsonMarshal(t interface{}) ([]byte, error) {\n\tbuffer := &bytes.Buffer{}\n\tenc := json.NewEncoder(buffer)\n\tenc.SetEscapeHTML(false)\n\terr := enc.Encode(t)\n\treturn buffer.Bytes(), err\n}", "func (v ServerKeys) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson94b2531bEncodeGitRonaksoftComRiverWebWasmConnection2(w, v)\n}", "func (jz JSONGzipEncoding) Marshal(v interface{}) ([]byte, error) {\n\tbuf, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// var bufSizeBefore = len(buf)\n\n\tbuf, err = GzipEncode(buf)\n\t// coloredoutput.Infof(\"gzip_json_compress_ratio=%d/%d=%.2f\",\n\t// bufSizeBefore, len(buf), float64(bufSizeBefore)/float64(len(buf)))\n\treturn buf, err\n}", "func (v FormDataMQ) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonB83d7b77EncodeGoplaygroundMyjson(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func EncodeJson(v interface{}) ([]byte, error) {\n\treturn json.ConfigCompatibleWithStandardLibrary.Marshal(v)\n}", "func (v Stash) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncodeDrhyuComIndexerModels(w, v)\n}", "func (key Key) MarshalJSON() ([]byte, error) {\n\tif !key.IsValid() {\n\t\treturn nil, fmt.Errorf(\"unknown key: %v\", key)\n\t}\n\n\treturn json.Marshal(string(key))\n}", "func JSON(data interface{}, args ...interface{}) string {\n\tw := Writer{\n\t\tOptions: ojg.DefaultOptions,\n\t\tWidth: 80,\n\t\tMaxDepth: 3,\n\t\tSEN: false,\n\t}\n\tw.config(args)\n\tb, _ := w.encode(data)\n\n\treturn string(b)\n}", "func (s StreamingPolicyContentKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"label\", s.Label)\n\tpopulate(objectMap, \"policyName\", s.PolicyName)\n\tpopulate(objectMap, \"tracks\", s.Tracks)\n\treturn json.Marshal(objectMap)\n}", "func TestEncode(t *testing.T) {\n\tvar err error\n\tassert := assert.New(t)\n\n\tauthor := bio{\n\t\tFirstname: \"Bastien\",\n\t\tLastname: \"Gysler\",\n\t\tHobbies: []string{\"DJ\", \"Running\", \"Tennis\"},\n\t\tMisc: map[string]string{\n\t\t\t\"lineSeparator\": \"\\u2028\",\n\t\t\t\"Nationality\": \"Swiss\",\n\t\t\t\"City\": \"Zürich\",\n\t\t\t\"foo\": \"\",\n\t\t\t\"bar\": \"\\\"quoted text\\\"\",\n\t\t\t\"esc\": \"escaped \\\\ sanitized\",\n\t\t\t\"r\": \"\\r return line\",\n\t\t\t\"default\": \"< >\",\n\t\t\t\"runeError\": \"\\uFFFD\",\n\t\t},\n\t}\n\n\t// Build document\n\troot := &Node{}\n\troot.AddChild(\"firstname\", &Node{\n\t\tData: author.Firstname,\n\t})\n\troot.AddChild(\"lastname\", &Node{\n\t\tData: author.Lastname,\n\t})\n\n\tfor _, h := range author.Hobbies {\n\t\troot.AddChild(\"hobbies\", &Node{\n\t\t\tData: h,\n\t\t})\n\t}\n\n\tmisc := &Node{}\n\tfor k, v := range author.Misc {\n\t\tmisc.AddChild(k, &Node{\n\t\t\tData: v,\n\t\t})\n\t}\n\troot.AddChild(\"misc\", misc)\n\tvar enc *Encoder\n\n\t// Convert to JSON string\n\tbuf := new(bytes.Buffer)\n\tenc = NewEncoder(buf)\n\n\terr = enc.Encode(nil)\n\tassert.NoError(err)\n\n\tenc.SetAttributePrefix(\"test\")\n\tenc.SetContentPrefix(\"test2\")\n\t// err = enc.EncodeWithCustomPrefixes(root, \"test3\", \"test4\")\n\tenc.CustomPrefixesOption(\"test3\", \"test4\")\n\terr = enc.Encode(root)\n\tassert.NoError(err)\n\n\terr = enc.Encode(root)\n\tassert.NoError(err)\n\n\t// Build SimpleJSON\n\tsj, err := sj.NewJson(buf.Bytes())\n\tres, err := sj.Map()\n\tassert.NoError(err)\n\n\t// Assertions\n\tassert.Equal(author.Firstname, res[\"firstname\"])\n\tassert.Equal(author.Lastname, res[\"lastname\"])\n\n\tresHobbies, err := sj.Get(\"hobbies\").StringArray()\n\tassert.NoError(err)\n\tassert.Equal(author.Hobbies, resHobbies)\n\n\tresMisc, err := sj.Get(\"misc\").Map()\n\tassert.NoError(err)\n\tfor k, v := range resMisc {\n\t\tassert.Equal(author.Misc[k], v)\n\t}\n\n\tenc.err = fmt.Errorf(\"Testing if error provided is returned\")\n\tassert.Error(enc.Encode(nil))\n}", "func (v ProductShrinked) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeBackendInternalModels3(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (j *Producer) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (f jsonFields) MarshalJSONObject(enc *gojay.Encoder) {\n\tfor _, ctxField := range f {\n\t\tencodeField(enc, ctxField.Key, ctxField.Val)\n\t}\n}", "func signAndEncodeJSON(w io.Writer, v interface{}, privateKey *packet.PrivateKey, config *packet.Config) error {\n\t// Get clearsign encoder.\n\tplaintext, err := clearsign.Encode(w, privateKey, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer plaintext.Close()\n\n\t// Wrap clearsign encoder with JSON encoder.\n\treturn json.NewEncoder(plaintext).Encode(v)\n}", "func (s SSHPublicKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"keyData\", s.KeyData)\n\treturn json.Marshal(objectMap)\n}", "func JsonEncode(i interface{}) string {\n\tb, err := json.Marshal(i)\n\n\tif err != nil {\n\t\tfmt.Println(\"util.getJsonStr.error\", err)\n\t\treturn \"\"\n\t}\n\n\treturn string(b)\n}", "func (a ApplicationGatewaySKU) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"capacity\", a.Capacity)\n\tpopulate(objectMap, \"name\", a.Name)\n\tpopulate(objectMap, \"tier\", a.Tier)\n\treturn json.Marshal(objectMap)\n}", "func jsonMarshal(t interface{}) ([]byte, error) {\n\tbuffer := &bytes.Buffer{}\n\tencoder := json.NewEncoder(buffer)\n\tencoder.SetEscapeHTML(false)\n\tencoder.SetIndent(\"\", \" \")\n\terr := encoder.Encode(t)\n\treturn buffer.Bytes(), err\n}", "func (obj CustomObjectKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CustomObjectKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"key-value-document\", Alias: (*Alias)(&obj)})\n}", "func encodeJSON(w io.Writer, v interface{}) (err error) {\n\tenc := json.NewEncoder(w)\n\tenc.SetEscapeHTML(false)\n\treturn enc.Encode(v)\n}", "func (k KeyUsage) MarshalJSON() ([]byte, error) {\n\tvar enc auxKeyUsage\n\tenc.Value = uint32(k)\n\tif k&KeyUsageDigitalSignature > 0 {\n\t\tenc.DigitalSignature = true\n\t}\n\tif k&KeyUsageContentCommitment > 0 {\n\t\tenc.ContentCommitment = true\n\t}\n\tif k&KeyUsageKeyEncipherment > 0 {\n\t\tenc.KeyEncipherment = true\n\t}\n\tif k&KeyUsageDataEncipherment > 0 {\n\t\tenc.DataEncipherment = true\n\t}\n\tif k&KeyUsageKeyAgreement > 0 {\n\t\tenc.KeyAgreement = true\n\t}\n\tif k&KeyUsageCertSign > 0 {\n\t\tenc.CertificateSign = true\n\t}\n\tif k&KeyUsageCRLSign > 0 {\n\t\tenc.CRLSign = true\n\t}\n\tif k&KeyUsageEncipherOnly > 0 {\n\t\tenc.EncipherOnly = true\n\t}\n\tif k&KeyUsageDecipherOnly > 0 {\n\t\tenc.DecipherOnly = true\n\t}\n\treturn json.Marshal(&enc)\n}", "func (c *JSONCodec) Marshal(v interface{}) ([]byte, error) {\n\treturn json.Marshal(v)\n}", "func (j *Producer) MarshalJSONBuf(buf fflib.EncodingBuffer) error {\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn nil\n\t}\n\tvar err error\n\tvar obj []byte\n\t_ = obj\n\t_ = err\n\tbuf.WriteString(`{ `)\n\tif len(j.ID) != 0 {\n\t\tbuf.WriteString(`\"id\":`)\n\t\tfflib.WriteJsonString(buf, string(j.ID))\n\t\tbuf.WriteByte(',')\n\t}\n\tif len(j.Name) != 0 {\n\t\tbuf.WriteString(`\"name\":`)\n\t\tfflib.WriteJsonString(buf, string(j.Name))\n\t\tbuf.WriteByte(',')\n\t}\n\tif len(j.Cat) != 0 {\n\t\tbuf.WriteString(`\"cat\":`)\n\t\tif j.Cat != nil {\n\t\t\tbuf.WriteString(`[`)\n\t\t\tfor i, v := range j.Cat {\n\t\t\t\tif i != 0 {\n\t\t\t\t\tbuf.WriteString(`,`)\n\t\t\t\t}\n\t\t\t\tfflib.WriteJsonString(buf, string(v))\n\t\t\t}\n\t\t\tbuf.WriteString(`]`)\n\t\t} else {\n\t\t\tbuf.WriteString(`null`)\n\t\t}\n\t\tbuf.WriteByte(',')\n\t}\n\tif len(j.Domain) != 0 {\n\t\tbuf.WriteString(`\"domain\":`)\n\t\tfflib.WriteJsonString(buf, string(j.Domain))\n\t\tbuf.WriteByte(',')\n\t}\n\tif j.Ext != nil {\n\t\tif true {\n\t\t\tbuf.WriteString(`\"ext\":`)\n\n\t\t\t{\n\n\t\t\t\tobj, err = j.Ext.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t\tbuf.WriteByte(',')\n\t\t}\n\t}\n\tbuf.Rewind(1)\n\tbuf.WriteByte('}')\n\treturn nil\n}", "func JSONEncode(data interface{}) string {\n\tbt, _ := json.Marshal(data)\n\treturn string(bt)\n}", "func (r RegenerateKeyParameters) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"keyName\", r.KeyName)\n\treturn json.Marshal(objectMap)\n}", "func (d DefaultKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"label\", d.Label)\n\tpopulate(objectMap, \"policyName\", d.PolicyName)\n\treturn json.Marshal(objectMap)\n}", "func (v Header) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson171edd05EncodeGithubComEmirmuminogluJwt(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (kem deprecatedKeyEntryMap) MarshalJSON() ([]byte, error) {\n\tintermediate := map[string]KeyEntry{}\n\tfor k, v := range kem {\n\t\tintermediate[strconv.Itoa(k)] = v\n\t}\n\treturn json.Marshal(&intermediate)\n}", "func (v UserJSONT) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson6afd136EncodeCourseraWeek3Perf(w, v)\n}", "func (sw SignatureWitness) MarshalJSON() ([]byte, error) {\n\tobj := struct {\n\t\tType string `json:\"type\"`\n\t\tQuorum int `json:\"quorum\"`\n\t\tKeys []keyID `json:\"keys\"`\n\t\tSigs []chainjson.HexBytes `json:\"signatures\"`\n\t}{\n\t\tType: \"signature\",\n\t\tQuorum: sw.Quorum,\n\t\tKeys: sw.Keys,\n\t\tSigs: sw.Sigs,\n\t}\n\treturn json.Marshal(obj)\n}", "func jsonMarshal(t interface{}) ([]byte, error) {\n\tvar buffer bytes.Buffer\n\tencoder := json.NewEncoder(&buffer)\n\tencoder.SetEscapeHTML(false)\n\tif err := encoder.Encode(t); err != nil {\n\t\treturn nil, err\n\t}\n\t// Prettify\n\tvar out bytes.Buffer\n\tif err := json.Indent(&out, buffer.Bytes(), \"\", \"\\t\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn out.Bytes(), nil\n}", "func (v Stash) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeDrhyuComIndexerModels(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v SigningPayload) EncodeJSON(b []byte) []byte {\n\tb = append(b, \"{\"...)\n\tif v.AccountIdentifier.Set {\n\t\tb = append(b, '\"', 'a', 'c', 'c', 'o', 'u', 'n', 't', '_', 'i', 'd', 'e', 'n', 't', 'i', 'f', 'i', 'e', 'r', '\"', ':')\n\t\tb = v.AccountIdentifier.Value.EncodeJSON(b)\n\t\tb = append(b, \",\"...)\n\t}\n\tif v.Address.Set {\n\t\tb = append(b, `\"address\":`...)\n\t\tb = json.AppendString(b, v.Address.Value)\n\t\tb = append(b, \",\"...)\n\t}\n\tb = append(b, `\"hex_bytes\":`...)\n\tb = json.AppendHexBytes(b, v.Bytes)\n\tb = append(b, \",\"...)\n\tif v.SignatureType.Set {\n\t\tb = append(b, '\"', 's', 'i', 'g', 'n', 'a', 't', 'u', 'r', 'e', '_', 't', 'y', 'p', 'e', '\"', ':')\n\t\tb = json.AppendString(b, string(v.SignatureType.Value))\n\t\tb = append(b, \",\"...)\n\t}\n\tb[len(b)-1] = '}'\n\treturn b\n}", "func Marshal(v interface{}) ([]byte, error) {\n\tif ImplementsPreJSONMarshaler(v) {\n\t\terr := v.(PreJSONMarshaler).PreMarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn json.Marshal(v)\n}", "func (v EventApplicationKeyAdd) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk20(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (m MultipleActivationKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", m.ID)\n\tpopulate(objectMap, \"location\", m.Location)\n\tpopulate(objectMap, \"name\", m.Name)\n\tpopulate(objectMap, \"properties\", m.Properties)\n\tpopulate(objectMap, \"tags\", m.Tags)\n\tpopulate(objectMap, \"type\", m.Type)\n\treturn json.Marshal(objectMap)\n}", "func (pk PublicKey) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(pk.String())\n}", "func (k KeyDelivery) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"accessControl\", k.AccessControl)\n\treturn json.Marshal(objectMap)\n}", "func (k KeyValueProperties) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"contentType\", k.ContentType)\n\tpopulate(objectMap, \"eTag\", k.ETag)\n\tpopulate(objectMap, \"key\", k.Key)\n\tpopulate(objectMap, \"label\", k.Label)\n\tpopulateTimeRFC3339(objectMap, \"lastModified\", k.LastModified)\n\tpopulate(objectMap, \"locked\", k.Locked)\n\tpopulate(objectMap, \"tags\", k.Tags)\n\tpopulate(objectMap, \"value\", k.Value)\n\treturn json.Marshal(objectMap)\n}", "func (v Bucket) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser27(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (rht *RHT) Marshal() string {\n\tmembers := rht.Members()\n\n\tsize := len(members)\n\tkeys := make([]string, 0, size)\n\tfor k := range members {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\tsb := strings.Builder{}\n\tsb.WriteString(\"{\")\n\n\tidx := 0\n\tfor _, k := range keys {\n\t\tvalue := members[k]\n\t\tsb.WriteString(fmt.Sprintf(\"\\\"%s\\\":%s\", k, value.Marshal()))\n\t\tif size-1 != idx {\n\t\t\tsb.WriteString(\",\")\n\t\t}\n\t\tidx++\n\t}\n\tsb.WriteString(\"}\")\n\n\treturn sb.String()\n}", "func (js JobSecrets) MarshalJSON() ([]byte, error) {\n\tjs.JobSecretsType = JobSecretsTypeJobSecrets\n\tobjectMap := make(map[string]interface{})\n\tif js.JobSecretsType != \"\" {\n\t\tobjectMap[\"jobSecretsType\"] = js.JobSecretsType\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (v WSRequest) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer3(w, v)\n}", "func (s SecurityDomainJSONWebKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"alg\", s.Alg)\n\tpopulate(objectMap, \"e\", s.E)\n\tpopulate(objectMap, \"key_ops\", s.KeyOps)\n\tpopulate(objectMap, \"kid\", s.Kid)\n\tpopulate(objectMap, \"kty\", s.Kty)\n\tpopulate(objectMap, \"n\", s.N)\n\tpopulate(objectMap, \"use\", s.Use)\n\tpopulate(objectMap, \"x5c\", s.X5C)\n\tpopulate(objectMap, \"x5t\", s.X5T)\n\tpopulate(objectMap, \"x5t#S256\", s.X5TS256)\n\treturn json.Marshal(objectMap)\n}", "func (a APIKeys) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"key1\", a.Key1)\n\tpopulate(objectMap, \"key2\", a.Key2)\n\treturn json.Marshal(objectMap)\n}", "func JSONMarshal(data interface{}) ([]byte, error) {\n\tvar b []byte\n\tvar err error\n\n\tb, err = json.MarshalIndent(data, \"\", \" \")\n\n\treturn b, err\n}", "func (v ServerKeys) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson94b2531bEncodeGitRonaksoftComRiverWebWasmConnection2(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (a AppSKUInfo) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", a.Name)\n\treturn json.Marshal(objectMap)\n}", "func (r *Key) marshal(c *Client) ([]byte, error) {\n\tm, err := expandKey(c, r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshalling Key: %w\", err)\n\t}\n\n\treturn json.Marshal(m)\n}", "func (om *OrderedMap) MarshalJSON() ([]byte, error) {\n\tbuffer := bytes.NewBufferString(\"{\")\n\n\tfirst := true\n\tfor idx := 0; idx < len(om.kvList); idx++ {\n\t\tif om.kvList[idx] == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !first {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\n\t\tjsonKey, err := json.Marshal(om.kvList[idx].Key)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tjsonValue, err := json.Marshal(om.kvList[idx].Value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuffer.Write(jsonKey)\n\t\tbuffer.WriteByte(58)\n\t\tbuffer.Write(jsonValue)\n\n\t\tfirst = false\n\t}\n\n\tbuffer.WriteString(\"}\")\n\treturn buffer.Bytes(), nil\n}", "func (v FormDataMQ) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonB83d7b77EncodeGoplaygroundMyjson(w, v)\n}", "func (s Sawshark) MarshalJSON() ([]byte, error) {\n\ts.Fishtype = FishtypeSawshark\n\ttype Alias Sawshark\n\treturn json.Marshal(&struct {\n\t\tAlias\n\t}{\n\t\tAlias: (Alias)(s),\n\t})\n}", "func JsonEncode(data []byte, v interface{}) error {\n\n\treturn json.Unmarshal(data, v)\n}", "func (j *JSON) Marshal(target interface{}) (output interface{}, err error) {\n\treturn jsonEncoding.Marshal(target)\n}", "func (t WKTime) MarshalJSON() ([]byte, error) {\n\treturn []byte(`\"` + t.Encode() + `\"`), nil\n}", "func (v Segment) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonB27eec76EncodeGithubComTisonetOpenrtbEasyjson6(w, v)\n}", "func (v Version) EncodeJSON(b []byte) []byte {\n\tb = append(b, \"{\"...)\n\tif len(v.Metadata) > 0 {\n\t\tb = append(b, `\"metadata\":`...)\n\t\tb = append(b, v.Metadata...)\n\t\tb = append(b, \",\"...)\n\t}\n\tif v.MiddlewareVersion.Set {\n\t\tb = append(b, '\"', 'm', 'i', 'd', 'd', 'l', 'e', 'w', 'a', 'r', 'e', '_', 'v', 'e', 'r', 's', 'i', 'o', 'n', '\"', ':')\n\t\tb = json.AppendString(b, v.MiddlewareVersion.Value)\n\t\tb = append(b, \",\"...)\n\t}\n\tb = append(b, `\"node_version\":`...)\n\tb = json.AppendString(b, v.NodeVersion)\n\tb = append(b, ',', '\"', 'r', 'o', 's', 'e', 't', 't', 'a', '_', 'v', 'e', 'r', 's', 'i', 'o', 'n', '\"', ':')\n\tb = json.AppendString(b, v.RosettaVersion)\n\treturn append(b, \"}\"...)\n}", "func (gkc *ServiceAccountKey) MarshalJSON() ([]byte, error) {\n\tfmap := make(map[string]any, 2)\n\tfmap[config.AuthorizerTypeProperty] = ServiceAccountKeyAuthorizerType\n\tfmap[\"key\"] = gkc.Key\n\treturn json.Marshal(fmap)\n}", "func (r ResourceSKU) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"kind\", r.Kind)\n\tpopulate(objectMap, \"locations\", r.Locations)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"resourceType\", r.ResourceType)\n\tpopulate(objectMap, \"restrictions\", r.Restrictions)\n\tpopulate(objectMap, \"tier\", r.Tier)\n\treturn json.Marshal(objectMap)\n}", "func (k KeyValueListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", k.NextLink)\n\tpopulate(objectMap, \"value\", k.Value)\n\treturn json.Marshal(objectMap)\n}", "func (s StreamingLocatorContentKey) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"labelReferenceInStreamingPolicy\", s.LabelReferenceInStreamingPolicy)\n\tpopulate(objectMap, \"policyName\", s.PolicyName)\n\tpopulate(objectMap, \"tracks\", s.Tracks)\n\tpopulate(objectMap, \"type\", s.Type)\n\tpopulate(objectMap, \"value\", s.Value)\n\treturn json.Marshal(objectMap)\n}" ]
[ "0.70164174", "0.6944281", "0.68375885", "0.67024183", "0.6682063", "0.6647078", "0.6481345", "0.647343", "0.64550096", "0.64235896", "0.64145947", "0.637341", "0.6367879", "0.6362876", "0.6359962", "0.63448554", "0.63441277", "0.632238", "0.6312419", "0.62963176", "0.62856406", "0.6265631", "0.6261716", "0.6256516", "0.62548137", "0.6252782", "0.62503266", "0.62421584", "0.6231277", "0.622927", "0.6218251", "0.6206533", "0.62043023", "0.62036794", "0.6196564", "0.6194289", "0.6188456", "0.61871123", "0.6157374", "0.6153328", "0.6150722", "0.6148101", "0.61415404", "0.6137081", "0.61349934", "0.6133089", "0.6127477", "0.61269635", "0.6121031", "0.6115432", "0.61115223", "0.6105062", "0.6103365", "0.61001205", "0.6099189", "0.6098707", "0.6098346", "0.6093518", "0.6092899", "0.6089062", "0.6086912", "0.6084805", "0.6078709", "0.60748154", "0.60713893", "0.60708433", "0.6068613", "0.60673255", "0.6065589", "0.60617447", "0.6054318", "0.60526913", "0.60502553", "0.60501903", "0.60453075", "0.60439044", "0.6041402", "0.6040906", "0.603292", "0.60301286", "0.6028616", "0.6025921", "0.6021722", "0.60215145", "0.60201085", "0.6014257", "0.60117614", "0.60076123", "0.60031813", "0.6003158", "0.60024685", "0.600238", "0.6000753", "0.59971136", "0.5993591", "0.59926677", "0.5991281", "0.5988219", "0.5985796", "0.59833777" ]
0.76333815
0
Validate checkes the JWK object to verify the parameter set represent a valid JWK. If jwk is valid a nil error will be returned. If a JWK is invalid an error will be returned describing the values that causes the validation to fail.
func (jwk *Jwk) Validate() error { // If the alg parameter is set, make sure it matches the set JWK Type if len(jwk.Algorithm) > 0 { algKeyType := GetKeyType(jwk.Algorithm) if algKeyType != jwk.Type { fmt.Errorf("Jwk Type (kty=%v) doesn't match the algorithm key type (%v)", jwk.Type, algKeyType) } } switch jwk.Type { case KeyTypeRSA: if err := jwk.validateRSAParams(); err != nil { return err } case KeyTypeEC: if err := jwk.validateECParams(); err != nil { return err } case KeyTypeOct: if err := jwk.validateOctParams(); err != nil { return err } default: return errors.New("KeyType (kty) must be EC, RSA or Oct") } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (jwk *Jwk) validateECParams() error {\n\tif jwk.X == nil {\n\t\treturn errors.New(\"EC Required Param (X) is nil\")\n\t}\n\tif jwk.Y == nil {\n\t\treturn errors.New(\"EC Required Param (Y) is nil\")\n\t}\n\tif jwk.Curve == nil {\n\t\treturn errors.New(\"EC Required Param (Crv) is nil\")\n\t}\n\treturn nil\n}", "func (pk PublicKey) JWK() JWK {\n\tentry, ok := pk[JwkProperty]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tjson, ok := entry.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn NewJWK(json)\n}", "func (m *RemoteJwks) Validate() error {\n\treturn m.validate(false)\n}", "func mustUnmarshalJWK(s string) *jose.JSONWebKey {\n\tret := &jose.JSONWebKey{}\n\tif err := json.Unmarshal([]byte(s), ret); err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}", "func (jwk *Jwk) validateRSAParams() error {\n\tif jwk.E < 1 {\n\t\treturn errors.New(\"RSA Required Param (E) is empty/default (<= 0)\")\n\t}\n\tif jwk.N == nil {\n\t\treturn errors.New(\"RSA Required Param (N) is nil\")\n\t}\n\n\tpOk := jwk.P != nil\n\tqOk := jwk.Q != nil\n\tdpOk := jwk.Dp != nil\n\tdqOk := jwk.Dq != nil\n\tqiOk := jwk.Qi != nil\n\tothOk := len(jwk.OtherPrimes) > 0\n\n\tparamsOR := pOk || qOk || dpOk || dqOk || qiOk\n\tparamsAnd := pOk && qOk && dpOk && dqOk && qiOk\n\n\tif jwk.D == nil {\n\t\tif (paramsOR || othOk) == true {\n\t\t\treturn errors.New(\"RSA first/second prime values are present but not Private key value (D)\")\n\t\t}\n\t} else {\n\t\tif paramsOR != paramsAnd {\n\t\t\treturn errors.New(\"Not all RSA first/second prime values are present or not present\")\n\t\t} else if !paramsOR && othOk {\n\t\t\treturn errors.New(\"RSA other primes is included but 1st, 2nd prime variables are missing\")\n\t\t} else if othOk {\n\t\t\tfor i, oth := range jwk.OtherPrimes {\n\t\t\t\tif oth.Coeff == nil {\n\t\t\t\t\treturn fmt.Errorf(\"Other Prime at index=%d, Coeff missing/nil\", i)\n\t\t\t\t} else if oth.R == nil {\n\t\t\t\t\treturn fmt.Errorf(\"Other Prime at index=%d, R missing/nil\", i)\n\t\t\t\t} else if oth.Exp == nil {\n\t\t\t\t\treturn fmt.Errorf(\"Other Prime at index=%d, Exp missing/nil\", i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *JSONWebKey) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (r VerifyJWTRequest) Validate() error {\n\treturn validation.ValidateStruct(&r,\n\t\tvalidation.Field(&r.Jwt, validation.Required),\n\t)\n}", "func (jwk *Jwk) validateOctParams() error {\n\tif len(jwk.KeyValue) < 1 {\n\t\treturn errors.New(\"Oct Required Param KeyValue (k) is empty\")\n\t}\n\n\treturn nil\n}", "func (ja *JWTAuth) Validate() error {\n\tif len(ja.SignKey) == 0 {\n\t\treturn errors.New(\"sign_key is required\")\n\t}\n\tif len(ja.UserClaims) == 0 {\n\t\tja.UserClaims = []string{\n\t\t\t\"username\",\n\t\t}\n\t}\n\tfor claim, placeholder := range ja.MetaClaims {\n\t\tif claim == \"\" || placeholder == \"\" {\n\t\t\treturn fmt.Errorf(\"invalid meta claim: %s -> %s\", claim, placeholder)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *JwtComponent) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif v, ok := interface{}(m.GetPrivateKey()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn JwtComponentValidationError{\n\t\t\t\tfield: \"PrivateKey\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetPublicKey()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn JwtComponentValidationError{\n\t\t\t\tfield: \"PublicKey\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewJWK(jwk map[string]interface{}) JWK {\n\treturn jwk\n}", "func (o *GetSlashingParametersOKBodyResult) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *JGroup) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAllowedDomains(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCustomize(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDefaultChannels(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStackTemplates(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTitle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *ThermalSimulationParameters) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAnisotropicStrainCoefficientsParallel(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAnisotropicStrainCoefficientsPerpendicular(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAnisotropicStrainCoefficientsZ(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBeamDiameter(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCoaxialAverageSensorZHeights(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHatchSpacing(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHeaterTemperature(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIncludeStressAnalysis(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInstantDynamicSensorLayers(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInstantDynamicSensorRadius(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInstantStaticSensorRadius(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLaserWattage(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLayerRotationAngle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLayerThickness(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateMeshResolutionFactor(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputCoaxialAverageSensorData(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputInstantDynamicSensor(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputInstantStaticSensor(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputPointProbe(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputPointThermalHistory(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputPrintRitePcsSensor(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputShrinkage(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOutputStateMap(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrintRitePcsSensorRadius(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateScanSpeed(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSelectedPoints(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSlicingStripeWidth(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStartingLayerAngle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (keySetter *KeySetter) Validate() []string {\n\tvar errorData []string = []string{}\n\tif keySetter.Key == \"\" {\n\t\terrorData = append(errorData, \"field 'key' is required\")\n\t}\n\tif keySetter.Value == \"\" || keySetter.Value == nil {\n\t\terrorData = append(errorData, \"field 'value' is required\")\n\t}\n\tif keySetter.Expiry < 0 {\n\t\terrorData = append(errorData, \"Enter a valid numerical expiry in ms\")\n\t}\n\treturn errorData\n}", "func (o *UIParameter) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := elemental.ValidateRequiredString(\"key\", o.Key); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidateRequiredString(\"type\", string(o.Type)); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"type\", string(o.Type), []string{\"Boolean\", \"Checkbox\", \"CVSSThreshold\", \"DangerMessage\", \"Duration\", \"Enum\", \"Endpoint\", \"FileDrop\", \"Float\", \"FloatSlice\", \"InfoMessage\", \"Integer\", \"IntegerSlice\", \"JSON\", \"List\", \"Message\", \"Namespace\", \"Password\", \"String\", \"StringSlice\", \"Switch\", \"TagsExpression\", \"Title\", \"WarningMessage\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\t// Custom object validation.\n\tif err := ValidateUIParameters(o); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (k Key) Validate() error {\n\n\t// check method\n\tif err := k.hasValidMethod(); err != nil {\n\t\treturn err\n\t}\n\n\t//check label\n\tif err := k.hasValidLabel(); err != nil {\n\t\treturn err\n\t}\n\n\t// check secret\n\tif err := k.hasValidSecret32(); err != nil {\n\t\treturn err\n\t}\n\n\t// check algo\n\tif err := k.hasValidAlgo(); err != nil {\n\t\treturn err\n\t}\n\n\t// check digits\n\tif err := k.hasValidDigits(); err != nil {\n\t\treturn err\n\t}\n\n\t// check period\n\tif err := k.hasValidPeriod(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func GetJWTPayload(ctx context.Context) (ValidatedJWTPayload, bool) {\n\tvalue := ctx.Value(key)\n\n\tpayload, ok := value.(ValidatedJWTPayload)\n\tif ok && payload.Validated {\n\t\treturn payload, true\n\t}\n\n\treturn ValidatedJWTPayload{}, false\n}", "func (o *GetSlashingParametersOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateResult(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (ut *MailerConfigInputPayload) Validate() (err error) {\n\tif ut.APIKey != nil {\n\t\tif utf8.RuneCountInString(*ut.APIKey) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.api_key`, *ut.APIKey, utf8.RuneCountInString(*ut.APIKey), 1, true))\n\t\t}\n\t}\n\tif ut.Domain != nil {\n\t\tif utf8.RuneCountInString(*ut.Domain) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.domain`, *ut.Domain, utf8.RuneCountInString(*ut.Domain), 1, true))\n\t\t}\n\t}\n\tif ut.FromName != nil {\n\t\tif utf8.RuneCountInString(*ut.FromName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.from_name`, *ut.FromName, utf8.RuneCountInString(*ut.FromName), 1, true))\n\t\t}\n\t}\n\tif ut.PublicAPIKey != nil {\n\t\tif utf8.RuneCountInString(*ut.PublicAPIKey) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.public_api_key`, *ut.PublicAPIKey, utf8.RuneCountInString(*ut.PublicAPIKey), 1, true))\n\t\t}\n\t}\n\treturn\n}", "func (c AuthConfig) Validate() []error {\n\tvar errs []error\n\n\tif len(c.JwksURI) == 0 {\n\t\terrs = append(errs, errors.Errorf(\"AuthConfig requires a non-empty JwksURI config value\"))\n\t}\n\n\treturn errs\n}", "func (asap *ASAP) Validate(jwt jwt.JWT, publicKey cr.PublicKey) error {\n\theader := jwt.(jws.JWS).Protected()\n\tkid := header.Get(KeyID).(string)\n\talg := header.Get(algorithm).(string)\n\n\tsigningMethod, err := getSigningMethod(alg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn jwt.Validate(publicKey, signingMethod, validator.GenerateValidator(kid, asap.ServiceID))\n}", "func (c openIDConfiguration) Validate() error {\n\tswitch {\n\tcase c.Issuer == \"\":\n\t\treturn errors.New(\"issuer cannot be empty\")\n\tcase c.JWKSetURI == \"\":\n\t\treturn errors.New(\"jwks_uri cannot be empty\")\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (jwk *Jwk) MarshalJSON() (data []byte, err error) {\n\n\t// Remove any potentionally conflicting claims from the JWK's additional members\n\tdelete(jwk.AdditionalMembers, \"kty\")\n\tdelete(jwk.AdditionalMembers, \"kid\")\n\tdelete(jwk.AdditionalMembers, \"alg\")\n\tdelete(jwk.AdditionalMembers, \"use\")\n\tdelete(jwk.AdditionalMembers, \"key_ops\")\n\tdelete(jwk.AdditionalMembers, \"crv\")\n\tdelete(jwk.AdditionalMembers, \"x\")\n\tdelete(jwk.AdditionalMembers, \"y\")\n\tdelete(jwk.AdditionalMembers, \"d\")\n\tdelete(jwk.AdditionalMembers, \"n\")\n\tdelete(jwk.AdditionalMembers, \"p\")\n\tdelete(jwk.AdditionalMembers, \"q\")\n\tdelete(jwk.AdditionalMembers, \"dp\")\n\tdelete(jwk.AdditionalMembers, \"dq\")\n\tdelete(jwk.AdditionalMembers, \"qi\")\n\tdelete(jwk.AdditionalMembers, \"e\")\n\tdelete(jwk.AdditionalMembers, \"oth\")\n\tdelete(jwk.AdditionalMembers, \"k\")\n\n\t// There are additional claims, individually marshal each member\n\tobj := make(map[string]*json.RawMessage, len(jwk.AdditionalMembers)+10)\n\n\tif bytes, err := json.Marshal(jwk.Type); err == nil {\n\t\trm := json.RawMessage(bytes)\n\t\tobj[\"kty\"] = &rm\n\t} else {\n\t\treturn nil, err\n\t}\n\n\tif len(jwk.Id) > 0 {\n\t\tif bytes, err := json.Marshal(jwk.Id); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[\"kid\"] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(jwk.Algorithm) > 0 {\n\t\tif bytes, err := json.Marshal(jwk.Algorithm); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[\"alg\"] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(jwk.Use) > 0 {\n\t\tif bytes, err := json.Marshal(jwk.Use); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[\"use\"] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(jwk.Operations) > 0 {\n\t\tif bytes, err := json.Marshal(jwk.Operations); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[\"key_ops\"] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tswitch jwk.Type {\n\tcase KeyTypeEC:\n\t\t{\n\t\t\tif jwk.Curve != nil {\n\t\t\t\tjwk.Curve.Params()\n\t\t\t\tp := jwk.Curve.Params()\n\t\t\t\tif bytes, err := json.Marshal(p.Name); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"crv\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.X != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.X}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"x\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Y != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Y}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"y\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.D != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.D}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"d\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase KeyTypeRSA:\n\t\t{\n\t\t\tif jwk.D != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.D}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"d\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif jwk.N != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.N}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"n\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.P != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.P}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"p\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Q != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Q}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"q\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Dp != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Dp}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"dp\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Dq != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Dq}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"dq\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.Qi != nil {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: jwk.Qi}\n\t\t\t\tif bytes, err := json.Marshal(b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"qi\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif jwk.E >= 0 {\n\t\t\t\tb64u := &Base64UrlUInt{UInt: big.NewInt(int64(jwk.E))}\n\t\t\t\tif bytes, err := json.Marshal(&b64u); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"e\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(jwk.OtherPrimes) > 0 {\n\t\t\t\ttempOthPrimes := make([]jwkOthPrimeJSON, len(jwk.OtherPrimes))\n\t\t\t\tfor i, v := range jwk.OtherPrimes {\n\t\t\t\t\ttempOthPrimes[i].Coeff = &Base64UrlUInt{UInt: v.Coeff}\n\t\t\t\t\ttempOthPrimes[i].Exp = &Base64UrlUInt{UInt: v.Exp}\n\t\t\t\t\ttempOthPrimes[i].R = &Base64UrlUInt{UInt: v.R}\n\t\t\t\t}\n\n\t\t\t\tif bytes, err := json.Marshal(tempOthPrimes); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"oth\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase KeyTypeOct:\n\t\t{\n\t\t\tif len(jwk.KeyValue) > 0 {\n\t\t\t\tb64o := &Base64UrlOctets{Octets: jwk.KeyValue}\n\t\t\t\tif bytes, err := json.Marshal(b64o); err == nil {\n\t\t\t\t\trm := json.RawMessage(bytes)\n\t\t\t\t\tobj[\"k\"] = &rm\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\t//Iterate through remaing members and add to json rawMessage\n\tfor k, v := range jwk.AdditionalMembers {\n\t\tif bytes, err := json.Marshal(v); err == nil {\n\t\t\trm := json.RawMessage(bytes)\n\t\t\tobj[k] = &rm\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Marshal obj\n\treturn json.Marshal(obj)\n}", "func (a *Service) ValidateJweToken(token string) (map[string]interface{}, *error_utils.ApiError) {\n\n\t// parse token string\n\tclaims, err := a.parseTokenString(token)\n\tif err != nil {\n\t\treturn nil, error_utils.NewUnauthorizedError(err.Error())\n\t}\n\n\t// validate dates\n\tif claims[\"orig_iat\"] == nil {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Orig Iat is missing\")\n\t}\n\n\t// try convert to float64\n\tif _, ok := claims[\"orig_iat\"].(float64); !ok {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Orig Iat must be float64 format\")\n\t}\n\n\t// get value and validate\n\torigIat := int64(claims[\"orig_iat\"].(float64))\n\tif origIat < a.timeFunc().Add(-a.maxRefresh).Unix() {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Token is expired\")\n\t}\n\n\t// check if exp exists in map\n\tif claims[\"exp\"] == nil {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Exp is missing\")\n\t}\n\n\t// try convert to float 64\n\tif _, ok := claims[\"exp\"].(float64); !ok {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Exp must be float64 format\")\n\t}\n\n\t// get value and validate\n\texp := int64(claims[\"exp\"].(float64))\n\tif exp < a.timeFunc().Unix(){\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Token is expired\")\n\t}\n\t// validate dates\n\n\t// validate issuer\n\t// check if iss exists in map\n\tif claims[\"iss\"] == nil {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Iss is missing\")\n\t}\n\n\t// try convert to string\n\tif _, ok := claims[\"iss\"].(string); !ok {\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Iss must be string format\")\n\t}\n\n\t// get value and validate\n\tissuer := claims[\"iss\"]\n\tif issuer != a.issuer{\n\t\treturn nil, error_utils.NewUnauthorizedError(\"Invalid issuer\")\n\t}\n\t// validate issuer\n\n\treturn claims, nil\n}", "func (kv BatchJobReplicateKV) Validate() error {\n\tif kv.Key == \"\" {\n\t\treturn errInvalidArgument\n\t}\n\treturn nil\n}", "func (o *V0037JobProperties) GetWckeyOk() (*string, bool) {\n\tif o == nil || o.Wckey == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Wckey, true\n}", "func (r *BatchJobKeyRotateV1) Validate(ctx context.Context, job BatchJobRequest, o ObjectLayer) error {\n\tif r == nil {\n\t\treturn nil\n\t}\n\n\tif r.APIVersion != batchKeyRotateAPIVersion {\n\t\treturn errInvalidArgument\n\t}\n\n\tif r.Bucket == \"\" {\n\t\treturn errInvalidArgument\n\t}\n\n\tif _, err := o.GetBucketInfo(ctx, r.Bucket, BucketOptions{}); err != nil {\n\t\tif isErrBucketNotFound(err) {\n\t\t\treturn batchKeyRotationJobError{\n\t\t\t\tCode: \"NoSuchSourceBucket\",\n\t\t\t\tDescription: \"The specified source bucket does not exist\",\n\t\t\t\tHTTPStatusCode: http.StatusNotFound,\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\tif GlobalKMS == nil {\n\t\treturn errKMSNotConfigured\n\t}\n\tif err := r.Encryption.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, tag := range r.Flags.Filter.Tags {\n\t\tif err := tag.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, meta := range r.Flags.Filter.Metadata {\n\t\tif err := meta.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := r.Flags.Retry.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewJwkSet(target string) (*JwkSet, error) {\n\tif target == \"\" {\n\t\treturn nil, errors.New(\"invalid empty target url\")\n\t}\n\n\tdata, err := getHttpRespData(target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn parseJwksData(data)\n}", "func (k *Kubelet) Validate() error {\n\tvar errors util.ValidateErrors\n\n\tb, err := yaml.Marshal(k)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"serializing configuration: %w\", err))\n\t}\n\n\tif err := yaml.Unmarshal(b, &k); err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"deserializing configuration: %w\", err))\n\t}\n\n\tif k.KubernetesCACertificate == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"kubernetesCACertificate can't be empty\"))\n\t}\n\n\terrors = append(errors, k.validateBootstrapConfig()...)\n\n\tif k.VolumePluginDir == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"volumePluginDir can't be empty\"))\n\t}\n\n\tif err := k.validateAdminConfig(); err != nil {\n\t\terrors = append(errors, err)\n\t}\n\n\tif err := k.Host.Validate(); err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"validating host configuration: %w\", err))\n\t}\n\n\tif k.Name == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"name can't be empty\"))\n\t}\n\n\treturn errors.Return()\n}", "func (ut *mailerConfigInputPayload) Validate() (err error) {\n\tif ut.APIKey != nil {\n\t\tif utf8.RuneCountInString(*ut.APIKey) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.api_key`, *ut.APIKey, utf8.RuneCountInString(*ut.APIKey), 1, true))\n\t\t}\n\t}\n\tif ut.Domain != nil {\n\t\tif utf8.RuneCountInString(*ut.Domain) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.domain`, *ut.Domain, utf8.RuneCountInString(*ut.Domain), 1, true))\n\t\t}\n\t}\n\tif ut.FromName != nil {\n\t\tif utf8.RuneCountInString(*ut.FromName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.from_name`, *ut.FromName, utf8.RuneCountInString(*ut.FromName), 1, true))\n\t\t}\n\t}\n\tif ut.PublicAPIKey != nil {\n\t\tif utf8.RuneCountInString(*ut.PublicAPIKey) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.public_api_key`, *ut.PublicAPIKey, utf8.RuneCountInString(*ut.PublicAPIKey), 1, true))\n\t\t}\n\t}\n\treturn\n}", "func Validate(schema, document string) (result *gojsonschema.Result, err error) {\n\tschemaLoader := gojsonschema.NewStringLoader(schema)\n\tdocumentLoader := gojsonschema.NewStringLoader(document)\n\treturn gojsonschema.Validate(schemaLoader, documentLoader)\n}", "func NewJwk(kty string) (j *Jwk, err error) {\n\tswitch kty {\n\tcase KeyTypeOct, KeyTypeRSA, KeyTypeEC:\n\t\tj = &Jwk{Type: kty}\n\tdefault:\n\t\terr = errors.New(\"Key Type Invalid. Must be Oct, RSA or EC\")\n\t}\n\n\treturn\n}", "func (r *Result) validate(errMsg *[]string, parentField string) {\n\tjn := resultJsonMap\n\taddErrMessage(errMsg, len(r.Key) > 0 && hasNonEmptyKV(r.Key), \"field '%s' must be non-empty and must not have empty keys or values\", parentField+\".\"+jn[\"Key\"])\n\taddErrMessage(errMsg, hasNonEmptyKV(r.Options), \"field '%s' must not have empty keys or values\", parentField+\".\"+jn[\"Options\"])\n\taddErrMessage(errMsg, regExHexadecimal.MatchString(string(r.Digest)), \"field '%s' must be hexadecimal\", parentField+\".\"+jn[\"Digest\"])\n}", "func (o *GetWellKnownJSONWebKeysInternalServerErrorBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *JSONWebKey) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (p PostGIS) WKTIsValidWithReason(wkt string) (bool, string) {\n\tvar isValid bool\n\tvar reason string\n\terr := p.db.QueryRow(`\n\t\tSELECT\n\t\t\tST_IsValid(ST_GeomFromText($1)),\n\t\t\tST_IsValidReason(ST_GeomFromText($1))`,\n\t\twkt,\n\t).Scan(&isValid, &reason)\n\tif err != nil {\n\t\t// It's not possible to distinguish between problems with the geometry\n\t\t// and problems with the database except by string-matching. It's\n\t\t// better to just report all errors, even if this means there will be\n\t\t// some false errors in the case of connectivity problems (or similar).\n\t\treturn false, err.Error()\n\t}\n\treturn isValid, reason\n}", "func (kv BatchKeyRotateKV) Validate() error {\n\tif kv.Key == \"\" {\n\t\treturn errInvalidArgument\n\t}\n\treturn nil\n}", "func (m *JwtRequirement) Validate() error {\n\treturn m.validate(false)\n}", "func (jz *Jzon) Validate(validator *Jzon) (ok bool, report *Jzon, err error) {\n\t// TODO:\n\treturn\n}", "func (c *JWTClaimsJSON) Valid() error {\n\tif c.UID == \"\" {\n\t\treturn fmt.Errorf(\"UID must be present in token claims\")\n\t}\n\tif c.Expiry == 0 {\n\t\treturn fmt.Errorf(\"Token has no expiry\")\n\t}\n\tif c.Expiry < int(time.Now().Unix()) {\n\t\treturn fmt.Errorf(\"Token has expired\")\n\t}\n\tif c.Iat > int(time.Now().Unix()+int64(time.Second)) {\n\t\treturn fmt.Errorf(\"Token is from the future\")\n\t}\n\tif c.Issuer != config.AuthStrategyLDAPIssuer {\n\t\treturn fmt.Errorf(\"token is invalid because of authentication strategy mismatch\")\n\t}\n\treturn nil\n}", "func (m *JwtHeader) Validate() error {\n\treturn m.validate(false)\n}", "func (m *MV12WE) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateQuality(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateResolution(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (s JBIG2EncoderSettings) Validate() error {\n\tconst processName = \"validateEncoder\"\n\tif s.Threshold < 0 || s.Threshold > 1.0 {\n\t\treturn errors.Errorf(processName, \"provided threshold value: '%v' must be in range [0.0, 1.0]\", s.Threshold)\n\t}\n\tif s.ResolutionX < 0 {\n\t\treturn errors.Errorf(processName, \"provided x resolution: '%d' must be positive or zero value\", s.ResolutionX)\n\t}\n\tif s.ResolutionY < 0 {\n\t\treturn errors.Errorf(processName, \"provided y resolution: '%d' must be positive or zero value\", s.ResolutionY)\n\t}\n\tif s.DefaultPixelValue != 0 && s.DefaultPixelValue != 1 {\n\t\treturn errors.Errorf(processName, \"default pixel value: '%d' must be a value for the bit: {0,1}\", s.DefaultPixelValue)\n\t}\n\tif s.Compression != JB2Generic {\n\t\treturn errors.Errorf(processName, \"provided compression is not implemented yet\")\n\t}\n\treturn nil\n}", "func (p Params) Validate() error {\n\tif err := validateTokenCourse(p.TokenCourse); err != nil {\n\t\treturn err\n\t}\n\tif err := validateSubscriptionPrice(p.SubscriptionPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateVPNGBPrice(p.VPNGBPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateStorageGBPrice(p.StorageGBPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateBaseVPNGb(p.BaseVPNGb); err != nil {\n\t\treturn err\n\t}\n\tif err := validateBaseStorageGb(p.BaseStorageGb); err != nil {\n\t\treturn err\n\t}\n\tif err := validateCourseChangeSigners(p.CourseChangeSigners); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (ut *jSONDataMetaStationFirmware) Validate() (err error) {\n\tif ut.Version == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"version\"))\n\t}\n\tif ut.Build == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"build\"))\n\t}\n\tif ut.Number == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"number\"))\n\t}\n\tif ut.Timestamp == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"timestamp\"))\n\t}\n\tif ut.Hash == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"hash\"))\n\t}\n\treturn\n}", "func (o *UserCurrentGetGPGKeyOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateCanCertify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCanEncryptComms(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCanEncryptStorage(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCanSign(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateEmails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateExpires(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateKeyID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePrimaryKeyID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePublicKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSubsKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (v GetWAPSelectedHostnamesRequest) Validate() error {\n\treturn validation.Errors{\n\t\t\"ConfigID\": validation.Validate(v.ConfigID, validation.Required),\n\t\t\"Version\": validation.Validate(v.Version, validation.Required),\n\t\t\"SecurityPolicyID\": validation.Validate(v.Version, validation.Required),\n\t}.Filter()\n}", "func (o *dryrunOptions) validate() error {\n\tif o.userWPAName == \"\" && o.labelSelector == \"\" && !o.allWPA {\n\t\treturn fmt.Errorf(\"the watermarkpodautoscaler name or label-selector is required\")\n\t}\n\n\treturn nil\n}", "func (m *JwtProvider) Validate() error {\n\treturn m.validate(false)\n}", "func (m *ScopedRoutes_ScopeKeyBuilder_FragmentBuilder_HeaderValueExtractor_KvElement) Validate() error {\n\treturn m.validate(false)\n}", "func (m *WasmParams) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (w Warrant) Validate() error {\n\tif len(w.FirstName) == 0 {\n\t\treturn errors.New(\"missing first name element\")\n\t}\n\tif len(w.LastName) == 0 {\n\t\treturn errors.New(\"missing last name element\")\n\t}\n\tif len(w.Civility) == 0 {\n\t\treturn errors.New(\"missing civility element\")\n\t}\n\treturn nil\n}", "func (o *OAUTHKey) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (o *GetFwLeaderboardsCharactersOKBodyKills) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateActiveTotal(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateLastWeek(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateYesterday(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func Validate(schema *gojsonschema.Schema, document gojsonschema.JSONLoader) (*errors.Errs, error) {\n\tresult, err := schema.Validate(document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif result.Valid() {\n\t\treturn nil, nil\n\t}\n\tvar errs errors.Errs\n\tfor _, resultErr := range result.Errors() {\n\t\terrs = append(errs, resultErrorToError(resultErr))\n\t}\n\treturn &errs, nil\n}", "func JWTValidator(certificates map[string]CertificateList) jwt.Keyfunc {\n\treturn func(token *jwt.Token) (interface{}, error) {\n\n\t\tvar certificateList CertificateList\n\t\tvar kid string\n\t\tvar ok bool\n\n\t\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\t\treturn nil, fmt.Errorf(\"unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\n\t\tif kid, ok = token.Header[\"kid\"].(string); !ok {\n\t\t\treturn nil, fmt.Errorf(\"field 'kid' is of invalid type %T, should be string\", token.Header[\"kid\"])\n\t\t}\n\n\t\tif certificateList, ok = certificates[kid]; !ok {\n\t\t\treturn nil, fmt.Errorf(\"kid '%s' not found in certificate list\", kid)\n\t\t}\n\n\t\tfor _, certificate := range certificateList {\n\t\t\treturn certificate.PublicKey, nil\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"no certificate candidates for kid '%s'\", kid)\n\t}\n}", "func (m *KeyPair) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with Resource\n\tif err := m.Resource.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGroup(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (r UserDetailsRequest) Validate() error {\n\treturn validation.ValidateStruct(&r,\n\t\tvalidation.Field(&r.Jwt, validation.Required),\n\t)\n}", "func (j *Job) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: j.Name, Name: \"Name\"},\n\t\t&validators.StringIsPresent{Field: j.Description, Name: \"Description\"},\n\t\t&validators.StringIsPresent{Field: j.Salary, Name: \"Salary\"},\n\t), nil\n}", "func (m *JwtAuthentication) Validate() error {\n\treturn m.validate(false)\n}", "func ValidateToken(tokenStr string, jwk map[string]JWKKey) (*jwt.Token, error) {\n\t// @note 2. Decode the token string into JWT format.\n\ttoken, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {\n\t\t// Methods both of Cognito User Pools and Google are RS256\n\t\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\t\t// @note 5. Get the kid from the JWT token header and retrieve the corresponding JSON Web Key that was stored\n\t\tif kid, ok := token.Header[\"kid\"]; ok {\n\t\t\tif kidStr, ok := kid.(string); ok {\n\t\t\t\tkey := jwk[kidStr]\n\t\t\t\t// @note 6. Verify the signature of the decoded JWT token.\n\t\t\t\trsaPublicKey := convertKey(key.E, key.N)\n\t\t\t\treturn rsaPublicKey, nil\n\t\t\t}\n\t\t}\n\t\t// Does not get RSA public key\n\t\treturn \"\", nil\n\t})\n\tif err != nil {\n\t\treturn token, err\n\t}\n\n\tclaims := token.Claims.(jwt.MapClaims)\n\tiss, ok := claims[\"iss\"]\n\tif !ok {\n\t\treturn token, fmt.Errorf(\"token does not contain issuer\")\n\t}\n\n\tissStr := iss.(string)\n\tif strings.Contains(issStr, \"cognito-idp\") {\n\t\terr = validateAWSJWTClaims(claims)\n\t\tif err != nil {\n\t\t\treturn token, err\n\t\t}\n\t} else if strings.Contains(issStr, \"accounts.google.com\") {\n\t\terr = validateGoogleJWTClaims(claims)\n\t\tif err != nil {\n\t\t\treturn token, err\n\t\t}\n\t}\n\n\tif token.Valid {\n\t\treturn token, nil\n\t}\n\n\treturn token, err\n}", "func (m JwtVapiClaims) Valid() error {\n\treturn nil\n}", "func Validate() error {\n\terrors := err.Errors()\n\tfor name, variable := range env.variables {\n\t\tif Get(name) == nil && variable.required {\n\t\t\terrors.AddError(err.Error(\"Property \" + name + \" not provided!\"))\n\t\t}\n\t}\n\tif errors.Count() > 0 {\n\t\tif env.settings.FailOnMissingRequired {\n\t\t\tpanic(errors)\n\t\t}\n\t\treturn errors\n\t}\n\treturn nil\n}", "func (ut *updateDeviceFirmwarePayload) Validate() (err error) {\n\tif ut.DeviceID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"deviceId\"))\n\t}\n\tif ut.FirmwareID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"firmwareId\"))\n\t}\n\treturn\n}", "func validateJWT(w http.ResponseWriter, req *http.Request) {\n\tif klog.V(3).Enabled() {\n\t\tklog.Infof(\"request received from: %v, headers: %v\", req.RemoteAddr, req.Header)\n\t}\n\tiapJWT := req.Header.Get(\"X-Goog-IAP-JWT-Assertion\")\n\tif iapJWT == \"\" {\n\t\tklog.V(1).Infof(\"X-Goog-IAP-JWT-Assertion header not found\")\n\t\thttp.Error(w, \"\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tif audience == \"\" {\n\t\tklog.V(1).ErrorS(fmt.Errorf(\"token cannot be validated, empty audience, check for previous errors\"), \"\")\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif issuer == \"\" {\n\t\tklog.V(1).ErrorS(fmt.Errorf(\"token cannot be validated, empty issuer, check for previous errors\"), \"\")\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tctx := context.Background()\n\t// we pass empty as audience here because we will validate it later\n\tpayload, err := jwtValidator.Validate(ctx, iapJWT, \"\")\n\tklog.V(3).Infof(\"payload received: %+v\", payload)\n\tif err != nil {\n\t\tklog.V(1).ErrorS(err, \"error validating jwt token\")\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\t// empty payload should not be possible\n\tif payload == nil {\n\t\tklog.V(1).ErrorS(nil, \"null payload received\")\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\t// validate the audience\n\tif audience != payload.Audience {\n\t\tklog.V(1).ErrorS(nil, \"error validating jwt token, invalid audience, expected %s, got %s\", audience, payload.Audience)\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\t// validate the issuer\n\tif issuer != payload.Issuer {\n\t\tklog.V(1).ErrorS(nil, \"error validating jwt token, invalid issuer, expected %s, got %s\", issuer, payload.Issuer)\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\t// validate expired - this may be redundant - but we check it anyway\n\tif payload.Expires == 0 || payload.Expires+30 < time.Now().Unix() {\n\t\tklog.V(1).ErrorS(nil, \"error validating jwt token, expired\")\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\t// validate IssuedAt - should not be in the future\n\tif payload.IssuedAt == 0 || payload.IssuedAt-30 > time.Now().Unix() {\n\t\tklog.V(1).ErrorS(nil, \"error validating jwt token, emitted in the future\")\n\t\thttp.Error(w, \"\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}", "func (p *Params) ValidateRequiredProperties() (bool, []error, []string) {\n\n\terrors := []error{}\n\twarnings := []string{}\n\n\t// validate app params\n\tif p.App == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Application name is required; either define an app label or use app property on this stage\"))\n\t}\n\tif p.Namespace == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Namespace is required; either use credentials with a defaultNamespace or set it via namespace property on this stage\"))\n\t}\n\n\tif p.Action == \"rollback-canary\" {\n\t\t// the above properties are all you need for a rollback\n\t\treturn len(errors) == 0, errors, warnings\n\t}\n\n\t// validate container params\n\tif p.Container.ImageRepository == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Image repository is required; set it via container.repository property on this stage\"))\n\t}\n\tif p.Container.ImageName == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Image name is required; set it via container.name property on this stage\"))\n\t}\n\tif p.Container.ImageTag == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Image tag is required; set it via container.tag property on this stage\"))\n\t}\n\n\t// validate cpu params\n\tif p.Container.CPU.Request == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Cpu request is required; set it via container.cpu.request property on this stage\"))\n\t}\n\tif p.Container.CPU.Limit == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Cpu limit is required; set it via container.cpu.limit property on this stage\"))\n\t}\n\n\t// validate memory params\n\tif p.Container.Memory.Request == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Memory request is required; set it via container.memory.request property on this stage\"))\n\t}\n\tif p.Container.Memory.Limit == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Memory limit is required; set it via container.memory.limit property on this stage\"))\n\t}\n\n\t// defaults for rollingupdate\n\tif p.RollingUpdate.MaxSurge == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Rollingupdate max surge is required; set it via rollingupdate.maxsurge property on this stage\"))\n\t}\n\tif p.RollingUpdate.MaxUnavailable == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Rollingupdate max unavailable is required; set it via rollingupdate.maxunavailable property on this stage\"))\n\t}\n\n\tif p.Kind == \"job\" || p.Kind == \"cronjob\" {\n\t\tif p.Kind == \"cronjob\" {\n\t\t\tif p.Schedule == \"\" {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"Schedule is required for a cronjob; set it via schedule property on this stage\"))\n\t\t\t}\n\n\t\t\tif p.ConcurrencyPolicy != \"Allow\" && p.ConcurrencyPolicy != \"Forbid\" && p.ConcurrencyPolicy != \"Replace\" {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"ConcurrencyPolicy is invalid; allowed values are Allow, Forbid or Replace\"))\n\t\t\t}\n\t\t}\n\n\t\t// the above properties are all you need for a worker\n\t\treturn len(errors) == 0, errors, warnings\n\t}\n\n\t// validate params with respect to incoming requests\n\tif p.Visibility == \"\" || (p.Visibility != \"private\" && p.Visibility != \"public\" && p.Visibility != \"iap\" && p.Visibility != \"public-whitelist\") {\n\t\terrors = append(errors, fmt.Errorf(\"Visibility property is required; set it via visibility property on this stage; allowed values are private, iap, public-whitelist or public\"))\n\t}\n\tif p.Visibility == \"iap\" && p.IapOauthCredentialsClientID == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"With visibility 'iap' property iapOauthClientID is required; set it via iapOauthClientID property on this stage\"))\n\t}\n\tif p.Visibility == \"iap\" && p.IapOauthCredentialsClientSecret == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"With visibility 'iap' property iapOauthClientSecret is required; set it via iapOauthClientSecret property on this stage\"))\n\t}\n\n\tif len(p.Hosts) == 0 {\n\t\terrors = append(errors, fmt.Errorf(\"At least one host is required; set it via hosts array property on this stage\"))\n\t}\n\tfor _, host := range p.Hosts {\n\t\tif len(host) > 253 {\n\t\t\terrors = append(errors, fmt.Errorf(\"Host %v is longer than the allowed 253 characters, which is invalid for DNS; please shorten your host\", host))\n\t\t\tbreak\n\t\t}\n\n\t\tmatchesInvalidChars, _ := regexp.MatchString(\"[^a-zA-Z0-9-.]\", host)\n\t\tif matchesInvalidChars {\n\t\t\terrors = append(errors, fmt.Errorf(\"Host %v has invalid characters; only a-z, 0-9, - and . are allowed; please fix your host\", host))\n\t\t}\n\n\t\thostLabels := strings.Split(host, \".\")\n\t\tfor _, label := range hostLabels {\n\t\t\tif len(label) > 63 {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"Host %v has label %v - the parts between dots - that is longer than the allowed 63 characters, which is invalid for DNS; please shorten your host label\", host, label))\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, host := range p.InternalHosts {\n\t\tif len(host) > 253 {\n\t\t\terrors = append(errors, fmt.Errorf(\"Internal host %v is longer than the allowed 253 characters, which is invalid for DNS; please shorten your host\", host))\n\t\t\tbreak\n\t\t}\n\n\t\tmatchesInvalidChars, _ := regexp.MatchString(\"[^a-zA-Z0-9-.]\", host)\n\t\tif matchesInvalidChars {\n\t\t\terrors = append(errors, fmt.Errorf(\"Internal host %v has invalid characters; only a-z, 0-9, - and . are allowed; please fix your host\", host))\n\t\t}\n\n\t\thostLabels := strings.Split(host, \".\")\n\t\tfor _, label := range hostLabels {\n\t\t\tif len(label) > 63 {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"Internal host %v has label %v - the parts between dots - that is longer than the allowed 63 characters, which is invalid for DNS; please shorten your host label\", host, label))\n\t\t\t}\n\t\t}\n\t}\n\n\tif p.Basepath == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Basepath property is required; set it via basepath property on this stage\"))\n\t}\n\tif p.Container.Port <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Container port must be larger than zero; set it via container.port property on this stage\"))\n\t}\n\n\t// validate autoscale params\n\tif p.Autoscale.MinReplicas <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Autoscaling min replicas must be larger than zero; set it via autoscale.min property on this stage\"))\n\t}\n\tif p.Autoscale.MaxReplicas <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Autoscaling max replicas must be larger than zero; set it via autoscale.max property on this stage\"))\n\t}\n\tif p.Autoscale.CPUPercentage <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Autoscaling cpu percentage must be larger than zero; set it via autoscale.cpu property on this stage\"))\n\t}\n\n\t// validate liveness params\n\tif p.Container.LivenessProbe.Path == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Liveness path is required; set it via container.liveness.path property on this stage\"))\n\t}\n\tif p.Container.LivenessProbe.Port <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Liveness port must be larger than zero; set it via container.liveness.port property on this stage\"))\n\t}\n\tif p.Container.LivenessProbe.InitialDelaySeconds <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Liveness initial delay must be larger than zero; set it via container.liveness.delay property on this stage\"))\n\t}\n\tif p.Container.LivenessProbe.TimeoutSeconds <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Liveness timeout must be larger than zero; set it via container.liveness.timeout property on this stage\"))\n\t}\n\n\t// validate readiness params\n\tif p.Container.ReadinessProbe.Path == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Readiness path is required; set it via container.readiness.path property on this stage\"))\n\t}\n\tif p.Container.ReadinessProbe.Port <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Readiness port must be larger than zero; set it via container.readiness.port property on this stage\"))\n\t}\n\tif p.Container.ReadinessProbe.TimeoutSeconds <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Readiness timeout must be larger than zero; set it via container.readiness.timeout property on this stage\"))\n\t}\n\n\t// validate metrics params\n\tif p.Container.Metrics.Scrape == nil {\n\t\terrors = append(errors, fmt.Errorf(\"Metrics scrape is required; set it via container.metrics.scrape property on this stage; allowed values are true or false\"))\n\t}\n\tif p.Container.Metrics.Scrape != nil && *p.Container.Metrics.Scrape {\n\t\tif p.Container.Metrics.Path == \"\" {\n\t\t\terrors = append(errors, fmt.Errorf(\"Metrics path is required; set it via container.metrics.path property on this stage\"))\n\t\t}\n\t\tif p.Container.Metrics.Port <= 0 {\n\t\t\terrors = append(errors, fmt.Errorf(\"Metrics port must be larger than zero; set it via container.metrics.port property on this stage\"))\n\t\t}\n\t}\n\n\t// The \"sidecar\" field is deprecated, so it can be empty. But if it's specified, then we validate it.\n\tif p.Sidecar.Type != \"\" && p.Sidecar.Type != \"none\" {\n\t\terrors = p.validateSidecar(&p.Sidecar, errors)\n\t\twarnings = append(warnings, \"The sidecar field is deprecated, the sidecars list should be used instead.\")\n\t}\n\n\t// validate sidecars params\n\tfor _, sidecar := range p.Sidecars {\n\t\terrors = p.validateSidecar(sidecar, errors)\n\t}\n\n\treturn len(errors) == 0, errors, warnings\n}", "func (pr *Params) Validate() error {\n\tnames := []string{}\n\tfor nm := range pr.Objects {\n\t\tnames = append(names, nm)\n\t}\n\treturn pr.Params.ValidateSheets(names)\n}", "func (skmr *SecretKeyMemberRequest) Validate() error {\n\tif skmr.AccountID == nil {\n\t\treturn ErrInvalidAccountID\n\t}\n\n\tif skmr.SecretKeyID == nil {\n\t\treturn ErrInvalidKeyID\n\t}\n\n\treturn nil\n}", "func (m *FortifyJob) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvokingUserName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateJobState(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateJobType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *GcpKms) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateLinks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateApplicationCredentials(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGcpKmsInlineEkmipReachability(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGoogleReachability(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProxyType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateScope(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateState(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSvm(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (mt *EasypostAPIKey) Validate() (err error) {\n\tif mt.Object == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"object\"))\n\t}\n\tif mt.Mode == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"mode\"))\n\t}\n\tif mt.Key == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"key\"))\n\t}\n\tif mt.CreatedAt == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"created_at\"))\n\t}\n\n\tif !(mt.Mode == \"test\" || mt.Mode == \"production\") {\n\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.mode`, mt.Mode, []interface{}{\"test\", \"production\"}))\n\t}\n\tif ok := goa.ValidatePattern(`^ApiKey$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^ApiKey$`))\n\t}\n\treturn\n}", "func (m *EnvironmentRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCredential(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDescription(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKerberosConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKubernetesConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLdapConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLocation(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProxyConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRdsConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRegions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (JSONSchema) Validate(json string) error {\n\treturn nil\n}", "func (m *SoftwareDataEncryption) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (c configuration) Validate() error {\n\tvar errs error\n\n\terrs = errors.Append(errs, c.Auth.Validate())\n\terrs = errors.Append(errs, c.Config.Validate())\n\n\tif c.Environment == \"\" {\n\t\terrs = errors.Append(errs, errors.New(\"environment is required\"))\n\t}\n\n\t// TODO: this config is only used here, so the validation is here too. Either the config or the validation should be moved somewhere else.\n\tif c.Distribution.PKE.Amazon.GlobalRegion == \"\" {\n\t\terrs = errors.Append(errs, errors.New(\"pke amazon global region is required\"))\n\t}\n\n\treturn errs\n}", "func (plan *DeploymentPlan) Validate() error {\n\n\terr := checkRequired(&plan.VMWConfig.VCenterURL,\n\t\t\"VMware vCenter/vSphere credentials are missing\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = checkRequired(&plan.VMWConfig.DCName,\n\t\t\"No Datacenter was specified, will try to use the default (will cause errors with Linked-Mode)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = checkRequired(&plan.VMWConfig.DSName,\n\t\t\"A VMware vCenter datastore is required for provisioning\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = checkRequired(&plan.VMWConfig.NetworkName,\n\t\t\"Specify a Network to connect to\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = checkRequired(&plan.VMWConfig.VSphereHost,\n\t\t\"A Host inside of vCenter/vSphere is required to provision on for VM capacity\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Ideally these should be populated as they're needed for a lot of the tasks.\n\terr = checkRequired(&plan.VMWConfig.VMTemplateAuth.Username,\n\t\t\"No Username for inside of the Guest OS was specified, somethings may fail\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = checkRequired(&plan.VMWConfig.VMTemplateAuth.Password,\n\t\t\"No Password for inside of the Guest OS was specified, somethings may fail\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif plan.VMWConfig.VCenterURL == \"\" || plan.VMWConfig.DSName == \"\" || plan.VMWConfig.VSphereHost == \"\" {\n\t\treturn fmt.Errorf(\"Missing VSphere host\")\n\t}\n\n\treturn nil\n}", "func (e JwtHeaderValidationError) Key() bool { return e.key }", "func (m *JwtRequirementOrList) Validate() error {\n\treturn m.validate(false)\n}", "func Validate(fileName string, input string) error {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\tschemaURI := fmt.Sprintf(\"file://%s\", filepath.Join(pwd, fileName))\n\n\tschemaLoader := gojsonschema.NewReferenceLoader(schemaURI)\n\tdocumentLoader := gojsonschema.NewStringLoader(input)\n\n\tresult, err := gojsonschema.Validate(schemaLoader, documentLoader)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error loading JSON schema, error: %v\", err)\n\t}\n\n\tif result.Valid() {\n\t\treturn nil\n\t}\n\tfmt.Printf(\"Errors for JSON schema: '%s'\\n\", schemaURI)\n\tfor _, desc := range result.Errors() {\n\t\tfmt.Printf(\"\\t- %s\\n\", desc)\n\t}\n\tfmt.Printf(\"\\n\")\n\treturn fmt.Errorf(\"The output of the integration doesn't have expected JSON format\")\n}", "func (m *JToken) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateFirst(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateItem(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLast(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNext(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrevious(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRoot(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (jwtParser JWTParser) Validate() JWTParser {\n\tif jwtParser.SigningKeyGetter == nil {\n\t\tjwtParser.SigningKeyGetter = func(*jwt.Token) (interface{}, error) {\n\t\t\treturn jwtParser.Secret, nil\n\t\t}\n\t}\n\tif jwtParser.ValidationKeyGetter == nil {\n\t\tjwtParser.ValidationKeyGetter = func(*jwt.Token) (interface{}, error) {\n\t\t\treturn jwtParser.Secret, nil\n\t\t}\n\t}\n\treturn jwtParser\n}", "func (m LBSKU) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (user *User) Validate() (map[string]interface{}, bool) {\n\n\tif user.FirstName == \"\" {\n\t\treturn utils.Message(false, \"User First name should be on the payload\"), false\n\t}\n\n\tif user.LastName == \"\" {\n\t\treturn utils.Message(false, \"User Last name should be on the payload\"), false\n\t}\n\n\tif user.PhoneNumber == \"\" {\n\t\treturn utils.Message(false, \"User Phone number should be on the payload\"), false\n\t}\n\n\tif user.Age == \"\" {\n\t\treturn utils.Message(false, \"User Age should be on the payload\"), false\n\t}\n\n\tif user.Email == \"\" {\n\t\treturn utils.Message(false, \"User Email should be on the payload\"), false\n\t}\n\n\t//All the required parameters are present\n\treturn utils.Message(true, \"success\"), true\n}", "func (m *V3GatewayIdentifiers) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *BackupWPA) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateApMac(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEapAnonymousIdentity(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEapPassword(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEapType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEapTypeExt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEapUsername(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEnabled(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePresharedKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSecurity(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSsid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateWpaAuthentication(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *TableReporterParamsFilter) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAlerts(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateClusters(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateConsistencyGroups(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContentLibraryImages(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContentLibraryVMTemplates(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDatacenters(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDisks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateElfDataStores(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateElfImages(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGlobalAlertRules(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHosts(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIscsiConnections(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIscsiLunSnapshots(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIscsiLuns(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIscsiTargets(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNamespaceGroups(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNfsExports(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNics(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNvmfNamespaceSnapshots(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNvmfNamespaces(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNvmfSubsystems(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSnapshotPlans(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSystemAuditLogs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTasks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUsbDevices(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUserAuditLogs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUsers(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVdses(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVlans(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVMEntityFilters(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVMPlacementGroups(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVMTemplates(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVMVolumes(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVms(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (ut *recoveryPayload) Validate() (err error) {\n\tif ut.Token == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"token\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 10 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 10, true))\n\t\t}\n\t}\n\treturn\n}", "func (ut *jSONDataMeta) Validate() (err error) {\n\tif ut.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"id\"))\n\t}\n\tif ut.Station != nil {\n\t\tif err2 := ut.Station.Validate(); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func (m *JobJobFilament) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (np *NamePointer) Validate() (err error) {\n\tvar typeValidation error\n\tswitch np.Key {\n\tcase \"account_pubkey\":\n\t\ttypeValidation = np.validateAccountPubkey()\n\tcase \"oracle_pubkey\":\n\t\ttypeValidation = np.validateOraclePubkey()\n\tcase \"contract_pubkey\":\n\t\ttypeValidation = np.validateContractPubkey()\n\tcase \"channel\":\n\t\ttypeValidation = np.validateChannel()\n\tdefault:\n\t\ttypeValidation = nil\n\t}\n\treturn typeValidation\n}", "func (p paymentJson) Validate() error {\n\tif p.AccountId == \"\" {\n\t\treturn errors.New(\"missing customer id\")\n\t}\n\tif p.Amount == 0 {\n\t\treturn errors.New(\"missing amount\")\n\t}\n\treturn nil\n}", "func (opts resourceOptions) validate() error {\n\t// Check that the required flags did not get a flag as their value.\n\t// We can safely look for a '-' as the first char as none of the fields accepts it.\n\t// NOTE: We must do this for all the required flags first or we may output the wrong\n\t// error as flags may seem to be missing because Cobra assigned them to another flag.\n\tif strings.HasPrefix(opts.Group, \"-\") {\n\t\treturn fmt.Errorf(groupPresent)\n\t}\n\tif strings.HasPrefix(opts.Version, \"-\") {\n\t\treturn fmt.Errorf(versionPresent)\n\t}\n\tif strings.HasPrefix(opts.Kind, \"-\") {\n\t\treturn fmt.Errorf(kindPresent)\n\t}\n\n\t// We do not check here if the GVK values are empty because that would\n\t// make them mandatory and some plugins may want to set default values.\n\t// Instead, this is checked by resource.GVK.Validate()\n\n\treturn nil\n}", "func (s *Schema) validate(v interface{}) error {\n\tif s.Always != nil {\n\t\tif !*s.Always {\n\t\t\treturn validationError(\"\", \"always fail\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tif s.Ref != nil {\n\t\tif err := s.Ref.validate(v); err != nil {\n\t\t\tfinishSchemaContext(err, s.Ref)\n\t\t\tvar refURL string\n\t\t\tif s.URL == s.Ref.URL {\n\t\t\t\trefURL = s.Ref.Ptr\n\t\t\t} else {\n\t\t\t\trefURL = s.Ref.URL + s.Ref.Ptr\n\t\t\t}\n\t\t\treturn validationError(\"$ref\", \"doesn't validate with %q\", refURL).add(err)\n\t\t}\n\n\t\t// All other properties in a \"$ref\" object MUST be ignored\n\t\treturn nil\n\t}\n\n\tif len(s.Types) > 0 {\n\t\tvType := jsonType(v)\n\t\tmatched := false\n\t\tfor _, t := range s.Types {\n\t\t\tif vType == t {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t} else if t == \"integer\" && vType == \"number\" {\n\t\t\t\tif _, ok := new(big.Int).SetString(fmt.Sprint(v), 10); ok {\n\t\t\t\t\tmatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn validationError(\"type\", \"expected %s, but got %s\", strings.Join(s.Types, \" or \"), vType)\n\t\t}\n\t}\n\n\tif len(s.Constant) > 0 {\n\t\tif !equals(v, s.Constant[0]) {\n\t\t\tswitch jsonType(s.Constant[0]) {\n\t\t\tcase \"object\", \"array\":\n\t\t\t\treturn validationError(\"const\", \"const failed\")\n\t\t\tdefault:\n\t\t\t\treturn validationError(\"const\", \"value must be %#v\", s.Constant[0])\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(s.Enum) > 0 {\n\t\tmatched := false\n\t\tfor _, item := range s.Enum {\n\t\t\tif equals(v, item) {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn validationError(\"enum\", s.enumError)\n\t\t}\n\t}\n\n\tif s.Not != nil && s.Not.validate(v) == nil {\n\t\treturn validationError(\"not\", \"not failed\")\n\t}\n\n\tfor i, sch := range s.AllOf {\n\t\tif err := sch.validate(v); err != nil {\n\t\t\treturn validationError(\"allOf/\"+strconv.Itoa(i), \"allOf failed\").add(err)\n\t\t}\n\t}\n\n\tif len(s.AnyOf) > 0 {\n\t\tmatched := false\n\t\tvar causes []error\n\t\tfor i, sch := range s.AnyOf {\n\t\t\tif err := sch.validate(v); err == nil {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tcauses = append(causes, addContext(\"\", strconv.Itoa(i), err))\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn validationError(\"anyOf\", \"anyOf failed\").add(causes...)\n\t\t}\n\t}\n\n\tif len(s.OneOf) > 0 {\n\t\tmatched := -1\n\t\tvar causes []error\n\t\tfor i, sch := range s.OneOf {\n\t\t\tif err := sch.validate(v); err == nil {\n\t\t\t\tif matched == -1 {\n\t\t\t\t\tmatched = i\n\t\t\t\t} else {\n\t\t\t\t\treturn validationError(\"oneOf\", \"valid against schemas at indexes %d and %d\", matched, i)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcauses = append(causes, addContext(\"\", strconv.Itoa(i), err))\n\t\t\t}\n\t\t}\n\t\tif matched == -1 {\n\t\t\treturn validationError(\"oneOf\", \"oneOf failed\").add(causes...)\n\t\t}\n\t}\n\n\tif s.If != nil {\n\t\tif s.If.validate(v) == nil {\n\t\t\tif s.Then != nil {\n\t\t\t\tif err := s.Then.validate(v); err != nil {\n\t\t\t\t\treturn validationError(\"then\", \"if-then failed\").add(err)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif s.Else != nil {\n\t\t\t\tif err := s.Else.validate(v); err != nil {\n\t\t\t\t\treturn validationError(\"else\", \"if-else failed\").add(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch v := v.(type) {\n\tcase map[string]interface{}:\n\t\tif s.MinProperties != -1 && len(v) < s.MinProperties {\n\t\t\treturn validationError(\"minProperties\", \"minimum %d properties allowed, but found %d properties\", s.MinProperties, len(v))\n\t\t}\n\t\tif s.MaxProperties != -1 && len(v) > s.MaxProperties {\n\t\t\treturn validationError(\"maxProperties\", \"maximum %d properties allowed, but found %d properties\", s.MaxProperties, len(v))\n\t\t}\n\t\tif len(s.Required) > 0 {\n\t\t\tvar missing []string\n\t\t\tfor _, pname := range s.Required {\n\t\t\t\tif _, ok := v[pname]; !ok {\n\t\t\t\t\tmissing = append(missing, strconv.Quote(pname))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(missing) > 0 {\n\t\t\t\treturn validationError(\"required\", \"missing properties: %s\", strings.Join(missing, \", \"))\n\t\t\t}\n\t\t}\n\n\t\tvar additionalProps map[string]struct{}\n\t\tif s.AdditionalProperties != nil {\n\t\t\tadditionalProps = make(map[string]struct{}, len(v))\n\t\t\tfor pname := range v {\n\t\t\t\tadditionalProps[pname] = struct{}{}\n\t\t\t}\n\t\t}\n\n\t\tif len(s.Properties) > 0 {\n\t\t\tfor pname, pschema := range s.Properties {\n\t\t\t\tif pvalue, ok := v[pname]; ok {\n\t\t\t\t\tdelete(additionalProps, pname)\n\t\t\t\t\tif err := pschema.validate(pvalue); err != nil {\n\t\t\t\t\t\treturn addContext(escape(pname), \"properties/\"+escape(pname), err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif s.PropertyNames != nil {\n\t\t\tfor pname := range v {\n\t\t\t\tif err := s.PropertyNames.validate(pname); err != nil {\n\t\t\t\t\treturn addContext(escape(pname), \"propertyNames\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif s.RegexProperties {\n\t\t\tfor pname := range v {\n\t\t\t\tif !formats.IsRegex(pname) {\n\t\t\t\t\treturn validationError(\"\", \"patternProperty %q is not valid regex\", pname)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor pattern, pschema := range s.PatternProperties {\n\t\t\tfor pname, pvalue := range v {\n\t\t\t\tif pattern.MatchString(pname) {\n\t\t\t\t\tdelete(additionalProps, pname)\n\t\t\t\t\tif err := pschema.validate(pvalue); err != nil {\n\t\t\t\t\t\treturn addContext(escape(pname), \"patternProperties/\"+escape(pattern.String()), err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif s.AdditionalProperties != nil {\n\t\t\tif _, ok := s.AdditionalProperties.(bool); ok {\n\t\t\t\tif len(additionalProps) != 0 {\n\t\t\t\t\tpnames := make([]string, 0, len(additionalProps))\n\t\t\t\t\tfor pname := range additionalProps {\n\t\t\t\t\t\tpnames = append(pnames, strconv.Quote(pname))\n\t\t\t\t\t}\n\t\t\t\t\treturn validationError(\"additionalProperties\", \"additionalProperties %s not allowed\", strings.Join(pnames, \", \"))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tschema := s.AdditionalProperties.(*Schema)\n\t\t\t\tfor pname := range additionalProps {\n\t\t\t\t\tif pvalue, ok := v[pname]; ok {\n\t\t\t\t\t\tif err := schema.validate(pvalue); err != nil {\n\t\t\t\t\t\t\treturn addContext(escape(pname), \"additionalProperties\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor dname, dvalue := range s.Dependencies {\n\t\t\tif _, ok := v[dname]; ok {\n\t\t\t\tswitch dvalue := dvalue.(type) {\n\t\t\t\tcase *Schema:\n\t\t\t\t\tif err := dvalue.validate(v); err != nil {\n\t\t\t\t\t\treturn addContext(\"\", \"dependencies/\"+escape(dname), err)\n\t\t\t\t\t}\n\t\t\t\tcase []string:\n\t\t\t\t\tfor i, pname := range dvalue {\n\t\t\t\t\t\tif _, ok := v[pname]; !ok {\n\t\t\t\t\t\t\treturn validationError(\"dependencies/\"+escape(dname)+\"/\"+strconv.Itoa(i), \"property %q is required, if %q property exists\", pname, dname)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tcase []interface{}:\n\t\tif s.MinItems != -1 && len(v) < s.MinItems {\n\t\t\treturn validationError(\"minItems\", \"minimum %d items allowed, but found %d items\", s.MinItems, len(v))\n\t\t}\n\t\tif s.MaxItems != -1 && len(v) > s.MaxItems {\n\t\t\treturn validationError(\"maxItems\", \"maximum %d items allowed, but found %d items\", s.MaxItems, len(v))\n\t\t}\n\t\tif s.UniqueItems {\n\t\t\tfor i := 1; i < len(v); i++ {\n\t\t\t\tfor j := 0; j < i; j++ {\n\t\t\t\t\tif equals(v[i], v[j]) {\n\t\t\t\t\t\treturn validationError(\"uniqueItems\", \"items at index %d and %d are equal\", j, i)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tswitch items := s.Items.(type) {\n\t\tcase *Schema:\n\t\t\tfor i, item := range v {\n\t\t\t\tif err := items.validate(item); err != nil {\n\t\t\t\t\treturn addContext(strconv.Itoa(i), \"items\", err)\n\t\t\t\t}\n\t\t\t}\n\t\tcase []*Schema:\n\t\t\tif additionalItems, ok := s.AdditionalItems.(bool); ok {\n\t\t\t\tif !additionalItems && len(v) > len(items) {\n\t\t\t\t\treturn validationError(\"additionalItems\", \"only %d items are allowed, but found %d items\", len(items), len(v))\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor i, item := range v {\n\t\t\t\tif i < len(items) {\n\t\t\t\t\tif err := items[i].validate(item); err != nil {\n\t\t\t\t\t\treturn addContext(strconv.Itoa(i), \"items/\"+strconv.Itoa(i), err)\n\t\t\t\t\t}\n\t\t\t\t} else if sch, ok := s.AdditionalItems.(*Schema); ok {\n\t\t\t\t\tif err := sch.validate(item); err != nil {\n\t\t\t\t\t\treturn addContext(strconv.Itoa(i), \"additionalItems\", err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif s.Contains != nil {\n\t\t\tmatched := false\n\t\t\tvar causes []error\n\t\t\tfor i, item := range v {\n\t\t\t\tif err := s.Contains.validate(item); err != nil {\n\t\t\t\t\tcauses = append(causes, addContext(strconv.Itoa(i), \"\", err))\n\t\t\t\t} else {\n\t\t\t\t\tmatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !matched {\n\t\t\t\treturn validationError(\"contains\", \"contains failed\").add(causes...)\n\t\t\t}\n\t\t}\n\n\tcase string:\n\t\tif s.MinLength != -1 || s.MaxLength != -1 {\n\t\t\tlength := utf8.RuneCount([]byte(v))\n\t\t\tif s.MinLength != -1 && length < s.MinLength {\n\t\t\t\treturn validationError(\"minLength\", \"length must be >= %d, but got %d\", s.MinLength, length)\n\t\t\t}\n\t\t\tif s.MaxLength != -1 && length > s.MaxLength {\n\t\t\t\treturn validationError(\"maxLength\", \"length must be <= %d, but got %d\", s.MaxLength, length)\n\t\t\t}\n\t\t}\n\t\tif s.Pattern != nil && !s.Pattern.MatchString(v) {\n\t\t\treturn validationError(\"pattern\", \"does not match pattern %q\", s.Pattern)\n\t\t}\n\t\tif s.Format != nil && !s.Format(v) {\n\t\t\treturn validationError(\"format\", \"%q is not valid %q\", v, s.FormatName)\n\t\t}\n\n\t\tvar content []byte\n\t\tif s.Decoder != nil {\n\t\t\tb, err := s.Decoder(v)\n\t\t\tif err != nil {\n\t\t\t\treturn validationError(\"contentEncoding\", \"%q is not %s encoded\", v, s.ContentEncoding)\n\t\t\t}\n\t\t\tcontent = b\n\t\t}\n\t\tif s.MediaType != nil {\n\t\t\tif s.Decoder == nil {\n\t\t\t\tcontent = []byte(v)\n\t\t\t}\n\t\t\tif err := s.MediaType(content); err != nil {\n\t\t\t\treturn validationError(\"contentMediaType\", \"value is not of mediatype %q\", s.ContentMediaType)\n\t\t\t}\n\t\t}\n\n\tcase json.Number, float64, int, int32, int64:\n\t\tnum, _ := new(big.Float).SetString(fmt.Sprint(v))\n\t\tif s.Minimum != nil && num.Cmp(s.Minimum) < 0 {\n\t\t\treturn validationError(\"minimum\", \"must be >= %v but found %v\", s.Minimum, v)\n\t\t}\n\t\tif s.ExclusiveMinimum != nil && num.Cmp(s.ExclusiveMinimum) <= 0 {\n\t\t\treturn validationError(\"exclusiveMinimum\", \"must be > %v but found %v\", s.ExclusiveMinimum, v)\n\t\t}\n\t\tif s.Maximum != nil && num.Cmp(s.Maximum) > 0 {\n\t\t\treturn validationError(\"maximum\", \"must be <= %v but found %v\", s.Maximum, v)\n\t\t}\n\t\tif s.ExclusiveMaximum != nil && num.Cmp(s.ExclusiveMaximum) >= 0 {\n\t\t\treturn validationError(\"exclusiveMaximum\", \"must be < %v but found %v\", s.ExclusiveMaximum, v)\n\t\t}\n\t\tif s.MultipleOf != nil {\n\t\t\tif q := new(big.Float).Quo(num, s.MultipleOf); !q.IsInt() {\n\t\t\t\treturn validationError(\"multipleOf\", \"%v not multipleOf %v\", v, s.MultipleOf)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (e JwtRequirementValidationError) Key() bool { return e.key }", "func (ut *jSONDataMetaSensor) Validate() (err error) {\n\tif ut.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"name\"))\n\t}\n\tif ut.Key == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"key\"))\n\t}\n\tif ut.UnitOfMeasure == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"unitOfMeasure\"))\n\t}\n\tif ut.Ranges == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"ranges\"))\n\t}\n\tfor _, e := range ut.Ranges {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (pk PublicKey) PublicKeyJwk() JWK {\n\tentry, ok := pk[PublicKeyJwkProperty]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tjson, ok := entry.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn NewJWK(json)\n}", "func (m *OpenStackInstanceGroupV4Parameters) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (ut *JSONDataMetaStationFirmware) Validate() (err error) {\n\tif ut.Version == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"version\"))\n\t}\n\tif ut.Build == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"build\"))\n\t}\n\tif ut.Number == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"number\"))\n\t}\n\n\tif ut.Hash == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"hash\"))\n\t}\n\treturn\n}", "func (params Params) Validate() error {\n\tif err := ValidateNicknameParams(params.Nickname); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ValidateDTagParams(params.DTag); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ValidateBioParams(params.Bio); err != nil {\n\t\treturn err\n\t}\n\n\treturn ValidateOracleParams(params.Oracle)\n}" ]
[ "0.6095678", "0.569532", "0.5664185", "0.560481", "0.5594125", "0.55730027", "0.5429043", "0.5408447", "0.52270234", "0.5226582", "0.5189666", "0.5134343", "0.5122218", "0.51015174", "0.5083125", "0.50354177", "0.5019506", "0.50113547", "0.49843422", "0.4983307", "0.49801493", "0.49795255", "0.49658987", "0.49572718", "0.49542546", "0.4943839", "0.49127567", "0.48972034", "0.48912793", "0.48830804", "0.4878149", "0.48752856", "0.48711118", "0.48709372", "0.48699924", "0.48699045", "0.4866638", "0.4864562", "0.48624235", "0.48603466", "0.48594385", "0.4856705", "0.48560938", "0.48380974", "0.48355484", "0.4834099", "0.48242617", "0.4807957", "0.4806879", "0.4797226", "0.4793183", "0.47884116", "0.47846907", "0.477748", "0.47720996", "0.47680563", "0.47642246", "0.4763689", "0.47603038", "0.47591183", "0.4758333", "0.47582296", "0.47475043", "0.47470215", "0.4744737", "0.47419062", "0.47402427", "0.47299382", "0.47266665", "0.47221977", "0.47142267", "0.47133806", "0.47123873", "0.47006726", "0.46863043", "0.46760792", "0.46687737", "0.46657062", "0.46632543", "0.46626806", "0.46474347", "0.46435538", "0.463563", "0.4631561", "0.46314678", "0.4629598", "0.46291798", "0.4626049", "0.46244788", "0.46120036", "0.46079147", "0.46059427", "0.4602289", "0.46019116", "0.460055", "0.4599668", "0.45973384", "0.459603", "0.45947486", "0.4588533" ]
0.7443554
0
ValidateRSAParams checks the RSA parameters of a RSA type of JWK. If a JWK is invalid an error will be returned describing the values that causes the validation to fail.
func (jwk *Jwk) validateRSAParams() error { if jwk.E < 1 { return errors.New("RSA Required Param (E) is empty/default (<= 0)") } if jwk.N == nil { return errors.New("RSA Required Param (N) is nil") } pOk := jwk.P != nil qOk := jwk.Q != nil dpOk := jwk.Dp != nil dqOk := jwk.Dq != nil qiOk := jwk.Qi != nil othOk := len(jwk.OtherPrimes) > 0 paramsOR := pOk || qOk || dpOk || dqOk || qiOk paramsAnd := pOk && qOk && dpOk && dqOk && qiOk if jwk.D == nil { if (paramsOR || othOk) == true { return errors.New("RSA first/second prime values are present but not Private key value (D)") } } else { if paramsOR != paramsAnd { return errors.New("Not all RSA first/second prime values are present or not present") } else if !paramsOR && othOk { return errors.New("RSA other primes is included but 1st, 2nd prime variables are missing") } else if othOk { for i, oth := range jwk.OtherPrimes { if oth.Coeff == nil { return fmt.Errorf("Other Prime at index=%d, Coeff missing/nil", i) } else if oth.R == nil { return fmt.Errorf("Other Prime at index=%d, R missing/nil", i) } else if oth.Exp == nil { return fmt.Errorf("Other Prime at index=%d, Exp missing/nil", i) } } } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (priv *PKCS11PrivateKeyRSA) Validate() error {\n\tpub := priv.key.PubKey.(*rsa.PublicKey)\n\tif pub.E < 2 {\n\t\treturn errMalformedRSAKey\n\t}\n\t// The software implementation actively rejects 'large' public\n\t// exponents, in order to simplify its own implementation.\n\t// Here, instead, we expect the PKCS#11 library to enforce its\n\t// own preferred constraints, whatever they might be.\n\treturn nil\n}", "func buildJWKFromRSA(k *rsa.PublicKey) (*Key, error) {\n\treturn &Key{\n\t\tKeyType: \"RSA\",\n\t\tN: base64.RawURLEncoding.EncodeToString(k.N.Bytes()),\n\t\tE: base64.RawURLEncoding.EncodeToString(big.NewInt(int64(k.E)).Bytes()),\n\t}, nil\n}", "func (jwk *RSAPrivateJWK) PrivateRSA() (*rsa.PrivateKey, error) {\n\tmodulusBytes, err := base64.RawURLEncoding.DecodeString(jwk.ModulusBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmodulus := new(big.Int)\n\tmodulus = modulus.SetBytes(modulusBytes)\n\tpublicExponentBytes, err := base64.RawURLEncoding.DecodeString(jwk.PublicExponentBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor len(publicExponentBytes) < 8 {\n\t\tpublicExponentBytes = append(publicExponentBytes, 0)\n\t}\n\tpublicExponent := int(binary.LittleEndian.Uint64(publicExponentBytes))\n\tprivateExponentBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExponentBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateExponent := new(big.Int)\n\tprivateExponent = privateExponent.SetBytes(privateExponentBytes)\n\tfirstPrimeFactorBytes, err := base64.RawURLEncoding.DecodeString(jwk.FirstPrimeFactorBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfirstPrimeFactor := new(big.Int)\n\tfirstPrimeFactor = firstPrimeFactor.SetBytes(firstPrimeFactorBytes)\n\tsecondPrimeFactorBytes, err := base64.RawURLEncoding.DecodeString(jwk.SecondPrimeFactorBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecondPrimeFactor := new(big.Int)\n\tsecondPrimeFactor = secondPrimeFactor.SetBytes(secondPrimeFactorBytes)\n\tprivateExpModFirstPrimeMinusOneBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExpModFirstPrimeMinusOneBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateExpModFirstPrimeMinusOne := new(big.Int)\n\tprivateExpModFirstPrimeMinusOne = privateExpModFirstPrimeMinusOne.SetBytes(privateExpModFirstPrimeMinusOneBytes)\n\tprivateExpModSecondPrimeMinusOneBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExpModSecondPrimeMinusOneBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateExpModSecondPrimeMinusOne := new(big.Int)\n\tprivateExpModSecondPrimeMinusOne = privateExpModSecondPrimeMinusOne.SetBytes(privateExpModSecondPrimeMinusOneBytes)\n\tsecondPrimeInverseModFirstPrimeBytes, err := base64.RawURLEncoding.DecodeString(jwk.SecondPrimeInverseModFirstPrimeBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecondPrimeInverseModFirstPrime := new(big.Int)\n\tsecondPrimeInverseModFirstPrime = secondPrimeInverseModFirstPrime.SetBytes(secondPrimeInverseModFirstPrimeBytes)\n\trsaPrivateKey := rsa.PrivateKey{\n\t\tPublicKey: rsa.PublicKey{\n\t\t\tN: modulus,\n\t\t\tE: publicExponent,\n\t\t},\n\t\tD: privateExponent,\n\t\tPrimes: []*big.Int{firstPrimeFactor, secondPrimeFactor},\n\t\tPrecomputed: rsa.PrecomputedValues{\n\t\t\tDp: privateExpModFirstPrimeMinusOne,\n\t\t\tDq: privateExpModSecondPrimeMinusOne,\n\t\t\tQinv: secondPrimeInverseModFirstPrime,\n\t\t},\n\t}\n\treturn &rsaPrivateKey, nil\n}", "func (jwk *RSAPublicJWK) PublicRSA() (*rsa.PublicKey, error) {\n\tmodulusBytes, err := base64.RawURLEncoding.DecodeString(jwk.ModulusBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmodulus := new(big.Int)\n\tmodulus = modulus.SetBytes(modulusBytes)\n\tpublicExponentBytes, err := base64.RawURLEncoding.DecodeString(jwk.PublicExponentBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor len(publicExponentBytes) < 8 {\n\t\tpublicExponentBytes = append(publicExponentBytes, 0)\n\t}\n\tpublicExponent := int(binary.LittleEndian.Uint64(publicExponentBytes))\n\trsaPublicKey := rsa.PublicKey{\n\t\tN: modulus,\n\t\tE: publicExponent,\n\t}\n\treturn &rsaPublicKey, nil\n}", "func parseRSA(in []byte) (*rsa.PublicKey, error) {\n\tvar w struct {\n\t\tE *big.Int\n\t\tN *big.Int\n\t\tRest []byte `ssh:\"rest\"`\n\t}\n\tif err := ssh.Unmarshal(in, &w); err != nil {\n\t\treturn nil, errors.Wrap(err, \"error unmarshaling public key\")\n\t}\n\tif w.E.BitLen() > 24 {\n\t\treturn nil, errors.New(\"invalid public key: exponent too large\")\n\t}\n\te := w.E.Int64()\n\tif e < 3 || e&1 == 0 {\n\t\treturn nil, errors.New(\"invalid public key: incorrect exponent\")\n\t}\n\n\tvar key rsa.PublicKey\n\tkey.E = int(e)\n\tkey.N = w.N\n\treturn &key, nil\n}", "func prepareRSAKeys(privRSAPath, pubRSAPath string)(*rsa.PublicKey, *rsa.PrivateKey, error){\n pwd, _ := os.Getwd()\n\n verifyBytes, err := ioutil.ReadFile(pwd+pubRSAPath)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrInvalidEmptyPublicKey\n }\n\n verifiedKey, err := jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrIsNotPubRSAKey\n }\n\n signBytes, err := ioutil.ReadFile(pwd+privRSAPath)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrInvalidEmptyPrivateKey\n }\n\n signedKey, err := jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrIsNotPrivRSAKey\n }\n \n return verifiedKey, signedKey, nil\n}", "func (jwk *Jwk) Validate() error {\n\n\t// If the alg parameter is set, make sure it matches the set JWK Type\n\tif len(jwk.Algorithm) > 0 {\n\t\talgKeyType := GetKeyType(jwk.Algorithm)\n\t\tif algKeyType != jwk.Type {\n\t\t\tfmt.Errorf(\"Jwk Type (kty=%v) doesn't match the algorithm key type (%v)\", jwk.Type, algKeyType)\n\t\t}\n\t}\n\tswitch jwk.Type {\n\tcase KeyTypeRSA:\n\t\tif err := jwk.validateRSAParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase KeyTypeEC:\n\t\tif err := jwk.validateECParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase KeyTypeOct:\n\t\tif err := jwk.validateOctParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tdefault:\n\t\treturn errors.New(\"KeyType (kty) must be EC, RSA or Oct\")\n\t}\n\n\treturn nil\n}", "func ValidateParams(k, m uint8) (*Params, error) {\n\tif k < 1 {\n\t\treturn nil, errors.New(\"k cannot be zero\")\n\t}\n\n\tif m < 1 {\n\t\treturn nil, errors.New(\"m cannot be zero\")\n\t}\n\n\tif k+m > 255 {\n\t\treturn nil, errors.New(\"(k + m) cannot be bigger than Galois field GF(2^8) - 1\")\n\t}\n\n\treturn &Params{\n\t\tK: k,\n\t\tM: m,\n\t}, nil\n}", "func parseRSAKey(key ssh.PublicKey) (*rsa.PublicKey, error) {\n\tvar sshWire struct {\n\t\tName string\n\t\tE *big.Int\n\t\tN *big.Int\n\t}\n\tif err := ssh.Unmarshal(key.Marshal(), &sshWire); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal key %v: %v\", key.Type(), err)\n\t}\n\treturn &rsa.PublicKey{N: sshWire.N, E: int(sshWire.E.Int64())}, nil\n}", "func GenRSAKey(len int, password string, kmPubFile, kmPrivFile, bpmPubFile, bpmPrivFile *os.File) error {\n\tif len == rsaLen2048 || len == rsaLen3072 {\n\t\tkey, err := rsa.GenerateKey(rand.Reader, len)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writePrivKeyToFile(key, kmPrivFile, password); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := writePubKeyToFile(key.Public(), kmPubFile); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tkey, err = rsa.GenerateKey(rand.Reader, len)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writePrivKeyToFile(key, bpmPrivFile, password); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := writePubKeyToFile(key.Public(), bpmPubFile); err != nil {\n\t\t\treturn err\n\n\t\t}\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"RSA key length must be 2048 or 3084 Bits, but length is: %d\", len)\n}", "func (j *JWKS) generateRSAKey() (crypto.PrivateKey, error) {\n\tif j.bits == 0 {\n\t\tj.bits = 2048\n\t}\n\tif j.bits < 2048 {\n\t\treturn nil, errors.Errorf(`jwks: key size must be at least 2048 bit for algorithm`)\n\t}\n\tkey, err := rsa.GenerateKey(rand.Reader, j.bits)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"jwks: unable to generate RSA key\")\n\t}\n\n\treturn key, nil\n}", "func PrivateKeyValidate(priv *rsa.PrivateKey,) error", "func (jwk *Jwk) validateECParams() error {\n\tif jwk.X == nil {\n\t\treturn errors.New(\"EC Required Param (X) is nil\")\n\t}\n\tif jwk.Y == nil {\n\t\treturn errors.New(\"EC Required Param (Y) is nil\")\n\t}\n\tif jwk.Curve == nil {\n\t\treturn errors.New(\"EC Required Param (Crv) is nil\")\n\t}\n\treturn nil\n}", "func (p Params) Validate() error {\n\tif err := validateTokenCourse(p.TokenCourse); err != nil {\n\t\treturn err\n\t}\n\tif err := validateSubscriptionPrice(p.SubscriptionPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateVPNGBPrice(p.VPNGBPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateStorageGBPrice(p.StorageGBPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateBaseVPNGb(p.BaseVPNGb); err != nil {\n\t\treturn err\n\t}\n\tif err := validateBaseStorageGb(p.BaseStorageGb); err != nil {\n\t\treturn err\n\t}\n\tif err := validateCourseChangeSigners(p.CourseChangeSigners); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewRSA(encoding encodingType) (*RSA, error) {\n\tif encoding == \"\" {\n\t\tencoding = Base64\n\t}\n\treturn &RSA{Encoding: encoding}, nil\n}", "func (me *XsdGoPkgHasElem_RSAKeyValue) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_RSAKeyValue; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.RSAKeyValue.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (v *PublicParamsManager) Validate() error {\n\tpp := v.PublicParams()\n\tif pp == nil {\n\t\treturn errors.New(\"public parameters not set\")\n\t}\n\treturn pp.Validate()\n}", "func UnmarshalParams(d []byte) (pubKey *signkeys.PublicKey, pubParams *jjm.BlindingParamClient, privateParams []byte, canReissue bool, err error) {\n\tp := new(Params)\n\t_, err = asn1.Unmarshal(d, p)\n\tif err != nil {\n\t\treturn nil, nil, nil, false, err\n\t}\n\tpubkey, err := new(signkeys.PublicKey).Unmarshal(p.PublicKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, false, err\n\t}\n\treturn pubkey, &p.PublicParams, p.PrivateParams, p.CanReissue, nil\n}", "func FromRSAPrivateKey(pk *rsa.PrivateKey) *RSAParameters {\n\tvar n, e, d, p, q, dp, dq, qinv string\n\n\tn = toBase64(pk.PublicKey.N)\n\te = toBase64(pk.PublicKey.E)\n\td = toBase64(pk.D)\n\n\tfor i, prime := range pk.Primes {\n\t\tif i == 0 {\n\t\t\tp = toBase64(prime)\n\t\t} else if i == 1 {\n\t\t\tq = toBase64(prime)\n\t\t} else {\n\t\t\tfmt.Println(\"ERROR: more than 2 primes\")\n\t\t}\n\t}\n\n\tdp = toBase64(pk.Precomputed.Dp)\n\tdq = toBase64(pk.Precomputed.Dq)\n\tqinv = toBase64(pk.Precomputed.Qinv)\n\n\tmsRSA := &RSAParameters{\n\t\tModulus: n,\n\t\tExponent: e,\n\t\tD: d,\n\t\tP: p,\n\t\tQ: q,\n\t\tDP: dp,\n\t\tDQ: dq,\n\t\tInverseQ: qinv,\n\t}\n\n\treturn msRSA\n}", "func (jwk *Jwk) validateOctParams() error {\n\tif len(jwk.KeyValue) < 1 {\n\t\treturn errors.New(\"Oct Required Param KeyValue (k) is empty\")\n\t}\n\n\treturn nil\n}", "func (me *XsdGoPkgHasElems_RSAKeyValue) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_RSAKeyValue; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfor _, x := range me.RSAKeyValues {\n\t\t\tif err = x.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func NewGojwtRSA(nameserver, headerkey, privKeyPath, pubKeyPath, lenbytes string, hours time.Duration) (*Gojwt, error){\n var verifiedRSAKey *rsa.PublicKey\n var signedRSAKey *rsa.PrivateKey\n \n if privKeyPath == \"\" {\n return nil, GojwtErrInvalidEmptyPrivateKey\n } else if pubKeyPath == \"\" {\n return nil, GojwtErrInvalidEmptyPublicKey\n }\n verifiedRSAKey, signedRSAKey, err := prepareRSAKeys(privKeyPath, pubKeyPath)\n if err != nil{\n return nil, err\n }\n return &Gojwt{\n pubKeyPath: pubKeyPath,\n privKeyPath: privKeyPath,\n pubRSAKey: verifiedRSAKey,\n privRSAKey: signedRSAKey,\n headerKeyAuth: headerkey,\n numHoursDuration: hours,\n method: \"RSA\",\n lenBytes: lenbytes,\n nameServer: nameserver}, nil\n}", "func InitRSAKeys() {\n\n\tsignBytes, err := ioutil.ReadFile(privKeyPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n\n\tsignKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n\n\tverifyBytes, err := ioutil.ReadFile(pubKeyPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n\n\tverifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n}", "func RSAToPublicJWK(publicKey *rsa.PublicKey, jwkID JWKID, algo Algorithm, expirationTime *time.Time) (*RSAPublicJWK, error) {\n\tpublicX509DER, err := x509.MarshalPKIXPublicKey(publicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpublicX509DERBase64 := base64.RawStdEncoding.EncodeToString(publicX509DER)\n\tpublicThumbprint := sha1.Sum(publicX509DER)\n\tpublicThumbprintBase64 := base64.RawURLEncoding.EncodeToString(publicThumbprint[:])\n\tmodulusBase64 := base64.RawURLEncoding.EncodeToString(publicKey.N.Bytes())\n\texpBuf := new(bytes.Buffer)\n\tbinary.Write(expBuf, binary.LittleEndian, uint64(publicKey.E))\n\texpBytes := bytes.TrimRight(expBuf.Bytes(), \"\\x00\")\n\tpublicExponentBase64 := base64.RawURLEncoding.EncodeToString(expBytes)\n\tvar usage Usage\n\tswitch algo {\n\tcase RS256, PS256:\n\t\tusage = Signing\n\t\tbreak\n\tcase ROAEP, RSA15:\n\t\tusage = Encryption\n\t}\n\tpublicJWK := RSAPublicJWK{\n\t\tJWK: JWK{\n\t\t\tCertificateChainBase64: []string{publicX509DERBase64},\n\t\t\tThumbprintBase64: publicThumbprintBase64,\n\t\t\tExpirationTime: expirationTime,\n\t\t\tID: jwkID,\n\t\t\tType: rsaType,\n\t\t\tAlgorithm: algo,\n\t\t\tUsage: usage,\n\t\t},\n\t\tModulusBase64: modulusBase64,\n\t\tPublicExponentBase64: publicExponentBase64,\n\t}\n\treturn &publicJWK, nil\n}", "func GenerateRSAKey(bits int) (privateKey, publicKey []byte, err error) {\n\tprvKey, err := rsa.GenerateKey(rand.Reader, bits)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpkixb, err := x509.MarshalPKIXPublicKey(&prvKey.PublicKey)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tprivateKey = pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(prvKey),\n\t})\n\n\tpublicKey = pem.EncodeToMemory(&pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tBytes: pkixb,\n\t})\n\n\treturn\n}", "func (pr *PasswordRecord) GetKeyRSA(password string) (key rsa.PrivateKey, err error) {\n\tif pr.Type != RSARecord {\n\t\treturn key, errors.New(\"Invalid function for record type\")\n\t}\n\n\terr = pr.ValidatePassword(password)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpassKey, err := derivePasswordKey(password, pr.KeySalt)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trsaExponentPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAExp, pr.RSAKey.RSAExpIV, passKey)\n\tif err != nil {\n\t\treturn\n\t}\n\trsaExponent, err := padding.RemovePadding(rsaExponentPadded)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trsaPrimePPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAPrimeP, pr.RSAKey.RSAPrimePIV, passKey)\n\tif err != nil {\n\t\treturn\n\t}\n\trsaPrimeP, err := padding.RemovePadding(rsaPrimePPadded)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trsaPrimeQPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAPrimeQ, pr.RSAKey.RSAPrimeQIV, passKey)\n\tif err != nil {\n\t\treturn\n\t}\n\trsaPrimeQ, err := padding.RemovePadding(rsaPrimeQPadded)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tkey.PublicKey = pr.RSAKey.RSAPublic\n\tkey.D = big.NewInt(0).SetBytes(rsaExponent)\n\tkey.Primes = []*big.Int{big.NewInt(0), big.NewInt(0)}\n\tkey.Primes[0].SetBytes(rsaPrimeP)\n\tkey.Primes[1].SetBytes(rsaPrimeQ)\n\n\terr = key.Validate()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func GenerateRSA() (*rsa.PrivateKey, rsa.PublicKey) {\n\treader := rand.Reader\n\tbitSize := 2048\n\tkey, err := rsa.GenerateKey(reader, bitSize)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error generating key: %v\", err)\n\t\t// TODO: handle error\n\t}\n\treturn key, key.PublicKey\n}", "func (g *Gossiper) RSAVerifyPMSignature(msg utils.PrivateMessage) bool {\n\thash := utils.HASH_ALGO.New()\n\n\tbytes, e := json.Marshal(msg)\n\tutils.HandleError(e)\n\thash.Write(bytes)\n\thashed := hash.Sum(nil)\n\n\tpubKeyBytes, e := hex.DecodeString(msg.Origin)\n\tutils.HandleError(e)\n\tpubKey, e := x509.ParsePKCS1PublicKey(pubKeyBytes)\n\tutils.HandleError(e)\n\n\te = rsa.VerifyPKCS1v15(pubKey, utils.HASH_ALGO, hashed, msg.Signature)\n\tutils.HandleError(e)\n\tif e == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func RSAToPrivateJWK(privateKey *rsa.PrivateKey, jwkID JWKID, algo Algorithm, expirationTime *time.Time) (*RSAPrivateJWK, error) {\n\tprivateX509DER := x509.MarshalPKCS1PrivateKey(privateKey)\n\tprivateX509DERBase64 := base64.RawStdEncoding.EncodeToString(privateX509DER)\n\tprivateThumbprint := sha1.Sum(privateX509DER)\n\tprivateThumbprintBase64 := base64.RawURLEncoding.EncodeToString(privateThumbprint[:])\n\tmodulusBase64 := base64.RawURLEncoding.EncodeToString(privateKey.PublicKey.N.Bytes())\n\texpBuf := new(bytes.Buffer)\n\tbinary.Write(expBuf, binary.LittleEndian, uint64(privateKey.PublicKey.E))\n\texpBytes := bytes.TrimRight(expBuf.Bytes(), \"\\x00\")\n\tpublicExponentBase64 := base64.RawURLEncoding.EncodeToString(expBytes)\n\tprivateExponentBase64 := base64.RawURLEncoding.EncodeToString(privateKey.D.Bytes())\n\tfirstPrimeFactor := privateKey.Primes[0]\n\tfirstPrimeFactorBase64 := base64.RawURLEncoding.EncodeToString(firstPrimeFactor.Bytes())\n\tsecondPrimeFactor := privateKey.Primes[1]\n\tsecondPrimeFactorBase64 := base64.RawURLEncoding.EncodeToString(secondPrimeFactor.Bytes())\n\t// precomputed\n\tprivateExpModFirstPrimeMinusOneBase64 := base64.RawURLEncoding.EncodeToString(privateKey.Precomputed.Dp.Bytes())\n\tprivateExpModSecondPrimeMinusOneBase64 := base64.RawURLEncoding.EncodeToString(privateKey.Precomputed.Dq.Bytes())\n\tsecondPrimeInverseModFirstPrimeBase64 := base64.RawURLEncoding.EncodeToString(privateKey.Precomputed.Qinv.Bytes())\n\tvar usage Usage\n\tswitch algo {\n\tcase RS256, PS256:\n\t\tusage = Signing\n\t\tbreak\n\tcase ROAEP, RSA15:\n\t\tusage = Encryption\n\t}\n\tprivateJWK := RSAPrivateJWK{\n\t\tJWK: JWK{\n\t\t\tCertificateChainBase64: []string{privateX509DERBase64},\n\t\t\tThumbprintBase64: privateThumbprintBase64,\n\t\t\tExpirationTime: expirationTime,\n\t\t\tID: jwkID,\n\t\t\tType: rsaType,\n\t\t\tAlgorithm: algo,\n\t\t\tUsage: usage,\n\t\t},\n\t\tModulusBase64: modulusBase64,\n\t\tPublicExponentBase64: publicExponentBase64,\n\t\tPrivateExponentBase64: privateExponentBase64,\n\t\tFirstPrimeFactorBase64: firstPrimeFactorBase64,\n\t\tSecondPrimeFactorBase64: secondPrimeFactorBase64,\n\t\t// precomputed\n\t\tPrivateExpModFirstPrimeMinusOneBase64: privateExpModFirstPrimeMinusOneBase64,\n\t\tPrivateExpModSecondPrimeMinusOneBase64: privateExpModSecondPrimeMinusOneBase64,\n\t\tSecondPrimeInverseModFirstPrimeBase64: secondPrimeInverseModFirstPrimeBase64,\n\t}\n\treturn &privateJWK, nil\n}", "func validatePubKey(publicKey string) error {\n\tpk, err := hex.DecodeString(publicKey)\n\tif err != nil {\n\t\tlog.Debugf(\"validatePubKey: decode hex string \"+\n\t\t\t\"failed for '%v': %v\", publicKey, err)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\t}\n\n\tvar emptyPK [identity.PublicKeySize]byte\n\tswitch {\n\tcase len(pk) != len(emptyPK):\n\t\tlog.Debugf(\"validatePubKey: invalid size: %v\",\n\t\t\tpublicKey)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\tcase bytes.Equal(pk, emptyPK[:]):\n\t\tlog.Debugf(\"validatePubKey: key is empty: %v\",\n\t\t\tpublicKey)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\t}\n\n\treturn nil\n}", "func (session *Session) GenerateRSAKeyPair(tokenLabel string, tokenPersistent bool, expDate time.Time, bits int) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) {\n\tif session == nil || session.Ctx == nil {\n\t\treturn 0, 0, fmt.Errorf(\"session not initialized\")\n\t}\n\ttoday := time.Now()\n\tpublicKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, []byte(tokenLabel)),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, tokenPersistent),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_START_DATE, today),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_END_DATE, expDate),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, []byte{1, 0, 1}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS_BITS, bits),\n\t}\n\n\tprivateKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, []byte(tokenLabel)),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, tokenPersistent),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_START_DATE, today),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_END_DATE, expDate),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SIGN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true),\n\t}\n\n\tpubKey, privKey, err := session.Ctx.GenerateKeyPair(\n\t\tsession.Handle,\n\t\t[]*pkcs11.Mechanism{\n\t\t\tpkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_KEY_PAIR_GEN, nil),\n\t\t},\n\t\tpublicKeyTemplate,\n\t\tprivateKeyTemplate,\n\t)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\treturn pubKey, privKey, nil\n}", "func (k *Kite) RSAKey(token *jwt.Token) (interface{}, error) {\n\tk.verifyOnce.Do(k.verifyInit)\n\n\tkontrolKey := k.KontrolKey()\n\n\tif kontrolKey == nil {\n\t\tpanic(\"kontrol key is not set in config\")\n\t}\n\n\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\treturn nil, errors.New(\"invalid signing method\")\n\t}\n\n\tclaims, ok := token.Claims.(*kitekey.KiteClaims)\n\tif !ok {\n\t\treturn nil, errors.New(\"token does not have valid claims\")\n\t}\n\n\tif claims.Issuer != k.Config.KontrolUser {\n\t\treturn nil, fmt.Errorf(\"issuer is not trusted: %s\", claims.Issuer)\n\t}\n\n\treturn kontrolKey, nil\n}", "func (m *PorositySimulationParameters) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateBeamDiameter(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGeometryHeight(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGeometryLength(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGeometryWidth(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHatchSpacingValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHeaterTemperature(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLaserWattageValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLayerRotationAngle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLayerThicknessValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateMeshLayersPerLayer(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateScanSpeedValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSlicingStripeWidthValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStartingLayerAngle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (p Params) Validate() error {\n\tif err := validateActiveParam(p.Active); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateDelegatorParams(p.DelegatorDistributionSchedules); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateLPParams(p.LiquidityProviderSchedules); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateMoneyMarketParams(p.MoneyMarkets); err != nil {\n\t\treturn err\n\t}\n\n\treturn validateCheckLtvIndexCount(p.CheckLtvIndexCount)\n}", "func NewRSAPEM() ([]byte, error) {\n\tprivate, err := rsa.GenerateKey(rand.Reader, 4096)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = private.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn marshalToPEM(private)\n}", "func generateRSAKey(p *pkcs11.Ctx,\n\tsession pkcs11.SessionHandle,\n\tgun data.GUN,\n\tpassRetriever notary.PassRetriever,\n\trole data.RoleName,\n) (*LunaPrivateKey, error) {\n\n\tpublicKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS_BITS, 2048),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, []byte{0x01, 0x00, 0x01}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, fmt.Sprintf(\"notary-%s;;%s;public\", gun, role)),\n\t}\n\n\tprivateKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SIGN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, fmt.Sprintf(\"notary-%s;;%s;private\", gun, role)),\n\t}\n\n\tmechanism := []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_KEY_PAIR_GEN, nil)}\n\tpubObjectHandle, privObjectHandle, err := p.GenerateKeyPair(session, mechanism, publicKeyTemplate, privateKeyTemplate)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Failed to generate key pair: %s\", err.Error())\n\t\treturn nil, fmt.Errorf(\"Failed to generate key pair: %v\", err)\n\t}\n\n\tpubKey, _, err := getRSAKeyFromObjectHandle(p, session, pubObjectHandle)\n\tif err != nil {\n\t\tdestroyObjects(p, session, []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle})\n\t\treturn nil, err\n\t}\n\tpubID := []byte(pubKey.ID())\n\terr = setIDForObjectHandles(p, session, pubID, []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprivateKey := NewLunaPrivateKey(pubID, pubKey, data.RSAPKCS1v15Signature, passRetriever)\n\tif privateKey == nil {\n\t\tdestroyObjects(p, session, []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle})\n\t\treturn nil, errors.New(\"could not initialize new LunaPrivateKey\")\n\t}\n\n\tid := pubKey.ID()\n\n\tcertObjectHandle, err := createCertificate(p, session, gun, role, id, privateKey)\n\tif err != nil {\n\t\tdestroyObjects(p, session, []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle})\n\t\treturn nil, fmt.Errorf(\"Error creating certificate: %v\", err)\n\t}\n\n\tlogrus.Debugf(\"Setting keyID: %s\", id)\n\tprivateKey.keyID = []byte(id)\n\n\tobjectHandles := []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle, certObjectHandle}\n\n\terr = setIDsAndLabels(p, session, gun, role, id, []string{\"public\", \"private\", \"cert\"}, objectHandles)\n\tif err != nil {\n\t\tdestroyObjects(p, session, objectHandles)\n\t\treturn nil, err\n\t}\n\n\treturn privateKey, nil\n}", "func (params Params) Validate() error {\n\tif err := ValidateNicknameParams(params.Nickname); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ValidateDTagParams(params.DTag); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ValidateBioParams(params.Bio); err != nil {\n\t\treturn err\n\t}\n\n\treturn ValidateOracleParams(params.Oracle)\n}", "func GenerateRSAKeyPair(opts GenerateRSAOptions) (*RSAKeyPair, error) {\n\t//creates the private key\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, opts.Bits)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error generating private key: %s\\n\", err)\n\t}\n\n\t//validates the private key\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error validating private key: %s\\n\", err)\n\t}\n\n\t// sets up the PEM block for private key\n\tprivateKeyBlock := pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tHeaders: nil,\n\t\tBytes: x509.MarshalPKCS1PrivateKey(privateKey),\n\t}\n\n\t//check to see if we are applying encryption to this key\n\tif opts.Encryption != nil {\n\t\t//check to make sure we have a password specified\n\t\tpass := strings.TrimSpace(opts.Encryption.Password)\n\t\tif pass == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"%s\", \"need a password!\")\n\t\t}\n\t\t//check to make sure we're using a supported PEMCipher\n\t\tencCipher := opts.Encryption.PEMCipher\n\t\tif encCipher != x509.PEMCipherDES &&\n\t\t\tencCipher != x509.PEMCipher3DES &&\n\t\t\tencCipher != x509.PEMCipherAES128 &&\n\t\t\tencCipher != x509.PEMCipherAES192 &&\n\t\t\tencCipher != x509.PEMCipherAES256 {\n\t\t\treturn nil, fmt.Errorf(\"%s\", \"invalid PEMCipher\")\n\t\t}\n\t\t//encrypt the private key block\n\t\tencBlock, err := x509.EncryptPEMBlock(rand.Reader, \"RSA PRIVATE KEY\", privateKeyBlock.Bytes, []byte(pass), encCipher)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error encrypting pirvate key: %s\\n\", err)\n\t\t}\n\t\t//replaces the starting one with the one we encrypted\n\t\tprivateKeyBlock = *encBlock\n\t}\n\n\t// serializes the public key in a DER-encoded PKIX format (see docs for more)\n\tpublicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error setting up public key: %s\\n\", err)\n\t}\n\n\t// sets up the PEM block for public key\n\tpublicKeyBlock := pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tHeaders: nil,\n\t\tBytes: publicKeyBytes,\n\t}\n\n\t//returns the created key pair\n\treturn &RSAKeyPair{\n\t\tPrivateKey: string(pem.EncodeToMemory(&privateKeyBlock)),\n\t\tPublicKey: string(pem.EncodeToMemory(&publicKeyBlock)),\n\t}, nil\n}", "func ValidateOracleParams(i interface{}) error {\n\tparams, isOracleParams := i.(OracleParams)\n\tif !isOracleParams {\n\t\treturn fmt.Errorf(\"invalid parameters type: %s\", i)\n\t}\n\n\tif params.AskCount < params.MinCount {\n\t\treturn fmt.Errorf(\"invalid ask count: %d, min count: %d\", params.AskCount, params.MinCount)\n\t}\n\n\tif params.MinCount <= 0 {\n\t\treturn fmt.Errorf(\"invalid min count: %d\", params.MinCount)\n\t}\n\n\tif params.PrepareGas <= 0 {\n\t\treturn fmt.Errorf(\"invalid prepare gas: %d\", params.PrepareGas)\n\t}\n\n\tif params.ExecuteGas <= 0 {\n\t\treturn fmt.Errorf(\"invalid execute gas: %d\", params.ExecuteGas)\n\t}\n\n\terr := params.FeeAmount.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func LoadRSAKey() interfaces.RSAKey {\n\tdeferFunc := logger.LogWithDefer(\"Load RSA keys...\")\n\tdefer deferFunc()\n\n\tsignBytes, err := ioutil.ReadFile(\"config/key/private.key\")\n\tif err != nil {\n\t\tpanic(\"Error when load private key. \" + err.Error() + \". Please generate RSA keys\")\n\t}\n\tprivateKey, err := jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n\tif err != nil {\n\t\tpanic(\"Error when load private key. \" + err.Error())\n\t}\n\n\tverifyBytes, err := ioutil.ReadFile(\"config/key/public.pem\")\n\tif err != nil {\n\t\tpanic(\"Error when load public key. \" + err.Error() + \". Please generate RSA keys\")\n\t}\n\tpublicKey, err := jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n\tif err != nil {\n\t\tpanic(\"Error when load public key. \" + err.Error())\n\t}\n\n\treturn &key{\n\t\tprivate: privateKey, public: publicKey,\n\t}\n}", "func (p Params) Validate() error {\n\tif err := validateActiveParam(p.Active); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateDelegatorParams(p.DelegatorDistributionSchedules); err != nil {\n\t\treturn err\n\t}\n\n\treturn validateLPParams(p.LiquidityProviderSchedules)\n}", "func ParsePublicKey(data []byte) (SignatureValidator, error) {\r\n\ttmpKey, err := x509.ParsePKIXPublicKey(data)\r\n\trsaKey, ok := tmpKey.(*rsa.PublicKey)\r\n\tif err != nil || !ok {\r\n\t\treturn nil, errors.New(\"invalid key type, only RSA is supported\")\r\n\t}\r\n\treturn &rsaPublicKey{rsaKey}, nil\r\n}", "func CheckParams(params Setting, passwordType string) bool {\n\n\tminLen := params.MinLength\n\tminSpecials := params.MinSpecialCharacters\n\tminDigits := params.MinDigits\n\tminLowers := params.MinLowercase\n\tminUppers := params.MinUppercase\n\n\tif minLen < AbsoluteMinLen ||\n\t\tminDigits < config[passwordType].MinDigits ||\n\t\tminLowers < config[passwordType].MinLowercase ||\n\t\tminUppers < config[passwordType].MinUppercase ||\n\t\tminSpecials < config[passwordType].MinSpecialCharacters {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func parsePublicKey(pemBytes []byte) (SignatureValidator, error) {\r\n\tgob.Register(rsaPrivateKey{})\r\n\tblock, _ := pem.Decode(pemBytes)\r\n\tif block == nil {\r\n\t\treturn nil, errors.New(\"no key found\")\r\n\t}\r\n\r\n\tswitch block.Type {\r\n\tcase \"PUBLIC KEY\":\r\n\t\treturn ParsePublicKey(block.Bytes)\r\n\tdefault:\r\n\t\treturn nil, fmt.Errorf(\"unsupported key block type %q\", block.Type)\r\n\t}\r\n}", "func ValidateParameters(r *Request) {\n\tif r.ParamsFilled() {\n\t\tv := validator{errors: []string{}}\n\t\tv.validateAny(reflect.ValueOf(r.Params), \"\")\n\n\t\tif count := len(v.errors); count > 0 {\n\t\t\tformat := \"%d validation errors:\\n- %s\"\n\t\t\tmsg := fmt.Sprintf(format, count, strings.Join(v.errors, \"\\n- \"))\n\t\t\tr.Error = apierr.New(\"InvalidParameter\", msg, nil)\n\t\t}\n\t}\n}", "func ValidatePublicKey(k *ecdsa.PublicKey) bool {\n\treturn k != nil && k.X != nil && k.Y != nil && k.X.Sign() != 0 && k.Y.Sign() != 0\n}", "func Validate(accessToken string, configURL string, c *cache.Cache) (bool, error) {\n\n\tjp := new(jwtgo.Parser)\n\tjp.ValidMethods = []string{\n\t\t\"RS256\", \"RS384\", \"RS512\", \"ES256\", \"ES384\", \"ES512\",\n\t\t\"RS3256\", \"RS3384\", \"RS3512\", \"ES3256\", \"ES3384\", \"ES3512\",\n\t}\n\n\t// Validate token against issuer\n\ttt, _ := jwtgo.Parse(accessToken, func(token *jwtgo.Token) (interface{}, error) {\n\t\tif _, ok := token.Method.(*jwtgo.SigningMethodRSA); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\n\t\t// check if publicKey already in cache\n\t\tpub, found := c.Get(\"key\")\n\t\tif found {\n\t\t\t//fmt.Println(\"Using cached pubKey\")\n\t\t\treturn pub, nil\n\t\t}\n\n\t\t// Retrieve Issuer metadata from discovery endpoint\n\t\td := openid.DiscoveryDoc{}\n\n\t\treq, err := http.NewRequest(http.MethodGet, configURL, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclnt := http.Client{}\n\n\t\tr, err := clnt.Do(req)\n\t\tif err != nil {\n\t\t\tclnt.CloseIdleConnections()\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer r.Body.Close()\n\n\t\tif r.StatusCode != http.StatusOK {\n\t\t\treturn nil, errors.New(r.Status)\n\t\t}\n\t\tdec := json.NewDecoder(r.Body)\n\t\tif err = dec.Decode(&d); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Get Public Key from JWK URI\n\t\tresp, err := clnt.Get(d.JwksURI)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn nil, errors.New(resp.Status)\n\t\t}\n\n\t\tvar jwk openid.JWKS\n\t\tif err = json.NewDecoder(resp.Body).Decode(&jwk); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar kk crypto.PublicKey\n\t\tfor _, key := range jwk.Keys {\n\t\t\tkk, err = key.DecodePublicKey()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Return the rsa public key for the token validation\n\t\tpubKey := kk.(*rsa.PublicKey)\n\n\t\tc.Set(\"key\", pubKey, cache.DefaultExpiration)\n\n\t\treturn pubKey, nil\n\n\t})\n\n\t//fmt.Println(tt)\n\treturn tt.Valid, nil\n}", "func GetRSAKeys(authserver string) (map[string]rsa.PublicKey, error) {\n\tjwksURI, err := getJwksURI(authserver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting jwks_uri failed: %w\", err)\n\t}\n\n\tkeyList := jwks{}\n\terr = getJSON(jwksURI, &keyList)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetching jwks failed: %w\", err)\n\t}\n\n\tkeys := make(map[string]rsa.PublicKey)\n\n\tfor _, key := range keyList.Keys {\n\n\t\tif key.Kty == \"RSA\" {\n\n\t\t\te, err := fromB64(key.E)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"big int from E: %w\", err)\n\t\t\t}\n\t\t\tn, err := fromB64(key.N)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"big int from N: %w\", err)\n\t\t\t}\n\n\t\t\tkeys[key.Kid] = rsa.PublicKey{N: &n, E: int(e.Int64())}\n\n\t\t}\n\t}\n\n\treturn keys, nil\n\n}", "func Validate(params Params) (err error) {\n\tif params.Length <= 0 {\n\t\treturn errors.New(\"Length must be more than 0\")\n\t}\n\tif params.Square <= 0 {\n\t\treturn errors.New(\"Square must be more than 0\")\n\t}\n\treturn nil\n}", "func ValidatePublicKeyRecord(k u.Key, val []byte) error {\n\tkeyparts := bytes.Split([]byte(k), []byte(\"/\"))\n\tif len(keyparts) < 3 {\n\t\treturn errors.New(\"invalid key\")\n\t}\n\n\tpkh := u.Hash(val)\n\tif !bytes.Equal(keyparts[2], pkh) {\n\t\treturn errors.New(\"public key does not match storage key\")\n\t}\n\treturn nil\n}", "func (_WyvernExchange *WyvernExchangeCaller) ValidateOrderParameters(opts *bind.CallOpts, addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _WyvernExchange.contract.Call(opts, out, \"validateOrderParameters_\", addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n\treturn *ret0, err\n}", "func ECDH_PUBLIC_KEY_VALIDATE(W []byte) int {\n\tWP := ECP_fromBytes(W)\n\tres := 0\n\n\tr := NewBIGints(CURVE_Order)\n\n\tif WP.Is_infinity() {\n\t\tres = INVALID_PUBLIC_KEY\n\t}\n\tif res == 0 {\n\n\t\tq := NewBIGints(Modulus)\n\t\tnb := q.nbits()\n\t\tk := NewBIGint(1)\n\t\tk.shl(uint((nb + 4) / 2))\n\t\tk.add(q)\n\t\tk.div(r)\n\n\t\tfor k.parity() == 0 {\n\t\t\tk.shr(1)\n\t\t\tWP.dbl()\n\t\t}\n\n\t\tif !k.isunity() {\n\t\t\tWP = WP.mul(k)\n\t\t}\n\t\tif WP.Is_infinity() {\n\t\t\tres = INVALID_PUBLIC_KEY\n\t\t}\n\n\t}\n\treturn res\n}", "func (m *PaymentServiceItemParam) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOrigin(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentServiceItemID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ValidateParams(paramSpec []GeneratorParam, params map[string]interface{}) error {\n\tallErrs := []error{}\n\tfor ix := range paramSpec {\n\t\tif paramSpec[ix].Required {\n\t\t\tvalue, found := params[paramSpec[ix].Name]\n\t\t\tif !found || IsZero(value) {\n\t\t\t\tallErrs = append(allErrs, fmt.Errorf(\"Parameter: %s is required\", paramSpec[ix].Name))\n\t\t\t}\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(allErrs)\n}", "func RSAVerify(key *rsa.PublicKey, hash crypto.Hash, data, sig []byte) (\n\terr error) {\n\n\th := hash.New()\n\tif _, err := h.Write(data); err != nil {\n\t\treturn err\n\t}\n\treturn rsa.VerifyPKCS1v15(key, hash, h.Sum(nil), sig)\n}", "func rsaEncrypt(pemPubKey, nonce, password []byte) ([]byte, error) {\n\tpubKeyBlock, rest := pem.Decode(pemPubKey)\n\tif len(rest) > 0 {\n\t\treturn nil, fmt.Errorf(\"trailing bytes in public key: %#v\", rest)\n\t}\n\n\tpublicKey, err := x509.ParsePKCS1PublicKey(pubKeyBlock.Bytes)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse PKCS#1 public key: %w\", err)\n\t}\n\n\treturn rsa.EncryptOAEP(sha1.New(), rand.Reader, publicKey, append(nonce, []byte(password)...), []byte{})\n}", "func (m *WasmParams) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func parseAndCheckParameters(params ...Parameter) (*parameters, error) {\n\tparameters := parameters{\n\t\tlogLevel: zerolog.GlobalLevel(),\n\t}\n\tfor _, p := range params {\n\t\tif params != nil {\n\t\t\tp.apply(&parameters)\n\t\t}\n\t}\n\n\tif parameters.monitor == nil {\n\t\t// Use no-op monitor.\n\t\tparameters.monitor = &noopMonitor{}\n\t}\n\tif parameters.signer == nil {\n\t\treturn nil, errors.New(\"no signer specified\")\n\t}\n\tif parameters.lister == nil {\n\t\treturn nil, errors.New(\"no lister specified\")\n\t}\n\tif parameters.process == nil {\n\t\treturn nil, errors.New(\"no process specified\")\n\t}\n\tif parameters.walletManager == nil {\n\t\treturn nil, errors.New(\"no wallet manager specified\")\n\t}\n\tif parameters.accountManager == nil {\n\t\treturn nil, errors.New(\"no account manager specified\")\n\t}\n\tif parameters.peers == nil {\n\t\treturn nil, errors.New(\"no peers specified\")\n\t}\n\tif parameters.name == \"\" {\n\t\treturn nil, errors.New(\"no name specified\")\n\t}\n\tif parameters.id == 0 {\n\t\treturn nil, errors.New(\"no ID specified\")\n\t}\n\tif parameters.listenAddress == \"\" {\n\t\treturn nil, errors.New(\"no listen address specified\")\n\t}\n\tif len(parameters.serverCert) == 0 {\n\t\treturn nil, errors.New(\"no server certificate specified\")\n\t}\n\tif len(parameters.serverKey) == 0 {\n\t\treturn nil, errors.New(\"no server key specified\")\n\t}\n\n\treturn &parameters, nil\n}", "func CheckAlgorithmIDParamNotNULL(algorithmIdentifier []byte, requiredAlgoID asn1.ObjectIdentifier) error {\n\texpectedAlgoIDBytes, ok := RSAAlgorithmIDToDER[requiredAlgoID.String()]\n\tif !ok {\n\t\treturn errors.New(\"error algorithmID to check is not RSA\")\n\t}\n\n\talgorithmSequence := cryptobyte.String(algorithmIdentifier)\n\n\t// byte comparison of algorithm sequence and checking no trailing data is present\n\tvar algorithmBytes []byte\n\tif algorithmSequence.ReadBytes(&algorithmBytes, len(expectedAlgoIDBytes)) {\n\t\tif bytes.Compare(algorithmBytes, expectedAlgoIDBytes) == 0 && algorithmSequence.Empty() {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// re-parse to get an error message detailing what did not match in the byte comparison\n\talgorithmSequence = cryptobyte.String(algorithmIdentifier)\n\tvar algorithm cryptobyte.String\n\tif !algorithmSequence.ReadASN1(&algorithm, cryptobyte_asn1.SEQUENCE) {\n\t\treturn errors.New(\"error reading algorithm\")\n\t}\n\n\tencryptionOID := asn1.ObjectIdentifier{}\n\tif !algorithm.ReadASN1ObjectIdentifier(&encryptionOID) {\n\t\treturn errors.New(\"error reading algorithm OID\")\n\t}\n\n\tif !encryptionOID.Equal(requiredAlgoID) {\n\t\treturn fmt.Errorf(\"algorithm OID is not equal to %s\", requiredAlgoID.String())\n\t}\n\n\tif algorithm.Empty() {\n\t\treturn errors.New(\"RSA algorithm identifier missing required NULL parameter\")\n\t}\n\n\tvar nullValue cryptobyte.String\n\tif !algorithm.ReadASN1(&nullValue, cryptobyte_asn1.NULL) {\n\t\treturn errors.New(\"RSA algorithm identifier with non-NULL parameter\")\n\t}\n\n\tif len(nullValue) != 0 {\n\t\treturn errors.New(\"RSA algorithm identifier with NULL parameter containing data\")\n\t}\n\n\t// ensure algorithm is empty and no trailing data is present\n\tif !algorithm.Empty() {\n\t\treturn errors.New(\"RSA algorithm identifier with trailing data\")\n\t}\n\n\treturn errors.New(\"RSA algorithm appears correct, but didn't match byte-wise comparison\")\n}", "func validateParams(method model.Method, params map[string]interface{}) (bool, error) {\n\tvar notSpecified []model.Parameter\n\tfor _, param := range method.Parameters {\n\t\tvalue := params[param.Name]\n\t\tif param.Required {\n\t\t\tif value != \"\" && value != nil{\n\t\t\t\tactualType := getTypeName(value)\n\t\t\t\tif actualType != param.Type {\n\t\t\t\t\tmsg := fmt.Sprintf(\"Wrong argument '%s' for method '%s'. Expected type '%s', but found '%s'\", param.Name, method.Name, param.Type, actualType)\n\t\t\t\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\t\t\t\treturn false, errors.New(msg)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnotSpecified = append(notSpecified, param)\n\t\t\t}\n\t\t} else {\n\t\t\tif value != \"\" && value != nil {\n\t\t\t\t// optional parameters check\n\t\t\t\tactualType := getTypeName(value)\n\t\t\t\tif actualType != param.Type {\n\t\t\t\t\tmsg := fmt.Sprintf(\"Wrong argument '%s' for method '%s'. Expected type '%s', but found '%s'\", param.Name, method.Name, param.Type, actualType)\n\t\t\t\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\t\t\t\treturn false, errors.New(msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(notSpecified) != 0 {\n\t\tvar paramStr string = \"\"\n\t\tfor _, param := range notSpecified {\n\t\t\tparamStr += fmt.Sprintf(\"'%s', \", param.Name)\n\t\t}\n\t\tmsg := fmt.Sprintf(\"Required parameters are not provided for '%s' method. Please specify: %s\", method.Name, paramStr[:len(paramStr) - 2])\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn false, errors.New(msg)\n\t}\n\treturn true, nil\n}", "func validateServiceParameters(parameters []*Service_Parameter, data *types.Struct) error {\n\tvar errs xerrors.Errors\n\n\tfor _, p := range parameters {\n\t\tvar value *types.Value\n\t\tif data != nil && data.Fields != nil {\n\t\t\tvalue = data.Fields[p.Key]\n\t\t}\n\t\tif err := p.Validate(value); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn errs.ErrorOrNil()\n}", "func GetRSAKey(size int) (data.PrivateKey, error) {\n\traw := map[int][]byte{\n\t\t1024: []byte(`-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDJ8BO2/HOHLJgrb3srafbNRUD8r0SGNJFi5h7t4vxZ4F5oBW/4\nO2/aZmdToinyuCm0eGguK77HAsTfSHqDUoEfuInNg7pPk4F6xa4feQzEeG6P0YaL\n+VbApUdCHLBE0tVZg1SCW97+27wqIM4Cl1Tcsbb+aXfgMaOFGxlyga+a6wIDAQAB\nAoGBAKDWLH2kGMfjBtghlLKBVWcs75PSbPuPRvTEYIIMNf3HrKmhGwtVG8ORqF5+\nXHbLo7vv4tpTUUHkvLUyXxHVVq1oX+QqiRwTRm+ROF0/T6LlrWvTzvowTKtkRbsm\nmqIYEbc+fBZ/7gEeW2ycCfE7HWgxNGvbUsK4LNa1ozJbrVEBAkEA8ML0mXyxq+cX\nCwWvdXscN9vopLG/y+LKsvlKckoI/Hc0HjPyraq5Docwl2trZEmkvct1EcN8VvcV\nvCtVsrAfwQJBANa4EBPfcIH2NKYHxt9cP00n74dVSHpwJYjBnbec5RCzn5UTbqd2\ni62AkQREYhHZAryvBVE81JAFW3nqI9ZTpasCQBqEPlBRTXgzYXRTUfnMb1UvoTXS\nZd9cwRppHmvr/4Ve05yn+AhsjyksdouWxyMqgTxuFhy4vQ8O85Pf6fZeM4ECQCPp\nWv8H4thJplqSeGeJFSlBYaVf1SRtN0ndIBTCj+kwMaOMQXiOsiPNmfN9wG09v2Bx\nYVFJ/D8uNjN4vo+tI8sCQFbtF+Qkj4uSFDZGMESF6MOgsGt1R1iCpvpMSr9h9V02\nLPXyS3ozB7Deq26pEiCrFtHxw2Pb7RJO6GEqH7Dg4oU=\n-----END RSA PRIVATE KEY-----`),\n\t\t2048: []byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAtKGse3BcxXAp5OkLGYq0HfDcCvgag3R/9e8pHUGsJhkSZFrn\nZWAsAVFKSYaYItf1D/g3izqVDMtMpXZ1chNzaRysnbrb/q7JTbiGzXo9FcshyUc9\ntcB60wFbvsXE2LaxZcKNxLYXbOvf+tdg/P07oPG24fzYI4+rbZ1wyoORbT1ys33Z\nhHyifFvO7rbe69y3HG+xbp7yWYAR4e8Nw9jX8/9sGslAV9vEXOdNL3qlcgsYRGDU\nDsUJsnWaMzjstvUxb8mVf9KG2W039ucgaXgBW/jeP3F1VSYFKLd03LvuJ8Ir5E0s\ncWjwTd59nm0XbbRI3KiBGnAgrJ4iK07HrUkpDQIDAQABAoIBAHfr1k1lfdH+83Fs\nXtgoRAiUviHyMfgQQlwO2eb4kMgCYTmLOJEPVmfRhlZmK18GrUZa7tVaoVYLKum3\nSaXg0AB67wcQ5bmiZTdaSPTmMOPlJpsw1wFxtpmcD0MKnfOa5w++KMzub4L63or0\nrwmHPi1ODLLgYMbLPW7a1eU9kDFLOnx3RRy9a29hQXxGsRYetrIbKmeDi6c+ndQ8\nI5YWObcixxl5GP6CTnEugV7wd2JmXuQRGFdopUwQESCD9VkxDSevQBSPoyZKHxGy\n/d3jf0VNlvwsxhD3ybhw8jTN/cmm2LWmP4jylG7iG7YRPVaW/0s39IZ9DnNDwgWB\n03Yk2gECgYEA44jcSI5kXOrbBGDdV+wTUoL24Zoc0URX33F15UIOQuQsypaFoRJ6\nJ23JWEZN99aquuo1+0BBSfiumbpLwSwfXi0nL3oTzS9eOp1HS7AwFGd/OHdpdMsC\nw2eInRwCh4GrEf508GXo+tSL2NS8+MFVAG2/SjEf06SroQ/rQ87Qm0ECgYEAyzqr\n6YvbAnRBy5GgQlTgxR9r0U8N7lM9g2Tk8uGvYI8zu/Tgia4diHAwK1ymKbl3lf95\n3NcHR+ffwOO+nnfFCvmCYXs4ggRCkeopv19bsCLkfnTBNTxPFh6lyLEnn3C+rcCe\nZAkKLrm8BHGviPIgn0aElMQAbhJxTWfClw/VVs0CgYAlDhfZ1R6xJypN9zx04iRv\nbpaoPQHubrPk1sR9dpl9+Uz2HTdb+PddznpY3vI5p4Mcd6Ic7eT0GATPUlCeAAKH\nwtC74aSx6MHux8hhoiriV8yXNJM/CwTDL+xGsdYTnWFvx8HhmKctmknAIT05QbsH\nG9hoS8HEJPAyhbYpz9eXQQKBgQCftPXQTPXJUe86uLBGMEmK34xtKkD6XzPiA/Hf\n5PdbXG39cQzbZZcT14YjLWXvOC8AE4qCwACaw1+VR+ROyDRy0W1iieD4W7ysymYQ\nXDHDk0gZEEudOE22RlNmCcHnjERsawiN+ISl/5P/sg+OASkdwd8CwZzM43VirP3A\nlNLEqQKBgHqj85n8ew23SR0GX0W1PgowaCHHD1p81y2afs1x7H9R1PNuQsTXKnpf\nvMiG7Oxakj4WDC5M5KsHWqchqKDycT+J1BfLI58Sf2qo6vtaV+4DARNgzcG/WB4b\nVnpsczK/1aUH7iBexuF0YqdPQwzpSvrY0XZcgCFQ52JDn3vjblhX\n-----END RSA PRIVATE KEY-----`),\n\t\t4096: []byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIJKgIBAAKCAgEAw28m5P1j7Rv1Wy4AicNkR4DXVxJXlPma+c5U/KJzFg0emiyx\nfkGQnUWeFofOI3rgrgK3deQ6yspgavTKWnHs4YeAz2egMSDsobI1OAP7ocPrFhYc\nFB+pTLXm1CkvyxIt9UWPxgc4CGiO1wIlfL8PpFg5vur7sAqbzxKeFx8GikbjFbQg\nd/RMFYeQacuimo9yea9DqjELvwewby3iP81FP9JJKiM3G6+7BiI+pJv65dNLbBUY\nHgKrmBHYg7WVSdmR7pZucEDoBqJcjc+kIHDGMH2vndWhIybEpHxxXdW+DrnPlhGV\n/hqKWw5fqJvhdh0OR1yefCCva0m6mZAKardzqxndFJqJbs1ehXg0luijVRYXaUpP\nuvHaKj+QV2R/PJWxkCLZLFSEAE156QT1sfY5FOh8rYBWBNrJk7X6qUTaF7Jfeo3H\nCF94ioP0Up8bohIu0lH8WPfTxdZ2lvUGSteMEYWBSbKhcbSCOP6a2K4/znSNl/J3\nLV/YcbmuSb7sAp+sZXELarYg/JMNVP4Vo2vh5S4ZCPYtk2or2WY27rMHWQ1vIhjB\nxjuSKzpLx9klusoTHB3wD6K7FwyT4JLUTfxGloSSpOuLG5yp9dAL/i8WHY20w6jP\n7ZYOss6OsQzp5ZqpW5M/0z60NsEOhfFXd1bxPYUP7//6N14XHTg31fg7vykCAwEA\nAQKCAgEAnn+j/K0ggKlfGL67Qv9Lcc4lVwGSNEknDhfvxyB809J6EjHTFYFZJqPS\nbZVgclfypk2fuqYJpHPzNGspPacNpW7+4ba6LX31S8I69R4N0wkQvM3bodp3tLYF\n6eUpVLl+ul/bFZC/OdqKlgewnXZa2j+PPa5Xx1MjQBJqUnggFr8c5no6pu5jUkaq\nsZKsYkuaXOPurbWvQBOdXN3Kk1IIKpWCLwF2bSbdOEFHqrqyBfiSP6rv707dGazH\nezImTEl+2A/6q2GIi/DbvUs8Ye70XVlht1ENqXOEoZ4nVyHFTS4XFC9ZBUdDFEwY\n+qbJeMBh1zBffG4JtqqKAobWW+xCioKVn2ArSzh1/2Q5652yeVVhR+GTSK2yd1uE\n5a5Pc65C8LCRNTz0iHEUESfVO5QnUq9bWShgm0H/LQ3sk8gzQjuBS5Ya523vOl1w\nxRUYxjEFW0382BrG0dn+WE2Yn0z5i2X9+WRgiKrh8tNZ+wNGN3MtZ5mloHsocH4N\nuUIZ6J0x/YruW126b0XA6fE+3taQDmJ4Qj/puU7+sFCs7MXUtd3tClEH1NUalH0T\n5awjZcJnMmGVmtGGfP1DtuEd082mIUuvKZj1vCEiSavwK3JDVl5goxlDpvEgdh2X\no1eSIMMZb6FG5h3dsyyMpXaRobgL+qbLm0XDGwtiIu+d5BE8OQECggEBAPL+FwUB\n2w4bRGzmDNRJm3oDcDlBROn5nFpzzSuXRA8zSrJbNB9s55EqTnZw7xVNa6nUxi9C\nd2Hqcbp9HD8EezlbMWJ4LASlYPzdBpAo5eyvK8YccE1QjlGlP7ZOf4+ekwlreqZ4\nfhRb4r/q49eW3aAWbJPu67MYu1iBMpdINZpMzDdE1wKjRXWu0j7Lr3SXjzgjD94E\nG+4VvJ0xc8WgjM9YSLxFN/5VZd+us7l6V18vOrdPDpAlJuTkmSpP0Xx4oUKJs7X+\n84CEB47GgUqf3bPadS8XRC2slEA+or5BJnPTVQ5YgTeWZE2kD3tLDOVHE7gLmV61\njYy2Icm+sosnfeECggEBAM3lVYO3D5Cw9Z4CkewrzMUxd7sSd5YqHavfEjvFc4Pk\n6Q6hsH1KR4Ai6loB8ugSz2SIS6KoqGD8ExvQxWy4AJf/n39hxb8/9IJ3b6IqBs64\n+ELJ8zw3QheER93FwK/KbawzLES9RkdpvDBSHFFfbGxjHpm+quQ8JcNIHTg43fb+\nTWe+mXYSjIWVCNssHBl5LRmkly37DxvBzu9YSZugESr80xSMDkBmWnpsq2Twh3q4\n2yP6jgfaZtV9AQQ01jkPgqpcuSoHm2qyqfiIr3LkA34OQmzWpyPn17If1DSJhlXo\nClSSl5Guqt9r0ifuBcMbl69OyAgpGr4N5sFxRk0wGkkCggEBAMt34hSqSiAUywYY\n2DNGc28GxAjdU3RMNBU1lF5k6nOD8o9IeWu7CGhwsYTR6hC/ZGCwL0dRc5/E7XhH\n3MgT247ago6+q7U0OfNirGU4Kdc3kwLvu0WyJ4nMQn5IWt4K3XpsyiXtDT3E9yjW\n6fQTev7a6A4zaJ/uHKnufUtaBrBukC3TcerehoIVYi185y1M33sVOOsiK7T/9JD3\n4MZiOqZAeZ9Uop9QKN7Vbd7ox5KHfLYT99DRmzDdDjf04ChG5llN7vJ9Sq6ZX665\nH3g6Ry2bxrYo2EkakoT9Lc77xNQF6Nn7WDAQuWqd7uzBmkm+a4+X/tPkWGOz+rTw\n/pYw+mECggEBAKQiMe1yPUJHD0YLHnB66h44tQ24RwS6RjUA+vQTD2cRUIiNdLgs\nQptvOgrOiuleNV4bGNBuSuwlhsYhw4BLno2NBYTyWEWBolVvCNrpTcv1wFLd0r0p\n/9HnbbLpNhXs9UjU8nFJwYCkVZTfoBtuSmyNB5PgXzLaj/AAyOpMywVe7C3Lz2JE\nnyjOCeVOYIgeBUnv32SUQxMJiQFcDDG3hHgUW+CBVcsYzP/TKT6qUBYQzwD7d8Xi\n4R9HK0xDIpMSPkO47xMGRWrlSoIJ1HNuOSqAC4vgAhWpeFVS8kN/bkuFUtbglVtZ\nNnYs6bdTE9zZXi4uS1/WBK+FPXLv7e8SbaECggEAI2gTDuCm5kVoVJhGzWA5/hmB\nPAUhSQpMHrT8Em4cXss6Q07q9A2l8NuNrZt6kNhwagdng7v7NdPY3ZBl/ntmKmZN\nxWUKzQCtIddW6Z/veO86F15NyBBZFXIOhzvwnrTtS3iX0JP0dlTZTv/Oe3DPk3aq\nsFJtHM6s44ZBYYAgzSAxTdl+80oGmtdrGnSRfRmlav1kjWLAKurXw8FTl9rKgGNA\nUUv/jGSe1DxnEMvtoSwQVjcS0im57vW0x8LEz5eTWMYwkvxGHm0/WU2Yb0I6mL4j\nPWrHwwPdRoF/cPNWa7eTsZBKdVN9iNHSu7yE9owXyHSpesI1IZf8Zq4bqPNpaA==\n-----END RSA PRIVATE KEY-----`),\n\t}\n\tblock, _ := pem.Decode(raw[size])\n\tkey, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprivKey, err := utils.RSAToPrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn privKey, nil\n}", "func (_WyvernExchange *WyvernExchangeSession) ValidateOrderParameters(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) (bool, error) {\n\treturn _WyvernExchange.Contract.ValidateOrderParameters(&_WyvernExchange.CallOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n}", "func (o *GetSlashingParametersOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateResult(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func NewRSAKeyPair() (*RSAKeyPair, error) {\n\treader := rand.Reader\n\tprivateKey, err := rsa.GenerateKey(reader, bitSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newRSAKeyPair(privateKey, &privateKey.PublicKey)\n}", "func encryptRSARecord(newRec *PasswordRecord, rsaPriv *rsa.PrivateKey, passKey []byte) (err error) {\n\tif newRec.RSAKey.RSAExpIV, err = symcrypt.MakeRandom(16); err != nil {\n\t\treturn\n\t}\n\n\tpaddedExponent := padding.AddPadding(rsaPriv.D.Bytes())\n\tif newRec.RSAKey.RSAExp, err = symcrypt.EncryptCBC(paddedExponent, newRec.RSAKey.RSAExpIV, passKey); err != nil {\n\t\treturn\n\t}\n\n\tif newRec.RSAKey.RSAPrimePIV, err = symcrypt.MakeRandom(16); err != nil {\n\t\treturn\n\t}\n\n\tpaddedPrimeP := padding.AddPadding(rsaPriv.Primes[0].Bytes())\n\tif newRec.RSAKey.RSAPrimeP, err = symcrypt.EncryptCBC(paddedPrimeP, newRec.RSAKey.RSAPrimePIV, passKey); err != nil {\n\t\treturn\n\t}\n\n\tif newRec.RSAKey.RSAPrimeQIV, err = symcrypt.MakeRandom(16); err != nil {\n\t\treturn\n\t}\n\n\tpaddedPrimeQ := padding.AddPadding(rsaPriv.Primes[1].Bytes())\n\tnewRec.RSAKey.RSAPrimeQ, err = symcrypt.EncryptCBC(paddedPrimeQ, newRec.RSAKey.RSAPrimeQIV, passKey)\n\treturn\n}", "func IsRsaPublicKey(str string, keylen int) bool {\n\tbb := bytes.NewBufferString(str)\n\tpemBytes, err := ioutil.ReadAll(bb)\n\tif err != nil {\n\t\treturn false\n\t}\n\tblock, _ := pem.Decode(pemBytes)\n\tif block != nil && block.Type != \"PUBLIC KEY\" {\n\t\treturn false\n\t}\n\tvar der []byte\n\n\tif block != nil {\n\t\tder = block.Bytes\n\t} else {\n\t\tder, err = base64.StdEncoding.DecodeString(str)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tkey, err := x509.ParsePKIXPublicKey(der)\n\tif err != nil {\n\t\treturn false\n\t}\n\tpubkey, ok := key.(*rsa.PublicKey)\n\tif !ok {\n\t\treturn false\n\t}\n\tbitlen := len(pubkey.N.Bytes()) * 8\n\treturn bitlen == int(keylen)\n}", "func (m *KeyPair) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with Resource\n\tif err := m.Resource.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGroup(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (p *Provider) GetRSAKeys() (key *rsa.PrivateKey, err error) {\n\tif p.key == nil {\n\t\treturn nil, ErrKeyRequired\n\t}\n\n\tvar ok bool\n\tif key, ok = p.key.(*rsa.PrivateKey); !ok {\n\t\treturn nil, fmt.Errorf(\"private key is not RSA but is %T\", p.key)\n\t}\n\n\tvar cert *x509.Certificate\n\tif cert, err = p.GetLeafCertificate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey.PublicKey = *cert.PublicKey.(*rsa.PublicKey)\n\treturn key, nil\n}", "func getRSAKeyFromObjectHandle(p *pkcs11.Ctx, session pkcs11.SessionHandle, objectHandle pkcs11.ObjectHandle) (*data.RSAPublicKey, data.RoleName, error) {\n\n\tattrTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS, []byte{0}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, []byte{0}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, []byte{0}),\n\t}\n\n\tattr, err := p.GetAttributeValue(session, objectHandle, attrTemplate)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Failed to get Attribute for: %d\", objectHandle)\n\t\treturn nil, \"\", fmt.Errorf(\"Failed to get attribute %d: %v\", objectHandle, err)\n\t}\n\n\trole := data.CanonicalRootRole\n\n\tvar modulus []byte\n\tvar exponent []byte\n\tfor _, a := range attr {\n\t\tif a.Type == pkcs11.CKA_MODULUS {\n\t\t\tmodulus = a.Value\n\t\t} else if a.Type == pkcs11.CKA_PUBLIC_EXPONENT {\n\t\t\texponent = a.Value\n\t\t} else if a.Type == pkcs11.CKA_LABEL {\n\t\t\tsplit := strings.Split(string(a.Value), \";\")\n\t\t\tif len(split) != 4 {\n\t\t\t\treturn nil, \"\", fmt.Errorf(\"Key contained invalid label.\")\n\t\t\t}\n\t\t\trole = data.RoleName(split[2])\n\t\t}\n\t}\n\n\trsaPubKey, err := getRSAPublicKey(modulus, exponent)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tpubBytes, err := x509.MarshalPKIXPublicKey(rsaPubKey)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Failed to Marshal RSA public key\")\n\t\treturn nil, \"\", err\n\t}\n\treturn data.NewRSAPublicKey(pubBytes), role, nil\n}", "func (_WyvernExchange *WyvernExchangeCallerSession) ValidateOrderParameters(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) (bool, error) {\n\treturn _WyvernExchange.Contract.ValidateOrderParameters(&_WyvernExchange.CallOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n}", "func MustRSAKey() *rsa.PrivateKey {\n\tkey, err := rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn key\n}", "func (m *GPGKey) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEmails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateExpires(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSubsKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (lib *PKCS11Lib) GenerateRSAKeyPair(bits int, purpose KeyPurpose) (*PKCS11PrivateKeyRSA, error) {\n\treturn lib.GenerateRSAKeyPairOnSlot(lib.Slot.id, nil, nil, bits, purpose)\n}", "func GenerateRSA(bitSize int) (*rsa.PrivateKey, error) {\n\tif bitSize <= 1024 {\n\t\treturn nil, ErrInsecureKeyBitSize\n\t}\n\n\treturn rsa.GenerateKey(rand.Reader, bitSize)\n}", "func fromRSAKey(key ssh.PublicKey) (security.PublicKey, error) {\n\tk, err := parseRSAKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn security.NewRSAPublicKey(k), nil\n}", "func (r *Client) validateTemplateParams(t *Template, params []*Parameter) error {\n\tmissing := map[string]interface{}{}\n\t// copy all wanted params into missing\n\tfor k, v := range t.Parameters {\n\t\tmissing[k] = v\n\t}\n\t// remove items from missing list as found\n\tfor wantedKey := range t.Parameters {\n\t\tfor _, param := range params {\n\t\t\tif param.ParameterKey == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// phew found it\n\t\t\tif *param.ParameterKey == wantedKey {\n\t\t\t\tdelete(missing, wantedKey)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\t// if any left, then we have an issue\n\tif len(missing) > 0 {\n\t\tkeys := []string{}\n\t\tfor k := range missing {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tkeysCSV := strings.Join(keys, \",\")\n\t\treturn fmt.Errorf(\"missing required input parameters: [%s]\", keysCSV)\n\t}\n\treturn nil\n}", "func (lib *PKCS11Lib) exportRSAPublicKey(session pkcs11.SessionHandle, pubHandle pkcs11.ObjectHandle) (crypto.PublicKey, error) {\n\tlogger.Tracef(\"session=0x%X, obj=0x%X\", session, pubHandle)\n\ttemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS, nil),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, nil),\n\t}\n\texported, err := lib.Ctx.GetAttributeValue(session, pubHandle, template)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tvar modulus = new(big.Int)\n\tmodulus.SetBytes(exported[0].Value)\n\tvar bigExponent = new(big.Int)\n\tbigExponent.SetBytes(exported[1].Value)\n\tif bigExponent.BitLen() > 32 {\n\t\treturn nil, errors.WithStack(errMalformedRSAKey)\n\t}\n\tif bigExponent.Sign() < 1 {\n\t\treturn nil, errors.WithStack(errMalformedRSAKey)\n\t}\n\texponent := int(bigExponent.Uint64())\n\tresult := rsa.PublicKey{\n\t\tN: modulus,\n\t\tE: exponent,\n\t}\n\tif result.E < 2 {\n\t\treturn nil, errors.WithStack(errMalformedRSAKey)\n\t}\n\treturn &result, nil\n}", "func (k *KeyInstanceCert) CreateRSAInstance() {\n\tprivateKey, _ := rsa.GenerateKey(rand.Reader, 4096)\n\tk.PrivateKey = privateKey //implicit durch compiler (*k).PrivateKey\n\tpublicKey := privateKey.PublicKey\n\tk.PublicKey = publicKey\n\n\tprivKeyPEM := new(bytes.Buffer)\n\tpem.Encode(privKeyPEM, &pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(privateKey),\n\t})\n\tk.PrivateKeyPEM = privKeyPEM\n\n\tpublicKeyPEM := new(bytes.Buffer)\n\tpem.Encode(publicKeyPEM, &pem.Block{\n\t\tType: \"RSA PUBLIC KEY\",\n\t\tBytes: x509.MarshalPKCS1PublicKey(&publicKey),\n\t})\n\tk.PublicKeyPEM = publicKeyPEM\n\n}", "func (asap *ASAP) Validate(jwt jwt.JWT, publicKey cr.PublicKey) error {\n\theader := jwt.(jws.JWS).Protected()\n\tkid := header.Get(KeyID).(string)\n\talg := header.Get(algorithm).(string)\n\n\tsigningMethod, err := getSigningMethod(alg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn jwt.Validate(publicKey, signingMethod, validator.GenerateValidator(kid, asap.ServiceID))\n}", "func (o *UIParameter) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := elemental.ValidateRequiredString(\"key\", o.Key); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidateRequiredString(\"type\", string(o.Type)); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"type\", string(o.Type), []string{\"Boolean\", \"Checkbox\", \"CVSSThreshold\", \"DangerMessage\", \"Duration\", \"Enum\", \"Endpoint\", \"FileDrop\", \"Float\", \"FloatSlice\", \"InfoMessage\", \"Integer\", \"IntegerSlice\", \"JSON\", \"List\", \"Message\", \"Namespace\", \"Password\", \"String\", \"StringSlice\", \"Switch\", \"TagsExpression\", \"Title\", \"WarningMessage\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\t// Custom object validation.\n\tif err := ValidateUIParameters(o); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (pk PublicKey) JWK() JWK {\n\tentry, ok := pk[JwkProperty]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tjson, ok := entry.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn NewJWK(json)\n}", "func (c *Coffin) encryptRSA(data []byte) ([]byte, error) {\n\n\t// If public key is not supplied, return error\n\tif len(c.Opts.PubKey) == 0 {\n\t\treturn emptyByte, ErrNoPubKey\n\t}\n\n\t// Unmarshall the RSA public key\n\trsaKey, err := UnmarshalPublicKey(bytes.NewBuffer(c.Opts.PubKey))\n\tif err != nil {\n\t\treturn emptyByte, err\n\t}\n\n\t// Encrypt the data\n\thash := sha512.New()\n\tciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, rsaKey, data, nil)\n\tif err != nil {\n\t\treturn emptyByte, err\n\t}\n\n\t// Return the data\n\treturn ciphertext, nil\n}", "func (r *RSA) Init() {\n\tlog.Infof(\"Generating %d bit RSA key...\", RSA_KEY_LENGTH)\n\n\t// generate RSA key\n\tvar pKey, err = rsa.GenerateKey(rand.Reader, RSA_KEY_LENGTH)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating RSA key:\" + err.Error())\n\t}\n\n\tr.privateKey = pKey\n\n\t// encode key to ASN.1 PublicKey Type\n\tvar key, err2 = asn1.Marshal(r.privateKey.PublicKey)\n\tif err2 != nil {\n\t\tlog.Fatal(\"Error encoding Public RSA key:\" + err2.Error())\n\t}\n\n\t// move public key to array\n\tcopy(r.PublicKey[:], key)\n}", "func validateParams() {\n\tif domain == \"\" {\n\t\tprintAndExit(\"-domain is required!\", true)\n\t}\n\n\tif passLength < 1 {\n\t\tprintAndExit(\"-password-length must be a positive number!\", true)\n\t}\n\n\tif passLength < 8 {\n\t\tfmt.Println(\"WARN: -password-length is too short. We will grant your wish, but this might be a security risk. Consider using longer password.\", false)\n\t}\n}", "func NewRSAKeyPair(name ndn.Name) (PrivateKey, PublicKey, error) {\n\tkeyName := ToKeyName(name)\n\tkey, e := rsa.GenerateKey(rand.Reader, 2048)\n\tif e != nil {\n\t\treturn nil, nil, e\n\t}\n\tpvt, e := NewRSAPrivateKey(keyName, key)\n\tif e != nil {\n\t\treturn nil, nil, e\n\t}\n\tpub, e := NewRSAPublicKey(keyName, &key.PublicKey)\n\tif e != nil {\n\t\treturn nil, nil, e\n\t}\n\treturn pvt, pub, e\n}", "func EncodePrivateKey(key crypto.PrivateKey) (jwk *JWK, err error) {\n\tjwk = new(JWK)\n\tswitch k := key.(type) {\n\tcase *ecdsa.PrivateKey:\n\t\tjwk.populateECPublicKey(&k.PublicKey)\n\t\tjwk.D = b64.EncodeToString(k.D.Bytes())\n\n\tcase *rsa.PrivateKey:\n\t\tjwk.populateRSAPublicKey(&k.PublicKey)\n\t\tjwk.D = b64.EncodeToString(k.D.Bytes())\n\t\tif len(k.Primes) < 2 || len(k.Precomputed.CRTValues) != len(k.Primes)-2 {\n\t\t\treturn nil, errors.New(\"jwk: invalid RSA primes number\")\n\t\t}\n\t\tjwk.P = b64.EncodeToString(k.Primes[0].Bytes())\n\t\tjwk.Q = b64.EncodeToString(k.Primes[1].Bytes())\n\t\tjwk.Dp = b64.EncodeToString(k.Precomputed.Dp.Bytes())\n\t\tjwk.Dq = b64.EncodeToString(k.Precomputed.Dq.Bytes())\n\t\tjwk.Qi = b64.EncodeToString(k.Precomputed.Qinv.Bytes())\n\n\t\tif len(k.Primes) > 2 {\n\t\t\tjwk.Oth = make([]*RSAPrime, len(k.Primes)-2)\n\t\t\tfor i := 0; i < len(k.Primes)-2; i++ {\n\t\t\t\tjwk.Oth[i] = &RSAPrime{\n\t\t\t\t\tR: b64.EncodeToString(k.Primes[i+2].Bytes()),\n\t\t\t\t\tD: b64.EncodeToString(k.Precomputed.CRTValues[i].Exp.Bytes()),\n\t\t\t\t\tT: b64.EncodeToString(k.Precomputed.CRTValues[i].Coeff.Bytes()),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"jwk: unknown private key type: %T\", key)\n\t}\n\n\treturn jwk, nil\n}", "func TestPublicKey(t *testing.T) {\n\tconst jsonkey = `{\"keys\":\n [\n {\"kty\":\"EC\",\n \"crv\":\"P-256\",\n \"x\":\"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4\",\n \"y\":\"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM\",\n \"use\":\"enc\",\n \"kid\":\"1\"},\n\n {\"kty\":\"RSA\",\n \"n\": \"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw\",\n \"e\":\"AQAB\",\n \"alg\":\"RS256\",\n \"kid\":\"2011-04-29\"}\n ]\n }`\n\n\tjwt, err := Unmarshal([]byte(jsonkey))\n\tif err != nil {\n\t\tt.Fatal(\"Unmarshal: \", err)\n\t} else if len(jwt.Keys) != 2 {\n\t\tt.Fatalf(\"Expected 2 keys, got %d\", len(jwt.Keys))\n\t}\n\n\tkeys := make([]crypto.PublicKey, len(jwt.Keys))\n\tfor ii, jwt := range jwt.Keys {\n\t\tkeys[ii], err = jwt.DecodePublicKey()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to decode key %d: %v\", ii, err)\n\t\t}\n\t}\n\n\tif key0, ok := keys[0].(*ecdsa.PublicKey); !ok {\n\t\tt.Fatalf(\"Expected ECDSA key[0], got %T\", keys[0])\n\t} else if key1, ok := keys[1].(*rsa.PublicKey); !ok {\n\t\tt.Fatalf(\"Expected RSA key[1], got %T\", keys[1])\n\t} else if key0.Curve != elliptic.P256() {\n\t\tt.Fatal(\"Key[0] is not using P-256 curve\")\n\t} else if !bytes.Equal(key0.X.Bytes(), []byte{0x30, 0xa0, 0x42, 0x4c, 0xd2,\n\t\t0x1c, 0x29, 0x44, 0x83, 0x8a, 0x2d, 0x75, 0xc9, 0x2b, 0x37, 0xe7, 0x6e, 0xa2,\n\t\t0xd, 0x9f, 0x0, 0x89, 0x3a, 0x3b, 0x4e, 0xee, 0x8a, 0x3c, 0xa, 0xaf, 0xec, 0x3e}) {\n\t\tt.Fatalf(\"Bad key[0].X, got %v\", key0.X.Bytes())\n\t} else if !bytes.Equal(key0.Y.Bytes(), []byte{0xe0, 0x4b, 0x65, 0xe9, 0x24,\n\t\t0x56, 0xd9, 0x88, 0x8b, 0x52, 0xb3, 0x79, 0xbd, 0xfb, 0xd5, 0x1e, 0xe8,\n\t\t0x69, 0xef, 0x1f, 0xf, 0xc6, 0x5b, 0x66, 0x59, 0x69, 0x5b, 0x6c, 0xce,\n\t\t0x8, 0x17, 0x23}) {\n\t\tt.Fatalf(\"Bad key[0].Y, got %v\", key0.Y.Bytes())\n\t} else if key1.E != 0x10001 {\n\t\tt.Fatalf(\"Bad key[1].E: %d\", key1.E)\n\t} else if !bytes.Equal(key1.N.Bytes(), []byte{0xd2, 0xfc, 0x7b, 0x6a, 0xa, 0x1e,\n\t\t0x6c, 0x67, 0x10, 0x4a, 0xeb, 0x8f, 0x88, 0xb2, 0x57, 0x66, 0x9b, 0x4d, 0xf6,\n\t\t0x79, 0xdd, 0xad, 0x9, 0x9b, 0x5c, 0x4a, 0x6c, 0xd9, 0xa8, 0x80, 0x15, 0xb5,\n\t\t0xa1, 0x33, 0xbf, 0xb, 0x85, 0x6c, 0x78, 0x71, 0xb6, 0xdf, 0x0, 0xb, 0x55,\n\t\t0x4f, 0xce, 0xb3, 0xc2, 0xed, 0x51, 0x2b, 0xb6, 0x8f, 0x14, 0x5c, 0x6e, 0x84,\n\t\t0x34, 0x75, 0x2f, 0xab, 0x52, 0xa1, 0xcf, 0xc1, 0x24, 0x40, 0x8f, 0x79, 0xb5,\n\t\t0x8a, 0x45, 0x78, 0xc1, 0x64, 0x28, 0x85, 0x57, 0x89, 0xf7, 0xa2, 0x49, 0xe3,\n\t\t0x84, 0xcb, 0x2d, 0x9f, 0xae, 0x2d, 0x67, 0xfd, 0x96, 0xfb, 0x92, 0x6c, 0x19,\n\t\t0x8e, 0x7, 0x73, 0x99, 0xfd, 0xc8, 0x15, 0xc0, 0xaf, 0x9, 0x7d, 0xde, 0x5a,\n\t\t0xad, 0xef, 0xf4, 0x4d, 0xe7, 0xe, 0x82, 0x7f, 0x48, 0x78, 0x43, 0x24, 0x39,\n\t\t0xbf, 0xee, 0xb9, 0x60, 0x68, 0xd0, 0x47, 0x4f, 0xc5, 0xd, 0x6d, 0x90, 0xbf,\n\t\t0x3a, 0x98, 0xdf, 0xaf, 0x10, 0x40, 0xc8, 0x9c, 0x2, 0xd6, 0x92, 0xab, 0x3b,\n\t\t0x3c, 0x28, 0x96, 0x60, 0x9d, 0x86, 0xfd, 0x73, 0xb7, 0x74, 0xce, 0x7, 0x40,\n\t\t0x64, 0x7c, 0xee, 0xea, 0xa3, 0x10, 0xbd, 0x12, 0xf9, 0x85, 0xa8, 0xeb, 0x9f,\n\t\t0x59, 0xfd, 0xd4, 0x26, 0xce, 0xa5, 0xb2, 0x12, 0xf, 0x4f, 0x2a, 0x34, 0xbc,\n\t\t0xab, 0x76, 0x4b, 0x7e, 0x6c, 0x54, 0xd6, 0x84, 0x2, 0x38, 0xbc, 0xc4, 0x5, 0x87,\n\t\t0xa5, 0x9e, 0x66, 0xed, 0x1f, 0x33, 0x89, 0x45, 0x77, 0x63, 0x5c, 0x47, 0xa,\n\t\t0xf7, 0x5c, 0xf9, 0x2c, 0x20, 0xd1, 0xda, 0x43, 0xe1, 0xbf, 0xc4, 0x19, 0xe2,\n\t\t0x22, 0xa6, 0xf0, 0xd0, 0xbb, 0x35, 0x8c, 0x5e, 0x38, 0xf9, 0xcb, 0x5, 0xa, 0xea,\n\t\t0xfe, 0x90, 0x48, 0x14, 0xf1, 0xac, 0x1a, 0xa4, 0x9c, 0xca, 0x9e, 0xa0, 0xca, 0x83}) {\n\t\tt.Fatal(\"Bad key[1].N, got %v\", key1.N.Bytes())\n\t}\n}", "func IsRsaPub(str string, params ...string) bool {\n\tif len(params) == 1 {\n\t\tlen, _ := ToInt(params[0])\n\t\treturn IsRsaPublicKey(str, int(len))\n\t}\n\n\treturn false\n}", "func rsaPublicKeyFromPem(publicKeyPem string) (*rsa.PublicKey, error) {\n\tblock, _ := pem.Decode([]byte(publicKeyPem))\n\n\tif block == nil {\n\t\treturn nil, errors.New(\"RSA Public Key From Pem Fail: \" + \"Pem Block Nil\")\n\t}\n\n\tif key, err := x509.ParsePKIXPublicKey(block.Bytes); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn key.(*rsa.PublicKey), nil\n\t}\n}", "func CheckParameters(r *rest.Request, needed_fields []string) (bool, map[string]string) {\n\tvar result map[string]string\n\tresult = make(map[string]string)\n\tfor _, field := range needed_fields {\n\t\tvalues, _ := r.URL.Query()[field]\n\t\tif len(values) < 1 {\n\t\t\treturn false, result\n\t\t}\n\t\tresult[field] = values[0]\n\t}\n\treturn true, result\n}", "func GenerateKeyPair(bits int) (keypair *KeyPair, err error) {\n\tkeypair = new(KeyPair)\n\tkeypair.PublicKey = new(PublicKey)\n\tkeypair.PrivateKey = new(PrivateKey)\n\n\tif bits == 0 {\n\t\terr = errors.New(\"RSA modulus size must not be zero.\")\n\t\treturn\n\t}\n\tif bits%8 != 0 {\n\t\terr = errors.New(\"RSA modulus size must be a multiple of 8.\")\n\t\treturn\n\t}\n\n\tfor limit := 0; limit < 1000; limit++ {\n\t\tvar tempKey *rsa.PrivateKey\n\t\ttempKey, err = rsa.GenerateKey(rand.Reader, bits)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif len(tempKey.Primes) != 2 {\n\t\t\terr = errors.New(\"RSA package generated a weird set of primes (i.e. not two)\")\n\t\t\treturn\n\t\t}\n\n\t\tp := tempKey.Primes[0]\n\t\tq := tempKey.Primes[1]\n\n\t\tif p.Cmp(q) == 0 {\n\t\t\terr = errors.New(\"RSA keypair factors were equal. This is really unlikely dependent on the bitsize and it appears something horrible has happened.\")\n\t\t\treturn\n\t\t}\n\t\tif gcd := new(big.Int).GCD(nil, nil, p, q); gcd.Cmp(big.NewInt(1)) != 0 {\n\t\t\terr = errors.New(\"RSA primes were not relatively prime!\")\n\t\t\treturn\n\t\t}\n\n\t\tmodulus := new(big.Int).Mul(p, q)\n\n\t\tpublicExp := big.NewInt(3)\n\t\t//publicExp := big.NewInt(65537)\n\n\t\t//totient = (p-1) * (q-1)\n\t\ttotient := new(big.Int)\n\t\ttotient.Sub(p, big.NewInt(1))\n\t\ttotient.Mul(totient, new(big.Int).Sub(q, big.NewInt(1)))\n\n\t\tif gcd := new(big.Int).GCD(nil, nil, publicExp, totient); gcd.Cmp(big.NewInt(1)) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tprivateExp := new(big.Int).ModInverse(publicExp, totient)\n\t\tkeypair.PublicKey.Modulus = modulus\n\t\tkeypair.PrivateKey.Modulus = modulus\n\t\tkeypair.PublicKey.PublicExp = publicExp\n\t\tkeypair.PrivateKey.PrivateExp = privateExp\n\t\treturn\n\t}\n\terr = errors.New(\"Failed to generate a within the limit!\")\n\treturn\n\n}", "func rsaEqual(priv *rsa.PrivateKey, x crypto.PrivateKey) bool {\n\txx, ok := x.(*rsa.PrivateKey)\n\tif !ok {\n\t\treturn false\n\t}\n\tif !(priv.PublicKey.N.Cmp(xx.N) == 0 && priv.PublicKey.E == xx.E) || priv.D.Cmp(xx.D) != 0 {\n\t\treturn false\n\t}\n\tif len(priv.Primes) != len(xx.Primes) {\n\t\treturn false\n\t}\n\tfor i := range priv.Primes {\n\t\tif priv.Primes[i].Cmp(xx.Primes[i]) != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p Params) Validate() error {\n\tif err := validateCreateWhoisPrice(p.CreateWhoisPrice); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateUpdateWhoisPrice(p.UpdateWhoisPrice); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateDeleteWhoisPrice(p.DeleteWhoisPrice); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SolvePuzzleRSA(ciphertext []byte, puzzle crypto.Puzzle) (message []byte, err error) {\n\tif puzzle == nil {\n\t\terr = fmt.Errorf(\"Puzzle cannot be nil, what are you solving\")\n\t\treturn\n\t}\n\n\tvar key []byte\n\tif key, err = puzzle.Solve(); err != nil {\n\t\terr = fmt.Errorf(\"Error solving auction puzzle: %s\", err)\n\t\treturn\n\t}\n\n\tvar privkey *rsa.PrivateKey\n\tif privkey, err = x509.ParsePKCS1PrivateKey(key); err != nil {\n\t\terr = fmt.Errorf(\"Error when parsing private key with pkcs#1 encoding: %s\", err)\n\t\treturn\n\t}\n\n\tif message, err = privkey.Decrypt(rand.Reader, ciphertext, nil); err != nil {\n\t\terr = fmt.Errorf(\"Error when decrypting puzzle message: %s\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func ValidateVolumeParameters(volParam map[string]map[string]string) {\n\tvar err error\n\tfor vol, params := range volParam {\n\t\tif Inst().ConfigMap != \"\" {\n\t\t\tparams[authTokenParam], err = Inst().S.GetTokenFromConfigMap(Inst().ConfigMap)\n\t\t\texpect(err).NotTo(haveOccurred())\n\t\t}\n\t\tStep(fmt.Sprintf(\"get volume: %s inspected by the volume driver\", vol), func() {\n\t\t\terr = Inst().V.ValidateCreateVolume(vol, params)\n\t\t\texpect(err).NotTo(haveOccurred())\n\t\t})\n\t}\n}", "func JWTValidator(certificates map[string]CertificateList) jwt.Keyfunc {\n\treturn func(token *jwt.Token) (interface{}, error) {\n\n\t\tvar certificateList CertificateList\n\t\tvar kid string\n\t\tvar ok bool\n\n\t\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\t\treturn nil, fmt.Errorf(\"unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\n\t\tif kid, ok = token.Header[\"kid\"].(string); !ok {\n\t\t\treturn nil, fmt.Errorf(\"field 'kid' is of invalid type %T, should be string\", token.Header[\"kid\"])\n\t\t}\n\n\t\tif certificateList, ok = certificates[kid]; !ok {\n\t\t\treturn nil, fmt.Errorf(\"kid '%s' not found in certificate list\", kid)\n\t\t}\n\n\t\tfor _, certificate := range certificateList {\n\t\t\treturn certificate.PublicKey, nil\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"no certificate candidates for kid '%s'\", kid)\n\t}\n}", "func (o *GetPublishersOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Envelope\n\tif err := o.Envelope.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func CreateRSA() {\n\tgenRsaKeys(2048)\n}", "func NewRSAWriter(w io.Writer, n, e int64) *RSAWriter {\n\tnbig := big.NewInt(n)\n\treturn &RSAWriter{\n\t\tw: w,\n\t\tn: nbig,\n\t\te: big.NewInt(e),\n\t\tbytes: uint64(nbig.BitLen() / 8),\n\t}\n}" ]
[ "0.6804986", "0.6333782", "0.6148202", "0.58484894", "0.5737118", "0.56840175", "0.56579584", "0.5655421", "0.5614205", "0.5572611", "0.55541784", "0.55131155", "0.5499171", "0.54608613", "0.54498476", "0.54304063", "0.54144347", "0.5405987", "0.5393092", "0.5390702", "0.53462625", "0.5334125", "0.53277487", "0.5247343", "0.5177483", "0.5123732", "0.50823134", "0.5064948", "0.5038374", "0.501143", "0.49910355", "0.49870384", "0.49861157", "0.4980661", "0.4968173", "0.496773", "0.49629343", "0.49623448", "0.4955299", "0.49375123", "0.4934826", "0.49337405", "0.4921632", "0.49155584", "0.49076322", "0.48847792", "0.4881764", "0.48783225", "0.48647138", "0.48641956", "0.48604876", "0.4857553", "0.48419955", "0.48280326", "0.48242316", "0.48180294", "0.48159996", "0.48097938", "0.47866696", "0.47842884", "0.4781471", "0.47814524", "0.47794113", "0.4778422", "0.47778773", "0.47692925", "0.4752889", "0.47488612", "0.47268263", "0.47158548", "0.47144553", "0.47138888", "0.4713881", "0.47120875", "0.47115016", "0.4707539", "0.47052005", "0.470187", "0.4700956", "0.46978357", "0.46965668", "0.46892947", "0.46808147", "0.4678981", "0.46773466", "0.4676616", "0.4674257", "0.46549058", "0.465321", "0.4650981", "0.46494725", "0.4625706", "0.46246135", "0.46190426", "0.46115395", "0.4594625", "0.4592362", "0.458648", "0.45761552", "0.45720804" ]
0.82881474
0
ValidateRSAParams checks the Elliptic parameters of an Elliptic type of JWK. If a JWK is invalid an error will be returned describing the values that causes the validation to fail.
func (jwk *Jwk) validateECParams() error { if jwk.X == nil { return errors.New("EC Required Param (X) is nil") } if jwk.Y == nil { return errors.New("EC Required Param (Y) is nil") } if jwk.Curve == nil { return errors.New("EC Required Param (Crv) is nil") } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (jwk *Jwk) validateRSAParams() error {\n\tif jwk.E < 1 {\n\t\treturn errors.New(\"RSA Required Param (E) is empty/default (<= 0)\")\n\t}\n\tif jwk.N == nil {\n\t\treturn errors.New(\"RSA Required Param (N) is nil\")\n\t}\n\n\tpOk := jwk.P != nil\n\tqOk := jwk.Q != nil\n\tdpOk := jwk.Dp != nil\n\tdqOk := jwk.Dq != nil\n\tqiOk := jwk.Qi != nil\n\tothOk := len(jwk.OtherPrimes) > 0\n\n\tparamsOR := pOk || qOk || dpOk || dqOk || qiOk\n\tparamsAnd := pOk && qOk && dpOk && dqOk && qiOk\n\n\tif jwk.D == nil {\n\t\tif (paramsOR || othOk) == true {\n\t\t\treturn errors.New(\"RSA first/second prime values are present but not Private key value (D)\")\n\t\t}\n\t} else {\n\t\tif paramsOR != paramsAnd {\n\t\t\treturn errors.New(\"Not all RSA first/second prime values are present or not present\")\n\t\t} else if !paramsOR && othOk {\n\t\t\treturn errors.New(\"RSA other primes is included but 1st, 2nd prime variables are missing\")\n\t\t} else if othOk {\n\t\t\tfor i, oth := range jwk.OtherPrimes {\n\t\t\t\tif oth.Coeff == nil {\n\t\t\t\t\treturn fmt.Errorf(\"Other Prime at index=%d, Coeff missing/nil\", i)\n\t\t\t\t} else if oth.R == nil {\n\t\t\t\t\treturn fmt.Errorf(\"Other Prime at index=%d, R missing/nil\", i)\n\t\t\t\t} else if oth.Exp == nil {\n\t\t\t\t\treturn fmt.Errorf(\"Other Prime at index=%d, Exp missing/nil\", i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (priv *PKCS11PrivateKeyRSA) Validate() error {\n\tpub := priv.key.PubKey.(*rsa.PublicKey)\n\tif pub.E < 2 {\n\t\treturn errMalformedRSAKey\n\t}\n\t// The software implementation actively rejects 'large' public\n\t// exponents, in order to simplify its own implementation.\n\t// Here, instead, we expect the PKCS#11 library to enforce its\n\t// own preferred constraints, whatever they might be.\n\treturn nil\n}", "func (jwk *RSAPrivateJWK) PrivateRSA() (*rsa.PrivateKey, error) {\n\tmodulusBytes, err := base64.RawURLEncoding.DecodeString(jwk.ModulusBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmodulus := new(big.Int)\n\tmodulus = modulus.SetBytes(modulusBytes)\n\tpublicExponentBytes, err := base64.RawURLEncoding.DecodeString(jwk.PublicExponentBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor len(publicExponentBytes) < 8 {\n\t\tpublicExponentBytes = append(publicExponentBytes, 0)\n\t}\n\tpublicExponent := int(binary.LittleEndian.Uint64(publicExponentBytes))\n\tprivateExponentBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExponentBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateExponent := new(big.Int)\n\tprivateExponent = privateExponent.SetBytes(privateExponentBytes)\n\tfirstPrimeFactorBytes, err := base64.RawURLEncoding.DecodeString(jwk.FirstPrimeFactorBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfirstPrimeFactor := new(big.Int)\n\tfirstPrimeFactor = firstPrimeFactor.SetBytes(firstPrimeFactorBytes)\n\tsecondPrimeFactorBytes, err := base64.RawURLEncoding.DecodeString(jwk.SecondPrimeFactorBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecondPrimeFactor := new(big.Int)\n\tsecondPrimeFactor = secondPrimeFactor.SetBytes(secondPrimeFactorBytes)\n\tprivateExpModFirstPrimeMinusOneBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExpModFirstPrimeMinusOneBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateExpModFirstPrimeMinusOne := new(big.Int)\n\tprivateExpModFirstPrimeMinusOne = privateExpModFirstPrimeMinusOne.SetBytes(privateExpModFirstPrimeMinusOneBytes)\n\tprivateExpModSecondPrimeMinusOneBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExpModSecondPrimeMinusOneBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateExpModSecondPrimeMinusOne := new(big.Int)\n\tprivateExpModSecondPrimeMinusOne = privateExpModSecondPrimeMinusOne.SetBytes(privateExpModSecondPrimeMinusOneBytes)\n\tsecondPrimeInverseModFirstPrimeBytes, err := base64.RawURLEncoding.DecodeString(jwk.SecondPrimeInverseModFirstPrimeBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecondPrimeInverseModFirstPrime := new(big.Int)\n\tsecondPrimeInverseModFirstPrime = secondPrimeInverseModFirstPrime.SetBytes(secondPrimeInverseModFirstPrimeBytes)\n\trsaPrivateKey := rsa.PrivateKey{\n\t\tPublicKey: rsa.PublicKey{\n\t\t\tN: modulus,\n\t\t\tE: publicExponent,\n\t\t},\n\t\tD: privateExponent,\n\t\tPrimes: []*big.Int{firstPrimeFactor, secondPrimeFactor},\n\t\tPrecomputed: rsa.PrecomputedValues{\n\t\t\tDp: privateExpModFirstPrimeMinusOne,\n\t\t\tDq: privateExpModSecondPrimeMinusOne,\n\t\t\tQinv: secondPrimeInverseModFirstPrime,\n\t\t},\n\t}\n\treturn &rsaPrivateKey, nil\n}", "func buildJWKFromRSA(k *rsa.PublicKey) (*Key, error) {\n\treturn &Key{\n\t\tKeyType: \"RSA\",\n\t\tN: base64.RawURLEncoding.EncodeToString(k.N.Bytes()),\n\t\tE: base64.RawURLEncoding.EncodeToString(big.NewInt(int64(k.E)).Bytes()),\n\t}, nil\n}", "func parseRSA(in []byte) (*rsa.PublicKey, error) {\n\tvar w struct {\n\t\tE *big.Int\n\t\tN *big.Int\n\t\tRest []byte `ssh:\"rest\"`\n\t}\n\tif err := ssh.Unmarshal(in, &w); err != nil {\n\t\treturn nil, errors.Wrap(err, \"error unmarshaling public key\")\n\t}\n\tif w.E.BitLen() > 24 {\n\t\treturn nil, errors.New(\"invalid public key: exponent too large\")\n\t}\n\te := w.E.Int64()\n\tif e < 3 || e&1 == 0 {\n\t\treturn nil, errors.New(\"invalid public key: incorrect exponent\")\n\t}\n\n\tvar key rsa.PublicKey\n\tkey.E = int(e)\n\tkey.N = w.N\n\treturn &key, nil\n}", "func (p Params) Validate() error {\n\tif err := validateTokenCourse(p.TokenCourse); err != nil {\n\t\treturn err\n\t}\n\tif err := validateSubscriptionPrice(p.SubscriptionPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateVPNGBPrice(p.VPNGBPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateStorageGBPrice(p.StorageGBPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateBaseVPNGb(p.BaseVPNGb); err != nil {\n\t\treturn err\n\t}\n\tif err := validateBaseStorageGb(p.BaseStorageGb); err != nil {\n\t\treturn err\n\t}\n\tif err := validateCourseChangeSigners(p.CourseChangeSigners); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ECDH_PUBLIC_KEY_VALIDATE(W []byte) int {\n\tWP := ECP_fromBytes(W)\n\tres := 0\n\n\tr := NewBIGints(CURVE_Order)\n\n\tif WP.Is_infinity() {\n\t\tres = INVALID_PUBLIC_KEY\n\t}\n\tif res == 0 {\n\n\t\tq := NewBIGints(Modulus)\n\t\tnb := q.nbits()\n\t\tk := NewBIGint(1)\n\t\tk.shl(uint((nb + 4) / 2))\n\t\tk.add(q)\n\t\tk.div(r)\n\n\t\tfor k.parity() == 0 {\n\t\t\tk.shr(1)\n\t\t\tWP.dbl()\n\t\t}\n\n\t\tif !k.isunity() {\n\t\t\tWP = WP.mul(k)\n\t\t}\n\t\tif WP.Is_infinity() {\n\t\t\tres = INVALID_PUBLIC_KEY\n\t\t}\n\n\t}\n\treturn res\n}", "func (jwk *Jwk) Validate() error {\n\n\t// If the alg parameter is set, make sure it matches the set JWK Type\n\tif len(jwk.Algorithm) > 0 {\n\t\talgKeyType := GetKeyType(jwk.Algorithm)\n\t\tif algKeyType != jwk.Type {\n\t\t\tfmt.Errorf(\"Jwk Type (kty=%v) doesn't match the algorithm key type (%v)\", jwk.Type, algKeyType)\n\t\t}\n\t}\n\tswitch jwk.Type {\n\tcase KeyTypeRSA:\n\t\tif err := jwk.validateRSAParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase KeyTypeEC:\n\t\tif err := jwk.validateECParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase KeyTypeOct:\n\t\tif err := jwk.validateOctParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tdefault:\n\t\treturn errors.New(\"KeyType (kty) must be EC, RSA or Oct\")\n\t}\n\n\treturn nil\n}", "func ValidateParams(k, m uint8) (*Params, error) {\n\tif k < 1 {\n\t\treturn nil, errors.New(\"k cannot be zero\")\n\t}\n\n\tif m < 1 {\n\t\treturn nil, errors.New(\"m cannot be zero\")\n\t}\n\n\tif k+m > 255 {\n\t\treturn nil, errors.New(\"(k + m) cannot be bigger than Galois field GF(2^8) - 1\")\n\t}\n\n\treturn &Params{\n\t\tK: k,\n\t\tM: m,\n\t}, nil\n}", "func (jwk *RSAPublicJWK) PublicRSA() (*rsa.PublicKey, error) {\n\tmodulusBytes, err := base64.RawURLEncoding.DecodeString(jwk.ModulusBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmodulus := new(big.Int)\n\tmodulus = modulus.SetBytes(modulusBytes)\n\tpublicExponentBytes, err := base64.RawURLEncoding.DecodeString(jwk.PublicExponentBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor len(publicExponentBytes) < 8 {\n\t\tpublicExponentBytes = append(publicExponentBytes, 0)\n\t}\n\tpublicExponent := int(binary.LittleEndian.Uint64(publicExponentBytes))\n\trsaPublicKey := rsa.PublicKey{\n\t\tN: modulus,\n\t\tE: publicExponent,\n\t}\n\treturn &rsaPublicKey, nil\n}", "func parseRSAKey(key ssh.PublicKey) (*rsa.PublicKey, error) {\n\tvar sshWire struct {\n\t\tName string\n\t\tE *big.Int\n\t\tN *big.Int\n\t}\n\tif err := ssh.Unmarshal(key.Marshal(), &sshWire); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal key %v: %v\", key.Type(), err)\n\t}\n\treturn &rsa.PublicKey{N: sshWire.N, E: int(sshWire.E.Int64())}, nil\n}", "func PrivateKeyValidate(priv *rsa.PrivateKey,) error", "func RSAToPrivateJWK(privateKey *rsa.PrivateKey, jwkID JWKID, algo Algorithm, expirationTime *time.Time) (*RSAPrivateJWK, error) {\n\tprivateX509DER := x509.MarshalPKCS1PrivateKey(privateKey)\n\tprivateX509DERBase64 := base64.RawStdEncoding.EncodeToString(privateX509DER)\n\tprivateThumbprint := sha1.Sum(privateX509DER)\n\tprivateThumbprintBase64 := base64.RawURLEncoding.EncodeToString(privateThumbprint[:])\n\tmodulusBase64 := base64.RawURLEncoding.EncodeToString(privateKey.PublicKey.N.Bytes())\n\texpBuf := new(bytes.Buffer)\n\tbinary.Write(expBuf, binary.LittleEndian, uint64(privateKey.PublicKey.E))\n\texpBytes := bytes.TrimRight(expBuf.Bytes(), \"\\x00\")\n\tpublicExponentBase64 := base64.RawURLEncoding.EncodeToString(expBytes)\n\tprivateExponentBase64 := base64.RawURLEncoding.EncodeToString(privateKey.D.Bytes())\n\tfirstPrimeFactor := privateKey.Primes[0]\n\tfirstPrimeFactorBase64 := base64.RawURLEncoding.EncodeToString(firstPrimeFactor.Bytes())\n\tsecondPrimeFactor := privateKey.Primes[1]\n\tsecondPrimeFactorBase64 := base64.RawURLEncoding.EncodeToString(secondPrimeFactor.Bytes())\n\t// precomputed\n\tprivateExpModFirstPrimeMinusOneBase64 := base64.RawURLEncoding.EncodeToString(privateKey.Precomputed.Dp.Bytes())\n\tprivateExpModSecondPrimeMinusOneBase64 := base64.RawURLEncoding.EncodeToString(privateKey.Precomputed.Dq.Bytes())\n\tsecondPrimeInverseModFirstPrimeBase64 := base64.RawURLEncoding.EncodeToString(privateKey.Precomputed.Qinv.Bytes())\n\tvar usage Usage\n\tswitch algo {\n\tcase RS256, PS256:\n\t\tusage = Signing\n\t\tbreak\n\tcase ROAEP, RSA15:\n\t\tusage = Encryption\n\t}\n\tprivateJWK := RSAPrivateJWK{\n\t\tJWK: JWK{\n\t\t\tCertificateChainBase64: []string{privateX509DERBase64},\n\t\t\tThumbprintBase64: privateThumbprintBase64,\n\t\t\tExpirationTime: expirationTime,\n\t\t\tID: jwkID,\n\t\t\tType: rsaType,\n\t\t\tAlgorithm: algo,\n\t\t\tUsage: usage,\n\t\t},\n\t\tModulusBase64: modulusBase64,\n\t\tPublicExponentBase64: publicExponentBase64,\n\t\tPrivateExponentBase64: privateExponentBase64,\n\t\tFirstPrimeFactorBase64: firstPrimeFactorBase64,\n\t\tSecondPrimeFactorBase64: secondPrimeFactorBase64,\n\t\t// precomputed\n\t\tPrivateExpModFirstPrimeMinusOneBase64: privateExpModFirstPrimeMinusOneBase64,\n\t\tPrivateExpModSecondPrimeMinusOneBase64: privateExpModSecondPrimeMinusOneBase64,\n\t\tSecondPrimeInverseModFirstPrimeBase64: secondPrimeInverseModFirstPrimeBase64,\n\t}\n\treturn &privateJWK, nil\n}", "func FromRSAPrivateKey(pk *rsa.PrivateKey) *RSAParameters {\n\tvar n, e, d, p, q, dp, dq, qinv string\n\n\tn = toBase64(pk.PublicKey.N)\n\te = toBase64(pk.PublicKey.E)\n\td = toBase64(pk.D)\n\n\tfor i, prime := range pk.Primes {\n\t\tif i == 0 {\n\t\t\tp = toBase64(prime)\n\t\t} else if i == 1 {\n\t\t\tq = toBase64(prime)\n\t\t} else {\n\t\t\tfmt.Println(\"ERROR: more than 2 primes\")\n\t\t}\n\t}\n\n\tdp = toBase64(pk.Precomputed.Dp)\n\tdq = toBase64(pk.Precomputed.Dq)\n\tqinv = toBase64(pk.Precomputed.Qinv)\n\n\tmsRSA := &RSAParameters{\n\t\tModulus: n,\n\t\tExponent: e,\n\t\tD: d,\n\t\tP: p,\n\t\tQ: q,\n\t\tDP: dp,\n\t\tDQ: dq,\n\t\tInverseQ: qinv,\n\t}\n\n\treturn msRSA\n}", "func UnmarshalParams(d []byte) (pubKey *signkeys.PublicKey, pubParams *jjm.BlindingParamClient, privateParams []byte, canReissue bool, err error) {\n\tp := new(Params)\n\t_, err = asn1.Unmarshal(d, p)\n\tif err != nil {\n\t\treturn nil, nil, nil, false, err\n\t}\n\tpubkey, err := new(signkeys.PublicKey).Unmarshal(p.PublicKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, false, err\n\t}\n\treturn pubkey, &p.PublicParams, p.PrivateParams, p.CanReissue, nil\n}", "func (h *auth) ParamsPKCE(c echo.Context) error {\n\tvar params service.LoginParams\n\tif err := c.Bind(&params); err != nil {\n\t\tlog.Println(\"Could not get parameters:\", err)\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"Could not get credentials.\"))\n\t}\n\tparams.UserAgent = c.Request().UserAgent()\n\tparams.Session = currentSession(c)\n\n\tif params.Email == \"\" {\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"Please provide an email address.\"))\n\t}\n\n\tif params.CodeChallenge == \"\" {\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"Please provide the code challenge parameter\"))\n\t}\n\n\tpkce := service.NewPKCE(h.db, params.Params)\n\n\tif err := pkce.StoreChallenge(params.CodeChallenge); err != nil {\n\t\tlog.Println(\"Could not store code challenge:\", err)\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"Could not store code challenge.\"))\n\t}\n\n\treturn h.params(c, params.Email)\n}", "func RSAToPublicJWK(publicKey *rsa.PublicKey, jwkID JWKID, algo Algorithm, expirationTime *time.Time) (*RSAPublicJWK, error) {\n\tpublicX509DER, err := x509.MarshalPKIXPublicKey(publicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpublicX509DERBase64 := base64.RawStdEncoding.EncodeToString(publicX509DER)\n\tpublicThumbprint := sha1.Sum(publicX509DER)\n\tpublicThumbprintBase64 := base64.RawURLEncoding.EncodeToString(publicThumbprint[:])\n\tmodulusBase64 := base64.RawURLEncoding.EncodeToString(publicKey.N.Bytes())\n\texpBuf := new(bytes.Buffer)\n\tbinary.Write(expBuf, binary.LittleEndian, uint64(publicKey.E))\n\texpBytes := bytes.TrimRight(expBuf.Bytes(), \"\\x00\")\n\tpublicExponentBase64 := base64.RawURLEncoding.EncodeToString(expBytes)\n\tvar usage Usage\n\tswitch algo {\n\tcase RS256, PS256:\n\t\tusage = Signing\n\t\tbreak\n\tcase ROAEP, RSA15:\n\t\tusage = Encryption\n\t}\n\tpublicJWK := RSAPublicJWK{\n\t\tJWK: JWK{\n\t\t\tCertificateChainBase64: []string{publicX509DERBase64},\n\t\t\tThumbprintBase64: publicThumbprintBase64,\n\t\t\tExpirationTime: expirationTime,\n\t\t\tID: jwkID,\n\t\t\tType: rsaType,\n\t\t\tAlgorithm: algo,\n\t\t\tUsage: usage,\n\t\t},\n\t\tModulusBase64: modulusBase64,\n\t\tPublicExponentBase64: publicExponentBase64,\n\t}\n\treturn &publicJWK, nil\n}", "func NewRSA(encoding encodingType) (*RSA, error) {\n\tif encoding == \"\" {\n\t\tencoding = Base64\n\t}\n\treturn &RSA{Encoding: encoding}, nil\n}", "func (v *PublicParamsManager) Validate() error {\n\tpp := v.PublicParams()\n\tif pp == nil {\n\t\treturn errors.New(\"public parameters not set\")\n\t}\n\treturn pp.Validate()\n}", "func (jwk *Jwk) validateOctParams() error {\n\tif len(jwk.KeyValue) < 1 {\n\t\treturn errors.New(\"Oct Required Param KeyValue (k) is empty\")\n\t}\n\n\treturn nil\n}", "func prepareRSAKeys(privRSAPath, pubRSAPath string)(*rsa.PublicKey, *rsa.PrivateKey, error){\n pwd, _ := os.Getwd()\n\n verifyBytes, err := ioutil.ReadFile(pwd+pubRSAPath)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrInvalidEmptyPublicKey\n }\n\n verifiedKey, err := jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrIsNotPubRSAKey\n }\n\n signBytes, err := ioutil.ReadFile(pwd+privRSAPath)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrInvalidEmptyPrivateKey\n }\n\n signedKey, err := jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrIsNotPrivRSAKey\n }\n \n return verifiedKey, signedKey, nil\n}", "func (me *XsdGoPkgHasElem_RSAKeyValue) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_RSAKeyValue; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.RSAKeyValue.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (j *JWKS) generateRSAKey() (crypto.PrivateKey, error) {\n\tif j.bits == 0 {\n\t\tj.bits = 2048\n\t}\n\tif j.bits < 2048 {\n\t\treturn nil, errors.Errorf(`jwks: key size must be at least 2048 bit for algorithm`)\n\t}\n\tkey, err := rsa.GenerateKey(rand.Reader, j.bits)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"jwks: unable to generate RSA key\")\n\t}\n\n\treturn key, nil\n}", "func generateKeyPair(algo string, ecCurve string) (privateKey interface{}, publicKey interface{}, err error) {\n\n // Make them case-insensitive\n switch strings.ToUpper(algo) {\n // If RSA, generate a pair of RSA keys\n case \"RSA\":\n // rsa.GenerateKey(): https://golang.org/pkg/crypto/rsa/#GenerateKey\n // Return value is of type *rsa.PrivateKey\n privateKey, err = rsa.GenerateKey(rand.Reader, 2048) // by default create a 2048 bit key\n\n // If ECDSA, use a provided curve\n case \"ECDSA\":\n // First check if ecCurve is provided\n if ecCurve == \"\" {\n return nil, nil, errors.New(\"ECDSA needs a curve\")\n }\n // Then generate the key based on the curve\n // Curves: https://golang.org/pkg/crypto/elliptic/#Curve\n // ecdsa.GenerateKey(): https://golang.org/pkg/crypto/ecdsa/#GenerateKey\n // Return value is of type *ecdsa.PrivateKey\n switch strings.ToUpper(ecCurve) {\n case \"P224\":\n privateKey, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)\n case \"P256\":\n privateKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n case \"P384\":\n \tprivateKey, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)\n case \"P521\":\n \tprivateKey, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)\n\n // If the curve is invalid\n default:\n return nil, nil, errors.New(\"Unrecognized curve, valid values are P224, P256, P384 and P521\")\n }\n\n // If neither RSA nor ECDSA return an error\n default:\n return nil, nil, errors.New(\"Unrecognized algorithm, valid options are RSA and ECDSA\")\n }\n\n // If we get here, then input parameters have been valid\n // Check if key generation has been successful by checking err\n if err != nil {\n return nil, nil, err\n }\n\n // Exporting the public key (needed later)\n switch tempPrivKey:= privateKey.(type) {\n case *rsa.PrivateKey:\n publicKey = &tempPrivKey.PublicKey\n case *ecdsa.PrivateKey:\n publicKey = &tempPrivKey.PublicKey\n }\n\n return privateKey, publicKey, err // or just return\n}", "func (j *JWK) PrivateKey() (crypto.PrivateKey, error) {\n\tswitch j.KeyType {\n\tcase \"EC\", \"EC-HSM\":\n\t\tif j.D == \"\" {\n\t\t\treturn nil, ErrPublic\n\t\t}\n\t\tpub, err := j.ecPublicKey()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkey := ecdsa.PrivateKey{\n\t\t\tPublicKey: *pub,\n\t\t}\n\t\tif key.D, err = parseBase64UInt(j.D); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &key, nil\n\n\tcase \"RSA\", \"RSA-HSM\":\n\t\tif j.D == \"\" {\n\t\t\treturn nil, ErrPublic\n\t\t}\n\n\t\tpub, err := j.rsaPublicKey()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkey := rsa.PrivateKey{\n\t\t\tPublicKey: *pub,\n\t\t}\n\t\tif key.D, err = parseBase64UInt(j.D); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkey.Primes = make([]*big.Int, 2+len(j.Oth))\n\t\tif key.Primes[0], err = parseBase64UInt(j.P); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif key.Primes[1], err = parseBase64UInt(j.Q); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor i, a := range j.Oth {\n\t\t\tr, err := parseBase64UInt(a.R)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif r.Sign() <= 0 {\n\t\t\t\treturn nil, errors.New(\"jwk: private key contains zero or negative prime\")\n\t\t\t}\n\t\t\tkey.Primes[i+2] = r\n\t\t}\n\n\t\tif err = key.Validate(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkey.Precompute()\n\n\t\treturn &key, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"jwk: unknown key type: %s\", j.KeyType)\n}", "func ValidatePublicKey(k *ecdsa.PublicKey) bool {\n\treturn k != nil && k.X != nil && k.Y != nil && k.X.Sign() != 0 && k.Y.Sign() != 0\n}", "func (me *XsdGoPkgHasElems_RSAKeyValue) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_RSAKeyValue; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfor _, x := range me.RSAKeyValues {\n\t\t\tif err = x.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func GenerateRSAKeyPair(opts GenerateRSAOptions) (*RSAKeyPair, error) {\n\t//creates the private key\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, opts.Bits)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error generating private key: %s\\n\", err)\n\t}\n\n\t//validates the private key\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error validating private key: %s\\n\", err)\n\t}\n\n\t// sets up the PEM block for private key\n\tprivateKeyBlock := pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tHeaders: nil,\n\t\tBytes: x509.MarshalPKCS1PrivateKey(privateKey),\n\t}\n\n\t//check to see if we are applying encryption to this key\n\tif opts.Encryption != nil {\n\t\t//check to make sure we have a password specified\n\t\tpass := strings.TrimSpace(opts.Encryption.Password)\n\t\tif pass == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"%s\", \"need a password!\")\n\t\t}\n\t\t//check to make sure we're using a supported PEMCipher\n\t\tencCipher := opts.Encryption.PEMCipher\n\t\tif encCipher != x509.PEMCipherDES &&\n\t\t\tencCipher != x509.PEMCipher3DES &&\n\t\t\tencCipher != x509.PEMCipherAES128 &&\n\t\t\tencCipher != x509.PEMCipherAES192 &&\n\t\t\tencCipher != x509.PEMCipherAES256 {\n\t\t\treturn nil, fmt.Errorf(\"%s\", \"invalid PEMCipher\")\n\t\t}\n\t\t//encrypt the private key block\n\t\tencBlock, err := x509.EncryptPEMBlock(rand.Reader, \"RSA PRIVATE KEY\", privateKeyBlock.Bytes, []byte(pass), encCipher)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error encrypting pirvate key: %s\\n\", err)\n\t\t}\n\t\t//replaces the starting one with the one we encrypted\n\t\tprivateKeyBlock = *encBlock\n\t}\n\n\t// serializes the public key in a DER-encoded PKIX format (see docs for more)\n\tpublicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error setting up public key: %s\\n\", err)\n\t}\n\n\t// sets up the PEM block for public key\n\tpublicKeyBlock := pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tHeaders: nil,\n\t\tBytes: publicKeyBytes,\n\t}\n\n\t//returns the created key pair\n\treturn &RSAKeyPair{\n\t\tPrivateKey: string(pem.EncodeToMemory(&privateKeyBlock)),\n\t\tPublicKey: string(pem.EncodeToMemory(&publicKeyBlock)),\n\t}, nil\n}", "func EncodePrivateKey(key crypto.PrivateKey) (jwk *JWK, err error) {\n\tjwk = new(JWK)\n\tswitch k := key.(type) {\n\tcase *ecdsa.PrivateKey:\n\t\tjwk.populateECPublicKey(&k.PublicKey)\n\t\tjwk.D = b64.EncodeToString(k.D.Bytes())\n\n\tcase *rsa.PrivateKey:\n\t\tjwk.populateRSAPublicKey(&k.PublicKey)\n\t\tjwk.D = b64.EncodeToString(k.D.Bytes())\n\t\tif len(k.Primes) < 2 || len(k.Precomputed.CRTValues) != len(k.Primes)-2 {\n\t\t\treturn nil, errors.New(\"jwk: invalid RSA primes number\")\n\t\t}\n\t\tjwk.P = b64.EncodeToString(k.Primes[0].Bytes())\n\t\tjwk.Q = b64.EncodeToString(k.Primes[1].Bytes())\n\t\tjwk.Dp = b64.EncodeToString(k.Precomputed.Dp.Bytes())\n\t\tjwk.Dq = b64.EncodeToString(k.Precomputed.Dq.Bytes())\n\t\tjwk.Qi = b64.EncodeToString(k.Precomputed.Qinv.Bytes())\n\n\t\tif len(k.Primes) > 2 {\n\t\t\tjwk.Oth = make([]*RSAPrime, len(k.Primes)-2)\n\t\t\tfor i := 0; i < len(k.Primes)-2; i++ {\n\t\t\t\tjwk.Oth[i] = &RSAPrime{\n\t\t\t\t\tR: b64.EncodeToString(k.Primes[i+2].Bytes()),\n\t\t\t\t\tD: b64.EncodeToString(k.Precomputed.CRTValues[i].Exp.Bytes()),\n\t\t\t\t\tT: b64.EncodeToString(k.Precomputed.CRTValues[i].Coeff.Bytes()),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"jwk: unknown private key type: %T\", key)\n\t}\n\n\treturn jwk, nil\n}", "func (p Params) Validate() error {\n\tif err := validateCreateWhoisPrice(p.CreateWhoisPrice); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateUpdateWhoisPrice(p.UpdateWhoisPrice); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateDeleteWhoisPrice(p.DeleteWhoisPrice); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func rsaEncrypt(pemPubKey, nonce, password []byte) ([]byte, error) {\n\tpubKeyBlock, rest := pem.Decode(pemPubKey)\n\tif len(rest) > 0 {\n\t\treturn nil, fmt.Errorf(\"trailing bytes in public key: %#v\", rest)\n\t}\n\n\tpublicKey, err := x509.ParsePKCS1PublicKey(pubKeyBlock.Bytes)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse PKCS#1 public key: %w\", err)\n\t}\n\n\treturn rsa.EncryptOAEP(sha1.New(), rand.Reader, publicKey, append(nonce, []byte(password)...), []byte{})\n}", "func NewGojwtRSA(nameserver, headerkey, privKeyPath, pubKeyPath, lenbytes string, hours time.Duration) (*Gojwt, error){\n var verifiedRSAKey *rsa.PublicKey\n var signedRSAKey *rsa.PrivateKey\n \n if privKeyPath == \"\" {\n return nil, GojwtErrInvalidEmptyPrivateKey\n } else if pubKeyPath == \"\" {\n return nil, GojwtErrInvalidEmptyPublicKey\n }\n verifiedRSAKey, signedRSAKey, err := prepareRSAKeys(privKeyPath, pubKeyPath)\n if err != nil{\n return nil, err\n }\n return &Gojwt{\n pubKeyPath: pubKeyPath,\n privKeyPath: privKeyPath,\n pubRSAKey: verifiedRSAKey,\n privRSAKey: signedRSAKey,\n headerKeyAuth: headerkey,\n numHoursDuration: hours,\n method: \"RSA\",\n lenBytes: lenbytes,\n nameServer: nameserver}, nil\n}", "func (m *KeyPair) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with Resource\n\tif err := m.Resource.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGroup(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *GPGKey) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEmails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateExpires(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSubsKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func InitRSAKeys() {\n\n\tsignBytes, err := ioutil.ReadFile(privKeyPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n\n\tsignKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n\n\tverifyBytes, err := ioutil.ReadFile(pubKeyPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n\n\tverifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n}", "func validatePubKey(publicKey string) error {\n\tpk, err := hex.DecodeString(publicKey)\n\tif err != nil {\n\t\tlog.Debugf(\"validatePubKey: decode hex string \"+\n\t\t\t\"failed for '%v': %v\", publicKey, err)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\t}\n\n\tvar emptyPK [identity.PublicKeySize]byte\n\tswitch {\n\tcase len(pk) != len(emptyPK):\n\t\tlog.Debugf(\"validatePubKey: invalid size: %v\",\n\t\t\tpublicKey)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\tcase bytes.Equal(pk, emptyPK[:]):\n\t\tlog.Debugf(\"validatePubKey: key is empty: %v\",\n\t\t\tpublicKey)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\t}\n\n\treturn nil\n}", "func GenRSAKey(len int, password string, kmPubFile, kmPrivFile, bpmPubFile, bpmPrivFile *os.File) error {\n\tif len == rsaLen2048 || len == rsaLen3072 {\n\t\tkey, err := rsa.GenerateKey(rand.Reader, len)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writePrivKeyToFile(key, kmPrivFile, password); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := writePubKeyToFile(key.Public(), kmPubFile); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tkey, err = rsa.GenerateKey(rand.Reader, len)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writePrivKeyToFile(key, bpmPrivFile, password); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := writePubKeyToFile(key.Public(), bpmPubFile); err != nil {\n\t\t\treturn err\n\n\t\t}\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"RSA key length must be 2048 or 3084 Bits, but length is: %d\", len)\n}", "func (c *KeyPair) Validate() error {\n\tif c.KeyID == \"\" {\n\t\treturn ErrInvalidKeyID\n\t} else if c.PrivateKey == \"\" {\n\t\treturn ErrInvalidPrivateKey\n\t} else if c.PublicKey == \"\" {\n\t\treturn ErrInvalidPublicKey\n\t} else if c.Issuer == \"\" {\n\t\treturn ErrInvalidIssuer\n\t}\n\treturn nil\n}", "func CheckAlgorithmIDParamNotNULL(algorithmIdentifier []byte, requiredAlgoID asn1.ObjectIdentifier) error {\n\texpectedAlgoIDBytes, ok := RSAAlgorithmIDToDER[requiredAlgoID.String()]\n\tif !ok {\n\t\treturn errors.New(\"error algorithmID to check is not RSA\")\n\t}\n\n\talgorithmSequence := cryptobyte.String(algorithmIdentifier)\n\n\t// byte comparison of algorithm sequence and checking no trailing data is present\n\tvar algorithmBytes []byte\n\tif algorithmSequence.ReadBytes(&algorithmBytes, len(expectedAlgoIDBytes)) {\n\t\tif bytes.Compare(algorithmBytes, expectedAlgoIDBytes) == 0 && algorithmSequence.Empty() {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// re-parse to get an error message detailing what did not match in the byte comparison\n\talgorithmSequence = cryptobyte.String(algorithmIdentifier)\n\tvar algorithm cryptobyte.String\n\tif !algorithmSequence.ReadASN1(&algorithm, cryptobyte_asn1.SEQUENCE) {\n\t\treturn errors.New(\"error reading algorithm\")\n\t}\n\n\tencryptionOID := asn1.ObjectIdentifier{}\n\tif !algorithm.ReadASN1ObjectIdentifier(&encryptionOID) {\n\t\treturn errors.New(\"error reading algorithm OID\")\n\t}\n\n\tif !encryptionOID.Equal(requiredAlgoID) {\n\t\treturn fmt.Errorf(\"algorithm OID is not equal to %s\", requiredAlgoID.String())\n\t}\n\n\tif algorithm.Empty() {\n\t\treturn errors.New(\"RSA algorithm identifier missing required NULL parameter\")\n\t}\n\n\tvar nullValue cryptobyte.String\n\tif !algorithm.ReadASN1(&nullValue, cryptobyte_asn1.NULL) {\n\t\treturn errors.New(\"RSA algorithm identifier with non-NULL parameter\")\n\t}\n\n\tif len(nullValue) != 0 {\n\t\treturn errors.New(\"RSA algorithm identifier with NULL parameter containing data\")\n\t}\n\n\t// ensure algorithm is empty and no trailing data is present\n\tif !algorithm.Empty() {\n\t\treturn errors.New(\"RSA algorithm identifier with trailing data\")\n\t}\n\n\treturn errors.New(\"RSA algorithm appears correct, but didn't match byte-wise comparison\")\n}", "func TestPublicKey(t *testing.T) {\n\tconst jsonkey = `{\"keys\":\n [\n {\"kty\":\"EC\",\n \"crv\":\"P-256\",\n \"x\":\"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4\",\n \"y\":\"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM\",\n \"use\":\"enc\",\n \"kid\":\"1\"},\n\n {\"kty\":\"RSA\",\n \"n\": \"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw\",\n \"e\":\"AQAB\",\n \"alg\":\"RS256\",\n \"kid\":\"2011-04-29\"}\n ]\n }`\n\n\tjwt, err := Unmarshal([]byte(jsonkey))\n\tif err != nil {\n\t\tt.Fatal(\"Unmarshal: \", err)\n\t} else if len(jwt.Keys) != 2 {\n\t\tt.Fatalf(\"Expected 2 keys, got %d\", len(jwt.Keys))\n\t}\n\n\tkeys := make([]crypto.PublicKey, len(jwt.Keys))\n\tfor ii, jwt := range jwt.Keys {\n\t\tkeys[ii], err = jwt.DecodePublicKey()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to decode key %d: %v\", ii, err)\n\t\t}\n\t}\n\n\tif key0, ok := keys[0].(*ecdsa.PublicKey); !ok {\n\t\tt.Fatalf(\"Expected ECDSA key[0], got %T\", keys[0])\n\t} else if key1, ok := keys[1].(*rsa.PublicKey); !ok {\n\t\tt.Fatalf(\"Expected RSA key[1], got %T\", keys[1])\n\t} else if key0.Curve != elliptic.P256() {\n\t\tt.Fatal(\"Key[0] is not using P-256 curve\")\n\t} else if !bytes.Equal(key0.X.Bytes(), []byte{0x30, 0xa0, 0x42, 0x4c, 0xd2,\n\t\t0x1c, 0x29, 0x44, 0x83, 0x8a, 0x2d, 0x75, 0xc9, 0x2b, 0x37, 0xe7, 0x6e, 0xa2,\n\t\t0xd, 0x9f, 0x0, 0x89, 0x3a, 0x3b, 0x4e, 0xee, 0x8a, 0x3c, 0xa, 0xaf, 0xec, 0x3e}) {\n\t\tt.Fatalf(\"Bad key[0].X, got %v\", key0.X.Bytes())\n\t} else if !bytes.Equal(key0.Y.Bytes(), []byte{0xe0, 0x4b, 0x65, 0xe9, 0x24,\n\t\t0x56, 0xd9, 0x88, 0x8b, 0x52, 0xb3, 0x79, 0xbd, 0xfb, 0xd5, 0x1e, 0xe8,\n\t\t0x69, 0xef, 0x1f, 0xf, 0xc6, 0x5b, 0x66, 0x59, 0x69, 0x5b, 0x6c, 0xce,\n\t\t0x8, 0x17, 0x23}) {\n\t\tt.Fatalf(\"Bad key[0].Y, got %v\", key0.Y.Bytes())\n\t} else if key1.E != 0x10001 {\n\t\tt.Fatalf(\"Bad key[1].E: %d\", key1.E)\n\t} else if !bytes.Equal(key1.N.Bytes(), []byte{0xd2, 0xfc, 0x7b, 0x6a, 0xa, 0x1e,\n\t\t0x6c, 0x67, 0x10, 0x4a, 0xeb, 0x8f, 0x88, 0xb2, 0x57, 0x66, 0x9b, 0x4d, 0xf6,\n\t\t0x79, 0xdd, 0xad, 0x9, 0x9b, 0x5c, 0x4a, 0x6c, 0xd9, 0xa8, 0x80, 0x15, 0xb5,\n\t\t0xa1, 0x33, 0xbf, 0xb, 0x85, 0x6c, 0x78, 0x71, 0xb6, 0xdf, 0x0, 0xb, 0x55,\n\t\t0x4f, 0xce, 0xb3, 0xc2, 0xed, 0x51, 0x2b, 0xb6, 0x8f, 0x14, 0x5c, 0x6e, 0x84,\n\t\t0x34, 0x75, 0x2f, 0xab, 0x52, 0xa1, 0xcf, 0xc1, 0x24, 0x40, 0x8f, 0x79, 0xb5,\n\t\t0x8a, 0x45, 0x78, 0xc1, 0x64, 0x28, 0x85, 0x57, 0x89, 0xf7, 0xa2, 0x49, 0xe3,\n\t\t0x84, 0xcb, 0x2d, 0x9f, 0xae, 0x2d, 0x67, 0xfd, 0x96, 0xfb, 0x92, 0x6c, 0x19,\n\t\t0x8e, 0x7, 0x73, 0x99, 0xfd, 0xc8, 0x15, 0xc0, 0xaf, 0x9, 0x7d, 0xde, 0x5a,\n\t\t0xad, 0xef, 0xf4, 0x4d, 0xe7, 0xe, 0x82, 0x7f, 0x48, 0x78, 0x43, 0x24, 0x39,\n\t\t0xbf, 0xee, 0xb9, 0x60, 0x68, 0xd0, 0x47, 0x4f, 0xc5, 0xd, 0x6d, 0x90, 0xbf,\n\t\t0x3a, 0x98, 0xdf, 0xaf, 0x10, 0x40, 0xc8, 0x9c, 0x2, 0xd6, 0x92, 0xab, 0x3b,\n\t\t0x3c, 0x28, 0x96, 0x60, 0x9d, 0x86, 0xfd, 0x73, 0xb7, 0x74, 0xce, 0x7, 0x40,\n\t\t0x64, 0x7c, 0xee, 0xea, 0xa3, 0x10, 0xbd, 0x12, 0xf9, 0x85, 0xa8, 0xeb, 0x9f,\n\t\t0x59, 0xfd, 0xd4, 0x26, 0xce, 0xa5, 0xb2, 0x12, 0xf, 0x4f, 0x2a, 0x34, 0xbc,\n\t\t0xab, 0x76, 0x4b, 0x7e, 0x6c, 0x54, 0xd6, 0x84, 0x2, 0x38, 0xbc, 0xc4, 0x5, 0x87,\n\t\t0xa5, 0x9e, 0x66, 0xed, 0x1f, 0x33, 0x89, 0x45, 0x77, 0x63, 0x5c, 0x47, 0xa,\n\t\t0xf7, 0x5c, 0xf9, 0x2c, 0x20, 0xd1, 0xda, 0x43, 0xe1, 0xbf, 0xc4, 0x19, 0xe2,\n\t\t0x22, 0xa6, 0xf0, 0xd0, 0xbb, 0x35, 0x8c, 0x5e, 0x38, 0xf9, 0xcb, 0x5, 0xa, 0xea,\n\t\t0xfe, 0x90, 0x48, 0x14, 0xf1, 0xac, 0x1a, 0xa4, 0x9c, 0xca, 0x9e, 0xa0, 0xca, 0x83}) {\n\t\tt.Fatal(\"Bad key[1].N, got %v\", key1.N.Bytes())\n\t}\n}", "func (r *RSAParameters) GetRSAPrivateKey() *rsa.PrivateKey {\n\tpk := new(rsa.PrivateKey)\n\n\tpk.PublicKey.N = base64ToBigInt(r.Modulus)\n\tpk.PublicKey.E = base64ToInt(r.Exponent)\n\tif pk.PublicKey.E == 0 {\n\t\tpk.PublicKey.E = 65537\n\t}\n\tpk.D = base64ToBigInt(r.D)\n\tpk.Primes = append(pk.Primes, base64ToBigInt(r.P))\n\tpk.Primes = append(pk.Primes, base64ToBigInt(r.Q))\n\tpk.Precomputed.Dp = base64ToBigInt(r.DP)\n\tpk.Precomputed.Dq = base64ToBigInt(r.DQ)\n\tpk.Precomputed.Qinv = base64ToBigInt(r.InverseQ)\n\n\treturn pk\n}", "func Validate(accessToken string, configURL string, c *cache.Cache) (bool, error) {\n\n\tjp := new(jwtgo.Parser)\n\tjp.ValidMethods = []string{\n\t\t\"RS256\", \"RS384\", \"RS512\", \"ES256\", \"ES384\", \"ES512\",\n\t\t\"RS3256\", \"RS3384\", \"RS3512\", \"ES3256\", \"ES3384\", \"ES3512\",\n\t}\n\n\t// Validate token against issuer\n\ttt, _ := jwtgo.Parse(accessToken, func(token *jwtgo.Token) (interface{}, error) {\n\t\tif _, ok := token.Method.(*jwtgo.SigningMethodRSA); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\n\t\t// check if publicKey already in cache\n\t\tpub, found := c.Get(\"key\")\n\t\tif found {\n\t\t\t//fmt.Println(\"Using cached pubKey\")\n\t\t\treturn pub, nil\n\t\t}\n\n\t\t// Retrieve Issuer metadata from discovery endpoint\n\t\td := openid.DiscoveryDoc{}\n\n\t\treq, err := http.NewRequest(http.MethodGet, configURL, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclnt := http.Client{}\n\n\t\tr, err := clnt.Do(req)\n\t\tif err != nil {\n\t\t\tclnt.CloseIdleConnections()\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer r.Body.Close()\n\n\t\tif r.StatusCode != http.StatusOK {\n\t\t\treturn nil, errors.New(r.Status)\n\t\t}\n\t\tdec := json.NewDecoder(r.Body)\n\t\tif err = dec.Decode(&d); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Get Public Key from JWK URI\n\t\tresp, err := clnt.Get(d.JwksURI)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn nil, errors.New(resp.Status)\n\t\t}\n\n\t\tvar jwk openid.JWKS\n\t\tif err = json.NewDecoder(resp.Body).Decode(&jwk); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar kk crypto.PublicKey\n\t\tfor _, key := range jwk.Keys {\n\t\t\tkk, err = key.DecodePublicKey()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Return the rsa public key for the token validation\n\t\tpubKey := kk.(*rsa.PublicKey)\n\n\t\tc.Set(\"key\", pubKey, cache.DefaultExpiration)\n\n\t\treturn pubKey, nil\n\n\t})\n\n\t//fmt.Println(tt)\n\treturn tt.Valid, nil\n}", "func (c *Coffin) encryptRSA(data []byte) ([]byte, error) {\n\n\t// If public key is not supplied, return error\n\tif len(c.Opts.PubKey) == 0 {\n\t\treturn emptyByte, ErrNoPubKey\n\t}\n\n\t// Unmarshall the RSA public key\n\trsaKey, err := UnmarshalPublicKey(bytes.NewBuffer(c.Opts.PubKey))\n\tif err != nil {\n\t\treturn emptyByte, err\n\t}\n\n\t// Encrypt the data\n\thash := sha512.New()\n\tciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, rsaKey, data, nil)\n\tif err != nil {\n\t\treturn emptyByte, err\n\t}\n\n\t// Return the data\n\treturn ciphertext, nil\n}", "func (p Params) Validate() error {\n\tif err := validateActiveParam(p.Active); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateDelegatorParams(p.DelegatorDistributionSchedules); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateLPParams(p.LiquidityProviderSchedules); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateMoneyMarketParams(p.MoneyMarkets); err != nil {\n\t\treturn err\n\t}\n\n\treturn validateCheckLtvIndexCount(p.CheckLtvIndexCount)\n}", "func (params Params) Validate() error {\n\tif err := ValidateNicknameParams(params.Nickname); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ValidateDTagParams(params.DTag); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ValidateBioParams(params.Bio); err != nil {\n\t\treturn err\n\t}\n\n\treturn ValidateOracleParams(params.Oracle)\n}", "func CurveParamsParams(curve *elliptic.CurveParams,) *elliptic.CurveParams", "func (_WyvernExchange *WyvernExchangeCaller) ValidateOrderParameters(opts *bind.CallOpts, addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _WyvernExchange.contract.Call(opts, out, \"validateOrderParameters_\", addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n\treturn *ret0, err\n}", "func GenerateRSAKey(bits int) (privateKey, publicKey []byte, err error) {\n\tprvKey, err := rsa.GenerateKey(rand.Reader, bits)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpkixb, err := x509.MarshalPKIXPublicKey(&prvKey.PublicKey)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tprivateKey = pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(prvKey),\n\t})\n\n\tpublicKey = pem.EncodeToMemory(&pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tBytes: pkixb,\n\t})\n\n\treturn\n}", "func GetRSAKey(size int) (data.PrivateKey, error) {\n\traw := map[int][]byte{\n\t\t1024: []byte(`-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDJ8BO2/HOHLJgrb3srafbNRUD8r0SGNJFi5h7t4vxZ4F5oBW/4\nO2/aZmdToinyuCm0eGguK77HAsTfSHqDUoEfuInNg7pPk4F6xa4feQzEeG6P0YaL\n+VbApUdCHLBE0tVZg1SCW97+27wqIM4Cl1Tcsbb+aXfgMaOFGxlyga+a6wIDAQAB\nAoGBAKDWLH2kGMfjBtghlLKBVWcs75PSbPuPRvTEYIIMNf3HrKmhGwtVG8ORqF5+\nXHbLo7vv4tpTUUHkvLUyXxHVVq1oX+QqiRwTRm+ROF0/T6LlrWvTzvowTKtkRbsm\nmqIYEbc+fBZ/7gEeW2ycCfE7HWgxNGvbUsK4LNa1ozJbrVEBAkEA8ML0mXyxq+cX\nCwWvdXscN9vopLG/y+LKsvlKckoI/Hc0HjPyraq5Docwl2trZEmkvct1EcN8VvcV\nvCtVsrAfwQJBANa4EBPfcIH2NKYHxt9cP00n74dVSHpwJYjBnbec5RCzn5UTbqd2\ni62AkQREYhHZAryvBVE81JAFW3nqI9ZTpasCQBqEPlBRTXgzYXRTUfnMb1UvoTXS\nZd9cwRppHmvr/4Ve05yn+AhsjyksdouWxyMqgTxuFhy4vQ8O85Pf6fZeM4ECQCPp\nWv8H4thJplqSeGeJFSlBYaVf1SRtN0ndIBTCj+kwMaOMQXiOsiPNmfN9wG09v2Bx\nYVFJ/D8uNjN4vo+tI8sCQFbtF+Qkj4uSFDZGMESF6MOgsGt1R1iCpvpMSr9h9V02\nLPXyS3ozB7Deq26pEiCrFtHxw2Pb7RJO6GEqH7Dg4oU=\n-----END RSA PRIVATE KEY-----`),\n\t\t2048: []byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAtKGse3BcxXAp5OkLGYq0HfDcCvgag3R/9e8pHUGsJhkSZFrn\nZWAsAVFKSYaYItf1D/g3izqVDMtMpXZ1chNzaRysnbrb/q7JTbiGzXo9FcshyUc9\ntcB60wFbvsXE2LaxZcKNxLYXbOvf+tdg/P07oPG24fzYI4+rbZ1wyoORbT1ys33Z\nhHyifFvO7rbe69y3HG+xbp7yWYAR4e8Nw9jX8/9sGslAV9vEXOdNL3qlcgsYRGDU\nDsUJsnWaMzjstvUxb8mVf9KG2W039ucgaXgBW/jeP3F1VSYFKLd03LvuJ8Ir5E0s\ncWjwTd59nm0XbbRI3KiBGnAgrJ4iK07HrUkpDQIDAQABAoIBAHfr1k1lfdH+83Fs\nXtgoRAiUviHyMfgQQlwO2eb4kMgCYTmLOJEPVmfRhlZmK18GrUZa7tVaoVYLKum3\nSaXg0AB67wcQ5bmiZTdaSPTmMOPlJpsw1wFxtpmcD0MKnfOa5w++KMzub4L63or0\nrwmHPi1ODLLgYMbLPW7a1eU9kDFLOnx3RRy9a29hQXxGsRYetrIbKmeDi6c+ndQ8\nI5YWObcixxl5GP6CTnEugV7wd2JmXuQRGFdopUwQESCD9VkxDSevQBSPoyZKHxGy\n/d3jf0VNlvwsxhD3ybhw8jTN/cmm2LWmP4jylG7iG7YRPVaW/0s39IZ9DnNDwgWB\n03Yk2gECgYEA44jcSI5kXOrbBGDdV+wTUoL24Zoc0URX33F15UIOQuQsypaFoRJ6\nJ23JWEZN99aquuo1+0BBSfiumbpLwSwfXi0nL3oTzS9eOp1HS7AwFGd/OHdpdMsC\nw2eInRwCh4GrEf508GXo+tSL2NS8+MFVAG2/SjEf06SroQ/rQ87Qm0ECgYEAyzqr\n6YvbAnRBy5GgQlTgxR9r0U8N7lM9g2Tk8uGvYI8zu/Tgia4diHAwK1ymKbl3lf95\n3NcHR+ffwOO+nnfFCvmCYXs4ggRCkeopv19bsCLkfnTBNTxPFh6lyLEnn3C+rcCe\nZAkKLrm8BHGviPIgn0aElMQAbhJxTWfClw/VVs0CgYAlDhfZ1R6xJypN9zx04iRv\nbpaoPQHubrPk1sR9dpl9+Uz2HTdb+PddznpY3vI5p4Mcd6Ic7eT0GATPUlCeAAKH\nwtC74aSx6MHux8hhoiriV8yXNJM/CwTDL+xGsdYTnWFvx8HhmKctmknAIT05QbsH\nG9hoS8HEJPAyhbYpz9eXQQKBgQCftPXQTPXJUe86uLBGMEmK34xtKkD6XzPiA/Hf\n5PdbXG39cQzbZZcT14YjLWXvOC8AE4qCwACaw1+VR+ROyDRy0W1iieD4W7ysymYQ\nXDHDk0gZEEudOE22RlNmCcHnjERsawiN+ISl/5P/sg+OASkdwd8CwZzM43VirP3A\nlNLEqQKBgHqj85n8ew23SR0GX0W1PgowaCHHD1p81y2afs1x7H9R1PNuQsTXKnpf\nvMiG7Oxakj4WDC5M5KsHWqchqKDycT+J1BfLI58Sf2qo6vtaV+4DARNgzcG/WB4b\nVnpsczK/1aUH7iBexuF0YqdPQwzpSvrY0XZcgCFQ52JDn3vjblhX\n-----END RSA PRIVATE KEY-----`),\n\t\t4096: []byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIJKgIBAAKCAgEAw28m5P1j7Rv1Wy4AicNkR4DXVxJXlPma+c5U/KJzFg0emiyx\nfkGQnUWeFofOI3rgrgK3deQ6yspgavTKWnHs4YeAz2egMSDsobI1OAP7ocPrFhYc\nFB+pTLXm1CkvyxIt9UWPxgc4CGiO1wIlfL8PpFg5vur7sAqbzxKeFx8GikbjFbQg\nd/RMFYeQacuimo9yea9DqjELvwewby3iP81FP9JJKiM3G6+7BiI+pJv65dNLbBUY\nHgKrmBHYg7WVSdmR7pZucEDoBqJcjc+kIHDGMH2vndWhIybEpHxxXdW+DrnPlhGV\n/hqKWw5fqJvhdh0OR1yefCCva0m6mZAKardzqxndFJqJbs1ehXg0luijVRYXaUpP\nuvHaKj+QV2R/PJWxkCLZLFSEAE156QT1sfY5FOh8rYBWBNrJk7X6qUTaF7Jfeo3H\nCF94ioP0Up8bohIu0lH8WPfTxdZ2lvUGSteMEYWBSbKhcbSCOP6a2K4/znSNl/J3\nLV/YcbmuSb7sAp+sZXELarYg/JMNVP4Vo2vh5S4ZCPYtk2or2WY27rMHWQ1vIhjB\nxjuSKzpLx9klusoTHB3wD6K7FwyT4JLUTfxGloSSpOuLG5yp9dAL/i8WHY20w6jP\n7ZYOss6OsQzp5ZqpW5M/0z60NsEOhfFXd1bxPYUP7//6N14XHTg31fg7vykCAwEA\nAQKCAgEAnn+j/K0ggKlfGL67Qv9Lcc4lVwGSNEknDhfvxyB809J6EjHTFYFZJqPS\nbZVgclfypk2fuqYJpHPzNGspPacNpW7+4ba6LX31S8I69R4N0wkQvM3bodp3tLYF\n6eUpVLl+ul/bFZC/OdqKlgewnXZa2j+PPa5Xx1MjQBJqUnggFr8c5no6pu5jUkaq\nsZKsYkuaXOPurbWvQBOdXN3Kk1IIKpWCLwF2bSbdOEFHqrqyBfiSP6rv707dGazH\nezImTEl+2A/6q2GIi/DbvUs8Ye70XVlht1ENqXOEoZ4nVyHFTS4XFC9ZBUdDFEwY\n+qbJeMBh1zBffG4JtqqKAobWW+xCioKVn2ArSzh1/2Q5652yeVVhR+GTSK2yd1uE\n5a5Pc65C8LCRNTz0iHEUESfVO5QnUq9bWShgm0H/LQ3sk8gzQjuBS5Ya523vOl1w\nxRUYxjEFW0382BrG0dn+WE2Yn0z5i2X9+WRgiKrh8tNZ+wNGN3MtZ5mloHsocH4N\nuUIZ6J0x/YruW126b0XA6fE+3taQDmJ4Qj/puU7+sFCs7MXUtd3tClEH1NUalH0T\n5awjZcJnMmGVmtGGfP1DtuEd082mIUuvKZj1vCEiSavwK3JDVl5goxlDpvEgdh2X\no1eSIMMZb6FG5h3dsyyMpXaRobgL+qbLm0XDGwtiIu+d5BE8OQECggEBAPL+FwUB\n2w4bRGzmDNRJm3oDcDlBROn5nFpzzSuXRA8zSrJbNB9s55EqTnZw7xVNa6nUxi9C\nd2Hqcbp9HD8EezlbMWJ4LASlYPzdBpAo5eyvK8YccE1QjlGlP7ZOf4+ekwlreqZ4\nfhRb4r/q49eW3aAWbJPu67MYu1iBMpdINZpMzDdE1wKjRXWu0j7Lr3SXjzgjD94E\nG+4VvJ0xc8WgjM9YSLxFN/5VZd+us7l6V18vOrdPDpAlJuTkmSpP0Xx4oUKJs7X+\n84CEB47GgUqf3bPadS8XRC2slEA+or5BJnPTVQ5YgTeWZE2kD3tLDOVHE7gLmV61\njYy2Icm+sosnfeECggEBAM3lVYO3D5Cw9Z4CkewrzMUxd7sSd5YqHavfEjvFc4Pk\n6Q6hsH1KR4Ai6loB8ugSz2SIS6KoqGD8ExvQxWy4AJf/n39hxb8/9IJ3b6IqBs64\n+ELJ8zw3QheER93FwK/KbawzLES9RkdpvDBSHFFfbGxjHpm+quQ8JcNIHTg43fb+\nTWe+mXYSjIWVCNssHBl5LRmkly37DxvBzu9YSZugESr80xSMDkBmWnpsq2Twh3q4\n2yP6jgfaZtV9AQQ01jkPgqpcuSoHm2qyqfiIr3LkA34OQmzWpyPn17If1DSJhlXo\nClSSl5Guqt9r0ifuBcMbl69OyAgpGr4N5sFxRk0wGkkCggEBAMt34hSqSiAUywYY\n2DNGc28GxAjdU3RMNBU1lF5k6nOD8o9IeWu7CGhwsYTR6hC/ZGCwL0dRc5/E7XhH\n3MgT247ago6+q7U0OfNirGU4Kdc3kwLvu0WyJ4nMQn5IWt4K3XpsyiXtDT3E9yjW\n6fQTev7a6A4zaJ/uHKnufUtaBrBukC3TcerehoIVYi185y1M33sVOOsiK7T/9JD3\n4MZiOqZAeZ9Uop9QKN7Vbd7ox5KHfLYT99DRmzDdDjf04ChG5llN7vJ9Sq6ZX665\nH3g6Ry2bxrYo2EkakoT9Lc77xNQF6Nn7WDAQuWqd7uzBmkm+a4+X/tPkWGOz+rTw\n/pYw+mECggEBAKQiMe1yPUJHD0YLHnB66h44tQ24RwS6RjUA+vQTD2cRUIiNdLgs\nQptvOgrOiuleNV4bGNBuSuwlhsYhw4BLno2NBYTyWEWBolVvCNrpTcv1wFLd0r0p\n/9HnbbLpNhXs9UjU8nFJwYCkVZTfoBtuSmyNB5PgXzLaj/AAyOpMywVe7C3Lz2JE\nnyjOCeVOYIgeBUnv32SUQxMJiQFcDDG3hHgUW+CBVcsYzP/TKT6qUBYQzwD7d8Xi\n4R9HK0xDIpMSPkO47xMGRWrlSoIJ1HNuOSqAC4vgAhWpeFVS8kN/bkuFUtbglVtZ\nNnYs6bdTE9zZXi4uS1/WBK+FPXLv7e8SbaECggEAI2gTDuCm5kVoVJhGzWA5/hmB\nPAUhSQpMHrT8Em4cXss6Q07q9A2l8NuNrZt6kNhwagdng7v7NdPY3ZBl/ntmKmZN\nxWUKzQCtIddW6Z/veO86F15NyBBZFXIOhzvwnrTtS3iX0JP0dlTZTv/Oe3DPk3aq\nsFJtHM6s44ZBYYAgzSAxTdl+80oGmtdrGnSRfRmlav1kjWLAKurXw8FTl9rKgGNA\nUUv/jGSe1DxnEMvtoSwQVjcS0im57vW0x8LEz5eTWMYwkvxGHm0/WU2Yb0I6mL4j\nPWrHwwPdRoF/cPNWa7eTsZBKdVN9iNHSu7yE9owXyHSpesI1IZf8Zq4bqPNpaA==\n-----END RSA PRIVATE KEY-----`),\n\t}\n\tblock, _ := pem.Decode(raw[size])\n\tkey, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprivKey, err := utils.RSAToPrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn privKey, nil\n}", "func (k *Kite) RSAKey(token *jwt.Token) (interface{}, error) {\n\tk.verifyOnce.Do(k.verifyInit)\n\n\tkontrolKey := k.KontrolKey()\n\n\tif kontrolKey == nil {\n\t\tpanic(\"kontrol key is not set in config\")\n\t}\n\n\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\treturn nil, errors.New(\"invalid signing method\")\n\t}\n\n\tclaims, ok := token.Claims.(*kitekey.KiteClaims)\n\tif !ok {\n\t\treturn nil, errors.New(\"token does not have valid claims\")\n\t}\n\n\tif claims.Issuer != k.Config.KontrolUser {\n\t\treturn nil, fmt.Errorf(\"issuer is not trusted: %s\", claims.Issuer)\n\t}\n\n\treturn kontrolKey, nil\n}", "func NewRSAPEM() ([]byte, error) {\n\tprivate, err := rsa.GenerateKey(rand.Reader, 4096)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = private.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn marshalToPEM(private)\n}", "func LoadRSAKey() interfaces.RSAKey {\n\tdeferFunc := logger.LogWithDefer(\"Load RSA keys...\")\n\tdefer deferFunc()\n\n\tsignBytes, err := ioutil.ReadFile(\"config/key/private.key\")\n\tif err != nil {\n\t\tpanic(\"Error when load private key. \" + err.Error() + \". Please generate RSA keys\")\n\t}\n\tprivateKey, err := jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n\tif err != nil {\n\t\tpanic(\"Error when load private key. \" + err.Error())\n\t}\n\n\tverifyBytes, err := ioutil.ReadFile(\"config/key/public.pem\")\n\tif err != nil {\n\t\tpanic(\"Error when load public key. \" + err.Error() + \". Please generate RSA keys\")\n\t}\n\tpublicKey, err := jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n\tif err != nil {\n\t\tpanic(\"Error when load public key. \" + err.Error())\n\t}\n\n\treturn &key{\n\t\tprivate: privateKey, public: publicKey,\n\t}\n}", "func (_WyvernExchange *WyvernExchangeSession) ValidateOrderParameters(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) (bool, error) {\n\treturn _WyvernExchange.Contract.ValidateOrderParameters(&_WyvernExchange.CallOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n}", "func ParsePKIXPublicKey(derBytes []byte) (interface{}, error) {\n\tvar pki publicKeyInfo\n\tif rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {\n\t\treturn nil, err\n\t} else if len(rest) != 0 {\n\t\treturn nil, errors.New(\"x509: trailing data after ASN.1 of public-key\")\n\t}\n\tif !oidPublicKeyECDSA.Equal(pki.Algorithm.Algorithm) {\n\t\treturn x509.ParsePKIXPublicKey(derBytes)\n\t}\n\n\tasn1Data := pki.PublicKey.RightAlign()\n\tparamsData := pki.Algorithm.Parameters.FullBytes\n\tnamedCurveOID := new(asn1.ObjectIdentifier)\n\trest, err := asn1.Unmarshal(paramsData, namedCurveOID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(rest) != 0 {\n\t\treturn nil, errors.New(\"x509: trailing data after ECDSA parameters\")\n\t}\n\tnamedCurve := namedCurveFromOID(*namedCurveOID)\n\tif namedCurve == nil {\n\t\treturn nil, errors.New(\"x509: unsupported elliptic curve\")\n\t}\n\tx, y := elliptic.Unmarshal(namedCurve, asn1Data)\n\tif x == nil {\n\t\treturn nil, errors.New(\"x509: failed to unmarshal elliptic curve point\")\n\t}\n\tpub := &ecdsa.PublicKey{\n\t\tCurve: namedCurve,\n\t\tX: x,\n\t\tY: y,\n\t}\n\treturn pub, nil\n}", "func (lib *PKCS11Lib) exportRSAPublicKey(session pkcs11.SessionHandle, pubHandle pkcs11.ObjectHandle) (crypto.PublicKey, error) {\n\tlogger.Tracef(\"session=0x%X, obj=0x%X\", session, pubHandle)\n\ttemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS, nil),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, nil),\n\t}\n\texported, err := lib.Ctx.GetAttributeValue(session, pubHandle, template)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tvar modulus = new(big.Int)\n\tmodulus.SetBytes(exported[0].Value)\n\tvar bigExponent = new(big.Int)\n\tbigExponent.SetBytes(exported[1].Value)\n\tif bigExponent.BitLen() > 32 {\n\t\treturn nil, errors.WithStack(errMalformedRSAKey)\n\t}\n\tif bigExponent.Sign() < 1 {\n\t\treturn nil, errors.WithStack(errMalformedRSAKey)\n\t}\n\texponent := int(bigExponent.Uint64())\n\tresult := rsa.PublicKey{\n\t\tN: modulus,\n\t\tE: exponent,\n\t}\n\tif result.E < 2 {\n\t\treturn nil, errors.WithStack(errMalformedRSAKey)\n\t}\n\treturn &result, nil\n}", "func (session *Session) GenerateRSAKeyPair(tokenLabel string, tokenPersistent bool, expDate time.Time, bits int) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) {\n\tif session == nil || session.Ctx == nil {\n\t\treturn 0, 0, fmt.Errorf(\"session not initialized\")\n\t}\n\ttoday := time.Now()\n\tpublicKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, []byte(tokenLabel)),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, tokenPersistent),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_START_DATE, today),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_END_DATE, expDate),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, []byte{1, 0, 1}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS_BITS, bits),\n\t}\n\n\tprivateKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, []byte(tokenLabel)),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, tokenPersistent),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_START_DATE, today),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_END_DATE, expDate),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SIGN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true),\n\t}\n\n\tpubKey, privKey, err := session.Ctx.GenerateKeyPair(\n\t\tsession.Handle,\n\t\t[]*pkcs11.Mechanism{\n\t\t\tpkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_KEY_PAIR_GEN, nil),\n\t\t},\n\t\tpublicKeyTemplate,\n\t\tprivateKeyTemplate,\n\t)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\treturn pubKey, privKey, nil\n}", "func (m *PorositySimulationParameters) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateBeamDiameter(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGeometryHeight(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGeometryLength(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGeometryWidth(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHatchSpacingValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHeaterTemperature(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLaserWattageValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLayerRotationAngle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLayerThicknessValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateMeshLayersPerLayer(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateScanSpeedValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSlicingStripeWidthValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStartingLayerAngle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) {\n\tvar privKey ecPrivateKey\n\tif _, err := asn1.Unmarshal(der, &privKey); err != nil {\n\t\treturn nil, errors.New(\"x509: failed to parse EC private key: \" + err.Error())\n\t}\n\tif privKey.Version != ecPrivKeyVersion {\n\t\treturn nil, fmt.Errorf(\"x509: unknown EC private key version %d\", privKey.Version)\n\t}\n\n\tvar curve elliptic.Curve\n\tif namedCurveOID != nil {\n\t\tcurve = namedCurveFromOID(*namedCurveOID)\n\t} else {\n\t\tcurve = namedCurveFromOID(privKey.NamedCurveOID)\n\t}\n\tif curve == nil {\n\t\treturn nil, errors.New(\"x509: unknown elliptic curve\")\n\t}\n\n\tk := new(big.Int).SetBytes(privKey.PrivateKey)\n\tcurveOrder := curve.Params().N\n\tif k.Cmp(curveOrder) >= 0 {\n\t\treturn nil, errors.New(\"x509: invalid elliptic curve private key value\")\n\t}\n\tpriv := new(ecdsa.PrivateKey)\n\tpriv.Curve = curve\n\tpriv.D = k\n\n\tprivateKey := make([]byte, (curveOrder.BitLen()+7)/8)\n\n\t// Some private keys have leading zero padding. This is invalid\n\t// according to [SEC1], but this code will ignore it.\n\tfor len(privKey.PrivateKey) > len(privateKey) {\n\t\tif privKey.PrivateKey[0] != 0 {\n\t\t\treturn nil, errors.New(\"x509: invalid private key length\")\n\t\t}\n\t\tprivKey.PrivateKey = privKey.PrivateKey[1:]\n\t}\n\n\t// Some private keys remove all leading zeros, this is also invalid\n\t// according to [SEC1] but since OpenSSL used to do this, we ignore\n\t// this too.\n\tcopy(privateKey[len(privateKey)-len(privKey.PrivateKey):], privKey.PrivateKey)\n\tpriv.X, priv.Y = curve.ScalarBaseMult(privateKey)\n\n\treturn priv, nil\n}", "func ParsePublicKey(data []byte) (SignatureValidator, error) {\r\n\ttmpKey, err := x509.ParsePKIXPublicKey(data)\r\n\trsaKey, ok := tmpKey.(*rsa.PublicKey)\r\n\tif err != nil || !ok {\r\n\t\treturn nil, errors.New(\"invalid key type, only RSA is supported\")\r\n\t}\r\n\treturn &rsaPublicKey{rsaKey}, nil\r\n}", "func (m *EventChannelParameters) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateBatch(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSMTPSecurity(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 ValidateOracleParams(i interface{}) error {\n\tparams, isOracleParams := i.(OracleParams)\n\tif !isOracleParams {\n\t\treturn fmt.Errorf(\"invalid parameters type: %s\", i)\n\t}\n\n\tif params.AskCount < params.MinCount {\n\t\treturn fmt.Errorf(\"invalid ask count: %d, min count: %d\", params.AskCount, params.MinCount)\n\t}\n\n\tif params.MinCount <= 0 {\n\t\treturn fmt.Errorf(\"invalid min count: %d\", params.MinCount)\n\t}\n\n\tif params.PrepareGas <= 0 {\n\t\treturn fmt.Errorf(\"invalid prepare gas: %d\", params.PrepareGas)\n\t}\n\n\tif params.ExecuteGas <= 0 {\n\t\treturn fmt.Errorf(\"invalid execute gas: %d\", params.ExecuteGas)\n\t}\n\n\terr := params.FeeAmount.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ParsePrivateKey(derBlob []byte) (parsedPrivateKey interface{}, keyType string, err error) {\n // First check if it is an RSA key\n parsedPrivateKey, err = x509.ParsePKCS1PrivateKey(derBlob)\n // If we get an error, it might be an EC key or malformed\n if err != nil {\n parsedPrivateKey, err = x509.ParseECPrivateKey(derBlob)\n if err != nil {\n return nil, \"\", err // if we encounter an error then the key is malformed (or not EC/RSA)\n }\n // Because we have a return inside the if, this is essentially the else part\n // If ParseECPrivateKey was sucessfulthen it's an EC key\n keyType = \"EC\"\n return parsedPrivateKey, keyType, err // no naked returns\n }\n // If ParsePKCS1PrivateKey was successful then it's an RSA key\n keyType = \"RSA\"\n return parsedPrivateKey, keyType, err\n\n // I could do a bunch of if-else and do only one return in the end, but I think this is more readable\n}", "func (p Params) Validate() error {\n\tif err := validateActiveParam(p.Active); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateDelegatorParams(p.DelegatorDistributionSchedules); err != nil {\n\t\treturn err\n\t}\n\n\treturn validateLPParams(p.LiquidityProviderSchedules)\n}", "func NewRSAKeyPair() (*RSAKeyPair, error) {\n\treader := rand.Reader\n\tprivateKey, err := rsa.GenerateKey(reader, bitSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newRSAKeyPair(privateKey, &privateKey.PublicKey)\n}", "func GenerateRSA() (*rsa.PrivateKey, rsa.PublicKey) {\n\treader := rand.Reader\n\tbitSize := 2048\n\tkey, err := rsa.GenerateKey(reader, bitSize)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error generating key: %v\", err)\n\t\t// TODO: handle error\n\t}\n\treturn key, key.PublicKey\n}", "func (m *PaymentServiceItemParam) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOrigin(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentServiceItemID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func parsePublicKey(pemBytes []byte) (SignatureValidator, error) {\r\n\tgob.Register(rsaPrivateKey{})\r\n\tblock, _ := pem.Decode(pemBytes)\r\n\tif block == nil {\r\n\t\treturn nil, errors.New(\"no key found\")\r\n\t}\r\n\r\n\tswitch block.Type {\r\n\tcase \"PUBLIC KEY\":\r\n\t\treturn ParsePublicKey(block.Bytes)\r\n\tdefault:\r\n\t\treturn nil, fmt.Errorf(\"unsupported key block type %q\", block.Type)\r\n\t}\r\n}", "func (_WyvernExchange *WyvernExchangeCallerSession) ValidateOrderParameters(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) (bool, error) {\n\treturn _WyvernExchange.Contract.ValidateOrderParameters(&_WyvernExchange.CallOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n}", "func GenerateKeyPair(bits int) (keypair *KeyPair, err error) {\n\tkeypair = new(KeyPair)\n\tkeypair.PublicKey = new(PublicKey)\n\tkeypair.PrivateKey = new(PrivateKey)\n\n\tif bits == 0 {\n\t\terr = errors.New(\"RSA modulus size must not be zero.\")\n\t\treturn\n\t}\n\tif bits%8 != 0 {\n\t\terr = errors.New(\"RSA modulus size must be a multiple of 8.\")\n\t\treturn\n\t}\n\n\tfor limit := 0; limit < 1000; limit++ {\n\t\tvar tempKey *rsa.PrivateKey\n\t\ttempKey, err = rsa.GenerateKey(rand.Reader, bits)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif len(tempKey.Primes) != 2 {\n\t\t\terr = errors.New(\"RSA package generated a weird set of primes (i.e. not two)\")\n\t\t\treturn\n\t\t}\n\n\t\tp := tempKey.Primes[0]\n\t\tq := tempKey.Primes[1]\n\n\t\tif p.Cmp(q) == 0 {\n\t\t\terr = errors.New(\"RSA keypair factors were equal. This is really unlikely dependent on the bitsize and it appears something horrible has happened.\")\n\t\t\treturn\n\t\t}\n\t\tif gcd := new(big.Int).GCD(nil, nil, p, q); gcd.Cmp(big.NewInt(1)) != 0 {\n\t\t\terr = errors.New(\"RSA primes were not relatively prime!\")\n\t\t\treturn\n\t\t}\n\n\t\tmodulus := new(big.Int).Mul(p, q)\n\n\t\tpublicExp := big.NewInt(3)\n\t\t//publicExp := big.NewInt(65537)\n\n\t\t//totient = (p-1) * (q-1)\n\t\ttotient := new(big.Int)\n\t\ttotient.Sub(p, big.NewInt(1))\n\t\ttotient.Mul(totient, new(big.Int).Sub(q, big.NewInt(1)))\n\n\t\tif gcd := new(big.Int).GCD(nil, nil, publicExp, totient); gcd.Cmp(big.NewInt(1)) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tprivateExp := new(big.Int).ModInverse(publicExp, totient)\n\t\tkeypair.PublicKey.Modulus = modulus\n\t\tkeypair.PrivateKey.Modulus = modulus\n\t\tkeypair.PublicKey.PublicExp = publicExp\n\t\tkeypair.PrivateKey.PrivateExp = privateExp\n\t\treturn\n\t}\n\terr = errors.New(\"Failed to generate a within the limit!\")\n\treturn\n\n}", "func getRSAPublicKey(modulus []byte, exponent []byte) (*rsa.PublicKey, error) {\n\tn := new(big.Int).SetBytes(modulus)\n\te := new(big.Int).SetBytes(exponent)\n\teInt := int(e.Int64())\n\trsaPubKey := rsa.PublicKey{N: n, E: eInt}\n\treturn &rsaPubKey, nil\n}", "func (pr *PasswordRecord) GetKeyRSA(password string) (key rsa.PrivateKey, err error) {\n\tif pr.Type != RSARecord {\n\t\treturn key, errors.New(\"Invalid function for record type\")\n\t}\n\n\terr = pr.ValidatePassword(password)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpassKey, err := derivePasswordKey(password, pr.KeySalt)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trsaExponentPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAExp, pr.RSAKey.RSAExpIV, passKey)\n\tif err != nil {\n\t\treturn\n\t}\n\trsaExponent, err := padding.RemovePadding(rsaExponentPadded)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trsaPrimePPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAPrimeP, pr.RSAKey.RSAPrimePIV, passKey)\n\tif err != nil {\n\t\treturn\n\t}\n\trsaPrimeP, err := padding.RemovePadding(rsaPrimePPadded)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trsaPrimeQPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAPrimeQ, pr.RSAKey.RSAPrimeQIV, passKey)\n\tif err != nil {\n\t\treturn\n\t}\n\trsaPrimeQ, err := padding.RemovePadding(rsaPrimeQPadded)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tkey.PublicKey = pr.RSAKey.RSAPublic\n\tkey.D = big.NewInt(0).SetBytes(rsaExponent)\n\tkey.Primes = []*big.Int{big.NewInt(0), big.NewInt(0)}\n\tkey.Primes[0].SetBytes(rsaPrimeP)\n\tkey.Primes[1].SetBytes(rsaPrimeQ)\n\n\terr = key.Validate()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func Validate(params Params) (err error) {\n\tif params.Length <= 0 {\n\t\treturn errors.New(\"Length must be more than 0\")\n\t}\n\tif params.Square <= 0 {\n\t\treturn errors.New(\"Square must be more than 0\")\n\t}\n\treturn nil\n}", "func encryptRSARecord(newRec *PasswordRecord, rsaPriv *rsa.PrivateKey, passKey []byte) (err error) {\n\tif newRec.RSAKey.RSAExpIV, err = symcrypt.MakeRandom(16); err != nil {\n\t\treturn\n\t}\n\n\tpaddedExponent := padding.AddPadding(rsaPriv.D.Bytes())\n\tif newRec.RSAKey.RSAExp, err = symcrypt.EncryptCBC(paddedExponent, newRec.RSAKey.RSAExpIV, passKey); err != nil {\n\t\treturn\n\t}\n\n\tif newRec.RSAKey.RSAPrimePIV, err = symcrypt.MakeRandom(16); err != nil {\n\t\treturn\n\t}\n\n\tpaddedPrimeP := padding.AddPadding(rsaPriv.Primes[0].Bytes())\n\tif newRec.RSAKey.RSAPrimeP, err = symcrypt.EncryptCBC(paddedPrimeP, newRec.RSAKey.RSAPrimePIV, passKey); err != nil {\n\t\treturn\n\t}\n\n\tif newRec.RSAKey.RSAPrimeQIV, err = symcrypt.MakeRandom(16); err != nil {\n\t\treturn\n\t}\n\n\tpaddedPrimeQ := padding.AddPadding(rsaPriv.Primes[1].Bytes())\n\tnewRec.RSAKey.RSAPrimeQ, err = symcrypt.EncryptCBC(paddedPrimeQ, newRec.RSAKey.RSAPrimeQIV, passKey)\n\treturn\n}", "func GetRSAKeys(authserver string) (map[string]rsa.PublicKey, error) {\n\tjwksURI, err := getJwksURI(authserver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting jwks_uri failed: %w\", err)\n\t}\n\n\tkeyList := jwks{}\n\terr = getJSON(jwksURI, &keyList)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetching jwks failed: %w\", err)\n\t}\n\n\tkeys := make(map[string]rsa.PublicKey)\n\n\tfor _, key := range keyList.Keys {\n\n\t\tif key.Kty == \"RSA\" {\n\n\t\t\te, err := fromB64(key.E)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"big int from E: %w\", err)\n\t\t\t}\n\t\t\tn, err := fromB64(key.N)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"big int from N: %w\", err)\n\t\t\t}\n\n\t\t\tkeys[key.Kid] = rsa.PublicKey{N: &n, E: int(e.Int64())}\n\n\t\t}\n\t}\n\n\treturn keys, nil\n\n}", "func ParsePublicKey(keyBytes []byte) (interface{}, error) {\n\tpk := PublicKeyData{}\n\twebauthncbor.Unmarshal(keyBytes, &pk)\n\n\tswitch COSEKeyType(pk.KeyType) {\n\tcase OctetKey:\n\t\tvar o OKPPublicKeyData\n\n\t\twebauthncbor.Unmarshal(keyBytes, &o)\n\t\to.PublicKeyData = pk\n\n\t\treturn o, nil\n\tcase EllipticKey:\n\t\tvar e EC2PublicKeyData\n\n\t\twebauthncbor.Unmarshal(keyBytes, &e)\n\t\te.PublicKeyData = pk\n\n\t\treturn e, nil\n\tcase RSAKey:\n\t\tvar r RSAPublicKeyData\n\n\t\twebauthncbor.Unmarshal(keyBytes, &r)\n\t\tr.PublicKeyData = pk\n\n\t\treturn r, nil\n\tdefault:\n\t\treturn nil, ErrUnsupportedKey\n\t}\n}", "func ValidatePublicKeyRecord(k u.Key, val []byte) error {\n\tkeyparts := bytes.Split([]byte(k), []byte(\"/\"))\n\tif len(keyparts) < 3 {\n\t\treturn errors.New(\"invalid key\")\n\t}\n\n\tpkh := u.Hash(val)\n\tif !bytes.Equal(keyparts[2], pkh) {\n\t\treturn errors.New(\"public key does not match storage key\")\n\t}\n\treturn nil\n}", "func ECPPublicKeyValidateBLS383(W []byte) (err error) {\n\n\tWOct := bindings.NewOctet(W)\n\tdefer WOct.Free()\n\n\terr = bindings.ECPPublicKeyValidateBLS383(WOct)\n\n\treturn\n}", "func parseAndCheckParameters(params ...Parameter) (*parameters, error) {\n\tparameters := parameters{\n\t\tlogLevel: zerolog.GlobalLevel(),\n\t}\n\tfor _, p := range params {\n\t\tif params != nil {\n\t\t\tp.apply(&parameters)\n\t\t}\n\t}\n\n\tif parameters.monitor == nil {\n\t\t// Use no-op monitor.\n\t\tparameters.monitor = &noopMonitor{}\n\t}\n\tif parameters.signer == nil {\n\t\treturn nil, errors.New(\"no signer specified\")\n\t}\n\tif parameters.lister == nil {\n\t\treturn nil, errors.New(\"no lister specified\")\n\t}\n\tif parameters.process == nil {\n\t\treturn nil, errors.New(\"no process specified\")\n\t}\n\tif parameters.walletManager == nil {\n\t\treturn nil, errors.New(\"no wallet manager specified\")\n\t}\n\tif parameters.accountManager == nil {\n\t\treturn nil, errors.New(\"no account manager specified\")\n\t}\n\tif parameters.peers == nil {\n\t\treturn nil, errors.New(\"no peers specified\")\n\t}\n\tif parameters.name == \"\" {\n\t\treturn nil, errors.New(\"no name specified\")\n\t}\n\tif parameters.id == 0 {\n\t\treturn nil, errors.New(\"no ID specified\")\n\t}\n\tif parameters.listenAddress == \"\" {\n\t\treturn nil, errors.New(\"no listen address specified\")\n\t}\n\tif len(parameters.serverCert) == 0 {\n\t\treturn nil, errors.New(\"no server certificate specified\")\n\t}\n\tif len(parameters.serverKey) == 0 {\n\t\treturn nil, errors.New(\"no server key specified\")\n\t}\n\n\treturn &parameters, nil\n}", "func (o *UserCurrentGetGPGKeyOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateCanCertify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCanEncryptComms(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCanEncryptStorage(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCanSign(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateEmails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateExpires(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateKeyID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePrimaryKeyID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePublicKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSubsKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func validateServiceParameters(parameters []*Service_Parameter, data *types.Struct) error {\n\tvar errs xerrors.Errors\n\n\tfor _, p := range parameters {\n\t\tvar value *types.Value\n\t\tif data != nil && data.Fields != nil {\n\t\t\tvalue = data.Fields[p.Key]\n\t\t}\n\t\tif err := p.Validate(value); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn errs.ErrorOrNil()\n}", "func ValidateParams(paramSpec []GeneratorParam, params map[string]interface{}) error {\n\tallErrs := []error{}\n\tfor ix := range paramSpec {\n\t\tif paramSpec[ix].Required {\n\t\t\tvalue, found := params[paramSpec[ix].Name]\n\t\t\tif !found || IsZero(value) {\n\t\t\t\tallErrs = append(allErrs, fmt.Errorf(\"Parameter: %s is required\", paramSpec[ix].Name))\n\t\t\t}\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(allErrs)\n}", "func (o *UIParameter) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := elemental.ValidateRequiredString(\"key\", o.Key); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidateRequiredString(\"type\", string(o.Type)); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"type\", string(o.Type), []string{\"Boolean\", \"Checkbox\", \"CVSSThreshold\", \"DangerMessage\", \"Duration\", \"Enum\", \"Endpoint\", \"FileDrop\", \"Float\", \"FloatSlice\", \"InfoMessage\", \"Integer\", \"IntegerSlice\", \"JSON\", \"List\", \"Message\", \"Namespace\", \"Password\", \"String\", \"StringSlice\", \"Switch\", \"TagsExpression\", \"Title\", \"WarningMessage\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\t// Custom object validation.\n\tif err := ValidateUIParameters(o); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (asap *ASAP) Validate(jwt jwt.JWT, publicKey cr.PublicKey) error {\n\theader := jwt.(jws.JWS).Protected()\n\tkid := header.Get(KeyID).(string)\n\talg := header.Get(algorithm).(string)\n\n\tsigningMethod, err := getSigningMethod(alg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn jwt.Validate(publicKey, signingMethod, validator.GenerateValidator(kid, asap.ServiceID))\n}", "func (g *Gossiper) RSAVerifyPMSignature(msg utils.PrivateMessage) bool {\n\thash := utils.HASH_ALGO.New()\n\n\tbytes, e := json.Marshal(msg)\n\tutils.HandleError(e)\n\thash.Write(bytes)\n\thashed := hash.Sum(nil)\n\n\tpubKeyBytes, e := hex.DecodeString(msg.Origin)\n\tutils.HandleError(e)\n\tpubKey, e := x509.ParsePKCS1PublicKey(pubKeyBytes)\n\tutils.HandleError(e)\n\n\te = rsa.VerifyPKCS1v15(pubKey, utils.HASH_ALGO, hashed, msg.Signature)\n\tutils.HandleError(e)\n\tif e == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func (o *UserListGPGKeysOKBodyItems0SubkeysItems0SubkeysItems0) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateEmails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateExpires(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSubsKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func LoadPublicKey(data []byte) (interface{}, error) {\n\tinput := data\n\n\tblock, _ := pem.Decode(data)\n\tif block != nil {\n\t\tinput = block.Bytes\n\t}\n\n\t// Try to load SubjectPublicKeyInfo\n\tpub, err0 := x509.ParsePKIXPublicKey(input)\n\tif err0 == nil {\n\t\treturn pub, nil\n\t}\n\n\tcert, err1 := x509.ParseCertificate(input)\n\tif err1 == nil {\n\t\treturn cert.PublicKey, nil\n\t}\n\n\tjwk, err2 := LoadJSONWebKey(data, true)\n\tif err2 == nil {\n\t\treturn jwk, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"JOSE: parse error, got '%s', '%s' and '%s'\", err0, err1, err2)\n}", "func rsaEqual(priv *rsa.PrivateKey, x crypto.PrivateKey) bool {\n\txx, ok := x.(*rsa.PrivateKey)\n\tif !ok {\n\t\treturn false\n\t}\n\tif !(priv.PublicKey.N.Cmp(xx.N) == 0 && priv.PublicKey.E == xx.E) || priv.D.Cmp(xx.D) != 0 {\n\t\treturn false\n\t}\n\tif len(priv.Primes) != len(xx.Primes) {\n\t\treturn false\n\t}\n\tfor i := range priv.Primes {\n\t\tif priv.Primes[i].Cmp(xx.Primes[i]) != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p *Provider) GetRSAKeys() (key *rsa.PrivateKey, err error) {\n\tif p.key == nil {\n\t\treturn nil, ErrKeyRequired\n\t}\n\n\tvar ok bool\n\tif key, ok = p.key.(*rsa.PrivateKey); !ok {\n\t\treturn nil, fmt.Errorf(\"private key is not RSA but is %T\", p.key)\n\t}\n\n\tvar cert *x509.Certificate\n\tif cert, err = p.GetLeafCertificate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey.PublicKey = *cert.PublicKey.(*rsa.PublicKey)\n\treturn key, nil\n}", "func ValidateParameters(r *Request) {\n\tif r.ParamsFilled() {\n\t\tv := validator{errors: []string{}}\n\t\tv.validateAny(reflect.ValueOf(r.Params), \"\")\n\n\t\tif count := len(v.errors); count > 0 {\n\t\t\tformat := \"%d validation errors:\\n- %s\"\n\t\t\tmsg := fmt.Sprintf(format, count, strings.Join(v.errors, \"\\n- \"))\n\t\t\tr.Error = apierr.New(\"InvalidParameter\", msg, nil)\n\t\t}\n\t}\n}", "func (m *AlertChannelEmailParams) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateTextTemplate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTitleTemplate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDefaultRecipients(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDefaultSMTPSettings(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRecipients(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSMTPData(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 *JwtComponent) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif v, ok := interface{}(m.GetPrivateKey()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn JwtComponentValidationError{\n\t\t\t\tfield: \"PrivateKey\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetPublicKey()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn JwtComponentValidationError{\n\t\t\t\tfield: \"PublicKey\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func isValidKeyPair(param []string) bool {\n\treturn len(param) == 2\n}", "func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {\n\tvar err error\n\n\t// Parse PEM block\n\tvar block *pem.Block\n\tif block, _ = pem.Decode(key); block == nil {\n\t\treturn nil, ErrKeyMustBePEMEncoded\n\t}\n\n\t// Parse the key\n\tvar parsedKey interface{}\n\tif parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {\n\t\tif cert, err := x509.ParseCertificate(block.Bytes); err == nil {\n\t\t\tparsedKey = cert.PublicKey\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar pkey *rsa.PublicKey\n\tvar ok bool\n\tif pkey, ok = parsedKey.(*rsa.PublicKey); !ok {\n\t\treturn nil, ErrNotRSAPublicKey\n\t}\n\n\treturn pkey, nil\n}", "func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {\n\tvar err error\n\n\t// Parse PEM block\n\tvar block *pem.Block\n\tif block, _ = pem.Decode(key); block == nil {\n\t\treturn nil, ErrKeyMustBePEMEncoded\n\t}\n\n\t// Parse the key\n\tvar parsedKey interface{}\n\tif parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {\n\t\tif cert, err := x509.ParseCertificate(block.Bytes); err == nil {\n\t\t\tparsedKey = cert.PublicKey\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar pkey *rsa.PublicKey\n\tvar ok bool\n\tif pkey, ok = parsedKey.(*rsa.PublicKey); !ok {\n\t\treturn nil, ErrNotRSAPublicKey\n\t}\n\n\treturn pkey, nil\n}", "func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {\n\tvar err error\n\n\t// Parse PEM block\n\tvar block *pem.Block\n\tif block, _ = pem.Decode(key); block == nil {\n\t\treturn nil, ErrKeyMustBePEMEncoded\n\t}\n\n\t// Parse the key\n\tvar parsedKey interface{}\n\tif parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {\n\t\tif cert, err := x509.ParseCertificate(block.Bytes); err == nil {\n\t\t\tparsedKey = cert.PublicKey\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar pkey *ecdsa.PublicKey\n\tvar ok bool\n\tif pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok {\n\t\treturn nil, ErrNotECPublicKey\n\t}\n\n\treturn pkey, nil\n}", "func (r *RSA) Init() {\n\tlog.Infof(\"Generating %d bit RSA key...\", RSA_KEY_LENGTH)\n\n\t// generate RSA key\n\tvar pKey, err = rsa.GenerateKey(rand.Reader, RSA_KEY_LENGTH)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating RSA key:\" + err.Error())\n\t}\n\n\tr.privateKey = pKey\n\n\t// encode key to ASN.1 PublicKey Type\n\tvar key, err2 = asn1.Marshal(r.privateKey.PublicKey)\n\tif err2 != nil {\n\t\tlog.Fatal(\"Error encoding Public RSA key:\" + err2.Error())\n\t}\n\n\t// move public key to array\n\tcopy(r.PublicKey[:], key)\n}", "func (o *TppCertificateParams) GetPublicKeyOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.PublicKey, true\n}", "func ParsePubKey(pubKeyStr []byte) (key *PublicKey, err error) {\n\tpubkey := PublicKey{}\n\n\tif len(pubKeyStr) == 0 {\n\t\treturn nil, errors.New(\"pubkey string is empty\")\n\t}\n\n\tformat := pubKeyStr[0]\n\tybit := (format & 0x1) == 0x1\n\tformat &= ^byte(0x1)\n\n\tswitch len(pubKeyStr) {\n\tcase PubKeyBytesLenUncompressed:\n\t\tif format != pubKeyUncompressed && format != pubKeyHybrid {\n\t\t\treturn nil, fmt.Errorf(\"invalid magic in pubkey str: \"+\n\t\t\t\t\"%d\", pubKeyStr[0])\n\t\t}\n\n\t\tpubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])\n\t\tpubkey.Y = new(big.Int).SetBytes(pubKeyStr[33:])\n\t\t// hybrid keys have extra information, make use of it.\n\t\tif format == pubKeyHybrid && ybit != isOdd(pubkey.Y) {\n\t\t\treturn nil, fmt.Errorf(\"ybit doesn't match oddness\")\n\t\t}\n\tcase PubKeyBytesLenCompressed:\n\t\t// format is 0x2 | solution, <X coordinate>\n\t\t// solution determines which solution of the curve we use.\n\t\t/// y^2 = x^3 + Curve.B\n\t\tif format != pubKeyCompressed {\n\t\t\treturn nil, fmt.Errorf(\"invalid magic in compressed \"+\n\t\t\t\t\"pubkey string: %d\", pubKeyStr[0])\n\t\t}\n\t\tpubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])\n\t\tpubkey.Y, err = decompressPoint(pubkey.X, ybit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault: // wrong!\n\t\treturn nil, fmt.Errorf(\"invalid pub key length %d\",\n\t\t\tlen(pubKeyStr))\n\t}\n\n\tif pubkey.X.Cmp(secp256k1.Params().P) >= 0 {\n\t\treturn nil, fmt.Errorf(\"pubkey X parameter is >= to P\")\n\t}\n\tif pubkey.Y.Cmp(secp256k1.Params().P) >= 0 {\n\t\treturn nil, fmt.Errorf(\"pubkey Y parameter is >= to P\")\n\t}\n\tif !secp256k1.IsOnCurve(pubkey.X, pubkey.Y) {\n\t\treturn nil, fmt.Errorf(\"pubkey isn't on secp256k1 curve\")\n\t}\n\treturn &pubkey, nil\n}", "func (pk PublicKey) JWK() JWK {\n\tentry, ok := pk[JwkProperty]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tjson, ok := entry.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn NewJWK(json)\n}", "func ConvertToPPK(privateKey *rsa.PrivateKey, pub []byte) ([]byte, error) {\n\t// https://the.earth.li/~sgtatham/putty/0.76/htmldoc/AppendixC.html#ppk\n\t// RSA keys are stored using an algorithm-name of 'ssh-rsa'. (Keys stored like this are also used by the updated RSA signature schemes that use\n\t// hashes other than SHA-1. The public key data has already provided the key modulus and the public encoding exponent. The private data stores:\n\t// mpint: the private decoding exponent of the key.\n\t// mpint: one prime factor p of the key.\n\t// mpint: the other prime factor q of the key. (RSA keys stored in this format are expected to have exactly two prime factors.)\n\t// mpint: the multiplicative inverse of q modulo p.\n\tppkPrivateKey := new(bytes.Buffer)\n\n\t// mpint: the private decoding exponent of the key.\n\t// this is known as 'D'\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(privateKey.D))\n\n\t// mpint: one prime factor p of the key.\n\t// this is known as 'P'\n\t// the RSA standard dictates that P > Q\n\t// for some reason what PuTTY names 'P' is Primes[1] to Go, and what PuTTY names 'Q' is Primes[0] to Go\n\tP, Q := privateKey.Primes[1], privateKey.Primes[0]\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(P))\n\n\t// mpint: the other prime factor q of the key. (RSA keys stored in this format are expected to have exactly two prime factors.)\n\t// this is known as 'Q'\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(Q))\n\n\t// mpint: the multiplicative inverse of q modulo p.\n\t// this is known as 'iqmp'\n\tiqmp := new(big.Int).ModInverse(Q, P)\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(iqmp))\n\n\t// now we need to base64-encode the PPK-formatted private key which is made up of the above values\n\tppkPrivateKeyBase64 := make([]byte, base64.StdEncoding.EncodedLen(ppkPrivateKey.Len()))\n\tbase64.StdEncoding.Encode(ppkPrivateKeyBase64, ppkPrivateKey.Bytes())\n\n\t// read Teleport public key\n\t// fortunately, this is the one thing that's in exactly the same format that the PPK file uses, so we can just copy it verbatim\n\t// remove ssh-rsa plus additional space from beginning of string if present\n\tif !bytes.HasPrefix(pub, []byte(constants.SSHRSAType+\" \")) {\n\t\treturn nil, trace.BadParameter(\"pub does not appear to be an ssh-rsa public key\")\n\t}\n\tpub = bytes.TrimSuffix(bytes.TrimPrefix(pub, []byte(constants.SSHRSAType+\" \")), []byte(\"\\n\"))\n\n\t// the PPK file contains an anti-tampering MAC which is made up of various values which appear in the file.\n\t// copied from Section C.3 of https://the.earth.li/~sgtatham/putty/0.76/htmldoc/AppendixC.html#ppk:\n\t// hex-mac-data is a hexadecimal-encoded value, 64 digits long (i.e. 32 bytes), generated using the HMAC-SHA-256 algorithm with the following binary data as input:\n\t// string: the algorithm-name header field.\n\t// string: the encryption-type header field.\n\t// string: the key-comment-string header field.\n\t// string: the binary public key data, as decoded from the base64 lines after the 'Public-Lines' header.\n\t// string: the plaintext of the binary private key data, as decoded from the base64 lines after the 'Private-Lines' header.\n\n\t// these values are also used in the MAC generation, so we declare them as variables\n\tkeyType := constants.SSHRSAType\n\tencryptionType := \"none\"\n\t// as work for the future, it'd be nice to get the proxy/user pair name in here to make the name more\n\t// of a unique identifier. this has to be done at generation time because the comment is part of the MAC\n\tfileComment := \"teleport-generated-ppk\"\n\n\t// string: the algorithm-name header field.\n\tmacKeyType := getRFC4251String([]byte(keyType))\n\t// create a buffer to hold the elements needed to generate the MAC\n\tmacInput := new(bytes.Buffer)\n\tbinary.Write(macInput, binary.LittleEndian, macKeyType)\n\n\t// string: the encryption-type header field.\n\tmacEncryptionType := getRFC4251String([]byte(encryptionType))\n\tbinary.Write(macInput, binary.BigEndian, macEncryptionType)\n\n\t// string: the key-comment-string header field.\n\tmacComment := getRFC4251String([]byte(fileComment))\n\tbinary.Write(macInput, binary.BigEndian, macComment)\n\n\t// base64-decode the Teleport public key, as we need its binary representation to generate the MAC\n\tdecoded := make([]byte, base64.StdEncoding.EncodedLen(len(pub)))\n\tn, err := base64.StdEncoding.Decode(decoded, pub)\n\tif err != nil {\n\t\treturn nil, trace.Errorf(\"could not base64-decode public key: %v, got %v bytes successfully\", err, n)\n\t}\n\tdecoded = decoded[:n]\n\t// append the decoded public key bytes to the MAC buffer\n\tmacPublicKeyData := getRFC4251String(decoded)\n\tbinary.Write(macInput, binary.BigEndian, macPublicKeyData)\n\n\t// append our PPK-formatted private key bytes to the MAC buffer\n\tmacPrivateKeyData := getRFC4251String(ppkPrivateKey.Bytes())\n\tbinary.Write(macInput, binary.BigEndian, macPrivateKeyData)\n\n\t// as per the PPK spec, the key for the MAC is blank when the PPK file is unencrypted.\n\t// therefore, the key is a zero-length byte slice.\n\thmacHash := hmac.New(sha256.New, []byte{})\n\t// generate the MAC using HMAC-SHA-256\n\thmacHash.Write(macInput.Bytes())\n\tmacString := hex.EncodeToString(hmacHash.Sum(nil))\n\n\t// build the string-formatted output PPK file\n\tppk := new(bytes.Buffer)\n\tfmt.Fprintf(ppk, \"PuTTY-User-Key-File-3: %v\\n\", keyType)\n\tfmt.Fprintf(ppk, \"Encryption: %v\\n\", encryptionType)\n\tfmt.Fprintf(ppk, \"Comment: %v\\n\", fileComment)\n\t// chunk the Teleport-formatted public key into 64-character length lines\n\tchunkedPublicKey := chunk(string(pub), 64)\n\tfmt.Fprintf(ppk, \"Public-Lines: %v\\n\", len(chunkedPublicKey))\n\tfor _, r := range chunkedPublicKey {\n\t\tfmt.Fprintf(ppk, \"%s\\n\", r)\n\t}\n\t// chunk the PPK-formatted private key into 64-character length lines\n\tchunkedPrivateKey := chunk(string(ppkPrivateKeyBase64), 64)\n\tfmt.Fprintf(ppk, \"Private-Lines: %v\\n\", len(chunkedPrivateKey))\n\tfor _, r := range chunkedPrivateKey {\n\t\tfmt.Fprintf(ppk, \"%s\\n\", r)\n\t}\n\tfmt.Fprintf(ppk, \"Private-MAC: %v\\n\", macString)\n\n\treturn ppk.Bytes(), nil\n}" ]
[ "0.81767845", "0.6853861", "0.61783284", "0.60745764", "0.57720494", "0.57669014", "0.57425594", "0.56880015", "0.5676771", "0.5632435", "0.55471593", "0.5539518", "0.5511913", "0.55004203", "0.5453801", "0.537776", "0.53551984", "0.5286759", "0.5272513", "0.5269113", "0.52666223", "0.5234639", "0.5208769", "0.52035767", "0.5174009", "0.5143713", "0.514062", "0.51283777", "0.51125413", "0.5080105", "0.5060027", "0.50576067", "0.50330716", "0.50202096", "0.5014435", "0.5010803", "0.50101155", "0.49962205", "0.49877638", "0.49665803", "0.4954317", "0.49505267", "0.49305323", "0.4929516", "0.49207392", "0.4909086", "0.4895806", "0.4892054", "0.48889157", "0.48880386", "0.48845857", "0.4874796", "0.48734787", "0.48697454", "0.48664778", "0.48630637", "0.48621494", "0.48616076", "0.48532575", "0.48525923", "0.48477533", "0.48413977", "0.4840271", "0.48359507", "0.48223123", "0.48222438", "0.4815047", "0.48065513", "0.48045692", "0.48040047", "0.48014832", "0.47863048", "0.47760946", "0.47500247", "0.4742801", "0.4738609", "0.47260278", "0.4716864", "0.47104076", "0.46921265", "0.4688578", "0.4684496", "0.4678548", "0.4670426", "0.46605876", "0.46605667", "0.46510708", "0.4644098", "0.46333098", "0.46193236", "0.461923", "0.4618598", "0.46146947", "0.46146947", "0.46022043", "0.459327", "0.45859376", "0.457331", "0.45696065", "0.45687693" ]
0.6563129
2
ValidateRSAParams checks the Octet (symmetric) parameters of an Octet type of JWK. If a JWK is invalid an error will be returned describing the values that causes the validation to fail.
func (jwk *Jwk) validateOctParams() error { if len(jwk.KeyValue) < 1 { return errors.New("Oct Required Param KeyValue (k) is empty") } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (jwk *Jwk) validateRSAParams() error {\n\tif jwk.E < 1 {\n\t\treturn errors.New(\"RSA Required Param (E) is empty/default (<= 0)\")\n\t}\n\tif jwk.N == nil {\n\t\treturn errors.New(\"RSA Required Param (N) is nil\")\n\t}\n\n\tpOk := jwk.P != nil\n\tqOk := jwk.Q != nil\n\tdpOk := jwk.Dp != nil\n\tdqOk := jwk.Dq != nil\n\tqiOk := jwk.Qi != nil\n\tothOk := len(jwk.OtherPrimes) > 0\n\n\tparamsOR := pOk || qOk || dpOk || dqOk || qiOk\n\tparamsAnd := pOk && qOk && dpOk && dqOk && qiOk\n\n\tif jwk.D == nil {\n\t\tif (paramsOR || othOk) == true {\n\t\t\treturn errors.New(\"RSA first/second prime values are present but not Private key value (D)\")\n\t\t}\n\t} else {\n\t\tif paramsOR != paramsAnd {\n\t\t\treturn errors.New(\"Not all RSA first/second prime values are present or not present\")\n\t\t} else if !paramsOR && othOk {\n\t\t\treturn errors.New(\"RSA other primes is included but 1st, 2nd prime variables are missing\")\n\t\t} else if othOk {\n\t\t\tfor i, oth := range jwk.OtherPrimes {\n\t\t\t\tif oth.Coeff == nil {\n\t\t\t\t\treturn fmt.Errorf(\"Other Prime at index=%d, Coeff missing/nil\", i)\n\t\t\t\t} else if oth.R == nil {\n\t\t\t\t\treturn fmt.Errorf(\"Other Prime at index=%d, R missing/nil\", i)\n\t\t\t\t} else if oth.Exp == nil {\n\t\t\t\t\treturn fmt.Errorf(\"Other Prime at index=%d, Exp missing/nil\", i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (priv *PKCS11PrivateKeyRSA) Validate() error {\n\tpub := priv.key.PubKey.(*rsa.PublicKey)\n\tif pub.E < 2 {\n\t\treturn errMalformedRSAKey\n\t}\n\t// The software implementation actively rejects 'large' public\n\t// exponents, in order to simplify its own implementation.\n\t// Here, instead, we expect the PKCS#11 library to enforce its\n\t// own preferred constraints, whatever they might be.\n\treturn nil\n}", "func (jwk *RSAPrivateJWK) PrivateRSA() (*rsa.PrivateKey, error) {\n\tmodulusBytes, err := base64.RawURLEncoding.DecodeString(jwk.ModulusBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmodulus := new(big.Int)\n\tmodulus = modulus.SetBytes(modulusBytes)\n\tpublicExponentBytes, err := base64.RawURLEncoding.DecodeString(jwk.PublicExponentBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor len(publicExponentBytes) < 8 {\n\t\tpublicExponentBytes = append(publicExponentBytes, 0)\n\t}\n\tpublicExponent := int(binary.LittleEndian.Uint64(publicExponentBytes))\n\tprivateExponentBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExponentBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateExponent := new(big.Int)\n\tprivateExponent = privateExponent.SetBytes(privateExponentBytes)\n\tfirstPrimeFactorBytes, err := base64.RawURLEncoding.DecodeString(jwk.FirstPrimeFactorBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfirstPrimeFactor := new(big.Int)\n\tfirstPrimeFactor = firstPrimeFactor.SetBytes(firstPrimeFactorBytes)\n\tsecondPrimeFactorBytes, err := base64.RawURLEncoding.DecodeString(jwk.SecondPrimeFactorBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecondPrimeFactor := new(big.Int)\n\tsecondPrimeFactor = secondPrimeFactor.SetBytes(secondPrimeFactorBytes)\n\tprivateExpModFirstPrimeMinusOneBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExpModFirstPrimeMinusOneBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateExpModFirstPrimeMinusOne := new(big.Int)\n\tprivateExpModFirstPrimeMinusOne = privateExpModFirstPrimeMinusOne.SetBytes(privateExpModFirstPrimeMinusOneBytes)\n\tprivateExpModSecondPrimeMinusOneBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExpModSecondPrimeMinusOneBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateExpModSecondPrimeMinusOne := new(big.Int)\n\tprivateExpModSecondPrimeMinusOne = privateExpModSecondPrimeMinusOne.SetBytes(privateExpModSecondPrimeMinusOneBytes)\n\tsecondPrimeInverseModFirstPrimeBytes, err := base64.RawURLEncoding.DecodeString(jwk.SecondPrimeInverseModFirstPrimeBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecondPrimeInverseModFirstPrime := new(big.Int)\n\tsecondPrimeInverseModFirstPrime = secondPrimeInverseModFirstPrime.SetBytes(secondPrimeInverseModFirstPrimeBytes)\n\trsaPrivateKey := rsa.PrivateKey{\n\t\tPublicKey: rsa.PublicKey{\n\t\t\tN: modulus,\n\t\t\tE: publicExponent,\n\t\t},\n\t\tD: privateExponent,\n\t\tPrimes: []*big.Int{firstPrimeFactor, secondPrimeFactor},\n\t\tPrecomputed: rsa.PrecomputedValues{\n\t\t\tDp: privateExpModFirstPrimeMinusOne,\n\t\t\tDq: privateExpModSecondPrimeMinusOne,\n\t\t\tQinv: secondPrimeInverseModFirstPrime,\n\t\t},\n\t}\n\treturn &rsaPrivateKey, nil\n}", "func buildJWKFromRSA(k *rsa.PublicKey) (*Key, error) {\n\treturn &Key{\n\t\tKeyType: \"RSA\",\n\t\tN: base64.RawURLEncoding.EncodeToString(k.N.Bytes()),\n\t\tE: base64.RawURLEncoding.EncodeToString(big.NewInt(int64(k.E)).Bytes()),\n\t}, nil\n}", "func parseRSA(in []byte) (*rsa.PublicKey, error) {\n\tvar w struct {\n\t\tE *big.Int\n\t\tN *big.Int\n\t\tRest []byte `ssh:\"rest\"`\n\t}\n\tif err := ssh.Unmarshal(in, &w); err != nil {\n\t\treturn nil, errors.Wrap(err, \"error unmarshaling public key\")\n\t}\n\tif w.E.BitLen() > 24 {\n\t\treturn nil, errors.New(\"invalid public key: exponent too large\")\n\t}\n\te := w.E.Int64()\n\tif e < 3 || e&1 == 0 {\n\t\treturn nil, errors.New(\"invalid public key: incorrect exponent\")\n\t}\n\n\tvar key rsa.PublicKey\n\tkey.E = int(e)\n\tkey.N = w.N\n\treturn &key, nil\n}", "func parseRSAKey(key ssh.PublicKey) (*rsa.PublicKey, error) {\n\tvar sshWire struct {\n\t\tName string\n\t\tE *big.Int\n\t\tN *big.Int\n\t}\n\tif err := ssh.Unmarshal(key.Marshal(), &sshWire); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal key %v: %v\", key.Type(), err)\n\t}\n\treturn &rsa.PublicKey{N: sshWire.N, E: int(sshWire.E.Int64())}, nil\n}", "func (jwk *RSAPublicJWK) PublicRSA() (*rsa.PublicKey, error) {\n\tmodulusBytes, err := base64.RawURLEncoding.DecodeString(jwk.ModulusBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmodulus := new(big.Int)\n\tmodulus = modulus.SetBytes(modulusBytes)\n\tpublicExponentBytes, err := base64.RawURLEncoding.DecodeString(jwk.PublicExponentBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor len(publicExponentBytes) < 8 {\n\t\tpublicExponentBytes = append(publicExponentBytes, 0)\n\t}\n\tpublicExponent := int(binary.LittleEndian.Uint64(publicExponentBytes))\n\trsaPublicKey := rsa.PublicKey{\n\t\tN: modulus,\n\t\tE: publicExponent,\n\t}\n\treturn &rsaPublicKey, nil\n}", "func FromRSAPrivateKey(pk *rsa.PrivateKey) *RSAParameters {\n\tvar n, e, d, p, q, dp, dq, qinv string\n\n\tn = toBase64(pk.PublicKey.N)\n\te = toBase64(pk.PublicKey.E)\n\td = toBase64(pk.D)\n\n\tfor i, prime := range pk.Primes {\n\t\tif i == 0 {\n\t\t\tp = toBase64(prime)\n\t\t} else if i == 1 {\n\t\t\tq = toBase64(prime)\n\t\t} else {\n\t\t\tfmt.Println(\"ERROR: more than 2 primes\")\n\t\t}\n\t}\n\n\tdp = toBase64(pk.Precomputed.Dp)\n\tdq = toBase64(pk.Precomputed.Dq)\n\tqinv = toBase64(pk.Precomputed.Qinv)\n\n\tmsRSA := &RSAParameters{\n\t\tModulus: n,\n\t\tExponent: e,\n\t\tD: d,\n\t\tP: p,\n\t\tQ: q,\n\t\tDP: dp,\n\t\tDQ: dq,\n\t\tInverseQ: qinv,\n\t}\n\n\treturn msRSA\n}", "func prepareRSAKeys(privRSAPath, pubRSAPath string)(*rsa.PublicKey, *rsa.PrivateKey, error){\n pwd, _ := os.Getwd()\n\n verifyBytes, err := ioutil.ReadFile(pwd+pubRSAPath)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrInvalidEmptyPublicKey\n }\n\n verifiedKey, err := jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrIsNotPubRSAKey\n }\n\n signBytes, err := ioutil.ReadFile(pwd+privRSAPath)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrInvalidEmptyPrivateKey\n }\n\n signedKey, err := jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n if err != nil{\n return &rsa.PublicKey{}, &rsa.PrivateKey{}, GojwtErrIsNotPrivRSAKey\n }\n \n return verifiedKey, signedKey, nil\n}", "func NewRSA(encoding encodingType) (*RSA, error) {\n\tif encoding == \"\" {\n\t\tencoding = Base64\n\t}\n\treturn &RSA{Encoding: encoding}, nil\n}", "func RSAToPrivateJWK(privateKey *rsa.PrivateKey, jwkID JWKID, algo Algorithm, expirationTime *time.Time) (*RSAPrivateJWK, error) {\n\tprivateX509DER := x509.MarshalPKCS1PrivateKey(privateKey)\n\tprivateX509DERBase64 := base64.RawStdEncoding.EncodeToString(privateX509DER)\n\tprivateThumbprint := sha1.Sum(privateX509DER)\n\tprivateThumbprintBase64 := base64.RawURLEncoding.EncodeToString(privateThumbprint[:])\n\tmodulusBase64 := base64.RawURLEncoding.EncodeToString(privateKey.PublicKey.N.Bytes())\n\texpBuf := new(bytes.Buffer)\n\tbinary.Write(expBuf, binary.LittleEndian, uint64(privateKey.PublicKey.E))\n\texpBytes := bytes.TrimRight(expBuf.Bytes(), \"\\x00\")\n\tpublicExponentBase64 := base64.RawURLEncoding.EncodeToString(expBytes)\n\tprivateExponentBase64 := base64.RawURLEncoding.EncodeToString(privateKey.D.Bytes())\n\tfirstPrimeFactor := privateKey.Primes[0]\n\tfirstPrimeFactorBase64 := base64.RawURLEncoding.EncodeToString(firstPrimeFactor.Bytes())\n\tsecondPrimeFactor := privateKey.Primes[1]\n\tsecondPrimeFactorBase64 := base64.RawURLEncoding.EncodeToString(secondPrimeFactor.Bytes())\n\t// precomputed\n\tprivateExpModFirstPrimeMinusOneBase64 := base64.RawURLEncoding.EncodeToString(privateKey.Precomputed.Dp.Bytes())\n\tprivateExpModSecondPrimeMinusOneBase64 := base64.RawURLEncoding.EncodeToString(privateKey.Precomputed.Dq.Bytes())\n\tsecondPrimeInverseModFirstPrimeBase64 := base64.RawURLEncoding.EncodeToString(privateKey.Precomputed.Qinv.Bytes())\n\tvar usage Usage\n\tswitch algo {\n\tcase RS256, PS256:\n\t\tusage = Signing\n\t\tbreak\n\tcase ROAEP, RSA15:\n\t\tusage = Encryption\n\t}\n\tprivateJWK := RSAPrivateJWK{\n\t\tJWK: JWK{\n\t\t\tCertificateChainBase64: []string{privateX509DERBase64},\n\t\t\tThumbprintBase64: privateThumbprintBase64,\n\t\t\tExpirationTime: expirationTime,\n\t\t\tID: jwkID,\n\t\t\tType: rsaType,\n\t\t\tAlgorithm: algo,\n\t\t\tUsage: usage,\n\t\t},\n\t\tModulusBase64: modulusBase64,\n\t\tPublicExponentBase64: publicExponentBase64,\n\t\tPrivateExponentBase64: privateExponentBase64,\n\t\tFirstPrimeFactorBase64: firstPrimeFactorBase64,\n\t\tSecondPrimeFactorBase64: secondPrimeFactorBase64,\n\t\t// precomputed\n\t\tPrivateExpModFirstPrimeMinusOneBase64: privateExpModFirstPrimeMinusOneBase64,\n\t\tPrivateExpModSecondPrimeMinusOneBase64: privateExpModSecondPrimeMinusOneBase64,\n\t\tSecondPrimeInverseModFirstPrimeBase64: secondPrimeInverseModFirstPrimeBase64,\n\t}\n\treturn &privateJWK, nil\n}", "func NewGojwtRSA(nameserver, headerkey, privKeyPath, pubKeyPath, lenbytes string, hours time.Duration) (*Gojwt, error){\n var verifiedRSAKey *rsa.PublicKey\n var signedRSAKey *rsa.PrivateKey\n \n if privKeyPath == \"\" {\n return nil, GojwtErrInvalidEmptyPrivateKey\n } else if pubKeyPath == \"\" {\n return nil, GojwtErrInvalidEmptyPublicKey\n }\n verifiedRSAKey, signedRSAKey, err := prepareRSAKeys(privKeyPath, pubKeyPath)\n if err != nil{\n return nil, err\n }\n return &Gojwt{\n pubKeyPath: pubKeyPath,\n privKeyPath: privKeyPath,\n pubRSAKey: verifiedRSAKey,\n privRSAKey: signedRSAKey,\n headerKeyAuth: headerkey,\n numHoursDuration: hours,\n method: \"RSA\",\n lenBytes: lenbytes,\n nameServer: nameserver}, nil\n}", "func PrivateKeyValidate(priv *rsa.PrivateKey,) error", "func (jwk *Jwk) validateECParams() error {\n\tif jwk.X == nil {\n\t\treturn errors.New(\"EC Required Param (X) is nil\")\n\t}\n\tif jwk.Y == nil {\n\t\treturn errors.New(\"EC Required Param (Y) is nil\")\n\t}\n\tif jwk.Curve == nil {\n\t\treturn errors.New(\"EC Required Param (Crv) is nil\")\n\t}\n\treturn nil\n}", "func UnmarshalParams(d []byte) (pubKey *signkeys.PublicKey, pubParams *jjm.BlindingParamClient, privateParams []byte, canReissue bool, err error) {\n\tp := new(Params)\n\t_, err = asn1.Unmarshal(d, p)\n\tif err != nil {\n\t\treturn nil, nil, nil, false, err\n\t}\n\tpubkey, err := new(signkeys.PublicKey).Unmarshal(p.PublicKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, false, err\n\t}\n\treturn pubkey, &p.PublicParams, p.PrivateParams, p.CanReissue, nil\n}", "func RSAToPublicJWK(publicKey *rsa.PublicKey, jwkID JWKID, algo Algorithm, expirationTime *time.Time) (*RSAPublicJWK, error) {\n\tpublicX509DER, err := x509.MarshalPKIXPublicKey(publicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpublicX509DERBase64 := base64.RawStdEncoding.EncodeToString(publicX509DER)\n\tpublicThumbprint := sha1.Sum(publicX509DER)\n\tpublicThumbprintBase64 := base64.RawURLEncoding.EncodeToString(publicThumbprint[:])\n\tmodulusBase64 := base64.RawURLEncoding.EncodeToString(publicKey.N.Bytes())\n\texpBuf := new(bytes.Buffer)\n\tbinary.Write(expBuf, binary.LittleEndian, uint64(publicKey.E))\n\texpBytes := bytes.TrimRight(expBuf.Bytes(), \"\\x00\")\n\tpublicExponentBase64 := base64.RawURLEncoding.EncodeToString(expBytes)\n\tvar usage Usage\n\tswitch algo {\n\tcase RS256, PS256:\n\t\tusage = Signing\n\t\tbreak\n\tcase ROAEP, RSA15:\n\t\tusage = Encryption\n\t}\n\tpublicJWK := RSAPublicJWK{\n\t\tJWK: JWK{\n\t\t\tCertificateChainBase64: []string{publicX509DERBase64},\n\t\t\tThumbprintBase64: publicThumbprintBase64,\n\t\t\tExpirationTime: expirationTime,\n\t\t\tID: jwkID,\n\t\t\tType: rsaType,\n\t\t\tAlgorithm: algo,\n\t\t\tUsage: usage,\n\t\t},\n\t\tModulusBase64: modulusBase64,\n\t\tPublicExponentBase64: publicExponentBase64,\n\t}\n\treturn &publicJWK, nil\n}", "func TestPublicKey(t *testing.T) {\n\tconst jsonkey = `{\"keys\":\n [\n {\"kty\":\"EC\",\n \"crv\":\"P-256\",\n \"x\":\"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4\",\n \"y\":\"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM\",\n \"use\":\"enc\",\n \"kid\":\"1\"},\n\n {\"kty\":\"RSA\",\n \"n\": \"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw\",\n \"e\":\"AQAB\",\n \"alg\":\"RS256\",\n \"kid\":\"2011-04-29\"}\n ]\n }`\n\n\tjwt, err := Unmarshal([]byte(jsonkey))\n\tif err != nil {\n\t\tt.Fatal(\"Unmarshal: \", err)\n\t} else if len(jwt.Keys) != 2 {\n\t\tt.Fatalf(\"Expected 2 keys, got %d\", len(jwt.Keys))\n\t}\n\n\tkeys := make([]crypto.PublicKey, len(jwt.Keys))\n\tfor ii, jwt := range jwt.Keys {\n\t\tkeys[ii], err = jwt.DecodePublicKey()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to decode key %d: %v\", ii, err)\n\t\t}\n\t}\n\n\tif key0, ok := keys[0].(*ecdsa.PublicKey); !ok {\n\t\tt.Fatalf(\"Expected ECDSA key[0], got %T\", keys[0])\n\t} else if key1, ok := keys[1].(*rsa.PublicKey); !ok {\n\t\tt.Fatalf(\"Expected RSA key[1], got %T\", keys[1])\n\t} else if key0.Curve != elliptic.P256() {\n\t\tt.Fatal(\"Key[0] is not using P-256 curve\")\n\t} else if !bytes.Equal(key0.X.Bytes(), []byte{0x30, 0xa0, 0x42, 0x4c, 0xd2,\n\t\t0x1c, 0x29, 0x44, 0x83, 0x8a, 0x2d, 0x75, 0xc9, 0x2b, 0x37, 0xe7, 0x6e, 0xa2,\n\t\t0xd, 0x9f, 0x0, 0x89, 0x3a, 0x3b, 0x4e, 0xee, 0x8a, 0x3c, 0xa, 0xaf, 0xec, 0x3e}) {\n\t\tt.Fatalf(\"Bad key[0].X, got %v\", key0.X.Bytes())\n\t} else if !bytes.Equal(key0.Y.Bytes(), []byte{0xe0, 0x4b, 0x65, 0xe9, 0x24,\n\t\t0x56, 0xd9, 0x88, 0x8b, 0x52, 0xb3, 0x79, 0xbd, 0xfb, 0xd5, 0x1e, 0xe8,\n\t\t0x69, 0xef, 0x1f, 0xf, 0xc6, 0x5b, 0x66, 0x59, 0x69, 0x5b, 0x6c, 0xce,\n\t\t0x8, 0x17, 0x23}) {\n\t\tt.Fatalf(\"Bad key[0].Y, got %v\", key0.Y.Bytes())\n\t} else if key1.E != 0x10001 {\n\t\tt.Fatalf(\"Bad key[1].E: %d\", key1.E)\n\t} else if !bytes.Equal(key1.N.Bytes(), []byte{0xd2, 0xfc, 0x7b, 0x6a, 0xa, 0x1e,\n\t\t0x6c, 0x67, 0x10, 0x4a, 0xeb, 0x8f, 0x88, 0xb2, 0x57, 0x66, 0x9b, 0x4d, 0xf6,\n\t\t0x79, 0xdd, 0xad, 0x9, 0x9b, 0x5c, 0x4a, 0x6c, 0xd9, 0xa8, 0x80, 0x15, 0xb5,\n\t\t0xa1, 0x33, 0xbf, 0xb, 0x85, 0x6c, 0x78, 0x71, 0xb6, 0xdf, 0x0, 0xb, 0x55,\n\t\t0x4f, 0xce, 0xb3, 0xc2, 0xed, 0x51, 0x2b, 0xb6, 0x8f, 0x14, 0x5c, 0x6e, 0x84,\n\t\t0x34, 0x75, 0x2f, 0xab, 0x52, 0xa1, 0xcf, 0xc1, 0x24, 0x40, 0x8f, 0x79, 0xb5,\n\t\t0x8a, 0x45, 0x78, 0xc1, 0x64, 0x28, 0x85, 0x57, 0x89, 0xf7, 0xa2, 0x49, 0xe3,\n\t\t0x84, 0xcb, 0x2d, 0x9f, 0xae, 0x2d, 0x67, 0xfd, 0x96, 0xfb, 0x92, 0x6c, 0x19,\n\t\t0x8e, 0x7, 0x73, 0x99, 0xfd, 0xc8, 0x15, 0xc0, 0xaf, 0x9, 0x7d, 0xde, 0x5a,\n\t\t0xad, 0xef, 0xf4, 0x4d, 0xe7, 0xe, 0x82, 0x7f, 0x48, 0x78, 0x43, 0x24, 0x39,\n\t\t0xbf, 0xee, 0xb9, 0x60, 0x68, 0xd0, 0x47, 0x4f, 0xc5, 0xd, 0x6d, 0x90, 0xbf,\n\t\t0x3a, 0x98, 0xdf, 0xaf, 0x10, 0x40, 0xc8, 0x9c, 0x2, 0xd6, 0x92, 0xab, 0x3b,\n\t\t0x3c, 0x28, 0x96, 0x60, 0x9d, 0x86, 0xfd, 0x73, 0xb7, 0x74, 0xce, 0x7, 0x40,\n\t\t0x64, 0x7c, 0xee, 0xea, 0xa3, 0x10, 0xbd, 0x12, 0xf9, 0x85, 0xa8, 0xeb, 0x9f,\n\t\t0x59, 0xfd, 0xd4, 0x26, 0xce, 0xa5, 0xb2, 0x12, 0xf, 0x4f, 0x2a, 0x34, 0xbc,\n\t\t0xab, 0x76, 0x4b, 0x7e, 0x6c, 0x54, 0xd6, 0x84, 0x2, 0x38, 0xbc, 0xc4, 0x5, 0x87,\n\t\t0xa5, 0x9e, 0x66, 0xed, 0x1f, 0x33, 0x89, 0x45, 0x77, 0x63, 0x5c, 0x47, 0xa,\n\t\t0xf7, 0x5c, 0xf9, 0x2c, 0x20, 0xd1, 0xda, 0x43, 0xe1, 0xbf, 0xc4, 0x19, 0xe2,\n\t\t0x22, 0xa6, 0xf0, 0xd0, 0xbb, 0x35, 0x8c, 0x5e, 0x38, 0xf9, 0xcb, 0x5, 0xa, 0xea,\n\t\t0xfe, 0x90, 0x48, 0x14, 0xf1, 0xac, 0x1a, 0xa4, 0x9c, 0xca, 0x9e, 0xa0, 0xca, 0x83}) {\n\t\tt.Fatal(\"Bad key[1].N, got %v\", key1.N.Bytes())\n\t}\n}", "func (j *JWKS) generateRSAKey() (crypto.PrivateKey, error) {\n\tif j.bits == 0 {\n\t\tj.bits = 2048\n\t}\n\tif j.bits < 2048 {\n\t\treturn nil, errors.Errorf(`jwks: key size must be at least 2048 bit for algorithm`)\n\t}\n\tkey, err := rsa.GenerateKey(rand.Reader, j.bits)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"jwks: unable to generate RSA key\")\n\t}\n\n\treturn key, nil\n}", "func InitRSAKeys() {\n\n\tsignBytes, err := ioutil.ReadFile(privKeyPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n\n\tsignKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n\n\tverifyBytes, err := ioutil.ReadFile(pubKeyPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n\n\tverifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n\tif err != nil {\n\t\tlog.Fatalf(\"[initKeys]: %s\\n\", err)\n\t}\n}", "func (me *XsdGoPkgHasElem_RSAKeyValue) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_RSAKeyValue; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.RSAKeyValue.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func rsaEncrypt(pemPubKey, nonce, password []byte) ([]byte, error) {\n\tpubKeyBlock, rest := pem.Decode(pemPubKey)\n\tif len(rest) > 0 {\n\t\treturn nil, fmt.Errorf(\"trailing bytes in public key: %#v\", rest)\n\t}\n\n\tpublicKey, err := x509.ParsePKCS1PublicKey(pubKeyBlock.Bytes)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse PKCS#1 public key: %w\", err)\n\t}\n\n\treturn rsa.EncryptOAEP(sha1.New(), rand.Reader, publicKey, append(nonce, []byte(password)...), []byte{})\n}", "func (p Params) Validate() error {\n\tif err := validateTokenCourse(p.TokenCourse); err != nil {\n\t\treturn err\n\t}\n\tif err := validateSubscriptionPrice(p.SubscriptionPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateVPNGBPrice(p.VPNGBPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateStorageGBPrice(p.StorageGBPrice); err != nil {\n\t\treturn err\n\t}\n\tif err := validateBaseVPNGb(p.BaseVPNGb); err != nil {\n\t\treturn err\n\t}\n\tif err := validateBaseStorageGb(p.BaseStorageGb); err != nil {\n\t\treturn err\n\t}\n\tif err := validateCourseChangeSigners(p.CourseChangeSigners); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ValidateParams(k, m uint8) (*Params, error) {\n\tif k < 1 {\n\t\treturn nil, errors.New(\"k cannot be zero\")\n\t}\n\n\tif m < 1 {\n\t\treturn nil, errors.New(\"m cannot be zero\")\n\t}\n\n\tif k+m > 255 {\n\t\treturn nil, errors.New(\"(k + m) cannot be bigger than Galois field GF(2^8) - 1\")\n\t}\n\n\treturn &Params{\n\t\tK: k,\n\t\tM: m,\n\t}, nil\n}", "func (jwk *Jwk) Validate() error {\n\n\t// If the alg parameter is set, make sure it matches the set JWK Type\n\tif len(jwk.Algorithm) > 0 {\n\t\talgKeyType := GetKeyType(jwk.Algorithm)\n\t\tif algKeyType != jwk.Type {\n\t\t\tfmt.Errorf(\"Jwk Type (kty=%v) doesn't match the algorithm key type (%v)\", jwk.Type, algKeyType)\n\t\t}\n\t}\n\tswitch jwk.Type {\n\tcase KeyTypeRSA:\n\t\tif err := jwk.validateRSAParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase KeyTypeEC:\n\t\tif err := jwk.validateECParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase KeyTypeOct:\n\t\tif err := jwk.validateOctParams(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tdefault:\n\t\treturn errors.New(\"KeyType (kty) must be EC, RSA or Oct\")\n\t}\n\n\treturn nil\n}", "func CheckAlgorithmIDParamNotNULL(algorithmIdentifier []byte, requiredAlgoID asn1.ObjectIdentifier) error {\n\texpectedAlgoIDBytes, ok := RSAAlgorithmIDToDER[requiredAlgoID.String()]\n\tif !ok {\n\t\treturn errors.New(\"error algorithmID to check is not RSA\")\n\t}\n\n\talgorithmSequence := cryptobyte.String(algorithmIdentifier)\n\n\t// byte comparison of algorithm sequence and checking no trailing data is present\n\tvar algorithmBytes []byte\n\tif algorithmSequence.ReadBytes(&algorithmBytes, len(expectedAlgoIDBytes)) {\n\t\tif bytes.Compare(algorithmBytes, expectedAlgoIDBytes) == 0 && algorithmSequence.Empty() {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// re-parse to get an error message detailing what did not match in the byte comparison\n\talgorithmSequence = cryptobyte.String(algorithmIdentifier)\n\tvar algorithm cryptobyte.String\n\tif !algorithmSequence.ReadASN1(&algorithm, cryptobyte_asn1.SEQUENCE) {\n\t\treturn errors.New(\"error reading algorithm\")\n\t}\n\n\tencryptionOID := asn1.ObjectIdentifier{}\n\tif !algorithm.ReadASN1ObjectIdentifier(&encryptionOID) {\n\t\treturn errors.New(\"error reading algorithm OID\")\n\t}\n\n\tif !encryptionOID.Equal(requiredAlgoID) {\n\t\treturn fmt.Errorf(\"algorithm OID is not equal to %s\", requiredAlgoID.String())\n\t}\n\n\tif algorithm.Empty() {\n\t\treturn errors.New(\"RSA algorithm identifier missing required NULL parameter\")\n\t}\n\n\tvar nullValue cryptobyte.String\n\tif !algorithm.ReadASN1(&nullValue, cryptobyte_asn1.NULL) {\n\t\treturn errors.New(\"RSA algorithm identifier with non-NULL parameter\")\n\t}\n\n\tif len(nullValue) != 0 {\n\t\treturn errors.New(\"RSA algorithm identifier with NULL parameter containing data\")\n\t}\n\n\t// ensure algorithm is empty and no trailing data is present\n\tif !algorithm.Empty() {\n\t\treturn errors.New(\"RSA algorithm identifier with trailing data\")\n\t}\n\n\treturn errors.New(\"RSA algorithm appears correct, but didn't match byte-wise comparison\")\n}", "func (session *Session) GenerateRSAKeyPair(tokenLabel string, tokenPersistent bool, expDate time.Time, bits int) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) {\n\tif session == nil || session.Ctx == nil {\n\t\treturn 0, 0, fmt.Errorf(\"session not initialized\")\n\t}\n\ttoday := time.Now()\n\tpublicKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, []byte(tokenLabel)),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, tokenPersistent),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_START_DATE, today),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_END_DATE, expDate),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, []byte{1, 0, 1}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS_BITS, bits),\n\t}\n\n\tprivateKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, []byte(tokenLabel)),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, tokenPersistent),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_START_DATE, today),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_END_DATE, expDate),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SIGN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true),\n\t}\n\n\tpubKey, privKey, err := session.Ctx.GenerateKeyPair(\n\t\tsession.Handle,\n\t\t[]*pkcs11.Mechanism{\n\t\t\tpkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_KEY_PAIR_GEN, nil),\n\t\t},\n\t\tpublicKeyTemplate,\n\t\tprivateKeyTemplate,\n\t)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\treturn pubKey, privKey, nil\n}", "func (m *PorositySimulationParameters) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateBeamDiameter(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGeometryHeight(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGeometryLength(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGeometryWidth(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHatchSpacingValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHeaterTemperature(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLaserWattageValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLayerRotationAngle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLayerThicknessValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateMeshLayersPerLayer(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateScanSpeedValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSlicingStripeWidthValues(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStartingLayerAngle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func GenerateRSAKey(bits int) (privateKey, publicKey []byte, err error) {\n\tprvKey, err := rsa.GenerateKey(rand.Reader, bits)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpkixb, err := x509.MarshalPKIXPublicKey(&prvKey.PublicKey)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tprivateKey = pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(prvKey),\n\t})\n\n\tpublicKey = pem.EncodeToMemory(&pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tBytes: pkixb,\n\t})\n\n\treturn\n}", "func rsaEqual(priv *rsa.PrivateKey, x crypto.PrivateKey) bool {\n\txx, ok := x.(*rsa.PrivateKey)\n\tif !ok {\n\t\treturn false\n\t}\n\tif !(priv.PublicKey.N.Cmp(xx.N) == 0 && priv.PublicKey.E == xx.E) || priv.D.Cmp(xx.D) != 0 {\n\t\treturn false\n\t}\n\tif len(priv.Primes) != len(xx.Primes) {\n\t\treturn false\n\t}\n\tfor i := range priv.Primes {\n\t\tif priv.Primes[i].Cmp(xx.Primes[i]) != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (me *XsdGoPkgHasElems_RSAKeyValue) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_RSAKeyValue; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfor _, x := range me.RSAKeyValues {\n\t\t\tif err = x.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func ParsePublicKey(data []byte) (SignatureValidator, error) {\r\n\ttmpKey, err := x509.ParsePKIXPublicKey(data)\r\n\trsaKey, ok := tmpKey.(*rsa.PublicKey)\r\n\tif err != nil || !ok {\r\n\t\treturn nil, errors.New(\"invalid key type, only RSA is supported\")\r\n\t}\r\n\treturn &rsaPublicKey{rsaKey}, nil\r\n}", "func parsePublicKey(pemBytes []byte) (SignatureValidator, error) {\r\n\tgob.Register(rsaPrivateKey{})\r\n\tblock, _ := pem.Decode(pemBytes)\r\n\tif block == nil {\r\n\t\treturn nil, errors.New(\"no key found\")\r\n\t}\r\n\r\n\tswitch block.Type {\r\n\tcase \"PUBLIC KEY\":\r\n\t\treturn ParsePublicKey(block.Bytes)\r\n\tdefault:\r\n\t\treturn nil, fmt.Errorf(\"unsupported key block type %q\", block.Type)\r\n\t}\r\n}", "func GenerateRSAKeyPair(opts GenerateRSAOptions) (*RSAKeyPair, error) {\n\t//creates the private key\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, opts.Bits)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error generating private key: %s\\n\", err)\n\t}\n\n\t//validates the private key\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error validating private key: %s\\n\", err)\n\t}\n\n\t// sets up the PEM block for private key\n\tprivateKeyBlock := pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tHeaders: nil,\n\t\tBytes: x509.MarshalPKCS1PrivateKey(privateKey),\n\t}\n\n\t//check to see if we are applying encryption to this key\n\tif opts.Encryption != nil {\n\t\t//check to make sure we have a password specified\n\t\tpass := strings.TrimSpace(opts.Encryption.Password)\n\t\tif pass == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"%s\", \"need a password!\")\n\t\t}\n\t\t//check to make sure we're using a supported PEMCipher\n\t\tencCipher := opts.Encryption.PEMCipher\n\t\tif encCipher != x509.PEMCipherDES &&\n\t\t\tencCipher != x509.PEMCipher3DES &&\n\t\t\tencCipher != x509.PEMCipherAES128 &&\n\t\t\tencCipher != x509.PEMCipherAES192 &&\n\t\t\tencCipher != x509.PEMCipherAES256 {\n\t\t\treturn nil, fmt.Errorf(\"%s\", \"invalid PEMCipher\")\n\t\t}\n\t\t//encrypt the private key block\n\t\tencBlock, err := x509.EncryptPEMBlock(rand.Reader, \"RSA PRIVATE KEY\", privateKeyBlock.Bytes, []byte(pass), encCipher)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error encrypting pirvate key: %s\\n\", err)\n\t\t}\n\t\t//replaces the starting one with the one we encrypted\n\t\tprivateKeyBlock = *encBlock\n\t}\n\n\t// serializes the public key in a DER-encoded PKIX format (see docs for more)\n\tpublicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error setting up public key: %s\\n\", err)\n\t}\n\n\t// sets up the PEM block for public key\n\tpublicKeyBlock := pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tHeaders: nil,\n\t\tBytes: publicKeyBytes,\n\t}\n\n\t//returns the created key pair\n\treturn &RSAKeyPair{\n\t\tPrivateKey: string(pem.EncodeToMemory(&privateKeyBlock)),\n\t\tPublicKey: string(pem.EncodeToMemory(&publicKeyBlock)),\n\t}, nil\n}", "func Validate(accessToken string, configURL string, c *cache.Cache) (bool, error) {\n\n\tjp := new(jwtgo.Parser)\n\tjp.ValidMethods = []string{\n\t\t\"RS256\", \"RS384\", \"RS512\", \"ES256\", \"ES384\", \"ES512\",\n\t\t\"RS3256\", \"RS3384\", \"RS3512\", \"ES3256\", \"ES3384\", \"ES3512\",\n\t}\n\n\t// Validate token against issuer\n\ttt, _ := jwtgo.Parse(accessToken, func(token *jwtgo.Token) (interface{}, error) {\n\t\tif _, ok := token.Method.(*jwtgo.SigningMethodRSA); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\n\t\t// check if publicKey already in cache\n\t\tpub, found := c.Get(\"key\")\n\t\tif found {\n\t\t\t//fmt.Println(\"Using cached pubKey\")\n\t\t\treturn pub, nil\n\t\t}\n\n\t\t// Retrieve Issuer metadata from discovery endpoint\n\t\td := openid.DiscoveryDoc{}\n\n\t\treq, err := http.NewRequest(http.MethodGet, configURL, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclnt := http.Client{}\n\n\t\tr, err := clnt.Do(req)\n\t\tif err != nil {\n\t\t\tclnt.CloseIdleConnections()\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer r.Body.Close()\n\n\t\tif r.StatusCode != http.StatusOK {\n\t\t\treturn nil, errors.New(r.Status)\n\t\t}\n\t\tdec := json.NewDecoder(r.Body)\n\t\tif err = dec.Decode(&d); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Get Public Key from JWK URI\n\t\tresp, err := clnt.Get(d.JwksURI)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn nil, errors.New(resp.Status)\n\t\t}\n\n\t\tvar jwk openid.JWKS\n\t\tif err = json.NewDecoder(resp.Body).Decode(&jwk); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar kk crypto.PublicKey\n\t\tfor _, key := range jwk.Keys {\n\t\t\tkk, err = key.DecodePublicKey()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Return the rsa public key for the token validation\n\t\tpubKey := kk.(*rsa.PublicKey)\n\n\t\tc.Set(\"key\", pubKey, cache.DefaultExpiration)\n\n\t\treturn pubKey, nil\n\n\t})\n\n\t//fmt.Println(tt)\n\treturn tt.Valid, nil\n}", "func (g *Gossiper) RSAVerifyPMSignature(msg utils.PrivateMessage) bool {\n\thash := utils.HASH_ALGO.New()\n\n\tbytes, e := json.Marshal(msg)\n\tutils.HandleError(e)\n\thash.Write(bytes)\n\thashed := hash.Sum(nil)\n\n\tpubKeyBytes, e := hex.DecodeString(msg.Origin)\n\tutils.HandleError(e)\n\tpubKey, e := x509.ParsePKCS1PublicKey(pubKeyBytes)\n\tutils.HandleError(e)\n\n\te = rsa.VerifyPKCS1v15(pubKey, utils.HASH_ALGO, hashed, msg.Signature)\n\tutils.HandleError(e)\n\tif e == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func GenerateKeyPair(bits int) (keypair *KeyPair, err error) {\n\tkeypair = new(KeyPair)\n\tkeypair.PublicKey = new(PublicKey)\n\tkeypair.PrivateKey = new(PrivateKey)\n\n\tif bits == 0 {\n\t\terr = errors.New(\"RSA modulus size must not be zero.\")\n\t\treturn\n\t}\n\tif bits%8 != 0 {\n\t\terr = errors.New(\"RSA modulus size must be a multiple of 8.\")\n\t\treturn\n\t}\n\n\tfor limit := 0; limit < 1000; limit++ {\n\t\tvar tempKey *rsa.PrivateKey\n\t\ttempKey, err = rsa.GenerateKey(rand.Reader, bits)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif len(tempKey.Primes) != 2 {\n\t\t\terr = errors.New(\"RSA package generated a weird set of primes (i.e. not two)\")\n\t\t\treturn\n\t\t}\n\n\t\tp := tempKey.Primes[0]\n\t\tq := tempKey.Primes[1]\n\n\t\tif p.Cmp(q) == 0 {\n\t\t\terr = errors.New(\"RSA keypair factors were equal. This is really unlikely dependent on the bitsize and it appears something horrible has happened.\")\n\t\t\treturn\n\t\t}\n\t\tif gcd := new(big.Int).GCD(nil, nil, p, q); gcd.Cmp(big.NewInt(1)) != 0 {\n\t\t\terr = errors.New(\"RSA primes were not relatively prime!\")\n\t\t\treturn\n\t\t}\n\n\t\tmodulus := new(big.Int).Mul(p, q)\n\n\t\tpublicExp := big.NewInt(3)\n\t\t//publicExp := big.NewInt(65537)\n\n\t\t//totient = (p-1) * (q-1)\n\t\ttotient := new(big.Int)\n\t\ttotient.Sub(p, big.NewInt(1))\n\t\ttotient.Mul(totient, new(big.Int).Sub(q, big.NewInt(1)))\n\n\t\tif gcd := new(big.Int).GCD(nil, nil, publicExp, totient); gcd.Cmp(big.NewInt(1)) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tprivateExp := new(big.Int).ModInverse(publicExp, totient)\n\t\tkeypair.PublicKey.Modulus = modulus\n\t\tkeypair.PrivateKey.Modulus = modulus\n\t\tkeypair.PublicKey.PublicExp = publicExp\n\t\tkeypair.PrivateKey.PrivateExp = privateExp\n\t\treturn\n\t}\n\terr = errors.New(\"Failed to generate a within the limit!\")\n\treturn\n\n}", "func parseAndCheckParameters(params ...Parameter) (*parameters, error) {\n\tparameters := parameters{\n\t\tlogLevel: zerolog.GlobalLevel(),\n\t}\n\tfor _, p := range params {\n\t\tif params != nil {\n\t\t\tp.apply(&parameters)\n\t\t}\n\t}\n\n\tif parameters.monitor == nil {\n\t\t// Use no-op monitor.\n\t\tparameters.monitor = &noopMonitor{}\n\t}\n\tif parameters.signer == nil {\n\t\treturn nil, errors.New(\"no signer specified\")\n\t}\n\tif parameters.lister == nil {\n\t\treturn nil, errors.New(\"no lister specified\")\n\t}\n\tif parameters.process == nil {\n\t\treturn nil, errors.New(\"no process specified\")\n\t}\n\tif parameters.walletManager == nil {\n\t\treturn nil, errors.New(\"no wallet manager specified\")\n\t}\n\tif parameters.accountManager == nil {\n\t\treturn nil, errors.New(\"no account manager specified\")\n\t}\n\tif parameters.peers == nil {\n\t\treturn nil, errors.New(\"no peers specified\")\n\t}\n\tif parameters.name == \"\" {\n\t\treturn nil, errors.New(\"no name specified\")\n\t}\n\tif parameters.id == 0 {\n\t\treturn nil, errors.New(\"no ID specified\")\n\t}\n\tif parameters.listenAddress == \"\" {\n\t\treturn nil, errors.New(\"no listen address specified\")\n\t}\n\tif len(parameters.serverCert) == 0 {\n\t\treturn nil, errors.New(\"no server certificate specified\")\n\t}\n\tif len(parameters.serverKey) == 0 {\n\t\treturn nil, errors.New(\"no server key specified\")\n\t}\n\n\treturn &parameters, nil\n}", "func validatePubKey(publicKey string) error {\n\tpk, err := hex.DecodeString(publicKey)\n\tif err != nil {\n\t\tlog.Debugf(\"validatePubKey: decode hex string \"+\n\t\t\t\"failed for '%v': %v\", publicKey, err)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\t}\n\n\tvar emptyPK [identity.PublicKeySize]byte\n\tswitch {\n\tcase len(pk) != len(emptyPK):\n\t\tlog.Debugf(\"validatePubKey: invalid size: %v\",\n\t\t\tpublicKey)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\tcase bytes.Equal(pk, emptyPK[:]):\n\t\tlog.Debugf(\"validatePubKey: key is empty: %v\",\n\t\t\tpublicKey)\n\t\treturn www.UserError{\n\t\t\tErrorCode: www.ErrorStatusInvalidPublicKey,\n\t\t}\n\t}\n\n\treturn nil\n}", "func GenRSAKey(len int, password string, kmPubFile, kmPrivFile, bpmPubFile, bpmPrivFile *os.File) error {\n\tif len == rsaLen2048 || len == rsaLen3072 {\n\t\tkey, err := rsa.GenerateKey(rand.Reader, len)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writePrivKeyToFile(key, kmPrivFile, password); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := writePubKeyToFile(key.Public(), kmPubFile); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tkey, err = rsa.GenerateKey(rand.Reader, len)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writePrivKeyToFile(key, bpmPrivFile, password); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := writePubKeyToFile(key.Public(), bpmPubFile); err != nil {\n\t\t\treturn err\n\n\t\t}\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"RSA key length must be 2048 or 3084 Bits, but length is: %d\", len)\n}", "func ValidatePublicKey(k *ecdsa.PublicKey) bool {\n\treturn k != nil && k.X != nil && k.Y != nil && k.X.Sign() != 0 && k.Y.Sign() != 0\n}", "func (v *VPNClientIPsecParameters) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", v, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"dhGroup\":\n\t\t\terr = unpopulate(val, \"DhGroup\", &v.DhGroup)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"ipsecEncryption\":\n\t\t\terr = unpopulate(val, \"IPSecEncryption\", &v.IPSecEncryption)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"ipsecIntegrity\":\n\t\t\terr = unpopulate(val, \"IPSecIntegrity\", &v.IPSecIntegrity)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"ikeEncryption\":\n\t\t\terr = unpopulate(val, \"IkeEncryption\", &v.IkeEncryption)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"ikeIntegrity\":\n\t\t\terr = unpopulate(val, \"IkeIntegrity\", &v.IkeIntegrity)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"pfsGroup\":\n\t\t\terr = unpopulate(val, \"PfsGroup\", &v.PfsGroup)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"saDataSizeKilobytes\":\n\t\t\terr = unpopulate(val, \"SaDataSizeKilobytes\", &v.SaDataSizeKilobytes)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"saLifeTimeSeconds\":\n\t\t\terr = unpopulate(val, \"SaLifeTimeSeconds\", &v.SaLifeTimeSeconds)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", v, err)\n\t\t}\n\t}\n\treturn nil\n}", "func NewRSAPEM() ([]byte, error) {\n\tprivate, err := rsa.GenerateKey(rand.Reader, 4096)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = private.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn marshalToPEM(private)\n}", "func VerifyPSS(pub *rsa.PublicKey, hash crypto.Hash, hashed []byte, sig []byte, opts *rsa.PSSOptions,) error", "func ValidateOracleParams(i interface{}) error {\n\tparams, isOracleParams := i.(OracleParams)\n\tif !isOracleParams {\n\t\treturn fmt.Errorf(\"invalid parameters type: %s\", i)\n\t}\n\n\tif params.AskCount < params.MinCount {\n\t\treturn fmt.Errorf(\"invalid ask count: %d, min count: %d\", params.AskCount, params.MinCount)\n\t}\n\n\tif params.MinCount <= 0 {\n\t\treturn fmt.Errorf(\"invalid min count: %d\", params.MinCount)\n\t}\n\n\tif params.PrepareGas <= 0 {\n\t\treturn fmt.Errorf(\"invalid prepare gas: %d\", params.PrepareGas)\n\t}\n\n\tif params.ExecuteGas <= 0 {\n\t\treturn fmt.Errorf(\"invalid execute gas: %d\", params.ExecuteGas)\n\t}\n\n\terr := params.FeeAmount.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (k *Kite) RSAKey(token *jwt.Token) (interface{}, error) {\n\tk.verifyOnce.Do(k.verifyInit)\n\n\tkontrolKey := k.KontrolKey()\n\n\tif kontrolKey == nil {\n\t\tpanic(\"kontrol key is not set in config\")\n\t}\n\n\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\treturn nil, errors.New(\"invalid signing method\")\n\t}\n\n\tclaims, ok := token.Claims.(*kitekey.KiteClaims)\n\tif !ok {\n\t\treturn nil, errors.New(\"token does not have valid claims\")\n\t}\n\n\tif claims.Issuer != k.Config.KontrolUser {\n\t\treturn nil, fmt.Errorf(\"issuer is not trusted: %s\", claims.Issuer)\n\t}\n\n\treturn kontrolKey, nil\n}", "func ECDH_PUBLIC_KEY_VALIDATE(W []byte) int {\n\tWP := ECP_fromBytes(W)\n\tres := 0\n\n\tr := NewBIGints(CURVE_Order)\n\n\tif WP.Is_infinity() {\n\t\tres = INVALID_PUBLIC_KEY\n\t}\n\tif res == 0 {\n\n\t\tq := NewBIGints(Modulus)\n\t\tnb := q.nbits()\n\t\tk := NewBIGint(1)\n\t\tk.shl(uint((nb + 4) / 2))\n\t\tk.add(q)\n\t\tk.div(r)\n\n\t\tfor k.parity() == 0 {\n\t\t\tk.shr(1)\n\t\t\tWP.dbl()\n\t\t}\n\n\t\tif !k.isunity() {\n\t\t\tWP = WP.mul(k)\n\t\t}\n\t\tif WP.Is_infinity() {\n\t\t\tres = INVALID_PUBLIC_KEY\n\t\t}\n\n\t}\n\treturn res\n}", "func (v *PublicParamsManager) Validate() error {\n\tpp := v.PublicParams()\n\tif pp == nil {\n\t\treturn errors.New(\"public parameters not set\")\n\t}\n\treturn pp.Validate()\n}", "func GetRSAKey(size int) (data.PrivateKey, error) {\n\traw := map[int][]byte{\n\t\t1024: []byte(`-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDJ8BO2/HOHLJgrb3srafbNRUD8r0SGNJFi5h7t4vxZ4F5oBW/4\nO2/aZmdToinyuCm0eGguK77HAsTfSHqDUoEfuInNg7pPk4F6xa4feQzEeG6P0YaL\n+VbApUdCHLBE0tVZg1SCW97+27wqIM4Cl1Tcsbb+aXfgMaOFGxlyga+a6wIDAQAB\nAoGBAKDWLH2kGMfjBtghlLKBVWcs75PSbPuPRvTEYIIMNf3HrKmhGwtVG8ORqF5+\nXHbLo7vv4tpTUUHkvLUyXxHVVq1oX+QqiRwTRm+ROF0/T6LlrWvTzvowTKtkRbsm\nmqIYEbc+fBZ/7gEeW2ycCfE7HWgxNGvbUsK4LNa1ozJbrVEBAkEA8ML0mXyxq+cX\nCwWvdXscN9vopLG/y+LKsvlKckoI/Hc0HjPyraq5Docwl2trZEmkvct1EcN8VvcV\nvCtVsrAfwQJBANa4EBPfcIH2NKYHxt9cP00n74dVSHpwJYjBnbec5RCzn5UTbqd2\ni62AkQREYhHZAryvBVE81JAFW3nqI9ZTpasCQBqEPlBRTXgzYXRTUfnMb1UvoTXS\nZd9cwRppHmvr/4Ve05yn+AhsjyksdouWxyMqgTxuFhy4vQ8O85Pf6fZeM4ECQCPp\nWv8H4thJplqSeGeJFSlBYaVf1SRtN0ndIBTCj+kwMaOMQXiOsiPNmfN9wG09v2Bx\nYVFJ/D8uNjN4vo+tI8sCQFbtF+Qkj4uSFDZGMESF6MOgsGt1R1iCpvpMSr9h9V02\nLPXyS3ozB7Deq26pEiCrFtHxw2Pb7RJO6GEqH7Dg4oU=\n-----END RSA PRIVATE KEY-----`),\n\t\t2048: []byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAtKGse3BcxXAp5OkLGYq0HfDcCvgag3R/9e8pHUGsJhkSZFrn\nZWAsAVFKSYaYItf1D/g3izqVDMtMpXZ1chNzaRysnbrb/q7JTbiGzXo9FcshyUc9\ntcB60wFbvsXE2LaxZcKNxLYXbOvf+tdg/P07oPG24fzYI4+rbZ1wyoORbT1ys33Z\nhHyifFvO7rbe69y3HG+xbp7yWYAR4e8Nw9jX8/9sGslAV9vEXOdNL3qlcgsYRGDU\nDsUJsnWaMzjstvUxb8mVf9KG2W039ucgaXgBW/jeP3F1VSYFKLd03LvuJ8Ir5E0s\ncWjwTd59nm0XbbRI3KiBGnAgrJ4iK07HrUkpDQIDAQABAoIBAHfr1k1lfdH+83Fs\nXtgoRAiUviHyMfgQQlwO2eb4kMgCYTmLOJEPVmfRhlZmK18GrUZa7tVaoVYLKum3\nSaXg0AB67wcQ5bmiZTdaSPTmMOPlJpsw1wFxtpmcD0MKnfOa5w++KMzub4L63or0\nrwmHPi1ODLLgYMbLPW7a1eU9kDFLOnx3RRy9a29hQXxGsRYetrIbKmeDi6c+ndQ8\nI5YWObcixxl5GP6CTnEugV7wd2JmXuQRGFdopUwQESCD9VkxDSevQBSPoyZKHxGy\n/d3jf0VNlvwsxhD3ybhw8jTN/cmm2LWmP4jylG7iG7YRPVaW/0s39IZ9DnNDwgWB\n03Yk2gECgYEA44jcSI5kXOrbBGDdV+wTUoL24Zoc0URX33F15UIOQuQsypaFoRJ6\nJ23JWEZN99aquuo1+0BBSfiumbpLwSwfXi0nL3oTzS9eOp1HS7AwFGd/OHdpdMsC\nw2eInRwCh4GrEf508GXo+tSL2NS8+MFVAG2/SjEf06SroQ/rQ87Qm0ECgYEAyzqr\n6YvbAnRBy5GgQlTgxR9r0U8N7lM9g2Tk8uGvYI8zu/Tgia4diHAwK1ymKbl3lf95\n3NcHR+ffwOO+nnfFCvmCYXs4ggRCkeopv19bsCLkfnTBNTxPFh6lyLEnn3C+rcCe\nZAkKLrm8BHGviPIgn0aElMQAbhJxTWfClw/VVs0CgYAlDhfZ1R6xJypN9zx04iRv\nbpaoPQHubrPk1sR9dpl9+Uz2HTdb+PddznpY3vI5p4Mcd6Ic7eT0GATPUlCeAAKH\nwtC74aSx6MHux8hhoiriV8yXNJM/CwTDL+xGsdYTnWFvx8HhmKctmknAIT05QbsH\nG9hoS8HEJPAyhbYpz9eXQQKBgQCftPXQTPXJUe86uLBGMEmK34xtKkD6XzPiA/Hf\n5PdbXG39cQzbZZcT14YjLWXvOC8AE4qCwACaw1+VR+ROyDRy0W1iieD4W7ysymYQ\nXDHDk0gZEEudOE22RlNmCcHnjERsawiN+ISl/5P/sg+OASkdwd8CwZzM43VirP3A\nlNLEqQKBgHqj85n8ew23SR0GX0W1PgowaCHHD1p81y2afs1x7H9R1PNuQsTXKnpf\nvMiG7Oxakj4WDC5M5KsHWqchqKDycT+J1BfLI58Sf2qo6vtaV+4DARNgzcG/WB4b\nVnpsczK/1aUH7iBexuF0YqdPQwzpSvrY0XZcgCFQ52JDn3vjblhX\n-----END RSA PRIVATE KEY-----`),\n\t\t4096: []byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIJKgIBAAKCAgEAw28m5P1j7Rv1Wy4AicNkR4DXVxJXlPma+c5U/KJzFg0emiyx\nfkGQnUWeFofOI3rgrgK3deQ6yspgavTKWnHs4YeAz2egMSDsobI1OAP7ocPrFhYc\nFB+pTLXm1CkvyxIt9UWPxgc4CGiO1wIlfL8PpFg5vur7sAqbzxKeFx8GikbjFbQg\nd/RMFYeQacuimo9yea9DqjELvwewby3iP81FP9JJKiM3G6+7BiI+pJv65dNLbBUY\nHgKrmBHYg7WVSdmR7pZucEDoBqJcjc+kIHDGMH2vndWhIybEpHxxXdW+DrnPlhGV\n/hqKWw5fqJvhdh0OR1yefCCva0m6mZAKardzqxndFJqJbs1ehXg0luijVRYXaUpP\nuvHaKj+QV2R/PJWxkCLZLFSEAE156QT1sfY5FOh8rYBWBNrJk7X6qUTaF7Jfeo3H\nCF94ioP0Up8bohIu0lH8WPfTxdZ2lvUGSteMEYWBSbKhcbSCOP6a2K4/znSNl/J3\nLV/YcbmuSb7sAp+sZXELarYg/JMNVP4Vo2vh5S4ZCPYtk2or2WY27rMHWQ1vIhjB\nxjuSKzpLx9klusoTHB3wD6K7FwyT4JLUTfxGloSSpOuLG5yp9dAL/i8WHY20w6jP\n7ZYOss6OsQzp5ZqpW5M/0z60NsEOhfFXd1bxPYUP7//6N14XHTg31fg7vykCAwEA\nAQKCAgEAnn+j/K0ggKlfGL67Qv9Lcc4lVwGSNEknDhfvxyB809J6EjHTFYFZJqPS\nbZVgclfypk2fuqYJpHPzNGspPacNpW7+4ba6LX31S8I69R4N0wkQvM3bodp3tLYF\n6eUpVLl+ul/bFZC/OdqKlgewnXZa2j+PPa5Xx1MjQBJqUnggFr8c5no6pu5jUkaq\nsZKsYkuaXOPurbWvQBOdXN3Kk1IIKpWCLwF2bSbdOEFHqrqyBfiSP6rv707dGazH\nezImTEl+2A/6q2GIi/DbvUs8Ye70XVlht1ENqXOEoZ4nVyHFTS4XFC9ZBUdDFEwY\n+qbJeMBh1zBffG4JtqqKAobWW+xCioKVn2ArSzh1/2Q5652yeVVhR+GTSK2yd1uE\n5a5Pc65C8LCRNTz0iHEUESfVO5QnUq9bWShgm0H/LQ3sk8gzQjuBS5Ya523vOl1w\nxRUYxjEFW0382BrG0dn+WE2Yn0z5i2X9+WRgiKrh8tNZ+wNGN3MtZ5mloHsocH4N\nuUIZ6J0x/YruW126b0XA6fE+3taQDmJ4Qj/puU7+sFCs7MXUtd3tClEH1NUalH0T\n5awjZcJnMmGVmtGGfP1DtuEd082mIUuvKZj1vCEiSavwK3JDVl5goxlDpvEgdh2X\no1eSIMMZb6FG5h3dsyyMpXaRobgL+qbLm0XDGwtiIu+d5BE8OQECggEBAPL+FwUB\n2w4bRGzmDNRJm3oDcDlBROn5nFpzzSuXRA8zSrJbNB9s55EqTnZw7xVNa6nUxi9C\nd2Hqcbp9HD8EezlbMWJ4LASlYPzdBpAo5eyvK8YccE1QjlGlP7ZOf4+ekwlreqZ4\nfhRb4r/q49eW3aAWbJPu67MYu1iBMpdINZpMzDdE1wKjRXWu0j7Lr3SXjzgjD94E\nG+4VvJ0xc8WgjM9YSLxFN/5VZd+us7l6V18vOrdPDpAlJuTkmSpP0Xx4oUKJs7X+\n84CEB47GgUqf3bPadS8XRC2slEA+or5BJnPTVQ5YgTeWZE2kD3tLDOVHE7gLmV61\njYy2Icm+sosnfeECggEBAM3lVYO3D5Cw9Z4CkewrzMUxd7sSd5YqHavfEjvFc4Pk\n6Q6hsH1KR4Ai6loB8ugSz2SIS6KoqGD8ExvQxWy4AJf/n39hxb8/9IJ3b6IqBs64\n+ELJ8zw3QheER93FwK/KbawzLES9RkdpvDBSHFFfbGxjHpm+quQ8JcNIHTg43fb+\nTWe+mXYSjIWVCNssHBl5LRmkly37DxvBzu9YSZugESr80xSMDkBmWnpsq2Twh3q4\n2yP6jgfaZtV9AQQ01jkPgqpcuSoHm2qyqfiIr3LkA34OQmzWpyPn17If1DSJhlXo\nClSSl5Guqt9r0ifuBcMbl69OyAgpGr4N5sFxRk0wGkkCggEBAMt34hSqSiAUywYY\n2DNGc28GxAjdU3RMNBU1lF5k6nOD8o9IeWu7CGhwsYTR6hC/ZGCwL0dRc5/E7XhH\n3MgT247ago6+q7U0OfNirGU4Kdc3kwLvu0WyJ4nMQn5IWt4K3XpsyiXtDT3E9yjW\n6fQTev7a6A4zaJ/uHKnufUtaBrBukC3TcerehoIVYi185y1M33sVOOsiK7T/9JD3\n4MZiOqZAeZ9Uop9QKN7Vbd7ox5KHfLYT99DRmzDdDjf04ChG5llN7vJ9Sq6ZX665\nH3g6Ry2bxrYo2EkakoT9Lc77xNQF6Nn7WDAQuWqd7uzBmkm+a4+X/tPkWGOz+rTw\n/pYw+mECggEBAKQiMe1yPUJHD0YLHnB66h44tQ24RwS6RjUA+vQTD2cRUIiNdLgs\nQptvOgrOiuleNV4bGNBuSuwlhsYhw4BLno2NBYTyWEWBolVvCNrpTcv1wFLd0r0p\n/9HnbbLpNhXs9UjU8nFJwYCkVZTfoBtuSmyNB5PgXzLaj/AAyOpMywVe7C3Lz2JE\nnyjOCeVOYIgeBUnv32SUQxMJiQFcDDG3hHgUW+CBVcsYzP/TKT6qUBYQzwD7d8Xi\n4R9HK0xDIpMSPkO47xMGRWrlSoIJ1HNuOSqAC4vgAhWpeFVS8kN/bkuFUtbglVtZ\nNnYs6bdTE9zZXi4uS1/WBK+FPXLv7e8SbaECggEAI2gTDuCm5kVoVJhGzWA5/hmB\nPAUhSQpMHrT8Em4cXss6Q07q9A2l8NuNrZt6kNhwagdng7v7NdPY3ZBl/ntmKmZN\nxWUKzQCtIddW6Z/veO86F15NyBBZFXIOhzvwnrTtS3iX0JP0dlTZTv/Oe3DPk3aq\nsFJtHM6s44ZBYYAgzSAxTdl+80oGmtdrGnSRfRmlav1kjWLAKurXw8FTl9rKgGNA\nUUv/jGSe1DxnEMvtoSwQVjcS0im57vW0x8LEz5eTWMYwkvxGHm0/WU2Yb0I6mL4j\nPWrHwwPdRoF/cPNWa7eTsZBKdVN9iNHSu7yE9owXyHSpesI1IZf8Zq4bqPNpaA==\n-----END RSA PRIVATE KEY-----`),\n\t}\n\tblock, _ := pem.Decode(raw[size])\n\tkey, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprivKey, err := utils.RSAToPrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn privKey, nil\n}", "func (pr *PasswordRecord) GetKeyRSA(password string) (key rsa.PrivateKey, err error) {\n\tif pr.Type != RSARecord {\n\t\treturn key, errors.New(\"Invalid function for record type\")\n\t}\n\n\terr = pr.ValidatePassword(password)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpassKey, err := derivePasswordKey(password, pr.KeySalt)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trsaExponentPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAExp, pr.RSAKey.RSAExpIV, passKey)\n\tif err != nil {\n\t\treturn\n\t}\n\trsaExponent, err := padding.RemovePadding(rsaExponentPadded)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trsaPrimePPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAPrimeP, pr.RSAKey.RSAPrimePIV, passKey)\n\tif err != nil {\n\t\treturn\n\t}\n\trsaPrimeP, err := padding.RemovePadding(rsaPrimePPadded)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trsaPrimeQPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAPrimeQ, pr.RSAKey.RSAPrimeQIV, passKey)\n\tif err != nil {\n\t\treturn\n\t}\n\trsaPrimeQ, err := padding.RemovePadding(rsaPrimeQPadded)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tkey.PublicKey = pr.RSAKey.RSAPublic\n\tkey.D = big.NewInt(0).SetBytes(rsaExponent)\n\tkey.Primes = []*big.Int{big.NewInt(0), big.NewInt(0)}\n\tkey.Primes[0].SetBytes(rsaPrimeP)\n\tkey.Primes[1].SetBytes(rsaPrimeQ)\n\n\terr = key.Validate()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func encryptRSARecord(newRec *PasswordRecord, rsaPriv *rsa.PrivateKey, passKey []byte) (err error) {\n\tif newRec.RSAKey.RSAExpIV, err = symcrypt.MakeRandom(16); err != nil {\n\t\treturn\n\t}\n\n\tpaddedExponent := padding.AddPadding(rsaPriv.D.Bytes())\n\tif newRec.RSAKey.RSAExp, err = symcrypt.EncryptCBC(paddedExponent, newRec.RSAKey.RSAExpIV, passKey); err != nil {\n\t\treturn\n\t}\n\n\tif newRec.RSAKey.RSAPrimePIV, err = symcrypt.MakeRandom(16); err != nil {\n\t\treturn\n\t}\n\n\tpaddedPrimeP := padding.AddPadding(rsaPriv.Primes[0].Bytes())\n\tif newRec.RSAKey.RSAPrimeP, err = symcrypt.EncryptCBC(paddedPrimeP, newRec.RSAKey.RSAPrimePIV, passKey); err != nil {\n\t\treturn\n\t}\n\n\tif newRec.RSAKey.RSAPrimeQIV, err = symcrypt.MakeRandom(16); err != nil {\n\t\treturn\n\t}\n\n\tpaddedPrimeQ := padding.AddPadding(rsaPriv.Primes[1].Bytes())\n\tnewRec.RSAKey.RSAPrimeQ, err = symcrypt.EncryptCBC(paddedPrimeQ, newRec.RSAKey.RSAPrimeQIV, passKey)\n\treturn\n}", "func EncodePrivateKey(key crypto.PrivateKey) (jwk *JWK, err error) {\n\tjwk = new(JWK)\n\tswitch k := key.(type) {\n\tcase *ecdsa.PrivateKey:\n\t\tjwk.populateECPublicKey(&k.PublicKey)\n\t\tjwk.D = b64.EncodeToString(k.D.Bytes())\n\n\tcase *rsa.PrivateKey:\n\t\tjwk.populateRSAPublicKey(&k.PublicKey)\n\t\tjwk.D = b64.EncodeToString(k.D.Bytes())\n\t\tif len(k.Primes) < 2 || len(k.Precomputed.CRTValues) != len(k.Primes)-2 {\n\t\t\treturn nil, errors.New(\"jwk: invalid RSA primes number\")\n\t\t}\n\t\tjwk.P = b64.EncodeToString(k.Primes[0].Bytes())\n\t\tjwk.Q = b64.EncodeToString(k.Primes[1].Bytes())\n\t\tjwk.Dp = b64.EncodeToString(k.Precomputed.Dp.Bytes())\n\t\tjwk.Dq = b64.EncodeToString(k.Precomputed.Dq.Bytes())\n\t\tjwk.Qi = b64.EncodeToString(k.Precomputed.Qinv.Bytes())\n\n\t\tif len(k.Primes) > 2 {\n\t\t\tjwk.Oth = make([]*RSAPrime, len(k.Primes)-2)\n\t\t\tfor i := 0; i < len(k.Primes)-2; i++ {\n\t\t\t\tjwk.Oth[i] = &RSAPrime{\n\t\t\t\t\tR: b64.EncodeToString(k.Primes[i+2].Bytes()),\n\t\t\t\t\tD: b64.EncodeToString(k.Precomputed.CRTValues[i].Exp.Bytes()),\n\t\t\t\t\tT: b64.EncodeToString(k.Precomputed.CRTValues[i].Coeff.Bytes()),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"jwk: unknown private key type: %T\", key)\n\t}\n\n\treturn jwk, nil\n}", "func RSAVerify(key *rsa.PublicKey, hash crypto.Hash, data, sig []byte) (\n\terr error) {\n\n\th := hash.New()\n\tif _, err := h.Write(data); err != nil {\n\t\treturn err\n\t}\n\treturn rsa.VerifyPKCS1v15(key, hash, h.Sum(nil), sig)\n}", "func (_WyvernExchange *WyvernExchangeSession) ValidateOrderParameters(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) (bool, error) {\n\treturn _WyvernExchange.Contract.ValidateOrderParameters(&_WyvernExchange.CallOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n}", "func (r *RSA) Init() {\n\tlog.Infof(\"Generating %d bit RSA key...\", RSA_KEY_LENGTH)\n\n\t// generate RSA key\n\tvar pKey, err = rsa.GenerateKey(rand.Reader, RSA_KEY_LENGTH)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating RSA key:\" + err.Error())\n\t}\n\n\tr.privateKey = pKey\n\n\t// encode key to ASN.1 PublicKey Type\n\tvar key, err2 = asn1.Marshal(r.privateKey.PublicKey)\n\tif err2 != nil {\n\t\tlog.Fatal(\"Error encoding Public RSA key:\" + err2.Error())\n\t}\n\n\t// move public key to array\n\tcopy(r.PublicKey[:], key)\n}", "func (c *Coffin) encryptRSA(data []byte) ([]byte, error) {\n\n\t// If public key is not supplied, return error\n\tif len(c.Opts.PubKey) == 0 {\n\t\treturn emptyByte, ErrNoPubKey\n\t}\n\n\t// Unmarshall the RSA public key\n\trsaKey, err := UnmarshalPublicKey(bytes.NewBuffer(c.Opts.PubKey))\n\tif err != nil {\n\t\treturn emptyByte, err\n\t}\n\n\t// Encrypt the data\n\thash := sha512.New()\n\tciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, rsaKey, data, nil)\n\tif err != nil {\n\t\treturn emptyByte, err\n\t}\n\n\t// Return the data\n\treturn ciphertext, nil\n}", "func (_WyvernExchange *WyvernExchangeCaller) ValidateOrderParameters(opts *bind.CallOpts, addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _WyvernExchange.contract.Call(opts, out, \"validateOrderParameters_\", addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n\treturn *ret0, err\n}", "func parsePublicKey(pemBytes []byte) (interface{}, error) {\n\tblock, _ := pem.Decode(pemBytes)\n\tif block == nil {\n\t\treturn nil, errors.New(\"ssh: no key found\")\n\t}\n\tswitch block.Type {\n\tcase \"PUBLIC KEY\":\n\t\trsa, err := x509.ParsePKIXPublicKey(block.Bytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn rsa, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"ssh: unsupported key type %q\", block.Type)\n\t}\n}", "func (_WyvernExchange *WyvernExchangeCallerSession) ValidateOrderParameters(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) (bool, error) {\n\treturn _WyvernExchange.Contract.ValidateOrderParameters(&_WyvernExchange.CallOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n}", "func GenerateRSA() (*rsa.PrivateKey, rsa.PublicKey) {\n\treader := rand.Reader\n\tbitSize := 2048\n\tkey, err := rsa.GenerateKey(reader, bitSize)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error generating key: %v\", err)\n\t\t// TODO: handle error\n\t}\n\treturn key, key.PublicKey\n}", "func validateServiceParameters(parameters []*Service_Parameter, data *types.Struct) error {\n\tvar errs xerrors.Errors\n\n\tfor _, p := range parameters {\n\t\tvar value *types.Value\n\t\tif data != nil && data.Fields != nil {\n\t\t\tvalue = data.Fields[p.Key]\n\t\t}\n\t\tif err := p.Validate(value); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn errs.ErrorOrNil()\n}", "func validateParams(method model.Method, params map[string]interface{}) (bool, error) {\n\tvar notSpecified []model.Parameter\n\tfor _, param := range method.Parameters {\n\t\tvalue := params[param.Name]\n\t\tif param.Required {\n\t\t\tif value != \"\" && value != nil{\n\t\t\t\tactualType := getTypeName(value)\n\t\t\t\tif actualType != param.Type {\n\t\t\t\t\tmsg := fmt.Sprintf(\"Wrong argument '%s' for method '%s'. Expected type '%s', but found '%s'\", param.Name, method.Name, param.Type, actualType)\n\t\t\t\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\t\t\t\treturn false, errors.New(msg)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnotSpecified = append(notSpecified, param)\n\t\t\t}\n\t\t} else {\n\t\t\tif value != \"\" && value != nil {\n\t\t\t\t// optional parameters check\n\t\t\t\tactualType := getTypeName(value)\n\t\t\t\tif actualType != param.Type {\n\t\t\t\t\tmsg := fmt.Sprintf(\"Wrong argument '%s' for method '%s'. Expected type '%s', but found '%s'\", param.Name, method.Name, param.Type, actualType)\n\t\t\t\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\t\t\t\treturn false, errors.New(msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(notSpecified) != 0 {\n\t\tvar paramStr string = \"\"\n\t\tfor _, param := range notSpecified {\n\t\t\tparamStr += fmt.Sprintf(\"'%s', \", param.Name)\n\t\t}\n\t\tmsg := fmt.Sprintf(\"Required parameters are not provided for '%s' method. Please specify: %s\", method.Name, paramStr[:len(paramStr) - 2])\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn false, errors.New(msg)\n\t}\n\treturn true, nil\n}", "func ParsePubKey(pubKeyStr []byte) (key *PublicKey, err error) {\n\tpubkey := PublicKey{}\n\n\tif len(pubKeyStr) == 0 {\n\t\treturn nil, errors.New(\"pubkey string is empty\")\n\t}\n\n\tformat := pubKeyStr[0]\n\tybit := (format & 0x1) == 0x1\n\tformat &= ^byte(0x1)\n\n\tswitch len(pubKeyStr) {\n\tcase PubKeyBytesLenUncompressed:\n\t\tif format != pubKeyUncompressed && format != pubKeyHybrid {\n\t\t\treturn nil, fmt.Errorf(\"invalid magic in pubkey str: \"+\n\t\t\t\t\"%d\", pubKeyStr[0])\n\t\t}\n\n\t\tpubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])\n\t\tpubkey.Y = new(big.Int).SetBytes(pubKeyStr[33:])\n\t\t// hybrid keys have extra information, make use of it.\n\t\tif format == pubKeyHybrid && ybit != isOdd(pubkey.Y) {\n\t\t\treturn nil, fmt.Errorf(\"ybit doesn't match oddness\")\n\t\t}\n\tcase PubKeyBytesLenCompressed:\n\t\t// format is 0x2 | solution, <X coordinate>\n\t\t// solution determines which solution of the curve we use.\n\t\t/// y^2 = x^3 + Curve.B\n\t\tif format != pubKeyCompressed {\n\t\t\treturn nil, fmt.Errorf(\"invalid magic in compressed \"+\n\t\t\t\t\"pubkey string: %d\", pubKeyStr[0])\n\t\t}\n\t\tpubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])\n\t\tpubkey.Y, err = decompressPoint(pubkey.X, ybit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault: // wrong!\n\t\treturn nil, fmt.Errorf(\"invalid pub key length %d\",\n\t\t\tlen(pubKeyStr))\n\t}\n\n\tif pubkey.X.Cmp(secp256k1.Params().P) >= 0 {\n\t\treturn nil, fmt.Errorf(\"pubkey X parameter is >= to P\")\n\t}\n\tif pubkey.Y.Cmp(secp256k1.Params().P) >= 0 {\n\t\treturn nil, fmt.Errorf(\"pubkey Y parameter is >= to P\")\n\t}\n\tif !secp256k1.IsOnCurve(pubkey.X, pubkey.Y) {\n\t\treturn nil, fmt.Errorf(\"pubkey isn't on secp256k1 curve\")\n\t}\n\treturn &pubkey, nil\n}", "func (asap *ASAP) Validate(jwt jwt.JWT, publicKey cr.PublicKey) error {\n\theader := jwt.(jws.JWS).Protected()\n\tkid := header.Get(KeyID).(string)\n\talg := header.Get(algorithm).(string)\n\n\tsigningMethod, err := getSigningMethod(alg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn jwt.Validate(publicKey, signingMethod, validator.GenerateValidator(kid, asap.ServiceID))\n}", "func (lib *PKCS11Lib) exportRSAPublicKey(session pkcs11.SessionHandle, pubHandle pkcs11.ObjectHandle) (crypto.PublicKey, error) {\n\tlogger.Tracef(\"session=0x%X, obj=0x%X\", session, pubHandle)\n\ttemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS, nil),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, nil),\n\t}\n\texported, err := lib.Ctx.GetAttributeValue(session, pubHandle, template)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tvar modulus = new(big.Int)\n\tmodulus.SetBytes(exported[0].Value)\n\tvar bigExponent = new(big.Int)\n\tbigExponent.SetBytes(exported[1].Value)\n\tif bigExponent.BitLen() > 32 {\n\t\treturn nil, errors.WithStack(errMalformedRSAKey)\n\t}\n\tif bigExponent.Sign() < 1 {\n\t\treturn nil, errors.WithStack(errMalformedRSAKey)\n\t}\n\texponent := int(bigExponent.Uint64())\n\tresult := rsa.PublicKey{\n\t\tN: modulus,\n\t\tE: exponent,\n\t}\n\tif result.E < 2 {\n\t\treturn nil, errors.WithStack(errMalformedRSAKey)\n\t}\n\treturn &result, nil\n}", "func CheckParams(params Setting, passwordType string) bool {\n\n\tminLen := params.MinLength\n\tminSpecials := params.MinSpecialCharacters\n\tminDigits := params.MinDigits\n\tminLowers := params.MinLowercase\n\tminUppers := params.MinUppercase\n\n\tif minLen < AbsoluteMinLen ||\n\t\tminDigits < config[passwordType].MinDigits ||\n\t\tminLowers < config[passwordType].MinLowercase ||\n\t\tminUppers < config[passwordType].MinUppercase ||\n\t\tminSpecials < config[passwordType].MinSpecialCharacters {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func IsRsaPublicKey(str string, keylen int) bool {\n\tbb := bytes.NewBufferString(str)\n\tpemBytes, err := ioutil.ReadAll(bb)\n\tif err != nil {\n\t\treturn false\n\t}\n\tblock, _ := pem.Decode(pemBytes)\n\tif block != nil && block.Type != \"PUBLIC KEY\" {\n\t\treturn false\n\t}\n\tvar der []byte\n\n\tif block != nil {\n\t\tder = block.Bytes\n\t} else {\n\t\tder, err = base64.StdEncoding.DecodeString(str)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tkey, err := x509.ParsePKIXPublicKey(der)\n\tif err != nil {\n\t\treturn false\n\t}\n\tpubkey, ok := key.(*rsa.PublicKey)\n\tif !ok {\n\t\treturn false\n\t}\n\tbitlen := len(pubkey.N.Bytes()) * 8\n\treturn bitlen == int(keylen)\n}", "func ConvertToPPK(privateKey *rsa.PrivateKey, pub []byte) ([]byte, error) {\n\t// https://the.earth.li/~sgtatham/putty/0.76/htmldoc/AppendixC.html#ppk\n\t// RSA keys are stored using an algorithm-name of 'ssh-rsa'. (Keys stored like this are also used by the updated RSA signature schemes that use\n\t// hashes other than SHA-1. The public key data has already provided the key modulus and the public encoding exponent. The private data stores:\n\t// mpint: the private decoding exponent of the key.\n\t// mpint: one prime factor p of the key.\n\t// mpint: the other prime factor q of the key. (RSA keys stored in this format are expected to have exactly two prime factors.)\n\t// mpint: the multiplicative inverse of q modulo p.\n\tppkPrivateKey := new(bytes.Buffer)\n\n\t// mpint: the private decoding exponent of the key.\n\t// this is known as 'D'\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(privateKey.D))\n\n\t// mpint: one prime factor p of the key.\n\t// this is known as 'P'\n\t// the RSA standard dictates that P > Q\n\t// for some reason what PuTTY names 'P' is Primes[1] to Go, and what PuTTY names 'Q' is Primes[0] to Go\n\tP, Q := privateKey.Primes[1], privateKey.Primes[0]\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(P))\n\n\t// mpint: the other prime factor q of the key. (RSA keys stored in this format are expected to have exactly two prime factors.)\n\t// this is known as 'Q'\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(Q))\n\n\t// mpint: the multiplicative inverse of q modulo p.\n\t// this is known as 'iqmp'\n\tiqmp := new(big.Int).ModInverse(Q, P)\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(iqmp))\n\n\t// now we need to base64-encode the PPK-formatted private key which is made up of the above values\n\tppkPrivateKeyBase64 := make([]byte, base64.StdEncoding.EncodedLen(ppkPrivateKey.Len()))\n\tbase64.StdEncoding.Encode(ppkPrivateKeyBase64, ppkPrivateKey.Bytes())\n\n\t// read Teleport public key\n\t// fortunately, this is the one thing that's in exactly the same format that the PPK file uses, so we can just copy it verbatim\n\t// remove ssh-rsa plus additional space from beginning of string if present\n\tif !bytes.HasPrefix(pub, []byte(constants.SSHRSAType+\" \")) {\n\t\treturn nil, trace.BadParameter(\"pub does not appear to be an ssh-rsa public key\")\n\t}\n\tpub = bytes.TrimSuffix(bytes.TrimPrefix(pub, []byte(constants.SSHRSAType+\" \")), []byte(\"\\n\"))\n\n\t// the PPK file contains an anti-tampering MAC which is made up of various values which appear in the file.\n\t// copied from Section C.3 of https://the.earth.li/~sgtatham/putty/0.76/htmldoc/AppendixC.html#ppk:\n\t// hex-mac-data is a hexadecimal-encoded value, 64 digits long (i.e. 32 bytes), generated using the HMAC-SHA-256 algorithm with the following binary data as input:\n\t// string: the algorithm-name header field.\n\t// string: the encryption-type header field.\n\t// string: the key-comment-string header field.\n\t// string: the binary public key data, as decoded from the base64 lines after the 'Public-Lines' header.\n\t// string: the plaintext of the binary private key data, as decoded from the base64 lines after the 'Private-Lines' header.\n\n\t// these values are also used in the MAC generation, so we declare them as variables\n\tkeyType := constants.SSHRSAType\n\tencryptionType := \"none\"\n\t// as work for the future, it'd be nice to get the proxy/user pair name in here to make the name more\n\t// of a unique identifier. this has to be done at generation time because the comment is part of the MAC\n\tfileComment := \"teleport-generated-ppk\"\n\n\t// string: the algorithm-name header field.\n\tmacKeyType := getRFC4251String([]byte(keyType))\n\t// create a buffer to hold the elements needed to generate the MAC\n\tmacInput := new(bytes.Buffer)\n\tbinary.Write(macInput, binary.LittleEndian, macKeyType)\n\n\t// string: the encryption-type header field.\n\tmacEncryptionType := getRFC4251String([]byte(encryptionType))\n\tbinary.Write(macInput, binary.BigEndian, macEncryptionType)\n\n\t// string: the key-comment-string header field.\n\tmacComment := getRFC4251String([]byte(fileComment))\n\tbinary.Write(macInput, binary.BigEndian, macComment)\n\n\t// base64-decode the Teleport public key, as we need its binary representation to generate the MAC\n\tdecoded := make([]byte, base64.StdEncoding.EncodedLen(len(pub)))\n\tn, err := base64.StdEncoding.Decode(decoded, pub)\n\tif err != nil {\n\t\treturn nil, trace.Errorf(\"could not base64-decode public key: %v, got %v bytes successfully\", err, n)\n\t}\n\tdecoded = decoded[:n]\n\t// append the decoded public key bytes to the MAC buffer\n\tmacPublicKeyData := getRFC4251String(decoded)\n\tbinary.Write(macInput, binary.BigEndian, macPublicKeyData)\n\n\t// append our PPK-formatted private key bytes to the MAC buffer\n\tmacPrivateKeyData := getRFC4251String(ppkPrivateKey.Bytes())\n\tbinary.Write(macInput, binary.BigEndian, macPrivateKeyData)\n\n\t// as per the PPK spec, the key for the MAC is blank when the PPK file is unencrypted.\n\t// therefore, the key is a zero-length byte slice.\n\thmacHash := hmac.New(sha256.New, []byte{})\n\t// generate the MAC using HMAC-SHA-256\n\thmacHash.Write(macInput.Bytes())\n\tmacString := hex.EncodeToString(hmacHash.Sum(nil))\n\n\t// build the string-formatted output PPK file\n\tppk := new(bytes.Buffer)\n\tfmt.Fprintf(ppk, \"PuTTY-User-Key-File-3: %v\\n\", keyType)\n\tfmt.Fprintf(ppk, \"Encryption: %v\\n\", encryptionType)\n\tfmt.Fprintf(ppk, \"Comment: %v\\n\", fileComment)\n\t// chunk the Teleport-formatted public key into 64-character length lines\n\tchunkedPublicKey := chunk(string(pub), 64)\n\tfmt.Fprintf(ppk, \"Public-Lines: %v\\n\", len(chunkedPublicKey))\n\tfor _, r := range chunkedPublicKey {\n\t\tfmt.Fprintf(ppk, \"%s\\n\", r)\n\t}\n\t// chunk the PPK-formatted private key into 64-character length lines\n\tchunkedPrivateKey := chunk(string(ppkPrivateKeyBase64), 64)\n\tfmt.Fprintf(ppk, \"Private-Lines: %v\\n\", len(chunkedPrivateKey))\n\tfor _, r := range chunkedPrivateKey {\n\t\tfmt.Fprintf(ppk, \"%s\\n\", r)\n\t}\n\tfmt.Fprintf(ppk, \"Private-MAC: %v\\n\", macString)\n\n\treturn ppk.Bytes(), nil\n}", "func generateRSAKey(p *pkcs11.Ctx,\n\tsession pkcs11.SessionHandle,\n\tgun data.GUN,\n\tpassRetriever notary.PassRetriever,\n\trole data.RoleName,\n) (*LunaPrivateKey, error) {\n\n\tpublicKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_MODULUS_BITS, 2048),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, []byte{0x01, 0x00, 0x01}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, fmt.Sprintf(\"notary-%s;;%s;public\", gun, role)),\n\t}\n\n\tprivateKeyTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_SIGN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, fmt.Sprintf(\"notary-%s;;%s;private\", gun, role)),\n\t}\n\n\tmechanism := []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_KEY_PAIR_GEN, nil)}\n\tpubObjectHandle, privObjectHandle, err := p.GenerateKeyPair(session, mechanism, publicKeyTemplate, privateKeyTemplate)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Failed to generate key pair: %s\", err.Error())\n\t\treturn nil, fmt.Errorf(\"Failed to generate key pair: %v\", err)\n\t}\n\n\tpubKey, _, err := getRSAKeyFromObjectHandle(p, session, pubObjectHandle)\n\tif err != nil {\n\t\tdestroyObjects(p, session, []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle})\n\t\treturn nil, err\n\t}\n\tpubID := []byte(pubKey.ID())\n\terr = setIDForObjectHandles(p, session, pubID, []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprivateKey := NewLunaPrivateKey(pubID, pubKey, data.RSAPKCS1v15Signature, passRetriever)\n\tif privateKey == nil {\n\t\tdestroyObjects(p, session, []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle})\n\t\treturn nil, errors.New(\"could not initialize new LunaPrivateKey\")\n\t}\n\n\tid := pubKey.ID()\n\n\tcertObjectHandle, err := createCertificate(p, session, gun, role, id, privateKey)\n\tif err != nil {\n\t\tdestroyObjects(p, session, []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle})\n\t\treturn nil, fmt.Errorf(\"Error creating certificate: %v\", err)\n\t}\n\n\tlogrus.Debugf(\"Setting keyID: %s\", id)\n\tprivateKey.keyID = []byte(id)\n\n\tobjectHandles := []pkcs11.ObjectHandle{pubObjectHandle, privObjectHandle, certObjectHandle}\n\n\terr = setIDsAndLabels(p, session, gun, role, id, []string{\"public\", \"private\", \"cert\"}, objectHandles)\n\tif err != nil {\n\t\tdestroyObjects(p, session, objectHandles)\n\t\treturn nil, err\n\t}\n\n\treturn privateKey, nil\n}", "func fromRSAKey(key ssh.PublicKey) (security.PublicKey, error) {\n\tk, err := parseRSAKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn security.NewRSAPublicKey(k), nil\n}", "func (k *KeyInstanceCert) CreateRSAInstance() {\n\tprivateKey, _ := rsa.GenerateKey(rand.Reader, 4096)\n\tk.PrivateKey = privateKey //implicit durch compiler (*k).PrivateKey\n\tpublicKey := privateKey.PublicKey\n\tk.PublicKey = publicKey\n\n\tprivKeyPEM := new(bytes.Buffer)\n\tpem.Encode(privKeyPEM, &pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(privateKey),\n\t})\n\tk.PrivateKeyPEM = privKeyPEM\n\n\tpublicKeyPEM := new(bytes.Buffer)\n\tpem.Encode(publicKeyPEM, &pem.Block{\n\t\tType: \"RSA PUBLIC KEY\",\n\t\tBytes: x509.MarshalPKCS1PublicKey(&publicKey),\n\t})\n\tk.PublicKeyPEM = publicKeyPEM\n\n}", "func RunJSONSerializationTestForKeyVaultSigningKeyParameters(subject KeyVaultSigningKeyParameters) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual KeyVaultSigningKeyParameters\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (o *TppCertificateParams) GetPublicKeyOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.PublicKey, true\n}", "func ParsePrivateKey(derBlob []byte) (parsedPrivateKey interface{}, keyType string, err error) {\n // First check if it is an RSA key\n parsedPrivateKey, err = x509.ParsePKCS1PrivateKey(derBlob)\n // If we get an error, it might be an EC key or malformed\n if err != nil {\n parsedPrivateKey, err = x509.ParseECPrivateKey(derBlob)\n if err != nil {\n return nil, \"\", err // if we encounter an error then the key is malformed (or not EC/RSA)\n }\n // Because we have a return inside the if, this is essentially the else part\n // If ParseECPrivateKey was sucessfulthen it's an EC key\n keyType = \"EC\"\n return parsedPrivateKey, keyType, err // no naked returns\n }\n // If ParsePKCS1PrivateKey was successful then it's an RSA key\n keyType = \"RSA\"\n return parsedPrivateKey, keyType, err\n\n // I could do a bunch of if-else and do only one return in the end, but I think this is more readable\n}", "func verify(publicKey *rsa.PublicKey, message []byte, sig []byte) error {\n\th := sha256.New()\n\th.Write(message)\n\td := h.Sum(nil)\n\treturn rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, d, sig)\n}", "func TestRSAKeyExport(t *testing.T) {\n\tkey, err := NewKeyFromPrivateKeyPEM([]byte(rsaPrivKeyAuthPEM))\n\tif err != nil {\n\t\tt.Fatal(\"Failed to parse certificate from PEM:\", err)\n\t}\n\n\tpemBytes, err := key.ExportPrivate()\n\tif err != nil {\n\t\tt.Fatal(\"Failed exporting PEM-format bytes:\", err)\n\t}\n\tif !bytes.Equal(pemBytes, []byte(rsaPrivKeyAuthPEM)) {\n\t\tt.Fatal(\"Failed exporting the same PEM-format bytes\")\n\t}\n}", "func NewRSAKeyPair() (*RSAKeyPair, error) {\n\treader := rand.Reader\n\tprivateKey, err := rsa.GenerateKey(reader, bitSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newRSAKeyPair(privateKey, &privateKey.PublicKey)\n}", "func (m *PaymentServiceItemParam) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOrigin(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentServiceItemID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (params Params) Validate() error {\n\tif err := ValidateNicknameParams(params.Nickname); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ValidateDTagParams(params.DTag); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ValidateBioParams(params.Bio); err != nil {\n\t\treturn err\n\t}\n\n\treturn ValidateOracleParams(params.Oracle)\n}", "func RsaPublicKeyVerify(data string, publicKeyHexOrPem string, signatureHex string) error {\n\t// data is required\n\tif len(data) == 0 {\n\t\treturn errors.New(\"Data To Verify is Required\")\n\t}\n\n\t// get public key\n\tvar publicKey *rsa.PublicKey\n\tvar err error\n\n\tif util.Left(publicKeyHexOrPem, 26) == \"-----BEGIN PUBLIC KEY-----\" && util.Right(publicKeyHexOrPem, 24) == \"-----END PUBLIC KEY-----\" {\n\t\t// get public key from pem\n\t\tpublicKey, err = rsaPublicKeyFromPem(publicKeyHexOrPem)\n\t} else {\n\t\t// get public key from hex\n\t\tpublicKey, err = rsaPublicKeyFromHex(publicKeyHexOrPem)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// convert data to byte array\n\tmsg := []byte(data)\n\n\t// define hash\n\th := sha256.New()\n\th.Write(msg)\n\td := h.Sum(nil)\n\n\tsig, _ := util.HexToByte(signatureHex)\n\n\terr1 := rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, d, sig)\n\n\tif err1 != nil {\n\t\treturn err1\n\t}\n\n\t// verified\n\treturn nil\n}", "func VerifyPKCS1v15(pub *rsa.PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error {\n\thashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttLen := len(prefix) + hashLen\n\tk := pub.Size()\n\tif k < tLen+11 {\n\t\treturn rsa.ErrVerification\n\t}\n\n\tc := new(big.Int).SetBytes(sig)\n\tm := encrypt(new(big.Int), pub, c)\n\tem := leftPad(m.Bytes(), k)\n\t// EM = 0x00 || 0x01 || PS || 0x00 || T\n\n\tok := subtle.ConstantTimeByteEq(em[0], 0)\n\tok &= subtle.ConstantTimeByteEq(em[1], 1)\n\tok &= subtle.ConstantTimeCompare(em[k-hashLen:k], hashed)\n\tok &= subtle.ConstantTimeCompare(em[k-tLen:k-hashLen], prefix)\n\tok &= subtle.ConstantTimeByteEq(em[k-tLen-1], 0)\n\n\tfor i := 2; i < k-tLen-1; i++ {\n\t\tok &= subtle.ConstantTimeByteEq(em[i], 0xff)\n\t}\n\n\tif ok != 1 {\n\t\treturn rsa.ErrVerification\n\t}\n\n\treturn nil\n}", "func GenerateRSA(bitSize int) (*rsa.PrivateKey, error) {\n\tif bitSize <= 1024 {\n\t\treturn nil, ErrInsecureKeyBitSize\n\t}\n\n\treturn rsa.GenerateKey(rand.Reader, bitSize)\n}", "func NewCognitoRSAParser(base64EncodedPublicKey map[string]string) (*CognitoRSAParser, error) {\n\tPublicKeys := map[string]*rsa.PublicKey{}\n\n\tfor kid, encodedPublicKey := range base64EncodedPublicKey {\n\t\tpublicKey, err := parsePublicKey(encodedPublicKey)\n\t\tif err != nil {\n\t\t\treturn nil, ErrFailedToParsePublicKey\n\t\t}\n\t\tPublicKeys[kid] = publicKey\n\t}\n\n\tjwtParser := &jwt.Parser{\n\t\tUseJSONNumber: true,\n\t}\n\n\treturn &CognitoRSAParser{\n\t\tPublicKeys: PublicKeys,\n\t\tjwtParser: jwtParser,\n\t}, nil\n}", "func LoadRSAKey() interfaces.RSAKey {\n\tdeferFunc := logger.LogWithDefer(\"Load RSA keys...\")\n\tdefer deferFunc()\n\n\tsignBytes, err := ioutil.ReadFile(\"config/key/private.key\")\n\tif err != nil {\n\t\tpanic(\"Error when load private key. \" + err.Error() + \". Please generate RSA keys\")\n\t}\n\tprivateKey, err := jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n\tif err != nil {\n\t\tpanic(\"Error when load private key. \" + err.Error())\n\t}\n\n\tverifyBytes, err := ioutil.ReadFile(\"config/key/public.pem\")\n\tif err != nil {\n\t\tpanic(\"Error when load public key. \" + err.Error() + \". Please generate RSA keys\")\n\t}\n\tpublicKey, err := jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n\tif err != nil {\n\t\tpanic(\"Error when load public key. \" + err.Error())\n\t}\n\n\treturn &key{\n\t\tprivate: privateKey, public: publicKey,\n\t}\n}", "func (m *JwtComponent) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif v, ok := interface{}(m.GetPrivateKey()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn JwtComponentValidationError{\n\t\t\t\tfield: \"PrivateKey\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetPublicKey()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn JwtComponentValidationError{\n\t\t\t\tfield: \"PublicKey\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewRSAWriter(w io.Writer, n, e int64) *RSAWriter {\n\tnbig := big.NewInt(n)\n\treturn &RSAWriter{\n\t\tw: w,\n\t\tn: nbig,\n\t\te: big.NewInt(e),\n\t\tbytes: uint64(nbig.BitLen() / 8),\n\t}\n}", "func GetRSAKeys(authserver string) (map[string]rsa.PublicKey, error) {\n\tjwksURI, err := getJwksURI(authserver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting jwks_uri failed: %w\", err)\n\t}\n\n\tkeyList := jwks{}\n\terr = getJSON(jwksURI, &keyList)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetching jwks failed: %w\", err)\n\t}\n\n\tkeys := make(map[string]rsa.PublicKey)\n\n\tfor _, key := range keyList.Keys {\n\n\t\tif key.Kty == \"RSA\" {\n\n\t\t\te, err := fromB64(key.E)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"big int from E: %w\", err)\n\t\t\t}\n\t\t\tn, err := fromB64(key.N)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"big int from N: %w\", err)\n\t\t\t}\n\n\t\t\tkeys[key.Kid] = rsa.PublicKey{N: &n, E: int(e.Int64())}\n\n\t\t}\n\t}\n\n\treturn keys, nil\n\n}", "func (lib *PKCS11Lib) GenerateRSAKeyPair(bits int, purpose KeyPurpose) (*PKCS11PrivateKeyRSA, error) {\n\treturn lib.GenerateRSAKeyPairOnSlot(lib.Slot.id, nil, nil, bits, purpose)\n}", "func (p Params) Validate() error {\n\tif err := validateActiveParam(p.Active); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateDelegatorParams(p.DelegatorDistributionSchedules); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateLPParams(p.LiquidityProviderSchedules); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateMoneyMarketParams(p.MoneyMarkets); err != nil {\n\t\treturn err\n\t}\n\n\treturn validateCheckLtvIndexCount(p.CheckLtvIndexCount)\n}", "func ValidatePublicKeyRecord(k u.Key, val []byte) error {\n\tkeyparts := bytes.Split([]byte(k), []byte(\"/\"))\n\tif len(keyparts) < 3 {\n\t\treturn errors.New(\"invalid key\")\n\t}\n\n\tpkh := u.Hash(val)\n\tif !bytes.Equal(keyparts[2], pkh) {\n\t\treturn errors.New(\"public key does not match storage key\")\n\t}\n\treturn nil\n}", "func (j *JWK) PrivateKey() (crypto.PrivateKey, error) {\n\tswitch j.KeyType {\n\tcase \"EC\", \"EC-HSM\":\n\t\tif j.D == \"\" {\n\t\t\treturn nil, ErrPublic\n\t\t}\n\t\tpub, err := j.ecPublicKey()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkey := ecdsa.PrivateKey{\n\t\t\tPublicKey: *pub,\n\t\t}\n\t\tif key.D, err = parseBase64UInt(j.D); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &key, nil\n\n\tcase \"RSA\", \"RSA-HSM\":\n\t\tif j.D == \"\" {\n\t\t\treturn nil, ErrPublic\n\t\t}\n\n\t\tpub, err := j.rsaPublicKey()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkey := rsa.PrivateKey{\n\t\t\tPublicKey: *pub,\n\t\t}\n\t\tif key.D, err = parseBase64UInt(j.D); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkey.Primes = make([]*big.Int, 2+len(j.Oth))\n\t\tif key.Primes[0], err = parseBase64UInt(j.P); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif key.Primes[1], err = parseBase64UInt(j.Q); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor i, a := range j.Oth {\n\t\t\tr, err := parseBase64UInt(a.R)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif r.Sign() <= 0 {\n\t\t\t\treturn nil, errors.New(\"jwk: private key contains zero or negative prime\")\n\t\t\t}\n\t\t\tkey.Primes[i+2] = r\n\t\t}\n\n\t\tif err = key.Validate(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkey.Precompute()\n\n\t\treturn &key, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"jwk: unknown key type: %s\", j.KeyType)\n}", "func MustRSAKey() *rsa.PrivateKey {\n\tkey, err := rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn key\n}", "func (r *RSAParameters) GetRSAPrivateKey() *rsa.PrivateKey {\n\tpk := new(rsa.PrivateKey)\n\n\tpk.PublicKey.N = base64ToBigInt(r.Modulus)\n\tpk.PublicKey.E = base64ToInt(r.Exponent)\n\tif pk.PublicKey.E == 0 {\n\t\tpk.PublicKey.E = 65537\n\t}\n\tpk.D = base64ToBigInt(r.D)\n\tpk.Primes = append(pk.Primes, base64ToBigInt(r.P))\n\tpk.Primes = append(pk.Primes, base64ToBigInt(r.Q))\n\tpk.Precomputed.Dp = base64ToBigInt(r.DP)\n\tpk.Precomputed.Dq = base64ToBigInt(r.DQ)\n\tpk.Precomputed.Qinv = base64ToBigInt(r.InverseQ)\n\n\treturn pk\n}", "func (r *Client) validateTemplateParams(t *Template, params []*Parameter) error {\n\tmissing := map[string]interface{}{}\n\t// copy all wanted params into missing\n\tfor k, v := range t.Parameters {\n\t\tmissing[k] = v\n\t}\n\t// remove items from missing list as found\n\tfor wantedKey := range t.Parameters {\n\t\tfor _, param := range params {\n\t\t\tif param.ParameterKey == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// phew found it\n\t\t\tif *param.ParameterKey == wantedKey {\n\t\t\t\tdelete(missing, wantedKey)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\t// if any left, then we have an issue\n\tif len(missing) > 0 {\n\t\tkeys := []string{}\n\t\tfor k := range missing {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tkeysCSV := strings.Join(keys, \",\")\n\t\treturn fmt.Errorf(\"missing required input parameters: [%s]\", keysCSV)\n\t}\n\treturn nil\n}", "func rsaPublicKeyFromPem(publicKeyPem string) (*rsa.PublicKey, error) {\n\tblock, _ := pem.Decode([]byte(publicKeyPem))\n\n\tif block == nil {\n\t\treturn nil, errors.New(\"RSA Public Key From Pem Fail: \" + \"Pem Block Nil\")\n\t}\n\n\tif key, err := x509.ParsePKIXPublicKey(block.Bytes); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn key.(*rsa.PublicKey), nil\n\t}\n}", "func ParsePublicKey(keyBytes []byte) (interface{}, error) {\n\tpk := PublicKeyData{}\n\twebauthncbor.Unmarshal(keyBytes, &pk)\n\n\tswitch COSEKeyType(pk.KeyType) {\n\tcase OctetKey:\n\t\tvar o OKPPublicKeyData\n\n\t\twebauthncbor.Unmarshal(keyBytes, &o)\n\t\to.PublicKeyData = pk\n\n\t\treturn o, nil\n\tcase EllipticKey:\n\t\tvar e EC2PublicKeyData\n\n\t\twebauthncbor.Unmarshal(keyBytes, &e)\n\t\te.PublicKeyData = pk\n\n\t\treturn e, nil\n\tcase RSAKey:\n\t\tvar r RSAPublicKeyData\n\n\t\twebauthncbor.Unmarshal(keyBytes, &r)\n\t\tr.PublicKeyData = pk\n\n\t\treturn r, nil\n\tdefault:\n\t\treturn nil, ErrUnsupportedKey\n\t}\n}", "func RsaPublicKeyEncrypt(data string, publicKeyHexOrPem string) (string, error) {\n\t// data must not exceed 214 bytes\n\tif len(data) > 214 {\n\t\treturn \"\", errors.New(\"RSA Public Key Encrypt Data Must Not Exceed 214 Bytes\")\n\t}\n\n\tif len(data) == 0 {\n\t\treturn \"\", errors.New(\"Data To Encrypt is Required\")\n\t}\n\n\t// get public key\n\tvar publicKey *rsa.PublicKey\n\tvar err error\n\n\tif util.Left(publicKeyHexOrPem, 26) == \"-----BEGIN PUBLIC KEY-----\" && util.Right(publicKeyHexOrPem, 24) == \"-----END PUBLIC KEY-----\" {\n\t\t// get public key from pem\n\t\tpublicKey, err = rsaPublicKeyFromPem(publicKeyHexOrPem)\n\t} else {\n\t\t// get public key from hex\n\t\tpublicKey, err = rsaPublicKeyFromHex(publicKeyHexOrPem)\n\t}\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// convert data into byte array\n\tmsg := []byte(data)\n\n\t// create hash\n\thash := sha256.New()\n\n\t// encrypt\n\tcipherText, err1 := rsa.EncryptOAEP(hash, rand.Reader, publicKey, msg, nil)\n\n\tif err1 != nil {\n\t\treturn \"\", err1\n\t}\n\n\t// return encrypted value\n\treturn util.ByteToHex(cipherText), nil\n}", "func SolvePuzzleRSA(ciphertext []byte, puzzle crypto.Puzzle) (message []byte, err error) {\n\tif puzzle == nil {\n\t\terr = fmt.Errorf(\"Puzzle cannot be nil, what are you solving\")\n\t\treturn\n\t}\n\n\tvar key []byte\n\tif key, err = puzzle.Solve(); err != nil {\n\t\terr = fmt.Errorf(\"Error solving auction puzzle: %s\", err)\n\t\treturn\n\t}\n\n\tvar privkey *rsa.PrivateKey\n\tif privkey, err = x509.ParsePKCS1PrivateKey(key); err != nil {\n\t\terr = fmt.Errorf(\"Error when parsing private key with pkcs#1 encoding: %s\", err)\n\t\treturn\n\t}\n\n\tif message, err = privkey.Decrypt(rand.Reader, ciphertext, nil); err != nil {\n\t\terr = fmt.Errorf(\"Error when decrypting puzzle message: %s\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func (h *auth) ParamsPKCE(c echo.Context) error {\n\tvar params service.LoginParams\n\tif err := c.Bind(&params); err != nil {\n\t\tlog.Println(\"Could not get parameters:\", err)\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"Could not get credentials.\"))\n\t}\n\tparams.UserAgent = c.Request().UserAgent()\n\tparams.Session = currentSession(c)\n\n\tif params.Email == \"\" {\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"Please provide an email address.\"))\n\t}\n\n\tif params.CodeChallenge == \"\" {\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"Please provide the code challenge parameter\"))\n\t}\n\n\tpkce := service.NewPKCE(h.db, params.Params)\n\n\tif err := pkce.StoreChallenge(params.CodeChallenge); err != nil {\n\t\tlog.Println(\"Could not store code challenge:\", err)\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"Could not store code challenge.\"))\n\t}\n\n\treturn h.params(c, params.Email)\n}", "func RSAEncrypt(src []byte, pubKey []byte) (res []byte, err error) {\n\tblock, _ := pem.Decode(pubKey)\n\n\t// unmarshal publicKey\n\tkeyInit, err := x509.ParsePKIXPublicKey(block.Bytes)\n\tif err != nil {\n\t\treturn\n\t}\n\tpublicKey := keyInit.(*rsa.PublicKey)\n\t// encrypt data with publicKey\n\tres, err = rsa.EncryptPKCS1v15(rand.Reader, publicKey, src)\n\treturn\n}", "func getRSAPublicKey(modulus []byte, exponent []byte) (*rsa.PublicKey, error) {\n\tn := new(big.Int).SetBytes(modulus)\n\te := new(big.Int).SetBytes(exponent)\n\teInt := int(e.Int64())\n\trsaPubKey := rsa.PublicKey{N: n, E: eInt}\n\treturn &rsaPubKey, nil\n}" ]
[ "0.7987645", "0.67373997", "0.62081987", "0.6145181", "0.6035359", "0.5793185", "0.5590855", "0.54903513", "0.54756767", "0.5403163", "0.54031277", "0.5334416", "0.5298498", "0.52967113", "0.5285707", "0.5281143", "0.5264965", "0.52576", "0.5218722", "0.52063566", "0.5171835", "0.51565105", "0.51563835", "0.51522315", "0.5122743", "0.51165706", "0.5105617", "0.5098983", "0.50857556", "0.5063441", "0.50418156", "0.50273067", "0.50222343", "0.5021128", "0.49594995", "0.49518326", "0.49192587", "0.4918441", "0.49164498", "0.49103394", "0.49100372", "0.48980248", "0.48900917", "0.4886612", "0.4873114", "0.48722744", "0.4867969", "0.48662314", "0.48517358", "0.4830731", "0.48275614", "0.48208883", "0.4809158", "0.47842774", "0.4769552", "0.47541344", "0.47359732", "0.4729275", "0.47268325", "0.46946537", "0.46699202", "0.46681336", "0.46674183", "0.46593934", "0.4658525", "0.46458796", "0.46230853", "0.461273", "0.4597015", "0.45954835", "0.4593569", "0.45843264", "0.45798826", "0.45772728", "0.45754352", "0.45745116", "0.45707822", "0.45662975", "0.45593014", "0.4556634", "0.4556588", "0.45536754", "0.4548844", "0.45399526", "0.4539385", "0.45390445", "0.4534668", "0.45299754", "0.4524646", "0.45139366", "0.45091435", "0.45080975", "0.45008275", "0.45004392", "0.44959447", "0.4483992", "0.44830427", "0.4481991", "0.44768533", "0.44634622" ]
0.607591
4
NewIndexDB creates a new instance of IndexDB
func NewIndexDB(db store.DB, recordStore *RecordDB) *IndexDB { return &IndexDB{db: db, recordStore: recordStore} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateIndexDB(langName string, dbT DBType) IndexDB {\n\t// TODO 暂时只实现了内存存储,一次性的。\n\treturn initMenDB(langName)\n}", "func NewIndex(addr, name, typ string, md *index.Metadata) (*Index, error) {\n\n\tfmt.Println(\"Get a new index: \", addr, name)\n client := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\t//MaxIdleConnsPerHost: 200,\n\t\t\tMaxIdleConnsPerHost: 2000000,\n\t\t},\n\t\tTimeout: 2500000 * time.Millisecond,\n\t}\n\tconn, err := elastic.NewClient(elastic.SetURL(addr), elastic.SetHttpClient(client))\n\tif err != nil {\n fmt.Println(\"Get error here\");\n\t\treturn nil, err\n\t}\n\tret := &Index{\n\t\tconn: conn,\n\t\tmd: md,\n\t\tname: name,\n\t\ttyp: typ,\n\t}\n fmt.Println(\"get here ======\");\n\n\treturn ret, nil\n\n}", "func NewIndex(addrs []string, pass string, temporary int, name string, md *index.Metadata) *Index {\n\n\tret := &Index{\n\n\t\thosts: addrs,\n\n\t\tmd: md,\n\t\tpassword: pass,\n\t\ttemporary: temporary,\n\n\t\tname: name,\n\n\t\tcommandPrefix: \"FT\",\n\t}\n\tif md != nil && md.Options != nil {\n\t\tif opts, ok := md.Options.(IndexingOptions); ok {\n\t\t\tif opts.Prefix != \"\" {\n\t\t\t\tret.commandPrefix = md.Options.(IndexingOptions).Prefix\n\t\t\t}\n\t\t}\n\t}\n\t//ret.pool.MaxActive = ret.pool.MaxIdle\n\n\treturn ret\n\n}", "func New(path string) (*Index, error) {\n\tkvdb, err := pudge.Open(path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Index{\n\t\tdb: kvdb,\n\t\tpath: path,\n\t}, nil\n}", "func (es *Repository) NewIndex(ctx context.Context, index string) (error){\n\tsvc := es.client.CreateIndex(\"ethan\")\n\n\t_, err := svc.Do(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func newDocumentIndex(opts *iface.CreateDocumentDBOptions) iface.StoreIndex {\n\treturn &documentIndex{\n\t\tindex: map[string][]byte{},\n\t\topts: opts,\n\t}\n}", "func New() *Index {\n\treturn &Index{Version: Version}\n}", "func (s *shard) initIndexDatabase() error {\n\tvar err error\n\tstoreOption := kv.DefaultStoreOption(filepath.Join(s.path, indexParentDir))\n\ts.indexStore, err = newKVStoreFunc(storeOption.Path, storeOption)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.forwardFamily, err = s.indexStore.CreateFamily(\n\t\tforwardIndexDir,\n\t\tkv.FamilyOption{\n\t\t\tCompactThreshold: 0,\n\t\t\tMerger: string(tagindex.SeriesForwardMerger)})\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.invertedFamily, err = s.indexStore.CreateFamily(\n\t\tinvertedIndexDir,\n\t\tkv.FamilyOption{\n\t\t\tCompactThreshold: 0,\n\t\t\tMerger: string(tagindex.SeriesInvertedMerger)})\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.indexDB, err = newIndexDBFunc(\n\t\tcontext.TODO(),\n\t\tfilepath.Join(s.path, metaDir),\n\t\ts.metadata, s.forwardFamily,\n\t\ts.invertedFamily)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewIndex() Index {\n\tnewIndex := Index{}\n\tnewIndex.Setup()\n\treturn newIndex\n}", "func (s *shard) initIndexDatabase() error {\n\tvar err error\n\tstoreOption := kv.DefaultStoreOption(filepath.Join(s.path, indexParentDir))\n\ts.indexStore, err = newKVStoreFunc(storeOption.Path, storeOption)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.forwardFamily, err = s.indexStore.CreateFamily(\n\t\tforwardIndexDir,\n\t\tkv.FamilyOption{\n\t\t\tCompactThreshold: 0,\n\t\t\tMerger: string(invertedindex.SeriesForwardMerger)})\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.invertedFamily, err = s.indexStore.CreateFamily(\n\t\tinvertedIndexDir,\n\t\tkv.FamilyOption{\n\t\t\tCompactThreshold: 0,\n\t\t\tMerger: string(invertedindex.SeriesInvertedMerger)})\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.indexDB, err = newIndexDBFunc(\n\t\tcontext.TODO(),\n\t\tfilepath.Join(s.path, metaDir),\n\t\ts.metadata, s.forwardFamily,\n\t\ts.invertedFamily)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func New(indexRegistry *registry.IndexRegistry, options ...func(*Index)) (I *Index, err error) {\n\tI = &Index{\n\t\tindexRegistry: indexRegistry,\n\t}\n\n\tfor _, option := range options {\n\t\toption(I)\n\t}\n\n\treturn\n}", "func New(path string) (ip *Indexio, err error) {\n\tvar i Indexio\n\t// Initialize functions map for marshaling and unmarshaling\n\tfm := turtleDB.NewFuncsMap(marshal, unmarshal)\n\t// Create new instance of turtleDB\n\tif i.db, err = turtleDB.New(\"indexio\", path, fm); err != nil {\n\t\treturn\n\t}\n\t// Initialize indexes bucket\n\tif err = i.db.Update(initBucket); err != nil {\n\t\treturn\n\t}\n\t// Assign ip as a pointer to i\n\tip = &i\n\treturn\n}", "func New(ds datastore.TxnDatastore, api *apistruct.FullNodeStruct) (*Index, error) {\n\tcs := chainsync.New(api)\n\tstore, err := chainstore.New(txndstr.Wrap(ds, \"chainstore\"), cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinitMetrics()\n\tctx, cancel := context.WithCancel(context.Background())\n\ts := &Index{\n\t\tapi: api,\n\t\tstore: store,\n\t\tsignaler: signaler.New(),\n\t\tindex: IndexSnapshot{\n\t\t\tMiners: make(map[string]Slashes),\n\t\t},\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tfinished: make(chan struct{}),\n\t}\n\tif err := s.loadFromDS(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo s.start()\n\treturn s, nil\n}", "func newQueueIndex(dataDir string) (*queueIndex, error) {\n\tindexFile := path.Join(dataDir, cIndexFileName)\n\tindexArena, err := newArena(indexFile, cIndexFileSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &queueIndex{\n\t\tindexFile: indexFile,\n\t\tindexArena: indexArena,\n\t}, nil\n}", "func NewIndex(kind IndexKind, table string) Index {\n\treturn &index{\n\t\tkind: kind,\n\t\ttable: table,\n\t}\n}", "func NewIndex() *Index {\n\treturn &Index{root: &node{}}\n}", "func NewDb(storeType StoreType, dataDir string) (*Db, error) {\n\n\tvar store *genji.DB\n\tvar err error\n\n\tswitch storeType {\n\tcase StoreTypeMemory:\n\t\tstore, err = genji.Open(\":memory:\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error opening memory store: \", err)\n\t\t}\n\n\tcase StoreTypeBolt:\n\t\tdbFile := path.Join(dataDir, \"data.db\")\n\t\tstore, err = genji.Open(dbFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\tcase StoreTypeBadger:\n\t\tlog.Fatal(\"Badger not currently supported\")\n\t\t/*\n\t\t\t // uncomment the following to enable badger support\n\t\t\t\t// Create a badger engine\n\t\t\t\tdbPath := path.Join(dataDir, \"badger\")\n\t\t\t\tng, err := badgerengine.NewEngine(badger.DefaultOptions(dbPath))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\t// Pass it to genji\n\t\t\t\tstore, err = genji.New(context.Background(), ng)\n\t\t*/\n\n\tdefault:\n\t\tlog.Fatal(\"Unknown store type: \", storeType)\n\t}\n\n\terr = store.Exec(`CREATE TABLE IF NOT EXISTS meta (id INT PRIMARY KEY)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating meta table: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE TABLE IF NOT EXISTS nodes (id TEXT PRIMARY KEY)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating nodes table: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating idx_nodes_type: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE TABLE IF NOT EXISTS edges (id TEXT PRIMARY KEY)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating edges table: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE INDEX IF NOT EXISTS idx_edge_up ON edges(up)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating idx_edge_up: %w\", err)\n\t}\n\n\terr = store.Exec(`CREATE INDEX IF NOT EXISTS idx_edge_down ON edges(down)`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating idx_edge_down: %w\", err)\n\t}\n\n\tdb := &Db{store: store}\n\treturn db, db.initialize()\n}", "func NewDb() *Db { //s interface{}\n\td := &Db{\n\t\tarr: make(Lister, 0, 100),\n\t\tupdate: time.Now().UnixNano(),\n\t}\n\treturn d\n}", "func New(ctx context.Context, ng engine.Engine) (*DB, error) {\n\treturn newDatabase(ctx, ng, database.Options{Codec: msgpack.NewCodec()})\n}", "func New(pg *pg.DB, index Index) *Model {\n\tInitTokenize()\n\treturn &Model{\n\t\tPG: pg,\n\t\tIndex: index,\n\t\tFiles: make(map[string]int),\n\t\tWords: make(map[string]int),\n\t}\n}", "func newIndex(name string) (index *ind) {\n\tindex = new(ind)\n\tindex.name = name\n\tindex.Storage = map[string][]string{}\n\tindex.Domains = map[string]bool{}\n\treturn\n}", "func New(ctx context.Context, dirPath string, opts *Options) (*DB, error) {\n\tvar (\n\t\trepo storage.Repository\n\t\terr error\n\t\tdbCloser io.Closer\n\t)\n\tif opts == nil {\n\t\topts = defaultOptions()\n\t}\n\n\tif opts.Logger == nil {\n\t\topts.Logger = log.Noop\n\t}\n\n\tlock := multex.New()\n\tmetrics := newMetrics()\n\topts.LdbStats.CompareAndSwap(nil, &metrics.LevelDBStats)\n\n\tlocker := func(addr swarm.Address) func() {\n\t\tlock.Lock(addr.ByteString())\n\t\treturn func() {\n\t\t\tlock.Unlock(addr.ByteString())\n\t\t}\n\t}\n\n\tif dirPath == \"\" {\n\t\trepo, dbCloser, err = initInmemRepository(locker)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// only perform migration if not done already\n\t\tif _, err := os.Stat(path.Join(dirPath, indexPath)); err != nil {\n\t\t\terr = performEpochMigration(ctx, dirPath, opts)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\trepo, dbCloser, err = initDiskRepository(ctx, dirPath, locker, opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tsharkyBasePath := \"\"\n\tif dirPath != \"\" {\n\t\tsharkyBasePath = path.Join(dirPath, sharkyPath)\n\t}\n\terr = migration.Migrate(\n\t\trepo.IndexStore(),\n\t\tlocalmigration.AllSteps(sharkyBasePath, sharkyNoOfShards, repo.ChunkStore()),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcacheObj, err := initCache(ctx, opts.CacheCapacity, repo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger := opts.Logger.WithName(loggerName).Register()\n\n\tdb := &DB{\n\t\tmetrics: metrics,\n\t\tlogger: logger,\n\t\tbaseAddr: opts.Address,\n\t\trepo: repo,\n\t\tlock: lock,\n\t\tcacheObj: cacheObj,\n\t\tretrieval: noopRetrieval{},\n\t\tpusherFeed: make(chan *pusher.Op),\n\t\tquit: make(chan struct{}),\n\t\tbgCacheLimiter: make(chan struct{}, 16),\n\t\tdbCloser: dbCloser,\n\t\tbatchstore: opts.Batchstore,\n\t\tvalidStamp: opts.ValidStamp,\n\t\tevents: events.NewSubscriber(),\n\t\treserveBinEvents: events.NewSubscriber(),\n\t\topts: workerOpts{\n\t\t\twarmupDuration: opts.WarmupDuration,\n\t\t\twakeupDuration: opts.ReserveWakeUpDuration,\n\t\t},\n\t\tdirectUploadLimiter: make(chan struct{}, pusher.ConcurrentPushes),\n\t\tinFlight: new(util.WaitingCounter),\n\t}\n\n\tif db.validStamp == nil {\n\t\tdb.validStamp = postage.ValidStamp(db.batchstore)\n\t}\n\n\tif opts.ReserveCapacity > 0 {\n\t\trs, err := reserve.New(\n\t\t\topts.Address,\n\t\t\trepo.IndexStore(),\n\t\t\topts.ReserveCapacity,\n\t\t\topts.RadiusSetter,\n\t\t\tlogger,\n\t\t\tfunc(ctx context.Context, store internal.Storage, addrs ...swarm.Address) error {\n\t\t\t\tdefer func() { db.metrics.CacheSize.Set(float64(db.cacheObj.Size())) }()\n\n\t\t\t\tdb.lock.Lock(cacheAccessLockKey)\n\t\t\t\tdefer db.lock.Unlock(cacheAccessLockKey)\n\n\t\t\t\treturn cacheObj.MoveFromReserve(ctx, store, addrs...)\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdb.reserve = rs\n\n\t\tdb.metrics.StorageRadius.Set(float64(rs.Radius()))\n\t\tdb.metrics.ReserveSize.Set(float64(rs.Size()))\n\t}\n\tdb.metrics.CacheSize.Set(float64(db.cacheObj.Size()))\n\n\t// Cleanup any dirty state in upload and pinning stores, this could happen\n\t// in case of dirty shutdowns\n\terr = errors.Join(\n\t\tupload.CleanupDirty(db),\n\t\tpinstore.CleanupDirty(db),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func dbNew() *DB {\n\treturn &DB{\n\t\tdata: make(map[string]string),\n\t}\n}", "func NewIndexDriver(root string) sql.IndexDriver {\n\treturn NewDriver(root, pilosa.DefaultClient())\n}", "func NewIndex(storage storages.Storage) Index {\n\treturn &multiIndex{index: storage}\n}", "func New(data []byte) *Index {}", "func NewIndex(f *os.File, c Config) (*Index, error) {\n\tidx := &Index{\n\t\tfile: f,\n\t}\n\n\tfi, err := os.Stat(f.Name())\n\tif err != nil {\n\t\treturn nil, lib.Wrap(err, \"Unable to get file stats\")\n\t}\n\n\tidx.size = uint64(fi.Size())\n\tif err = os.Truncate(\n\t\tf.Name(), int64(c.Segment.MaxIndexBytes),\n\t); err != nil {\n\t\treturn nil, lib.Wrap(err, \"Unable to truncate file\")\n\t}\n\n\tif idx.mmap, err = gommap.Map(\n\t\tidx.file.Fd(),\n\t\tgommap.PROT_READ|gommap.PROT_WRITE,\n\t\tgommap.MAP_SHARED,\n\t); err != nil {\n\t\treturn nil, lib.Wrap(err, \"Unable to create gommap map\")\n\t}\n\n\treturn idx, nil\n}", "func CreateIndex(context *web.AppContext) *web.AppError {\n\n\tdb := context.MDB\n\tvar input model.Index\n\tjson.NewDecoder(context.Body).Decode(&input)\n\n\terr := db.Session.DB(\"\").C(input.Target).EnsureIndex(input.Index)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Error creating index [%+v]\", input)\n\t\treturn &web.AppError{err, message, http.StatusInternalServerError}\n\t}\n\n\treturn nil\n}", "func New(data []byte) *Index", "func NewIndexStorage(cfg *config.Storage, dir string, log *logging.Logger) (IndexStorage, error) {\n\tsecure := true\n\tif strings.HasPrefix(cfg.Host, \"localhost\") || strings.HasPrefix(cfg.Host, \"127.0.0.1\") {\n\t\tsecure = false\n\t}\n\n\tclient, err := minio.New(cfg.Host, cfg.Key, cfg.Secret, secure)\n\tif err != nil {\n\t\treturn IndexStorage{}, err\n\t}\n\n\treturn IndexStorage{cfg, dir, client, log.With(\"storage\", cfg.Bucket)}, nil\n}", "func NewIndex(path, name string) (*Index, error) {\n\terr := validateName(name)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"validating name\")\n\t}\n\n\treturn &Index{\n\t\tpath: path,\n\t\tname: name,\n\t\tfields: make(map[string]*Field),\n\n\t\tnewAttrStore: newNopAttrStore,\n\t\tcolumnAttrs: nopStore,\n\n\t\tbroadcaster: NopBroadcaster,\n\t\tStats: stats.NopStatsClient,\n\t\tlogger: logger.NopLogger,\n\t\ttrackExistence: true,\n\t}, nil\n}", "func NewDb(db *sql.DB, driverName string) *DB {\n return &DB{DB: db, driverName: driverName, Mapper: mapper()}\n}", "func NewIndex(physicalID int64, tblInfo *model.TableInfo, indexInfo *model.IndexInfo) table.Index {\n\tindex := &index{\n\t\tidxInfo: indexInfo,\n\t\ttblInfo: tblInfo,\n\t\t// The prefix can't encode from tblInfo.ID, because table partition may change the id to partition id.\n\t\tprefix: tablecodec.EncodeTableIndexPrefix(physicalID, indexInfo.ID),\n\t}\n\treturn index\n}", "func CreateNewIndex(url string, alias string) (string, error) {\n\t// create our day-specific name\n\tphysicalIndex := fmt.Sprintf(\"%s_%s\", alias, time.Now().Format(\"2006_01_02\"))\n\tidx := 0\n\n\t// check if it exists\n\tfor true {\n\t\tresp, err := http.Get(fmt.Sprintf(\"%s/%s\", url, physicalIndex))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t// not found, great, move on\n\t\tif resp.StatusCode == http.StatusNotFound {\n\t\t\tbreak\n\t\t}\n\n\t\t// was found, increase our index and try again\n\t\tidx++\n\t\tphysicalIndex = fmt.Sprintf(\"%s_%s_%d\", alias, time.Now().Format(\"2006_01_02\"), idx)\n\t}\n\n\t// initialize our index\n\tcreateURL := fmt.Sprintf(\"%s/%s\", url, physicalIndex)\n\t_, err := MakeJSONRequest(http.MethodPut, createURL, indexSettings, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// all went well, return our physical index name\n\tlog.WithField(\"index\", physicalIndex).Info(\"created index\")\n\treturn physicalIndex, nil\n}", "func newDbIterator(typeName []byte, it iterator, db *leveldb.DB) (*DbIterator, error) {\n\n\tidx := &DbIterator{typeName: typeName, it: it, db: db}\n\n\treturn idx, nil\n}", "func New(ctx context.Context, ng engine.Engine, opts Options) (*Database, error) {\n\tif opts.Codec == nil {\n\t\treturn nil, errors.New(\"missing codec\")\n\t}\n\n\tdb := Database{\n\t\tng: ng,\n\t\tCodec: opts.Codec,\n\t}\n\n\tntx, err := db.ng.Begin(ctx, engine.TxOptions{\n\t\tWritable: true,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer ntx.Rollback()\n\n\terr = db.initInternalStores(ntx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = ntx.Commit()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &db, nil\n}", "func NewDB() *DB {\n\treturn &DB{}\n}", "func newDatabase(s *Server) *Database {\n\treturn &Database{\n\t\tserver: s,\n\t\tusers: make(map[string]*DBUser),\n\t\tpolicies: make(map[string]*RetentionPolicy),\n\t\tshards: make(map[uint64]*Shard),\n\t\tseries: make(map[string]*Series),\n\t}\n}", "func (d *Driver) Create(\n\tdb, table, id string,\n\texpressions []sql.Expression,\n\tconfig map[string]string,\n) (sql.Index, error) {\n\t_, err := mkdir(d.root, db, table, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif config == nil {\n\t\tconfig = make(map[string]string)\n\t}\n\n\texprs := make([]string, len(expressions))\n\tfor i, e := range expressions {\n\t\texprs[i] = e.String()\n\t}\n\n\tcfg := index.NewConfig(db, table, id, exprs, d.ID(), config)\n\terr = index.WriteConfigFile(d.configFilePath(db, table, id), cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tidx, err := d.newPilosaIndex(db, table)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmapping := newMapping(d.mappingFilePath(db, table, id))\n\tprocessingFile := d.processingFilePath(db, table, id)\n\tif err := index.WriteProcessingFile(\n\t\tprocessingFile,\n\t\t[]byte{processingFileOnCreate},\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newPilosaIndex(idx, mapping, cfg), nil\n}", "func New(config *Config) (Database, error) {\n\tdb, err := connectToDB(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(\"Successfully connected to db\")\n\n\terr = migrateDB(config, db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(\"Successfully ran migrations\")\n\n\tsqlxDB := sqlx.NewDb(db, config.Driver)\n\n\tbaseDB := database{\n\t\tdb: sqlxDB,\n\t}\n\n\treturn &queries{\n\t\tauthorsQueries{baseDB},\n\t\tpostsQueries{baseDB},\n\t}, nil\n}", "func (b backend) New(ctx context.Context, l log.Interface, cfg *config.Config) (persist.Database, error) {\n\tusername, password, host, port, db :=\n\t\tcfg.Database.Postgres.Username,\n\t\tcfg.Database.Postgres.Password,\n\t\tcfg.Database.Postgres.Host,\n\t\tcfg.Database.Postgres.Port,\n\t\tcfg.Database.Postgres.DB\n\n\tconnString := fmt.Sprintf(\n\t\t\"postgres://%s:%s@%s:%d/%s\",\n\t\tusername,\n\t\tpassword,\n\t\thost,\n\t\tport,\n\t\tdb,\n\t)\n\n\tconn, err := pgxpool.Connect(ctx, connString)\n\tif err != nil {\n\t\treturn nil, errwrap.Wrap(err, \"failed to connect to postgres\")\n\t}\n\n\tq := gen.New(conn)\n\n\treturn &database{\n\t\tqueries: q,\n\t}, nil\n}", "func New(db *bolt.DB) *kvq.DB {\n\treturn kvq.NewDB(&DB{db})\n}", "func New(dsn string, maxConn int) dao.DB {\n\treturn &db{\n\t\tDB: open(dsn, maxConn),\n\t}\n}", "func NewIndexBuilder(cfg *Config, g *GitRepo) *IndexBuilder {\n\treturn &IndexBuilder{\n\t\tcfg: cfg,\n\t\tg: g,\n\t\tmetadataCommit: make(commitInfoMap),\n\t}\n}", "func New(tb testing.TB, dir string, ver string, logger func(string)) (*DB, error) {\n\tdb, err := doNew(tb, dir, ver, logger)\n\tif err != nil && tb != nil {\n\t\ttb.Fatal(\"failed initializing database: \", err)\n\t}\n\treturn db, err\n}", "func New(config *connect.Config) Db {\n\tvar db Db\n\t// first find db in dbMap by DatabaseName\n\tdb = dbMap[config.DatabaseName]\n\t// find\n\tif db != nil {\n\t\treturn db\n\t}\n\t// not find in dbMap - New\n\tswitch config.DbType {\n\tcase connect.MONGODB:\n\t\t// init mongodb\n\t\tdb = mongo.New(config)\n\t}\n\tdbMap[config.DatabaseName] = db\n\treturn db\n}", "func NewIndex(name string, columns []string, indexType IndexType) Index {\n\treturn Index{\n\t\tName: name,\n\t\tColumns: columns,\n\t\tType: indexType,\n\t}\n}", "func CreateIndex(excludedPaths []string) (Index, error) {\n\tglog.V(1).Infof(\"CreateIndex(%v)\", excludedPaths)\n\n\tmapping := bleve.NewIndexMapping()\n\tif len(excludedPaths) > 0 {\n\t\tcustomMapping := bleve.NewDocumentMapping()\n\t\tfor _, path := range excludedPaths {\n\t\t\tpaths := strings.Split(path, \".\")\n\t\t\tpathToMapping(paths, customMapping)\n\t\t}\n\t\tmapping.DefaultMapping = customMapping\n\t}\n\tindex, err := bleve.NewMemOnly(mapping)\n\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tbatch := index.NewBatch()\n\n\treturn &bleveIndex{\n\t\tindex: index,\n\t\taddInc: 0,\n\t\tbatch: batch,\n\t}, nil\n}", "func (db *Database) CreateIndex(label, property string) (*Index, error) {\n\turi := join(db.Url, \"schema/index\", label)\n\tpayload := indexRequest{[]string{property}}\n\tresult := Index{db: db}\n\tne := NeoError{}\n\tresp, err := db.Session.Post(uri, payload, &result, &ne)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch resp.Status() {\n\tcase 200:\n\t\treturn &result, nil // Success\n\tcase 405:\n\t\treturn nil, NotAllowed\n\t}\n\treturn nil, ne\n}", "func newDatabase(count int) (*database, error) {\n\tdb, err := sql.Open(\"postgres\", fmt.Sprintf(`host=%s port=%s user=%s\n\t\tpassword=%s dbname=%s sslmode=disable`,\n\t\thost, port, user, password, dbname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := db.Ping(); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"connected to psql client, host: %s\\n\", host)\n\n\treturn &database{\n\t\tdb: db,\n\t\terrChan: make(chan error, count),\n\t}, nil\n}", "func NewIndexBuilder() *IndexBuilder {\n\treturn &IndexBuilder{\n\t\tcontentPostings: make(map[ngram][]uint32),\n\t\tnamePostings: make(map[ngram][]uint32),\n\t\tbranches: make(map[string]int),\n\t}\n}", "func New(data []byte) []*Index {\n\treturn NewWithReader(bytes.NewReader(data))\n}", "func New(size int) *DB {\n\treturn &DB{\n\t\tdocs: make(map[int][]byte, size),\n\t\tall: intset.NewBitSet(0),\n\t}\n}", "func NewIndex(unique bool, columns []Column) *Index {\n\treturn &Index{\n\t\tbtree: btree.NewBTreeG[Doc](func(a, b Doc) bool {\n\t\t\treturn Order(a, b, columns, !unique) < 0\n\t\t}),\n\t}\n}", "func (dbclient *CouchDatabase) CreateNewIndexWithRetry(indexdefinition string, designDoc string) error {\n\t//get the number of retries\n\tmaxRetries := dbclient.CouchInstance.Conf.MaxRetries\n\n\t_, err := retry.Invoke(\n\t\tfunc() (interface{}, error) {\n\t\t\texists, err := dbclient.IndexDesignDocExists(designDoc)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif exists {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\n\t\t\treturn dbclient.CreateIndex(indexdefinition)\n\t\t},\n\t\tretry.WithMaxAttempts(maxRetries),\n\t)\n\treturn err\n}", "func NewIndexed() *Indexed {\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn &Indexed{\n\t\tsize: 0,\n\t}\n}", "func NewIndex(buf string) (*Index, error) {\n\tindex := &Index{}\n\terr := yaml.Unmarshal([]byte(buf), index)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn index, nil\n}", "func (d *Driver) Create(db, table, id string, expressions []sql.Expression, config map[string]string) (sql.Index, error) {\n\t_, err := mkdir(d.root, db, table, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texprs := make([]string, len(expressions))\n\tfor i, e := range expressions {\n\t\texprs[i] = e.String()\n\t}\n\n\tcfg := index.NewConfig(db, table, id, exprs, d.ID(), config)\n\terr = index.WriteConfigFile(d.configFilePath(db, table, id), cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newPilosaIndex(d.mappingFilePath(db, table, id), d.client, cfg), nil\n}", "func NewIndex(mapping IndexMapping, opts ...IndexOption) *Index {\n\tindex := &Index{\n\t\tIndexMapping: mapping,\n\t\tpopulateBatchSize: defaultPopulateBatchSize,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(index)\n\t}\n\n\treturn index\n}", "func newDBStore(db *couchdb.CouchDatabase, dbName string) *dbstore {\n\treturn &dbstore{dbName, db}\n}", "func New(db *sql.DB, maxGatewayCount int) DB {\n\treturn database{\n\t\tdb: db,\n\t\tmaxGatewayCount: maxGatewayCount,\n\t}\n}", "func NewDb() *Db {\n\treturn &Db{\n\t\tmake(map[string]*TitleInfo),\n\t\tmake(map[string]*EpisodeInfo),\n\t\tmake(map[string][]string),\n\t}\n}", "func NewIndex(texts []string, name string) *Index {\n\treturn &Index{texts: texts, name: name}\n}", "func newDB(client *gorm.DB) (*DB, error) {\n\tif client == nil {\n\t\treturn nil, fmt.Errorf(\"Mysql: could not connect\")\n\t}\n\tdb := &DB{\n\t\tclient: client,\n\t}\n\treturn db, nil\n}", "func NewIndex(data []byte) (*Index, error) {\n\tvar i Index\n\tdec := gob.NewDecoder(bytes.NewBuffer(data))\n\tif err := dec.Decode(&i); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &i, nil\n}", "func NewDB(e *entities.DB) *DB {\n\treturn &DB{e: e}\n}", "func NewIndexFile() *IndexFile {\n\treturn &IndexFile{}\n}", "func (s *searcher) CreateIndex() error {\n\tcolor.Cyan(\"[start] initialize index.\")\n\t// get user\n\tuser, reload, err := s.getUser()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[err] createIndex %w\", err)\n\t}\n\n\t// check to whether exist starred items or not.\n\tvar isNewIndex bool\n\tif err := s.db.Update(func(tx *bolt.Tx) error {\n\t\tvar err error\n\t\tbucket := tx.Bucket([]byte(starredBucketName(s.gitToken)))\n\t\tif bucket == nil {\n\t\t\tbucket, err = tx.CreateBucket([]byte(starredBucketName(s.gitToken)))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tisNewIndex = true\n\t\t} else {\n\t\t\tisNewIndex = false\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\tClearAll()\n\t\tcolor.Yellow(\"[err] collapse db file, so delete db file\")\n\t\treturn fmt.Errorf(\"[err] createIndex %w\", err)\n\t}\n\n\t// read old database.\n\tvar oldStarredList []*git.Starred\n\toldStarredMap := map[string]*git.Starred{}\n\tif !isNewIndex {\n\t\t// read old starred from db\n\t\ts.db.View(func(tx *bolt.Tx) error {\n\t\t\tbucket := tx.Bucket([]byte(starredBucketName(s.gitToken)))\n\t\t\tbucket.ForEach(func(k, v []byte) error {\n\t\t\t\tvar starred *git.Starred\n\t\t\t\tif err := json.Unmarshal(v, &starred); err != nil {\n\t\t\t\t\tcolor.Yellow(\"[err] parsing %s\", string(k))\n\t\t\t\t} else {\n\t\t\t\t\toldStarredList = append(oldStarredList, starred)\n\t\t\t\t\toldStarredMap[starred.FullName] = starred\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\n\t\t// write old starred to index\n\t\tfor _, starred := range oldStarredList {\n\t\t\tif err := s.index.Index(starred.FullName, starred); err != nil {\n\t\t\t\tcolor.Yellow(\"[err] indexing %s\", starred.FullName)\n\t\t\t}\n\t\t}\n\t}\n\n\t// are you all ready?\n\tif !reload && !isNewIndex {\n\t\tcount, _ := s.index.DocCount()\n\t\tcolor.Green(\"[success][using cache] %d items\", count)\n\t\treturn nil\n\t}\n\n\t// reload new starred list.\n\tnewStarredList, err := s.git.ListStarredAll()\n\tif err != nil {\n\t\tcolor.Yellow(\"[err] don't getting starred list %s\", err.Error())\n\t\tif !isNewIndex {\n\t\t\tcount, _ := s.index.DocCount()\n\t\t\tcolor.Yellow(\"[fail][using cache] %d items\", count)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"[err] CreateIndex %w\", err)\n\t}\n\tnewStarredMap := map[string]*git.Starred{}\n\tfor _, starred := range newStarredList {\n\t\tnewStarredMap[starred.FullName] = starred\n\t}\n\n\t// update and insert\n\tif isNewIndex {\n\t\tcolor.White(\"[refresh] all repositories\")\n\t\ts.git.SetReadme(newStarredList)\n\t\ts.writeDBAndIndex(newStarredList)\n\t} else {\n\t\t// insert or update starred\n\t\tvar insertList []*git.Starred\n\t\tvar updateList []*git.Starred\n\t\tfor _, newStarred := range newStarredList {\n\t\t\tif oldStarred, ok := oldStarredMap[newStarred.FullName]; !ok {\n\t\t\t\tinsertList = append(insertList, newStarred)\n\t\t\t\tcolor.White(\"[insert] %s repository pushed_at %s\",\n\t\t\t\t\tnewStarred.FullName, newStarred.PushedAt.Format(time.RFC3339))\n\t\t\t} else {\n\t\t\t\tif oldStarred.PushedAt.Unix() != newStarred.PushedAt.Unix() &&\n\t\t\t\t\toldStarred.CachedAt.Unix() < time.Now().Add(-24*7*time.Hour).Unix() { // after 7 days.\n\t\t\t\t\tupdateList = append(updateList, newStarred)\n\t\t\t\t\tcolor.White(\"[update] %s repository pushed_at %s\",\n\t\t\t\t\t\tnewStarred.FullName, newStarred.PushedAt.Format(time.RFC3339))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// insert\n\t\ts.git.SetReadme(insertList)\n\t\ts.writeDBAndIndex(insertList)\n\n\t\t// update\n\t\ts.git.SetReadme(updateList)\n\t\ts.writeDBAndIndex(updateList)\n\n\t\t// delete starred\n\t\tvar deleteList []*git.Starred\n\t\tfor _, oldStarred := range oldStarredList {\n\t\t\tif _, ok := newStarredMap[oldStarred.FullName]; !ok {\n\t\t\t\tdeleteList = append(deleteList, oldStarred)\n\t\t\t\tcolor.White(\"[delete] %s repository pushed_at %s\",\n\t\t\t\t\toldStarred.FullName, oldStarred.PushedAt.Format(time.RFC3339))\n\t\t\t}\n\t\t}\n\t\t// delete\n\t\ts.deleteDBAndIndex(deleteList)\n\t}\n\n\t// rewrite a user to db\n\tuserData, err := json.Marshal(user)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[err] createIndex %w\", err)\n\t}\n\ts.db.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(userBucketName))\n\t\tbucket.Put([]byte(s.gitToken), userData)\n\t\treturn nil\n\t})\n\n\tcount, _ := s.index.DocCount()\n\tcolor.Green(\"[success][new reload] %d items\", count)\n\treturn nil\n}", "func newDatabase(info extraInfo, db *sql.DB) *database {\n\treturn &database{\n\t\tname: info.dbName,\n\t\tdriverName: info.driverName,\n\t\tdb: db,\n\t}\n}", "func New(metainfo *Client, encStore *encryption.Store) *DB {\n\treturn &DB{\n\t\tmetainfo: metainfo,\n\t\tencStore: encStore,\n\t}\n}", "func New(config *config.ServerConfig, html *render.HTML) http.Handler {\n\treturn &indexController{config, html}\n}", "func (b Factory) New(ctx context.Context, name string, l log.Interface, cfg *config.Config) (Database, error) {\n\tbackend, ok := b[name]\n\tif !ok {\n\t\treturn nil, errwrap.Wrap(ErrDatabaseNotFound, name)\n\t}\n\n\tdb, err := backend.New(ctx, l, cfg)\n\n\treturn db, errwrap.Wrap(err, \"failed to create backend\")\n}", "func New(dl logbook.Logbook, databaseName string) (*Database, error) {\n\tdb := &Database{\n\t\tDlog: dl,\n\t}\n\n\t// Check if data folder exists\n\t_, err := os.Stat(config.DBFolder)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\t// If folder does not exist, create it\n\t\t\terr := os.Mkdir(config.DBFolder, 0777)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(\"error\")\n\t\t\t}\n\t\t}\n\t}\n\n\terr = os.Chdir(config.DBFolder)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, errors.New(\"error\")\n\t}\n\n\tf, err := os.Create(databaseName)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, errors.New(\"error\")\n\t}\n\n\tdefer f.Close()\n\n\tdb.DatabaseName = databaseName\n\tdb.Version = 001\n\tdb.File = f\n\tdb.Data = map[string][]byte{}\n\n\twr := bufio.NewWriter(f)\n\n\t_, err = fmt.Fprintf(wr, \"DolceDB.%d\", config.DBVersion)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\twr.Flush()\n\n\terr = db.RebuildMap()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func New(cfg config.DB) (*gorm.DB, error) {\n\tdb, err := database.New(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := db.AutoMigrate(\n\t\trepository.Client{},\n\t\trepository.Deal{},\n\t\trepository.Position{},\n\t\trepository.OHLCV{},\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func CreateDB(path string, nbuckets uint32) (*Database,error){\r\n\tdb,err := godbm.Create(path,nbuckets)\r\n\treturn &Database{DB:db},err\r\n}", "func New(path string) (*DB, error) {\n\tdb, err := bolt.Open(path, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\treturn &DB{Bolt: db}, err\n}", "func CreateBleveIndex(indexPath string, forceCreate, allowAppend bool) (bleve.Index, error) {\n\t// Create a new index.\n\tmapping := bleve.NewIndexMapping()\n\tindex, err := bleve.New(indexPath, mapping)\n\tif err == bleve.ErrorIndexPathExists {\n\t\tcommon.Log.Error(\"Bleve index %q exists.\", indexPath)\n\t\tif forceCreate {\n\t\t\tcommon.Log.Info(\"Removing %q.\", indexPath)\n\t\t\tremoveIndex(indexPath)\n\t\t\tindex, err = bleve.New(indexPath, mapping)\n\t\t} else if allowAppend {\n\t\t\tcommon.Log.Info(\"Opening existing %q.\", indexPath)\n\t\t\tindex, err = bleve.Open(indexPath)\n\t\t}\n\t}\n\treturn index, err\n}", "func NewMainDataIndex() (*DataIndex, error) {\n\tif mainDataIndex != nil {\n\t\treturn mainDataIndex, nil\n\t}\n\n\ti := &DataIndex{Name: mainIndexName}\n\terr := error(nil)\n\n\ti.Http, err = NewHttpClient(i.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ti.BlobStore, err = NewS3Store(\"datadex.archives\", i)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmainDataIndex = i\n\treturn mainDataIndex, nil\n}", "func NewIndexConnection(context Context) *IndexConnection {\n\tsize := context.GetScanCap()\n\tif size <= 0 {\n\t\tsize = _ENTRY_CAP\n\t}\n\n\trv := &IndexConnection{\n\t\tcontext: context,\n\t}\n\tnewEntryExchange(&rv.sender, size)\n\treturn rv\n}", "func NewSimpleDB() *SimpleDB {\n\tindex := make(map[string]int64)\n\treturn &SimpleDB{\n\t\tindex: index,\n\t}\n}", "func CreateNew(dbFile, feeXPub string) error {\n\tlog.Infof(\"Initializing new database at %s\", dbFile)\n\n\tdb, err := bolt.Open(dbFile, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to open db file: %w\", err)\n\t}\n\n\tdefer db.Close()\n\n\t// Create all storage buckets of the VSP if they don't already exist.\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t// Create parent bucket.\n\t\tvspBkt, err := tx.CreateBucket(vspBktK)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %s bucket: %w\", string(vspBktK), err)\n\t\t}\n\n\t\t// Initialize with initial database version (1).\n\t\terr = vspBkt.Put(versionK, uint32ToBytes(initialVersion))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Info(\"Generating ed25519 signing key\")\n\n\t\t// Generate ed25519 key\n\t\t_, signKey, err := ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to generate signing key: %w\", err)\n\t\t}\n\t\terr = vspBkt.Put(privateKeyK, signKey.Seed())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Generate a secret key for initializing the cookie store.\n\t\tlog.Info(\"Generating cookie secret\")\n\t\tsecret := make([]byte, 32)\n\t\t_, err = rand.Read(secret)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = vspBkt.Put(cookieSecretK, secret)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Info(\"Storing extended public key\")\n\t\t// Store fee xpub\n\t\terr = vspBkt.Put(feeXPubK, []byte(feeXPub))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Create ticket bucket.\n\t\t_, err = vspBkt.CreateBucket(ticketBktK)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %s bucket: %w\", string(ticketBktK), err)\n\t\t}\n\n\t\t// Create vote change bucket.\n\t\t_, err = vspBkt.CreateBucket(voteChangeBktK)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %s bucket: %w\", string(voteChangeBktK), err)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(\"Database initialized\")\n\n\treturn nil\n}", "func (fact FileFactory) CreateDB(ctx context.Context, nbf *types.NomsBinFormat, urlObj *url.URL, params map[string]interface{}) (datas.Database, types.ValueReadWriter, tree.NodeStore, error) {\n\tsingletonLock.Lock()\n\tdefer singletonLock.Unlock()\n\n\tif s, ok := singletons[urlObj.Path]; ok {\n\t\treturn s.ddb, s.vrw, s.ns, nil\n\t}\n\n\tpath, err := url.PathUnescape(urlObj.Path)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tpath = filepath.FromSlash(path)\n\tpath = urlObj.Host + path\n\n\terr = validateDir(path)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tvar useJournal bool\n\tif params != nil {\n\t\t_, useJournal = params[ChunkJournalParam]\n\t}\n\n\tvar newGenSt *nbs.NomsBlockStore\n\tq := nbs.NewUnlimitedMemQuotaProvider()\n\tif useJournal && chunkJournalFeatureFlag {\n\t\tnewGenSt, err = nbs.NewLocalJournalingStore(ctx, nbf.VersionString(), path, q)\n\t} else {\n\t\tnewGenSt, err = nbs.NewLocalStore(ctx, nbf.VersionString(), path, defaultMemTableSize, q)\n\t}\n\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\toldgenPath := filepath.Join(path, \"oldgen\")\n\terr = validateDir(oldgenPath)\n\tif err != nil {\n\t\tif !errors.Is(err, os.ErrNotExist) {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\terr = os.Mkdir(oldgenPath, os.ModePerm)\n\t\tif err != nil && !errors.Is(err, os.ErrExist) {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t}\n\n\toldGenSt, err := nbs.NewLocalStore(ctx, newGenSt.Version(), oldgenPath, defaultMemTableSize, q)\n\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tst := nbs.NewGenerationalCS(oldGenSt, newGenSt)\n\t// metrics?\n\n\tvrw := types.NewValueStore(st)\n\tns := tree.NewNodeStore(st)\n\tddb := datas.NewTypesDatabase(vrw, ns)\n\n\tsingletons[urlObj.Path] = singletonDB{\n\t\tddb: ddb,\n\t\tvrw: vrw,\n\t\tns: ns,\n\t}\n\n\treturn ddb, vrw, ns, nil\n}", "func NewLogIndex() indices.Index { return &logIndex{} }", "func InitDB(db *mgo.Database) {\n\tfor i := range workIndexes {\n\t\terr := db.C(workIndexes[i].Name).EnsureIndex(workIndexes[i].Index)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t}\n}", "func newDBStore(db *leveldbhelper.DBHandle, dbName string) *store {\n\treturn &store{db, dbName}\n}", "func (i *IndexedDB) Open(\n\tctx context.Context,\n\tname string,\n\tversion int,\n\tupgrader func(d *DatabaseUpdate, oldVersion, newVersion int) error,\n) (*Database, error) {\n\tvar db *Database\n\terrCh := make(chan error, 1)\n\tputErr := func(err error) {\n\t\tselect {\n\t\tcase errCh <- err:\n\t\tdefault:\n\t\t}\n\t}\n\todbReq := i.val.Call(\"open\", name, version)\n\todbReq.Set(\"onupgradeneeded\", js.FuncOf(\n\t\tfunc(th js.Value, dats []js.Value) interface{} {\n\t\t\tevent := dats[0]\n\t\t\t// event is an IDBVersionChangeEvent\n\t\t\toldVersion := event.Get(\"oldVersion\").Int()\n\t\t\tnewVersion := event.Get(\"newVersion\").Int()\n\t\t\tdb = &Database{val: event.Get(\"target\").Get(\"result\")}\n\t\t\tif err := upgrader(&DatabaseUpdate{Database: db}, oldVersion, newVersion); err != nil {\n\t\t\t\tputErr(err)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t))\n\todbReq.Set(\"onerror\", js.FuncOf(\n\t\tfunc(th js.Value, dats []js.Value) interface{} {\n\t\t\to := dats[0]\n\t\t\tgo putErr(errors.New(o.\n\t\t\t\tGet(\"target\").\n\t\t\t\tGet(\"error\").\n\t\t\t\tGet(\"message\").\n\t\t\t\tString(),\n\t\t\t))\n\t\t\treturn nil\n\t\t},\n\t))\n\todbReq.Set(\"onsuccess\", js.FuncOf(\n\t\tfunc(th js.Value, dats []js.Value) interface{} {\n\t\t\to := dats[0]\n\t\t\tif db == nil {\n\t\t\t\tdb = NewDatabase(o.Get(\"target\").Get(\"result\"))\n\t\t\t}\n\t\t\tgo putErr(nil)\n\t\t\treturn nil\n\t\t},\n\t))\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\tcase err := <-errCh:\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn db, nil\n}", "func New(db *sql.DB) *Database {\n\treturn &Database{\n\t\tdb: db,\n\t}\n}", "func New(db *sql.DB) *Database {\n\treturn &Database{\n\t\tdb: db,\n\t}\n}", "func NewIndexFile() *IndexFile {\n\treturn &IndexFile{\n\t\tAPIVersion: APIVersionV1,\n\t\tGenerated: time.Now(),\n\t\tEntries: map[string]VersionedBundle{},\n\t\tPublicKeys: []string{},\n\t}\n}", "func newIndexWithTempPath(name string) *Index {\n\tpath, err := ioutil.TempDir(\"\", \"pilosa-index-\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tindex, err := NewIndex(path, name)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn index\n}", "func New(cfg config.Config, log *logrus.Logger) error {\n\tvar tpl bytes.Buffer\n\tvars := map[string]interface{}{\n\t\t\"typename\": getTypeName(cfg.Repository.URL),\n\t}\n\n\tindexMappingTemplate, _ := template.New(\"geo_mapping\").Parse(`{\n\t\t\"mappings\": {\n\t\t\t\"{{ .typename }}\": {\n\t\t\t\t\"properties\": {\n\t\t\t\t\t\"geometry\": {\n\t\t\t\t\t\t\"type\": \"geo_shape\"\n\t\t\t\t\t},\n \"collection\": {\n \"type\": \"text\",\n \"fielddata\": true\n }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}`)\n\n\tindexMappingTemplate.Execute(&tpl, vars)\n\n\tctx := context.Background()\n\n\tclient, err := createClient(&cfg.Repository)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tindexName := getIndexName(cfg.Repository.URL)\n\n\tcreateIndex, err := client.CreateIndex(indexName).Body(tpl.String()).Do(ctx)\n\tif err != nil {\n\t\terrorText := fmt.Sprintf(\"Cannot create repository: %v\\n\", err)\n\t\tlog.Errorf(errorText)\n\t\treturn errors.New(errorText)\n\t}\n\tif !createIndex.Acknowledged {\n\t\treturn errors.New(\"CreateIndex was not acknowledged. Check that timeout value is correct.\")\n\t}\n\n\tlog.Debug(\"Creating Repository\" + cfg.Repository.URL)\n\tlog.Debug(\"Type: \" + cfg.Repository.Type)\n\tlog.Debug(\"URL: \" + cfg.Repository.URL)\n\n\treturn nil\n}", "func NewDb(context Context) Db {\n\treturn &dbImpl{\n\t\tcontext: context,\n\t}\n}", "func createNewDB(log *logrus.Entry, cnf *Config) error {\n\tvar err error\n\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable\",\n\t\tcnf.DBHost, cnf.DBPort, cnf.DBUser, cnf.DBPassword, cnf.DBName)\n\n\tdb, err = sql.Open(\"postgres\", psqlInfo)\n\n\tif err != nil {\n\t\tlog.WithError(err).Fatalf(\"Failed to connect to db\")\n\t}\n\n\t//try to ping the db\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.WithError(err).Fatalf(\"Failed to ping db\")\n\t}\n\n\tif err = helpers.MigrateDB(db, cnf.SQLMigrationDir); err != nil {\n\t\treturn err\n\t}\n\n\tboil.SetDB(db)\n\n\treturn nil\n}", "func MakeIndex() error {\n\n\treturn nil\n}", "func New(db *sql.DB) *Database {\n\treturn &Database{\n\t\tUsers: users.New(db),\n\t\tSessions: sessions.New(db),\n\t\tWorkouts: workouts.New(db),\n\t\tExercises: exercises.New(db),\n\t}\n}", "func NewDB(filename string) (*DB, error) {\n\tdb, err := bbolt.Open(filename, 0600, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DB{db: db}, nil\n}", "func NewDB(filename string) (*DB, error) {\n\tdb, err := bbolt.Open(filename, 0600, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DB{db: db}, nil\n}", "func NewDB(conf *Config) (db *DB, err error) {\n\tdb = new(DB)\n\tdb.DB, err = sql.Open(\"postgres\", conf.OpenDBURL())\n\t// TODO (kostyarin): configure db: max idle, max open, lifetime, etc\n\t// using hardcoded values, or keeping the values in\n\t// the Config\n\treturn\n}", "func NewDB(now string) *DB {\n\treturn &DB{\n\t\tmeasurements: make(map[string]*Measurement),\n\t\tseries: make(map[uint32]*Series),\n\t\tNow: mustParseTime(now),\n\t}\n}", "func NewDB() *DB {\n\td := new(DB)\n\td.Init()\n\treturn d\n}" ]
[ "0.7321358", "0.7077958", "0.6995988", "0.695568", "0.68397", "0.6816478", "0.6716526", "0.6652811", "0.664919", "0.66478133", "0.6618617", "0.65940624", "0.65865254", "0.6480771", "0.64426786", "0.64285284", "0.6395965", "0.6346326", "0.6320402", "0.6302338", "0.6245616", "0.6229138", "0.6229036", "0.6227165", "0.6216742", "0.62113667", "0.62079114", "0.61823666", "0.61355436", "0.6129097", "0.6122665", "0.6116569", "0.6085264", "0.6084873", "0.6073171", "0.60626656", "0.6062655", "0.6054751", "0.6035376", "0.60221463", "0.60142946", "0.6013382", "0.6008504", "0.6005906", "0.60041696", "0.598034", "0.5979987", "0.59794205", "0.59765387", "0.59749043", "0.59669274", "0.5958867", "0.5944028", "0.5937026", "0.5934278", "0.59282666", "0.5928084", "0.5923825", "0.5922406", "0.59070027", "0.5904967", "0.5895931", "0.589264", "0.58860415", "0.58817416", "0.5878981", "0.58744156", "0.5870218", "0.58676565", "0.58663297", "0.58654636", "0.58592546", "0.58508784", "0.5846602", "0.5836341", "0.5830796", "0.5826649", "0.5826275", "0.5825539", "0.58185136", "0.5812588", "0.5812295", "0.58083177", "0.57965535", "0.5793704", "0.5791699", "0.57855976", "0.57855976", "0.5776348", "0.5771741", "0.5768051", "0.57653564", "0.5762999", "0.5758795", "0.57551694", "0.57548374", "0.57548374", "0.5750265", "0.57494247", "0.57161283" ]
0.7238606
1
SetIndex adds a bucket with provided pulseNumber and ID
func (i *IndexDB) SetIndex(ctx context.Context, pn insolar.PulseNumber, bucket record.Index) error { i.lock.Lock() defer i.lock.Unlock() err := i.setBucket(pn, bucket.ObjID, &bucket) if err != nil { return err } stats.Record(ctx, statIndexesAddedCount.M(1)) inslogger.FromContext(ctx).Debugf("[SetIndex] bucket for obj - %v was set successfully. Pulse: %d", bucket.ObjID.DebugString(), pn) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i *IndexDB) ForID(ctx context.Context, pn insolar.PulseNumber, objID insolar.ID) (record.Index, error) {\n\tvar buck *record.Index\n\tbuck, err := i.getBucket(pn, objID)\n\tif err == ErrIndexNotFound {\n\t\tlastPN, err := i.getLastKnownPN(objID)\n\t\tif err != nil {\n\t\t\treturn record.Index{}, ErrIndexNotFound\n\t\t}\n\n\t\tbuck, err = i.getBucket(lastPN, objID)\n\t\tif err != nil {\n\t\t\treturn record.Index{}, err\n\t\t}\n\t} else if err != nil {\n\t\treturn record.Index{}, err\n\t}\n\n\treturn *buck, nil\n}", "func poolSetIndex(a interface{}, i int) {\n\ta.(*freeClientPoolEntry).index = i\n}", "func (i *indexerGCV) Set(key gcvKey, val gcvVal) {\r\n\ti.Lock()\r\n\ti.idxr[key] = append(i.idxr[key], val)\r\n\ti.Unlock()\r\n}", "func bucketIndex(index int) int {\n\treturn (MaxRoutingTableSize - 1) - index\n}", "func (n Nodes) SetIndex(i int, node *Node)", "func (d *OneToOne) Set(data GenericDataType) {\n\tidx := d.writeIndex % uint64(len(d.buffer))\n\n\tnewBucket := &bucket{\n\t\tdata: data,\n\t\tseq: d.writeIndex,\n\t}\n\td.writeIndex++\n\n\tatomic.StorePointer(&d.buffer[idx], unsafe.Pointer(newBucket))\n}", "func (m *IndexBucketModifierMock) SetBucket(p context.Context, p1 insolar.PulseNumber, p2 IndexBucket) (r error) {\n\tcounter := atomic.AddUint64(&m.SetBucketPreCounter, 1)\n\tdefer atomic.AddUint64(&m.SetBucketCounter, 1)\n\n\tif len(m.SetBucketMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.SetBucketMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to IndexBucketModifierMock.SetBucket. %v %v %v\", p, p1, p2)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.SetBucketMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, IndexBucketModifierMockSetBucketInput{p, p1, p2}, \"IndexBucketModifier.SetBucket got unexpected parameters\")\n\n\t\tresult := m.SetBucketMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the IndexBucketModifierMock.SetBucket\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.SetBucketMock.mainExpectation != nil {\n\n\t\tinput := m.SetBucketMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, IndexBucketModifierMockSetBucketInput{p, p1, p2}, \"IndexBucketModifier.SetBucket got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.SetBucketMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the IndexBucketModifierMock.SetBucket\")\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.SetBucketFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to IndexBucketModifierMock.SetBucket. %v %v %v\", p, p1, p2)\n\t\treturn\n\t}\n\n\treturn m.SetBucketFunc(p, p1, p2)\n}", "func SetBucketNum(n uint) Setting {\n\treturn func(cf *fetcherSetting) {\n\t\tcf.bucketNum = n\n\t}\n}", "func indexWrite(key string, p *pkg) {\n\tlocker.Lock()\n\tdefer locker.Unlock()\n\n\tindexedPkgs[key] = p\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 (d *DrainableStan) add(id string) {\n\tdefer d.m.Unlock()\n\n\td.m.Lock()\n\tif d.bucket == nil {\n\t\td.bucket = map[string]struct{}{}\n\t}\n\td.bucket[id] = struct{}{}\n}", "func WithBucketNum(num int) Setter {\n\treturn func(c *Cache) error {\n\t\tc.BucketNum = num\n\t\treturn nil\n\t}\n}", "func (rs *Restake) BucketIndex() uint64 { return rs.bucketIndex }", "func (self *SinglePad) SetIndexA(member int) {\n self.Object.Set(\"index\", member)\n}", "func (rt RouteTable) SetBucketTimestamp(id string, now time.Time) error {\n\ti, err := strconv.Atoi(id)\n\tif err != nil {\n\t\treturn NodeErr.New(\"unable to convert id to int\")\n\t}\n\n\trt.ht.SetBucketTime(i, now)\n\n\treturn nil\n}", "func NewBucket(tokens uint64) *Bucket {\n\treturn &Bucket{Added: float64(tokens)}\n}", "func (ds *DepositToStake) BucketIndex() uint64 { return ds.bucketIndex }", "func (m KeyedSamples) Add(index int64, t time.Duration) {\n\tkey := fmt.Sprintf(\"%010d\", index) // Easiest way to have samples show up in sorted order in the json.\n\tms, found := m[key]\n\tif !found {\n\t\tms = new(Multisample)\n\t\tm[key] = ms\n\t}\n\tms.Add(t)\n}", "func (sa *SnapshotArray) Set(index int, val int) {\n\tsa.current[index] = val\n}", "func (m *mIndexBucketModifierMockSetBucket) Set(f func(p context.Context, p1 insolar.PulseNumber, p2 IndexBucket) (r error)) *IndexBucketModifierMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.SetBucketFunc = f\n\treturn m.mock\n}", "func (m *Planner) SetBuckets(value []PlannerBucketable)() {\n m.buckets = value\n}", "func (_Abi *AbiCaller) GuardianSetIndex(opts *bind.CallOpts) (uint32, error) {\n\tvar out []interface{}\n\terr := _Abi.contract.Call(opts, &out, \"guardian_set_index\")\n\n\tif err != nil {\n\t\treturn *new(uint32), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(uint32)).(*uint32)\n\n\treturn out0, err\n\n}", "func Put(stub shim.ChaincodeStubInterface, object interface{}, indexStr string, id string) (error) {\n\t// append the id to the array of indexes\n\tlogger.Debugf(\"Storing %v %v\", indexStr, id)\n\n\t_, err := append_id(stub, indexStr, id, true)\n\n\tif err != nil { return errors.Wrap(err, \"Error appending new id \"+id+\" to \"+indexStr) }\n\tlogger.Debugf(\"Id %v appended to index: %v\", id, indexStr)\n\n\t// Store the object on the blockchain\n\titem, err := json.Marshal(object)\n\terr = stub.PutState(id, item)\n\tif err != nil { return errors.Wrap(err, \"Error putting data into ledger\") } // TODO: (determine) is there a rollback of the append_id if this happens?\n\n\tlogger.Infof(\"Created %v %v\", reflect.TypeOf(object), id)\n\n\treturn nil\n}", "func (self *Graphics) SetChildIndex(child *DisplayObject, index int) {\n self.Object.Call(\"setChildIndex\", child, index)\n}", "func (ms HistogramBucketExemplar) SetValue(v float64) {\n\t(*ms.orig).Value = v\n}", "func (db *DB) Set(key string, val []byte, bucket ...string) error {\n\treturn db.Update(func(tx *Tx) error {\n\t\tb := tx.tmpBucket\n\t\tfor _, bn := range bucket {\n\t\t\tb = b.Bucket(bn)\n\t\t}\n\t\tb.Set(key, val)\n\t\treturn nil\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 (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 (this *SnapshotArray) Set(index int, val int) {\n\tif len(this.arr[index]) < this.snapId+1 {\n\t\tfor len(this.arr[index]) < this.snapId+1 {\n\t\t\tthis.arr[index] = append(this.arr[index], this.arr[index][len(this.arr[index])-1])\n\t\t}\n\t}\n\tthis.arr[index][this.snapId] = val\n}", "func (t *BenchmarkerChaincode) updateIndex(stub shim.ChaincodeStubInterface, key, indexName string, indexValueSpace [][]string) error {\n\tif indexName == \"\" {\n\t\treturn nil\n\t}\n\n\tvar indexValues []string\n\tfor _, validValues := range indexValueSpace {\n\t\tchoice := rand.Intn(len(validValues))\n\t\tindexValues = append(indexValues, validValues[choice])\n\t}\n\n\tindexKey, err := stub.CreateCompositeKey(indexName+\"~id\", append(indexValues, key))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalue := []byte{0x00}\n\tif err := stub.PutState(indexKey, value); err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Set composite key '%s' to '%s' for key '%s'\\n\", indexKey, value, key)\n\n\treturn nil\n}", "func (item *queueItem) setIndexState(state indexState) {\n\tif state == item.indexState {\n\t\treturn\n\t}\n\tif item.indexState != \"\" {\n\t\tmetricIndexState.WithLabelValues(string(item.indexState)).Dec()\n\t}\n\titem.indexState = state\n\tif item.indexState != \"\" {\n\t\tmetricIndexState.WithLabelValues(string(item.indexState)).Inc()\n\t}\n}", "func (bl *lfList) bucketValue(b int) int {\n return int(atomic.LoadInt32(&bl.b[b]))\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 (ix *IndexedBucket) initBuckets() error {\n\treturn ix.DB.Update(func(tx *bolt.Tx) error {\n\t\t// Create the main bucket if it does not exist.\n\t\tif _, err := tx.CreateBucketIfNotExists(ix.mainBucket); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar removeIndices util.StringSet = nil\n\t\tvar addIndices util.StringSet = nil\n\n\t\t// Get the metadata bucket and load the meta data.\n\t\tmetaBucketName := []byte(META_DATA_BUCKET_PREFIX + string(ix.mainBucket))\n\t\tcodec := util.JSONCodec(&metaData{})\n\t\tbucket := tx.Bucket(metaBucketName)\n\t\tvar err error\n\n\t\t// If the bucket doesn't exist or is empty, we create all indices.\n\t\tif bucket == nil {\n\t\t\tif bucket, err = tx.CreateBucket(metaBucketName); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taddIndices = ix.indices\n\t\t} else if metaBytes := bucket.Get([]byte(META_DATA_KEY)); metaBytes == nil {\n\t\t\taddIndices = ix.indices\n\t\t} else {\n\t\t\t// deserialize the meta data.\n\t\t\tiMeta, err := codec.Decode(metaBytes)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmetaRec := iMeta.(*metaData)\n\n\t\t\t// Find the indices that need to be added or removed.\n\t\t\texistingIndices := util.NewStringSet(metaRec.Indices)\n\t\t\taddIndices = ix.indices.Complement(existingIndices)\n\t\t\tremoveIndices = existingIndices.Complement(ix.indices)\n\t\t}\n\n\t\t// Delete all unnecessary indices.\n\t\tfor idxName := range removeIndices {\n\t\t\tif err := tx.DeleteBucket([]byte(idxName)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// Add the necessary indices.\n\t\tif len(addIndices) > 0 {\n\t\t\tif err := ix.buildIndices(tx, addIndices); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// Write the meta data.\n\t\tmetaRec := &metaData{Version: 1, Indices: ix.indices.Keys()}\n\t\tmetaBytes, err := codec.Encode(metaRec)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn bucket.Put([]byte(META_DATA_KEY), metaBytes)\n\t})\n}", "func (b *Bucket) SetSequence(v uint64) error {\n return b.bucket.SetSequence(v)\n}", "func addIndexOp(bucket *bolt.Bucket, k []byte) error {\n\treturn bucket.Put(k, []byte{})\n}", "func (tx *Tx) AddBucket(reportID string, b *Bucket) (string, error) {\n\tlog.Printf(\"Adding bucket %s under reportID: %s\", b.Bucketname, reportID)\n\tconst sqlCreateBucket = `\n\tINSERT INTO bucket (\n\t\treport_id,\n\t\tbucketname,\n\t\tregion,\n\t\treport_path,\n\t\taws_access_key_id,\n\t\taws_secret_access_key\n\t) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id;`\n\tvar id string\n\terr := tx.QueryRow(sqlCreateBucket, reportID, b.Bucketname, b.Region, b.ReportPath, b.AWSAccessKeyID, b.AWSSecretAccessKey).Scan(&id)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"unique_s3path\") {\n\t\t\treturn \"\", errors.Errorf(errors.CodeBadRequest, \"Bucket '%s' with report path '%s' already configured\", b.Bucketname, b.ReportPath)\n\t\t}\n\t\treturn \"\", errors.InternalError(err)\n\t}\n\terr = tx.UpdateUserReportMtime(reportID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tlog.Printf(\"Added bucket %s/%s (bucket_id: %s) to report %s\", b.Bucketname, b.ReportPath, id, reportID)\n\treturn id, nil\n}", "func (b *Bitset) Add(index uint) {\n\tb.BS.Set(index)\n}", "func (bd BoltDB) Set(bucket, key string, value []byte) error {\n\treturn bd.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bucket))\n\t\treturn b.Put([]byte(key), value)\n\t})\n}", "func (idx *MultiIndex) Add(indexValue int, key uint64) {\n\t// check that exists\n\titem := idx.Tree.Get(&MultiItem{\n\t\tIdxValue: indexValue,\n\t})\n\n\tvar it *MultiItem = nil\n\n\tif item == nil {\n\t\titem := &MultiItem{\n\t\t\tKeys: make([]int, 0),\n\t\t\tIdxValue: indexValue,\n\t\t\tTree: btree.New(byFlatVal),\n\t\t}\n\t\tidx.Tree.Set(item)\n\t\tit = item\n\t} else {\n\t\tit = item.(*MultiItem)\n\t}\n\n\tit.Keys = append(it.Keys, int(key))\n\tit.Tree.Set(int(key))\n}", "func (r *RoutingTable) MarkBucketRefreshed(idx int) {\n\tr.mutex.Lock()\n\tdefer r.mutex.Unlock()\n\n\tif idx > len(r.refresh)-1 {\n\t\treturn\n\t}\n\tr.refresh[idx] = time.Now()\n}", "func (self *Graphics) SetChildIndexI(args ...interface{}) {\n self.Object.Call(\"setChildIndex\", args)\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 (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 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 (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 (bitmap *bitmap) Set(index int) {\n\tbitmap.set(index, 1)\n}", "func (tx *Tx) SetBucket(name string, mFn MarshalFn, uFn UnmarshalFn) *Bucket {\n\tif mFn == nil {\n\t\tmFn = tx.db.opts.DefaultMarshalFn\n\t}\n\tif uFn == nil {\n\t\tuFn = tx.db.opts.DefaultUnmarshalFn\n\t}\n\n\tb, ok := tx.buckets[name]\n\tif ok {\n\t\tgoto RET\n\t}\n\n\ttx.db.m.Lock()\n\tif b = tx.db.buckets[name]; b == nil {\n\t\ttx.action(backend.ActionCreateBucket, name, \"\", nil)\n\t\tb = newBucket(name, mFn, uFn)\n\t\ttx.db.buckets[name] = b\n\t}\n\tb.m.Lock()\n\ttx.db.m.Unlock()\n\tb.tx = tx\n\ttx.buckets[name] = b\n\nRET:\n\tb.mFn, b.uFn = mFn, uFn\n\treturn b\n}", "func (h *Hash) Store(key string, value int) {\n\n\t// For the specified key, identify what bucket in\n\t// the slice we need to store the key/value inside of.\n\tidx := h.hashKey(key)\n\n\t// Extract a copy of the bucket from the hash table.\n\tbucket := h.buckets[idx]\n\t// Iterate over the indexes for the specified bucket.\n\tfor idx := range bucket {\n\n\t\t// Compare the keys and if there is a match replace the\n\t\t// existing entry value for the new value.\n\t\tif bucket[idx].key == key {\n\t\t\tbucket[idx].value = value\n\t\t\treturn\n\t\t}\n\t}\n\n\t// This key does not exist, so add this new value.\n\th.buckets[idx] = append(bucket, entry{key, value})\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 (tk *timekeeper) changeIndexStateForBucket(bucket string, state common.IndexState) {\n\n\t//for all indexes in this bucket, change the state\n\tfor _, buildInfo := range tk.indexBuildInfo {\n\n\t\tif buildInfo.indexInst.Defn.Bucket == bucket {\n\n\t\t\tbuildInfo.indexInst.State = state\n\t\t}\n\t}\n\n}", "func (m *SearchBucket) SetCount(value *int32)() {\n m.count = value\n}", "func (s *Series) Insert(t time.Time, value float64) {\n\tb := &Bucket{s.floor(t), value}\n\tidx := s.index(b.T)\n\ts.buckets[idx] = b\n}", "func (q *Queue) SetIndexed(repoName string, opts IndexOptions, state indexState) {\n\tq.mu.Lock()\n\titem := q.get(repoName)\n\titem.setIndexState(state)\n\tif state != indexStateFail {\n\t\titem.indexed = reflect.DeepEqual(opts, item.opts)\n\t}\n\tif item.heapIdx >= 0 {\n\t\t// We only update the position in the queue, never add it.\n\t\theap.Fix(&q.pq, item.heapIdx)\n\t}\n\tq.mu.Unlock()\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 (x *Index) Write(w io.Writer) error", "func (pal *CGBPalette) updateIndex(value byte) {\n\tpal.index = value & 0x3F\n\tpal.inc = bits.Test(value, 7)\n}", "func (mmSetIndex *mIndexModifierMockSetIndex) Set(f func(ctx context.Context, pn insolar.PulseNumber, index record.Index) (err error)) *IndexModifierMock {\n\tif mmSetIndex.defaultExpectation != nil {\n\t\tmmSetIndex.mock.t.Fatalf(\"Default expectation is already set for the IndexModifier.SetIndex method\")\n\t}\n\n\tif len(mmSetIndex.expectations) > 0 {\n\t\tmmSetIndex.mock.t.Fatalf(\"Some expectations are already set for the IndexModifier.SetIndex method\")\n\t}\n\n\tmmSetIndex.mock.funcSetIndex = f\n\treturn mmSetIndex.mock\n}", "func (a *ArrayMetaDataSlab) Insert(storage SlabStorage, index uint64, v Storable) error {\n\tif index > uint64(a.header.count) {\n\t\treturn NewIndexOutOfBoundsError(index, 0, uint64(a.header.count))\n\t}\n\n\tif len(a.childrenHeaders) == 0 {\n\t\treturn NewSlabDataErrorf(\"Inserting to empty MetaDataSlab\")\n\t}\n\n\tvar childID StorageID\n\tvar childHeaderIndex int\n\tvar adjustedIndex uint64\n\tif index == uint64(a.header.count) {\n\t\tchildHeaderIndex = len(a.childrenHeaders) - 1\n\t\th := a.childrenHeaders[childHeaderIndex]\n\t\tchildID = h.id\n\t\tadjustedIndex = uint64(h.count)\n\t} else {\n\t\tvar err error\n\t\tchildHeaderIndex, adjustedIndex, childID, err = a.childSlabIndexInfo(index)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tchild, err := getArraySlab(storage, childID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = child.Insert(storage, adjustedIndex, v)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ta.header.count++\n\n\t// Increment childrenCountSum from childHeaderIndex\n\tfor i := childHeaderIndex; i < len(a.childrenCountSum); i++ {\n\t\ta.childrenCountSum[i]++\n\t}\n\n\ta.childrenHeaders[childHeaderIndex] = child.Header()\n\n\t// Insertion increases the size,\n\t// check if full\n\n\tif child.IsFull() {\n\t\treturn a.SplitChildSlab(storage, child, childHeaderIndex)\n\t}\n\n\t// Insertion always increases the size,\n\t// so there is no need to check underflow\n\n\treturn storage.Store(a.header.id, a)\n}", "func (x *Index) Write(w io.Writer) error {}", "func (d *Dao) AddHisIdxCache(c context.Context, tp int32, oid int64, month string, dates []string) (err error) {\n\tvar (\n\t\tconn = d.dmMC.Get(c)\n\t\tkey = keyHistoryIdx(tp, oid, month)\n\t)\n\tdefer conn.Close()\n\titem := &memcache.Item{\n\t\tKey: key,\n\t\tObject: dates,\n\t\tFlags: memcache.FlagJSON,\n\t\tExpiration: d.historyExpire,\n\t}\n\tif err = conn.Set(item); err != nil {\n\t\tlog.Error(\"conn.Set(%s) error(%v)\", key, err)\n\t}\n\treturn\n}", "func (c *Chip8) SetIndex() {\n\tc.index = c.inst & 0x0FFF\n}", "func (ms HistogramBucket) SetCount(v uint64) {\n\t(*ms.orig).Count = v\n}", "func (index *Index) id(i, itemID []byte) []byte {\n\treturn append(index.bucket.Prefix(byframe.Encode(i)), itemID...)\n}", "func (e *Engine) setIndex(index int64) {\n\te.Index = index\n\te.Name = naming.Name(index)\n}", "func NewBucket(size int) *Bucket {\n\treturn &Bucket{make(chan struct{}, size)}\n}", "func (rc *Cache) PutIndex(key, name string) error {\n\tvar err error\n\tif _, err = rc.do(\"HSET\", key, name, \"1\"); err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func newBuckets(n int) *buckets {\n\treturn &buckets{counts: make([]uint64, n)}\n}", "func (h *Harmonic) Put(key string, val int) {\n\tidx, found := h.getIndex(key)\n\tif found {\n\t\th.s[idx].val = val\n\t\treturn\n\t}\n\n\tif idx > h.end {\n\t\th.append(key, val)\n\t} else if idx == -1 {\n\t\th.prepend(key, val)\n\t} else {\n\t\th.insert(idx, key, val)\n\t}\n\n\th.end++\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 (r *Root) Set(ctx context.Context, i uint64, val cbg.CBORMarshaler) error {\n\tif i > MaxIndex {\n\t\treturn fmt.Errorf(\"index %d is out of range for the amt\", i)\n\t}\n\n\tvar d cbg.Deferred\n\tif val == nil {\n\t\td.Raw = cbg.CborNull\n\t} else {\n\t\tvalueBuf := new(bytes.Buffer)\n\t\tif err := val.MarshalCBOR(valueBuf); err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.Raw = valueBuf.Bytes()\n\t}\n\n\t// where the index is greater than the number of elements we can fit into the\n\t// current AMT, grow it until it will fit.\n\tfor i >= nodesForHeight(r.bitWidth, r.height+1) {\n\t\t// if we have existing data, perform the re-height here by pushing down\n\t\t// the existing tree into the left-most portion of a new root\n\t\tif !r.node.empty() {\n\t\t\tnd := r.node\n\t\t\t// since all our current elements fit in the old height, we _know_ that\n\t\t\t// they will all sit under element [0] of this new node.\n\t\t\tr.node = &node{links: make([]*link, 1<<r.bitWidth)}\n\t\t\tr.node.links[0] = &link{\n\t\t\t\tdirty: true,\n\t\t\t\tcached: nd,\n\t\t\t}\n\t\t}\n\t\t// else we still need to add new nodes to form the right height, but we can\n\t\t// defer that to our set() call below which will lazily create new nodes\n\t\t// where it expects there to be some\n\t\tr.height++\n\t}\n\n\taddVal, err := r.node.set(ctx, r.store, r.bitWidth, r.height, i, &d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif addVal {\n\t\t// Something is wrong, so we'll just do our best to not overflow.\n\t\tif r.count >= (MaxIndex - 1) {\n\t\t\treturn errInvalidCount\n\t\t}\n\t\tr.count++\n\t}\n\n\treturn nil\n}", "func (m *RecurrencePattern) SetIndex(value *WeekIndex)() {\n m.index = value\n}", "func (self *TileSprite) SetChildIndex(child *DisplayObject, index int) {\n self.Object.Call(\"setChildIndex\", child, index)\n}", "func append_id(stub shim.ChaincodeStubInterface, indexStr string, id string, toAppend bool) ([]byte,error) {\n\t// Retrieve existing index\n logger.Debugf(\"Appending ID \"+id+\" in indexes \"+indexStr)\n\ttmpIndex, err := GetIndex(stub, indexStr)\n\tif err != nil { return nil, errors.Wrap(err, \"Error getting \"+indexStr) }\n\n\tif !toAppend {\n\t\tid += strconv.Itoa(len(tmpIndex)+1)\n\t}\n\n\n\t// Append the id to the index\n _, exists := tmpIndex[id]\n\tif !exists {\n tmpIndex[id] = true\n\t}\n\n\t// Marshal the index\n\tjsonAsBytes, err := json.Marshal(tmpIndex)\n\tif err != nil {\n\t\treturn nil,errors.Wrap(err, \"Error storing new '\" + indexStr + \"' into ledger\")\n\t}\n\n\t// Store the index into the ledger\n\terr = stub.PutState(indexStr, jsonAsBytes)\n\tif err != nil {\n\t\treturn nil,errors.Wrap(err, \"Error storing new '\" + indexStr + \"' into ledger\")\n\t}\n\n\treturn []byte(id),nil\n}", "func (e *Element) SetIndex(value int) {\n\tif e.Scene != nil {\n\t\te.Scene.Resize.Notify()\n\t}\n\n\tif e.Parent != nil {\n\t\te.Parent.projectIndex(&value)\n\t\te.Parent.children.ReIndex(e.index, value)\n\t\te.Parent.updateIndexes(e.index, value) // this will set the index\n\t}\n}", "func (countIndex *CountIndex) Add(point Point) {\n\tcountIndex.Remove(point.Id())\n\tcountIndex.currentPosition[point.Id()] = point\n\tcountIndex.index.AddEntryAt(point).(counter).Add(point)\n}", "func setIndex(resp http.ResponseWriter, index uint64) {\n\t// If we ever return X-Consul-Index of 0 blocking clients will go into a busy\n\t// loop and hammer us since ?index=0 will never block. It's always safe to\n\t// return index=1 since the very first Raft write is always an internal one\n\t// writing the raft config for the cluster so no user-facing blocking query\n\t// will ever legitimately have an X-Consul-Index of 1.\n\tif index == 0 {\n\t\tindex = 1\n\t}\n\tresp.Header().Set(\"X-Consul-Index\", strconv.FormatUint(index, 10))\n}", "func BuildIndex(ctx context.Context, numBuckets, id int64, records ast.RecordSet) (int64, *Histogram, error) {\n\treturn build4SortedColumn(ctx, numBuckets, id, records, false)\n}", "func (self *LSHforest) Add(key string, sig []uint64) {\n\t// split the signature into the right number of bands and then hash each one\n\thashedSignature := make([]string, self.L)\n\tfor i := 0; i < self.L; i++ {\n\t\thashedSignature[i] = self.hashedSignatureFunc(sig[i*self.K : (i+1)*self.K])\n\t}\n\t// iterate over each band in the LSH forest\n\tfor i := 0; i < len(self.InitialHashTables); i++ {\n\t\t// if the current band in the signature isn't in the current band in the LSH forest, add it\n\t\tif _, ok := self.InitialHashTables[i][hashedSignature[i]]; !ok {\n\t\t\tself.InitialHashTables[i][hashedSignature[i]] = make(graphKeys, 1)\n\t\t\tself.InitialHashTables[i][hashedSignature[i]][0] = key\n\t\t\t// if it is, append the current key (graph location) to this hashed signature band\n\t\t} else {\n\t\t\tself.InitialHashTables[i][hashedSignature[i]] = append(self.InitialHashTables[i][hashedSignature[i]], key)\n\t\t}\n\t}\n}", "func (i Index) Set(sourceID string, id int, table string, record *Record) {\n\tinfo := RecordInfo{\n\t\tID: id,\n\t\tTable: table,\n\t\tRecord: record,\n\t}\n\n\tsourceID = strings.ToLower(sourceID)\n\tsourceID = strings.TrimSpace(sourceID)\n\ti[sourceID] = info\n}", "func (m *WorkbookRangeBorder) SetSideIndex(value *string)() {\n err := m.GetBackingStore().Set(\"sideIndex\", value)\n if err != nil {\n panic(err)\n }\n}", "func (q *quartileIndex) Set(at int, val bool) {\n\tcur := q.bits.Get(at)\n\tif cur && val {\n\t\treturn\n\t}\n\tif !cur && !val {\n\t\treturn\n\t}\n\tq.bits.Set(at, val)\n\tvar delta int\n\tif val {\n\t\tdelta = 1\n\t} else {\n\t\tdelta = -1\n\t}\n\tfor i, o := range q.offsets {\n\t\tif at < o {\n\t\t\tq.counts[i] += delta\n\t\t}\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 (b *bucket) Add(token Token) {\n\tupserted := false\n\n\tfor i, item := range b.items {\n\t\tif item.token == token {\n\t\t\titem.weight++\n\t\t\tb.items[i] = item\n\t\t\tupserted = true\n\t\t}\n\t}\n\n\tif !upserted {\n\t\tb.items = append(b.items, bucketItem{token, defaultWeight})\n\t}\n\n\tb.weight++\n}", "func (bush *KDBush) buildIndex(points []Point, nodeSize int) {\n\tbush.NodeSize = nodeSize\n\tbush.Points = points\n\n\tbush.idxs = make([]int, len(points))\n\tbush.coords = make([]float64, 2*len(points))\n\n\tfor i, v := range points {\n\t\tbush.idxs[i] = i\n\t\tx, y := v.Coordinates()\n\t\tbush.coords[i*2] = x\n\t\tbush.coords[i*2+1] = y\n\t}\n\n\tsort(bush.idxs, bush.coords, bush.NodeSize, 0, len(bush.idxs)-1, 0)\n}", "func (q *quartileIndex) Insert(n int, at int) error {\n\tif n%4 != 0 {\n\t\tpanic(\"can only extend by nibbles (multiples of 4)\")\n\t}\n\terr := q.bits.Insert(n, at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tnewlen := q.bits.Len()\n\tfor i := 0; i < 3; i++ {\n\t\tq.adjust(i, n, at, (newlen * (i + 1) / 4))\n\t}\n\treturn nil\n}", "func (hat *HashedArrayTree) Set(index int, value interface{}) error {\n\tif !hat.validIndex(index) {\n\t\treturn ErrIndexOutOfRange\n\t}\n\tti, li := hat.topIndex(index), hat.leafIndex(index)\n\that.top[ti][li] = value\n\treturn nil\n}", "func (_SimpleMultiSig *SimpleMultiSigCaller) NonceBucket(opts *bind.CallOpts, arg0 *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _SimpleMultiSig.contract.Call(opts, out, \"nonceBucket\", arg0)\n\treturn *ret0, err\n}", "func (lh *LHash) Put(key []byte, value client.ObjectRef) error {\n\t_, _, 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\tbucket, err := lh.newBucket(lh.refs[lh.root.BucketIndex(lh.hash(key))])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t_, added, chainDelta, err := bucket.put(key, value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// fmt.Printf(\"(%v) Put %v, added:%v; chainDelta:%v\\n\", lh.root.Size, key, added, chainDelta)\n\t\tif added || chainDelta != 0 {\n\t\t\tif added {\n\t\t\t\tlh.root.Size++\n\t\t\t}\n\t\t\tlh.root.BucketCount += chainDelta\n\t\t\tif lh.root.NeedsSplit() {\n\t\t\t\terr = lh.split()\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\treturn nil, lh.write()\n\t\t}\n\t\treturn nil, nil\n\t})\n\treturn err\n}", "func (l *RandomAccessGroupLookup) Set(key flux.GroupKey, value interface{}) {\n\tid := l.idForKey(key)\n\te, ok := l.index[string(id)]\n\tif !ok {\n\t\te = &groupLookupElement{\n\t\t\tKey: key,\n\t\t}\n\t\tl.index[string(id)] = e\n\t\tl.elements = append(l.elements, e)\n\t}\n\te.Value = value\n\te.Deleted = false\n}", "func (b *Bucket) Bucket(name string) *Bucket { panic(\"n/i\") }", "func patchBucket(w http.ResponseWriter, r *http.Request) {\n\n\tpathParams := mux.Vars(r)\n\tsageBucketID := pathParams[\"bucket\"]\n\t//objectKey := pathParams[\"key\"]\n\n\tvars := mux.Vars(r)\n\tusername := vars[\"username\"]\n\n\t//rawQuery := r.URL.RawQuery\n\n\t// normal bucket metadata\n\n\tallowed, err := userHasBucketPermission(username, sageBucketID, \"FULL_CONTROL\")\n\tif err != nil {\n\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tif !allowed {\n\t\trespondJSONError(w, http.StatusUnauthorized, \"Write access to bucket metadata denied (%s, %s)\", username, sageBucketID)\n\t\treturn\n\t}\n\n\tvar deltaBucket map[string]string\n\n\terr = json.NewDecoder(r.Body).Decode(&deltaBucket)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Could not parse json: %s\", err.Error())\n\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tlog.Printf(\"got: %v\", deltaBucket)\n\n\tdb, err := sql.Open(\"mysql\", mysqlDSN)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Unable to connect to database: %v\", err)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\tnewBucketname, ok := deltaBucket[\"name\"]\n\tif ok {\n\n\t\tinsertQueryStr := \"UPDATE Buckets SET name=? WHERE id=UUID_TO_BIN(?) ;\"\n\t\t_, err = db.Exec(insertQueryStr, newBucketname, sageBucketID)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Bucket creation in mysql failed: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\n\t}\n\n\t// return should return real bucket\n\n\tnewBucket, err := GetSageBucket(sageBucketID)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"GetSageBucket returned: %s\", err.Error())\n\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\trespondJSON(w, http.StatusOK, newBucket)\n\t//bucket fields:\n\t//metadata , name , type, (owner, change requires permission change)\n\n\t//permission\n\n}", "func NewIndexBucketModifierMock(t minimock.Tester) *IndexBucketModifierMock {\n\tm := &IndexBucketModifierMock{t: t}\n\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.SetBucketMock = mIndexBucketModifierMockSetBucket{mock: m}\n\n\treturn m\n}", "func (access IntAccess) Set(row int, val int) {\n access.rawData[access.indices[row]] = val\n}", "func (lo *LuaObject) Set(idx interface{}, val interface{}) interface{} {\n L := lo.L\n lo.Push() // the table\n GoToLua(L, nil, valueOf(idx))\n GoToLua(L, nil, valueOf(val))\n L.SetTable(-3)\n L.Pop(1) // the table\n return val\n}", "func (backend *ESClient) addDataToIndexWithID(ctx context.Context,\n\tmapping mappings.Mapping,\n\tID string,\n\tdata interface{}) error {\n\n\t// Add a document on a particular index and a particular id\n\t// This is not creating an index with a timestring at the end\n\t_, err := backend.client.Index().\n\t\tIndex(mapping.Index).\n\t\tId(ID).\n\t\tType(mapping.Type).\n\t\tBodyJson(data).\n\t\tDo(ctx)\n\treturn err\n}", "func addToIndex(repo *git.Repository, path string) error {\n\n\tindex, err := repo.Index()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = index.AddByPath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = index.WriteTree()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = index.Write()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn err\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 AddBucket(name string) {\n\tbucketsToAdd = append(bucketsToAdd, name)\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.5462457", "0.53987634", "0.5329833", "0.5281275", "0.52774054", "0.52120125", "0.51768976", "0.51632243", "0.51465714", "0.5141648", "0.5139099", "0.51226485", "0.51036954", "0.5090387", "0.50686425", "0.50326204", "0.5007259", "0.4998986", "0.49797478", "0.49673653", "0.49490982", "0.49490058", "0.49487886", "0.4931216", "0.4930297", "0.4922741", "0.49156845", "0.48982397", "0.4886024", "0.48839667", "0.48591682", "0.4849517", "0.48327363", "0.48191425", "0.48143378", "0.4803578", "0.47882378", "0.4783346", "0.47738445", "0.4771406", "0.4770853", "0.4757135", "0.4752383", "0.47390386", "0.47361302", "0.47339362", "0.4713124", "0.46971995", "0.4694578", "0.4693005", "0.46814042", "0.4667962", "0.46630818", "0.46600142", "0.4640313", "0.46367276", "0.46300304", "0.4626297", "0.46235314", "0.46212208", "0.46198583", "0.4618513", "0.46148354", "0.459894", "0.4597063", "0.45946983", "0.45854092", "0.45828694", "0.45816427", "0.457796", "0.45652077", "0.45644954", "0.45583376", "0.45570683", "0.45508957", "0.45409548", "0.45356217", "0.4530403", "0.4523482", "0.45212168", "0.4517197", "0.45170128", "0.4513639", "0.45054135", "0.44945565", "0.448846", "0.44854748", "0.4482519", "0.44810852", "0.44757125", "0.44736525", "0.44652092", "0.44643873", "0.445617", "0.4453294", "0.4447793", "0.44467765", "0.44464573", "0.44408572", "0.4432399" ]
0.5037024
15
UpdateLastKnownPulse must be called after updating TopSyncPulse
func (i *IndexDB) UpdateLastKnownPulse(ctx context.Context, topSyncPulse insolar.PulseNumber) error { i.lock.Lock() defer i.lock.Unlock() indexes, err := i.ForPulse(ctx, topSyncPulse) if err != nil && err != ErrIndexNotFound { return errors.Wrapf(err, "failed to get indexes for pulse: %d", topSyncPulse) } for idx := range indexes { inslogger.FromContext(ctx).Debugf("UpdateLastKnownPulse. pulse: %d, object: %s", topSyncPulse, indexes[idx].ObjID.DebugString()) if err := i.setLastKnownPN(topSyncPulse, indexes[idx].ObjID); err != nil { return errors.Wrapf(err, "can't setLastKnownPN. objId: %s. pulse: %d", indexes[idx].ObjID.DebugString(), topSyncPulse) } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (trd *trxDispatcher) updateLastSeenBlock() {\n\t// get the current value\n\tlsb := trd.blkObserver.Load()\n\tlog.Noticef(\"last seen block is #%d\", lsb)\n\n\t// make the change in the database so the progress persists\n\terr := repo.UpdateLastKnownBlock((*hexutil.Uint64)(&lsb))\n\tif err != nil {\n\t\tlog.Errorf(\"could not update last seen block; %s\", err.Error())\n\t}\n}", "func (l *Latency) UpdateLast(m Metadata) { l.update(m, true) }", "func (m *PulseManager) Set(ctx context.Context, newPulse insolar.Pulse) error {\n\tm.setLock.Lock()\n\tdefer m.setLock.Unlock()\n\tif m.stopped {\n\t\treturn errors.New(\"can't call Set method on PulseManager after stop\")\n\t}\n\n\tctx, logger := inslogger.WithField(ctx, \"new_pulse\", newPulse.PulseNumber.String())\n\tlogger.Debug(\"received pulse\")\n\n\tctx, span := instracer.StartSpan(\n\t\tctx, \"PulseManager.Set\", trace.WithSampler(trace.AlwaysSample()),\n\t)\n\tspan.AddAttributes(\n\t\ttrace.Int64Attribute(\"pulse.PulseNumber\", int64(newPulse.PulseNumber)),\n\t)\n\tdefer span.End()\n\n\t// Dealing with node lists.\n\tlogger.Debug(\"dealing with node lists.\")\n\t{\n\t\tfromNetwork := m.NodeNet.GetAccessor(newPulse.PulseNumber).GetWorkingNodes()\n\t\tif len(fromNetwork) == 0 {\n\t\t\tlogger.Errorf(\"received zero nodes for pulse %d\", newPulse.PulseNumber)\n\t\t\treturn nil\n\t\t}\n\t\ttoSet := make([]insolar.Node, 0, len(fromNetwork))\n\t\tfor _, n := range fromNetwork {\n\t\t\ttoSet = append(toSet, insolar.Node{ID: n.ID(), Role: n.Role()})\n\t\t}\n\t\terr := m.NodeSetter.Set(newPulse.PulseNumber, toSet)\n\t\tif err != nil {\n\t\t\tpanic(errors.Wrap(err, \"call of SetActiveNodes failed\"))\n\t\t}\n\t}\n\n\tstoragePulse, err := m.PulseAccessor.Latest(ctx)\n\tif err == pulse.ErrNotFound {\n\t\tstoragePulse = *insolar.GenesisPulse\n\t} else if err != nil {\n\t\treturn errors.Wrap(err, \"call of GetLatestPulseNumber failed\")\n\t}\n\n\tfor _, d := range m.dispatchers {\n\t\td.ClosePulse(ctx, storagePulse)\n\t}\n\n\terr = m.JetModifier.Clone(ctx, storagePulse.PulseNumber, newPulse.PulseNumber, false)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to clone jet.Tree fromPulse=%v toPulse=%v\", storagePulse.PulseNumber, newPulse.PulseNumber)\n\t}\n\n\tif err := m.PulseAppender.Append(ctx, newPulse); err != nil {\n\t\treturn errors.Wrap(err, \"call of AddPulse failed\")\n\t}\n\n\terr = m.LogicRunner.OnPulse(ctx, storagePulse, newPulse)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, d := range m.dispatchers {\n\t\td.BeginPulse(ctx, newPulse)\n\t}\n\n\treturn nil\n}", "func updateLastAppended(s *followerReplication, req *pb.AppendEntriesRequest) {\n\t// Mark any inflight logs as committed\n\tif logs := req.Entries; len(logs) > 0 {\n\t\tlast := logs[len(logs)-1]\n\t\tatomic.StoreUint64(&s.nextIndex, last.Index+1)\n\t\ts.commitment.match(s.peer.ID, last.Index)\n\t}\n\n\t// Notify still leader\n\ts.notifyAll(true)\n}", "func (svr *Server) update(){\n\tmsg := svr.queue.Dequeue()\n\tif msg != nil {\n\t\t// fmt.Println(\"server receives msg with vecClocks: \", msg.Vec)\n\t\t// fmt.Println(\"server has vecClocks: \", svr.vecClocks)\n\t\tsvr.vecClockCond.L.Lock()\n\t\tfor svr.vecClocks[msg.Id] != msg.Vec[msg.Id]-1 || !smallerEqualExceptI(msg.Vec, svr.vecClocks, msg.Id) {\n\t\t\tif svr.vecClocks[msg.Id] > msg.Vec[msg.Id]-1 {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsvr.vecClockCond.Wait()\n\t\t}\n\t\t// update timestamp and write to local memory\n\t\tsvr.vecClocks[msg.Id] = msg.Vec[msg.Id]\n\t\t// fmt.Println(\"server increments vecClocks: \", svr.vecClocks)\n\t\tsvr.vecClockCond.Broadcast()\n\t\tsvr.vecClockCond.L.Unlock()\n\t\tif err := d.WriteString(msg.Key,msg.Val); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}", "func (p *Peer) UpdateLastAnnouncedBlock(blkHash *chainhash.Hash) {\n\tlog.Tracef(\"Updating last blk for peer %v, %v\", p.addr, blkHash)\n\n\tp.statsMtx.Lock()\n\tp.lastAnnouncedBlock = blkHash\n\tp.statsMtx.Unlock()\n}", "func (pb *PBServer) tick() {\n view, ok := pb.vs.Get()\n now := time.Now()\n if !ok {\n if now.Sub(pb.lastGetViewTime) > viewservice.PingInterval * viewservice.DeadPings / 2 {\n pb.staleView = true\n }\n return\n } else {\n pb.lastGetViewTime = now\n pb.staleView = false\n }\n\n // fmt.Printf(\"viewnum: %d, me: %s, p: %s, b: %s\\n\", view.Viewnum, pb.me, view.Primary, view.Backup)\n pb.mu.Lock()\n defer pb.mu.Unlock()\n update_view := true\n if view.Primary == pb.me {\n if view.Backup == \"\" {\n update_view = true\n } else if view.Backup != pb.view.Backup {\n snapshot := SnapshotArgs{pb.values}\n var reply SnapshotReply\n ok := call(view.Backup, \"PBServer.SendSnapshot\", &snapshot, &reply)\n if !ok {\n fmt.Printf(\"Failed to call PBServer.SendSnapshot on backup: '%s'\\n\", view.Backup)\n update_view = false\n } else if reply.Err == OK {\n fmt.Printf(\"Successfully send snapshot to backup: '%s'\\n\", view.Backup)\n update_view = true\n } else {\n fmt.Printf(\"Failed to send snapshot to backup '%s': %s\\n\", view.Backup, reply.Err)\n update_view = false\n }\n }\n }\n // if view.Backup == pb.Me {\n // if pb.view.Backup != pb.Me {\n // \n // }\n // }\n if update_view {\n pb.view = view\n }\n pb.vs.Ping(pb.view.Viewnum)\n}", "func (svr *Server) update(){\n\tmsg := svr.queue.Dequeue()\n\tif msg != nil {\n\t\t// fmt.Println(\"server receives msg with vec_clock: \", msg.Vec)\n\t\t// fmt.Println(\"server has vec_clock: \", svr.vec_clock)\n\t\tsvr.vec_clock_cond.L.Lock()\n\t\tfor svr.vec_clock[msg.Id] != msg.Vec[msg.Id]-1 || !smallerEqualExceptI(msg.Vec, svr.vec_clock, msg.Id) {\n\t\t\tsvr.vec_clock_cond.Wait()\n\t\t\tif svr.vec_clock[msg.Id] > msg.Vec[msg.Id]-1 {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// update timestamp and write to local memory\n\t\tsvr.vec_clock[msg.Id] = msg.Vec[msg.Id]\n\t\t// fmt.Println(\"server increments vec_clock: \", svr.vec_clock)\n\t\tsvr.vec_clock_cond.Broadcast()\n\t\tsvr.vec_clock_cond.L.Unlock()\n\t\tsvr.m_data_lock.Lock()\n\t\tsvr.m_data[msg.Key] = msg.Val\n\t\tsvr.m_data_lock.Unlock()\n\t}\n}", "func (e *Endpoint) UpdateLastConnection() {\n\te.LastConnection = time.Now().UTC()\n}", "func (mmOnPulseFromConsensus *GatewayMock) OnPulseFromConsensusAfterCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmOnPulseFromConsensus.afterOnPulseFromConsensusCounter)\n}", "func (p *Peer) runUpdateSyncing() {\n\ttimer := time.NewTimer(p.streamer.syncUpdateDelay)\n\tdefer timer.Stop()\n\n\tselect {\n\tcase <-timer.C:\n\tcase <-p.streamer.quit:\n\t\treturn\n\t}\n\n\tkad := p.streamer.delivery.kad\n\tpo := chunk.Proximity(p.BzzAddr.Over(), kad.BaseAddr())\n\n\tdepth := kad.NeighbourhoodDepth()\n\n\tlog.Debug(\"update syncing subscriptions: initial\", \"peer\", p.ID(), \"po\", po, \"depth\", depth)\n\n\t// initial subscriptions\n\tp.updateSyncSubscriptions(syncSubscriptionsDiff(po, -1, depth, kad.MaxProxDisplay))\n\n\tdepthChangeSignal, unsubscribeDepthChangeSignal := kad.SubscribeToNeighbourhoodDepthChange()\n\tdefer unsubscribeDepthChangeSignal()\n\n\tprevDepth := depth\n\tfor {\n\t\tselect {\n\t\tcase _, ok := <-depthChangeSignal:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// update subscriptions for this peer when depth changes\n\t\t\tdepth := kad.NeighbourhoodDepth()\n\t\t\tlog.Debug(\"update syncing subscriptions\", \"peer\", p.ID(), \"po\", po, \"depth\", depth)\n\t\t\tp.updateSyncSubscriptions(syncSubscriptionsDiff(po, prevDepth, depth, kad.MaxProxDisplay))\n\t\t\tprevDepth = depth\n\t\tcase <-p.streamer.quit:\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Debug(\"update syncing subscriptions: exiting\", \"peer\", p.ID())\n}", "func (rf *Raft) pulse() {\n\tfor rf.isLeader() {\n\t\t// Start send AppendEntries RPC to the rest of cluster\n\t\tfor ii := range rf.peers {\n\t\t\tif ii == rf.me {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgo func(i int) {\n\t\t\t\targs := rf.makeAppendEntriesArgs(i)\n\t\t\t\treply := AppendEntriesReply{}\n\t\t\t\trf.sendAppendEntries(i, &args, &reply)\n\t\t\t\trf.appendEntriesReplyHandler <- reply\n\t\t\t}(ii)\n\t\t}\n\n\t\ttime.Sleep(time.Duration(HeartBeatsInterval) * time.Millisecond)\n\t}\n}", "func (f *Input) syncLastPollFiles(ctx context.Context) {\n\tvar buf bytes.Buffer\n\tenc := json.NewEncoder(&buf)\n\n\t// Encode the number of known files\n\tif err := enc.Encode(len(f.knownFiles)); err != nil {\n\t\tf.Errorw(\"Failed to encode known files\", zap.Error(err))\n\t\treturn\n\t}\n\n\t// Encode each known file\n\tfor _, fileReader := range f.knownFiles {\n\t\tif err := enc.Encode(fileReader); err != nil {\n\t\t\tf.Errorw(\"Failed to encode known files\", zap.Error(err))\n\t\t}\n\t}\n\n\tif err := f.persister.Set(ctx, knownFilesKey, buf.Bytes()); err != nil {\n\t\tf.Errorw(\"Failed to sync to database\", zap.Error(err))\n\t}\n}", "func (s *Storage) GetPulseByPrev(prevPulse models.Pulse) (models.Pulse, error) {\n\ttimer := prometheus.NewTimer(GetPulseByPrevDuration)\n\tdefer timer.ObserveDuration()\n\n\tvar pulse models.Pulse\n\terr := s.db.Where(\"prev_pulse_number = ?\", prevPulse.PulseNumber).First(&pulse).Error\n\treturn pulse, err\n}", "func (mmOnPulseFromPulsar *GatewayMock) OnPulseFromPulsarAfterCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmOnPulseFromPulsar.afterOnPulseFromPulsarCounter)\n}", "func (buf *queueBuffer) updateLast(newNode *messageNode) {\n\tif buf.last != nil {\n\t\tbuf.last.next = newNode\n\t}\n\tbuf.last = newNode\n}", "func (huo *HistorytakingUpdateOne) AddPulse(i int) *HistorytakingUpdateOne {\n\thuo.mutation.AddPulse(i)\n\treturn huo\n}", "func (s *Storage) GetNextSavedPulse(fromPulseNumber models.Pulse, completedOnly bool) (models.Pulse, error) {\n\ttimer := prometheus.NewTimer(GetNextSavedPulseDuration)\n\tdefer timer.ObserveDuration()\n\n\tvar pulses []models.Pulse\n\tdb := s.db.Where(\"pulse_number > ?\", fromPulseNumber.PulseNumber)\n\tif completedOnly {\n\t\tdb = db.Where(\"is_complete = ?\", true)\n\t}\n\terr := db.Order(\"pulse_number asc\").Limit(1).Find(&pulses).Error\n\tif err != nil {\n\t\treturn models.Pulse{}, err\n\t}\n\tif len(pulses) == 0 {\n\t\treturn models.Pulse{}, nil\n\t}\n\treturn pulses[0], err\n}", "func (pb *PBServer) tick() {\n\tpb.Lock()\n\tdefer pb.Unlock()\n\n\t// Your code here.\n\tnewView, err := pb.vs.Ping(pb.curView.Viewnum)\n\tif err != nil {\n\t\tlog.Printf(\"ping view service error:%v\", err)\n\t\treturn\n\t}\n\n\tif newView.Viewnum == pb.curView.Viewnum { // no change\n\t\treturn\n\t}\n\n\tif newView.Primary != \"\" && newView.Primary == pb.me {\n\t\tif newView.Backup != \"\" && pb.curView.Backup != newView.Backup { // backup changed\n\t\t\terr := pb.clone(newView.Viewnum, newView.Backup)\n\t\t\tif err != nil { // backup not ready\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tpb.curView = newView\n}", "func (rf *Raft) updateLastApplied() {\n\trf.lock(\"UpdateLastApplied\")\n\tdefer rf.unlock(\"UpdateLastApplied\")\n\tfor rf.lastApplied < rf.commitIndex {\n\t\trf.lastApplied += 1\n\t\tcommand := rf.log[rf.lastApplied].Command\n\t\tapplyMsg := ApplyMsg{true, command, rf.lastApplied}\n\t\t// DPrintf(\"updateLastApplied, server[%d]\", rf.me)\n\t\trf.applyCh <- applyMsg\n\t\t// DPrintf(\"final apply from server[%d], his state is %v\", rf.me, rf.state)\n\t}\n\n}", "func (c *MhistConnector) Update() {\n\tfor {\n\t\tmessage := <-c.brokerChannel\n\t\tmeasurement := proto.MeasurementFromModel(&models.Raw{\n\t\t\tValue: message.Measurement,\n\t\t})\n\t\terr := c.writeStream.Send(&proto.MeasurementMessage{\n\t\t\tName: message.Channel,\n\t\t\tMeasurement: measurement,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Writing to MHIST StoreStream failed: %v\", err)\n\t\t}\n\t\tlog.Printf(\"Message added to MHIST:\\nName: %s,\\nMeasurement: %s,\\nTimestamp: %d\", message.Channel, string(message.Measurement), message.Timestamp)\n\t}\n}", "func (m *Dash) Update() error {\n\n\tif m.roomba == nil {\n\t\treturn fmt.Errorf(\"roomba not initialized\")\n\t}\n\n\tt := time.NewTicker(1000 * time.Millisecond)\n\tsg := []byte{constants.SENSOR_GROUP_6, constants.SENSOR_GROUP_101}\n\tpg := [][]byte{constants.PACKET_GROUP_6, constants.PACKET_GROUP_101}\n\n\tfor {\n\t\t<-t.C\n\t\tfmt.Printf(\"%s\\n\", time.Now().Format(\"2006/01/02 150405\"))\n\n\t\t// Iterate through the packet groups. Sensor group 100 does not work as advertised.\n\t\t// Use sensor group, 6 and 101 instead.\n\t\tfor grp := 0; grp < 2; grp++ {\n\t\t\td, e := m.roomba.Sensors(sg[grp])\n\t\t\tfmt.Println(\"Raw:%v Len:%v\", d, len(d))\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\n\t\t\ti := byte(0)\n\t\t\tfor _, p := range pg[grp] {\n\t\t\t\tpktL := constants.SENSOR_PACKET_LENGTH[p]\n\n\t\t\t\tif pktL == 1 {\n\t\t\t\t\tfmt.Printf(\"%25s: %v \\n\", constants.SENSORS_NAME[p], d[i])\n\t\t\t\t}\n\t\t\t\tif pktL == 2 {\n\n\t\t\t\t\tfmt.Printf(\"%25s: %v \\n\", constants.SENSORS_NAME[p], int16(d[i])<<8|int16(d[i+1]))\n\t\t\t\t}\n\t\t\t\ti = i + pktL\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *RouterController) updateLastSyncProcessed() {\n\tlastSyncProcessed := c.endpointsListConsumed && c.routesListConsumed &&\n\t\t(c.Namespaces == nil || c.filteredByNamespace)\n\tif err := c.Plugin.SetLastSyncProcessed(lastSyncProcessed); err != nil {\n\t\tutilruntime.HandleError(err)\n\t}\n}", "func (s *Storage) SavePulse(pulse models.Pulse) error {\n\ttimer := prometheus.NewTimer(SavePulseDuration)\n\tdefer timer.ObserveDuration()\n\n\terr := s.db.Set(\"gorm:insert_option\", \"\"+\n\t\t\"ON CONFLICT (pulse_number) DO UPDATE SET prev_pulse_number=EXCLUDED.prev_pulse_number, \"+\n\t\t\"next_pulse_number=EXCLUDED.next_pulse_number, timestamp=EXCLUDED.timestamp\",\n\t).Create(&pulse).Error\n\treturn errors.Wrap(err, \"error while saving pulse\")\n}", "func (bbo *TabularBBO) LastUpdate(s []float64, a int, r float64, rng *mathlib.Random) {\n\t// If ready to update, update and wipe the states, actions, and rewards.\n\tif bbo.ep.LastUpdate(s, a, r) {\n\t\tbbo.episodeLimitReached(rng)\n\t}\n}", "func (hu *HistorytakingUpdate) AddPulse(i int) *HistorytakingUpdate {\n\thu.mutation.AddPulse(i)\n\treturn hu\n}", "func (_XStaking *XStakingCaller) LastUpdateTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"lastUpdateTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (pb *PBServer) tick() {\n pb.mu.Lock()\n // Your code here\n v := pb.view\n pb.view, _ = pb.vs.Ping(pb.view.Viewnum)\n if pb.view.Viewnum > v.Viewnum && pb.view.Backup != \"\" && pb.me == pb.view.Primary {\n// if v.Backup != pb.view.Backup && pb.view.Backup != \"\" && pb.me == pb.view.Primary {\n args := &CopyArgs{}\n reply := CopyReply{}\n args.KV = pb.kv\n args.Serials = pb.serials\n fmt.Printf(\"######%s copy database\\n\", pb.me)\n for true {\n ok := call(pb.view.Backup, \"PBServer.ForwardComplete\", args, &reply)\n if ok {\n break\n }\n }\n }\n pb.mu.Unlock()\n// DPrintf(\"tick! %s %d\\n\", pb.me, pb.view.Viewnum);\n}", "func (pb *PBServer) tick() {\n\n newview, err := pb.vs.Ping(pb.view.Viewnum)\n if err != nil {\n fmt.Printf(\"view serivice unreachable!, error %s\\n\", err)\n return;\n }\n\n if pb.view.Viewnum != newview.Viewnum {\n fmt.Printf(\"view changed from \\n%s ==>\\n%s\\n\",pb.view, newview)\n if (pb.view.Primary == pb.me &&\n newview.Primary == pb.me &&\n pb.view.Backup != newview.Backup &&\n newview.Backup != \"\") {\n // backup changes and I'm still primary \n pb.view = newview\n fmt.Printf(\"new backup is %s\\n\", newview.Backup)\n pb.syncWithBackup()\n }\n }\n // only when pb is in the view, proceed to new view\n if pb.me == newview.Primary || pb.me == newview.Backup {\n pb.view = newview\n } else {\n fmt.Printf(\"I'm not in the view, keep trying\\n\")\n }\n}", "func (this *metaUsbSvc) LastUpdate() (time.Time) {\n\treturn this.Usb.LastUpdate()\n}", "func (rf *Raft) updateLastCommit() {\n\t// rf.lock(\"updateLastCommit\")\n\t// defer rf.unlock(\"updateLastCommit\")\n\tmatchIndexCopy := make([]int, len(rf.matchIndex))\n\tcopy(matchIndexCopy, rf.matchIndex)\n\t// for i := range rf.matchIndex {\n\t//\tDPrintf(\"matchIndex[%d] is %d\", i, rf.matchIndex[i])\n\t// }\n\n\t// sort.Sort(sort.IntSlice(matchIndexCopy))\n\tsort.Sort(sort.Reverse(sort.IntSlice(matchIndexCopy)))\n\tN := matchIndexCopy[len(matchIndexCopy)/2]\n\t// for i := range rf.log {\n\t//\tDPrintf(\"server[%d] %v\", rf.me, rf.log[i])\n\t// }\n\t// for i := range rf.matchIndex {\n\t// \tDPrintf(\"server[%d]'s matchindex is %v\", i, rf.matchIndex[i])\n\t// }\n\t// Check\n\tN = Min(N, rf.getLastIndex())\n\n\tif N > rf.commitIndex && rf.log[N].LogTerm == rf.currentTerm && rf.state == LEADER {\n\t\trf.commitIndex = N\n\t\t// DPrintf(\"updateLastCommit from server[%d]\", rf.me)\n\t\trf.notifyApplyCh <- struct{}{}\n\n\t}\n\n}", "func (p *Peer) LastPingMicros() int64 {\n\tp.statsMtx.RLock()\n\tlastPingMicros := p.lastPingMicros\n\tp.statsMtx.RUnlock()\n\n\treturn lastPingMicros\n}", "func (db *DB) SetLastPulseAsLightMaterial(ctx context.Context, pulsenum core.PulseNumber) error {\n\treturn db.Update(ctx, func(tx *TransactionManager) error {\n\t\treturn tx.set(ctx, prefixkey(scopeIDSystem, []byte{sysLastPulseAsLightMaterial}), pulsenum.Bytes())\n\t})\n}", "func (rf *Raft) UpdateLastApplied() {\n\t////fmt.Print(\"update the last applied index for peer %d\\n\", rf.me)\n\tfor rf.commitIndex > rf.lastApplied {\n\t\trf.lastApplied += 1\n\t\tlog := rf.logEntries[rf.lastApplied]\n\t\tapplyMsg := ApplyMsg{\n\t\t\tCommandValid: true,\n\t\t\tCommand: log.Command,\n\t\t\tCommandIndex: rf.lastApplied,\n\t\t}\n\t\trf.applyCh <- applyMsg\n\t}\n}", "func (x *x509Handler) update(u *workload.X509SVIDResponse) {\n\tx.mtx.Lock()\n\tdefer x.mtx.Unlock()\n\n\tif reflect.DeepEqual(u, x.latest) {\n\t\treturn\n\t}\n\n\tx.latest = u\n\n\t// Don't block if the channel is full\n\tselect {\n\tcase x.changes <- struct{}{}:\n\t\tbreak\n\tdefault:\n\t\tbreak\n\t}\n}", "func (ch Channel) PolyAftertouch(key, pressure uint8) []byte {\n\treturn channelMessage2(ch.Index(), 10, key, pressure)\n}", "func (ps pulseSlave) Pulse(p syncosc.Pulse) error {\n\tfmt.Printf(\"%d\\n\", p.Count)\n\treturn nil\n}", "func (s *Storage) CompletePulse(pulseNumber int64) error {\n\ttimer := prometheus.NewTimer(CompletePulseDuration)\n\tdefer timer.ObserveDuration()\n\treturn s.db.Transaction(func(tx *gorm.DB) error {\n\t\tpulse := models.Pulse{PulseNumber: pulseNumber}\n\t\tupdate := tx.Model(&pulse).Update(models.Pulse{IsComplete: true})\n\t\tif update.Error != nil {\n\t\t\treturn errors.Wrap(update.Error, \"error while updating pulse completeness\")\n\t\t}\n\t\trowsAffected := update.RowsAffected\n\t\tif rowsAffected == 0 {\n\t\t\treturn errors.Errorf(\"try to complete not existing pulse with number %d\", pulseNumber)\n\t\t}\n\t\tif rowsAffected != 1 {\n\t\t\treturn errors.Errorf(\"several rows were affected by update for pulse with number %d to complete, it was not expected\", pulseNumber)\n\t\t}\n\t\treturn nil\n\t})\n}", "func (m *MockRemotePeer) UpdateLastNotice(blkHash types.BlockID, blkNumber types.BlockNo) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UpdateLastNotice\", blkHash, blkNumber)\n}", "func TrackStreams() {\n // Sleep until the time is a multiple of the refresh period\n now := time.Now()\n wakeUpTime := now.Truncate(config.Timing.Period).Add(config.Timing.Period)\n fmt.Print(\"Waiting...\")\n time.Sleep(wakeUpTime.Sub(now))\n fmt.Println(\"Go\")\n\n // Start periodic updates\n ticker := time.NewTicker(config.Timing.Period)\n Update() // Update immediately, since ticker waits for next interval\n for {\n <-ticker.C\n Update()\n }\n}", "func (c *Core) restoreLatestSync() error {\n\t// Load all pins from the datastore.\n\tq := query.Query{\n\t\tPrefix: SyncPrefix,\n\t}\n\tresults, err := c.DS.Query(context.Background(), q)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer results.Close()\n\n\tvar count int\n\tfor r := range results.Next() {\n\t\tif r.Error != nil {\n\t\t\treturn fmt.Errorf(\"cannot read latest syncs: %w\", r.Error)\n\t\t}\n\t\tent := r.Entry\n\t\t_, lastCid, err := cid.CidFromBytes(ent.Value)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"Failed to decode latest sync CID\", \"err\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif lastCid == cid.Undef {\n\t\t\tcontinue\n\t\t}\n\t\tpeerID, err := peer.Decode(strings.TrimPrefix(ent.Key, SyncPrefix))\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"Failed to decode peer ID of latest sync\", \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\terr = c.LS.SetLatestSync(peerID, lastCid)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"Failed to set latest sync\", \"err\", err, \"peer\", peerID)\n\t\t\tcontinue\n\t\t}\n\t\tlogger.Debugw(\"Set latest sync\", \"provider\", peerID, \"cid\", lastCid)\n\t\tcount++\n\t}\n\tlogger.Infow(\"Loaded latest sync for providers\", \"count\", count)\n\treturn nil\n}", "func (tk *timekeeper) updateSyncCount(cmd Message, ts Timestamp) {\n\n\tstreamId := cmd.(*MsgStream).GetStreamId()\n\tmeta := cmd.(*MsgStream).GetMutationMeta()\n\n\tbucketNewTsReqd := tk.streamBucketNewTsReqdMap[streamId]\n\tbucketFlushInProgressMap := tk.streamBucketFlushInProgressMap[streamId]\n\tbucketTsListMap := tk.streamBucketTsListMap[streamId]\n\tbucketFlushEnabledMap := tk.streamBucketFlushEnabledMap[streamId]\n\tbucketSyncCountMap := tk.streamBucketSyncCountMap[streamId]\n\n\t//update sync count for this bucket\n\tif syncCount, ok := (*bucketSyncCountMap)[meta.bucket]; ok {\n\t\tsyncCount++\n\t\tif syncCount >= SYNC_COUNT_TS_TRIGGER &&\n\t\t\t(*bucketNewTsReqd)[meta.bucket] == true {\n\t\t\t//generate new stability timestamp\n\t\t\tcommon.Debugf(\"Timekeeper::handleSync \\n\\tGenerating new Stability \"+\n\t\t\t\t\"TS: %v Bucket: %v Stream: %v. SyncCount: %v\", ts,\n\t\t\t\tmeta.bucket, streamId, syncCount)\n\n\t\t\tnewTs := CopyTimestamp(ts)\n\t\t\ttsList := (*bucketTsListMap)[meta.bucket]\n\n\t\t\t//if there is no flush already in progress for this bucket\n\t\t\t//no pending TS in list and flush is not disabled, send new TS\n\t\t\tif (*bucketFlushInProgressMap)[meta.bucket] == false &&\n\t\t\t\t(*bucketFlushEnabledMap)[meta.bucket] == true &&\n\t\t\t\ttsList.Len() == 0 {\n\t\t\t\tgo tk.sendNewStabilityTS(newTs, meta.bucket, streamId)\n\t\t\t} else {\n\t\t\t\t//store the ts in list\n\t\t\t\tcommon.Debugf(\"Timekeeper::handleSync \\n\\tAdding TS: %v to Pending \"+\n\t\t\t\t\t\"List for Bucket: %v Stream: %v.\", ts, meta.bucket, streamId)\n\t\t\t\ttsList.PushBack(newTs)\n\t\t\t}\n\t\t\t(*bucketSyncCountMap)[meta.bucket] = 0\n\t\t\t(*bucketNewTsReqd)[meta.bucket] = false\n\t\t} else {\n\t\t\tcommon.Tracef(\"Timekeeper::handleSync \\n\\tUpdating Sync Count for Bucket: %v \"+\n\t\t\t\t\"Stream: %v. SyncCount: %v.\", meta.bucket, streamId, syncCount)\n\t\t\t//update only if its less than trigger count, otherwise it makes no\n\t\t\t//difference. On long running systems, syncCount may overflow otherwise\n\t\t\tif syncCount < SYNC_COUNT_TS_TRIGGER {\n\t\t\t\t(*bucketSyncCountMap)[meta.bucket] = syncCount\n\t\t\t}\n\t\t}\n\t} else {\n\t\t//add a new counter for this bucket\n\t\tcommon.Debugf(\"Timekeeper::handleSync \\n\\tAdding new Sync Count for Bucket: %v \"+\n\t\t\t\"Stream: %v. SyncCount: %v.\", meta.bucket, streamId, syncCount)\n\t\t(*bucketSyncCountMap)[meta.bucket] = 1\n\t}\n}", "func (s *followerReplication) setLastContact() {\n\ts.lastContactLock.Lock()\n\ts.lastContact = time.Now()\n\ts.lastContactLock.Unlock()\n}", "func (m *MockStreamFlowController) UpdateHighestReceived(arg0 protocol.ByteCount, arg1 bool) error {\n\tret := m.ctrl.Call(m, \"UpdateHighestReceived\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *PulseManager) Current() (*core.Pulse, error) {\n\tpulseNum := m.db.GetCurrentPulse()\n\tentropy, err := m.db.GetEntropy(pulseNum)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpulse := core.Pulse{\n\t\tPulseNumber: pulseNum,\n\t\tEntropy: *entropy,\n\t}\n\treturn &pulse, nil\n}", "func (kv *ShardKV) tick() {\n DPrintf(\"Server %s called tick function! Current max_config_in_log is %d\", kv.id, kv.max_config_in_log)\n kv.mu.Lock()\n defer kv.mu.Unlock()\n\n new_config := kv.sm.Query(-1)\n kv.max_config_in_log = int(math.Max(float64(kv.max_config_in_log), float64(kv.curr_config.Num)))\n if new_config.Num > kv.max_config_in_log { // change this to kv.max_config_in_log\n DPrintf2(\"Server %s Configuration is old! Putting configs from %d to %d in log\", kv.id, kv.max_config_in_log +1, new_config.Num)\n for config_num := kv.max_config_in_log +1; config_num <= new_config.Num; config_num++{\n kv.max_config_in_log = config_num\n kv.startReconfiguration(kv.sm.Query(config_num))\n } \n }\n // DPrintf(\"Server %s ending tick function\", kv.id)\n}", "func (m *DomainMonitor) Update() {\n\tm.mutex.Lock()\n\tif !m.closed && m.instance != nil {\n\t\tm.instance.Poll()\n\t}\n\tm.mutex.Unlock()\n}", "func (o *Wireless) SetLastSeen(v float32) {\n\to.LastSeen = &v\n}", "func (sm *ShardMaster) update() {\n\tvar noop Op\n\tnoop.ProposedConfig.Num = 0\n\t// Concatenate first 16 digits of current time with\n\t// first 3 digits of sm.me\n\t// Using 3 digits of sm.me allows for a thousand peers\n\t// Using 16 digits of the time means it won't repeat for about 115 days\n\t// Using both time and \"me\" means it's probably unique\n\t// Using 19 digits means it will fit in a uint64\n\ttimeDigits := uint64(time.Now().UnixNano() % 10000000000000000)\n\tmeDigits := uint64(sm.me % 1000)\n\tnoop.ID = timeDigits*1000 + meDigits\n\n\tupdated := false\n\tfor !updated && !sm.dead {\n\t\tsm.px.Start(sm.maxSequenceCommitted+1, noop)\n\t\t// Wait until its Status is decided\n\t\tdecided := false\n\t\tvar decidedValue interface{}\n\t\ttoWait := 25 * time.Millisecond\n\t\tfor !decided && !sm.dead {\n\t\t\tdecided, decidedValue = sm.px.Status(sm.maxSequenceCommitted + 1)\n\t\t\tif !decided {\n\t\t\t\ttime.Sleep(toWait)\n\t\t\t\t//if toWait < 2*time.Second {\n\t\t\t\t//\ttoWait *= 2\n\t\t\t\t//}\n\t\t\t}\n\t\t}\n\n\t\tif sm.dead {\n\t\t\tbreak\n\t\t}\n\n\t\t// Get the decided configuration for this sequence\n\t\tdecidedConfig := decidedValue.(Op).ProposedConfig\n\t\t// If the decided value has the chosen unique ID, ours was accepted and we are updated\n\t\t// Otherwise, store decided configuration (if it's not another no-op)\n\t\tif decidedValue.(Op).ID == noop.ID {\n\t\t\tupdated = true\n\t\t} else {\n\t\t\tif decidedConfig.Num > 0 {\n\t\t\t\tsm.addConfig(decidedConfig)\n\t\t\t}\n\t\t}\n\t\tsm.maxSequenceCommitted++\n\t}\n\tsm.px.Done(sm.maxSequenceCommitted)\n}", "func (d *Decoder) Pulse() Pulse {\n\tvar p pulse\n\tfor {\n\t\tp = <-d.c\n\t\tif p.sec == 0 {\n\t\t\td.decodeDate(p.l, uint32(p.h))\n\t\t\tbreak\n\t\t}\n\t\tif d.date.Sec >= 0 || p.sec < 0 {\n\t\t\td.date.Sec = p.sec\n\t\t\tbreak\n\t\t}\n\t}\n\treturn Pulse{d.date, p.stamp}\n}", "func (h *Handler) Sync(to []*key.Identity) (*Beacon, error) {\n\th.Lock()\n\th.syncing = true\n\th.Unlock()\n\tdefer func() {\n\t\th.Lock()\n\t\th.syncing = false\n\t\th.Unlock()\n\t}()\n\tvar nextRound uint64\n\tvar nextTime int64\n\tvar err error\n\tvar lastBeacon *Beacon\n\tlastBeacon, err = h.store.Last()\n\tif err == ErrNoBeaconSaved {\n\t\treturn nil, errors.New(\"no genesis block stored. BUG\")\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnextRound, nextTime = NextRound(h.conf.Clock.Now().Unix(), h.conf.Group.Period, h.conf.Group.GenesisTime)\n\tif lastBeacon.Round+1 == nextRound {\n\t\t// next round will build on the one we have - no need to sync\n\t\treturn lastBeacon, nil\n\t}\n\t// Reason to try multiple times is when syncing, we might leave the sync\n\t// after the targeted time. It shouldn't happen though often.\n\tfor trial := 0; trial < SyncRetrial; trial++ {\n\t\t// there is a gap - we need to sync with other peers\n\t\tlastBeacon, err := h.syncFrom(to, lastBeacon)\n\t\tif err != nil {\n\t\t\th.l.Error(\"sync\", \"failed\", \"from\", lastBeacon.Round)\n\t\t}\n\t\tif lastBeacon != nil {\n\t\t\tnextRound, nextTime = NextRound(h.conf.Clock.Now().Unix(), h.conf.Group.Period, h.conf.Group.GenesisTime)\n\t\t\tif lastBeacon.Round+1 == nextRound {\n\t\t\t\t// next round will build on the one we have - no need to sync\n\t\t\t\th.l.Debug(\"sync\", \"done\", \"upto\", lastBeacon.Round, \"next_time\", nextTime)\n\t\t\t\treturn lastBeacon, nil\n\t\t\t}\n\t\t\th.l.Debug(\"sync\", \"incomplete\", \"want\", nextRound-1, \"has\", lastBeacon.Round)\n\t\t} else {\n\t\t\th.l.Error(\"after_sync\", \"nil_beacon\")\n\t\t}\n\t\th.l.Debug(\"sync_incomplete\", \"try_again\", fmt.Sprintf(\"%d/%d\", trial, SyncRetrial))\n\t\t//h.conf.Clock.Sleep(SyncRetrialWait)\n\t}\n\th.l.Error(\"sync\", \"failed\", \"network_down_or_BUG\")\n\treturn lastBeacon, errors.New(\"impossible to sync to current round: network is down?\")\n}", "func (o *ObservedDataType) SetLastObserved(t interface{}) error {\n\tts, _ := timestamp.ToString(t, \"micro\")\n\to.LastObserved = ts\n\treturn nil\n}", "func updateLastSeen(id string) {\n\tnow := time.Now()\n\n\t/* Make sure we have a Implant for this ID */\n\tIMPLANTS.ContainsOrAdd(id, NewImplant(id))\n\n\t/* Get the Implant to update */\n\tv, ok := IMPLANTS.Get(id)\n\tif !ok {\n\t\tlog.Printf(\"[ID-%v] Forgotten too fast\", id)\n\t\treturn\n\t}\n\ti, ok := v.(*Implant)\n\tif !ok {\n\t\tlog.Panicf(\"wrong type of implant: %T\", v)\n\t}\n\n\ti.l.Lock()\n\tdefer i.l.Unlock()\n\t/* Log if this is the first time we've seen this implant */\n\tif i.seen.IsZero() {\n\t\tlog.Printf(\"[ID-%v] Hello.\", id)\n\t}\n\n\t/* Update timestamp if the one we have is newer */\n\tif now.After(i.seen) {\n\t\ti.seen = now\n\t}\n}", "func getLastKnownPosition(txn *badger.Txn, pn insolar.PulseNumber) (uint32, error) {\n\tkey := lastKnownRecordPositionKey{pn: pn}\n\n\tfullKey := append(key.Scope().Bytes(), key.ID()...)\n\n\titem, err := txn.Get(fullKey)\n\tif err != nil {\n\t\tif err == badger.ErrKeyNotFound {\n\t\t\treturn 0, ErrNotFound\n\t\t}\n\t\treturn 0, err\n\t}\n\n\tbuff, err := item.ValueCopy(nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn binary.BigEndian.Uint32(buff), nil\n}", "func (self *IoStatsBuilder) Update(current map[int]*IoAmount, now time.Time) {\n\tseconds := now.Sub(self.lastMeasurement).Seconds()\n\tvar total IoAmount\n\tfor pid, amt := range current {\n\t\ttotal.Increment(amt)\n\t\tdelete(self.lastPids, pid)\n\t}\n\tfor _, amt := range self.lastPids {\n\t\tself.deadUsage.Increment(amt)\n\t}\n\ttotal.Increment(&self.deadUsage)\n\tself.lastPids = current\n\tself.lastMeasurement = now\n\tdiff := self.Total.update(&total)\n\tif seconds > 0 {\n\t\trate := diff.rate(seconds)\n\t\tself.RateMax.TakeMax(rate)\n\t\trate.weightSquared(seconds)\n\t\tself.weightedSumSquared.Increment(rate)\n\t\tif t := now.Sub(self.start).Seconds(); t > 0 {\n\t\t\tself.RateDev = self.weightedSumSquared.computeStdDev(\n\t\t\t\t&self.Total, t)\n\t\t}\n\t}\n}", "func (t *AudioPlayer) Update(a *app.App, deltaTime time.Duration) {\n\n\tif time.Now().Sub(t.lastUpdate) < 100*time.Millisecond {\n\t\treturn\n\t}\n\tt.pc1.UpdateTime()\n\tt.pc2.UpdateTime()\n\tt.pc3.UpdateTime()\n\tt.pc4.UpdateTime()\n\tt.lastUpdate = time.Now()\n}", "func (bot *ExchangeBot) signalUpdate(token string) {\n\tvar signal *UpdateSignal\n\tif bot.IsFailed() {\n\t\tsignal = &UpdateSignal{\n\t\t\tToken: token,\n\t\t\tState: nil,\n\t\t\tBytes: []byte{},\n\t\t}\n\t} else {\n\t\tsignal = &UpdateSignal{\n\t\t\tToken: token,\n\t\t\tState: bot.State(),\n\t\t\tBytes: bot.StateBytes(),\n\t\t}\n\t}\n\tfor _, ch := range bot.updateChans {\n\t\tselect {\n\t\tcase ch <- signal:\n\t\tdefault:\n\t\t}\n\t}\n}", "func (c *Core) watchSyncFinished(onSyncFin <-chan golegs.SyncFinished) {\n\tfor syncFin := range onSyncFin {\n\t\tif _, err := c.PS.Get(context.Background(), syncFin.Cid); err != nil {\n\t\t\t// skip if data is not stored\n\t\t\tcontinue\n\t\t}\n\n\t\texist, _ := c.checkCidCached(syncFin.Cid)\n\t\tif exist {\n\t\t\t// seen cid before, skip\n\t\t\tcontinue\n\t\t}\n\n\t\tmetrics.Counter(context.Background(), metrics.ProviderNotificationCount, syncFin.PeerID.String(), 1)()\n\n\t\t// Persist the latest sync\n\t\terr := c.DS.Put(context.Background(), datastore.NewKey(SyncPrefix+syncFin.PeerID.String()), syncFin.Cid.Bytes())\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"Error persisting latest sync\", \"err\", err, \"peer\", syncFin.PeerID)\n\t\t\tcontinue\n\t\t}\n\t\tlogger.Debugw(\"Persisted latest sync\", \"peer\", syncFin.PeerID, \"cid\", syncFin.Cid)\n\t}\n\tclose(c.watchDone)\n}", "func (huo *HistorytakingUpdateOne) SetPulse(i int) *HistorytakingUpdateOne {\n\thuo.mutation.ResetPulse()\n\thuo.mutation.SetPulse(i)\n\treturn huo\n}", "func (q *SimpleQueue) SubscriberSetLastRead(ctx context.Context, user cn.CapUser,\n\tsubscriber string, id int64,\n\tsaveMode cn.SaveMode) (err *mft.Error) {\n\n\tif !q.Subscribers.mx.TryLock(ctx) {\n\t\treturn GenerateError(10032000)\n\t}\n\n\tif q.UseDefaultSaveModeForce {\n\t\tsaveMode = q.DefaultSaveMode\n\t} else if saveMode == cn.QueueSetDefaultMode {\n\t\tsaveMode = q.DefaultSaveMode\n\t}\n\n\tif saveMode != cn.NotSaveSaveMode &&\n\t\tsaveMode != cn.SaveImmediatelySaveMode &&\n\t\tsaveMode != cn.SaveMarkSaveMode &&\n\t\tsaveMode != cn.SaveWaitSaveMode {\n\t\treturn GenerateError(10032002, saveMode)\n\t}\n\n\tisChanged := false\n\tvar chWait chan bool\n\tv, ok := q.Subscribers.SubscribersInfo[subscriber]\n\tif !ok && id != 0 {\n\t\tv = &SimpleQueueSubscriberInfo{\n\t\t\tStartDt: time.Now(),\n\t\t\tLastID: id,\n\t\t\tLastDt: time.Now(),\n\t\t}\n\t\tq.Subscribers.SubscribersInfo[subscriber] = v\n\n\t\tisChanged = true\n\t} else if v.LastID < id && id != 0 {\n\t\tv.LastID = id\n\t\tv.LastDt = time.Now()\n\n\t\tisChanged = true\n\t} else if ok && id == 0 {\n\t\tdelete(q.Subscribers.SubscribersInfo, subscriber)\n\t}\n\n\tif !isChanged {\n\t\tq.Subscribers.mx.Unlock()\n\t\treturn nil\n\t}\n\n\tif saveMode == cn.SaveWaitSaveMode {\n\t\tchWait = make(chan bool, 1)\n\t\tq.Subscribers.SaveWait = append(q.Subscribers.SaveWait, chWait)\n\t}\n\n\tif saveMode == cn.SaveMarkSaveMode {\n\t\tq.Subscribers.ChangesRv = q.IDGenerator.RvGetPart()\n\t}\n\n\tq.Subscribers.mx.Unlock()\n\n\tif saveMode == cn.SaveImmediatelySaveMode {\n\t\terr = q.SaveSubscribers(ctx, user)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\tif saveMode == cn.SaveWaitSaveMode {\n\t\tif chWait != nil {\n\t\t\tselect {\n\t\t\tcase <-chWait:\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn GenerateError(10032001)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (p *Participant) newSignedUpdate() {\n\t// Check that this function was not called by error.\n\tif p.engine.SiblingIndex() > state.QuorumSize {\n\t\tp.log.Error(\"error call on newSignedUpdate\")\n\t\treturn\n\t}\n\n\t// Generate the entropy for this round of random numbers.\n\tvar entropy state.Entropy\n\tcopy(entropy[:], siacrypto.RandomByteSlice(state.EntropyVolume))\n\n\tsp, err := p.engine.BuildStorageProof()\n\tif err == state.ErrEmptyQuorum {\n\t\tp.log.Debug(\"could not build storage proof:\", err)\n\t} else if err != nil {\n\t\tp.log.Error(sialog.AddCtx(err, \"failed to construct storage proof\"))\n\t\treturn\n\t}\n\thb := delta.Heartbeat{\n\t\tParentBlock: p.engine.Metadata().ParentBlock,\n\t\tEntropy: entropy,\n\t\tStorageProof: sp,\n\t}\n\n\tsignature, err := p.secretKey.SignObject(hb)\n\tif err != nil {\n\t\tp.log.Error(\"failed to sign heartbeat:\", err)\n\t\treturn\n\t}\n\n\t// Create the update with the heartbeat and heartbeat signature.\n\tp.engineLock.RLock()\n\tupdate := Update{\n\t\tHeight: p.engine.Metadata().Height,\n\t\tHeartbeat: hb,\n\t\tHeartbeatSignature: signature,\n\t}\n\tp.engineLock.RUnlock()\n\n\t// Attach all of the script inputs to the update, clearing the list of\n\t// script inputs in the process.\n\tp.updatesLock.Lock()\n\tupdate.ScriptInputs = p.scriptInputs\n\tp.scriptInputs = nil\n\tp.updatesLock.Unlock()\n\n\t// Attach all of the update advancements to the signed heartbeat and sign\n\t// them.\n\tp.updatesLock.Lock()\n\tupdate.UpdateAdvancements = p.updateAdvancements\n\tp.updateAdvancements = nil\n\tfor _, ua := range update.UpdateAdvancements {\n\t\tuas, err := p.secretKey.SignObject(ua)\n\t\tif err != nil {\n\t\t\t// log an error\n\t\t\tcontinue\n\t\t}\n\t\tupdate.AdvancementSignatures = append(update.AdvancementSignatures, uas)\n\t}\n\tp.updatesLock.Unlock()\n\n\t// Sign the update and create a SignedUpdate object with ourselves as the\n\t// first signatory.\n\tupdateSignature, err := p.secretKey.SignObject(update)\n\tsu := SignedUpdate{\n\t\tUpdate: update,\n\t\tSignatories: make([]byte, 1),\n\t\tSignatures: make([]siacrypto.Signature, 1),\n\t}\n\tsu.Signatories[0] = p.engine.SiblingIndex()\n\tsu.Signatures[0] = updateSignature\n\n\t// Add the heartbeat to our own heartbeat map.\n\tupdateHash, err := siacrypto.HashObject(update)\n\tif err != nil {\n\t\tp.log.Error(\"failed to hash update:\", err)\n\t\treturn\n\t}\n\tp.updatesLock.Lock()\n\tp.updates[p.engine.SiblingIndex()][updateHash] = update\n\tp.updatesLock.Unlock()\n\n\t// Broadcast the SignedUpdate to the network.\n\tp.broadcast(network.Message{\n\t\tProc: \"Participant.HandleSignedUpdate\",\n\t\tArgs: su,\n\t})\n}", "func LastUpdateTime(t time.Time) Precondition { return lastUpdateTime(t) }", "func (c *Connection) PongReceiver() {\n\tc.lastResponse = time.Now()\n\tc.logger.Debugf(\"\\n[Connection][PongReceiver] Actualizacion de ultima respuesta %s\", c.lastResponse.Format(time.RFC3339))\n}", "func (t *Pitch) Update(a *app.App, deltaTime time.Duration) {}", "func (t *Pitch) Update(a *app.App, deltaTime time.Duration) {}", "func (s *Storage) GetPulse(pulseNumber int64) (models.Pulse, error) {\n\ttimer := prometheus.NewTimer(GetPulseDuration)\n\tdefer timer.ObserveDuration()\n\n\tvar pulse models.Pulse\n\terr := s.db.Where(\"pulse_number = ?\", pulseNumber).First(&pulse).Error\n\tif err != nil {\n\t\treturn pulse, err\n\t}\n\n\tpulse = s.updateNextPulse(pulse)\n\tpulse = s.updatePrevPulse(pulse)\n\n\treturn pulse, err\n}", "func defaultOr(latestPoll *metav1.Time, pollingInterval time.Duration, creationTimestamp time.Time, now time.Time) time.Duration {\n\tif latestPoll.IsZero() {\n\t\tlatestPoll = &metav1.Time{Time: creationTimestamp}\n\t}\n\n\tremaining := latestPoll.Add(pollingInterval).Sub(now)\n\t// sync ahead of the default interval in the case where now + default sync is after the last sync plus the interval\n\tif remaining < queueinformer.DefaultResyncPeriod {\n\t\treturn remaining\n\t}\n\t// return the default sync period otherwise: the next sync cycle will check again\n\treturn queueinformer.DefaultResyncPeriod\n}", "func (NilUGauge) Update(v uint64) {}", "func (tr *Tracker) SetLastSync(t time.Time) {\n\ttr.status.LastUpdated.LastSync = t\n}", "func (u updates) Last(l UpdateLabels) prometheus.Gauge {\n\treturn u.last.WithLabelValues(l.Values()...)\n}", "func Update () {\n // Compute the current time rounded to the interval\n roundTime := time.Now().Round(config.Timing.Period)\n unixTimeString := strconv.FormatInt(roundTime.Unix(), 10);\n\n // Query Twitch for each filter's streams, and assemble a map of unique\n // streams along with all filters which found them\n taggedStreams := make(map[string]*taggedStream)\n filters := database.GetAllFilters()\n for _, filter := range filters {\n // Make appropriate Twitch query\n var sr *twitchapi.GetStreamsResponse\n if filter.QueryType == database.QueryTypeStreams {\n sr = twitchapi.AllStreams(filter.QueryParam)\n }\n //} else if filter.QueryType == database.QueryTypeFollows {\n // sr = twitchapi.FollowedStreams(filter.QueryParam)\n //}\n // Assimilate all recieved streams into our tagged stream map\n for _, s := range sr.Streams {\n id := s.ChannelId\n if _, seen := taggedStreams[id]; !seen { // Idiom to check if in map\n taggedStreams[id] = &taggedStream{Stream:s}\n }\n taggedStreams[id].AppendFilter(filter.ID)\n }\n database.UpdateFilter(filter.ID, roundTime)\n }\n\n // For each (stream, filters) pair, grab and save a snapshot to the DB\n for _, sf := range taggedStreams {\n stream := sf.Stream\n channelName := stream.ChannelDisplayName\n status := stream.Status\n fmt.Printf(\"(%v) %v: %v\\n\", len(sf.FilterIds), channelName, status)\n\n // Query Twitch for the channel's most recent (current) archive video ID\n archive := twitchapi.ChannelRecentArchive(stream.ChannelId)\n\n // If this snapshot doesn't correspond to the most recent archive, then\n // either the streamer has disabled archiving, the archive somehow isn't\n // accessible yet, or something else. So, store no VOD for this thumb.\n vodID := \"\"\n vodSeconds := 0\n vodTime := roundTime\n if archive != nil {\n if archive.Broadcast_Id == stream.Id {\n vodID = archive.Id\n vodSeconds = int(roundTime.Sub(archive.Created_At_Time).Seconds())\n //vodTime = archive.Created_At_Time\n } else {\n fmt.Printf(\"recent archive is not current stream\\n\")\n }\n } else {\n fmt.Printf(\"recent archive was nil\\n\")\n }\n\n // Download stream preview image from Twitch\n imagePath := config.Path.ImagesRelative + \"/\" +\n stream.ChannelName + \"_\" + unixTimeString + \".jpg\"\n imageDLPath := config.Path.Root + imagePath\n imageUrl := stream.Preview\n DownloadImage(imageUrl, imageDLPath)\n\n // Finally, store new info for this stream in the DB\n database.AddThumbToDB(\n roundTime, stream.ChannelName, stream.ChannelDisplayName,\n vodSeconds, vodID, imagePath, vodTime, stream.Status,\n stream.Viewers, sf.FilterIds)\n\n // Query Twitch for the channel's recent clips.\n // Commented out 2022-02-14 due to helix API migration and we don't even\n // or prune these clips anyways.\n //cr := twitchapi.TopClipsDay(stream.ChannelName)\n //for _, clip := range cr.Clips {\n // database.AddClipToDB(clip.TrackingId, clip.Created_At_Time,\n // clip.Thumbnails.Small, clip.Url, stream.ChannelName)\n //}\n }\n\n // Delete old streams (and their thumbs, follows, image files) from the DB\n database.PruneOldStreams(roundTime)\n\n RegenerateFilterPages()\n\n // TODO: Occasionally check for \"stray\" data:\n // (Also perform this check on app startup)\n // Follows whose stream or filter no longer exists\n // Have to check for each one.\n // Thumbs whose stream no longer exists\n // Total of streams NumThumbs != # thumbs\n // Image files whose thumb no longer exists\n // # image files != # thumbs\n\n fmt.Printf(\"update finish\\n\")\n /*fmt.Printf(\"%v deleted\\n\", numDeleted)\n fmt.Printf(\"%v thumbs \\n\", database.NumThumbs())\n fmt.Printf(\"%v jpg files\\n\", NumFilesInDir(config.Path.Images))\n fmt.Printf(\"%v distinct channels\\n\", len(database.DistinctChannels()))*/\n}", "func (vs *ViewServer) tick() {\n\t// Your code here.\n\tvs.mu.Lock()\n\tif vs.view.Viewnum == vs.primaryAck {\n\t\tcurrentTime := time.Now()\n\t\t// primary liveness check\n\t\tif vs.view.Primary != \"\" {\n\t\t\tprimaryLastPingTime := vs.pingTrack[vs.view.Primary]\n\t\t\t//log.Printf(\"[viewserver]tick, primary last ping: %+v\", primaryLastPingTime)\n\t\t\tif primaryLastPingTime.Add(PingInterval * DeadPings).Before(currentTime) {\n\t\t\t\tvs.view.Primary = \"\"\n\t\t\t}\n\t\t}\n\n\t\t// backup liveness check\n\t\tif vs.view.Backup != \"\" {\n\t\t\tbackupLastPingTime := vs.pingTrack[vs.view.Backup]\n\t\t\t//log.Printf(\"[viewserver]tick, backup last ping: %+v\", backupLastPingTime)\n\t\t\tif backupLastPingTime.Add(PingInterval * DeadPings).Before(currentTime) {\n\t\t\t\tvs.view.Backup = \"\"\n\t\t\t}\n\t\t}\n\n\t\tif vs.view.Primary == \"\" && vs.view.Backup != \"\" {\n\t\t\t//promote backup to primary\n\t\t\tvs.view.Primary = vs.view.Backup\n\t\t\tvs.view.Backup = \"\"\n\t\t\tvs.view.Viewnum += 1\n\t\t\tlog.Printf(\"[viewserver]tick, promote backup to primary, primary: %s\", vs.view.Primary)\n\t\t}\n\t}\n\tvs.mu.Unlock()\n}", "func (mmUpdate *StorageMock) UpdateAfterCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmUpdate.afterUpdateCounter)\n}", "func waitForStatsChange(b IRolloutBalancer, rolloutType string, wantedLen int) {\n\tdeadline := time.After(500 * time.Millisecond)\n\tfor {\n\t\tstats := b.Stats(StatsOptions{RolloutType: rolloutType})\n\t\tif len(stats) == wantedLen {\n\t\t\treturn\n\t\t}\n\t\tselect {\n\t\tcase <-deadline:\n\t\t\tpanic(fmt.Errorf(\"stats not changed! Last stats: %#v\", stats))\n\t\tcase <-time.After(1 * time.Millisecond):\n\t\t\t// poll stats\n\t\t}\n\t}\n}", "func (r *Raft) heartbeat(replication *followerReplication, stopCh chan struct{}) {\n\tvar failures uint64\n\treq := pb.AppendEntriesRequest{\n\t\tTerm: replication.currentTerm,\n\t\tLeader: r.transport.EncodePeer(r.localID, r.localAddr),\n\t}\n\tvar resp pb.AppendEntriesResponse\n\tfor {\n\t\t// Wait for the next heartbeat interval or forced notify\n\t\tselect {\n\t\tcase <-replication.notifyCh:\n\t\tcase <-randomTimeout(r.config().HeartbeatTimeout / 10): // [100ms, 200ms]\n\t\tcase <-stopCh:\n\t\t\treturn\n\t\t}\n\n\t\treplication.peerLock.RLock()\n\t\tpeer := replication.peer\n\t\treplication.peerLock.RUnlock()\n\n\t\tif err := r.transport.AppendEntries(peer.ID, peer.Address, &req, &resp); err != nil {\n\t\t\tklog.Errorf(fmt.Sprintf(\"failed to heartbeat from %s/%s to %s/%s err:%v\",\n\t\t\t\tr.localID, r.localAddr, peer.ID, peer.Address, err))\n\t\t\tr.observe(FailedHeartbeatObservation{PeerID: peer.ID, LastContact: replication.LastContact()})\n\n\t\t\t// backoff\n\t\t\tfailures++\n\t\t\tselect {\n\t\t\tcase <-time.After(backoff(failureWait, failures, maxFailureScale)):\n\t\t\tcase <-stopCh:\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tif failures > 0 {\n\t\t\t\tr.observe(ResumedHeartbeatObservation{PeerID: peer.ID})\n\t\t\t}\n\n\t\t\treplication.setLastContact()\n\t\t\tfailures = 0\n\t\t\treplication.notifyAll(resp.Success)\n\t\t}\n\t}\n}", "func (sv *Server) maybeScheduleReSync(note pushtypes.PushNote, ref string, fromBeginning bool) error {\n\n\trepoName := note.GetRepoName()\n\tlocalRefHash := plumbing2.ZeroHash\n\n\t// Get the local hash of the reference\n\tlocalRef, err := note.GetTargetRepo().Reference(plumbing2.ReferenceName(ref), false)\n\tif err != nil && err != plumbing2.ErrReferenceNotFound {\n\t\treturn err\n\t} else if localRef != nil {\n\t\tlocalRefHash = localRef.Hash()\n\t}\n\n\t// Get the network hash of the reference\n\trepoState := note.GetTargetRepo().GetState()\n\trepoRefHash := plumbing2.ZeroHash\n\tif netRef := repoState.References.Get(ref); !netRef.IsNil() {\n\t\trepoRefHash = plumbing.BytesToHash(netRef.Hash)\n\t}\n\n\t// Check if the note's pushed reference local hash and the network hash match.\n\t// If yes, no resync needs to happen.\n\tif bytes.Equal(localRefHash[:], repoRefHash[:]) {\n\t\tsv.log.Debug(\"Abandon ref resync; local and network state match\", \"Repo\", repoName, \"Ref\", ref)\n\t\treturn nil\n\t}\n\n\t// Get last synchronized\n\trefLastSyncHeight, err := sv.logic.RepoSyncInfoKeeper().GetRefLastSyncHeight(repoName, ref)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If the last successful synced reference height equal the last successful synced\n\t// height for the entire repo, it means something unnatural/external messed up\n\t// the repo history. We react by resyncing the reference from the beginning.\n\trepoLastUpdated := repoState.UpdatedAt.UInt64()\n\tif !fromBeginning && refLastSyncHeight == repoLastUpdated {\n\t\trefLastSyncHeight = repoState.CreatedAt.UInt64()\n\t}\n\n\t// If sync from beginning is requested, start from the parent\n\t// repo's time of creation\n\tif fromBeginning {\n\t\trefLastSyncHeight = repoState.CreatedAt.UInt64()\n\t}\n\n\tsv.log.Debug(\"Scheduling reference for resync\", \"Repo\", repoName, \"Ref\", ref)\n\n\t// Add the repo to the refsync watcher\n\tif err := sv.refSyncer.Watch(repoName, ref, refLastSyncHeight, repoLastUpdated); err != nil {\n\t\treturn fmt.Errorf(\"%s: reference is still being resynchronized (try again later)\", ref)\n\t}\n\n\treturn nil\n}", "func (p *rpioPoller) poll() {\npollLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-p.ticker.C:\n\t\t\t// Read pins and handle edge detection\n\t\t\tfor pin, registration := range p.registeredPins {\n\t\t\t\tif pin.EdgeDetected() {\n\t\t\t\t\tgo registration.callback(registration.edge)\n\t\t\t\t}\n\t\t\t}\n\t\tcase newRegistration := <-p.newPin:\n\t\t\t// Add pin registration to pins to poll\n\t\t\tp.registeredPins[newRegistration.pin] = newRegistration\n\t\tcase registrationToRemove := <-p.removePin:\n\t\t\t// Remove pin registration from pins to poll\n\t\t\tdelete(p.registeredPins, registrationToRemove)\n\t\tcase newPollFreq := <-p.newPollFreq:\n\t\t\t// Update the ticker polling frequency\n\t\t\tp.ticker.Reset(newPollFreq)\n\t\tcase <-p.stop:\n\t\t\tbreak pollLoop\n\t\t}\n\t}\n}", "func (m *PacketParserMock) MinimockGetPulsePacketDone() bool {\n\tfor _, e := range m.GetPulsePacketMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.GetPulsePacketMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetPulsePacketCounter) < 1 {\n\t\treturn false\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcGetPulsePacket != nil && mm_atomic.LoadUint64(&m.afterGetPulsePacketCounter) < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (f *lightFetcher) checkUpdateStats(p *peer, newEntry *updateStatsEntry) {\n\tnow := mclock.Now()\n\tfp := f.peers[p]\n\tif fp == nil {\n\t\tp.Log().Debug(\"Unknown peer to check update stats\")\n\t\treturn\n\t}\n\n\tif newEntry != nil && fp.firstUpdateStats == nil {\n\t\tfp.firstUpdateStats = newEntry\n\t}\n\tfor fp.firstUpdateStats != nil && fp.firstUpdateStats.time <= now-mclock.AbsTime(blockDelayTimeout) {\n\t\tf.handler.backend.serverPool.adjustBlockDelay(p.poolEntry, blockDelayTimeout)\n\t\tfp.firstUpdateStats = fp.firstUpdateStats.next\n\t}\n\tif fp.confirmedTd != nil {\n\t\tfor fp.firstUpdateStats != nil && fp.firstUpdateStats.td.Cmp(fp.confirmedTd) <= 0 {\n\t\t\tf.handler.backend.serverPool.adjustBlockDelay(p.poolEntry, time.Duration(now-fp.firstUpdateStats.time))\n\t\t\tfp.firstUpdateStats = fp.firstUpdateStats.next\n\t\t}\n\t}\n}", "func (hu *HistorytakingUpdate) SetPulse(i int) *HistorytakingUpdate {\n\thu.mutation.ResetPulse()\n\thu.mutation.SetPulse(i)\n\treturn hu\n}", "func (r *volumeReactor) syncAll() {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tfor _, c := range r.claims {\n\t\tr.changedObjects = append(r.changedObjects, c)\n\t}\n\tfor _, v := range r.volumes {\n\t\tr.changedObjects = append(r.changedObjects, v)\n\t}\n\tr.changedSinceLastSync = 0\n}", "func (kv *DisKV) tick() {\n\t// Your code here.\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\tnconfig := kv.sm.Query(-1)\n\tif nconfig.Num > kv.Current.Num {\n\t\tif nconfig.Num > kv.Current.Num+1 {\n\t\t\tnconfig = kv.sm.Query(kv.Current.Num + 1)\n\t\t}\n\t\tkv.reconfigure(nconfig)\n\t} else {\n\t\top := Op{Type: \"Heartbeat\", View: kv.me, Ck: rand.Int63()}\n\t\tkv.Seq++\n\t\tseq := kv.Seq\n\n\t\tkv.px.Start(seq, op)\n\t\txop := kv.getOp(seq)\n\t\tkv.process(xop, seq, 0)\n\t}\n}", "func (pb *PBServer) tick() {\n\tnextView, err := pb.vs.Ping(pb.viewNum)\n\tif err == nil {\n\t\t//log.Printf(\"Server [%s] New View num is [%d], Primary is [%s] \", pb.me, nextView.Viewnum, nextView.Primary)\n\t\tif pb.me == nextView.Primary && pb.backup != nextView.Backup {\n\t\t\targs := new(CopyArgs)\n\t\t\targs.Data = pb.data\n\t\t\targs.HandlResult = pb.handleResult\n\t\t\treply := new(CopyReply)\n\t\t\tcall(nextView.Backup, \"PBServer.Copy\", args, reply)\n\t\t}\n\t\tpb.viewNum = nextView.Viewnum\n\t\tpb.primary = nextView.Primary\n\t\tpb.backup = nextView.Backup\n\t\tpb.pingFail = 0\n\t} else {\n\t\tpb.pingFail += 1\n\t\tif pb.pingFail > viewservice.DeadPings {\n\t\t\tpb.primary = \"\"\n\t\t\tpb.backup = \"\"\n\t\t\tpb.viewNum = 0\n\t\t}\n\t}\n}", "func (mmGetPulsePacket *PacketParserMock) GetPulsePacketAfterCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmGetPulsePacket.afterGetPulsePacketCounter)\n}", "func (vs *ViewServer) tick(){\n\t// Your code here.\n\tvs.mu.Lock()\n\tnow := time.Now()\n\ttimeWindow := DeadPings * PingInterval\n\n\t// check if we can get the primary server\n\tif now.Sub(vs.pingTime[vs.currentView.Primary]) >= timeWindow && vs.primaryACK == true{\n\t\t// primary already ACK currentView -> update view using backup\n\t\tupdate(vs, vs.currentView.Backup, vs.idleServer)\n\t}\n\n\t// check recent pings from backup server\n\tif now.Sub(vs.pingTime[vs.currentView.Backup]) >= timeWindow && vs.backupACK == true{\n\t\t// check if there's an idle server\n\t\tif vs.idleServer != \"\"{\n\t\t\t// use idle server as backup\n\t\t\tupdate(vs, vs.currentView.Primary, vs.idleServer)\n\t\t}\n\t}\n\n\t// check pings from idle server\n\tif now.Sub(vs.pingTime[vs.idleServer]) >= timeWindow{\n\t\tvs.idleServer = \"\"\n\t} else {\n\t\tif vs.primaryACK == true && vs.idleServer != \"\" && vs.currentView.Backup == \"\"{\n\t\t\t// no backup -> use idle server\n\t\t\tupdate(vs, vs.currentView.Primary, vs.idleServer)\n\t\t}\n\t}\n\n\tvs.mu.Unlock()\n}", "func (_m *MockServiceClient) UpdateLastConnected(id string, time int64) error {\n\tret := _m.Called(id, time)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, int64) error); ok {\n\t\tr0 = rf(id, time)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (p *Player) syncPlayerInfo() {\n\tvar pladd []play.PIAddPlayer\n\tvar plrem []play.PIRemovePlayer\n\tvar pllat []play.PIUpdateLatency\n\n\t// check for any players that we already got\n\tfor uid, c := range p.waitingForPlayers {\n\t\tselect {\n\t\tcase _, ok := <-c:\n\t\t\tif ok {\n\t\t\t\t// we are the first to see this change\n\t\t\t\tclose(c)\n\t\t\t}\n\n\t\t\t// we know about this player\n\t\t\tdelete(p.waitingForPlayers, uid)\n\t\t\tp.knownPlayers[uid] = true\n\t\tdefault:\n\t\t\t// not sent yet, ignore\n\t\t}\n\t}\n\n\t// check for any new players\n\tif p.joined {\n\t\tpladd = make([]play.PIAddPlayer, 0, len(players))\n\t\tfor _, p := range players {\n\t\t\tpladd = append(pladd, play.PIAddPlayer{\n\t\t\t\tUUID: p.UUID,\n\t\t\t\tName: p.Username,\n\t\t\t\tGamemode: 0,\n\t\t\t\tPing: int32(p.Ping.Milliseconds()),\n\t\t\t})\n\t\t}\n\t} else {\n\t\t// the player has a list of everyone, only send updates\n\t\tpladd = make([]play.PIAddPlayer, 0, len(newPlayers))\n\t\tplrem = make([]play.PIRemovePlayer, 0, len(leftPlayers))\n\n\t\tfor _, p := range newPlayers {\n\t\t\tpladd = append(pladd, play.PIAddPlayer{\n\t\t\t\tUUID: p.UUID,\n\t\t\t\tName: p.Username,\n\t\t\t\tGamemode: 0,\n\t\t\t\tPing: int32(p.Ping),\n\t\t\t})\n\t\t}\n\n\t\tfor _, p := range leftPlayers {\n\t\t\tplrem = append(plrem, play.PIRemovePlayer{UUID: p.UUID})\n\t\t}\n\t}\n\n\t// update latencies\n\tfor _, p := range players {\n\t\tif p.PingChanged {\n\t\t\tpllat = append(pllat, play.PIUpdateLatency{\n\t\t\t\tUUID: p.UUID,\n\t\t\t\tPing: int32(p.Ping),\n\t\t\t})\n\t\t}\n\t}\n\n\tif len(pladd) > 0 {\n\t\t// insert all the players we are waiting for to\n\t\t// the map\n\t\tdone := make(chan bool)\n\t\tp.SendChan(play.PlayerInfo{ AddPlayer: pladd }, done)\n\t\tfor _, p := range newPlayers {\n\t\t\tp.waitingForPlayers[p.UUID] = done\n\t\t}\n\t}\n\n\tif len(plrem) > 0 {\n\t\tp.Send(play.PlayerInfo{ RemovePlayer: plrem })\n\t}\n\n\tif len(pllat) > 0 {\n\t\tp.Send(play.PlayerInfo{ UpdateLatency: pllat })\n\t}\n}", "func (kcp *KCP) Update() {\n\tcurrentTime := millisecond()\n\tif kcp.updated == 0 {\n\t\tkcp.updated = 1\n\t\tkcp.tsFlush = currentTime\n\t}\n\n\tslap := timediff(currentTime, kcp.tsFlush)\n\tif slap >= 10000 || slap < -10000 {\n\t\tkcp.tsFlush = currentTime\n\t\tslap = 0\n\t}\n\n\tif slap >= 0 {\n\t\tkcp.tsFlush += kcp.interval\n\t\tif timediff(currentTime, kcp.tsFlush) >= 0 {\n\t\t\tkcp.tsFlush = currentTime + kcp.interval\n\t\t}\n\n\t\tkcp.flush()\n\t}\n}", "func (s *Storage) GetSequentialPulse() (models.Pulse, error) {\n\ttimer := prometheus.NewTimer(GetSequentialPulseDuration)\n\tdefer timer.ObserveDuration()\n\n\tvar pulses []models.Pulse\n\terr := s.db.Where(\"is_sequential = ?\", true).Order(\"pulse_number desc\").Limit(1).Find(&pulses).Error\n\tif err != nil {\n\t\treturn models.Pulse{}, err\n\t}\n\tif len(pulses) == 0 {\n\t\treturn models.Pulse{}, nil\n\t}\n\treturn pulses[0], err\n}", "func (oc *Operachain) Sync() {\n\tfor {\n\t\t//requestVersion\n\t\ttime.Sleep(time.Second)\n\n\t\tfor _, node := range oc.KnownAddress {\n\t\t\tif node != oc.MyAddress {\n\t\t\t\tpayload := gobEncode(HeightMsg{oc.KnownHeight, oc.MyAddress})\n\t\t\t\treqeust := append(commandToBytes(\"rstBlocks\"), payload...)\n\t\t\t\toc.sendData(node, reqeust)\n\t\t\t}\n\t\t}\n\t}\n}", "func setLastKnownPosition(txn *badger.Txn, pn insolar.PulseNumber, position uint32) error {\n\tlastPositionKey := lastKnownRecordPositionKey{pn: pn}\n\tparsedPosition := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(parsedPosition, position)\n\n\tfullKey := append(lastPositionKey.Scope().Bytes(), lastPositionKey.ID()...)\n\n\treturn txn.Set(fullKey, parsedPosition)\n}", "func (s *Server) timing() {\n\tt := time.Now().Unix()\n\tif t > s.lastPulse {\n\t\ts.lastPulse = t\n\t\tfor _, m := range mobs {\n\t\t\tm.Pulse()\n\t\t}\n\t\tfor _, cl := range s.clients {\n\t\t\tcl.Pulse()\n\t\t}\n\t}\n\tif t > s.nextTick {\n\t\ts.nextTick = t + rand.Int63n(tickLength) + tickLength\n\t\tfor _, m := range mobs {\n\t\t\tm.Tick()\n\t\t}\n\t\tfor _, cl := range s.clients {\n\t\t\tcl.Tick()\n\t\t}\n\t}\n}", "func UpdateRoutine(freq, timeout time.Duration) {\n\tticker := time.NewTicker(freq)\n\t// new request every config.DefaultRequestsTimeout time\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\tgo func() {\n\t\tconfirm := 1\n\t\tfor ; true; <-ticker.C {\n\t\t\t// retrieve the last block\n\t\t\tlastBlockTmp, err := dataCollection.GetLastBlockNumber(timeout)\n\t\t\tif confirm > 0 {\n\t\t\t\tconfirm--\n\t\t\t\twg.Done()\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tatomic.StoreUint64(&lastBlock, lastBlockTmp)\n\t\t}\n\t}()\n\twg.Wait()\n}", "func (mr *MockRemotePeerMockRecorder) UpdateLastNotice(blkHash, blkNumber interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateLastNotice\", reflect.TypeOf((*MockRemotePeer)(nil).UpdateLastNotice), blkHash, blkNumber)\n}", "func (aa *agent) updateCommunicationTime(new time.Time) {\n\t// only update if new time is not in the future, and either the old time is invalid or new time > old time\n\taa.lock.Lock()\n\tdefer aa.lock.Unlock()\n\tif last, err := ptypes.Timestamp(aa.adapter.LastCommunication); !new.After(time.Now()) && (err != nil || new.After(last)) {\n\t\ttimestamp, err := ptypes.TimestampProto(new)\n\t\tif err != nil {\n\t\t\treturn // if the new time cannot be encoded, just ignore it\n\t\t}\n\n\t\taa.adapter.LastCommunication = timestamp\n\t}\n}", "func (b *bucket) updateLongestRun(value uint32) {\n\tcardinalityEstimation := findRun(value) + 1\n\n\tif b.cardinalityEstimation < cardinalityEstimation {\n\t\tb.cardinalityEstimation = cardinalityEstimation\n\t}\n}", "func (mmGetPulseNumber *PacketParserMock) GetPulseNumberAfterCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmGetPulseNumber.afterGetPulseNumberCounter)\n}", "func (pb *PBServer) tick() {\n\tpb.mu.Lock()\n defer pb.mu.Unlock()\n\n\tvar viewnum uint\n\tif pb.me == pb.view.Primary || pb.me == pb.view.Backup {\n\t\tviewnum = pb.view.Viewnum\n\t} else {\n\t\tviewnum = 0\n\t}\n\n\tview, err := pb.vs.Ping(viewnum)\n\tif err != nil {\n\t\tlogger.Debug(err)\n\t}\n\n\t// migrate the data if new backup appears\n\tif view.Backup != \"\" && pb.view.Backup != view.Backup && pb.me == view.Primary {\n args := MigrateArgs{Db: pb.db, Handled: pb.handled}\n reply := MigrateReply{}\n\n if !call(view.Backup, \"PBServer.Migrate\", &args, &reply) {\n return\n }\n\t}\n\n\tpb.view = view\n}", "func (self *averageCache) flush(flushLimit int) {\n\tlog.WithFields(log.Fields{\n\t\t\"cache\": self.name,\n\t}).Debug(\"Internal Flush\")\n\tvar valueFlushTargets []*whisper.TimeSeriesPoint = make([]*whisper.TimeSeriesPoint, 0)\n\tvar countFlushTargets []*whisper.TimeSeriesPoint = make([]*whisper.TimeSeriesPoint, 0)\n\tfor timeSlot, cacheSlot := range self.cache {\n\t\t// TODO: \n\t\t// Write all changes to subscriptions\n\t\tif cacheSlot.LastUpdated <= flushLimit {\n\t\t\tvalueFlushTargets = append(valueFlushTargets, &whisper.TimeSeriesPoint{timeSlot, cacheSlot.Value})\n\t\t\tcountFlushTargets = append(countFlushTargets, &whisper.TimeSeriesPoint{timeSlot, cacheSlot.Count})\n\t\t\tdelete(self.cache, timeSlot)\n\t\t}\n\t}\n\tlog.Debug(\"FlushAverages: \", valueFlushTargets)\n\tlog.Debug(\"FlushCounts: \", countFlushTargets)\n\n\t// TODO: Write flush targets to whisper\n\t// In another fiber perhaps to make this non-blocking?\n\tself.valueBackend.Write(valueFlushTargets)\n\tself.countBackend.Write(countFlushTargets)\n}", "func (r *Raft) tick() {\n\n\tswitch r.State {\n\tcase StateFollower:\n\t\tr.electionElapsed += 1\n\t\tif r.electionElapsed >= r.randomElectionTimeout {\n\t\t\tr.handleMsgUp()\n\t\t}\n\tcase StateCandidate:\n\t\tr.electionElapsed += 1\n\t\tif r.electionElapsed >= r.randomElectionTimeout {\n\t\t\tr.handleMsgUp()\n\t\t}\n\n\tcase StateLeader:\n\t\t// todo append retry is 1 logic clock\n\t\t//r.sendMsgToAll(r.sendAppendWrap)\n\t\tif r.heartbeatElapsed == 0 {\n\t\t\tr.sendHeartBeatToAll()\n\t\t}\n\t\tr.heartbeatElapsed = (r.heartbeatElapsed + 1) % r.heartbeatTimeout\n\t}\n\n\t// Your Code Here (2A).\n}" ]
[ "0.5581604", "0.5498568", "0.5405669", "0.5070121", "0.5051444", "0.50203633", "0.4999089", "0.49901783", "0.4933522", "0.49308974", "0.4929331", "0.4919969", "0.49038833", "0.48871338", "0.48802578", "0.48719504", "0.48650056", "0.48559475", "0.48462912", "0.48119715", "0.47915608", "0.47784895", "0.47754917", "0.4758478", "0.4755875", "0.4751962", "0.473532", "0.47081754", "0.47066188", "0.46930018", "0.46891317", "0.46838817", "0.46834046", "0.4683229", "0.46677703", "0.4664518", "0.46642134", "0.46596482", "0.46302247", "0.46259603", "0.46206003", "0.4599367", "0.45922512", "0.45778993", "0.4577848", "0.45674652", "0.4559658", "0.45375112", "0.4530607", "0.45305273", "0.45266476", "0.4521674", "0.45204866", "0.4516398", "0.4503549", "0.45029104", "0.44989234", "0.44975942", "0.44956765", "0.4485251", "0.4476425", "0.44701812", "0.4453696", "0.44506663", "0.44506663", "0.44472614", "0.44469032", "0.4438596", "0.4432753", "0.4432453", "0.44288948", "0.442797", "0.44211337", "0.44196168", "0.44054064", "0.44024536", "0.440161", "0.43955228", "0.43949357", "0.4386932", "0.43850288", "0.4382438", "0.43769345", "0.43743587", "0.4367248", "0.43665332", "0.43629646", "0.43628272", "0.43624556", "0.43612587", "0.43602753", "0.43583834", "0.43574643", "0.4346967", "0.4343296", "0.4341749", "0.43396312", "0.4338137", "0.43378222", "0.43377054" ]
0.70539033
0
TruncateHead remove all records after lastPulse
func (i *IndexDB) TruncateHead(ctx context.Context, from insolar.PulseNumber) error { i.lock.Lock() defer i.lock.Unlock() it := i.db.NewIterator(&indexKey{objID: *insolar.NewID(pulse.MinTimePulse, nil), pn: from}, false) defer it.Close() var hasKeys bool for it.Next() { hasKeys = true key := newIndexKey(it.Key()) err := i.db.Delete(&key) if err != nil { return errors.Wrapf(err, "can't delete key: %+v", key) } inslogger.FromContext(ctx).Debugf("Erased key. Pulse number: %s. ObjectID: %s", key.pn.String(), key.objID.String()) } if !hasKeys { inslogger.FromContext(ctx).Infof("No records. Nothing done. Pulse number: %s", from.String()) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RecordDB) TruncateHead(ctx context.Context, from insolar.PulseNumber) error {\n\n\tif err := r.truncateRecordsHead(ctx, from); err != nil {\n\t\treturn errors.Wrap(err, \"failed to truncate records head\")\n\t}\n\n\tif err := r.truncatePositionRecordHead(ctx, recordPositionKey{pn: from}, recordPositionKeyPrefix); err != nil {\n\t\treturn errors.Wrap(err, \"failed to truncate record positions head\")\n\t}\n\n\tif err := r.truncatePositionRecordHead(ctx, lastKnownRecordPositionKey{pn: from}, lastKnownRecordPositionKeyPrefix); err != nil {\n\t\treturn errors.Wrap(err, \"failed to truncate last known record positions head\")\n\t}\n\n\treturn nil\n}", "func (l *Log) Truncate(lowest uint64) error {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tvar segments []*segment\n\tfor _, s := range l.segments {\n\t\tif s.nextOffset <= lowest+1 {\n\t\t\tif err := s.Remove(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tsegments = append(segments, s)\n\t}\n\tl.segments = segments\n\treturn nil\n}", "func (l *Log) Truncate(lowest uint64) error {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\tvar segments []*segment\n\tfor _, seg := range l.segments {\n\t\tif latestOffset := seg.nextOffset - 1; latestOffset <= lowest {\n\t\t\tif err := seg.Remove(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tsegments = append(segments, seg)\n\t}\n\n\tl.segments = segments\n\n\treturn nil\n}", "func (wal *WAL) TruncateBefore(o Offset) error {\n\tcutoff := sequenceToFilename(o.FileSequence())\n\t_, latestOffset, err := wal.Latest()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to determine latest offset: %v\", err)\n\t}\n\tlatestSequence := latestOffset.FileSequence()\n\treturn wal.forEachSegment(func(file os.FileInfo, first bool, last bool) (bool, error) {\n\t\tif last || file.Name() >= cutoff {\n\t\t\t// Files are sorted by name, if we've gotten past the cutoff or\n\t\t\t// encountered the last (active) file, don't bother continuing.\n\t\t\treturn false, nil\n\t\t}\n\t\tif filenameToSequence(file.Name()) == latestSequence {\n\t\t\t// Don't delete the file containing the latest valid entry\n\t\t\treturn true, nil\n\t\t}\n\t\trmErr := os.Remove(filepath.Join(wal.dir, file.Name()))\n\t\tif rmErr != nil {\n\t\t\treturn false, rmErr\n\t\t}\n\t\twal.log.Debugf(\"Removed WAL file %v\", filepath.Join(wal.dir, file.Name()))\n\t\treturn true, nil\n\t})\n}", "func (b *ChangeBuffer) truncateAfter(e list.Element) {\n\t// We must iterate and remove elements one by one to avoid memory leaks\n\tfirst := e.Next()\n\tfor first != nil {\n\t\tif first.Next() != nil {\n\t\t\tfirst = first.Next()\n\t\t\tb.Remove(first.Prev())\n\t\t} else {\n\t\t\tb.Remove(first)\n\t\t\tfirst = nil\n\t\t}\n\t}\n}", "func (t *BoundedTable) Truncate(ctx context.Context) error {\n\t// just reset everything.\n\tfor i := int64(0); i < t.capacity; i++ {\n\t\tatomic.StorePointer(&t.records[i], unsafe.Pointer(nil))\n\t}\n\tt.cursor = 0\n\treturn nil\n}", "func (rf *Raft) TruncateLog(lastAppliedIndex int) {\n\trf.mu.Lock()\n\tif lastAppliedIndex <= rf.lastApplied && lastAppliedIndex >= rf.Log.LastIncludedLength {\n\t\trf.Log.LastIncludedTerm = rf.Log.Entries[lastAppliedIndex-rf.Log.LastIncludedLength].Term\n\t\trf.Log.Entries = rf.Log.Entries[(lastAppliedIndex - rf.Log.LastIncludedLength + 1):]\n\t\trf.Log.LastIncludedLength = lastAppliedIndex + 1\n\t}\n\trf.mu.Unlock()\n}", "func (r *walReader) truncate(lastOffset int64) error {\n\tr.logger.Log(\"msg\", \"WAL corruption detected; truncating\",\n\t\t\"err\", r.err, \"file\", r.current().Name(), \"pos\", lastOffset)\n\n\t// Close and delete all files after the current one.\n\tfor _, f := range r.wal.files[r.cur+1:] {\n\t\tif err := f.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := os.Remove(f.Name()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tr.wal.files = r.wal.files[:r.cur+1]\n\n\t// Seek the current file to the last valid offset where we continue writing from.\n\t_, err := r.current().Seek(lastOffset, os.SEEK_SET)\n\treturn err\n}", "func (l *Ledger) Truncate(utxovmLastID []byte) error {\n\tl.xlog.Info(\"start truncate ledger\", \"blockid\", utils.F(utxovmLastID))\n\n\t// 获取账本锁\n\tl.mutex.Lock()\n\tdefer l.mutex.Unlock()\n\n\tbatchWrite := l.baseDB.NewBatch()\n\tnewMeta := proto.Clone(l.meta).(*pb.LedgerMeta)\n\tnewMeta.TipBlockid = utxovmLastID\n\n\t// 获取裁剪目标区块信息\n\tblock, err := l.fetchBlock(utxovmLastID)\n\tif err != nil {\n\t\tl.xlog.Warn(\"failed to find utxovm last block\", \"err\", err, \"blockid\", utils.F(utxovmLastID))\n\t\treturn err\n\t}\n\t// 查询分支信息\n\tbranchTips, err := l.GetBranchInfo(block.Blockid, block.Height)\n\tif err != nil {\n\t\tl.xlog.Warn(\"failed to find all branch tips\", \"err\", err)\n\t\treturn err\n\t}\n\n\t// 逐个分支裁剪到目标高度\n\tfor _, branchTip := range branchTips {\n\t\tdeletedBlockid := []byte(branchTip)\n\t\t// 裁剪到目标高度\n\t\terr = l.removeBlocks(deletedBlockid, block.Blockid, batchWrite)\n\t\tif err != nil {\n\t\t\tl.xlog.Warn(\"failed to remove garbage blocks\", \"from\", utils.F(l.meta.TipBlockid),\n\t\t\t\t\"to\", utils.F(block.Blockid))\n\t\t\treturn err\n\t\t}\n\t\t// 更新分支高度信息\n\t\terr = l.updateBranchInfo(block.Blockid, deletedBlockid, block.Height, batchWrite)\n\t\tif err != nil {\n\t\t\tl.xlog.Warn(\"truncate failed when calling updateBranchInfo\", \"err\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tnewMeta.TrunkHeight = block.Height\n\tmetaBuf, err := proto.Marshal(newMeta)\n\tif err != nil {\n\t\tl.xlog.Warn(\"failed to marshal pb meta\")\n\t\treturn err\n\t}\n\tbatchWrite.Put([]byte(pb.MetaTablePrefix), metaBuf)\n\terr = batchWrite.Write()\n\tif err != nil {\n\t\tl.xlog.Warn(\"batch write failed when truncate\", \"err\", err)\n\t\treturn err\n\t}\n\tl.meta = newMeta\n\n\tl.xlog.Info(\"truncate blockid succeed\")\n\treturn nil\n}", "func (t Table) Truncate(ctx context.Context) error {\n\tkeys, err := t.getKeys(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get table keys: %w\", err)\n\t}\n\n\titems, err := t.scan(ctx, keys)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"scan: %w\", err)\n\t}\n\n\tlog.Printf(\"[%s] contains %d items\\n\", t.name, len(items))\n\n\tif err := t.batchDelete(ctx, items); err != nil {\n\t\treturn fmt.Errorf(\"batch delete: %w\", err)\n\t}\n\n\tlog.Printf(\"[%s] complete to truncate table\\n\", t.name)\n\n\treturn nil\n}", "func (b *ChangeBuffer) truncateBefore(e list.Element) {\n\tlast := e.Prev()\n\tfor last != nil {\n\t\tif last.Prev() != nil {\n\t\t\tlast = last.Prev()\n\t\t\tb.Remove(last.Next())\n\t\t} else {\n\t\t\tb.Remove(last)\n\t\t\tlast = nil\n\t\t}\n\t}\n}", "func (snapshots EBSSnapshots) TrimHead(n int) EBSSnapshots {\n\tif n > len(snapshots) {\n\t\treturn EBSSnapshots{}\n\t}\n\treturn snapshots[n:]\n}", "func (seq Sequence) Truncate(width int, resolution time.Duration, asOf time.Time, until time.Time) (result Sequence) {\n\tif len(seq) == 0 {\n\t\treturn nil\n\t}\n\tresult = seq\n\toldUntil := result.Until()\n\tasOf = RoundTimeUntilDown(asOf, resolution, oldUntil)\n\tuntil = RoundTimeUntilDown(until, resolution, oldUntil)\n\n\tif !until.IsZero() {\n\t\tperiodsToRemove := int(oldUntil.Sub(until) / resolution)\n\t\tif periodsToRemove > 0 {\n\t\t\tbytesToRemove := periodsToRemove * width\n\t\t\tif bytesToRemove+Width64bits >= len(seq) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tresult = result[bytesToRemove:]\n\t\t\tresult.SetUntil(until)\n\t\t}\n\t}\n\n\tif !asOf.IsZero() {\n\t\tmaxPeriods := int(result.Until().Sub(asOf) / resolution)\n\t\tif maxPeriods <= 0 {\n\t\t\t// Entire sequence falls outside of truncation range\n\t\t\treturn nil\n\t\t}\n\t\tmaxLength := Width64bits + maxPeriods*width\n\t\tif maxLength >= len(result) {\n\t\t\treturn result\n\t\t}\n\t\treturn result[:maxLength]\n\t}\n\n\treturn result\n}", "func (b *pebbleBucket) DelBeforeTS(ts uint64) error {\n\tstart, end := b.name, keyUpperBound(b.name)\n\titer := b.db.NewIter(b.prefixIterOpts)\n\tfor iter.First(); iter.Valid(); iter.Next() {\n\t\t_, kts := decodeBatchKey(iter.Key(), b.name)\n\t\tif kts > ts {\n\t\t\tend = iter.Key()\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif err := iter.Close(); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\treturn errors.Trace(b.db.DeleteRange(start, end, b.writeOpts))\n}", "func (v *Data) Truncate(l int) {\n\tvar nil PicData\n\tdv := *v\n\tfor i := l; i < len(dv); i++ {\n\t\tdv[i] = nil\n\t}\n\n\t*v = dv[:l]\n}", "func (result *Result) Truncate(l int) *Result {\n\tif l == 0 {\n\t\treturn result\n\t}\n\n\tout := &Result{\n\t\tInsertID: result.InsertID,\n\t\tRowsAffected: result.RowsAffected,\n\t\tInfo: result.Info,\n\t\tSessionStateChanges: result.SessionStateChanges,\n\t}\n\tif result.Fields != nil {\n\t\tout.Fields = result.Fields[:l]\n\t}\n\tif result.Rows != nil {\n\t\tout.Rows = make([][]Value, 0, len(result.Rows))\n\t\tfor _, r := range result.Rows {\n\t\t\tout.Rows = append(out.Rows, r[:l])\n\t\t}\n\t}\n\treturn out\n}", "func Drain(s beam.Scope) {\n\tbeam.Init()\n\ts.Scope(\"truncate\")\n\tbeam.ParDo(s, &TruncateFn{}, beam.Impulse(s))\n}", "func (reader *embedFileReader) Truncate(int64) error {\n\treturn ErrNotAvail\n}", "func TestTiFlashTruncateTable(t *testing.T) {\n\ts, teardown := createTiFlashContext(t)\n\tdefer teardown()\n\ttk := testkit.NewTestKit(t, s.store)\n\n\ttk.MustExec(\"use test\")\n\ttk.MustExec(\"drop table if exists ddltiflashp\")\n\ttk.MustExec(\"create table ddltiflashp(z int not null) partition by range (z) (partition p0 values less than (10), partition p1 values less than (20))\")\n\ttk.MustExec(\"alter table ddltiflashp set tiflash replica 1\")\n\n\ttime.Sleep(ddl.PollTiFlashInterval * RoundToBeAvailablePartitionTable)\n\t// Should get schema right now\n\ttk.MustExec(\"truncate table ddltiflashp\")\n\ttime.Sleep(ddl.PollTiFlashInterval * RoundToBeAvailablePartitionTable)\n\tCheckTableAvailableWithTableName(s.dom, t, 1, []string{}, \"test\", \"ddltiflashp\")\n\ttk.MustExec(\"drop table if exists ddltiflash2\")\n\ttk.MustExec(\"create table ddltiflash2(z int)\")\n\ttk.MustExec(\"alter table ddltiflash2 set tiflash replica 1\")\n\ttime.Sleep(ddl.PollTiFlashInterval * RoundToBeAvailable)\n\t// Should get schema right now\n\n\ttk.MustExec(\"truncate table ddltiflash2\")\n\ttime.Sleep(ddl.PollTiFlashInterval * RoundToBeAvailable)\n\tCheckTableAvailableWithTableName(s.dom, t, 1, []string{}, \"test\", \"ddltiflash2\")\n}", "func (s *Segment) Truncate(offset Offset) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tfor i, c := range s.chunks {\n\t\tif c.Offset().After(offset) {\n\t\t\t// Shrink the current chunk slice.\n\t\t\ts.chunks = s.chunks[i:]\n\n\t\t\t// Adjust the internal read pointer.\n\t\t\tif s.chunkIdx > 0 {\n\t\t\t\ts.chunkIdx -= i + 1\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (w *WAL) cut() error {\n\t// close old wal file; truncate to avoid wasting space if an early cut\n\toff, serr := w.tail().Seek(0, io.SeekCurrent)\n\tif serr != nil {\n\t\treturn serr\n\t}\n\n\tif err := w.tail().Truncate(off); err != nil {\n\t\treturn err\n\t}\n\n\tif err := w.sync(); err != nil {\n\t\treturn err\n\t}\n\n\tfpath := filepath.Join(w.dir, walName(w.seq()+1, w.enti+1))\n\n\t// create a temp wal file with name sequence + 1, or truncate the existing one\n\tnewTail, err := w.fp.Open()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// update writer and save the previous crc\n\tw.locks = append(w.locks, newTail)\n\tprevCrc := w.encoder.crc.Sum32()\n\tw.encoder, err = newFileEncoder(w.tail().File, prevCrc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = w.saveCrc(prevCrc); err != nil {\n\t\treturn err\n\t}\n\n\tif err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {\n\t\treturn err\n\t}\n\n\tif err = w.saveState(&w.state); err != nil {\n\t\treturn err\n\t}\n\n\t// atomically move temp wal file to wal file\n\tif err = w.sync(); err != nil {\n\t\treturn err\n\t}\n\n\toff, err = w.tail().Seek(0, io.SeekCurrent)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = os.Rename(newTail.Name(), fpath); err != nil {\n\t\treturn err\n\t}\n\tstart := time.Now()\n\tif err = fileutil.Fsync(w.dirFile); err != nil {\n\t\treturn err\n\t}\n\twalFsyncSec.Observe(time.Since(start).Seconds())\n\n\t// reopen newTail with its new path so calls to Name() match the wal filename format\n\tnewTail.Close()\n\n\tif newTail, err = fileutil.LockFile(fpath, os.O_WRONLY, fileutil.PrivateFileMode); err != nil {\n\t\treturn err\n\t}\n\tif _, err = newTail.Seek(off, io.SeekStart); err != nil {\n\t\treturn err\n\t}\n\n\tw.locks[len(w.locks)-1] = newTail\n\n\tprevCrc = w.encoder.crc.Sum32()\n\tw.encoder, err = newFileEncoder(w.tail().File, prevCrc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.Infof(fmt.Sprintf(\"created a new WAL segment path:%s\", fpath))\n\treturn nil\n}", "func (p Packet) Truncate() Packet {\n\tmLen := p.Len()\n\tif len(p) > mLen {\n\t\tp = p[:mLen]\n\t}\n\treturn p\n}", "func (p *TimePanel) CutHead(until time.Time) {\n\ti := sort.Search(len(p.dates), func(i int) bool {\n\t\treturn !p.dates[i].Before(until)\n\t})\n\tp.ICutHead(i)\n}", "func (w *fileWAL) truncate() error {\n\treturn w.f.Truncate(w.lastReadOffset)\n}", "func (b *baseKVStoreBatch) truncate(size int) {\n\tb.writeQueue = b.writeQueue[:size]\n}", "func (t *DbService) Truncate(request *TruncateRequest) (*TruncateResponse, error) {\n\trsp := &TruncateResponse{}\n\treturn rsp, t.client.Call(\"db\", \"Truncate\", request, rsp)\n}", "func (list_obj *SortedSeqnoListWithLock) truncateSeqnos(through_seqno uint64) {\n\tlist_obj.lock.Lock()\n\tdefer list_obj.lock.Unlock()\n\tseqno_list := list_obj.seqno_list\n\tindex, found := simple_utils.SearchUint64List(seqno_list, through_seqno)\n\tif found {\n\t\tlist_obj.seqno_list = seqno_list[index+1:]\n\t} else if index > 0 {\n\t\tlist_obj.seqno_list = seqno_list[index:]\n\t}\n}", "func DeleteAfter(t Time, L *list.List) {\n\tif L.Len() == 0 {\n\t\treturn\n\t}\n\tfront := L.Front()\n\tif front.Value.(Elem).GetTime() >= t {\n\t\tL = L.Init()\n\t\treturn\n\t}\nLoop:\n\tfor {\n\t\tel := L.Back()\n\t\tif el.Value.(Elem).GetTime() >= t {\n\t\t\tL.Remove(el)\n\t\t} else {\n\t\t\tbreak Loop\n\t\t}\n\t}\n}", "func (w *SegmentWAL) cut() error {\n\t// Sync current tail to disk and close.\n\tif tf := w.tail(); tf != nil {\n\t\tif err := w.sync(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\toff, err := tf.Seek(0, os.SEEK_CUR)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := tf.Truncate(off); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := tf.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tp, _, err := nextSequenceFile(w.dirFile.Name(), \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tf, err := os.Create(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = fileutil.Preallocate(f, w.segmentSize, true); err != nil {\n\t\treturn err\n\t}\n\tif err = w.dirFile.Sync(); err != nil {\n\t\treturn err\n\t}\n\n\t// Write header metadata for new file.\n\tmetab := make([]byte, 8)\n\tbinary.BigEndian.PutUint32(metab[:4], WALMagic)\n\tmetab[4] = WALFormatDefault\n\n\tif _, err := f.Write(metab); err != nil {\n\t\treturn err\n\t}\n\n\tw.files = append(w.files, f)\n\tw.cur = bufio.NewWriterSize(f, 4*1024*1024)\n\tw.curN = 8\n\n\treturn nil\n}", "func (t *Token) TruncateStart() *Token {\n\trtn := t.Prev\n\tt.Prev = nil\n\tif rtn != nil {\n\t\trtn.Next = nil\n\t}\n\treturn rtn\n}", "func (records Records) Cleaned() Records {\n\trecordsCount := len(records)\n\tif recordsCount == 0 {\n\t\treturn records\n\t}\n\n\tif recordsCount == 1 {\n\t\tr := records[0]\n\t\tif r.Duration == 0 {\n\t\t\tr.Duration = DefaultMeetDuration\n\t\t}\n\n\t\treturn records\n\t}\n\n\tsort.Sort(OrderByDate(records))\n\n\treturn fixDuration(recordsCount, records)\n}", "func (kv *fazzRedis) Truncate() error {\n\treturn kv.client.FlushAll().Err()\n}", "func (db *DB) Truncate() {\n\tfor _, table := range []string{\"archives\", \"transforms\"} {\n\t\t_, err := db.Exec(fmt.Sprintf(\"DELETE FROM %s\", table))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (wal *WAL) TruncateBeforeTime(ts time.Time) error {\n\treturn wal.TruncateBefore(NewOffset(tsToFileSequence(ts), 0))\n}", "func (p *CassandraClient) Truncate(cfname string) (err error) {\n\tif err = p.sendTruncate(cfname); err != nil {\n\t\treturn\n\t}\n\treturn p.recvTruncate()\n}", "func (kv *fazzRedis) Truncate(ctx context.Context) error {\n\treturn kv.client.FlushAll(ctx).Err()\n}", "func (ttruo *TradeTimeRangeUpdateOne) ClearRecords() *TradeTimeRangeUpdateOne {\n\tttruo.mutation.ClearRecords()\n\treturn ttruo\n}", "func (m *mergeWithTimestampsType) Flush() {\n\ttsLen := len(m.timestamps)\n\tif !m.lastRecordSet {\n\t\treturn\n\t}\n\tfor m.timestampIdx < tsLen {\n\t\tm.lastRecord.TimeStamp = m.timestamps[m.timestampIdx]\n\t\tif !m.wrapped.Append(&m.lastRecord) {\n\t\t\treturn\n\t\t}\n\t\tm.timestampIdx++\n\t}\n}", "func (b *ringBuf) truncateFrom(lo uint64) (removedBytes, removedEntries int32) {\n\tit, ok := iterateFrom(b, lo)\n\tfor ok {\n\t\tremovedBytes += int32(it.entry(b).Size())\n\t\tremovedEntries++\n\t\tit.clear(b)\n\t\tit, ok = it.next(b)\n\t}\n\tb.len -= int(removedEntries)\n\tif b.len < (len(b.buf) / shrinkThreshold) {\n\t\trealloc(b, 0, b.len)\n\t}\n\treturn\n}", "func (t *Track) Clean() {\n\tfor i := 0; i < len(t.samples); i++ {\n\t\tt.samples[i] = nil\n\t}\n\tt.samples = t.samples[:0]\n\tt.samples = nil\n}", "func (s *MemStorage) deleteBefore(channelID string, t int64) error {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tevents, ok := s.events[channelID]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\ti := positionGt(events, t)\n\tif i >= 0 {\n\t\tl := len(events[i:])\n\t\tc := defaultChannelLength\n\t\tif l > c {\n\t\t\tc = l\n\t\t}\n\t\ttruncated := make([]Event, l, c)\n\t\tcopy(truncated, events[i:])\n\t\ts.events[channelID] = truncated\n\t}\n\n\treturn nil\n}", "func (t Timestamp) Truncate(d Duration) Timestamp {\n\tif d <= 0 {\n\t\treturn t\n\t}\n\treturn t.Add(-Duration(int64(t) % int64(d)))\n}", "func (h *atomicHeadTailIndex) decHead() headTailIndex {\n\treturn headTailIndex(h.u.Add(-(1 << 32)))\n}", "func RemoveLastElemFromTop(c *gin.Context) { dequeueTop([]qMessage{}) }", "func (sb *SeekableBuffer) Truncate(size int64) (err error) {\n\tdefer func() {\n\t\tif state := recover(); state != nil {\n\t\t\terr = state.(error)\n\t\t}\n\t}()\n\n\tsizeInt := int(size)\n\tif sizeInt < len(sb.data)-1 {\n\t\tsb.data = sb.data[:sizeInt]\n\t} else {\n\t\tnew := make([]byte, sizeInt-len(sb.data))\n\t\tsb.data = append(sb.data, new...)\n\t}\n\n\treturn nil\n\n}", "func (ls *linestate) deleteToEnd() {\n\tls.buf = ls.buf[:ls.pos]\n\tls.refreshLine()\n}", "func (m *Mantle) truncatedMidGap() uint64 {\n\tmidGap := midGap(m.book(), rateStep)\n\treturn truncate(int64(midGap), int64(rateStep))\n}", "func (rf *Raft) cutoffLogBeforeIndex(lastLogIndex int, lastLogTerm int) {\n DISPrintf(\"Start to cut off server(%d) log. lastLogIndex=%d, lastLogfTerm=%d, before cut off its len(log)=%d\", rf.me, lastLogIndex, lastLogTerm, len(rf.log))\n if lastLogIndex >= len(rf.log) {\n rf.log = make([]Entry, 1, 100)\n rf.log[0].Term = lastLogTerm\n }else if rf.convertToGlobalViewIndex(lastLogIndex) <= rf.commitIndex {\n rf.log = rf.log[lastLogIndex:]\n DISPrintf(\"Cut off server(%d) log success and now its len(log)=%d\", rf.me, len(rf.log))\n }\n}", "func (d PacketData) TrimFront(count int) {\n\tif count > d.Size() {\n\t\tcount = d.Size()\n\t}\n\tbuf := d.pk.Data().ToBuffer()\n\tbuf.TrimFront(int64(count))\n\td.pk.buf.Truncate(int64(d.pk.dataOffset()))\n\td.pk.buf.Merge(&buf)\n}", "func Truncate() {\n\tfmt.Println(\"----------------> Truncate\")\n\n\tbuf := bytes.NewBufferString(\"hello\")\n\n\t//buf=hello\n\tfmt.Println(buf.String())\n\n\tbuf.Truncate(3)\n\t//buf=hel\n\tfmt.Println(buf.String())\n\n\tbuf.Truncate(2)\n\t//buf=he\n\tfmt.Println(buf.String())\n\n\tbuf.Truncate(0)\n\t//buf=\n\tfmt.Println(buf.String())\n}", "func (h *atomicHeadTailIndex) reset() {\n\th.u.Store(0)\n}", "func (sd *SelectDataset) Truncate() *TruncateDataset {\n\ttd := newTruncateDataset(sd.dialect.Dialect(), sd.queryFactory)\n\tif sd.clauses.HasSources() {\n\t\ttd = td.Table(sd.clauses.From())\n\t}\n\treturn td\n}", "func TestTiFlashTruncatePartition(t *testing.T) {\n\ts, teardown := createTiFlashContext(t)\n\tdefer teardown()\n\ttk := testkit.NewTestKit(t, s.store)\n\n\ttk.MustExec(\"use test\")\n\ttk.MustExec(\"drop table if exists ddltiflash\")\n\ttk.MustExec(\"create table ddltiflash(i int not null, s varchar(255)) partition by range (i) (partition p0 values less than (10), partition p1 values less than (20))\")\n\ttk.MustExec(\"alter table ddltiflash set tiflash replica 1\")\n\ttime.Sleep(ddl.PollTiFlashInterval * RoundToBeAvailablePartitionTable)\n\ttk.MustExec(\"insert into ddltiflash values(1, 'abc'), (11, 'def')\")\n\ttk.MustExec(\"alter table ddltiflash truncate partition p1\")\n\ttime.Sleep(ddl.PollTiFlashInterval * RoundToBeAvailablePartitionTable)\n\tCheckTableAvailableWithTableName(s.dom, t, 1, []string{}, \"test\", \"ddltiflash\")\n}", "func (t *Token) TruncateEnd() *Token {\n\trtn := t.Next\n\tt.Next = nil\n\tif rtn != nil {\n\t\trtn.Prev = nil\n\t}\n\treturn rtn\n}", "func (res Responder) Truncate(n int) {\n\tres.b.Truncate(n)\n}", "func DeleteBefore(t Time, L *list.List) {\n\tif L.Len() == 0 {\n\t\treturn\n\t}\n\tback := L.Back()\n\tif back.Value.(Elem).GetTime() <= t {\n\t\tL = L.Init()\n\t\treturn\n\t}\nLoop:\n\tfor {\n\t\tel := L.Front()\n\t\tif el.Value.(Elem).GetTime() <= t {\n\t\t\tL.Remove(el)\n\t\t} else {\n\t\t\tbreak Loop\n\t\t}\n\t}\n}", "func (s *Srt) TrimTo(ms uint32) int {\n\tvar deleted int = 0\n\ts.ForEach(func(_ int, sub *Subtitle) bool {\n\t\tif sub.StartMs < ms {\n\t\t\tsub.MarkAsDeleted()\n\t\t\tdeleted++\n\t\t\ts.count--\n\t\t\treturn true\n\t\t}\n\t\tsub.StartMs -= ms\n\t\tsub.EndMs -= ms\n\t\treturn true\n\t})\n\treturn deleted\n}", "func (cp *ChangeLog) TruncateTo(maxLength int) int {\n\tif remove := len(cp.Entries) - maxLength; remove > 0 {\n\t\t// Set Since to the max of the sequences being removed:\n\t\tfor _, entry := range cp.Entries[0:remove] {\n\t\t\tif entry.Sequence > cp.Since {\n\t\t\t\tcp.Since = entry.Sequence\n\t\t\t}\n\t\t}\n\t\t// Copy entries into a new array to avoid leaving the entire old array in memory:\n\t\tnewEntries := make([]*LogEntry, maxLength)\n\t\tcopy(newEntries, cp.Entries[remove:])\n\t\tcp.Entries = newEntries\n\t\treturn remove\n\t}\n\treturn 0\n}", "func (sa *SuffixArray) Truncate(length uint64) error { return sa.ba.Truncate(length) }", "func (log *LogFile) updateHeadTail() error {\n\t// where are we in the log data file?\n\toffset, err := log.getWritePos()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\tif log.wrapNum == 0 {\n\t\t// if we haven't wrapped yet then gradually increase numSizeBytes\n\t\tlog.numSizeBytes = uint64(offset)\n\t\tstdlog.Printf(\"On 1st lap, increase numSizeBytes=%v\", log.numSizeBytes)\n\t}\n\n\t// point to offset in the data file where the next log entry is due to go\n\t// it is not written there yet but will be there when we next write it\n\tlog.headOffset = uint64(offset)\n\n\tstdlog.Printf(\"Update head %v and tail %v\\n\", log.headOffset, log.tailOffset)\n\tdata := metaData{HeadOffset: log.headOffset, TailOffset: log.tailOffset, MaxSizeBytes: log.maxSizeBytes, \n\t\tNumSizeBytes: log.numSizeBytes, WrapNum: log.wrapNum, NumEntries: log.NumEntries}\n\treturn log.writeMetaData(data)\n}", "func (c *Collection) removeBefore(t time.Time) error {\n\tif c == nil {\n\t\treturn errors.New(\"Collection.removeBefore: c == nil\")\n\t}\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tcLen := len(c.collection)\n\tif cLen == 0 {\n\t\treturn nil // we have a collection but no data\n\t}\n\t// remove old data here.\n\tfirst := 0\n\tdone := false\n\tfor !done {\n\t\tif c.collection[first].When().Before(t) {\n\t\t\tfirst++\n\t\t\tif first == cLen {\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\tfirst--\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// get the interval we need.\n\tif first == len(c.collection) {\n\t\tc.collection = nil // remove all entries\n\t} else if first != -1 {\n\t\tc.collection = c.collection[first:]\n\t}\n\treturn nil // no errors\n}", "func (r *Repairer) Truncate(part uint64, size int64) error {\n\tp := partitionFullPath(r.conf, r.topic, part)\n\treturn os.Truncate(p, size)\n}", "func deleteRecordFromSlice(slice []Record, id int) []Record {\n return append(slice[:id], slice[id+1:]...)\n}", "func (ingest *Ingestion) Clear(start int64, end int64) error {\n\tclear := ingest.DB.DeleteRange\n\n\terr := clear(start, end, \"history_effects\", \"history_operation_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_operation_participants\", \"history_operation_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_operations\", \"id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_transaction_participants\", \"history_transaction_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_transactions\", \"id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_ledgers\", \"id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = clear(start, end, \"history_trades\", \"history_operation_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (w *Writer) ZeroUntil(index int64)", "func (h *Queue) TrimTail(distance types.Distance) {\n\tif !h.trimSet || (h.trimValue > distance) {\n\t\th.trimSet = true\n\t\th.trimValue = distance\n\t}\n}", "func (t *Track) CleanForLive() {\n\tif len(t.chunksDuration) > t.chunksDepth {\n\t\tt.chunksDuration = t.chunksDuration[len(t.chunksDuration) - (t.chunksDepth + 1):]\n\t}\n\tif len(t.chunksSize) > t.chunksDepth {\n\t\tt.chunksSize = t.chunksSize[len(t.chunksSize) - (t.chunksDepth + 1):]\n\t}\n\tif len(t.chunksName) > t.chunksDepth {\n\t\tt.chunksName = t.chunksName[len(t.chunksName) - (t.chunksDepth + 1):]\n\t}\n}", "func (ttru *TradeTimeRangeUpdate) ClearRecords() *TradeTimeRangeUpdate {\n\tttru.mutation.ClearRecords()\n\treturn ttru\n}", "func (list_obj *DualSortedSeqnoListWithLock) truncateSeqnos(through_seqno uint64) {\n\tlist_obj.lock.Lock()\n\tdefer list_obj.lock.Unlock()\n\n\tlist_obj.seqno_list_1 = truncateGapSeqnoList(through_seqno, list_obj.seqno_list_1)\n\tlist_obj.seqno_list_2 = truncateGapSeqnoList(through_seqno, list_obj.seqno_list_2)\n}", "func (truo *TradeRecordUpdateOne) ClearTimeRange() *TradeRecordUpdateOne {\n\ttruo.mutation.ClearTimeRange()\n\treturn truo\n}", "func (s *streamKey) trimBefore(id string) int {\n\ts.mu.Lock()\n\tvar delete []string\n\tfor _, entry := range s.entries {\n\t\tif entry.ID < id {\n\t\t\tdelete = append(delete, entry.ID)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\ts.mu.Unlock()\n\ts.delete(delete)\n\treturn len(delete)\n}", "func Truncate(name string, size int64) error", "func (e *Execution) purge(threshold uint64) {\n\tfor blockID, record := range e.records {\n\t\tif record.Block.Header.Height < threshold {\n\t\t\tdelete(e.records, blockID)\n\t\t}\n\t}\n}", "func TestHandleLogTruncate(t *testing.T) {\n\tt.Skip(\"flaky\")\n\tta, lines, w, fs, dir := makeTestTailReal(t, \"trunc\")\n\tdefer os.RemoveAll(dir) // clean up\n\n\tlogfile := filepath.Join(dir, \"log\")\n\tf, err := fs.Create(logfile)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tresult := []*LogLine{}\n\tdone := make(chan struct{})\n\twg := sync.WaitGroup{}\n\tgo func() {\n\t\tfor line := range lines {\n\t\t\tresult = append(result, line)\n\t\t\twg.Done()\n\t\t}\n\t\tclose(done)\n\t}()\n\n\terr = ta.TailPath(logfile)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t_, err = f.WriteString(\"a\\nb\\nc\\n\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\twg.Add(3)\n\twg.Wait()\n\n\terr = f.Truncate(0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// This is potentially racy. Unlike in the case where we've got new\n\t// lines that we can verify were seen with the WaitGroup, here nothing\n\t// ensures that this update-due-to-truncate is seen by the Tailer before\n\t// we write new data to the file. In order to avoid the race we'll make\n\t// sure that the total data size written post-truncate is less than\n\t// pre-truncate, so that the post-truncate offset is always smaller\n\t// than the offset seen after wg.Add(3); wg.Wait() above.\n\n\t_, err = f.WriteString(\"d\\ne\\n\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\twg.Add(2)\n\n\t// ugh\n\twg.Wait()\n\tw.Close()\n\t<-done\n\n\texpected := []*LogLine{\n\t\t{logfile, \"a\"},\n\t\t{logfile, \"b\"},\n\t\t{logfile, \"c\"},\n\t\t{logfile, \"d\"},\n\t\t{logfile, \"e\"},\n\t}\n\tif diff := cmp.Diff(expected, result); diff != \"\" {\n\t\tt.Errorf(\"result didn't match:\\n%s\", diff)\n\t}\n}", "func (adapter *GORMAdapter) TruncateTable(entity interface{}) orm.Result {\n\treturn orm.Result{\n\t\tError: adapter.db.Delete(entity).Error,\n\t}\n}", "func (o *LargeObject) Truncate(size int64) (err error) {\n\t_, err = o.tx.Exec(o.ctx, \"select lo_truncate64($1, $2)\", o.fd, size)\n\treturn err\n}", "func StopLeading() {\n\tif intLeader == config.Id() {\n\t\tlastLeader = time.Now()\n\t}\n}", "func (repo *Repository) Truncate() error {\n\treturn repo.db.Delete(v1.Badge{}).Error\n}", "func (t *timeDataType) Truncate(d time.Duration) *timeDataType {\n\treturn t.Formatter(func(t time.Time) time.Time {\n\t\treturn t.Truncate(d)\n\t})\n}", "func TruncateEncodedChangeLog(r *bytes.Reader, maxLength, minLength int, w io.Writer) (removed int, newLength int) {\n\tsince := readSequence(r)\n\t// Find the starting position and sequence of each entry:\n\tentryPos := make([]int64, 0, 1000)\n\tentrySeq := make([]uint64, 0, 1000)\n\tfor {\n\t\tpos, err := r.Seek(0, 1)\n\t\tif err != nil {\n\t\t\tpanic(\"Seek??\")\n\t\t}\n\t\tflags, err := r.ReadByte()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak // eof\n\t\t\t}\n\t\t\tpanic(\"ReadByte failed\")\n\t\t}\n\t\tseq := readSequence(r)\n\t\tskipString(r)\n\t\tskipString(r)\n\t\tskipString(r)\n\t\tif flags > kMaxFlag {\n\t\t\tpanic(fmt.Sprintf(\"TruncateEncodedChangeLog: bad flags 0x%x, entry %d, offset %d\",\n\t\t\t\tflags, len(entryPos), pos))\n\t\t}\n\n\t\tentryPos = append(entryPos, pos)\n\t\tentrySeq = append(entrySeq, seq)\n\t}\n\n\t// How many entries to remove?\n\t// * Leave no more than maxLength entries\n\t// * Every sequence value removed should be less than every sequence remaining.\n\t// * The new 'since' value should be the maximum sequence removed.\n\toldLength := len(entryPos)\n\tremoved = oldLength - maxLength\n\tif removed <= 0 {\n\t\tremoved = 0\n\t} else {\n\t\tpivot, newSince := findPivot(entrySeq, removed-1)\n\t\tremoved = pivot + 1\n\t\tif oldLength-removed >= minLength {\n\t\t\tsince = newSince\n\t\t} else {\n\t\t\tremoved = 0\n\t\t\tbase.Warn(\"TruncateEncodedChangeLog: Couldn't find a safe place to truncate\")\n\t\t\t//TODO: Possibly find a pivot earlier than desired?\n\t\t}\n\t}\n\n\t// Write the updated Since and the remaining entries:\n\twriteSequence(since, w)\n\tif _, err := r.Seek(entryPos[removed], 0); err != nil {\n\t\tpanic(\"Seek back???\")\n\t}\n\tif _, err := io.Copy(w, r); err != nil {\n\t\tpanic(\"Copy???\")\n\t}\n\treturn removed, oldLength - removed\n}", "func (w *Wrapper) cleanBefore() {\n\tw.LastInsertID = 0\n\tw.LastResult = nil\n\tw.LastParams = []interface{}{}\n\tw.count = 0\n}", "func (s *Srt) Cut(start, end uint32) int {\n\tvar deleted int = 0\n\tduration := end - start\n\ts.ForEach(func(_ int, sub *Subtitle) bool {\n\t\tif sub.StartMs >= start && sub.StartMs < end {\n\t\t\tsub.MarkAsDeleted()\n\t\t\ts.count--\n\t\t\tdeleted++\n\t\t} else if sub.StartMs >= end {\n\t\t\tsub.StartMs -= duration\n\t\t\tsub.EndMs -= duration\n\t\t}\n\t\treturn true\n\t})\n\treturn deleted\n}", "func (l *FSList) TruncFilter() {\n\tfl := len(l.Filter)\n\tif fl <= 0 {\n\t\treturn\n\t}\n\tl.Filter = l.Filter[:fl-1]\n}", "func (l *LookupOscillator) BatchTruncateTick(freq float64, nframes int) []float64 {\n\tout := make([]float64, nframes)\n\tfor i := 0; i < nframes; i++ {\n\t\tindex := l.curphase\n\t\tif l.curfreq != freq {\n\t\t\tl.curfreq = freq\n\t\t\tl.incr = l.SizeOverSr * l.curfreq\n\t\t}\n\t\tcurphase := l.curphase\n\t\tcurphase += l.incr\n\t\tfor curphase > float64(Len(l.Table)) {\n\t\t\tcurphase -= float64(Len(l.Table))\n\t\t}\n\t\tfor curphase < 0.0 {\n\t\t\tcurphase += float64(Len(l.Table))\n\t\t}\n\t\tl.curphase = curphase\n\t\tout[i] = l.Table.data[int(index)]\n\t}\n\treturn out\n}", "func removeLines(fn string, start, n int) (err error) {\n\tlogs.INFO.Println(\"Clear file -> \", fn)\n\tif n < 0 {\n\t\tn = store.getLines()\n\t}\n\tif n == 0 {\n\t\tlogs.INFO.Println(\"Nothing to clear\")\n\t\tseek = 0\n\t\treturn nil\n\t}\n\tlogs.INFO.Println(\"Total lines -> \", n)\n\tif start < 1 {\n\t\tlogs.WARNING.Println(\"Invalid request. line numbers start at 1.\")\n\t}\n\tvar f *os.File\n\tif f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {\n\t\tlogs.CRITICAL.Println(\"Failed to open the file -> \", err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif cErr := f.Close(); err == nil {\n\t\t\terr = cErr\n\t\t}\n\t}()\n\tvar b []byte\n\tif b, err = ioutil.ReadAll(f); err != nil {\n\t\tlogs.CRITICAL.Println(\"Failed to reading the file -> \", err)\n\t\treturn\n\t}\n\tcut, ok := skip(b, start-1)\n\tif !ok {\n\t\tlogs.CRITICAL.Printf(\"less than %d lines -> \", start)\n\t\treturn\n\t}\n\tif n == 0 {\n\t\treturn nil\n\t}\n\ttail, ok := skip(cut, n)\n\tif !ok {\n\t\tlogs.CRITICAL.Printf(\"less than %d lines after line %d \", n, start)\n\t\treturn\n\t}\n\tt := int64(len(b) - len(cut))\n\tif err = f.Truncate(t); err != nil {\n\t\treturn\n\t}\n\t// Writing in the archive the bytes already with cut removed\n\tif len(tail) > 0 {\n\t\t_, err = f.WriteAt(tail, t)\n\t}\n\treturn\n}", "func (r *Reader) Unlimit() {\n\tr.newLimit <- nil\n}", "func santizeMetaData(h Heartbeat) Heartbeat {\n\th.CursorPosition = nil\n\th.Dependencies = nil\n\th.LineNumber = nil\n\th.Lines = nil\n\n\treturn h\n}", "func (s *streamKey) after(id string) []StreamEntry {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tpos := sort.Search(len(s.entries), func(i int) bool {\n\t\treturn streamCmp(id, s.entries[i].ID) < 0\n\t})\n\treturn s.entries[pos:]\n}", "func historyDelete(splited []string, length int) {\n if length == 2 {\n connect.DeleteGlobalMessages()\n return\n }\n connect.DeleteLocalMessages(splited[2:])\n}", "func (rso *RadosStripedObject) Truncate(size int64) (err error) {\n\n\tobj := C.CString(rso.ObjectName)\n\tdefer C.free(unsafe.Pointer(obj))\n\tc_size := C.uint64_t(size)\n\tret, err := C.rados_striper_trunc(rso.Ioctx, obj, c_size)\n\tif ret < 0 {\n\t\treturn err\n\t} else {\n\t\treturn nil\n\t}\n\treturn\n}", "func (mlog *MemoryLogStorage) TruncateMessages(index int64) error {\n\tlocalIndex := index - 1\n\tif localIndex < 0 {\n\t\treturn nil\n\t}\n\tif localIndex >= int64(len(mlog.offsets)) {\n\t\treturn nil\n\t}\n\tshrinkTo := mlog.offsets[localIndex]\n\tmlog.data = mlog.data[:shrinkTo]\n\tmlog.offsets = mlog.offsets[:localIndex]\n\treturn nil\n}", "func (recorder *TrxHistoryRecorder) Clean() {\n\trecorder.summaries.cache = list.New()\n}", "func (u *GameServerUpsertOne) ClearLastContactAt() *GameServerUpsertOne {\n\treturn u.Update(func(s *GameServerUpsert) {\n\t\ts.ClearLastContactAt()\n\t})\n}", "func (puo *PatientrecordUpdateOne) ClearMedicalrecordstaff() *PatientrecordUpdateOne {\n\tpuo.mutation.ClearMedicalrecordstaff()\n\treturn puo\n}", "func (huo *HistorytakingUpdateOne) ClearPatientrecord() *HistorytakingUpdateOne {\n\thuo.mutation.ClearPatientrecord()\n\treturn huo\n}", "func (v *Data) Clear() {\n\tv.Truncate(0)\n}", "func (t *OplogTailer) tail() error {\n\tvar iter *mgo.Iter\n\tlastTs := t.InitialTs\n\n\t// Stores the unique op IDs that have been reported for lastTs\n\t// (keeps us from re-reporting oplog entries when we restart the iterator)\n\t// Note that timestamps are only unique for a given mongod, so if there are\n\t// multiple replicaset members there may be multiple oplog entries for a given ts.\n\tvar hidsForLastTs []int64\n\n\tfor {\n\t\tif iter == nil {\n\t\t\t// If we recreate the iterator (e.g. if the cursor's been invalidated)\n\t\t\t// need to move up ts to avoid reporting entries that have already been processed.\n\t\t\tsel := append(t.baseQuery,\n\t\t\t\tbson.DocElem{\n\t\t\t\t\tName: \"ts\",\n\t\t\t\t\tValue: []bson.DocElem{\n\t\t\t\t\t\tbson.DocElem{\n\t\t\t\t\t\t\tName: \"$gte\",\n\t\t\t\t\t\t\tValue: lastTs,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tbson.DocElem{\n\t\t\t\t\tName: \"h\",\n\t\t\t\t\tValue: []bson.DocElem{\n\t\t\t\t\t\tbson.DocElem{\n\t\t\t\t\t\t\tName: \"$nin\",\n\t\t\t\t\t\t\tValue: hidsForLastTs,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t)\n\t\t\t// Ref: https://github.com/go-mgo/mgo/issues/121\n\t\t\tquery := t.coll.Find(sel)\n\t\t\tquery = query.LogReplay()\n\t\t\titer = query.Tail(tailTimeout)\n\t\t}\n\n\t\tvar o OplogDoc\n\t\tif iter.Next(&o) {\n\t\t\tselect {\n\t\t\tcase <-t.DoneChan:\n\t\t\t\titer.Close()\n\t\t\t\treturn nil\n\t\t\tcase t.OutChan <- &o:\n\t\t\t}\n\n\t\t\tif o.Timestamp > lastTs {\n\t\t\t\tlastTs = o.Timestamp\n\t\t\t\thidsForLastTs = nil\n\t\t\t}\n\t\t\thidsForLastTs = append(hidsForLastTs, o.HistoryID)\n\t\t} else {\n\t\t\terr := iter.Err()\n\t\t\tif err != nil && err != mgo.ErrCursor {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif iter.Timeout() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\titer = nil\n\t\t}\n\t}\n}", "func TestTableTruncate(t *testing.T) {\n\tt.Run(\"Should succeed if table empty\", func(t *testing.T) {\n\t\ttb, cleanup := newTestTable(t)\n\t\tdefer cleanup()\n\n\t\terr := tb.Truncate()\n\t\tassert.NoError(t, err)\n\t})\n\n\tt.Run(\"Should truncate the table\", func(t *testing.T) {\n\t\ttb, cleanup := newTestTable(t)\n\t\tdefer cleanup()\n\n\t\t// create two documents\n\t\tdoc1 := newDocument()\n\t\tdoc2 := newDocument()\n\n\t\t_, err := tb.Insert(doc1)\n\t\tassert.NoError(t, err)\n\t\t_, err = tb.Insert(doc2)\n\t\tassert.NoError(t, err)\n\n\t\terr = tb.Truncate()\n\t\tassert.NoError(t, err)\n\n\t\terr = tb.Iterate(func(_ types.Document) error {\n\t\t\treturn errors.New(\"should not iterate\")\n\t\t})\n\n\t\tassert.NoError(t, err)\n\t})\n}", "func DBTruncateTable(tableName string) error {\n\t_, err := r.Table(tableName).Delete().RunWrite(dbSession)\n\treturn err\n}", "func (tbl DbCompoundTable) Truncate(force bool) (err error) {\n\tfor _, query := range tbl.Dialect().TruncateDDL(tbl.Name().String(), force) {\n\t\t_, err = support.Exec(tbl, nil, query)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.75272435", "0.5956599", "0.58818066", "0.585593", "0.58506346", "0.5821484", "0.5794194", "0.57208204", "0.5657627", "0.5587941", "0.5498917", "0.5479526", "0.54287946", "0.5406762", "0.5404167", "0.53492576", "0.5343496", "0.5339121", "0.5239251", "0.5235306", "0.5232906", "0.52215016", "0.5213665", "0.5213078", "0.5200276", "0.5176488", "0.51560533", "0.51273155", "0.5122654", "0.50931406", "0.5082012", "0.50809705", "0.5079536", "0.50758994", "0.5061221", "0.50609624", "0.5041504", "0.5038606", "0.50150615", "0.5014168", "0.49962378", "0.49859872", "0.4984931", "0.4961818", "0.49604577", "0.49461606", "0.49413916", "0.4934312", "0.49289784", "0.49163857", "0.49135834", "0.4901754", "0.4900632", "0.48892853", "0.48860374", "0.48830396", "0.4878303", "0.48769155", "0.4876805", "0.48753673", "0.48642826", "0.48244143", "0.4820448", "0.48005807", "0.47937715", "0.47880962", "0.4787568", "0.477581", "0.4772108", "0.4770148", "0.4766963", "0.47525725", "0.47519445", "0.47325063", "0.47301304", "0.47223702", "0.47099125", "0.47055155", "0.47053748", "0.47004798", "0.46947062", "0.4694497", "0.46873197", "0.46718177", "0.466577", "0.46621916", "0.46593618", "0.46506092", "0.4644383", "0.46399528", "0.4638034", "0.46341556", "0.46341428", "0.4622324", "0.46111473", "0.46068898", "0.4606541", "0.46061173", "0.46051505", "0.45949656" ]
0.7663238
0
ForID returns a lifeline from a bucket with provided PN and ObjID
func (i *IndexDB) ForID(ctx context.Context, pn insolar.PulseNumber, objID insolar.ID) (record.Index, error) { var buck *record.Index buck, err := i.getBucket(pn, objID) if err == ErrIndexNotFound { lastPN, err := i.getLastKnownPN(objID) if err != nil { return record.Index{}, ErrIndexNotFound } buck, err = i.getBucket(lastPN, objID) if err != nil { return record.Index{}, err } } else if err != nil { return record.Index{}, err } return *buck, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Storage) GetLifeline(objRef []byte, fromIndex *string, pulseNumberLt, pulseNumberGt, timestampLte, timestampGte *int64, limit, offset int, sortByIndexAsc bool) ([]models.Record, int, error) {\n\ttimer := prometheus.NewTimer(GetLifelineDuration)\n\tdefer timer.ObserveDuration()\n\n\tquery := s.db.Model(&models.Record{}).Where(\"object_reference = ?\", objRef).Where(\"type = ?\", models.State)\n\n\tquery = filterByPulse(query, pulseNumberLt, pulseNumberGt)\n\n\tquery = filterByTimestamp(query, timestampLte, timestampGte)\n\n\tvar err error\n\tif fromIndex != nil {\n\t\tquery, err = filterRecordsByIndex(query, *fromIndex, sortByIndexAsc)\n\t\tif err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t}\n\n\tquery = sortRecordsByDirection(query, sortByIndexAsc)\n\n\trecords, total, err := getRecords(query, limit, offset)\n\tif err != nil {\n\t\treturn nil, 0, errors.Wrapf(err, \"error while select records for object %v from db\", objRef)\n\t}\n\treturn records, total, nil\n}", "func (hp *hdfsProvider) GetObj(ctx context.Context, lom *cluster.LOM, owt cmn.OWT) (errCode int, err error) {\n\treader, _, errCode, err := hp.GetObjReader(ctx, lom)\n\tif err != nil {\n\t\treturn errCode, err\n\t}\n\tparams := cluster.AllocPutObjParams()\n\t{\n\t\tparams.WorkTag = fs.WorkfileColdget\n\t\tparams.Reader = reader\n\t\tparams.OWT = owt\n\t\tparams.Atime = time.Now()\n\t}\n\tif err = hp.t.PutObject(lom, params); err != nil {\n\t\treturn\n\t}\n\tif verbose {\n\t\tnlog.Infof(\"[get_object] %s\", lom)\n\t}\n\treturn\n}", "func hostGetObjectId(objId int32, keyId int32, typeId int32) int32", "func (o *Object) ID() string {\n\treturn o.BucketName + \"/\" + o.Name\n}", "func (t *targetrunner) httpobjget(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\tconfig = cmn.GCO.Get()\n\t\tquery = r.URL.Query()\n\t\tisGFNRequest = cmn.IsParseBool(query.Get(cmn.URLParamIsGFNRequest))\n\t)\n\tapiItems, err := t.checkRESTItems(w, r, 2, false, cmn.Version, cmn.Objects)\n\tif err != nil {\n\t\treturn\n\t}\n\tbucket, objName := apiItems[0], apiItems[1]\n\tstarted := time.Now()\n\tif redirDelta := t.redirectLatency(started, query); redirDelta != 0 {\n\t\tt.statsT.Add(stats.GetRedirLatency, redirDelta)\n\t}\n\trangeOff, rangeLen, err := t.offsetAndLength(query)\n\tif err != nil {\n\t\tt.invalmsghdlr(w, r, err.Error())\n\t\treturn\n\t}\n\tbck, err := newBckFromQuery(bucket, r.URL.Query())\n\tif err != nil {\n\t\tt.invalmsghdlr(w, r, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tlom := &cluster.LOM{T: t, ObjName: objName}\n\tif err = lom.Init(bck.Bck, config); err != nil {\n\t\tif _, ok := err.(*cmn.ErrorRemoteBucketDoesNotExist); ok {\n\t\t\tt.BMDVersionFixup(r, cmn.Bck{}, true /* sleep */)\n\t\t\terr = lom.Init(bck.Bck, config)\n\t\t}\n\t\tif err != nil {\n\t\t\tt.invalmsghdlr(w, r, err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\tgoi := &getObjInfo{\n\t\tstarted: started,\n\t\tt: t,\n\t\tlom: lom,\n\t\tw: w,\n\t\tctx: t.contextWithAuth(r.Header),\n\t\toffset: rangeOff,\n\t\tlength: rangeLen,\n\t\tisGFN: isGFNRequest,\n\t\tchunked: config.Net.HTTP.Chunked,\n\t}\n\tif err, errCode := goi.getObject(); err != nil {\n\t\tif cmn.IsErrConnectionReset(err) {\n\t\t\tglog.Errorf(\"GET %s: %v\", lom, err)\n\t\t} else {\n\t\t\tt.invalmsghdlr(w, r, err.Error(), errCode)\n\t\t}\n\t}\n}", "func LHashFromObj(conn *client.Connection, objRef client.ObjectRef) *LHash {\n\treturn &LHash{\n\t\tConn: conn,\n\t\tObjRef: objRef,\n\t}\n}", "func (t *badgerTableVersion) getObjKey(id, objID []byte) []byte {\n\tprefix := []byte(t.prefix + \"object/\")\n\tprefix = append(prefix, id...)\n\tprefix = append(prefix, '/')\n\n\treturn append(prefix, objID...)\n}", "func (llrb *LLRB) ID() string {\n\treturn llrb.name\n}", "func (t *targetrunner) httpobjget(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\tconfig = cmn.GCO.Get()\n\t\tquery = r.URL.Query()\n\t\tisGFNRequest, _ = cmn.ParseBool(query.Get(cmn.URLParamIsGFNRequest))\n\t)\n\n\tapiItems, err := t.checkRESTItems(w, r, 2, false, cmn.Version, cmn.Objects)\n\tif err != nil {\n\t\treturn\n\t}\n\tbucket, objName := apiItems[0], apiItems[1]\n\tbckProvider := query.Get(cmn.URLParamBckProvider)\n\tstarted := time.Now()\n\tif redirDelta := t.redirectLatency(started, query); redirDelta != 0 {\n\t\tt.statsif.Add(stats.GetRedirLatency, redirDelta)\n\t}\n\trangeOff, rangeLen, err := t.offsetAndLength(query)\n\tif err != nil {\n\t\tt.invalmsghdlr(w, r, err.Error())\n\t\treturn\n\t}\n\tlom, err := cluster.LOM{T: t, Bucket: bucket, Objname: objName}.Init(bckProvider, config)\n\tif err != nil {\n\t\tt.invalmsghdlr(w, r, err.Error())\n\t\treturn\n\t}\n\tif err = lom.AllowGET(); err != nil {\n\t\tt.invalmsghdlr(w, r, err.Error())\n\t\treturn\n\t}\n\n\tgoi := &getObjInfo{\n\t\tstarted: started,\n\t\tt: t,\n\t\tlom: lom,\n\t\tw: w,\n\t\tctx: t.contextWithAuth(r.Header),\n\t\toffset: rangeOff,\n\t\tlength: rangeLen,\n\t\tgfn: isGFNRequest,\n\t\tchunked: config.Net.HTTP.Chunked,\n\t}\n\tif err, errCode := goi.getObject(); err != nil {\n\t\tif cmn.IsErrConnectionReset(err) {\n\t\t\tglog.Errorf(\"GET %s: %v\", lom, err)\n\t\t} else {\n\t\t\tt.invalmsghdlr(w, r, err.Error(), errCode)\n\t\t}\n\t}\n}", "func (t *targetrunner) httpobjget(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\tnhobj cksumvalue\n\t\tbucket, objname, fqn string\n\t\tuname, errstr, version string\n\t\tsize int64\n\t\tprops *objectProps\n\t\tstarted time.Time\n\t\terrcode int\n\t\tcoldget, vchanged, inNextTier bool\n\t)\n\tstarted = time.Now()\n\tcksumcfg := &ctx.config.Cksum\n\tversioncfg := &ctx.config.Ver\n\tct := t.contextWithAuth(r)\n\tapitems := t.restAPIItems(r.URL.Path, 5)\n\tif apitems = t.checkRestAPI(w, r, apitems, 2, Rversion, Robjects); apitems == nil {\n\t\treturn\n\t}\n\tbucket, objname = apitems[0], apitems[1]\n\tif !t.validatebckname(w, r, bucket) {\n\t\treturn\n\t}\n\toffset, length, readRange, errstr := t.validateOffsetAndLength(r)\n\tif errstr != \"\" {\n\t\tt.invalmsghdlr(w, r, errstr)\n\t\treturn\n\t}\n\n\tbucketmd := t.bmdowner.get()\n\tislocal := bucketmd.islocal(bucket)\n\terrstr, errcode = t.checkLocalQueryParameter(bucket, r, islocal)\n\tif errstr != \"\" {\n\t\tt.invalmsghdlr(w, r, errstr, errcode)\n\t\treturn\n\t}\n\n\t// lockname(ro)\n\tfqn, uname = t.fqn(bucket, objname, islocal), uniquename(bucket, objname)\n\tt.rtnamemap.lockname(uname, false, &pendinginfo{Time: time.Now(), fqn: fqn}, time.Second)\n\n\t// existence, access & versioning\n\tif coldget, size, version, errstr = t.lookupLocally(bucket, objname, fqn); islocal && errstr != \"\" {\n\t\terrcode = http.StatusInternalServerError\n\t\t// given certain conditions (below) make an effort to locate the object cluster-wide\n\t\tif strings.Contains(errstr, doesnotexist) {\n\t\t\terrcode = http.StatusNotFound\n\t\t\taborted, running := t.xactinp.isAbortedOrRunningRebalance()\n\t\t\tif aborted || running {\n\t\t\t\tif props := t.getFromNeighbor(bucket, objname, r, islocal); props != nil {\n\t\t\t\t\tsize, nhobj = props.size, props.nhobj\n\t\t\t\t\tgoto existslocally\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t_, p := bucketmd.get(bucket, islocal)\n\t\t\t\tif p.NextTierURL != \"\" {\n\t\t\t\t\tif inNextTier, errstr, errcode = t.objectInNextTier(p.NextTierURL, bucket, objname); inNextTier {\n\t\t\t\t\t\tprops, errstr, errcode = t.getObjectNextTier(p.NextTierURL, bucket, objname, fqn)\n\t\t\t\t\t\tif errstr == \"\" {\n\t\t\t\t\t\t\tsize, nhobj = props.size, props.nhobj\n\t\t\t\t\t\t\tgoto existslocally\n\t\t\t\t\t\t}\n\t\t\t\t\t\tglog.Errorf(\"Error getting object from next tier after successful lookup, err: %s,\"+\n\t\t\t\t\t\t\t\" HTTP status code: %d\", errstr, errcode)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tt.invalmsghdlr(w, r, errstr, errcode)\n\t\tt.rtnamemap.unlockname(uname, false)\n\t\treturn\n\t}\n\n\tif !coldget && !islocal {\n\t\tif versioncfg.ValidateWarmGet && (version != \"\" &&\n\t\t\tt.versioningConfigured(bucket)) {\n\t\t\tif vchanged, errstr, errcode = t.checkCloudVersion(\n\t\t\t\tct, bucket, objname, version); errstr != \"\" {\n\t\t\t\tt.invalmsghdlr(w, r, errstr, errcode)\n\t\t\t\tt.rtnamemap.unlockname(uname, false)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// TODO: add a knob to return what's cached while upgrading the version async\n\t\t\tcoldget = vchanged\n\t\t}\n\t}\n\tif !coldget && cksumcfg.ValidateWarmGet && cksumcfg.Checksum != ChecksumNone {\n\t\tvalidChecksum, errstr := t.validateObjectChecksum(fqn, cksumcfg.Checksum, size)\n\t\tif errstr != \"\" {\n\t\t\tt.invalmsghdlr(w, r, errstr, http.StatusInternalServerError)\n\t\t\tt.rtnamemap.unlockname(uname, false)\n\t\t\treturn\n\t\t}\n\t\tif !validChecksum {\n\t\t\tif islocal {\n\t\t\t\tif err := os.Remove(fqn); err != nil {\n\t\t\t\t\tglog.Warningf(\"Bad checksum, failed to remove %s/%s, err: %v\", bucket, objname, err)\n\t\t\t\t}\n\t\t\t\tt.invalmsghdlr(w, r, fmt.Sprintf(\"Bad checksum %s/%s\", bucket, objname), http.StatusInternalServerError)\n\t\t\t\tt.rtnamemap.unlockname(uname, false)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcoldget = true\n\t\t}\n\t}\n\tif coldget {\n\t\tt.rtnamemap.unlockname(uname, false)\n\t\tif props, errstr, errcode = t.coldget(ct, bucket, objname, false); errstr != \"\" {\n\t\t\tif errcode == 0 {\n\t\t\t\tt.invalmsghdlr(w, r, errstr)\n\t\t\t} else {\n\t\t\t\tt.invalmsghdlr(w, r, errstr, errcode)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tsize, nhobj = props.size, props.nhobj\n\t}\n\nexistslocally:\n\t// note: coldget() keeps the read lock if successful\n\tdefer t.rtnamemap.unlockname(uname, false)\n\n\t//\n\t// local file => http response\n\t//\n\tif size == 0 {\n\t\tglog.Warningf(\"Unexpected: object %s/%s size is 0 (zero)\", bucket, objname)\n\t}\n\treturnRangeChecksum := readRange && cksumcfg.EnableReadRangeChecksum\n\tif !coldget && !returnRangeChecksum && cksumcfg.Checksum != ChecksumNone {\n\t\thashbinary, errstr := Getxattr(fqn, XattrXXHashVal)\n\t\tif errstr == \"\" && hashbinary != nil {\n\t\t\tnhobj = newcksumvalue(cksumcfg.Checksum, string(hashbinary))\n\t\t}\n\t}\n\tif nhobj != nil && !returnRangeChecksum {\n\t\thtype, hval := nhobj.get()\n\t\tw.Header().Add(HeaderDfcChecksumType, htype)\n\t\tw.Header().Add(HeaderDfcChecksumVal, hval)\n\t}\n\tif props != nil && props.version != \"\" {\n\t\tw.Header().Add(HeaderDfcObjVersion, props.version)\n\t}\n\n\tfile, err := os.Open(fqn)\n\tif err != nil {\n\t\tif os.IsPermission(err) {\n\t\t\terrstr = fmt.Sprintf(\"Permission denied: access forbidden to %s\", fqn)\n\t\t\tt.invalmsghdlr(w, r, errstr, http.StatusForbidden)\n\t\t} else {\n\t\t\terrstr = fmt.Sprintf(\"Failed to open local file %s, err: %v\", fqn, err)\n\t\t\tt.invalmsghdlr(w, r, errstr, http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tdefer file.Close()\n\tif readRange {\n\t\tsize = length\n\t}\n\tslab := selectslab(size)\n\tbuf := slab.alloc()\n\tdefer slab.free(buf)\n\n\tif cksumcfg.Checksum != ChecksumNone && returnRangeChecksum {\n\t\tslab := selectslab(length)\n\t\tbuf := slab.alloc()\n\t\treader := io.NewSectionReader(file, offset, length)\n\t\txxhashval, errstr := ComputeXXHash(reader, buf, xxhash.New64())\n\t\tslab.free(buf)\n\t\tif errstr != \"\" {\n\t\t\ts := fmt.Sprintf(\"Unable to compute checksum for byte range, offset:%d, length:%d from %s, err: %s\", offset, length, fqn, errstr)\n\t\t\tt.invalmsghdlr(w, r, s, http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Add(HeaderDfcChecksumType, cksumcfg.Checksum)\n\t\tw.Header().Add(HeaderDfcChecksumVal, xxhashval)\n\t}\n\n\tvar written int64\n\tif readRange {\n\t\treader := io.NewSectionReader(file, offset, length)\n\t\twritten, err = io.CopyBuffer(w, reader, buf)\n\t} else {\n\t\t// copy\n\t\twritten, err = io.CopyBuffer(w, file, buf)\n\t}\n\tif err != nil {\n\t\terrstr = fmt.Sprintf(\"Failed to send file %s, err: %v\", fqn, err)\n\t\tglog.Errorln(t.errHTTP(r, errstr, http.StatusInternalServerError))\n\t\tt.statsif.add(\"numerr\", 1)\n\t\treturn\n\t}\n\tif !coldget {\n\t\tgetatimerunner().touch(fqn)\n\t}\n\tif glog.V(4) {\n\t\ts := fmt.Sprintf(\"GET: %s/%s, %.2f MB, %d µs\", bucket, objname, float64(written)/MiB, time.Since(started)/1000)\n\t\tif coldget {\n\t\t\ts += \" (cold)\"\n\t\t}\n\t\tglog.Infoln(s)\n\t}\n\n\tdelta := time.Since(started)\n\tt.statsdC.Send(\"get\",\n\t\tstatsd.Metric{\n\t\t\tType: statsd.Counter,\n\t\t\tName: \"count\",\n\t\t\tValue: 1,\n\t\t},\n\t\tstatsd.Metric{\n\t\t\tType: statsd.Timer,\n\t\t\tName: \"latency\",\n\t\t\tValue: float64(delta / time.Millisecond),\n\t\t},\n\t)\n\n\tt.statsif.addMany(\"numget\", int64(1), \"getlatency\", int64(delta/1000))\n}", "func (r *RecordDB) ForID(ctx context.Context, id insolar.ID) (record.Material, error) {\n\treturn r.get(id)\n}", "func (s Store) GetFromID(id string) (l *Lease) {\n\tnewl := &Lease{}\n\ti, err := strconv.ParseInt(id, 10, 64)\n\tif err != nil {\n\t\tlogger.Error(\"Id conversion error\", err)\n\t\treturn nil\n\t}\n\tnewl, _ = s.leases.ID(i)\n\treturn newl\n}", "func (o LookupSpacesBucketResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSpacesBucketResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LakeOutput) LakeId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Lake) pulumi.StringOutput { return v.LakeId }).(pulumi.StringOutput)\n}", "func NewObjectID(id string) GrapheneObject {\n\tgid := new(ObjectID)\n\tif err := gid.Parse(id); err != nil {\n\t\tlogging.Errorf(\n\t\t\t\"ObjectID parser error %v\",\n\t\t\terrors.Annotate(err, \"Parse\"),\n\t\t)\n\t\treturn nil\n\t}\n\n\treturn gid\n}", "func (o *GetInterceptionitemsParams) SetLiid(liid string) {\n\to.Liid = liid\n}", "func LoadByJobRunID(ctx context.Context, m *gorpmapper.Mapper, db gorp.SqlExecutor, jobRunId int64, itemTypes []string, opts ...gorpmapper.GetOptionFunc) ([]sdk.CDNItem, error) {\n\tquery := gorpmapper.NewQuery(`\n\t\tSELECT *\n\t\tFROM item\n\t\tWHERE api_ref->>'node_run_job_id' = $1\n\t\tAND type = ANY($2)\n\t\tAND to_delete = false\n\t\tORDER BY created DESC\n\t`).Args(strconv.FormatInt(jobRunId, 10), pq.StringArray(itemTypes))\n\treturn getItems(ctx, m, db, query, opts...)\n}", "func (s *service) GetJobSeekerByID(ID string) (JobSeekerFormat, error) {\n\t// validate input ID is not negative number\n\tif err := helper.ValidateIDNumber(ID); err != nil {\n\t\treturn JobSeekerFormat{}, err\n\t}\n\n\tjobSeeker, err := s.repository.FindByID(ID)\n\n\tif err != nil {\n\t\treturn JobSeekerFormat{}, err\n\t}\n\n\tif jobSeeker.ID == 0 {\n\t\treturn JobSeekerFormat{}, errors.New(\"job seeker id not found\")\n\t}\n\tformatJobSeeker := FormatJobSeeker(jobSeeker)\n\treturn formatJobSeeker, nil\n}", "func (*GetGLAByIdRq) Descriptor() ([]byte, []int) {\n\treturn file_account_proto_rawDescGZIP(), []int{1}\n}", "func LoadByID(ctx context.Context, m *gorpmapper.Mapper, db gorp.SqlExecutor, id string, opts ...gorpmapper.GetOptionFunc) (*sdk.CDNItem, error) {\n\tquery := gorpmapper.NewQuery(\"SELECT * FROM item WHERE id = $1\").Args(id)\n\treturn getItem(ctx, m, db, query, opts...)\n}", "func (repo *Repository) Readlink(id SHA1) (string, error) {\n\n\tb, err := repo.OpenObject(id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif b.Type() != ObjBlob {\n\t\treturn \"\", fmt.Errorf(\"id must point to a blob\")\n\t}\n\n\tblob := b.(*Blob)\n\n\t//TODO: check size and don't read unreasonable large blobs\n\tdata, err := ioutil.ReadAll(blob)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(data), nil\n}", "func GetBucketByAuthID(context *gin.Context) {\n\tresponseCode := constant.INVALID_PARAMS\n\tauthID, authErr := strconv.Atoi(context.Query(\"auth_id\"))\n\toffset := context.GetInt(\"offset\")\n\tif authErr != nil{\n\t\t//log.Println(authErr)\n\t\tutils.AppLogger.Info(authErr.Error(), zap.String(\"service\", \"GetBucketByAuthID()\"))\n\t\tcontext.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\n\t\t\t\"code\": responseCode,\n\t\t\t\"data\": make(map[string]string),\n\t\t\t\"msg\": constant.GetMessage(responseCode),\n\t\t})\n\t\treturn\n\t}\n\n\tvalidCheck := validation.Validation{}\n\tvalidCheck.Required(authID, \"auth_id\").Message(\"Must have auth id\")\n\tvalidCheck.Min(authID, 1, \"auth_id\").Message(\"Auth id should be positive\")\n\tvalidCheck.Min(offset, 0, \"page_offset\").Message(\"Page offset must be >= 0\")\n\n\tdata := make(map[string]interface{})\n\tif !validCheck.HasErrors() {\n\t\tif buckets, err := models.GetBucketByAuthID(uint(authID), offset); err != nil {\n\t\t\tresponseCode = constant.INTERNAL_SERVER_ERROR\n\t\t} else {\n\t\t\tresponseCode = constant.BUCKET_GET_SUCCESS\n\t\t\tdata[\"buckets\"] = buckets\n\t\t}\n\t} else {\n\t\tfor _, err := range validCheck.Errors {\n\t\t\t//log.Println(err.Message)\n\t\t\tutils.AppLogger.Info(err.Message, zap.String(\"service\", \"GetBucketByAuthID()\"))\n\t\t}\n\t}\n\n\tcontext.JSON(http.StatusOK, gin.H{\n\t\t\"code\": responseCode,\n\t\t\"data\": data,\n\t\t\"msg\": constant.GetMessage(responseCode),\n\t})\n}", "func (o LookupOpenZfsSnapshotResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOpenZfsSnapshotResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (hp *hdfsProvider) GetObjReader(ctx context.Context, lom *cluster.LOM) (r io.ReadCloser,\n\texpectedCksm *cos.Cksum, errCode int, err error) {\n\tfilePath := filepath.Join(lom.Bck().Props.Extra.HDFS.RefDirectory, lom.ObjName)\n\tfr, err := hp.c.Open(filePath)\n\tif err != nil {\n\t\terrCode, err = hdfsErrorToAISError(err)\n\t\treturn\n\t}\n\tlom.SetCustomKey(cmn.SourceObjMD, apc.HDFS)\n\tsetSize(ctx, fr.Stat().Size())\n\treturn wrapReader(ctx, fr), nil, 0, nil\n}", "func parseObjectID(id string, r *repo.Repository) (repo.ObjectID, error) {\n\thead, tail := splitHeadTail(id)\n\tif len(head) == 0 {\n\t\treturn repo.NullObjectID, fmt.Errorf(\"invalid object ID: %v\", id)\n\t}\n\n\toid, err := repo.ParseObjectID(head)\n\tif err != nil {\n\t\treturn repo.NullObjectID, fmt.Errorf(\"can't parse object ID %v: %v\", head, err)\n\t}\n\n\tif tail == \"\" {\n\t\treturn oid, nil\n\t}\n\n\tdir := repofs.Directory(r, oid)\n\tif err != nil {\n\t\treturn repo.NullObjectID, err\n\t}\n\n\treturn parseNestedObjectID(dir, tail)\n}", "func IDLT(id string) predicate.OrderLineItem {\n\treturn predicate.OrderLineItem(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldID), id))\n\t})\n}", "func prnGetID(prn string) string {\n\tidx := strings.Index(prn, \"/\")\n\treturn prn[idx+1:]\n}", "func (o *RecipeLipid) Lipid(mods ...qm.QueryMod) lipidQuery {\n\tqueryMods := []qm.QueryMod{\n\t\tqm.Where(\"\\\"id\\\" = ?\", o.LipidID),\n\t}\n\n\tqueryMods = append(queryMods, mods...)\n\n\tquery := Lipids(queryMods...)\n\tqueries.SetFrom(query.Query, \"\\\"lipid\\\"\")\n\n\treturn query\n}", "func (c *Client) JobFromID(ctx context.Context, id string) (*Job, error) {\n\treturn c.JobFromProject(ctx, c.projectID, id, c.Location)\n}", "func LookupBucketObject(ctx *pulumi.Context, args *GetBucketObjectArgs) (*GetBucketObjectResult, error) {\n\tinputs := make(map[string]interface{})\n\tif args != nil {\n\t\tinputs[\"bucket\"] = args.Bucket\n\t\tinputs[\"key\"] = args.Key\n\t\tinputs[\"range\"] = args.Range\n\t\tinputs[\"tags\"] = args.Tags\n\t\tinputs[\"versionId\"] = args.VersionId\n\t}\n\toutputs, err := ctx.Invoke(\"aws:s3/getBucketObject:getBucketObject\", inputs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &GetBucketObjectResult{\n\t\tBody: outputs[\"body\"],\n\t\tBucket: outputs[\"bucket\"],\n\t\tCacheControl: outputs[\"cacheControl\"],\n\t\tContentDisposition: outputs[\"contentDisposition\"],\n\t\tContentEncoding: outputs[\"contentEncoding\"],\n\t\tContentLanguage: outputs[\"contentLanguage\"],\n\t\tContentLength: outputs[\"contentLength\"],\n\t\tContentType: outputs[\"contentType\"],\n\t\tEtag: outputs[\"etag\"],\n\t\tExpiration: outputs[\"expiration\"],\n\t\tExpires: outputs[\"expires\"],\n\t\tKey: outputs[\"key\"],\n\t\tLastModified: outputs[\"lastModified\"],\n\t\tMetadata: outputs[\"metadata\"],\n\t\tObjectLockLegalHoldStatus: outputs[\"objectLockLegalHoldStatus\"],\n\t\tObjectLockMode: outputs[\"objectLockMode\"],\n\t\tObjectLockRetainUntilDate: outputs[\"objectLockRetainUntilDate\"],\n\t\tRange: outputs[\"range\"],\n\t\tServerSideEncryption: outputs[\"serverSideEncryption\"],\n\t\tSseKmsKeyId: outputs[\"sseKmsKeyId\"],\n\t\tStorageClass: outputs[\"storageClass\"],\n\t\tTags: outputs[\"tags\"],\n\t\tVersionId: outputs[\"versionId\"],\n\t\tWebsiteRedirectLocation: outputs[\"websiteRedirectLocation\"],\n\t\tId: outputs[\"id\"],\n\t}, nil\n}", "func ObjectID(oid primitive.ObjectID) Val {\n\tv := Val{t: bsontype.ObjectID}\n\tcopy(v.bootstrap[0:12], oid[:])\n\treturn v\n}", "func makeKey(objId string, sliceId uint32, id blizstorage.ChunkIdentity, field string) []byte {\r\n\r\n\tif bytes.Equal(id[:], sliceDBNilChunkId[:]) {\r\n\t\treturn []byte(field)\r\n\t}\r\n\r\n\t// blizstorage.ChunkIdentity2Int(id)\r\n\tpart := fmt.Sprintf(\"%s:%d:%s\", objId, sliceId, field)\r\n\r\n\treturn append(sliceDBItemPrefix, append(id[:], part...)...)\r\n}", "func (r *Bucket) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func getObjectPath(oid OID) string {\n\t// in future we might want to use first couple of bytes as a directory\n\t// like git does\n\treturn filepath.Join(constants.GitDir, oid.String())\n}", "func (index *Index) id(i, itemID []byte) []byte {\n\treturn append(index.bucket.Prefix(byframe.Encode(i)), itemID...)\n}", "func (pl *pricelistV0) OnIpldPut(dataSize int) GasCharge {\n\treturn newGasCharge(\"OnIpldPut\", pl.ipldPutBase, int64(dataSize)*pl.ipldPutPerByte*pl.storageGasMulti).\n\t\tWithExtra(dataSize).WithVirtual(400000, int64(dataSize)*1300)\n}", "func GetObjectLabel(identifier uint32, name uint32, bufSize int32, length *int32, label *uint8) {\n\tsyscall.Syscall6(gpGetObjectLabel, 5, uintptr(identifier), uintptr(name), uintptr(bufSize), uintptr(unsafe.Pointer(length)), uintptr(unsafe.Pointer(label)), 0)\n}", "func (o baseObject) ObjectID() int64 {\n\treturn o.ID\n}", "func (bc *TranslatableBusinessCase) ObjectID() string {\n\treturn bc.ID.String()\n}", "func (s *DefaultReadWriter) GetLatestKeyForID(id string) (string, error) {\n\ts3api, err := s.open()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\toutput, err := s3api.ListObjects(&s3.ListObjectsInput{\n\t\tBucket: aws.String(s.bucketName),\n\t\tPrefix: aws.String(id + \"/\"),\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar latestKey string\n\tvar latestTimestamp *time.Time\n\tfor _, obj := range output.Contents {\n\t\tif latestTimestamp == nil || latestTimestamp.Before(*obj.LastModified) {\n\t\t\tlatestTimestamp = obj.LastModified\n\t\t\tlatestKey = *obj.Key\n\t\t}\n\t}\n\n\treturn latestKey, nil\n}", "func (b *StorageBucketImporter) ImportID(rc terraform.ResourceChange, pcv ProviderConfigMap) (string, error) {\n\tproject := fromConfigValues(\"project\", rc.Change.After, pcv)\n\tname := fromConfigValues(\"name\", rc.Change.After, nil)\n\tif project == nil {\n\t\treturn \"\", fmt.Errorf(\"could not find project in resource change or provider config\")\n\t}\n\tif name == nil {\n\t\treturn \"\", fmt.Errorf(\"could not find name in resource change or provider config\")\n\t}\n\n\treturn fmt.Sprintf(\"%v/%v\", project, name), nil\n}", "func (db *DB) GetObjectIndex(\n\tctx context.Context,\n\tid *core.RecordID,\n\tforupdate bool,\n) (*index.ObjectLifeline, error) {\n\ttx := db.BeginTransaction(false)\n\tdefer tx.Discard()\n\n\tidx, err := tx.GetObjectIndex(ctx, id, forupdate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn idx, nil\n}", "func (tm *ServiceTracerouteManager) GetTracerouteFromIPID(id uint16) *ServiceTraceroute {\n\ttm.runningTracesMutex.Lock()\n\n\tvar st *ServiceTraceroute\n\n\tfor _, runningServiceTraceroute := range tm.RunningServiceTraceroutes {\n\t\tsize := uint16(runningServiceTraceroute.GetDistance() * runningServiceTraceroute.GetIterations())\n\n\t\tif id >= runningServiceTraceroute.GetIDOffset() && id < (runningServiceTraceroute.GetIDOffset()+size) {\n\t\t\tst = runningServiceTraceroute\n\t\t\tbreak\n\t\t}\n\t}\n\n\ttm.runningTracesMutex.Unlock()\n\n\treturn st\n}", "func (c APIClient) GetObject(hash string, writer io.Writer) error {\n\tgetObjectClient, err := c.ObjectAPIClient.GetObject(\n\t\tc.Ctx(),\n\t\t&pfs.Object{Hash: hash},\n\t)\n\tif err != nil {\n\t\treturn grpcutil.ScrubGRPC(err)\n\t}\n\tif err := grpcutil.WriteFromStreamingBytesClient(getObjectClient, writer); err != nil {\n\t\treturn grpcutil.ScrubGRPC(err)\n\t}\n\treturn nil\n}", "func ID(id string) predicate.OrderLineItem {\n\treturn predicate.OrderLineItem(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldID), id))\n\t})\n}", "func getBucket(instanceID string) string {\n\treturn fmt.Sprintf(bucketTemplate, instanceID)\n}", "func IDLT(id int) predicate.MarketInfo {\n\treturn predicate.MarketInfo(sql.FieldLT(FieldID, id))\n}", "func (rt RouteTable) GetBucket(id string) (bucket Bucket, ok bool) {\n\ti, err := hex.DecodeString(id)\n\tif err != nil {\n\t\treturn KBucket{}, false\n\t}\n\tb := rt.ht.GetBucket(i)\n\tif b == nil {\n\t\treturn KBucket{}, false\n\t}\n\n\treturn KBucket{\n\t\tnodes: convertNetworkNodes(b),\n\t}, true\n}", "func (hp *hdfsProvider) ListObjects(bck *meta.Bck, msg *apc.LsoMsg, lst *cmn.LsoResult) (int, error) {\n\tvar (\n\t\th = cmn.BackendHelpers.HDFS\n\t\tidx int\n\t)\n\tmsg.PageSize = calcPageSize(msg.PageSize, hp.MaxPageSize())\n\n\terr := hp.c.Walk(bck.Props.Extra.HDFS.RefDirectory, func(path string, fi os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\tif cos.IsEOF(err) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tif uint(len(lst.Entries)) >= msg.PageSize {\n\t\t\treturn skipDir(fi)\n\t\t}\n\t\tobjName := strings.TrimPrefix(strings.TrimPrefix(path, bck.Props.Extra.HDFS.RefDirectory), string(filepath.Separator))\n\t\tif msg.Prefix != \"\" {\n\t\t\tif fi.IsDir() {\n\t\t\t\tif !cmn.DirHasOrIsPrefix(objName, msg.Prefix) {\n\t\t\t\t\treturn skipDir(fi)\n\t\t\t\t}\n\t\t\t} else if !cmn.ObjHasPrefix(objName, msg.Prefix) {\n\t\t\t\treturn skipDir(fi)\n\t\t\t}\n\t\t}\n\t\tif msg.ContinuationToken != \"\" && objName <= msg.ContinuationToken {\n\t\t\treturn nil\n\t\t}\n\t\tif msg.StartAfter != \"\" && objName <= msg.StartAfter {\n\t\t\treturn nil\n\t\t}\n\t\tif fi.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tvar entry *cmn.LsoEntry\n\t\tif idx < len(lst.Entries) {\n\t\t\tentry = lst.Entries[idx]\n\t\t} else {\n\t\t\tentry = &cmn.LsoEntry{Name: objName}\n\t\t\tlst.Entries = append(lst.Entries, entry)\n\t\t}\n\t\tidx++\n\t\tentry.Size = fi.Size()\n\t\tif msg.WantProp(apc.GetPropsChecksum) {\n\t\t\tfr, err := hp.c.Open(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer fr.Close()\n\t\t\tcksum, err := fr.Checksum()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif v, ok := h.EncodeCksum(cksum); ok {\n\t\t\t\tentry.Checksum = v\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn hdfsErrorToAISError(err)\n\t}\n\tlst.Entries = lst.Entries[:idx]\n\t// Set continuation token only if we reached the page size.\n\tif uint(len(lst.Entries)) >= msg.PageSize {\n\t\tlst.ContinuationToken = lst.Entries[len(lst.Entries)-1].Name\n\t}\n\treturn 0, nil\n}", "func GetObject(oid OID) (StoredObject, error) {\n\tvar obj StoredObject\n\tdata, err := ioutil.ReadFile(getObjectPath(oid))\n\tif err != nil {\n\t\treturn obj, err\n\t}\n\tsplit := bytes.SplitN(data, []byte{0}, 2)\n\tif len(split) != 2 {\n\t\treturn obj, ErrInvalidObject\n\t}\n\tobjType, err := Decode(split[0])\n\tif err != nil {\n\t\treturn obj, err\n\t}\n\tobj.Data = split[1]\n\tobj.ObjType = objType\n\treturn obj, nil\n}", "func (c *Client) JobFromID(ctx context.Context, id string) (*Job, error) {\n\tjob, err := c.service.getJob(ctx, c.projectID, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjob.c = c\n\treturn job, nil\n}", "func GetObjectLabel(identifier uint32, name uint32, bufSize int32, length *int32, label *int8) {\n C.glowGetObjectLabel(gpGetObjectLabel, (C.GLenum)(identifier), (C.GLuint)(name), (C.GLsizei)(bufSize), (*C.GLsizei)(unsafe.Pointer(length)), (*C.GLchar)(unsafe.Pointer(label)))\n}", "func (ll *LevelLedger) GetObjectIndex(ref *record.Reference) (*index.ObjectLifeline, error) {\n\tk := prefixkey(scopeIDLifeline, ref.Key())\n\tbuf, err := ll.ldb.Get(k, nil)\n\tif err != nil {\n\t\tif err == leveldb.ErrNotFound {\n\t\t\treturn nil, ErrNotFound\n\t\t}\n\t\treturn nil, err\n\t}\n\tidx, err := index.DecodeObjectLifeline(buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn idx, nil\n}", "func (o GetLBOutboundRuleResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetLBOutboundRuleResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (db *ImageDB) DownloadByID(id primitive.ObjectID) (bytes.Buffer, error) {\n\tbucket, _ := gridfs.NewBucket(\n\t\tdb.database,\n\t)\n\tbuf := bytes.Buffer{}\n\t_, err := bucket.DownloadToStream(id, &buf)\n\treturn buf, err\n}", "func (xl xlObjects) listObjects(ctx context.Context, bucket, prefix, marker, delimiter string, maxKeys int) (loi ListObjectsInfo, e error) {\n\t// Default is recursive, if delimiter is set then list non recursive.\n\trecursive := true\n\tif delimiter == SlashSeparator {\n\t\trecursive = false\n\t}\n\n\twalkResultCh, endWalkCh := xl.listPool.Release(listParams{bucket, recursive, marker, prefix, false})\n\tif walkResultCh == nil {\n\t\tendWalkCh = make(chan struct{})\n\t\tlistDir := listDirFactory(ctx, xl.getLoadBalancedDisks()...)\n\t\twalkResultCh = startTreeWalk(ctx, bucket, prefix, marker, recursive, listDir, endWalkCh)\n\t}\n\n\tvar objInfos []ObjectInfo\n\tvar eof bool\n\tvar nextMarker string\n\tfor i := 0; i < maxKeys; {\n\n\t\twalkResult, ok := <-walkResultCh\n\t\tif !ok {\n\t\t\t// Closed channel.\n\t\t\teof = true\n\t\t\tbreak\n\t\t}\n\t\tentry := walkResult.entry\n\t\tvar objInfo ObjectInfo\n\t\tif hasSuffix(entry, SlashSeparator) {\n\t\t\t// Object name needs to be full path.\n\t\t\tobjInfo.Bucket = bucket\n\t\t\tobjInfo.Name = entry\n\t\t\tobjInfo.IsDir = true\n\t\t} else {\n\t\t\t// Set the Mode to a \"regular\" file.\n\t\t\tvar err error\n\t\t\tobjInfo, err = xl.getObjectInfo(ctx, bucket, entry)\n\t\t\tif err != nil {\n\t\t\t\t// Ignore errFileNotFound as the object might have got\n\t\t\t\t// deleted in the interim period of listing and getObjectInfo(),\n\t\t\t\t// ignore quorum error as it might be an entry from an outdated disk.\n\t\t\t\tif IsErrIgnored(err, []error{\n\t\t\t\t\terrFileNotFound,\n\t\t\t\t\terrXLReadQuorum,\n\t\t\t\t}...) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn loi, toObjectErr(err, bucket, prefix)\n\t\t\t}\n\t\t}\n\t\tnextMarker = objInfo.Name\n\t\tobjInfos = append(objInfos, objInfo)\n\t\ti++\n\t\tif walkResult.end {\n\t\t\teof = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tparams := listParams{bucket, recursive, nextMarker, prefix, false}\n\tif !eof {\n\t\txl.listPool.Set(params, walkResultCh, endWalkCh)\n\t}\n\n\tresult := ListObjectsInfo{}\n\tfor _, objInfo := range objInfos {\n\t\tif objInfo.IsDir && delimiter == SlashSeparator {\n\t\t\tresult.Prefixes = append(result.Prefixes, objInfo.Name)\n\t\t\tcontinue\n\t\t}\n\t\tresult.Objects = append(result.Objects, objInfo)\n\t}\n\n\tif !eof {\n\t\tresult.IsTruncated = true\n\t\tif len(objInfos) > 0 {\n\t\t\tresult.NextMarker = objInfos[len(objInfos)-1].Name\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func (o *GetLogicalSwitchParams) SetLswitchID(lswitchID string) {\n\to.LswitchID = lswitchID\n}", "func (client *GCSBlobstore) getObjectHandle(gcs *storage.Client, src string) *storage.ObjectHandle {\n\thandle := gcs.Bucket(client.config.BucketName).Object(src)\n\tif client.config.EncryptionKey != nil {\n\t\thandle = handle.Key(client.config.EncryptionKey)\n\t}\n\treturn handle\n}", "func (bv *BaseVSphere) ID() string {\n\treturn fmt.Sprintf(\"%s[%s@%s]\", bv.Type, bv.Name, bv.Endpoint)\n}", "func (c *Client) GetLodging(id string, filters ...Filter) (Lodging, error) {\n\tresp, err := c.doRequest(http.MethodGet, fmt.Sprintf(EndpointFormatGetObject, TypeLodging, id, formatFilters(filters)), nil)\n\tif err != nil {\n\t\treturn Lodging{}, err\n\t}\n\n\t// Check if we didn't get a result and return an error if true.\n\tif len(resp.Lodging) <= 0 {\n\t\treturn Lodging{}, fmt.Errorf(\"get lodging id %s returned an empty result\", id)\n\t}\n\n\t// Return the object.\n\treturn resp.Lodging[0], nil\n}", "func GetObject(oid string) (string, ObjectType, error) {\n\tobjectPath := fmt.Sprintf(\"%s/%s/%s\", UGIT_DIR, OBJECTS_DIR, oid)\n\tdata, err := ioutil.ReadFile(objectPath)\n\tif err != nil {\n\t\treturn \"\", ObjectType(\"\"), err\n\t}\n\tparts := bytes.Split(data, []byte{BYTE_SEPARATOR})\n\t_type := ObjectType(parts[0])\n\tcontent := string(parts[1])\n\treturn content, _type, err\n}", "func (obj *SObject) ID() string {\n\treturn obj.StringField(sobjectIDKey)\n}", "func (o BucketOutput) BundleId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Bucket) pulumi.StringOutput { return v.BundleId }).(pulumi.StringOutput)\n}", "func GetObjectLabel(identifier uint32, name uint32, bufSize int32, length *int32, label *uint8) {\n\tC.glowGetObjectLabel(gpGetObjectLabel, (C.GLenum)(identifier), (C.GLuint)(name), (C.GLsizei)(bufSize), (*C.GLsizei)(unsafe.Pointer(length)), (*C.GLchar)(unsafe.Pointer(label)))\n}", "func GetObjectLabel(identifier uint32, name uint32, bufSize int32, length *int32, label *uint8) {\n\tC.glowGetObjectLabel(gpGetObjectLabel, (C.GLenum)(identifier), (C.GLuint)(name), (C.GLsizei)(bufSize), (*C.GLsizei)(unsafe.Pointer(length)), (*C.GLchar)(unsafe.Pointer(label)))\n}", "func IDLT(id int) predicate.Blob {\n\treturn predicate.Blob(\n\t\tfunc(s *sql.Selector) {\n\t\t\ts.Where(sql.LT(s.C(FieldID), id))\n\t\t},\n\t)\n}", "func IDLT(id int) predicate.BaselineClass {\n\treturn predicate.BaselineClass(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldID), id))\n\t})\n}", "func (d *litMapping) LitOf(id Identifier) z.Lit {\n\tm, ok := d.lits[id]\n\tif ok {\n\t\treturn m\n\t}\n\td.errs = append(d.errs, fmt.Errorf(\"variable %q referenced but not provided\", id))\n\treturn z.LitNull\n}", "func (o AttachmentOutput) LoadBalancerId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Attachment) pulumi.StringOutput { return v.LoadBalancerId }).(pulumi.StringOutput)\n}", "func IDLT(id int) predicate.CarRepairrecord {\n\treturn predicate.CarRepairrecord(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldID), id))\n\t})\n}", "func (xl xlObjects) GetObject(bucket, object string, startOffset int64) (io.ReadCloser, error) {\n\t// Verify if bucket is valid.\n\tif !IsValidBucketName(bucket) {\n\t\treturn nil, BucketNameInvalid{Bucket: bucket}\n\t}\n\t// Verify if object is valid.\n\tif !IsValidObjectName(object) {\n\t\treturn nil, ObjectNameInvalid{Bucket: bucket, Object: object}\n\t}\n\tnsMutex.RLock(bucket, object)\n\tdefer nsMutex.RUnlock(bucket, object)\n\tif !isMultipartObject(xl.storage, bucket, object) {\n\t\t_, err := xl.storage.StatFile(bucket, object)\n\t\tif err == nil {\n\t\t\tvar reader io.ReadCloser\n\t\t\treader, err = xl.storage.ReadFile(bucket, object, startOffset)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, toObjectErr(err, bucket, object)\n\t\t\t}\n\t\t\treturn reader, nil\n\t\t}\n\t\treturn nil, toObjectErr(err, bucket, object)\n\t}\n\tfileReader, fileWriter := io.Pipe()\n\tinfo, err := getMultipartObjectInfo(xl.storage, bucket, object)\n\tif err != nil {\n\t\treturn nil, toObjectErr(err, bucket, object)\n\t}\n\tpartIndex, offset, err := info.GetPartNumberOffset(startOffset)\n\tif err != nil {\n\t\treturn nil, toObjectErr(err, bucket, object)\n\t}\n\n\t// Hold a read lock once more which can be released after the following go-routine ends.\n\t// We hold RLock once more because the current function would return before the go routine below\n\t// executes and hence releasing the read lock (because of defer'ed nsMutex.RUnlock() call).\n\tnsMutex.RLock(bucket, object)\n\tgo func() {\n\t\tdefer nsMutex.RUnlock(bucket, object)\n\t\tfor ; partIndex < len(info.Parts); partIndex++ {\n\t\t\tpart := info.Parts[partIndex]\n\t\t\tr, err := xl.storage.ReadFile(bucket, pathJoin(object, partNumToPartFileName(part.PartNumber)), offset)\n\t\t\tif err != nil {\n\t\t\t\tfileWriter.CloseWithError(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Reset offset to 0 as it would be non-0 only for the first loop if startOffset is non-0.\n\t\t\toffset = 0\n\t\t\tif _, err = io.Copy(fileWriter, r); err != nil {\n\t\t\t\tswitch reader := r.(type) {\n\t\t\t\tcase *io.PipeReader:\n\t\t\t\t\treader.CloseWithError(err)\n\t\t\t\tcase io.ReadCloser:\n\t\t\t\t\treader.Close()\n\t\t\t\t}\n\t\t\t\tfileWriter.CloseWithError(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Close the readerCloser that reads multiparts of an object from the xl storage layer.\n\t\t\t// Not closing leaks underlying file descriptors.\n\t\t\tr.Close()\n\t\t}\n\t\tfileWriter.Close()\n\t}()\n\treturn fileReader, nil\n}", "func (r *OrgBucketID) ID() influxdb.ID {\n\tr.m.Lock()\n\tn := r.src.Uint64()\n\tr.m.Unlock()\n\n\tn = sanitize(n)\n\treturn influxdb.ID(n)\n}", "func (o *Object) ID() string {\n\treturn o.id\n}", "func (o *Object) ID() string {\n\treturn o.id\n}", "func (b *ExactMatchLookupJobMatchingRowsCollectionRequestBuilder) ID(id string) *LookupResultRowRequestBuilder {\n\tbb := &LookupResultRowRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.baseURL += \"/\" + id\n\treturn bb\n}", "func (o *StorageSpaceAllOf) SetLdevId(v string) {\n\to.LdevId = &v\n}", "func (self *RegisObjManager) LoadDiamondLogObj(id string) *RedisDiamondLogObj {\n\tvalue, ok := self.Load(id)\n\tif ok {\n\t\treturn value.(*RedisDiamondLogObj)\n\t}\n\treturn nil\n}", "func IDLT(id int) predicate.GroupBandwidth {\n\treturn predicate.GroupBandwidth(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldID), id))\n\t})\n}", "func (l *store) leaderID(shardID uint64) (uint64, error) {\n\tleaderID, _, ok, err := l.nh.GetLeaderID(shardID)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif !ok {\n\t\treturn 0, nil\n\t}\n\treturn leaderID, nil\n}", "func (o *Object) ID() string {\n\tdo, ok := o.Object.(fs.IDer)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn do.ID()\n}", "func (o *Object) ID() string {\n\tdo, ok := o.Object.(fs.IDer)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn do.ID()\n}", "func (p ObjectID) ID() string {\n\treturn fmt.Sprintf(\"%d.%d.%d\",\n\t\tp.SpaceType(),\n\t\tp.ObjectType(),\n\t\tp.Instance(),\n\t)\n}", "func (o LookupLoadBalancerResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupLoadBalancerResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func FindGistForID(ID interface{}) Gist {\n\tgist := Gist{}\n\tDb.Get(&gist, \"SELECT * FROM gists WHERE id = $1\", ID)\n\treturn gist\n}", "func (o OceanLoggingExportS3Output) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v OceanLoggingExportS3) string { return v.Id }).(pulumi.StringOutput)\n}", "func (app *App) NewObjectWithId(resourceName string, objectId string) *Object {\n\treturn &Object{\n\t\tapp: app,\n\t\tResourceName: resourceName,\n\t\tObjectId: objectId,\n\t\tdata: make(map[string]interface{}),\n\t\tchangedData: make(map[string]interface{}),\n\t\tbaseURL: fmt.Sprintf(\"%s/resources/%s\", app.baseURL, resourceName),\n\t}\n}", "func IDLT(id int) predicate.AllocationStrategy {\n\treturn predicate.AllocationStrategy(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldID), id))\n\t})\n}", "func (objectIDs *DbObjectIDs) GetObjectID(key ExternalIDKey) string {\n\treturn objectIDs.objectIDs[key]\n}", "func getLayerByID(id int32) float64 {\r\n\tvar f64ID float64 = float64(id)\r\n\tlayer := math.Floor(math.Log2(f64ID*3+1) / 2)\r\n\treturn layer\r\n}", "func (a *LANsApiService) DatacentersLansNicsFindById(ctx _context.Context, datacenterId string, lanId string, nicId string) ApiDatacentersLansNicsFindByIdRequest {\n\treturn ApiDatacentersLansNicsFindByIdRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tdatacenterId: datacenterId,\n\t\tlanId: lanId,\n\t\tnicId: nicId,\n\t}\n}", "func (*llcFactory) New(args *xreg.XactArgs) xreg.BucketEntry {\n\treturn &llcFactory{t: args.T, uuid: args.UUID}\n}", "func getLinodeIDByName(linodeName string) (int, error) {\n\tpages := 1\n\tfor page := 1; page <= pages; page++ {\n\t\turl := fmt.Sprintf(\"https://api.linode.com/v4/linode/instances?page=%d\", page)\n\t\t//var err error\n\t\tit, err := Get(url, &ListNodeResponse{})\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tresp, ok := it.(*ListNodeResponse)\n\t\tif !ok {\n\t\t\treturn 0, fmt.Errorf(\"Error casting to ListNodeReponse\")\n\t\t}\n\t\tpages = resp.Pages\n\t\tfor _, n := range resp.Data {\n\t\t\tif n.Label == linodeName {\n\t\t\t\treturn n.ID, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn 0, fmt.Errorf(\"Not Found\")\n}", "func (g *Gpks) Get(id interface{}) (proto.Message, error) {\n\tvar nid int64\n\tswitch tid := id.(type) {\n\tcase string:\n\t\t// off\n\t\tif off, ok := g.sid[tid]; ok {\n\t\t\t_, err := g.file.Seek(off, 0) // shift\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfmsz := make([]byte, 8)\n\t\t\t_, err = g.file.Read(fmsz)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tmsz := bytes_to_int(fmsz[4:])\n\t\t\tbt := make([]byte, msz)\n\t\t\t_, err = g.file.Read(bt)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn unmarshal(bt)\n\t\t}\n\t\t// not exist\n\t\treturn nil, nil\n\tcase int64:\n\t\tnid = tid\n\tcase int:\n\t\tnid = int64(tid)\n\tdefault:\n\t\treturn nil, ErrWrongIdType\n\t}\n\t// off\n\tif off, ok := g.nid[nid]; ok {\n\t\t_, err := g.file.Seek(off, 0) // shift\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfmsz := make([]byte, 8)\n\t\t_, err = g.file.Read(fmsz)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmsz := bytes_to_int(fmsz[4:])\n\t\tbt := make([]byte, msz)\n\t\t_, err = g.file.Read(bt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn unmarshal(bt)\n\t}\n\t// not exist\n\treturn nil, nil\n}", "func (l ExportLayer) ID() string {\n\treturn strings.TrimSuffix(string(l), \"/layer.tar\")\n}", "func (l *Lock) get(ctx context.Context) (*LockRecord, string, error) {\n\tl.backend.logger.Debug(\"Called getLockRecord()\")\n\n\t// Read lock Key\n\n\tdefer metrics.MeasureSince(metricGetHa, time.Now())\n\topcClientRequestId, err := uuid.GenerateUUID()\n\tif err != nil {\n\t\tl.backend.logger.Error(\"getHa: error generating UUID\")\n\t\treturn nil, \"\", errwrap.Wrapf(\"failed to generate UUID: {{err}}\", err)\n\t}\n\tl.backend.logger.Debug(\"getHa\", \"opc-client-request-id\", opcClientRequestId)\n\n\trequest := objectstorage.GetObjectRequest{\n\t\tNamespaceName: &l.backend.namespaceName,\n\t\tBucketName: &l.backend.lockBucketName,\n\t\tObjectName: &l.key,\n\t\tOpcClientRequestId: &opcClientRequestId,\n\t}\n\n\tctx, cancel := context.WithTimeout(ctx, ObjectStorageCallsReadTimeout)\n\tdefer cancel()\n\n\tresponse, err := l.backend.client.GetObject(ctx, request)\n\tl.backend.logRequest(\"getHA\", response.RawResponse, response.OpcClientRequestId, response.OpcRequestId, err)\n\n\tif err != nil {\n\t\tif response.RawResponse != nil && response.RawResponse.StatusCode == http.StatusNotFound {\n\t\t\treturn nil, \"\", nil\n\t\t}\n\n\t\tmetrics.IncrCounter(metricGetFailed, 1)\n\t\tl.backend.logger.Error(\"Error calling GET\", \"err\", err)\n\t\treturn nil, \"\", errwrap.Wrapf(fmt.Sprintf(\"failed to read Value for %q: {{err}}\", l.key), err)\n\t}\n\n\tdefer response.RawResponse.Body.Close()\n\n\tbody, err := ioutil.ReadAll(response.Content)\n\tif err != nil {\n\t\tmetrics.IncrCounter(metricGetFailed, 1)\n\t\tl.backend.logger.Error(\"Error reading content\", \"err\", err)\n\t\treturn nil, \"\", errwrap.Wrapf(\"failed to decode Value into bytes: {{err}}\", err)\n\t}\n\n\tvar lockRecord LockRecord\n\terr = json.Unmarshal(body, &lockRecord)\n\tif err != nil {\n\t\tmetrics.IncrCounter(metricGetFailed, 1)\n\t\tl.backend.logger.Error(\"Error un-marshalling content\", \"err\", err)\n\t\treturn nil, \"\", errwrap.Wrapf(fmt.Sprintf(\"failed to read Value for %q: {{err}}\", l.key), err)\n\t}\n\n\treturn &lockRecord, *response.ETag, nil\n}", "func (l *pydioObjects) GetObject(ctx context.Context, bucket string, key string, startOffset int64, length int64, writer io.Writer, tag string, opts minio.ObjectOptions) error {\n\n\t// log.Println(\"[GetObject] From Router\", bucket, key, startOffset, length)\n\n\tpath := strings.TrimLeft(key, \"/\")\n\tobjectReader, err := l.Router.GetObject(ctx, &tree.Node{\n\t\tPath: path,\n\t}, &models.GetRequestData{\n\t\tStartOffset: startOffset,\n\t\tLength: length,\n\t\tVersionId: opts.VersionID,\n\t})\n\tif err != nil {\n\t\treturn pydioToMinioError(err, bucket, key)\n\t}\n\tdefer objectReader.Close()\n\tif _, err := io.Copy(writer, objectReader); err != nil {\n\t\treturn minio.ErrorRespToObjectError(err, bucket, key)\n\t}\n\treturn nil\n\n}", "func (obj *SObject) setID(id string) {\n\t(*obj)[sobjectIDKey] = id\n}", "func (l *gcsGateway) AnonGetObject(bucket string, object string, startOffset int64, length int64, writer io.Writer) error {\n\treq, err := http.NewRequest(\"GET\", toGCSPublicURL(bucket, object), nil)\n\tif err != nil {\n\t\treturn gcsToObjectError(traceError(err), bucket, object)\n\t}\n\n\tif length > 0 && startOffset > 0 {\n\t\treq.Header.Add(\"Range\", fmt.Sprintf(\"bytes=%d-%d\", startOffset, startOffset+length-1))\n\t} else if startOffset > 0 {\n\t\treq.Header.Add(\"Range\", fmt.Sprintf(\"bytes=%d-\", startOffset))\n\t}\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn gcsToObjectError(traceError(err), bucket, object)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusPartialContent && resp.StatusCode != http.StatusOK {\n\t\treturn gcsToObjectError(traceError(anonErrToObjectErr(resp.StatusCode, bucket, object)), bucket, object)\n\t}\n\n\t_, err = io.Copy(writer, resp.Body)\n\treturn gcsToObjectError(traceError(err), bucket, object)\n}", "func (b *Bolt) NewID() (sid string, err error) {\n\terr = b.client.Update(func(tx *bolt.Tx) error {\n\t\tbkt := tx.Bucket([]byte(b.bucket))\n\t\tid, err := bkt.NextSequence()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsid = strconv.FormatUint(id, 10)\n\t\treturn nil\n\t})\n\treturn\n}", "func (db *DB) GetObjectIndex(id *record.ID, forupdate bool) (*index.ObjectLifeline, error) {\n\ttx := db.BeginTransaction(false)\n\tdefer tx.Discard()\n\n\tidx, err := tx.GetObjectIndex(id, forupdate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn idx, nil\n}" ]
[ "0.53838265", "0.5233115", "0.5099102", "0.5027689", "0.49831283", "0.4896206", "0.4884035", "0.48583797", "0.4837276", "0.47559118", "0.4734468", "0.4723855", "0.47236726", "0.4702978", "0.46923214", "0.46632597", "0.4632157", "0.46318308", "0.4618542", "0.46080965", "0.46025997", "0.45820868", "0.45626298", "0.4553386", "0.44883692", "0.4487949", "0.44817272", "0.44736716", "0.44707426", "0.4460465", "0.4458466", "0.4446033", "0.443876", "0.44367686", "0.44327402", "0.44317195", "0.44270205", "0.44238067", "0.44224167", "0.44113454", "0.44026807", "0.4402668", "0.439416", "0.43927538", "0.43898666", "0.43883473", "0.43865398", "0.43849027", "0.4378164", "0.43778792", "0.43705374", "0.43680772", "0.43659383", "0.43641096", "0.43610993", "0.4353092", "0.43496257", "0.43468904", "0.43335792", "0.43321204", "0.4326465", "0.43221244", "0.43204165", "0.43104398", "0.43104398", "0.42955977", "0.42914596", "0.42898986", "0.42880905", "0.42851573", "0.42712998", "0.4271228", "0.42666137", "0.42666137", "0.42645073", "0.42640758", "0.4264061", "0.42630333", "0.42626455", "0.4255757", "0.4255757", "0.42548594", "0.4249524", "0.42481974", "0.42377752", "0.42369747", "0.4236722", "0.42360753", "0.4232959", "0.42329347", "0.42294407", "0.42254147", "0.42224708", "0.42224693", "0.42222744", "0.4221045", "0.42128092", "0.4212641", "0.42090964", "0.42073837" ]
0.53829193
1
WaitReady waits for machinecontroller and its webhook to become ready
func WaitReady(s *state.State) error { if !s.Cluster.MachineController.Deploy { return nil } s.Logger.Infoln("Waiting for machine-controller to come up...") if err := cleanupStaleResources(s.Context, s.DynamicClient); err != nil { return err } if err := waitForWebhook(s.Context, s.DynamicClient); err != nil { return err } if err := waitForMachineController(s.Context, s.DynamicClient); err != nil { return err } return waitForCRDs(s) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WaitReady(ctx *util.Context) error {\n\tif !ctx.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\tctx.Logger.Infoln(\"Waiting for machine-controller to come up…\")\n\n\t// Wait a bit to let scheduler to react\n\ttime.Sleep(10 * time.Second)\n\n\tif err := WaitForWebhook(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller-webhook did not come up\")\n\t}\n\n\tif err := WaitForMachineController(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller did not come up\")\n\t}\n\treturn nil\n}", "func waitForWebhook(ctx context.Context, client dynclient.Client) error {\n\tcondFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{\n\t\tNamespace: resources.MachineControllerNameSpace,\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\n\t\t\tappLabelKey: resources.MachineControllerWebhookName,\n\t\t}),\n\t})\n\n\treturn fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), \"waiting for machine-controller webhook to became ready\")\n}", "func waitForMachineController(ctx context.Context, client dynclient.Client) error {\n\tcondFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{\n\t\tNamespace: resources.MachineControllerNameSpace,\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\n\t\t\tappLabelKey: resources.MachineControllerName,\n\t\t}),\n\t})\n\n\treturn fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), \"waiting for machine-controller to became ready\")\n}", "func (c *BFTChain) WaitReady() error {\n\treturn nil\n}", "func (vm *VirtualMachine) WaitUntilReady(client SkytapClient) (*VirtualMachine, error) {\n\treturn vm.WaitUntilInState(client, []string{RunStateStop, RunStateStart, RunStatePause}, false)\n}", "func WaitForReady() {\n\tdefaultClient.WaitForReady()\n}", "func (c *Client) WaitUntilReady() {\n\tc.waitUntilReady()\n}", "func (envManager *TestEnvManager) WaitUntilReady() (bool, error) {\n\tlog.Println(\"Start checking components' status\")\n\tretry := u.Retrier{\n\t\tBaseDelay: 1 * time.Second,\n\t\tMaxDelay: 10 * time.Second,\n\t\tRetries: 8,\n\t}\n\n\tready := false\n\tretryFn := func(_ context.Context, i int) error {\n\t\tfor _, comp := range envManager.testEnv.GetComponents() {\n\t\t\tif alive, err := comp.IsAlive(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to comfirm compoment %s is alive %v\", comp.GetName(), err)\n\t\t\t} else if !alive {\n\t\t\t\treturn fmt.Errorf(\"component %s is not alive\", comp.GetName())\n\t\t\t}\n\t\t}\n\n\t\tready = true\n\t\tlog.Println(\"All components are ready\")\n\t\treturn nil\n\t}\n\n\t_, err := retry.Retry(context.Background(), retryFn)\n\treturn ready, err\n}", "func WaitForReady() {\n\tucc.WaitForReady()\n}", "func waitReady(project, name, region string) error {\n\twait := time.Minute * 4\n\tdeadline := time.Now().Add(wait)\n\tfor time.Now().Before(deadline) {\n\t\tsvc, err := getService(project, name, region)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to query Service for readiness: %w\", err)\n\t\t}\n\n\t\tfor _, cond := range svc.Status.Conditions {\n\t\t\tif cond.Type == \"Ready\" {\n\t\t\t\tif cond.Status == \"True\" {\n\t\t\t\t\treturn nil\n\t\t\t\t} else if cond.Status == \"False\" {\n\t\t\t\t\treturn fmt.Errorf(\"reason=%s message=%s\", cond.Reason, cond.Message)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second * 2)\n\t}\n\treturn fmt.Errorf(\"the service did not become ready in %s, check Cloud Console for logs to see why it failed\", wait)\n}", "func (a *Agent) WaitReady() {\n\ta.statusLock.RLock()\n\tdefer a.statusLock.RUnlock()\n\n\tfor {\n\t\tif a.status == 1 {\n\t\t\treturn\n\t\t}\n\t\ta.statusCond.Wait()\n\t}\n}", "func (p *Pebble) WaitReady(t *testing.T) {\n\tif p.pebbleCMD.Process == nil {\n\t\tt.Fatal(\"Pebble not started\")\n\t}\n\turl := p.DirectoryURL()\n\tRetry(t, 10, 10*time.Millisecond, func() error {\n\t\tctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)\n\t\tdefer cancel()\n\n\t\tt.Log(\"Checking pebble readiness\")\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp, err := p.httpClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp.Body.Close()\n\t\treturn nil\n\t})\n}", "func WaitReady() {\n\tif deviceReady {\n\t\treturn\n\t}\n\tch := make(chan struct{}, 0)\n\tf := func() {\n\t\tdeviceReady = true\n\t\tclose(ch)\n\t}\n\tOnDeviceReady(f)\n\t<-ch\n\tUnDeviceReady(f)\n}", "func (s *S8Proxy) WaitUntilClientIsReady() {\n\ts.gtpClient.WaitUntilClientIsReady(0)\n}", "func (m *DomainMonitor) WaitReady() (err error) {\n\treturn m.sink.WaitReady()\n}", "func waitForConductor(ctx context.Context, client *gophercloud.ServiceClient) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for conductor API to become available...\")\n\t\t\tdriverCount := 0\n\n\t\t\tdrivers.ListDrivers(client, drivers.ListDriversOpts{\n\t\t\t\tDetail: false,\n\t\t\t}).EachPage(func(page pagination.Page) (bool, error) {\n\t\t\t\tactual, err := drivers.ExtractDrivers(page)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tdriverCount += len(actual)\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\t// If we have any drivers, conductor is up.\n\t\t\tif driverCount > 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func (c *ClientManager) WaitInstanceUntilReady(id int, until time.Time) error {\n\tfor {\n\t\tvirtualGuest, found, err := c.GetInstance(id, \"id, lastOperatingSystemReload[id,modifyDate], activeTransaction[id,transactionStatus.name], provisionDate, powerState.keyName\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !found {\n\t\t\treturn bosherr.WrapErrorf(err, \"SoftLayer virtual guest '%d' does not exist\", id)\n\t\t}\n\n\t\tlastReload := virtualGuest.LastOperatingSystemReload\n\t\tactiveTxn := virtualGuest.ActiveTransaction\n\t\tprovisionDate := virtualGuest.ProvisionDate\n\n\t\t// if lastReload != nil && lastReload.ModifyDate != nil {\n\t\t// \tfmt.Println(\"lastReload: \", (*lastReload.ModifyDate).Format(time.RFC3339))\n\t\t// }\n\t\t// if activeTxn != nil && activeTxn.TransactionStatus != nil && activeTxn.TransactionStatus.Name != nil {\n\t\t// \tfmt.Println(\"activeTxn: \", *activeTxn.TransactionStatus.Name)\n\t\t// }\n\t\t// if provisionDate != nil {\n\t\t// \tfmt.Println(\"provisionDate: \", (*provisionDate).Format(time.RFC3339))\n\t\t// }\n\n\t\treloading := activeTxn != nil && lastReload != nil && *activeTxn.Id == *lastReload.Id\n\t\tif provisionDate != nil && !reloading {\n\t\t\t// fmt.Println(\"power state:\", *virtualGuest.PowerState.KeyName)\n\t\t\tif *virtualGuest.PowerState.KeyName == \"RUNNING\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tnow := time.Now()\n\t\tif now.After(until) {\n\t\t\treturn bosherr.Errorf(\"Power on virtual guest with id %d Time Out!\", *virtualGuest.Id)\n\t\t}\n\n\t\tmin := math.Min(float64(10.0), float64(until.Sub(now)))\n\t\ttime.Sleep(time.Duration(min) * time.Second)\n\t}\n}", "func (s *ssh) WaitReady(hostName string, timeout time.Duration) error {\n\tif timeout < utils.TimeoutCtxHost {\n\t\ttimeout = utils.TimeoutCtxHost\n\t}\n\thost := &host{session: s.session}\n\tcfg, err := host.SSHConfig(hostName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn conv.ToSystemSshConfig(cfg).WaitServerReady(timeout)\n}", "func waitForMachineSetToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForMachineSetStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(machineSet *capiv1alpha1.MachineSet) bool { return machineSet != nil },\n\t)\n}", "func (l *LocalSDKServer) Ready(context.Context, *sdk.Empty) (*sdk.Empty, error) {\n\tlogrus.Info(\"Ready request has been received!\")\n\treturn &sdk.Empty{}, nil\n}", "func (client *gRPCVtctldClient) WaitForReady(ctx context.Context) error {\n\t// The gRPC implementation of WaitForReady uses the gRPC Connectivity API\n\t// See https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md\n\tfor {\n\t\tselect {\n\t\t// A READY connection to the vtctld could not be established\n\t\t// within the context timeout. The caller should close their\n\t\t// existing connection and establish a new one.\n\t\tcase <-ctx.Done():\n\t\t\treturn ErrConnectionTimeout\n\n\t\t// Wait to transition to READY state\n\t\tdefault:\n\t\t\tconnState := client.cc.GetState()\n\n\t\t\tswitch connState {\n\t\t\tcase connectivity.Ready:\n\t\t\t\treturn nil\n\n\t\t\t// Per https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md,\n\t\t\t// a client that enters the SHUTDOWN state never leaves this state, and all new RPCs should\n\t\t\t// fail immediately. Further polling is futile, in other words, and so we\n\t\t\t// return an error immediately to indicate that the caller can close the connection.\n\t\t\tcase connectivity.Shutdown:\n\t\t\t\treturn ErrConnectionShutdown\n\n\t\t\t// If the connection is IDLE, CONNECTING, or in a TRANSIENT_FAILURE mode,\n\t\t\t// then we wait to see if it will transition to a READY state.\n\t\t\tdefault:\n\t\t\t\tif !client.cc.WaitForStateChange(ctx, connState) {\n\t\t\t\t\t// If the client has failed to transition, fail so that the caller can close the connection.\n\t\t\t\t\treturn fmt.Errorf(\"failed to transition from state %s\", connState)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (chanSync *channelRelaySync) WaitOnSetup() {\n\tdefer chanSync.shared.setupComplete.Wait()\n}", "func (client *Client) WaitForBrokerReady(name string) error {\n\tnamespace := client.Namespace\n\tbrokerMeta := base.MetaEventing(name, namespace, \"Broker\")\n\tif err := base.WaitForResourceReady(client.Dynamic, brokerMeta); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Wait(dev *model.Dev, okStatusList []config.UpState) error {\n\toktetoLog.Spinner(\"Activating your development container...\")\n\toktetoLog.StartSpinner()\n\tdefer oktetoLog.StopSpinner()\n\n\tstop := make(chan os.Signal, 1)\n\tsignal.Notify(stop, os.Interrupt)\n\texit := make(chan error, 1)\n\n\tgo func() {\n\n\t\tticker := time.NewTicker(500 * time.Millisecond)\n\t\tfor {\n\t\t\tstatus, err := config.GetState(dev.Name, dev.Namespace)\n\t\t\tif err != nil {\n\t\t\t\texit <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif status == config.Failed {\n\t\t\t\texit <- fmt.Errorf(\"your development container has failed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, okStatus := range okStatusList {\n\t\t\t\tif status == okStatus {\n\t\t\t\t\texit <- nil\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\t<-ticker.C\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-stop:\n\t\toktetoLog.Infof(\"CTRL+C received, starting shutdown sequence\")\n\t\toktetoLog.StopSpinner()\n\t\treturn oktetoErrors.ErrIntSig\n\tcase err := <-exit:\n\t\tif err != nil {\n\t\t\toktetoLog.Infof(\"exit signal received due to error: %s\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (cli *CLI) SystemWaitReady() {\n\tintervalSec := time.Duration(3)\n\tutil.Panic(wait.PollImmediateInfinite(intervalSec*time.Second, func() (bool, error) {\n\t\tsys := &nbv1.NooBaa{}\n\t\terr := cli.Client.Get(cli.Ctx, client.ObjectKey{Namespace: cli.Namespace, Name: cli.SystemName}, sys)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif sys.Status.Phase == nbv1.SystemPhaseReady {\n\t\t\tcli.Log.Printf(\"✅ System Phase is \\\"%s\\\".\\n\", sys.Status.Phase)\n\t\t\treturn true, nil\n\t\t}\n\t\tif sys.Status.Phase == nbv1.SystemPhaseRejected {\n\t\t\treturn false, fmt.Errorf(\"❌ System Phase is \\\"%s\\\". describe noobaa for more information\", sys.Status.Phase)\n\t\t}\n\t\tcli.Log.Printf(\"⏳ System Phase is \\\"%s\\\". Waiting for it to be ready ...\\n\", sys.Status.Phase)\n\t\treturn false, nil\n\t}))\n}", "func (b *Bucket) WaitUntilReady(timeout time.Duration, opts *WaitUntilReadyOptions) error {\n\tif opts == nil {\n\t\topts = &WaitUntilReadyOptions{}\n\t}\n\n\tcli := b.sb.getCachedClient()\n\tif cli == nil {\n\t\treturn errors.New(\"bucket is not connected\")\n\t}\n\n\terr := cli.getBootstrapError()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprovider, err := cli.getWaitUntilReadyProvider()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdesiredState := opts.DesiredState\n\tif desiredState == 0 {\n\t\tdesiredState = ClusterStateOnline\n\t}\n\n\terr = provider.WaitUntilReady(\n\t\ttime.Now().Add(timeout),\n\t\tgocbcore.WaitUntilReadyOptions{\n\t\t\tDesiredState: gocbcore.ClusterState(desiredState),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (k *kubelet) waitForNodeReady() error {\n\tkc, _ := k.config.AdminConfig.ToYAMLString() //nolint:errcheck // This is checked in Validate().\n\n\tc, err := client.NewClient([]byte(kc))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating kubernetes client: %w\", err)\n\t}\n\n\treturn c.WaitForNodeReady(k.config.Name)\n}", "func waitWebhookConfigurationReady(f *framework.Framework, namespace string) error {\n\tcmClient := f.VclusterClient.CoreV1().ConfigMaps(namespace + \"-markers\")\n\treturn wait.PollUntilContextTimeout(f.Context, 100*time.Millisecond, 30*time.Second, true, func(ctx context.Context) (bool, error) {\n\t\tmarker := &corev1.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: string(uuid.NewUUID()),\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tuniqueName: \"true\",\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t_, err := cmClient.Create(ctx, marker, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\t// The always-deny webhook does not provide a reason, so check for the error string we expect\n\t\t\tif strings.Contains(err.Error(), \"denied\") {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\t// best effort cleanup of markers that are no longer needed\n\t\t_ = cmClient.Delete(ctx, marker.GetName(), metav1.DeleteOptions{})\n\t\tf.Log.Infof(\"Waiting for webhook configuration to be ready...\")\n\t\treturn false, nil\n\t})\n}", "func (n *Netlify) WaitUntilDeployReady(ctx context.Context, d *models.Deploy) (*models.Deploy, error) {\n\treturn n.waitForState(ctx, d, \"prepared\", \"ready\")\n}", "func (g *Group) WaitTillReady() {\n\t<-g.readyCh\n}", "func (m *MachineScope) SetReady() {\n\tm.AzureMachine.Status.Ready = true\n}", "func (h *Handler) WaitReady(name string) error {\n\tif h.IsReady(name) {\n\t\treturn nil\n\t}\n\n\terrCh := make(chan error, 1)\n\tchkCh := make(chan struct{}, 1)\n\tsigCh := make(chan os.Signal, 1)\n\tsignal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGQUIT)\n\tctxCheck, cancelCheck := context.WithCancel(h.ctx)\n\tctxWatch, cancelWatch := context.WithCancel(h.ctx)\n\tdefer cancelCheck()\n\tdefer cancelWatch()\n\n\t// this goroutine used to check whether pod is ready and exists.\n\t// if pod already ready, return nil.\n\t// if pod does not exist, return error.\n\t// if pod exists but not ready, return nothing.\n\tgo func(context.Context) {\n\t\t<-chkCh\n\t\tfor i := 0; i < 6; i++ {\n\t\t\t// pod is already ready, return nil\n\t\t\tif h.IsReady(name) {\n\t\t\t\terrCh <- nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// pod no longer exists, return err\n\t\t\t_, err := h.Get(name)\n\t\t\tif k8serrors.IsNotFound(err) {\n\t\t\t\terrCh <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// pod exists but not ready, return northing.\n\t\t\tif err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Error(err)\n\t\t\ttime.Sleep(time.Second * 10)\n\t\t}\n\t}(ctxCheck)\n\n\t// this goroutine used to watch pod.\n\tgo func(ctx context.Context) {\n\t\tfor {\n\t\t\ttimeout := int64(0)\n\t\t\tlistOptions := metav1.SingleObject(metav1.ObjectMeta{Name: name, Namespace: h.namespace})\n\t\t\tlistOptions.TimeoutSeconds = &timeout\n\t\t\twatcher, err := h.clientset.CoreV1().Pods(h.namespace).Watch(h.ctx, listOptions)\n\t\t\tif err != nil {\n\t\t\t\terrCh <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tchkCh <- struct{}{}\n\t\t\tfor event := range watcher.ResultChan() {\n\t\t\t\tswitch event.Type {\n\t\t\t\tcase watch.Modified:\n\t\t\t\t\tif h.IsReady(name) {\n\t\t\t\t\t\twatcher.Stop()\n\t\t\t\t\t\terrCh <- nil\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\tcase watch.Deleted:\n\t\t\t\t\twatcher.Stop()\n\t\t\t\t\terrCh <- fmt.Errorf(\"pod/%s was deleted\", name)\n\t\t\t\t\treturn\n\t\t\t\tcase watch.Bookmark:\n\t\t\t\t\tlog.Debug(\"watch pod: bookmark\")\n\t\t\t\tcase watch.Error:\n\t\t\t\t\tlog.Debug(\"watch pod: error\")\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If event channel is closed, it means the kube-apiserver has closed the connection.\n\t\t\tlog.Debug(\"watch pod: reconnect to kubernetes\")\n\t\t\twatcher.Stop()\n\t\t}\n\t}(ctxWatch)\n\n\tselect {\n\tcase sig := <-sigCh:\n\t\treturn fmt.Errorf(\"cancelled by signal: %s\", sig.String())\n\tcase err := <-errCh:\n\t\treturn err\n\t}\n}", "func waitForMachineState(api *cloudapi.Client, id, state string, timeout time.Duration) error {\n\treturn waitFor(\n\t\tfunc() (bool, error) {\n\t\t\tcurrentState, err := readMachineState(api, id)\n\t\t\treturn currentState == state, err\n\t\t},\n\t\tmachineStateChangeCheckInterval,\n\t\tmachineStateChangeTimeout,\n\t)\n}", "func (i *TiFlashInstance) Ready(ctx context.Context, e ctxt.Executor, timeout uint64, tlsCfg *tls.Config) error {\n\t// FIXME: the timeout is applied twice in the whole `Ready()` process, in the worst\n\t// case it might wait double time as other components\n\tif err := PortStarted(ctx, e, i.GetServicePort(), timeout); err != nil {\n\t\treturn err\n\t}\n\n\tscheme := \"http\"\n\tif i.topo.BaseTopo().GlobalOptions.TLSEnabled {\n\t\tscheme = \"https\"\n\t}\n\taddr := fmt.Sprintf(\"%s://%s/tiflash/store-status\", scheme, utils.JoinHostPort(i.GetManageHost(), i.GetStatusPort()))\n\treq, err := http.NewRequest(\"GET\", addr, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq = req.WithContext(ctx)\n\n\tretryOpt := utils.RetryOption{\n\t\tDelay: time.Second,\n\t\tTimeout: time.Second * time.Duration(timeout),\n\t}\n\tvar queryErr error\n\tif err := utils.Retry(func() error {\n\t\tclient := utils.NewHTTPClient(statusQueryTimeout, tlsCfg)\n\t\tres, err := client.Client().Do(req)\n\t\tif err != nil {\n\t\t\tqueryErr = err\n\t\t\treturn err\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, err := io.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\tqueryErr = err\n\t\t\treturn err\n\t\t}\n\t\tif res.StatusCode == http.StatusNotFound || string(body) == \"Running\" {\n\t\t\treturn nil\n\t\t}\n\n\t\terr = fmt.Errorf(\"tiflash store status is '%s', not fully running yet\", string(body))\n\t\tqueryErr = err\n\t\treturn err\n\t}, retryOpt); err != nil {\n\t\treturn perrs.Annotatef(queryErr, \"timed out waiting for tiflash %s:%d to be ready after %ds\",\n\t\t\ti.Host, i.Port, timeout)\n\t}\n\treturn nil\n}", "func (client *Client) WaitForTriggerReady(name string) error {\n\tnamespace := client.Namespace\n\ttriggerMeta := base.MetaEventing(name, namespace, \"Trigger\")\n\tif err := base.WaitForResourceReady(client.Dynamic, triggerMeta); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_m *BandwidthThrottlerSvc) Wait() {\n\t_m.Called()\n}", "func (s *SeleniumServer) Wait() {\n\terr := s.cmd.Wait()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func waitForApiServerToBeUp(svcMasterIp string, sshClientConfig *ssh.ClientConfig,\n\ttimeout time.Duration) error {\n\tkubeConfigPath := GetAndExpectStringEnvVar(gcKubeConfigPath)\n\twaitErr := wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\tcmd := fmt.Sprintf(\"kubectl get ns,sc --kubeconfig %s\",\n\t\t\tkubeConfigPath)\n\t\tframework.Logf(\"Invoking command '%v' on host %v\", cmd,\n\t\t\tsvcMasterIp)\n\t\tcmdResult, err := sshExec(sshClientConfig, svcMasterIp,\n\t\t\tcmd)\n\t\tframework.Logf(\"result %v\", cmdResult)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif err == nil {\n\t\t\tframework.Logf(\"Apiserver is fully up\")\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn waitErr\n}", "func (a *Application) Wait() {\n\t<-a.terminated\n\tlog.Printf(\"[TEST] thats all folks\")\n}", "func (b *Bot) WaitUntilCompletion() {\n\tb.server.Wait()\n}", "func (svc *SSHService) WaitServerReady(hostParam interface{}, timeout time.Duration) error {\n\tvar err error\n\tsshSvc := NewSSHService(svc.provider)\n\tssh, err := sshSvc.GetConfig(hostParam)\n\tif err != nil {\n\t\treturn logicErrf(err, \"Failed to read SSH config\")\n\t}\n\twaitErr := ssh.WaitServerReady(timeout)\n\treturn infraErr(waitErr)\n}", "func (s *Serv) Wait() {\n\t<-s.done\n}", "func ensureVWHReady(){\n\tMustRunWithTimeout(certsReadyTime, \"kubectl create ns check-webhook\")\n\tMustRun(\"kubectl delete ns check-webhook\")\n}", "func (b *Botanist) WaitUntilRequiredExtensionsReady(ctx context.Context) error {\n\treturn retry.UntilTimeout(ctx, 5*time.Second, time.Minute, func(ctx context.Context) (done bool, err error) {\n\t\tif err := b.RequiredExtensionsReady(ctx); err != nil {\n\t\t\tb.Logger.Infof(\"Waiting until all the required extension controllers are ready (%+v)\", err)\n\t\t\treturn retry.MinorError(err)\n\t\t}\n\t\treturn retry.Ok()\n\t})\n}", "func (proxy *ProxyService) WaitReady(ctx context.Context) (bool, error) {\n\tselect {\n\tcase <-proxy.readyCh:\n\t\treturn proxy.IsReady(), nil\n\tcase <-ctx.Done():\n\t\treturn false, trace.Wrap(ctx.Err(), \"proxy service is not ready\")\n\t}\n}", "func (a *serverApp) Wait() {\n\t<-a.terminated\n}", "func (m *Machine) hasReadyCondition() bool {\n\n\tif m.vmiInstance == nil {\n\t\treturn false\n\t}\n\n\tfor _, cond := range m.vmiInstance.Status.Conditions {\n\t\tif cond.Type == kubevirtv1.VirtualMachineInstanceReady &&\n\t\t\tcond.Status == corev1.ConditionTrue {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func WaitFabricReady(ctx context.Context, log logging.Logger, params WaitFabricReadyParams) error {\n\tif common.InterfaceIsNil(params.StateProvider) {\n\t\treturn errors.New(\"nil NetDevStateProvider\")\n\t}\n\n\tif len(params.FabricIfaces) == 0 {\n\t\treturn errors.New(\"no fabric interfaces requested\")\n\t}\n\n\tparams.FabricIfaces = common.DedupeStringSlice(params.FabricIfaces)\n\n\tch := make(chan error)\n\tgo loopFabricReady(log, params, ch)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase err := <-ch:\n\t\treturn err\n\t}\n}", "func (c *apiConsumers) Wait() {\n\tc.wait()\n}", "func Wait(options *WaitOptions, settings *env.Settings) error {\n\tkc, err := env.GetClient(settings)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//return status(kc, options, settings.Namespace)\n\treturn wait(kc, options, settings.Namespace)\n}", "func WaitOnReady(pvCount int, sleep, timeout time.Duration) bool {\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\tch := make(chan bool)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tch <- AreAllReady(pvCount)\n\t\t\t\ttime.Sleep(sleep)\n\t\t\t}\n\t\t}\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase ready := <-ch:\n\t\t\tif ready {\n\t\t\t\treturn ready\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tDescribePVs()\n\t\t\treturn false\n\t\t}\n\t}\n}", "func (p *Init) Wait() {\n\t<-p.waitBlock\n}", "func (app *ClientApplication) Ready() error {\n\tif ready, err := app.client().Ready(); err != nil {\n\t\treturn err\n\t} else if !ready {\n\t\treturn fmt.Errorf(\"worker not ready\")\n\t}\n\tlog.Infof(\"Worker is ready\")\n\treturn nil\n}", "func TestWaitUntilAllNodesReady(t *testing.T) {\n\tt.Parallel()\n\n\toptions := NewKubectlOptions(\"\", \"\", \"default\")\n\n\tWaitUntilAllNodesReady(t, options, 12, 5*time.Second)\n\n\tnodes := GetNodes(t, options)\n\tnodeNames := map[string]bool{}\n\tfor _, node := range nodes {\n\t\tnodeNames[node.Name] = true\n\t}\n\n\treadyNodes := GetReadyNodes(t, options)\n\treadyNodeNames := map[string]bool{}\n\tfor _, node := range readyNodes {\n\t\treadyNodeNames[node.Name] = true\n\t}\n\n\tassert.Equal(t, nodeNames, readyNodeNames)\n}", "func (s WeworkSender) Ready() bool {\n\tif s.InfoKey != \"\" && s.WarnKey != \"\" && s.ErrorKey != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}", "func (e *endpoint) Wait() {\n\te.completed.Wait()\n}", "func (client *Client) WaitForChannelReady(name string) error {\n\tnamespace := client.Namespace\n\tchannelMeta := base.MetaEventing(name, namespace, \"Channel\")\n\tif err := base.WaitForResourceReady(client.Dynamic, channelMeta); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func WaitReady(namespaceStore *nbv1.NamespaceStore) bool {\n\tlog := util.Logger()\n\tklient := util.KubeClient()\n\n\tinterval := time.Duration(3)\n\n\terr := wait.PollUntilContextCancel(ctx, interval*time.Second, true, func(ctx context.Context) (bool, error) {\n\t\terr := klient.Get(util.Context(), util.ObjectKey(namespaceStore), namespaceStore)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"⏳ Failed to get NamespaceStore: %s\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tCheckPhase(namespaceStore)\n\t\tif namespaceStore.Status.Phase == nbv1.NamespaceStorePhaseRejected {\n\t\t\treturn false, fmt.Errorf(\"NamespaceStorePhaseRejected\")\n\t\t}\n\t\tif namespaceStore.Status.Phase != nbv1.NamespaceStorePhaseReady {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\treturn (err == nil)\n}", "func (mod *Module)WaitTillStartupDone(){\n\tfor mod.hasRunStartup == false{//wait for startup to stop running\n\t\ttime.Sleep(time.Millisecond*10)\n\t}\n}", "func (b *Botanist) WaitUntilKubeAPIServerReady(ctx context.Context) error {\n\treturn retry.UntilTimeout(ctx, 5*time.Second, 300*time.Second, func(ctx context.Context) (done bool, err error) {\n\n\t\tdeploy := &appsv1.Deployment{}\n\t\tif err := b.K8sSeedClient.DirectClient().Get(ctx, kutil.Key(b.Shoot.SeedNamespace, v1beta1constants.DeploymentNameKubeAPIServer), deploy); err != nil {\n\t\t\treturn retry.SevereError(err)\n\t\t}\n\t\tif deploy.Generation != deploy.Status.ObservedGeneration {\n\t\t\treturn retry.MinorError(fmt.Errorf(\"kube-apiserver not observed at latest generation (%d/%d)\",\n\t\t\t\tdeploy.Status.ObservedGeneration, deploy.Generation))\n\t\t}\n\n\t\treplicas := int32(0)\n\t\tif deploy.Spec.Replicas != nil {\n\t\t\treplicas = *deploy.Spec.Replicas\n\t\t}\n\t\tif replicas != deploy.Status.UpdatedReplicas {\n\t\t\treturn retry.MinorError(fmt.Errorf(\"kube-apiserver does not have enough updated replicas (%d/%d)\",\n\t\t\t\tdeploy.Status.UpdatedReplicas, replicas))\n\t\t}\n\t\tif replicas != deploy.Status.Replicas {\n\t\t\treturn retry.MinorError(fmt.Errorf(\"kube-apiserver deployment has outdated replicas\"))\n\t\t}\n\t\tif replicas != deploy.Status.AvailableReplicas {\n\t\t\treturn retry.MinorError(fmt.Errorf(\"kube-apiserver does not have enough available replicas (%d/%d\",\n\t\t\t\tdeploy.Status.AvailableReplicas, replicas))\n\t\t}\n\n\t\treturn retry.Ok()\n\t})\n}", "func notifyReady() {\n}", "func (c *myClient) waitForEnvironmentsReady(p, t int, envList ...string) (err error) {\n\n\tlogger.Infof(\"Waiting up to %v seconds for the environments to be ready\", t)\n\ttimeOut := 0\n\tfor timeOut < t {\n\t\tlogger.Info(\"Waiting for the environments\")\n\t\ttime.Sleep(time.Duration(p) * time.Second)\n\t\ttimeOut = timeOut + p\n\t\tif err = c.checkForBusyEnvironments(envList); err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif timeOut >= t {\n\t\terr = fmt.Errorf(\"waitForEnvironmentsReady timed out\")\n\t}\n\treturn err\n}", "func (relaySync *relaySync) WaitForInit(ctx context.Context) error {\n\tselect {\n\tcase <-relaySync.firstSetupWait:\n\tcase <-ctx.Done():\n\t\treturn streadway.ErrClosed\n\t}\n\n\treturn nil\n}", "func (m *StateSwitcherMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func waitForClusterReady(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForClusterStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(cluster *capiv1alpha1.Cluster) bool {\n\t\t\tstatus, err := controller.ClusterStatusFromClusterAPI(cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn status.Ready\n\t\t},\n\t)\n}", "func (client *Client) WaitHostReady(hostID string, timeout time.Duration) (*model.Host, error) {\n\treturn client.osclt.WaitHostReady(hostID, timeout)\n}", "func (a *App) Ready() {\n\ta.ready.Wait()\n}", "func (a *App) Ready() {\n\ta.ready.Wait()\n}", "func (_m *Broadcaster) DependentReady() {\n\t_m.Called()\n}", "func IsReady(name string, timing ...time.Duration) feature.StepFn {\n\treturn k8s.IsReady(GVR(), name, timing...)\n}", "func waitForAPI(ctx context.Context, client *gophercloud.ServiceClient) {\n\thttpClient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}\n\n\t// NOTE: Some versions of Ironic inspector returns 404 for /v1/ but 200 for /v1,\n\t// which seems to be the default behavior for Flask. Remove the trailing slash\n\t// from the client endpoint.\n\tendpoint := strings.TrimSuffix(client.Endpoint, \"/\")\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for API to become available...\")\n\n\t\t\tr, err := httpClient.Get(endpoint)\n\t\t\tif err == nil {\n\t\t\t\tstatusCode := r.StatusCode\n\t\t\t\tr.Body.Close()\n\t\t\t\tif statusCode == http.StatusOK {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func (f *FakeCmdRunner) Wait() error {\n\treturn f.Err\n}", "func (s *sshClientExternal) Wait() error {\n\tif s.session == nil {\n\t\treturn nil\n\t}\n\treturn s.session.Wait()\n}", "func (a *Agent) Wait() error {\n\ta.init()\n\treturn <-a.waitCh\n}", "func ready(s *sdk.SDK) {\n\terr := s.Ready()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not send ready message\")\n\t}\n}", "func Wait() {\n\tdefaultManager.Wait()\n}", "func (node *Node) Wait() error {\n\treturn node.httpAPIServer.Wait()\n}", "func (b *buildandrun) Wait() {\n\t<-b.done\n}", "func (p *EventReplay) Wait() {}", "func (e *engine) Wait(context.Context, *Spec, *Step) (*State, error) {\n\treturn nil, nil // no-op for bash implementation\n}", "func (oc *contractTransmitter) Ready() error { return nil }", "func (s *Service) Wait() {\n\ts.waiter.Wait()\n}", "func (s *Service) Wait() {\n\ts.waiter.Wait()\n}", "func (s *Service) Wait() {\n\ts.waiter.Wait()\n}", "func (s *Store) WaitForInit() {\n\ts.initComplete.Wait()\n}", "func (elm *etcdLeaseManager) Wait() {\n\telm.wg.Wait()\n}", "func (c *controller) ready(w http.ResponseWriter, r *http.Request) {\n\tlogger.Trace(\"ready check\")\n\tw.WriteHeader(http.StatusNoContent)\n}", "func (s *Service) Wait(timeout time.Duration) (int, error) {\n\turl := s.BaseURL\n\tswitch s.Name {\n\tcase DeployService:\n\t\turl += \"/status.html\" // because /ApplicationStatus is not publicly reachable in Vespa Cloud\n\tcase QueryService, DocumentService:\n\t\turl += \"/ApplicationStatus\"\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"invalid service: %s\", s.Name)\n\t}\n\treturn waitForOK(s, url, timeout)\n}", "func (a *Application) Wait() {\n\t<-a.terminated\n}", "func WaitAPIServiceReady(c *aggregator.Clientset, name string, timeout time.Duration) error {\n\tif err := wait.PollImmediate(time.Second, timeout, func() (done bool, err error) {\n\t\tapiService, e := c.ApiregistrationV1().APIServices().Get(context.TODO(), name, metav1.GetOptions{})\n\t\tif e != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif apiregistrationv1helper.IsAPIServiceConditionTrue(apiService, apiregistrationv1.Available) {\n\t\t\treturn true, nil\n\t\t}\n\n\t\tklog.Infof(\"Waiting for APIService(%s) condition(%s), will try\", name, apiregistrationv1.Available)\n\t\treturn false, nil\n\t}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *HTTPProbe) Ready() {\n\tp.ready.Swap(1)\n}", "func (c *NetClient) Wait() {\n\t<-c.haltedCh\n}", "func WaitForResourceReady(dynamicClient dynamic.Interface, obj *MetaResource) error {\n\tmetricName := fmt.Sprintf(\"WaitForResourceReady/%s\", obj.Name)\n\t_, span := trace.StartSpan(context.Background(), metricName)\n\tdefer span.End()\n\n\treturn wait.PollImmediate(interval, timeout, func() (bool, error) {\n\t\treturn isResourceReady(dynamicClient, obj)\n\t})\n}", "func (h *KubernetesHelper) WaitUntilDeployReady(deploys map[string]DeploySpec) {\n\tctx := context.Background()\n\tfor deploy, spec := range deploys {\n\t\tif err := h.CheckPods(ctx, spec.Namespace, deploy, 1); err != nil {\n\t\t\tvar out string\n\t\t\t//nolint:errorlint\n\t\t\tif rce, ok := err.(*RestartCountError); ok {\n\t\t\t\tout = fmt.Sprintf(\"Error running test: failed to wait for deploy/%s to become 'ready', too many restarts (%v)\\n\", deploy, rce)\n\t\t\t} else {\n\t\t\t\tout = fmt.Sprintf(\"Error running test: failed to wait for deploy/%s to become 'ready', timed out waiting for condition\\n\", deploy)\n\t\t\t}\n\t\t\tos.Stderr.Write([]byte(out))\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func (n *Netlify) WaitUntilDeployLive(ctx context.Context, d *models.Deploy) (*models.Deploy, error) {\n\treturn n.waitForState(ctx, d, \"ready\")\n}", "func WaitForCondition(mcpName string, conditionType machineconfigv1.MachineConfigPoolConditionType, conditionStatus corev1.ConditionStatus) {\n\n\tvar cnfNodes []corev1.Node\n\trunningOnSingleNode, err := cluster.IsSingleNode()\n\tExpectWithOffset(1, err).ToNot(HaveOccurred())\n\t// checking in eventually as in case of single node cluster the only node may\n\t// be rebooting\n\tEventuallyWithOffset(1, func() error {\n\t\tmcp, err := GetByName(mcpName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed getting MCP by name\")\n\t\t}\n\n\t\tnodeLabels := mcp.Spec.NodeSelector.MatchLabels\n\t\tkey, _ := components.GetFirstKeyAndValue(nodeLabels)\n\t\treq, err := labels.NewRequirement(key, selection.Exists, []string{})\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed creating node selector\")\n\t\t}\n\n\t\tselector := labels.NewSelector()\n\t\tselector = selector.Add(*req)\n\t\tcnfNodes, err = nodes.GetBySelector(selector)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed getting nodes by selector\")\n\t\t}\n\n\t\ttestlog.Infof(\"MCP %q is targeting %v node(s)\", mcp.Name, len(cnfNodes))\n\t\treturn nil\n\t}, cluster.ComputeTestTimeout(10*time.Minute, runningOnSingleNode), 5*time.Second).ShouldNot(HaveOccurred(), \"Failed to find CNF nodes by MCP %q\", mcpName)\n\n\t// timeout should be based on the number of worker-cnf nodes\n\ttimeout := time.Duration(len(cnfNodes)*mcpUpdateTimeoutPerNode) * time.Minute\n\tif len(cnfNodes) == 0 {\n\t\ttimeout = 2 * time.Minute\n\t}\n\n\tEventuallyWithOffset(1, func() corev1.ConditionStatus {\n\t\treturn GetConditionStatus(mcpName, conditionType)\n\t}, cluster.ComputeTestTimeout(timeout, runningOnSingleNode), 30*time.Second).Should(Equal(conditionStatus), \"Failed to find condition status by MCP %q\", mcpName)\n}", "func (b *Botanist) WaitUntilEtcdsReady(ctx context.Context) error {\n\treturn etcd.WaitUntilEtcdsReady(\n\t\tctx,\n\t\tb.K8sSeedClient.DirectClient(),\n\t\tb.Logger,\n\t\tb.Shoot.SeedNamespace,\n\t\t2,\n\t\t5*time.Second,\n\t\t3*time.Minute,\n\t\t5*time.Minute,\n\t)\n}", "func (customer *Customer) CustomerIsReadyAndEntersWaitState(check bool) (err error) {\n\n\tvar currentTrigger ssm.Trigger\n\n\tcurrentTrigger = TriggerCustomerWaitsForCommands\n\n\tswitch check {\n\n\tcase true:\n\t\t// Do a check if state machine is in correct state for triggering event\n\t\tif customer.CustomerStateMachine.CanFire(currentTrigger.Key) == true {\n\t\t\terr = nil\n\n\t\t} else {\n\n\t\t\terr = customer.CustomerStateMachine.Fire(currentTrigger.Key, nil)\n\t\t}\n\n\tcase false:\n\t\t// Execute Trigger\n\t\terr = customer.CustomerStateMachine.Fire(currentTrigger.Key, nil)\n\t\tif err != nil {\n\t\t\tlogTriggerStateError(4, customer.CustomerStateMachine.State(), currentTrigger, err)\n\n\t\t}\n\t}\n\n\treturn err\n\n}", "func (c *controller) waitDeploymentReady(\n\tctx context.Context,\n\tdeploymentName string,\n\tnamespace string,\n) error {\n\t// Init ticker to check status every second\n\tticker := time.NewTicker(time.Second)\n\tdefer ticker.Stop()\n\n\t// Init knative ServicesGetter\n\tdeployments := c.k8sAppsClient.Deployments(namespace)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn fmt.Errorf(\"timeout waiting for deployment %s to be ready\", deploymentName)\n\t\tcase <-ticker.C:\n\t\t\tdeployment, err := deployments.Get(deploymentName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to get deployment status for %s: %v\", deploymentName, err)\n\t\t\t}\n\n\t\t\tif deploymentReady(deployment) {\n\t\t\t\t// Service is completely ready\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n}", "func (r *Response) wait() {\n\tr.StatusCode = HTTPStatusOK\n}" ]
[ "0.81729543", "0.73304754", "0.6926979", "0.69264543", "0.6682231", "0.6572147", "0.6555187", "0.6544689", "0.64363945", "0.62041384", "0.61236566", "0.60687506", "0.60536796", "0.60392857", "0.5971176", "0.59554976", "0.58414894", "0.58387625", "0.5814672", "0.5803259", "0.5783128", "0.577015", "0.57497394", "0.57397735", "0.57397246", "0.5721885", "0.5696095", "0.56816375", "0.5658691", "0.5648395", "0.5647614", "0.56443214", "0.5635702", "0.5634624", "0.5622948", "0.5599984", "0.5588777", "0.5585816", "0.5568214", "0.55585915", "0.55512005", "0.55510014", "0.5536125", "0.552952", "0.5520784", "0.5511295", "0.55084884", "0.5501455", "0.5499604", "0.5495508", "0.5473597", "0.54714936", "0.5465977", "0.5462402", "0.54593503", "0.54591805", "0.5453497", "0.5431939", "0.54318064", "0.5431432", "0.54226506", "0.5419544", "0.5408438", "0.5400009", "0.538846", "0.5385435", "0.53802556", "0.53802556", "0.53777194", "0.5368712", "0.53631085", "0.5352946", "0.5347596", "0.534614", "0.53440166", "0.5332794", "0.53289384", "0.5327947", "0.53262335", "0.5323447", "0.53205186", "0.53196967", "0.53196967", "0.53196967", "0.5315257", "0.5313336", "0.53087336", "0.5300953", "0.53009075", "0.5300501", "0.52923", "0.52921873", "0.5290592", "0.52893496", "0.5285912", "0.5282355", "0.5278832", "0.5270685", "0.52649003", "0.5262643" ]
0.7730005
1
waitForCRDs waits for machinecontroller CRDs to be created and become established
func waitForCRDs(s *state.State) error { condFn := clientutil.CRDsReadyCondition(s.Context, s.DynamicClient, CRDNames()) err := wait.PollUntilContextTimeout(s.Context, 5*time.Second, 3*time.Minute, false, condFn.WithContext()) return fail.KubeClient(err, "waiting for machine-controller CRDs to became ready") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MeshReconciler) waitForCRD(name string, client runtimeclient.Client) error {\n\tm.logger.WithField(\"name\", name).Debug(\"waiting for CRD\")\n\n\tbackoffConfig := backoff.ConstantBackoffConfig{\n\t\tDelay: time.Duration(backoffDelaySeconds) * time.Second,\n\t\tMaxRetries: backoffMaxretries,\n\t}\n\tbackoffPolicy := backoff.NewConstantBackoffPolicy(backoffConfig)\n\n\tvar crd apiextensionsv1beta1.CustomResourceDefinition\n\terr := backoff.Retry(func() error {\n\t\terr := client.Get(context.Background(), types.NamespacedName{\n\t\t\tName: name,\n\t\t}, &crd)\n\t\tif err != nil {\n\t\t\treturn errors.WrapIf(err, \"could not get CRD\")\n\t\t}\n\n\t\tfor _, condition := range crd.Status.Conditions {\n\t\t\tif condition.Type == apiextensionsv1beta1.Established {\n\t\t\t\tif condition.Status == apiextensionsv1beta1.ConditionTrue {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn errors.New(\"CRD is not established yet\")\n\t}, backoffPolicy)\n\n\treturn err\n}", "func waitForCRDEstablishment(clientset apiextensionsclient.Interface) error {\n\treturn wait.Poll(500*time.Millisecond, 60*time.Second, func() (bool, error) {\n\t\tsparkAppCrd, err := getCRD(clientset)\n\t\tfor _, cond := range sparkAppCrd.Status.Conditions {\n\t\t\tswitch cond.Type {\n\t\t\tcase apiextensionsv1beta1.Established:\n\t\t\t\tif cond.Status == apiextensionsv1beta1.ConditionTrue {\n\t\t\t\t\treturn true, err\n\t\t\t\t}\n\t\t\tcase apiextensionsv1beta1.NamesAccepted:\n\t\t\t\tif cond.Status == apiextensionsv1beta1.ConditionFalse {\n\t\t\t\t\tfmt.Printf(\"Name conflict: %v\\n\", cond.Reason)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false, err\n\t})\n}", "func waitForCRDCreated(clientset *fake.Clientset, CRDName string) error {\n\treturn wait.Poll(50*time.Millisecond, 5*time.Second, func() (bool, error) {\n\t\t_, err := clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Get(CRDName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn true, err\n\t})\n}", "func (rcc *rotateCertsCmd) waitForControlPlaneReadiness() error {\n\tlog.Info(\"Checking health of control plane components\")\n\tpods := make([]string, 0)\n\tfor _, n := range rcc.cs.Properties.GetMasterVMNameList() {\n\t\tfor _, c := range []string{kubeAddonManager, kubeAPIServer, kubeControllerManager, kubeScheduler} {\n\t\t\tpods = append(pods, fmt.Sprintf(\"%s-%s\", c, n))\n\t\t}\n\t}\n\tif err := ops.WaitForReady(rcc.kubeClient, metav1.NamespaceSystem, pods, rotateCertsDefaultInterval, rotateCertsDefaultTimeout, rcc.nodes); err != nil {\n\t\treturn errors.Wrap(err, \"waiting for control plane containers to reach the Ready state within the timeout period\")\n\t}\n\treturn nil\n}", "func waitForMachineController(ctx context.Context, client dynclient.Client) error {\n\tcondFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{\n\t\tNamespace: resources.MachineControllerNameSpace,\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\n\t\t\tappLabelKey: resources.MachineControllerName,\n\t\t}),\n\t})\n\n\treturn fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), \"waiting for machine-controller to became ready\")\n}", "func waitForKnativeCrdsRegistered(timeout, interval time.Duration) error {\n\telapsed := time.Duration(0)\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(interval):\n\t\t\tif err := kubectl(nil, \"get\", \"images.caching.internal.knative.dev\"); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\telapsed += interval\n\t\t\tif elapsed > timeout {\n\t\t\t\treturn errors.Errorf(\"failed to confirm knative crd registration after %v\", timeout)\n\t\t\t}\n\t\t}\n\t}\n}", "func waitForConductor(ctx context.Context, client *gophercloud.ServiceClient) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for conductor API to become available...\")\n\t\t\tdriverCount := 0\n\n\t\t\tdrivers.ListDrivers(client, drivers.ListDriversOpts{\n\t\t\t\tDetail: false,\n\t\t\t}).EachPage(func(page pagination.Page) (bool, error) {\n\t\t\t\tactual, err := drivers.ExtractDrivers(page)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tdriverCount += len(actual)\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\t// If we have any drivers, conductor is up.\n\t\t\tif driverCount > 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func waitUntilRDSClusterCreated(rdsClientSess *rds.RDS, restoreParams map[string]string) error {\n\trdsClusterName := restoreParams[\"restoreRDS\"]\n\n\tmaxWaitAttempts := 120\n\n\tinput := &rds.DescribeDBClustersInput{\n\t\tDBClusterIdentifier: aws.String(rdsClusterName),\n\t}\n\n\tfmt.Printf(\"Wait until RDS cluster [%v] is fully created ...\\n\", rdsClusterName)\n\n\tstart := time.Now()\n\n\t// Check until created\n\tfor waitAttempt := 0; waitAttempt < maxWaitAttempts; waitAttempt++ {\n\t\telapsedTime := time.Since(start)\n\t\tif waitAttempt > 0 {\n\t\t\tformattedTime := strings.Split(fmt.Sprintf(\"%6v\", elapsedTime), \".\")\n\t\t\tfmt.Printf(\"Cluster creation elapsed time: %vs\\n\", formattedTime[0])\n\t\t}\n\n\t\tresp, err := rdsClientSess.DescribeDBClusters(input)\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Wait RDS cluster creation err %v\", err)\n\t\t}\n\n\t\tfmt.Printf(\"Cluster status: [%s]\\n\", *resp.DBClusters[0].Status)\n\t\tif *resp.DBClusters[0].Status == \"available\" {\n\t\t\tfmt.Printf(\"RDS cluster [%v] created successfully\\n\", rdsClusterName)\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(30 * time.Second)\n\t}\n\treturn fmt.Errorf(\"Aurora Cluster [%v] is not ready, exceed max wait attemps\\n\", rdsClusterName)\n}", "func waitForInit() error {\n\tstart := time.Now()\n\tmaxEnd := start.Add(time.Minute)\n\tfor {\n\t\t// Check for existence of vpcCniInitDonePath\n\t\tif _, err := os.Stat(vpcCniInitDonePath); err == nil {\n\t\t\t// Delete the done file in case of a reboot of the node or restart of the container (force init container to run again)\n\t\t\tif err := os.Remove(vpcCniInitDonePath); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// If file deletion fails, log and allow retry\n\t\t\tlog.Errorf(\"Failed to delete file: %s\", vpcCniInitDonePath)\n\t\t}\n\t\tif time.Now().After(maxEnd) {\n\t\t\treturn errors.Errorf(\"time exceeded\")\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func (r *CRDRegistry) RegisterCRDs() error {\n\tfor _, crd := range crds {\n\t\t// create the CustomResourceDefinition in the api\n\t\tif err := r.createCRD(crd); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// wait for the CustomResourceDefinition to be established\n\t\tif err := r.awaitCRD(crd, watchTimeout); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (sc *syncContext) ensureCRDReady(name string) {\n\t_ = wait.PollImmediate(time.Duration(100)*time.Millisecond, crdReadinessTimeout, func() (bool, error) {\n\t\tcrd, err := sc.extensionsclientset.ApiextensionsV1beta1().CustomResourceDefinitions().Get(name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tfor _, condition := range crd.Status.Conditions {\n\t\t\tif condition.Type == v1beta1.Established {\n\t\t\t\treturn condition.Status == v1beta1.ConditionTrue, nil\n\t\t\t}\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func waitForDaemonSets(c kubernetes.Interface, ns string, allowedNotReadyNodes int32, timeout time.Duration) error {\n\tif allowedNotReadyNodes == -1 {\n\t\treturn nil\n\t}\n\n\tstart := time.Now()\n\tframework.Logf(\"Waiting up to %v for all daemonsets in namespace '%s' to start\",\n\t\ttimeout, ns)\n\n\treturn wait.PollImmediate(framework.Poll, timeout, func() (bool, error) {\n\t\tdsList, err := c.AppsV1().DaemonSets(ns).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\tframework.Logf(\"Error getting daemonsets in namespace: '%s': %v\", ns, err)\n\t\t\treturn false, err\n\t\t}\n\t\tvar notReadyDaemonSets []string\n\t\tfor _, ds := range dsList.Items {\n\t\t\tframework.Logf(\"%d / %d pods ready in namespace '%s' in daemonset '%s' (%d seconds elapsed)\", ds.Status.NumberReady, ds.Status.DesiredNumberScheduled, ns, ds.ObjectMeta.Name, int(time.Since(start).Seconds()))\n\t\t\tif ds.Status.DesiredNumberScheduled-ds.Status.NumberReady > allowedNotReadyNodes {\n\t\t\t\tnotReadyDaemonSets = append(notReadyDaemonSets, ds.ObjectMeta.Name)\n\t\t\t}\n\t\t}\n\n\t\tif len(notReadyDaemonSets) > 0 {\n\t\t\tframework.Logf(\"there are not ready daemonsets: %v\", notReadyDaemonSets)\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t})\n}", "func WaitForCassDcReady(key types.NamespacedName, retryInterval, timeout time.Duration) error {\n\tstart := time.Now()\n\treturn wait.Poll(retryInterval, timeout, func() (bool, error) {\n\t\tcassdc, err := GetCassDc(key)\n\t\tif err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn true, err\n\t\t}\n\t\tlogCassDcStatus(cassdc, start)\n\t\treturn cassdc.Status.CassandraOperatorProgress == cassdcapi.ProgressReady, nil\n\t})\n}", "func waitForPods(cs *framework.ClientSet, expectedTotal, min, max int32) error {\n\terr := wait.PollImmediate(1*time.Second, 5*time.Minute, func() (bool, error) {\n\t\td, err := cs.AppsV1Interface.Deployments(\"openshift-machine-config-operator\").Get(context.TODO(), \"etcd-quorum-guard\", metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\t// By this point the deployment should exist.\n\t\t\tfmt.Printf(\" error waiting for etcd-quorum-guard deployment to exist: %v\\n\", err)\n\t\t\treturn true, err\n\t\t}\n\t\tif d.Status.Replicas < 1 {\n\t\t\tfmt.Println(\"operator deployment has no replicas\")\n\t\t\treturn false, nil\n\t\t}\n\t\tif d.Status.Replicas == expectedTotal &&\n\t\t\td.Status.AvailableReplicas >= min &&\n\t\t\td.Status.AvailableReplicas <= max {\n\t\t\tfmt.Printf(\" Deployment is ready! %d %d\\n\", d.Status.Replicas, d.Status.AvailableReplicas)\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor pod, info := range pods {\n\t\tif info.status == \"Running\" {\n\t\t\tnode := info.node\n\t\t\tif node == \"\" {\n\t\t\t\treturn fmt.Errorf(\"Pod %s not associated with a node\", pod)\n\t\t\t}\n\t\t\tif _, ok := nodes[node]; !ok {\n\t\t\t\treturn fmt.Errorf(\"pod %s running on %s, not a master\", pod, node)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func WaitDestroy(s *state.State) error {\n\ts.Logger.Info(\"Waiting for all machines to get deleted...\")\n\n\treturn wait.PollUntilContextTimeout(s.Context, 5*time.Second, 5*time.Minute, false, func(ctx context.Context) (bool, error) {\n\t\tlist := &clusterv1alpha1.MachineList{}\n\t\tif err := s.DynamicClient.List(ctx, list, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil {\n\t\t\treturn false, fail.KubeClient(err, \"getting %T\", list)\n\t\t}\n\t\tif len(list.Items) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t})\n}", "func (s *Installer) WaitForArgoCD() error {\n\tif s.Verbose {\n\t\tdefer NewWaitingMessage(\"Argo CD\", s.StatusUpdateInterval).Stop()\n\t}\n\twaitForDeployments := []string{\n\t\t\"argocd-application-controller\",\n\t\t\"argocd-dex-server\",\n\t\t\"argocd-redis\",\n\t\t\"argocd-repo-server\",\n\t\t\"argocd-server\",\n\t}\n\tdones := make([]chan error, len(waitForDeployments), len(waitForDeployments))\n\tfor i, deploymentName := range waitForDeployments {\n\t\tdone := make(chan error, 1)\n\t\tdones[i] = done\n\t\tgo func(deploymentName string, done chan<- error) {\n\t\t\tdefer close(done)\n\t\t\tdone <- WaitForDeployment(\n\t\t\t\ts.client,\n\t\t\t\tdeploymentName,\n\t\t\t\t\"argocd\",\n\t\t\t\t5*time.Second,\n\t\t\t\t30*time.Second)\n\t\t}(deploymentName, done)\n\t}\n\tvar multi error\n\tfor _, done := range dones {\n\t\tif err := <-done; err != nil {\n\t\t\tmulti = multierror.Append(multi, err)\n\t\t}\n\t}\n\treturn multi\n}", "func WaitForResources(objects object.K8sObjects, opts *kubectlcmd.Options) error {\n\tif opts.DryRun {\n\t\tlogAndPrint(\"Not waiting for resources ready in dry run mode.\")\n\t\treturn nil\n\t}\n\n\tcs, err := kubernetes.NewForConfig(k8sRESTConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"k8s client error: %s\", err)\n\t}\n\n\terrPoll := wait.Poll(2*time.Second, opts.WaitTimeout, func() (bool, error) {\n\t\tpods := []v1.Pod{}\n\t\tservices := []v1.Service{}\n\t\tdeployments := []deployment{}\n\t\tnamespaces := []v1.Namespace{}\n\n\t\tfor _, o := range objects {\n\t\t\tkind := o.GroupVersionKind().Kind\n\t\t\tswitch kind {\n\t\t\tcase \"Namespace\":\n\t\t\t\tnamespace, err := cs.CoreV1().Namespaces().Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tnamespaces = append(namespaces, *namespace)\n\t\t\tcase \"Pod\":\n\t\t\t\tpod, err := cs.CoreV1().Pods(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, *pod)\n\t\t\tcase \"ReplicationController\":\n\t\t\t\trc, err := cs.CoreV1().ReplicationControllers(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tlist, err := getPods(cs, rc.Namespace, rc.Spec.Selector)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, list...)\n\t\t\tcase \"Deployment\":\n\t\t\t\tcurrentDeployment, err := cs.AppsV1().Deployments(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\t_, _, newReplicaSet, err := kubectlutil.GetAllReplicaSets(currentDeployment, cs.AppsV1())\n\t\t\t\tif err != nil || newReplicaSet == nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tnewDeployment := deployment{\n\t\t\t\t\tnewReplicaSet,\n\t\t\t\t\tcurrentDeployment,\n\t\t\t\t}\n\t\t\t\tdeployments = append(deployments, newDeployment)\n\t\t\tcase \"DaemonSet\":\n\t\t\t\tds, err := cs.AppsV1().DaemonSets(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tlist, err := getPods(cs, ds.Namespace, ds.Spec.Selector.MatchLabels)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, list...)\n\t\t\tcase \"StatefulSet\":\n\t\t\t\tsts, err := cs.AppsV1().StatefulSets(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tlist, err := getPods(cs, sts.Namespace, sts.Spec.Selector.MatchLabels)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, list...)\n\t\t\tcase \"ReplicaSet\":\n\t\t\t\trs, err := cs.AppsV1().ReplicaSets(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tlist, err := getPods(cs, rs.Namespace, rs.Spec.Selector.MatchLabels)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, list...)\n\t\t\tcase \"Service\":\n\t\t\t\tsvc, err := cs.CoreV1().Services(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tservices = append(services, *svc)\n\t\t\t}\n\t\t}\n\t\tisReady := namespacesReady(namespaces) && podsReady(pods) && deploymentsReady(deployments) && servicesReady(services)\n\t\tif !isReady {\n\t\t\tlogAndPrint(\"Waiting for resources ready with timeout of %v\", opts.WaitTimeout)\n\t\t}\n\t\treturn isReady, nil\n\t})\n\n\tif errPoll != nil {\n\t\tlogAndPrint(\"Failed to wait for resources ready: %v\", errPoll)\n\t\treturn fmt.Errorf(\"failed to wait for resources ready: %s\", errPoll)\n\t}\n\treturn nil\n}", "func (c *myClient) waitForEnvironmentsReady(p, t int, envList ...string) (err error) {\n\n\tlogger.Infof(\"Waiting up to %v seconds for the environments to be ready\", t)\n\ttimeOut := 0\n\tfor timeOut < t {\n\t\tlogger.Info(\"Waiting for the environments\")\n\t\ttime.Sleep(time.Duration(p) * time.Second)\n\t\ttimeOut = timeOut + p\n\t\tif err = c.checkForBusyEnvironments(envList); err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif timeOut >= t {\n\t\terr = fmt.Errorf(\"waitForEnvironmentsReady timed out\")\n\t}\n\treturn err\n}", "func waitForClusterReady(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForClusterStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(cluster *capiv1alpha1.Cluster) bool {\n\t\t\tstatus, err := controller.ClusterStatusFromClusterAPI(cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn status.Ready\n\t\t},\n\t)\n}", "func waitForReadyNodes(desiredCount int, timeout time.Duration, requiredConsecutiveSuccesses int) error {\n\tstop := time.Now().Add(timeout)\n\n\tconsecutiveSuccesses := 0\n\tfor {\n\t\tif time.Now().After(stop) {\n\t\t\tbreak\n\t\t}\n\n\t\tnodes, err := kubectlGetNodes(\"\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"kubectl get nodes failed, sleeping: %v\", err)\n\t\t\tconsecutiveSuccesses = 0\n\t\t\ttime.Sleep(30 * time.Second)\n\t\t\tcontinue\n\t\t}\n\t\treadyNodes := countReadyNodes(nodes)\n\t\tif readyNodes >= desiredCount {\n\t\t\tconsecutiveSuccesses++\n\t\t\tif consecutiveSuccesses >= requiredConsecutiveSuccesses {\n\t\t\t\tlog.Printf(\"%d ready nodes found, %d sequential successes - cluster is ready\",\n\t\t\t\t\treadyNodes,\n\t\t\t\t\tconsecutiveSuccesses)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tlog.Printf(\"%d ready nodes found, waiting for %d sequential successes (success count = %d)\",\n\t\t\t\treadyNodes,\n\t\t\t\trequiredConsecutiveSuccesses,\n\t\t\t\tconsecutiveSuccesses)\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t} else {\n\t\t\tconsecutiveSuccesses = 0\n\t\t\tlog.Printf(\"%d (ready nodes) < %d (requested instances), sleeping\", readyNodes, desiredCount)\n\t\t\ttime.Sleep(30 * time.Second)\n\t\t}\n\t}\n\treturn fmt.Errorf(\"waiting for ready nodes timed out\")\n}", "func waitForReplicasInit(\n\tctx context.Context,\n\tdialer *nodedialer.Dialer,\n\trangeID roachpb.RangeID,\n\treplicas []roachpb.ReplicaDescriptor,\n) error {\n\treturn contextutil.RunWithTimeout(ctx, \"wait for replicas init\", 5*time.Second, func(ctx context.Context) error {\n\t\tg := ctxgroup.WithContext(ctx)\n\t\tfor _, repl := range replicas {\n\t\t\trepl := repl // copy for goroutine\n\t\t\tg.GoCtx(func(ctx context.Context) error {\n\t\t\t\tconn, err := dialer.Dial(ctx, repl.NodeID, rpc.DefaultClass)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"could not dial n%d\", repl.NodeID)\n\t\t\t\t}\n\t\t\t\t_, err = NewPerReplicaClient(conn).WaitForReplicaInit(ctx, &WaitForReplicaInitRequest{\n\t\t\t\t\tStoreRequestHeader: StoreRequestHeader{NodeID: repl.NodeID, StoreID: repl.StoreID},\n\t\t\t\t\tRangeID: rangeID,\n\t\t\t\t})\n\t\t\t\treturn err\n\t\t\t})\n\t\t}\n\t\treturn g.Wait()\n\t})\n}", "func getCRDs(csv *v1alpha1.ClusterServiceVersion) (crds []client.Object) {\n\tfor _, resource := range csv.Status.RequirementStatus {\n\t\tif resource.Kind == crdKind {\n\t\t\tobj := &unstructured.Unstructured{}\n\t\t\tobj.SetGroupVersionKind(schema.GroupVersionKind{\n\t\t\t\tGroup: resource.Group,\n\t\t\t\tVersion: resource.Version,\n\t\t\t\tKind: resource.Kind,\n\t\t\t})\n\t\t\tobj.SetName(resource.Name)\n\t\t\tcrds = append(crds, obj)\n\t\t}\n\t}\n\treturn\n}", "func WaitForResources(objects object.K8sObjects, restConfig *rest.Config, cs kubernetes.Interface,\n\twaitTimeout time.Duration, dryRun bool, l *progress.ManifestLog) error {\n\tif dryRun {\n\t\treturn nil\n\t}\n\n\tif err := waitForCRDs(objects, restConfig); err != nil {\n\t\treturn err\n\t}\n\n\tvar notReady []string\n\n\t// Check if we are ready immediately, to avoid the 2s delay below when we are already redy\n\tif ready, _, err := waitForResources(objects, cs, l); err == nil && ready {\n\t\treturn nil\n\t}\n\n\terrPoll := wait.Poll(2*time.Second, waitTimeout, func() (bool, error) {\n\t\tisReady, notReadyObjects, err := waitForResources(objects, cs, l)\n\t\tnotReady = notReadyObjects\n\t\treturn isReady, err\n\t})\n\n\tif errPoll != nil {\n\t\tmsg := fmt.Sprintf(\"resources not ready after %v: %v\\n%s\", waitTimeout, errPoll, strings.Join(notReady, \"\\n\"))\n\t\treturn errors.New(msg)\n\t}\n\treturn nil\n}", "func WaitReady(s *state.State) error {\n\tif !s.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\ts.Logger.Infoln(\"Waiting for machine-controller to come up...\")\n\n\tif err := cleanupStaleResources(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForWebhook(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForMachineController(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\treturn waitForCRDs(s)\n}", "func waitForClusterProvisioned(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForClusterStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(cluster *capiv1alpha1.Cluster) bool {\n\t\t\tstatus, err := controller.ClusterStatusFromClusterAPI(cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn status.Provisioned\n\t\t},\n\t)\n}", "func SetupCRDs(crdPath, pattern string) env.Func {\n\treturn func(ctx context.Context, c *envconf.Config) (context.Context, error) {\n\t\tr, err := resources.New(c.Client().RESTConfig())\n\t\tif err != nil {\n\t\t\treturn ctx, err\n\t\t}\n\t\treturn ctx, decoder.ApplyWithManifestDir(ctx, r, crdPath, pattern, []resources.CreateOption{})\n\t}\n}", "func waitForCnsVSphereVolumeMigrationCrd(ctx context.Context, vpath string) (*v1alpha1.CnsVSphereVolumeMigration, error) {\n\tvar (\n\t\tfound bool\n\t\tcrd *v1alpha1.CnsVSphereVolumeMigration\n\t)\n\twaitErr := wait.PollImmediate(poll, pollTimeout, func() (bool, error) {\n\t\tfound, crd = getCnsVSphereVolumeMigrationCrd(ctx, vpath)\n\t\treturn found, nil\n\t})\n\treturn crd, waitErr\n}", "func processCRDs(ctx context.Context, processor crdProcessor, defs []crd.Definition) error {\n\tclient, err := crdClientFn()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, def := range defs {\n\t\tcustomResourceDefinition, err := loadCRD(def.Contents)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := processor(ctx, client, customResourceDefinition); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func waitUntilRDSClusterDeleted(rdsClientSess *rds.RDS, restoreParams map[string]string) error {\n\n\trdsClusterName := restoreParams[\"restoreRDS\"]\n\n\tinput := &rds.DescribeDBClustersInput{\n\t\tDBClusterIdentifier: aws.String(rdsClusterName),\n\t}\n\n\t// Check if Cluster exists\n\t_, err := rdsClientSess.DescribeDBClusters(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tif aerr.Code() == rds.ErrCodeDBClusterNotFoundFault {\n\t\t\t\tfmt.Println(rds.ErrCodeDBClusterNotFoundFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Wait RDS cluster deletion err %v\", err)\n\t\t\t} else {\n\t\t\t\t// Print the error, cast err to awserr.Error to get the Code and Message from an error.\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn fmt.Errorf(\"Wait RDS cluster deletion err %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: DEBUG - fmt.Println(result)\n\tfmt.Printf(\"Wait until RDS cluster [%v] is fully deleted...\\n\", rdsClusterName)\n\n\tstart := time.Now()\n\n\tmaxWaitAttempts := 120\n\n\t// Check until deleted\n\tfor waitAttempt := 0; waitAttempt < maxWaitAttempts; waitAttempt++ {\n\t\telapsedTime := time.Since(start).Seconds()\n\n\t\tif waitAttempt > 0 {\n\t\t\tformattedTime := strings.Split(fmt.Sprintf(\"%6v\", elapsedTime), \".\")\n\t\t\tfmt.Printf(\"Cluster deletion elapsed time: %vs\\n\", formattedTime[0])\n\t\t}\n\n\t\tresp, err := rdsClientSess.DescribeDBClusters(input)\n\t\tif err != nil {\n\t\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\t\tif aerr.Code() == rds.ErrCodeDBClusterNotFoundFault {\n\t\t\t\t\tfmt.Println(\"RDS Cluster deleted successfully\")\n\t\t\t\t\treturn nil\n\t\t\t\t} else {\n\t\t\t\t\t// Print the error, cast err to awserr.Error to get the Code and Message from an error.\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn fmt.Errorf(\"Wait RDS cluster deletion err %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfmt.Printf(\"Cluster status: [%s]\\n\", *resp.DBClusters[0].Status)\n\t\tif *resp.DBClusters[0].Status == \"terminated\" {\n\t\t\tfmt.Printf(\"RDS cluster [%v] deleted successfully\\n\", rdsClusterName)\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(30 * time.Second)\n\t}\n\n\t// Timeout Err\n\treturn fmt.Errorf(\"RDS Cluster [%v] could not be deleted, exceed max wait attemps\\n\", rdsClusterName)\n}", "func WaitDaemonsetReady(namespace, name string, timeout time.Duration) error {\n\n\tnodes, err := daemonsetClient.K8sClient.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get node list, err:%s\", err)\n\t}\n\n\tnodesCount := int32(len(nodes.Items))\n\tisReady := false\n\tfor start := time.Now(); !isReady && time.Since(start) < timeout; {\n\t\tdaemonSet, err := daemonsetClient.K8sClient.AppsV1().DaemonSets(namespace).Get(context.Background(), name, metav1.GetOptions{})\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get daemonset, err: %s\", err)\n\t\t}\n\n\t\tif daemonSet.Status.DesiredNumberScheduled != nodesCount {\n\t\t\treturn fmt.Errorf(\"daemonset DesiredNumberScheduled not equal to number of nodes:%d, please instantiate debug pods on all nodes\", nodesCount)\n\t\t}\n\n\t\tlogrus.Infof(\"Waiting for (%d) debug pods to be ready: %+v\", nodesCount, daemonSet.Status)\n\t\tif isDaemonSetReady(&daemonSet.Status) {\n\t\t\tisReady = true\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(waitingTime)\n\t}\n\n\tif !isReady {\n\t\treturn errors.New(\"daemonset debug pods not ready\")\n\t}\n\n\tlogrus.Infof(\"All the debug pods are ready.\")\n\treturn nil\n}", "func (client *Client) WaitForAllTestResourcesReady() error {\n\tif err := client.WaitForChannelsReady(); err != nil {\n\t\treturn err\n\t}\n\tif err := client.WaitForSubscriptionsReady(); err != nil {\n\t\treturn err\n\t}\n\tif err := client.WaitForBrokersReady(); err != nil {\n\t\treturn err\n\t}\n\tif err := client.WaitForTriggersReady(); err != nil {\n\t\treturn err\n\t}\n\tif err := client.WaitForCronJobSourcesReady(); err != nil {\n\t\treturn err\n\t}\n\tif err := client.WaitForContainerSourcesReady(); err != nil {\n\t\treturn err\n\t}\n\tif err := pkgTest.WaitForAllPodsRunning(client.Kube, client.Namespace); err != nil {\n\t\treturn err\n\t}\n\t// FIXME(Fredy-Z): This hacky sleep is added to try mitigating the test flakiness.\n\t// Will delete it after we find the root cause and fix.\n\ttime.Sleep(10 * time.Second)\n\treturn nil\n}", "func waitAndCleanup() {\n\ttime.Sleep(1 * time.Second)\n\n\t// Disconnect from switches.\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tvrtrAgents[i].Delete()\n\t\tvxlanAgents[i].Delete()\n\t\tvlanAgents[i].Delete()\n\t}\n\tfor i := 0; i < NUM_VLRTR_AGENT; i++ {\n\t\tvlrtrAgents[i].Delete()\n\t}\n\tfor i := 0; i < NUM_HOST_BRIDGE; i++ {\n\t\thostBridges[i].Delete()\n\t}\n\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tbrName := \"vrtrBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tbrName := \"vxlanBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[NUM_AGENT+i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tbrName := \"vlanBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[(2*NUM_AGENT)+i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_VLRTR_AGENT; i++ {\n\t\tbrName := \"vlrtrBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[(3*NUM_AGENT)+i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_HOST_BRIDGE; i++ {\n\t\tbrName := \"hostBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[HB_AGENT_INDEX].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n}", "func (rcc *rotateCertsCmd) waitForKubeSystemReadiness() error {\n\tlog.Info(\"Checking health of all kube-system pods\")\n\ttimeout := time.Duration(len(rcc.nodes)) * time.Duration(float64(time.Minute)*1.25)\n\tif rotateCertsDefaultTimeout > timeout {\n\t\ttimeout = rotateCertsDefaultTimeout\n\t}\n\tif err := ops.WaitForAllInNamespaceReady(rcc.kubeClient, metav1.NamespaceSystem, rotateCertsDefaultInterval, timeout, rcc.nodes); err != nil {\n\t\treturn errors.Wrap(err, \"waiting for kube-system containers to reach the Ready state within the timeout period\")\n\t}\n\treturn nil\n}", "func waitForGlusterContainer() error {\n\n\t//Check if docker gluster container is up and running\n\tfor {\n\t\tglusterServerContainerVal, err := helpers.GetSystemDockerNode(\"gluster-server\")\n\t\tif err != nil {\n\t\t\trwolog.Error(\"Error in checking docker gluster container for status \", err.Error())\n\t\t\treturn err\n\t\t}\n\n\t\tif len(glusterServerContainerVal) > 0 {\n\t\t\tbreak\n\t\t} else {\n\t\t\trwolog.Debug(\"Sleeping for 10 seconds to get gluster docker container up\")\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t}\n\treturn nil\n}", "func waitForCertificateReady(configMap *corev1.ConfigMap) bool {\n\tlog := util.Logger()\n\tklient := util.KubeClient()\n\n\tinterval := time.Duration(3)\n\ttimeout := time.Duration(15)\n\n\terr := wait.PollUntilContextTimeout(ctx, interval*time.Second, timeout*time.Second, true, func(ctx context.Context) (bool, error) {\n\t\tif err := klient.Get(util.Context(), util.ObjectKey(configMap), configMap); err != nil {\n\t\t\tlog.Printf(\"⏳ Failed to get service ca certificate: %s\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tif configMap.Data[\"service-ca.crt\"] == \"\" {\n\t\t\treturn false, fmt.Errorf(\"service ca certificate not created\")\n\t\t}\n\n\t\treturn true, nil\n\t})\n\treturn (err == nil)\n}", "func waitForConnection(ctx context.Context, c client.Interface) {\n\tlog.Info(\"Checking datastore connection\")\n\tfor {\n\t\t// Query some arbitrary configuration to see if the connection\n\t\t// is working. Getting a specific Node is a good option, even\n\t\t// if the Node does not exist.\n\t\t_, err := c.Nodes().Get(ctx, \"foo\", options.GetOptions{})\n\n\t\t// We only care about a couple of error cases, all others would\n\t\t// suggest the datastore is accessible.\n\t\tif err != nil {\n\t\t\tswitch err.(type) {\n\t\t\tcase cerrors.ErrorConnectionUnauthorized:\n\t\t\t\tlog.WithError(err).Warn(\"Connection to the datastore is unauthorized\")\n\t\t\t\tutils.Terminate()\n\t\t\tcase cerrors.ErrorDatastoreError:\n\t\t\t\tlog.WithError(err).Info(\"Hit error connecting to datastore - retry\")\n\t\t\t\ttime.Sleep(1000 * time.Millisecond)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// We've connected to the datastore - break out of the loop.\n\t\tbreak\n\t}\n\tlog.Info(\"Datastore connection verified\")\n}", "func (c *containerAdapter) waitClusterVolumes(ctx context.Context) error {\n\tfor _, attached := range c.container.task.Volumes {\n\t\t// for every attachment, try until we succeed or until the context\n\t\t// is canceled.\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\tdefault:\n\t\t\t\t// continue through the code.\n\t\t\t}\n\t\t\tpath, err := c.dependencies.Volumes().Get(attached.ID)\n\t\t\tif err == nil && path != \"\" {\n\t\t\t\t// break out of the inner-most loop\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tswarmlog.G(ctx).Debug(\"volumes ready\")\n\treturn nil\n}", "func waitForSystemdActiveState(units []string, maxAttempts int) (errch chan error) {\n\terrchan := make(chan error)\n\tvar wg sync.WaitGroup\n\tfor _, name := range units {\n\t\twg.Add(1)\n\t\tgo checkSystemdActiveState(name, maxAttempts, &wg, errchan)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(errchan)\n\t}()\n\n\treturn errchan\n}", "func WaitReady(ctx *util.Context) error {\n\tif !ctx.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\tctx.Logger.Infoln(\"Waiting for machine-controller to come up…\")\n\n\t// Wait a bit to let scheduler to react\n\ttime.Sleep(10 * time.Second)\n\n\tif err := WaitForWebhook(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller-webhook did not come up\")\n\t}\n\n\tif err := WaitForMachineController(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller did not come up\")\n\t}\n\treturn nil\n}", "func (c *Client) WaitForResources(timeout time.Duration, resources []*manifest.MappingResult) error {\n\treturn wait.Poll(5*time.Second, timeout, func() (bool, error) {\n\t\tstatefulSets := []appsv1.StatefulSet{}\n\t\tdeployments := []deployment{}\n\t\tfor _, r := range resources {\n\t\t\tswitch r.Metadata.Kind {\n\t\t\tcase \"ConfigMap\":\n\t\t\tcase \"Service\":\n\t\t\tcase \"ReplicationController\":\n\t\t\tcase \"Pod\":\n\t\t\tcase \"Deployment\":\n\t\t\t\tcurrentDeployment, err := c.clientset.AppsV1().Deployments(r.Metadata.ObjectMeta.Namespace).Get(context.TODO(), r.Metadata.ObjectMeta.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\t// Find RS associated with deployment\n\t\t\t\tnewReplicaSet, err := c.getNewReplicaSet(currentDeployment)\n\t\t\t\tif err != nil || newReplicaSet == nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tnewDeployment := deployment{\n\t\t\t\t\tnewReplicaSet,\n\t\t\t\t\tcurrentDeployment,\n\t\t\t\t}\n\t\t\t\tdeployments = append(deployments, newDeployment)\n\t\t\tcase \"StatefulSet\":\n\t\t\t\tsf, err := c.clientset.AppsV1().StatefulSets(r.Metadata.ObjectMeta.Namespace).Get(context.TODO(), r.Metadata.ObjectMeta.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tstatefulSets = append(statefulSets, *sf)\n\t\t\t}\n\t\t}\n\t\tisReady := c.statefulSetsReady(statefulSets) && c.deploymentsReady(deployments)\n\t\treturn isReady, nil\n\t})\n}", "func waitResults(clients []*SSHClient.SSHClient, results chan bool, c *cli.Context) {\n\ttimeout := time.After(time.Duration(c.Int(\"timeout\")) * time.Second)\n\n\tfor i := 0; i < len(clients); i++ {\n\t\tselect {\n\t\tcase res := <-results:\n\t\t\tres = !res\n\t\tcase <-timeout:\n\t\t\tfmt.Println(\"Timed out! Commands might be still running on the hosts\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func collectCRDResources(discovery discovery.DiscoveryInterface) ([]*metav1.APIResourceList, error) {\n\tresources, err := discovery.ServerResources()\n\tcrdResources := []*metav1.APIResourceList{}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, res := range resources {\n\t\tgv, err := schema.ParseGroupVersion(res.GroupVersion)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif gv.Group != \"apiextensions.k8s.io\" {\n\t\t\tcontinue\n\t\t}\n\t\temptyAPIResourceList := metav1.APIResourceList{\n\t\t\tGroupVersion: res.GroupVersion,\n\t\t}\n\t\temptyAPIResourceList.APIResources = findCRDGVRs(res.APIResources)\n\t\tcrdResources = append(crdResources, &emptyAPIResourceList)\n\t}\n\n\treturn crdResources, nil\n}", "func WaitForBKClusterToTerminate(t *testing.T, k8client client.Client, b *bkapi.BookkeeperCluster) error {\n\tlog.Printf(\"waiting for Bookkeeper cluster to terminate: %s\", b.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(b.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(map[string]string{\"bookkeeper_cluster\": b.GetName()})},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"bookkeeper cluster terminated: %s\", b.Name)\n\treturn nil\n}", "func (k *kubelet) waitForNodeReady() error {\n\tkc, _ := k.config.AdminConfig.ToYAMLString() //nolint:errcheck // This is checked in Validate().\n\n\tc, err := client.NewClient([]byte(kc))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating kubernetes client: %w\", err)\n\t}\n\n\treturn c.WaitForNodeReady(k.config.Name)\n}", "func (m *MeshReconciler) waitForIstioCRToBeDeleted(client client.Client) error {\n\tm.logger.Debug(\"waiting for Istio CR to be deleted\")\n\n\tbackoffConfig := backoff.ConstantBackoffConfig{\n\t\tDelay: time.Duration(backoffDelaySeconds) * time.Second,\n\t\tMaxRetries: backoffMaxretries,\n\t}\n\tbackoffPolicy := backoff.NewConstantBackoffPolicy(backoffConfig)\n\n\terr := backoff.Retry(func() error {\n\t\tvar istio v1beta1.Istio\n\t\terr := client.Get(context.Background(), types.NamespacedName{\n\t\t\tName: m.Configuration.name,\n\t\t\tNamespace: istioOperatorNamespace,\n\t\t}, &istio)\n\t\tif k8serrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn errors.New(\"Istio CR still exists\")\n\t}, backoffPolicy)\n\n\treturn errors.WithStack(err)\n}", "func waitForMachineSetToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForMachineSetStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(machineSet *capiv1alpha1.MachineSet) bool { return machineSet != nil },\n\t)\n}", "func WaitForCleanup() error {\n\tctx := context.Background()\n\tcli, err := client.NewEnvClient()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar (\n\t\tinterval = time.NewTicker(1 * time.Second)\n\t\ttimeout = time.NewTimer(1 * time.Minute)\n\t)\n\n\tfor range interval.C {\n\t\tselect {\n\t\tcase <-timeout.C:\n\t\t\treturn errors.New(\"timed out waiting for all easycontainers containers to get removed\")\n\t\tdefault:\n\t\t\t// only grab the containers created by easycontainers\n\t\t\targs := filters.NewArgs()\n\t\t\targs.Add(\"name\", \"/\"+prefix)\n\n\t\t\tcontainers, err := cli.ContainerList(ctx, types.ContainerListOptions{\n\t\t\t\tFilters: args,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif len(containers) == 0 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (b *Botanist) WaitForControllersToBeActive(ctx context.Context) error {\n\ttype controllerInfo struct {\n\t\tname string\n\t\tlabels map[string]string\n\t}\n\n\ttype checkOutput struct {\n\t\tcontrollerName string\n\t\tready bool\n\t\terr error\n\t}\n\n\tvar (\n\t\tcontrollers = []controllerInfo{}\n\t\tpollInterval = 5 * time.Second\n\t)\n\n\t// Check whether the kube-controller-manager deployment exists\n\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(b.Shoot.SeedNamespace, v1beta1constants.DeploymentNameKubeControllerManager), &appsv1.Deployment{}); err == nil {\n\t\tcontrollers = append(controllers, controllerInfo{\n\t\t\tname: v1beta1constants.DeploymentNameKubeControllerManager,\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"app\": \"kubernetes\",\n\t\t\t\t\"role\": \"controller-manager\",\n\t\t\t},\n\t\t})\n\t} else if client.IgnoreNotFound(err) != nil {\n\t\treturn err\n\t}\n\n\treturn retry.UntilTimeout(context.TODO(), pollInterval, 90*time.Second, func(ctx context.Context) (done bool, err error) {\n\t\tvar (\n\t\t\twg sync.WaitGroup\n\t\t\tout = make(chan *checkOutput)\n\t\t)\n\n\t\tfor _, controller := range controllers {\n\t\t\twg.Add(1)\n\n\t\t\tgo func(controller controllerInfo) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tpodList := &corev1.PodList{}\n\t\t\t\terr := b.K8sSeedClient.Client().List(ctx, podList,\n\t\t\t\t\tclient.InNamespace(b.Shoot.SeedNamespace),\n\t\t\t\t\tclient.MatchingLabels(controller.labels))\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check that only one replica of the controller exists.\n\t\t\t\tif len(podList.Items) != 1 {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for %s to have exactly one replica\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Check that the existing replica is not in getting deleted.\n\t\t\t\tif podList.Items[0].DeletionTimestamp != nil {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for a new replica of %s\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check if the controller is active by reading its leader election record.\n\t\t\t\tleaderElectionRecord, err := common.ReadLeaderElectionRecord(b.K8sShootClient, resourcelock.EndpointsResourceLock, metav1.NamespaceSystem, controller.name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif delta := metav1.Now().UTC().Sub(leaderElectionRecord.RenewTime.Time.UTC()); delta <= pollInterval-time.Second {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, ready: true}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tb.Logger.Infof(\"Waiting for %s to be active\", controller.name)\n\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t}(controller)\n\t\t}\n\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tclose(out)\n\t\t}()\n\n\t\tfor result := range out {\n\t\t\tif result.err != nil {\n\t\t\t\treturn retry.SevereError(fmt.Errorf(\"could not check whether controller %s is active: %+v\", result.controllerName, result.err))\n\t\t\t}\n\t\t\tif !result.ready {\n\t\t\t\treturn retry.MinorError(fmt.Errorf(\"controller %s is not active\", result.controllerName))\n\t\t\t}\n\t\t}\n\n\t\treturn retry.Ok()\n\t})\n}", "func (e *DockerRegistryServiceController) waitForDockerURLs(ready chan<- struct{}, stopCh <-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Wait for the stores to fill\n\tif !cache.WaitForCacheSync(stopCh, e.servicesSynced, e.secretsSynced) {\n\t\treturn\n\t}\n\n\t// after syncing, determine the current state and assume that we're up to date for it if you don't do this,\n\t// you'll get an initial storm as you mess with all the dockercfg secrets every time you startup\n\turls := e.getDockerRegistryLocations()\n\te.setRegistryURLs(urls...)\n\te.dockercfgController.SetDockerURLs(urls...)\n\tclose(e.dockerURLsInitialized)\n\tclose(ready)\n\n\treturn\n}", "func waitForHelmRunning(ctx context.Context, configPath string) error {\n\tfor {\n\t\tcmd := exec.Command(\"helm\", \"ls\", \"--kubeconfig\", configPath)\n\t\tvar out bytes.Buffer\n\t\tcmd.Stderr = &out\n\t\tcmd.Run()\n\t\tif out.String() == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.Wrap(ctx.Err(), \"timed out waiting for helm to become ready\")\n\t\tcase <-time.After(5 * time.Second):\n\t\t}\n\t}\n}", "func ClusterCRD(t *testing.T) {\n\tctx := test.NewTestCtx(t)\n\tdefer ctx.Cleanup()\n\n\terr := helpers.DeployOperator(t, ctx)\n\thelpers.AssertNoError(t, err)\n\n\tt.Run(\"auto-installs-pipelines\", testsuites.ValidateAutoInstall)\n\tt.Run(\"deployment-recreation\", testsuites.ValidateDeploymentRecreate)\n\tt.Run(\"delete-pipelines\", testsuites.ValidateDeletion)\n}", "func (mgr *WatcherManager) runCrdWatcher(obj *apiextensionsV1beta1.CustomResourceDefinition) {\n\tgroupVersion := obj.Spec.Group + \"/\" + obj.Spec.Version\n\tcrdName := obj.Name\n\n\tcrdClient, ok := resources.CrdClientList[groupVersion]\n\n\tif !ok {\n\t\tcrdClient, ok = resources.CrdClientList[crdName]\n\t}\n\n\tif ok {\n\t\tvar runtimeObject k8sruntime.Object\n\t\tvar namespaced bool\n\t\tif obj.Spec.Scope == \"Cluster\" {\n\t\t\tnamespaced = false\n\t\t} else if obj.Spec.Scope == \"Namespaced\" {\n\t\t\tnamespaced = true\n\t\t}\n\n\t\t// init and run writer handler\n\t\taction := action.NewStorageAction(mgr.clusterID, obj.Spec.Names.Kind, mgr.storageService)\n\t\tmgr.writer.Handlers[obj.Spec.Names.Kind] = output.NewHandler(mgr.clusterID, obj.Spec.Names.Kind, action)\n\t\tstopChan := make(chan struct{})\n\t\tmgr.writer.Handlers[obj.Spec.Names.Kind].Run(stopChan)\n\n\t\t// init and run watcher\n\t\twatcher := NewWatcher(&crdClient, mgr.watchResource.Namespace, obj.Spec.Names.Kind, obj.Spec.Names.Plural, runtimeObject, mgr.writer, mgr.watchers, namespaced) // nolint\n\t\twatcher.stopChan = stopChan\n\t\tmgr.crdWatchers[obj.Spec.Names.Kind] = watcher\n\t\tglog.Infof(\"watcher manager, start list-watcher[%+v]\", obj.Spec.Names.Kind)\n\t\tgo watcher.Run(watcher.stopChan)\n\t}\n}", "func waitForConsistency() {\n\ttime.Sleep(500 * time.Millisecond)\n}", "func EnsureCRDCreated(cfg *rest.Config) (created bool, err error) {\n\tcrdVar, err := createCRDObject(helmRequestCRDYaml)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn crd.EnsureCRDCreated(cfg, crdVar)\n\t// return util.EnsureCRDCreated(cfg, CRD)\n}", "func (k Kubectl) WaitPodsReady(timeout time.Duration) error {\n\treturn utils.CheckUntil(5*time.Second, timeout, func() (bool, error) {\n\t\tcmd := kindCommand(\"kubectl get -n authelia pods --no-headers\")\n\t\tcmd.Stdout = nil\n\t\tcmd.Stderr = nil\n\t\toutput, _ := cmd.Output()\n\n\t\tlines := strings.Split(string(output), \"\\n\")\n\n\t\tnonEmptyLines := make([]string, 0)\n\t\tfor _, line := range lines {\n\t\t\tif line != \"\" {\n\t\t\t\tnonEmptyLines = append(nonEmptyLines, line)\n\t\t\t}\n\t\t}\n\n\t\tfor _, line := range nonEmptyLines {\n\t\t\tif !strings.Contains(line, \"1/1\") {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t})\n}", "func DeployCR(bs *bootstrap.Bootstrap) {\n\tfor _, kind := range Kinds {\n\t\tif err := waitResourceReady(bs, apiGroupVersion, kind); err != nil {\n\t\t\tklog.Errorf(\"Failed to wait for resource ready with kind %s, apiGroupVersion: %s\", kind, apiGroupVersion)\n\t\t}\n\t}\n\n\tfor _, cr := range DeployCRs {\n\t\tfor {\n\t\t\tdone := deployResource(bs, cr)\n\t\t\tif done {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\n\t}\n}", "func waitKcpConn() *smux.Session {\n\tfor {\n\t\tif session, err := createKcpConn(); err == nil {\n\t\t\treturn session\n\t\t} else {\n\t\t\tlog.Println(\"re-connecting:\", err)\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t}\n}", "func (m *Machine) WaitForPVCsDelete(namespace string) error {\n\treturn wait.PollImmediate(m.PollInterval, m.PollTimeout, func() (bool, error) {\n\t\treturn m.PVCsDeleted(namespace)\n\t})\n}", "func (b *Botanist) WaitUntilContainerRuntimeResourcesReady(ctx context.Context) error {\n\tfns := []flow.TaskFn{}\n\n\tfor _, worker := range b.Shoot.Info.Spec.Provider.Workers {\n\t\tif worker.CRI != nil {\n\t\t\tfor _, containerRuntime := range worker.CRI.ContainerRuntimes {\n\t\t\t\tvar (\n\t\t\t\t\tname = getContainerRuntimeKey(containerRuntime.Type, worker.Name)\n\t\t\t\t\tnamespace = b.Shoot.SeedNamespace\n\t\t\t\t)\n\t\t\t\tfns = append(fns, func(ctx context.Context) error {\n\t\t\t\t\tif err := retry.UntilTimeout(ctx, DefaultInterval, shoot.ExtensionDefaultTimeout, func(ctx context.Context) (bool, error) {\n\t\t\t\t\t\treq := &extensionsv1alpha1.ContainerRuntime{}\n\t\t\t\t\t\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(namespace, name), req); err != nil {\n\t\t\t\t\t\t\treturn retry.SevereError(err)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif err := health.CheckExtensionObject(req); err != nil {\n\t\t\t\t\t\t\tb.Logger.WithError(err).Errorf(\"Container runtime %s/%s did not get ready yet\", namespace, name)\n\t\t\t\t\t\t\treturn retry.MinorError(err)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn retry.Ok()\n\t\t\t\t\t}); err != nil {\n\t\t\t\t\t\treturn gardencorev1beta1helper.DetermineError(err, fmt.Sprintf(\"failed waiting for container runtime %s to be ready: %v\", name, err))\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn flow.ParallelExitOnError(fns...)(ctx)\n}", "func (c *CRDRemover) removeCRDs(req *common.HcoRequest) {\n\tremoved := make([]schema.GroupKind, 0, len(c.crdsToRemove))\n\tunremoved := make([]schema.GroupKind, 0, len(c.crdsToRemove))\n\n\t// The deletion is performed concurrently for all CRDs.\n\tvar mutex sync.Mutex\n\tvar wg sync.WaitGroup\n\twg.Add(len(c.crdsToRemove))\n\n\tfor _, crdToBeRemoved := range c.crdsToRemove {\n\t\tgo func(crd schema.GroupKind) {\n\t\t\tisRemoved := c.removeCRD(req, crd)\n\n\t\t\tmutex.Lock()\n\t\t\tdefer mutex.Unlock()\n\n\t\t\tif isRemoved {\n\t\t\t\tremoved = append(removed, crd)\n\t\t\t} else {\n\t\t\t\tunremoved = append(unremoved, crd)\n\t\t\t}\n\n\t\t\twg.Done()\n\t\t}(crdToBeRemoved)\n\t}\n\n\twg.Wait()\n\n\t// For CRDs that failed to remove, we'll retry in the next reconciliation loop.\n\tc.crdsToRemove = unremoved\n\n\t// For CRDs that were successfully removed, we can proceed to remove\n\t// their corresponding entries from HCO.Status.RelatedObjects.\n\tc.relatedObjectsToRemove = append(c.relatedObjectsToRemove, removed...)\n}", "func (adminOrg *AdminOrg) CreateVdcWait(vdcDefinition *types.VdcConfiguration) error {\n\ttask, err := adminOrg.CreateVdc(vdcDefinition)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = task.WaitTaskCompletion()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't finish creating VDC %s\", err)\n\t}\n\treturn nil\n}", "func (b *Botanist) WaitUntilContainerRuntimeResourcesDeleted(ctx context.Context) error {\n\tvar (\n\t\tlastError *gardencorev1beta1.LastError\n\t\tcontainerRuntimes = &extensionsv1alpha1.ContainerRuntimeList{}\n\t)\n\n\tif err := b.K8sSeedClient.Client().List(ctx, containerRuntimes, client.InNamespace(b.Shoot.SeedNamespace)); err != nil {\n\t\treturn err\n\t}\n\n\tfns := make([]flow.TaskFn, 0, len(containerRuntimes.Items))\n\tfor _, containerRuntime := range containerRuntimes.Items {\n\t\tif containerRuntime.GetDeletionTimestamp() == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar (\n\t\t\tname = containerRuntime.Name\n\t\t\tnamespace = containerRuntime.Namespace\n\t\t)\n\n\t\tfns = append(fns, func(ctx context.Context) error {\n\t\t\tif err := retry.UntilTimeout(ctx, DefaultInterval, shoot.ExtensionDefaultTimeout, func(ctx context.Context) (bool, error) {\n\t\t\t\tretrievedContainerRuntime := extensionsv1alpha1.ContainerRuntime{}\n\t\t\t\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(namespace, name), &retrievedContainerRuntime); err != nil {\n\t\t\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t\t\treturn retry.Ok()\n\t\t\t\t\t}\n\t\t\t\t\treturn retry.SevereError(err)\n\t\t\t\t}\n\n\t\t\t\tif lastErr := retrievedContainerRuntime.Status.LastError; lastErr != nil {\n\t\t\t\t\tb.Logger.Errorf(\"Container runtime %s did not get deleted yet, lastError is: %s\", name, lastErr.Description)\n\t\t\t\t\tlastError = lastErr\n\t\t\t\t}\n\n\t\t\t\treturn retry.MinorError(gardencorev1beta1helper.WrapWithLastError(fmt.Errorf(\"container runtime %s is still present\", name), lastError))\n\t\t\t}); err != nil {\n\t\t\t\tmessage := \"Failed waiting for container runtime delete\"\n\t\t\t\tif lastError != nil {\n\t\t\t\t\treturn gardencorev1beta1helper.DetermineError(errors.New(lastError.Description), fmt.Sprintf(\"%s: %s\", message, lastError.Description))\n\t\t\t\t}\n\t\t\t\treturn gardencorev1beta1helper.DetermineError(err, fmt.Sprintf(\"%s: %s\", message, err.Error()))\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\treturn flow.Parallel(fns...)(ctx)\n}", "func (c *KafkaCluster) waitForRsteps(steps int) (int, error) {\n\tcancel := make(chan struct{})\n\tresult := make(chan int)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-cancel:\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tcval := atomic.LoadInt32(c.rsteps)\n\t\t\t\tif cval >= int32(steps) {\n\t\t\t\t\tresult <- int(cval)\n\t\t\t\t}\n\t\t\t\ttime.Sleep(5 * time.Millisecond)\n\t\t\t}\n\t\t}\n\t}()\n\n\tselect {\n\tcase res := <-result:\n\t\treturn res, nil\n\tcase <-time.After(3 * time.Second):\n\t\tclose(cancel)\n\t\treturn 0, errors.New(\"Timed out waiting for steps\")\n\t}\n}", "func (tc *testContext) waitForServicesConfigMapDeletion(cmName string) error {\n\terr := wait.PollImmediate(retry.Interval, retry.ResourceChangeTimeout, func() (bool, error) {\n\t\t_, err := tc.client.K8s.CoreV1().ConfigMaps(wmcoNamespace).Get(context.TODO(), cmName, meta.GetOptions{})\n\t\tif err == nil {\n\t\t\t// Retry if the resource is found\n\t\t\treturn false, nil\n\t\t}\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, fmt.Errorf(\"error retrieving ConfigMap: %s: %w\", cmName, err)\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error waiting for ConfigMap deletion %s/%s: %w\", wmcoNamespace, cmName, err)\n\t}\n\treturn nil\n}", "func waitReady(project, name, region string) error {\n\twait := time.Minute * 4\n\tdeadline := time.Now().Add(wait)\n\tfor time.Now().Before(deadline) {\n\t\tsvc, err := getService(project, name, region)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to query Service for readiness: %w\", err)\n\t\t}\n\n\t\tfor _, cond := range svc.Status.Conditions {\n\t\t\tif cond.Type == \"Ready\" {\n\t\t\t\tif cond.Status == \"True\" {\n\t\t\t\t\treturn nil\n\t\t\t\t} else if cond.Status == \"False\" {\n\t\t\t\t\treturn fmt.Errorf(\"reason=%s message=%s\", cond.Reason, cond.Message)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second * 2)\n\t}\n\treturn fmt.Errorf(\"the service did not become ready in %s, check Cloud Console for logs to see why it failed\", wait)\n}", "func (d *deploymentTester) waitForReadyReplicas() error {\n\tif err := wait.PollImmediate(pollInterval, pollTimeout, func() (bool, error) {\n\t\tdeployment, err := d.c.AppsV1().Deployments(d.deployment.Namespace).Get(context.TODO(), d.deployment.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to get deployment %q: %v\", d.deployment.Name, err)\n\t\t}\n\t\treturn deployment.Status.ReadyReplicas == *deployment.Spec.Replicas, nil\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"failed to wait for .readyReplicas to equal .replicas: %v\", err)\n\t}\n\treturn nil\n}", "func WaitForZKClusterToTerminate(t *testing.T, k8client client.Client, z *zkapi.ZookeeperCluster) error {\n\tlog.Printf(\"waiting for zookeeper cluster to terminate: %s\", z.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(z.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(map[string]string{\"app\": z.GetName()})},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"zookeeper cluster terminated: %s\", z.Name)\n\treturn nil\n}", "func waitForWebhook(ctx context.Context, client dynclient.Client) error {\n\tcondFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{\n\t\tNamespace: resources.MachineControllerNameSpace,\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\n\t\t\tappLabelKey: resources.MachineControllerWebhookName,\n\t\t}),\n\t})\n\n\treturn fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), \"waiting for machine-controller webhook to became ready\")\n}", "func waitForClusterReachable(kubeconfig string) error {\n\tcfg, err := loadKubeconfigContents(kubeconfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.Timeout = 15 * time.Second\n\tclient, err := clientset.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn wait.PollImmediate(15*time.Second, 20*time.Minute, func() (bool, error) {\n\t\t_, err := client.Core().Namespaces().Get(\"openshift-apiserver\", metav1.GetOptions{})\n\t\tif err == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\tlog.Printf(\"cluster is not yet reachable %s: %v\", cfg.Host, err)\n\t\treturn false, nil\n\t})\n}", "func waitSerial() {\n\tfor !machine.Serial.DTR() {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}", "func (it *integTestSuite) TestNpmWorkloadCreateDelete(c *C) {\n\t// if not present create the default tenant\n\tc.Skip(\"Skipped till we figure out pushing the correct insertion profile in this test suite. THis is already tested in venice integ\")\n\tit.CreateTenant(\"default\")\n\t// create a wait channel\n\twaitCh := make(chan error, it.numAgents*2)\n\n\t// create a workload on each host\n\tfor i := range it.agents {\n\t\tmacAddr := fmt.Sprintf(\"0002.0000.%02x00\", i)\n\t\terr := it.CreateWorkload(\"default\", \"default\", fmt.Sprintf(\"testWorkload-%d\", i), fmt.Sprintf(\"testHost-%d\", i), macAddr, uint32(100+i), 1)\n\t\tAssertOk(c, err, \"Error creating workload\")\n\t}\n\n\t// verify the network got created for external vlan\n\tAssertEventually(c, func() (bool, interface{}) {\n\t\t_, nerr := it.npmCtrler.StateMgr.FindNetwork(\"default\", \"Network-Vlan-1\")\n\t\treturn (nerr == nil), nil\n\t}, \"Network not found in statemgr\")\n\n\t// wait for all endpoints to be propagated to other agents\n\tfor _, ag := range it.agents {\n\t\tgo func(ag *Dpagent) {\n\t\t\tfound := CheckEventually(func() (bool, interface{}) {\n\t\t\t\tepMeta := netproto.Endpoint{\n\t\t\t\t\tTypeMeta: api.TypeMeta{Kind: \"Endpoint\"},\n\t\t\t\t}\n\t\t\t\tendpoints, _ := ag.dscAgent.PipelineAPI.HandleEndpoint(agentTypes.List, epMeta)\n\t\t\t\treturn len(endpoints) == it.numAgents, nil\n\t\t\t}, \"10ms\", it.pollTimeout())\n\t\t\tif !found {\n\t\t\t\tepMeta := netproto.Endpoint{\n\t\t\t\t\tTypeMeta: api.TypeMeta{Kind: \"Endpoint\"},\n\t\t\t\t}\n\t\t\t\tendpoints, _ := ag.dscAgent.PipelineAPI.HandleEndpoint(agentTypes.List, epMeta)\n\t\t\t\tlog.Infof(\"Endpoint count expected [%v] found [%v]\", it.numAgents, len(endpoints))\n\t\t\t\twaitCh <- fmt.Errorf(\"Endpoint count incorrect in datapath\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfoundLocal := false\n\t\t\tfor idx := range it.agents {\n\t\t\t\tmacAddr := fmt.Sprintf(\"0002.0000.%02x00\", idx)\n\t\t\t\tname, _ := strconv.ParseMacAddr(macAddr)\n\t\t\t\tepname := fmt.Sprintf(\"testWorkload-%d-%s\", idx, name)\n\t\t\t\tepmeta := netproto.Endpoint{\n\t\t\t\t\tTypeMeta: api.TypeMeta{Kind: \"Endpoint\"},\n\t\t\t\t\tObjectMeta: api.ObjectMeta{\n\t\t\t\t\t\tTenant: \"default\",\n\t\t\t\t\t\tNamespace: \"default\",\n\t\t\t\t\t\tName: epname,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tsep, perr := ag.dscAgent.PipelineAPI.HandleEndpoint(agentTypes.Get, epmeta)\n\t\t\t\tif perr != nil {\n\t\t\t\t\twaitCh <- fmt.Errorf(\"Endpoint %s not found in netagent, err=%v\", epname, perr)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif sep[0].Spec.NodeUUID == ag.dscAgent.InfraAPI.GetDscName() {\n\t\t\t\t\tfoundLocal = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !foundLocal {\n\t\t\t\twaitCh <- fmt.Errorf(\"No local endpoint found on %s\", ag.dscAgent.InfraAPI.GetDscName())\n\t\t\t\treturn\n\t\t\t}\n\t\t\twaitCh <- nil\n\t\t}(ag)\n\t}\n\n\t// wait for all goroutines to complete\n\tfor i := 0; i < it.numAgents; i++ {\n\t\tAssertOk(c, <-waitCh, \"Endpoint info incorrect in datapath\")\n\n\t}\n\n\t// now delete the workloads\n\tfor idx := range it.agents {\n\t\terr := it.DeleteWorkload(\"default\", \"default\", fmt.Sprintf(\"testWorkload-%d\", idx))\n\t\tAssertOk(c, err, \"Error deleting workload\")\n\t}\n\n\tfor _, ag := range it.agents {\n\t\tgo func(ag *Dpagent) {\n\t\t\tif !CheckEventually(func() (bool, interface{}) {\n\t\t\t\tepMeta := netproto.Endpoint{\n\t\t\t\t\tTypeMeta: api.TypeMeta{Kind: \"Endpoint\"},\n\t\t\t\t}\n\t\t\t\tendpoints, _ := ag.dscAgent.PipelineAPI.HandleEndpoint(agentTypes.List, epMeta)\n\t\t\t\treturn len(endpoints) == 0, nil\n\t\t\t}, \"10ms\", it.pollTimeout()) {\n\t\t\t\twaitCh <- fmt.Errorf(\"Endpoint was not deleted from datapath\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\twaitCh <- nil\n\t\t}(ag)\n\t}\n\n\t// wait for all goroutines to complete\n\tfor i := 0; i < it.numAgents; i++ {\n\t\tAssertOk(c, <-waitCh, \"Endpoint delete error\")\n\t}\n\n\t// delete the network\n\terr := it.DeleteNetwork(\"default\", \"Network-Vlan-1\")\n\tc.Assert(err, IsNil)\n\tAssertEventually(c, func() (bool, interface{}) {\n\t\t_, nerr := it.npmCtrler.StateMgr.FindNetwork(\"default\", \"Network-Vlan-1\")\n\t\treturn (nerr != nil), nil\n\t}, \"Network still found in statemgr\")\n}", "func (h *CRDHandler) EnsureCRD(meta *CRDMeta, namespacedScoped bool) (*apiextensionsv1.CustomResourceDefinition, error) {\n\tcrd, err := h.createOrUpdateCRD(meta, namespacedScoped)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// After CRD creation, it might take a few seconds for the RESTful API endpoint\n\t// to be created. Keeps watching the Established condition of BackendConfig\n\t// CRD to be true.\n\tif err := wait.PollImmediate(checkCRDEstablishedInterval, checkCRDEstablishedTimeout, func() (bool, error) {\n\t\tcrd, err = h.client.ApiextensionsV1().CustomResourceDefinitions().Get(context.TODO(), crd.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tfor _, c := range crd.Status.Conditions {\n\t\t\tif c.Type == apiextensionsv1.Established && c.Status == apiextensionsv1.ConditionTrue {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t\treturn false, nil\n\t}); err != nil {\n\t\treturn nil, fmt.Errorf(\"timed out waiting for %v CRD to become Established: %v\", meta.kind, err)\n\t}\n\n\tklog.V(0).Infof(\"%v CRD is Established.\", meta.kind)\n\treturn crd, nil\n}", "func CreateOCRJobs(\n\tocrInstances []contracts.OffchainAggregator,\n\tbootstrapNode *client.ChainlinkK8sClient,\n\tworkerNodes []*client.ChainlinkK8sClient,\n\tmockValue int,\n\tmockserver *ctfClient.MockserverClient,\n) error {\n\tfor _, ocrInstance := range ocrInstances {\n\t\tbootstrapP2PIds, err := bootstrapNode.MustReadP2PKeys()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"reading P2P keys from bootstrap node have failed: %w\", err)\n\t\t}\n\t\tbootstrapP2PId := bootstrapP2PIds.Data[0].Attributes.PeerID\n\t\tbootstrapSpec := &client.OCRBootstrapJobSpec{\n\t\t\tName: fmt.Sprintf(\"bootstrap-%s\", uuid.New().String()),\n\t\t\tContractAddress: ocrInstance.Address(),\n\t\t\tP2PPeerID: bootstrapP2PId,\n\t\t\tIsBootstrapPeer: true,\n\t\t}\n\t\t_, err = bootstrapNode.MustCreateJob(bootstrapSpec)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"creating bootstrap job have failed: %w\", err)\n\t\t}\n\n\t\tfor _, node := range workerNodes {\n\t\t\tnodeP2PIds, err := node.MustReadP2PKeys()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"reading P2P keys from OCR node have failed: %w\", err)\n\t\t\t}\n\t\t\tnodeP2PId := nodeP2PIds.Data[0].Attributes.PeerID\n\t\t\tnodeTransmitterAddress, err := node.PrimaryEthAddress()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"getting primary ETH address from OCR node have failed: %w\", err)\n\t\t\t}\n\t\t\tnodeOCRKeys, err := node.MustReadOCRKeys()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"getting OCR keys from OCR node have failed: %w\", err)\n\t\t\t}\n\t\t\tnodeOCRKeyId := nodeOCRKeys.Data[0].ID\n\n\t\t\tnodeContractPairID, err := BuildNodeContractPairID(node, ocrInstance)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbta := &client.BridgeTypeAttributes{\n\t\t\t\tName: nodeContractPairID,\n\t\t\t\tURL: fmt.Sprintf(\"%s/%s\", mockserver.Config.ClusterURL, strings.TrimPrefix(nodeContractPairID, \"/\")),\n\t\t\t}\n\t\t\terr = SetAdapterResponse(mockValue, ocrInstance, node, mockserver)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"setting adapter response for OCR node failed: %w\", err)\n\t\t\t}\n\t\t\terr = node.MustCreateBridge(bta)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"creating bridge job have failed: %w\", err)\n\t\t\t}\n\n\t\t\tbootstrapPeers := []*client.ChainlinkClient{bootstrapNode.ChainlinkClient}\n\t\t\tocrSpec := &client.OCRTaskJobSpec{\n\t\t\t\tContractAddress: ocrInstance.Address(),\n\t\t\t\tP2PPeerID: nodeP2PId,\n\t\t\t\tP2PBootstrapPeers: bootstrapPeers,\n\t\t\t\tKeyBundleID: nodeOCRKeyId,\n\t\t\t\tTransmitterAddress: nodeTransmitterAddress,\n\t\t\t\tObservationSource: client.ObservationSourceSpecBridge(bta),\n\t\t\t}\n\t\t\t_, err = node.MustCreateJob(ocrSpec)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"creating OCR task job on OCR node have failed: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (cm *CertificateManager) WaitForCertDirReady() error {\n\ttimeout := time.Minute * 5\n\tselect {\n\tcase <-cm.certDirReady():\n\t\treturn nil\n\tcase <-time.After(timeout):\n\t\treturn fmt.Errorf(\"timed out after %s\", timeout.String())\n\t}\n}", "func checkNodesReady(c *client.Client, nt time.Duration, expect int) ([]string, error) {\n\t// First, keep getting all of the nodes until we get the number we expect.\n\tvar nodeList *api.NodeList\n\tvar errLast error\n\tstart := time.Now()\n\tfound := wait.Poll(poll, nt, func() (bool, error) {\n\t\t// Even though listNodes(...) has its own retries, a rolling-update\n\t\t// (GCE/GKE implementation of restart) can complete before the apiserver\n\t\t// knows about all of the nodes. Thus, we retry the list nodes call\n\t\t// until we get the expected number of nodes.\n\t\tnodeList, errLast = listNodes(c, labels.Everything(), fields.Everything())\n\t\tif errLast != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif len(nodeList.Items) != expect {\n\t\t\terrLast = fmt.Errorf(\"expected to find %d nodes but found only %d (%v elapsed)\",\n\t\t\t\texpect, len(nodeList.Items), time.Since(start))\n\t\t\tLogf(\"%v\", errLast)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}) == nil\n\tnodeNames := make([]string, len(nodeList.Items))\n\tfor i, n := range nodeList.Items {\n\t\tnodeNames[i] = n.ObjectMeta.Name\n\t}\n\tif !found {\n\t\treturn nodeNames, fmt.Errorf(\"couldn't find %d nodes within %v; last error: %v\",\n\t\t\texpect, nt, errLast)\n\t}\n\tLogf(\"Successfully found %d nodes\", expect)\n\n\t// Next, ensure in parallel that all the nodes are ready. We subtract the\n\t// time we spent waiting above.\n\ttimeout := nt - time.Since(start)\n\tresult := make(chan bool, len(nodeList.Items))\n\tfor _, n := range nodeNames {\n\t\tn := n\n\t\tgo func() { result <- waitForNodeToBeReady(c, n, timeout) }()\n\t}\n\tfailed := false\n\t// TODO(mbforbes): Change to `for range` syntax once we support only Go\n\t// >= 1.4.\n\tfor i := range nodeList.Items {\n\t\t_ = i\n\t\tif !<-result {\n\t\t\tfailed = true\n\t\t}\n\t}\n\tif failed {\n\t\treturn nodeNames, fmt.Errorf(\"at least one node failed to be ready\")\n\t}\n\treturn nodeNames, nil\n}", "func (b *Botanist) WaitUntilEtcdReady(ctx context.Context) error {\n\tvar (\n\t\tretryCountUntilSevere int\n\t\tinterval = 5 * time.Second\n\t\tsevereThreshold = 30 * time.Second\n\t\ttimeout = 5 * time.Minute\n\t)\n\n\treturn retry.UntilTimeout(ctx, interval, timeout, func(ctx context.Context) (done bool, err error) {\n\t\tretryCountUntilSevere++\n\n\t\tetcdList := &druidv1alpha1.EtcdList{}\n\t\tif err := b.K8sSeedClient.DirectClient().List(ctx, etcdList,\n\t\t\tclient.InNamespace(b.Shoot.SeedNamespace),\n\t\t\tclient.MatchingLabels{\"garden.sapcloud.io/role\": \"controlplane\"},\n\t\t); err != nil {\n\t\t\treturn retry.SevereError(err)\n\t\t}\n\n\t\tif n := len(etcdList.Items); n < 2 {\n\t\t\tb.Logger.Info(\"Waiting until the etcd gets created...\")\n\t\t\treturn retry.MinorError(fmt.Errorf(\"only %d/%d etcd resources found\", n, 2))\n\t\t}\n\n\t\tvar lastErrors error\n\n\t\tfor _, etcd := range etcdList.Items {\n\t\t\tswitch {\n\t\t\tcase etcd.Status.LastError != nil:\n\t\t\t\treturn retry.MinorOrSevereError(retryCountUntilSevere, int(severeThreshold.Nanoseconds()/interval.Nanoseconds()), fmt.Errorf(\"%s reconciliation errored: %s\", etcd.Name, *etcd.Status.LastError))\n\t\t\tcase etcd.DeletionTimestamp != nil:\n\t\t\t\tlastErrors = multierror.Append(lastErrors, fmt.Errorf(\"%s unexpectedly has a deletion timestamp\", etcd.Name))\n\t\t\tcase etcd.Status.ObservedGeneration == nil || etcd.Generation != *etcd.Status.ObservedGeneration:\n\t\t\t\tlastErrors = multierror.Append(lastErrors, fmt.Errorf(\"%s reconciliation pending\", etcd.Name))\n\t\t\tcase metav1.HasAnnotation(etcd.ObjectMeta, v1beta1constants.GardenerOperation):\n\t\t\t\tlastErrors = multierror.Append(lastErrors, fmt.Errorf(\"%s reconciliation in process\", etcd.Name))\n\t\t\tcase !utils.IsTrue(etcd.Status.Ready):\n\t\t\t\tlastErrors = multierror.Append(lastErrors, fmt.Errorf(\"%s is not ready yet\", etcd.Name))\n\t\t\t}\n\t\t}\n\n\t\tif lastErrors == nil {\n\t\t\treturn retry.Ok()\n\t\t}\n\n\t\tb.Logger.Info(\"Waiting until the both etcds are ready...\")\n\t\treturn retry.MinorError(lastErrors)\n\t})\n}", "func waitUntilRDSInstanceCreated(rdsClientSess *rds.RDS, restoreParams map[string]string) error {\n\trdsClusterName := restoreParams[\"restoreRDS\"]\n\trdsInstanceName := rdsClusterName + \"-0\" // TODO: this should be handled better\n\n\tinput := &rds.DescribeDBInstancesInput{\n\t\tDBInstanceIdentifier: aws.String(rdsInstanceName),\n\t}\n\n\tstart := time.Now()\n\tmaxWaitAttempts := 120\n\n\tfmt.Printf(\"Wait until RDS instance [%v] in cluster [%v] is fully created ...\\n\", rdsInstanceName, rdsClusterName)\n\n\tfor waitAttempt := 0; waitAttempt < maxWaitAttempts; waitAttempt++ {\n\t\telapsedTime := time.Since(start)\n\t\tif waitAttempt > 0 {\n\t\t\tformattedTime := strings.Split(fmt.Sprintf(\"%6v\", elapsedTime), \".\")\n\t\t\tfmt.Printf(\"Instance creation elapsed time: %vs\\n\", formattedTime[0])\n\t\t}\n\n\t\tresp, err := rdsClientSess.DescribeDBInstances(input)\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Wait RDS instance create err %v\", err)\n\t\t}\n\n\t\tfmt.Printf(\"Instance status: [%s]\\n\", *resp.DBInstances[0].DBInstanceStatus)\n\t\tif *resp.DBInstances[0].DBInstanceStatus== \"available\" {\n\t\t\tfmt.Printf(\"RDS instance [%v] created successfully\\n\", rdsClusterName)\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(30 * time.Second)\n\t}\n\tfmt.Printf(\"RDS instance [%v] created successfully in RDS cluster [%v]\\n\", rdsInstanceName, rdsClusterName)\n\treturn nil\n}", "func (c *EEBus) waitForConnection() error {\n\ttimeout := time.After(90 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\treturn os.ErrDeadlineExceeded\n\t\tcase connected := <-c.connectedC:\n\t\t\tif connected {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n}", "func (o Scorecard) waitForTestsToComplete(tests []Test) (err error) {\n\twaitTimeInSeconds := int(o.WaitTime.Seconds())\n\tfor elapsedSeconds := 0; elapsedSeconds < waitTimeInSeconds; elapsedSeconds++ {\n\t\tallPodsCompleted := true\n\t\tfor _, test := range tests {\n\t\t\tp := test.TestPod\n\t\t\tvar tmp *v1.Pod\n\t\t\ttmp, err = o.Client.CoreV1().Pods(p.Namespace).Get(context.TODO(), p.Name, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error getting pod %s %w\", p.Name, err)\n\t\t\t}\n\t\t\tif tmp.Status.Phase != v1.PodSucceeded {\n\t\t\t\tallPodsCompleted = false\n\t\t\t}\n\n\t\t}\n\t\tif allPodsCompleted {\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\treturn fmt.Errorf(\"error - wait time of %d seconds has been exceeded\", o.WaitTime)\n\n}", "func (c *Client) WaitForDaemonSet(ns, name string, timeout time.Duration) error {\n\tif c.ApplyDryRun {\n\t\treturn nil\n\t}\n\tclient, err := c.GetClientset()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdaemonsets := client.AppsV1().DaemonSets(ns)\n\tid := Name{Kind: \"Daemonset\", Name: name, Namespace: ns}\n\tstart := time.Now()\n\tmsg := false\n\tfor {\n\t\tdaemonset, err := daemonsets.Get(context.TODO(), name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif start.Add(timeout).Before(time.Now()) {\n\t\t\treturn fmt.Errorf(\"%s timeout waiting for daemonset to become ready\", id)\n\t\t}\n\n\t\tif daemonset != nil && daemonset.Status.NumberReady >= 1 {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !msg {\n\t\t\tc.Infof(\"%s ⏳ waiting for at least 1 pod\", id)\n\t\t\tmsg = true\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\t}\n}", "func recordCRs(namespaceDir string, namespace string) error {\n\tcrds, err := kubeList(namespace, \"crd\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// record all unique CRs floating about\n\tfor _, crd := range crds {\n\t\t// consider all installed CRDs that are solo-managed\n\t\tif !strings.Contains(crd, \"solo.io\") {\n\t\t\tcontinue\n\t\t}\n\n\t\t// if there are any existing CRs corresponding to this CRD\n\t\tcrs, err := kubeList(namespace, crd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(crs) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcrdDir := filepath.Join(namespaceDir, crd)\n\t\tif err := os.MkdirAll(crdDir, os.ModePerm); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// we record each one in its own .yaml representation\n\t\tfor _, cr := range crs {\n\t\t\tf := fileAtPath(filepath.Join(crdDir, cr+\".yaml\"))\n\t\t\tcrDetails, err := kubeGet(namespace, crd, cr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tf.WriteString(crDetails)\n\t\t\tf.Close()\n\t\t}\n\t}\n\n\treturn nil\n}", "func WaitForDeletion(ctx context.Context, mcpKey types.NamespacedName, timeout time.Duration) error {\n\treturn wait.PollImmediate(5*time.Second, timeout, func() (bool, error) {\n\t\tmcp := &machineconfigv1.MachineConfigPool{}\n\t\tif err := testclient.Client.Get(ctx, mcpKey, mcp); apierrors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func waitForNewChildLB(ctx context.Context, ch *testutils.Channel) (*fakeChildBalancer, error) {\n\tval, err := ch.Receive(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error when waiting for a new edsLB: %v\", err)\n\t}\n\treturn val.(*fakeChildBalancer), nil\n}", "func WaitForClusterToTerminate(t *testing.T, f *framework.Framework, ctx *framework.TestCtx, z *api.ZookeeperCluster) error {\n\tt.Logf(\"waiting for zookeeper cluster to terminate: %s\", z.Name)\n\n\tlistOptions := metav1.ListOptions{\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\"app\": z.GetName()}).String(),\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList, err := f.KubeClient.CoreV1().Pods(z.Namespace).List(goctx.TODO(), listOptions)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tt.Logf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList, err := f.KubeClient.CoreV1().PersistentVolumeClaims(z.Namespace).List(goctx.TODO(), listOptions)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tt.Logf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.Logf(\"zookeeper cluster terminated: %s\", z.Name)\n\treturn nil\n}", "func waitForAwsResource(name, event string, c *client.Client) error {\n\ttick := time.Tick(time.Second * 2)\n\ttimeout := time.After(time.Minute * 5)\n\tfmt.Printf(\"Waiting for %s \", name)\n\tfailedEv := event + \"_FAILED\"\n\tcompletedEv := event + \"_COMPLETE\"\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-tick:\n\t\t\trs, err := c.GetResource(name)\n\t\t\tif err != nil {\n\t\t\t\tif event == \"DELETE\" {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfmt.Print(\".\")\n\t\t\tif rs.Status == failedEv {\n\t\t\t\treturn fmt.Errorf(\"%s failed because of \\\"%s\\\"\", event, rs.StatusReason)\n\t\t\t}\n\t\t\tif rs.Status == completedEv {\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tcase <-timeout:\n\t\t\tfmt.Print(\"timeout (5 minutes). Skipping\")\n\t\t\tbreak Loop\n\t\t}\n\t}\n\n\treturn nil\n}", "func waitForClusterToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForClusterStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(cluster *capiv1alpha1.Cluster) bool { return cluster != nil },\n\t)\n}", "func TestRktDriver_Start_Wait_Stop_DNS(t *testing.T) {\n\tctestutil.RktCompatible(t)\n\tif !testutil.IsCI() {\n\t\tt.Parallel()\n\t}\n\n\trequire := require.New(t)\n\td := NewRktDriver(testlog.HCLogger(t))\n\tharness := dtestutil.NewDriverHarness(t, d)\n\n\ttask := &drivers.TaskConfig{\n\t\tID: uuid.Generate(),\n\t\tAllocID: uuid.Generate(),\n\t\tName: \"etcd\",\n\t\tResources: &drivers.Resources{\n\t\t\tNomadResources: &structs.AllocatedTaskResources{\n\t\t\t\tMemory: structs.AllocatedMemoryResources{\n\t\t\t\t\tMemoryMB: 128,\n\t\t\t\t},\n\t\t\t\tCpu: structs.AllocatedCpuResources{\n\t\t\t\t\tCpuShares: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t\tLinuxResources: &drivers.LinuxResources{\n\t\t\t\tMemoryLimitBytes: 134217728,\n\t\t\t\tCPUShares: 100,\n\t\t\t},\n\t\t},\n\t}\n\n\ttc := &TaskConfig{\n\t\tTrustPrefix: \"coreos.com/etcd\",\n\t\tImageName: \"coreos.com/etcd:v2.0.4\",\n\t\tCommand: \"/etcd\",\n\t\tDNSServers: []string{\"8.8.8.8\", \"8.8.4.4\"},\n\t\tDNSSearchDomains: []string{\"example.com\", \"example.org\", \"example.net\"},\n\t\tNet: []string{\"host\"},\n\t}\n\trequire.NoError(task.EncodeConcreteDriverConfig(&tc))\n\ttesttask.SetTaskConfigEnv(task)\n\tcleanup := harness.MkAllocDir(task, true)\n\tdefer cleanup()\n\n\thandle, driverNet, err := harness.StartTask(task)\n\trequire.NoError(err)\n\trequire.Nil(driverNet)\n\n\tch, err := harness.WaitTask(context.Background(), handle.Config.ID)\n\trequire.NoError(err)\n\n\trequire.NoError(harness.WaitUntilStarted(task.ID, 1*time.Second))\n\n\tgo func() {\n\t\tharness.StopTask(task.ID, 2*time.Second, \"SIGTERM\")\n\t}()\n\n\tselect {\n\tcase result := <-ch:\n\t\trequire.Equal(int(unix.SIGTERM), result.Signal)\n\tcase <-time.After(10 * time.Second):\n\t\trequire.Fail(\"timeout waiting for task to shutdown\")\n\t}\n\n\t// Ensure that the task is marked as dead, but account\n\t// for WaitTask() closing channel before internal state is updated\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tstatus, err := harness.InspectTask(task.ID)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"inspecting task failed: %v\", err)\n\t\t}\n\t\tif status.State != drivers.TaskStateExited {\n\t\t\treturn false, fmt.Errorf(\"task hasn't exited yet; status: %v\", status.State)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.NoError(err)\n\t})\n\n\trequire.NoError(harness.DestroyTask(task.ID, true))\n}", "func (envManager *TestEnvManager) WaitUntilReady() (bool, error) {\n\tlog.Println(\"Start checking components' status\")\n\tretry := u.Retrier{\n\t\tBaseDelay: 1 * time.Second,\n\t\tMaxDelay: 10 * time.Second,\n\t\tRetries: 8,\n\t}\n\n\tready := false\n\tretryFn := func(_ context.Context, i int) error {\n\t\tfor _, comp := range envManager.testEnv.GetComponents() {\n\t\t\tif alive, err := comp.IsAlive(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to comfirm compoment %s is alive %v\", comp.GetName(), err)\n\t\t\t} else if !alive {\n\t\t\t\treturn fmt.Errorf(\"component %s is not alive\", comp.GetName())\n\t\t\t}\n\t\t}\n\n\t\tready = true\n\t\tlog.Println(\"All components are ready\")\n\t\treturn nil\n\t}\n\n\t_, err := retry.Retry(context.Background(), retryFn)\n\treturn ready, err\n}", "func TestWaitUntilAllNodesReady(t *testing.T) {\n\tt.Parallel()\n\n\toptions := NewKubectlOptions(\"\", \"\", \"default\")\n\n\tWaitUntilAllNodesReady(t, options, 12, 5*time.Second)\n\n\tnodes := GetNodes(t, options)\n\tnodeNames := map[string]bool{}\n\tfor _, node := range nodes {\n\t\tnodeNames[node.Name] = true\n\t}\n\n\treadyNodes := GetReadyNodes(t, options)\n\treadyNodeNames := map[string]bool{}\n\tfor _, node := range readyNodes {\n\t\treadyNodeNames[node.Name] = true\n\t}\n\n\tassert.Equal(t, nodeNames, readyNodeNames)\n}", "func wait(ctx context.Context, c TimedActuator,\n\tresChan chan error, cancel context.CancelFunc) error {\n\tif timeout := c.GetTimeout(); timeout != nil {\n\t\treturn waitWithTimeout(ctx, resChan, *timeout, cancel)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tcase err := <-resChan:\n\t\t\tif err != nil {\n\t\t\t\tcancel()\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *myClient) batchCreateSelfServiceContainer(containerList ...PatientContainer) (resultsList []map[string]interface{}, err error) {\n\tfor _, v := range containerList {\n\t\tif result, err := c.createSelfServiceContainer(v, false); result != nil && err == nil && (result[\"job\"] != nil || result[\"action\"] != nil) {\n\t\t\tresultsList = append(resultsList, result)\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tc.jobWaiter(resultsList...)\n\n\treturn resultsList, err\n}", "func WaitForCondition(mcpName string, conditionType machineconfigv1.MachineConfigPoolConditionType, conditionStatus corev1.ConditionStatus) {\n\n\tvar cnfNodes []corev1.Node\n\trunningOnSingleNode, err := cluster.IsSingleNode()\n\tExpectWithOffset(1, err).ToNot(HaveOccurred())\n\t// checking in eventually as in case of single node cluster the only node may\n\t// be rebooting\n\tEventuallyWithOffset(1, func() error {\n\t\tmcp, err := GetByName(mcpName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed getting MCP by name\")\n\t\t}\n\n\t\tnodeLabels := mcp.Spec.NodeSelector.MatchLabels\n\t\tkey, _ := components.GetFirstKeyAndValue(nodeLabels)\n\t\treq, err := labels.NewRequirement(key, selection.Exists, []string{})\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed creating node selector\")\n\t\t}\n\n\t\tselector := labels.NewSelector()\n\t\tselector = selector.Add(*req)\n\t\tcnfNodes, err = nodes.GetBySelector(selector)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed getting nodes by selector\")\n\t\t}\n\n\t\ttestlog.Infof(\"MCP %q is targeting %v node(s)\", mcp.Name, len(cnfNodes))\n\t\treturn nil\n\t}, cluster.ComputeTestTimeout(10*time.Minute, runningOnSingleNode), 5*time.Second).ShouldNot(HaveOccurred(), \"Failed to find CNF nodes by MCP %q\", mcpName)\n\n\t// timeout should be based on the number of worker-cnf nodes\n\ttimeout := time.Duration(len(cnfNodes)*mcpUpdateTimeoutPerNode) * time.Minute\n\tif len(cnfNodes) == 0 {\n\t\ttimeout = 2 * time.Minute\n\t}\n\n\tEventuallyWithOffset(1, func() corev1.ConditionStatus {\n\t\treturn GetConditionStatus(mcpName, conditionType)\n\t}, cluster.ComputeTestTimeout(timeout, runningOnSingleNode), 30*time.Second).Should(Equal(conditionStatus), \"Failed to find condition status by MCP %q\", mcpName)\n}", "func (c *knDynamicClient) ListCRDs(options metav1.ListOptions) (*unstructured.UnstructuredList, error) {\n\tgvr := schema.GroupVersionResource{\n\t\tGroup: crdGroup,\n\t\tVersion: crdVersion,\n\t\tResource: crdKinds,\n\t}\n\n\tuList, err := c.client.Resource(gvr).List(options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn uList, nil\n}", "func (c *myClient) discoverCDB(envName, cdbName, username, password string, wait bool) (results map[string]interface{}, err error) {\n\tnamespace := \"sourceconfig\"\n\tscObj, err := c.findSourceCongfigByNameAndEnvironmentName(cdbName, envName)\n\tscObjRef := scObj[\"reference\"]\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turl := fmt.Sprintf(\"%s/%s\", namespace, scObjRef)\n\tpostBody := fmt.Sprintf(`{\n\t\t\"type\": \"OracleSIConfig\", \n\t\t\"user\": \"%s\",\n\t\t\"credentials\": {\n\t\t\t\"type\": \"PasswordCredential\",\n\t\t\t\"password\": \"%s\"\n\t\t\t}\n\t\t}`, username, password)\n\taction, _, err := c.httpPost(url, postBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif wait {\n\t\tc.jobWaiter(action)\n\t}\n\treturn action, err\n\n}", "func WaitForPodsRunningReady(c clientset.Interface, ns string, minPods, allowedNotReadyPods int32, timeout time.Duration, ignoreLabels map[string]string) error {\n\tif minPods == -1 || allowedNotReadyPods == -1 {\n\t\treturn nil\n\t}\n\n\tignoreSelector := labels.SelectorFromSet(map[string]string{})\n\tstart := time.Now()\n\tframework.Logf(\"Waiting up to %v for all pods (need at least %d) in namespace '%s' to be running and ready\",\n\t\ttimeout, minPods, ns)\n\tvar ignoreNotReady bool\n\tbadPods := []v1.Pod{}\n\tdesiredPods := 0\n\tnotReady := int32(0)\n\tvar lastAPIError error\n\n\tif wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\t// We get the new list of pods, replication controllers, and\n\t\t// replica sets in every iteration because more pods come\n\t\t// online during startup and we want to ensure they are also\n\t\t// checked.\n\t\treplicas, replicaOk := int32(0), int32(0)\n\t\t// Clear API error from the last attempt in case the following calls succeed.\n\t\tlastAPIError = nil\n\n\t\trcList, err := c.CoreV1().ReplicationControllers(ns).List(context.TODO(), metav1.ListOptions{})\n\t\tlastAPIError = err\n\t\tif err != nil {\n\t\t\treturn handleWaitingAPIError(err, false, \"listing replication controllers in namespace %s\", ns)\n\t\t}\n\t\tfor _, rc := range rcList.Items {\n\t\t\treplicas += *rc.Spec.Replicas\n\t\t\treplicaOk += rc.Status.ReadyReplicas\n\t\t}\n\n\t\trsList, err := c.AppsV1().ReplicaSets(ns).List(context.TODO(), metav1.ListOptions{})\n\t\tlastAPIError = err\n\t\tif err != nil {\n\t\t\treturn handleWaitingAPIError(err, false, \"listing replication sets in namespace %s\", ns)\n\t\t}\n\t\tfor _, rs := range rsList.Items {\n\t\t\treplicas += *rs.Spec.Replicas\n\t\t\treplicaOk += rs.Status.ReadyReplicas\n\t\t}\n\n\t\tpodList, err := c.CoreV1().Pods(ns).List(context.TODO(), metav1.ListOptions{})\n\t\tlastAPIError = err\n\t\tif err != nil {\n\t\t\treturn handleWaitingAPIError(err, false, \"listing pods in namespace %s\", ns)\n\t\t}\n\t\tnOk := int32(0)\n\t\tnotReady = int32(0)\n\t\tbadPods = []v1.Pod{}\n\t\tdesiredPods = len(podList.Items)\n\t\tfor _, pod := range podList.Items {\n\t\t\tif len(ignoreLabels) != 0 && ignoreSelector.Matches(labels.Set(pod.Labels)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tres, err := testutils.PodRunningReady(&pod)\n\t\t\tswitch {\n\t\t\tcase res && err == nil:\n\t\t\t\tnOk++\n\t\t\tcase pod.Status.Phase == v1.PodSucceeded:\n\t\t\t\tframework.Logf(\"The status of Pod %s is Succeeded, skipping waiting\", pod.ObjectMeta.Name)\n\t\t\t\t// it doesn't make sense to wait for this pod\n\t\t\t\tcontinue\n\t\t\tcase pod.Status.Phase != v1.PodFailed:\n\t\t\t\tframework.Logf(\"The status of Pod %s is %s (Ready = false), waiting for it to be either Running (with Ready = true) or Failed\", pod.ObjectMeta.Name, pod.Status.Phase)\n\t\t\t\tnotReady++\n\t\t\t\tbadPods = append(badPods, pod)\n\t\t\tdefault:\n\t\t\t\tif metav1.GetControllerOf(&pod) == nil {\n\t\t\t\t\tframework.Logf(\"Pod %s is Failed, but it's not controlled by a controller\", pod.ObjectMeta.Name)\n\t\t\t\t\tbadPods = append(badPods, pod)\n\t\t\t\t}\n\t\t\t\t// ignore failed pods that are controlled by some controller\n\t\t\t}\n\t\t}\n\n\t\tframework.Logf(\"%d / %d pods in namespace '%s' are running and ready (%d seconds elapsed)\",\n\t\t\tnOk, len(podList.Items), ns, int(time.Since(start).Seconds()))\n\t\tframework.Logf(\"expected %d pod replicas in namespace '%s', %d are Running and Ready.\", replicas, ns, replicaOk)\n\n\t\tif replicaOk == replicas && nOk >= minPods && len(badPods) == 0 {\n\t\t\treturn true, nil\n\t\t}\n\t\tignoreNotReady = (notReady <= allowedNotReadyPods)\n\t\tLogPodStates(badPods)\n\t\treturn false, nil\n\t}) != nil {\n\t\tif !ignoreNotReady {\n\t\t\treturn errorBadPodsStates(badPods, desiredPods, ns, \"RUNNING and READY\", timeout, lastAPIError)\n\t\t}\n\t\tframework.Logf(\"Number of not-ready pods (%d) is below the allowed threshold (%d).\", notReady, allowedNotReadyPods)\n\t}\n\treturn nil\n}", "func ForDaemonSetReady(clName string, c kubernetes.Interface, namespace, daemonSetName string) error {\n\tctx := context.Background()\n\tlog.Debugf(\"Waiting up to %v for %s daemon set roll out %s ...\", defaults.WaitDurationResources, daemonSetName, clName)\n\tdeploymentContext, cancel := context.WithTimeout(ctx, defaults.WaitDurationResources)\n\twait.Until(func() {\n\t\tdaemonSet, err := c.AppsV1().DaemonSets(namespace).Get(daemonSetName, metav1.GetOptions{})\n\t\tif err == nil && daemonSet.Status.CurrentNumberScheduled > 0 {\n\t\t\tif daemonSet.Status.NumberReady == daemonSet.Status.DesiredNumberScheduled {\n\t\t\t\tlog.Infof(\"✔ %s successfully rolled out to %s, ready replicas: %v\", daemonSetName, clName, daemonSet.Status.NumberReady)\n\t\t\t\tcancel()\n\t\t\t} else {\n\t\t\t\tlog.Infof(\"Still waiting for %s daemon set roll out for %s, ready replicas: %v\", daemonSetName, clName, daemonSet.Status.NumberReady)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Debugf(\"Still waiting for %s daemon set roll out %s ...\", daemonSetName, clName)\n\t\t}\n\t}, 5*time.Second, deploymentContext.Done())\n\terr := deploymentContext.Err()\n\tif err != nil && err != context.Canceled {\n\t\treturn errors.Wrapf(err, \"Error waiting for %s daemon set roll out.\", daemonSetName)\n\t}\n\treturn nil\n}", "func WaitForInfraServices(ctx context.Context, kc *kubernetes.Clientset) error {\n\tfor _, app := range daemonsetWhitelist {\n\t\tlog.Infof(\"checking daemonset %s/%s\", app.Namespace, app.Name)\n\n\t\terr := wait.PollImmediateUntil(time.Second, func() (bool, error) {\n\t\t\tds, err := kc.AppsV1().DaemonSets(app.Namespace).Get(app.Name, metav1.GetOptions{})\n\t\t\tswitch {\n\t\t\tcase kerrors.IsNotFound(err):\n\t\t\t\treturn false, nil\n\t\t\tcase err == nil:\n\t\t\t\treturn ds.Status.DesiredNumberScheduled == ds.Status.CurrentNumberScheduled &&\n\t\t\t\t\tds.Status.DesiredNumberScheduled == ds.Status.NumberReady &&\n\t\t\t\t\tds.Status.DesiredNumberScheduled == ds.Status.UpdatedNumberScheduled &&\n\t\t\t\t\tds.Generation == ds.Status.ObservedGeneration, nil\n\t\t\tdefault:\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}, ctx.Done())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, app := range deploymentWhitelist {\n\t\tlog.Infof(\"checking deployment %s/%s\", app.Namespace, app.Name)\n\n\t\terr := wait.PollImmediateUntil(time.Second, func() (bool, error) {\n\t\t\td, err := kc.AppsV1().Deployments(app.Namespace).Get(app.Name, metav1.GetOptions{})\n\t\t\tswitch {\n\t\t\tcase kerrors.IsNotFound(err):\n\t\t\t\treturn false, nil\n\t\t\tcase err == nil:\n\t\t\t\tspecReplicas := int32(1)\n\t\t\t\tif d.Spec.Replicas != nil {\n\t\t\t\t\tspecReplicas = *d.Spec.Replicas\n\t\t\t\t}\n\n\t\t\t\treturn specReplicas == d.Status.Replicas &&\n\t\t\t\t\tspecReplicas == d.Status.ReadyReplicas &&\n\t\t\t\t\tspecReplicas == d.Status.AvailableReplicas &&\n\t\t\t\t\tspecReplicas == d.Status.UpdatedReplicas &&\n\t\t\t\t\td.Generation == d.Status.ObservedGeneration, nil\n\t\t\tdefault:\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}, ctx.Done())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func WaitForWantedNodes(cfg cbgt.Cfg, wantedNodes []string,\n\tcancelCh <-chan struct{}, secs int, ignoreWaitTimeOut bool) (\n\t[]string, error) {\n\tvar nodeDefWantedUUIDs []string\n\tfor i := 0; i < secs; i++ {\n\t\tselect {\n\t\tcase <-cancelCh:\n\t\t\treturn nil, ErrCtlCanceled\n\t\tdefault:\n\t\t}\n\n\t\tnodeDefsWanted, _, err :=\n\t\t\tcbgt.CfgGetNodeDefs(cfg, cbgt.NODE_DEFS_WANTED)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tnodeDefWantedUUIDs = nil\n\t\tfor _, nodeDef := range nodeDefsWanted.NodeDefs {\n\t\t\tnodeDefWantedUUIDs = append(nodeDefWantedUUIDs, nodeDef.UUID)\n\t\t}\n\t\tif len(cbgt.StringsRemoveStrings(wantedNodes, nodeDefWantedUUIDs)) <= 0 {\n\t\t\treturn cbgt.StringsRemoveStrings(nodeDefWantedUUIDs, wantedNodes), nil\n\t\t}\n\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\tif ignoreWaitTimeOut {\n\t\tlog.Printf(\"ctl: WaitForWantedNodes ignoreWaitTimeOut\")\n\t\treturn cbgt.StringsRemoveStrings(nodeDefWantedUUIDs, wantedNodes), nil\n\t}\n\treturn nil, fmt.Errorf(\"ctl: WaitForWantedNodes\"+\n\t\t\" could not attain wantedNodes: %#v,\"+\n\t\t\" only reached nodeDefWantedUUIDs: %#v\",\n\t\twantedNodes, nodeDefWantedUUIDs)\n}", "func cassandraClusterRollingRestartDCTest(t *testing.T, f *framework.Framework, ctx *framework.TestCtx) {\n\tnamespace, err := ctx.GetWatchNamespace()\n\tif err != nil {\n\t\tt.Fatalf(\"Could not get namespace: %v\", err)\n\t}\n\n\tt.Log(\"Create the Cluster with 1 DC consisting of 1 rack of 1 node\")\n\n\tcc := mye2eutil.HelperInitCluster(t, f, ctx, \"cassandracluster-1DC.yaml\", namespace)\n\tt.Logf(\"Create CassandraCluster cassandracluster-1DC.yaml in namespace %s\", namespace)\n\n\t// use TestCtx's create helper to create the object and add a cleanup function for the new object\n\tif err := f.Client.Create(goctx.TODO(), cc, &framework.CleanupOptions{TestContext: ctx,\n\t\tTimeout: mye2eutil.CleanupTimeout,\n\t\tRetryInterval: mye2eutil.CleanupRetryInterval}); err != nil {\n\t\tt.Fatalf(\"Error Creating cassandracluster: %v\", err)\n\t}\n\n\tif err := mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc1-rack1\", 1,\n\t\tmye2eutil.RetryInterval, mye2eutil.Timeout); err != nil {\n\t\tt.Fatalf(\"WaitForStatefulset got an error: %v\", err)\n\t}\n\n\tif err := mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\",\n\t\tmye2eutil.RetryInterval, mye2eutil.Timeout); err != nil {\n\t\tt.Fatalf(\"WaitForStatusDone got an error: %v\", err)\n\t}\n\n\tt.Log(\"Download statefulset and store current revision\")\n\tstatefulset, err := f.KubeClient.AppsV1().StatefulSets(namespace).Get(goctx.TODO(),\n\t\t\"cassandra-e2e-dc1-rack1\", metav1.GetOptions{})\n\tif err != nil {\n\t\tt.Fatalf(\"Could not download statefulset: %v\", err)\n\t}\n\n\tstfsVersion := statefulset.Status.CurrentRevision\n\n\tt.Log(\"Download last version of CassandraCluster\")\n\tif err := f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\",\n\t\tNamespace: namespace}, cc); err != nil {\n\t\tt.Fatalf(\"Could not download last version of CassandraCluster: %v\", err)\n\t}\n\n\tt.Log(\"Trigger rolling restart of 1st DC by updating RollingRestart flag\")\n\n\tcc.Spec.Topology.DC[0].Rack[0].RollingRestart = true\n\n\tif err := f.Client.Update(goctx.TODO(), cc); err != nil {\n\t\tt.Fatalf(\"Could not update CassandraCluster: %v\", err)\n\t}\n\n\tif err := mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc1-rack1\", 1,\n\t\tmye2eutil.RetryInterval, mye2eutil.Timeout); err != nil {\n\t\tt.Fatalf(\"WaitForStatefulset got an error: %v\", err)\n\t}\n\n\tif err := mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\",\n\t\tmye2eutil.RetryInterval, mye2eutil.Timeout); err != nil {\n\t\tt.Fatalf(\"WaitForStatusDone got an error: %v\", err)\n\t}\n\n\tt.Log(\"Download statefulset and check current revision has been updated\")\n\tstatefulset, err = f.KubeClient.AppsV1().StatefulSets(namespace).Get(goctx.TODO(),\n\t\t\"cassandra-e2e-dc1-rack1\", metav1.GetOptions{})\n\tif err != nil {\n\t\tt.Fatalf(\"Could not download statefulset: %v\", err)\n\t}\n\n\tassert.NotEqual(t, stfsVersion, statefulset.Status.CurrentRevision)\n\n\tt.Logf(\"Current labels on statefulset : %v\", statefulset.Spec.Template.Labels)\n\n\t_, rollingRestartLabelExists := statefulset.Spec.Template.Labels[\"rolling-restart\"]\n\n\tt.Log(\"Assert that rolling-restart label has been added to statefulset\")\n\tassert.Equal(t, true, rollingRestartLabelExists)\n\n\tt.Log(\"Download last version of CassandraCluster and check RollingRestart flag has been cleaned out\")\n\n\t// Delete Topology in order to get it updated as a whole\n\tcc.Spec.Topology.DC = nil\n\n\tif err := f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\",\n\t\tNamespace: namespace}, cc); err != nil {\n\t\tt.Fatalf(\"Could not get CassandraCluster: %v\", err)\n\t}\n\n\tassert.Equal(t, false, cc.Spec.Topology.DC[0].Rack[0].RollingRestart)\n}", "func (c *Client) doWaitForStatus(eniID string, checkNum, checkInterval int, finalStatus string) error {\n\tfor i := 0; i < checkNum; i++ {\n\t\ttime.Sleep(time.Second * time.Duration(checkInterval))\n\t\tenis, err := c.queryENI(eniID, \"\", \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, eni := range enis {\n\t\t\tif *eni.NetworkInterfaceId == eniID {\n\t\t\t\tswitch *eni.State {\n\t\t\t\tcase ENI_STATUS_AVAILABLE:\n\t\t\t\t\tswitch finalStatus {\n\t\t\t\t\tcase ENI_STATUS_ATTACHED:\n\t\t\t\t\t\tif eni.Attachment != nil && eni.Attachment.InstanceId != nil {\n\t\t\t\t\t\t\tblog.Infof(\"eni %s is attached\", eniID)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblog.Infof(\"eni %s is not attached\", eniID)\n\t\t\t\t\tcase ENI_STATUS_DETACHED:\n\t\t\t\t\t\tif eni.Attachment == nil {\n\t\t\t\t\t\t\tblog.Infof(\"eni %s is detached\", eniID)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblog.Infof(\"eni %s is not detached\", eniID)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tblog.Infof(\"eni %s is %s now\", eniID, *eni.State)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase ENI_STATUS_PENDING, ENI_STATUS_ATTACHING, ENI_STATUS_DETACHING, ENI_STATUS_DELETING:\n\t\t\t\t\tblog.Infof(\"eni %s is %s\", eniID, *eni.State)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tblog.Errorf(\"timeout when wait for eni %s\", eniID)\n\treturn fmt.Errorf(\"timeout when wait for eni %s\", eniID)\n}" ]
[ "0.67166954", "0.6538773", "0.63380307", "0.6060883", "0.59197", "0.58800954", "0.5797496", "0.57853615", "0.5667254", "0.5638806", "0.55470073", "0.5496028", "0.54223436", "0.53780425", "0.5365897", "0.5323093", "0.531257", "0.5297731", "0.5264647", "0.5243112", "0.5234411", "0.52329737", "0.5190569", "0.51737976", "0.5144015", "0.51432973", "0.5127018", "0.51262957", "0.51257515", "0.5122304", "0.51106983", "0.5090236", "0.5076789", "0.5069465", "0.50233173", "0.5023079", "0.501304", "0.50108707", "0.49995363", "0.49907538", "0.49775904", "0.49704581", "0.49345723", "0.49238122", "0.49210507", "0.48825163", "0.48817804", "0.48638576", "0.48597008", "0.48441455", "0.48323083", "0.48282322", "0.48228025", "0.48221526", "0.48203245", "0.48100004", "0.480389", "0.47856343", "0.47785586", "0.47779053", "0.4756858", "0.47558862", "0.47432005", "0.474094", "0.4735022", "0.47203347", "0.47155368", "0.4708284", "0.46983895", "0.46951407", "0.46948498", "0.46944743", "0.46918064", "0.46869665", "0.46860653", "0.46852022", "0.46847296", "0.46806866", "0.46774364", "0.46561292", "0.46544445", "0.46514463", "0.4640565", "0.46380192", "0.46313044", "0.46272886", "0.46262628", "0.46173567", "0.4612599", "0.46043333", "0.45969072", "0.45961484", "0.45803806", "0.45787653", "0.4565336", "0.4562004", "0.4561452", "0.45532167", "0.45500863", "0.45483992" ]
0.83833635
0
DestroyWorkers destroys all MachineDeployment, MachineSet and Machine objects
func DestroyWorkers(s *state.State) error { if !s.Cluster.MachineController.Deploy { s.Logger.Info("Skipping deleting workers because machine-controller is disabled in configuration.") return nil } if s.DynamicClient == nil { return fail.NoKubeClient() } ctx := context.Background() // Annotate nodes with kubermatic.io/skip-eviction=true to skip eviction s.Logger.Info("Annotating nodes to skip eviction...") nodes := &corev1.NodeList{} if err := s.DynamicClient.List(ctx, nodes); err != nil { return fail.KubeClient(err, "listing Nodes") } for _, node := range nodes.Items { nodeKey := dynclient.ObjectKey{Name: node.Name} retErr := retry.RetryOnConflict(retry.DefaultRetry, func() error { n := corev1.Node{} if err := s.DynamicClient.Get(ctx, nodeKey, &n); err != nil { return fail.KubeClient(err, "getting %T %s", n, nodeKey) } if n.Annotations == nil { n.Annotations = map[string]string{} } n.Annotations["kubermatic.io/skip-eviction"] = "true" return fail.KubeClient(s.DynamicClient.Update(ctx, &n), "updating %T %s", n, nodeKey) }) if retErr != nil { return retErr } } // Delete all MachineDeployment objects s.Logger.Info("Deleting MachineDeployment objects...") mdList := &clusterv1alpha1.MachineDeploymentList{} if err := s.DynamicClient.List(ctx, mdList, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil { if !errorsutil.IsNotFound(err) { return fail.KubeClient(err, "listing %T", mdList) } } for i := range mdList.Items { if err := s.DynamicClient.Delete(ctx, &mdList.Items[i]); err != nil { md := mdList.Items[i] return fail.KubeClient(err, "deleting %T %s", md, dynclient.ObjectKeyFromObject(&md)) } } // Delete all MachineSet objects s.Logger.Info("Deleting MachineSet objects...") msList := &clusterv1alpha1.MachineSetList{} if err := s.DynamicClient.List(ctx, msList, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil { if !errorsutil.IsNotFound(err) { return fail.KubeClient(err, "getting %T", mdList) } } for i := range msList.Items { if err := s.DynamicClient.Delete(ctx, &msList.Items[i]); err != nil { if !errorsutil.IsNotFound(err) { ms := msList.Items[i] return fail.KubeClient(err, "deleting %T %s", ms, dynclient.ObjectKeyFromObject(&ms)) } } } // Delete all Machine objects s.Logger.Info("Deleting Machine objects...") mList := &clusterv1alpha1.MachineList{} if err := s.DynamicClient.List(ctx, mList, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil { if !errorsutil.IsNotFound(err) { return fail.KubeClient(err, "getting %T", mList) } } for i := range mList.Items { if err := s.DynamicClient.Delete(ctx, &mList.Items[i]); err != nil { if !errorsutil.IsNotFound(err) { ma := mList.Items[i] return fail.KubeClient(err, "deleting %T %s", ma, dynclient.ObjectKeyFromObject(&ma)) } } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bc *BaseCluster) Destroy() {\n\tfor _, m := range bc.Machines() {\n\t\tbc.numMachines--\n\t\tm.Destroy()\n\t}\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n l := list.New()\n for _, w := range mr.Workers {\n DPrintf(\"DoWork: shutdown %s\\n\", w.address)\n args := &ShutdownArgs{}\n var reply ShutdownReply;\n ok := call(w.address, \"Worker.Shutdown\", args, &reply)\n if ok == false {\n fmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n } else {\n l.PushBack(reply.Njobs)\n }\n }\n return l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n l := list.New()\n for _, w := range mr.Workers {\n DPrintf(\"DoWork: shutdown %s\\n\", w.address)\n args := &ShutdownArgs{}\n var reply ShutdownReply;\n ok := call(w.address, \"Worker.Shutdown\", args, &reply)\n if ok == false {\n fmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n } else {\n l.PushBack(reply.Njobs)\n }\n }\n return l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n l := list.New()\n for _, w := range mr.Workers {\n DPrintf(\"DoWork: shutdown %s\\n\", w.address)\n args := &ShutdownArgs{}\n var reply ShutdownReply;\n ok := call(w.address, \"Worker.Shutdown\", args, &reply)\n if ok == false {\n fmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n } else {\n l.PushBack(reply.Njobs)\n }\n }\n return l\n}", "func (w *worker) Terminate() {\n\tfor _, v := range w.allGateways {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.allMasters {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.allNodes {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.concernedGateways {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.concernedMasters {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.concernedNodes {\n\t\tv.Released()\n\t}\n\tif w.availableGateway != nil {\n\t\tw.availableGateway.Released()\n\t}\n\tif w.availableMaster != nil {\n\t\tw.availableMaster.Released()\n\t}\n\tif w.availableNode != nil {\n\t\tw.availableNode.Released()\n\t}\n}", "func KillWorkloads(clientset kubernetes.Interface) {\n\t// Look for namespace or default to default namespace\n\tnamespace := helpers.GetEnv(\"NAMESPACE\", \"default\")\n\t// Wait Group To handle the waiting for all deletes to complete\n\tvar wg sync.WaitGroup\n\twg.Add(6)\n\t// Delete all Deployments\n\tif helpers.CheckDeleteResourceAllowed(\"deployments\") {\n\t\tgo deleteDeployments(clientset, &namespace, &wg)\n\t}\n\t// Delete all Statefulsets\n\tif helpers.CheckDeleteResourceAllowed(\"statefulsets\") {\n\t\tgo deleteStatefulsets(clientset, &namespace, &wg)\n\t}\n\t// Delete Services\n\tif helpers.CheckDeleteResourceAllowed(\"services\") {\n\t\tgo deleteServices(clientset, &namespace, &wg)\n\t}\n\t// Delete All Secrets\n\tif helpers.CheckDeleteResourceAllowed(\"secrets\") {\n\t\tgo deleteSecrets(clientset, &namespace, &wg)\n\t}\n\t// Delete All Configmaps\n\tif helpers.CheckDeleteResourceAllowed(\"configmaps\") {\n\t\tgo deleteConfigMaps(clientset, &namespace, &wg)\n\t}\n\t// Delete All Daemonsets\n\tif helpers.CheckDeleteResourceAllowed(\"daemonsets\") {\n\t\tgo deleteDaemonSets(clientset, &namespace, &wg)\n\t}\n\t// wait for processes to finish\n\twg.Wait()\n}", "func KillWorkloads(clientset kubernetes.Interface) {\n\t// Look for namespace or default to default namespace\n\tnamespace := helpers.GetEnv(\"NAMESPACE\", \"default\")\n\t// Wait Group To handle the waiting for all deletes to complete\n\tvar wg sync.WaitGroup\n\twg.Add(5)\n\t// Delete all Deployments\n\tif helpers.CheckDeleteResourceAllowed(\"deployments\") {\n\t\tgo deleteDeployments(clientset, &namespace, &wg)\n\t}\n\t// Delete all Statefulsets\n\tif helpers.CheckDeleteResourceAllowed(\"statefulsets\") {\n\t\tgo deleteStatefulsets(clientset, &namespace, &wg)\n\t}\n\t// Delete Services\n\tif helpers.CheckDeleteResourceAllowed(\"services\") {\n\t\tgo deleteServices(clientset, &namespace, &wg)\n\t}\n\t// Delete All Secrets\n\tif helpers.CheckDeleteResourceAllowed(\"secrets\") {\n\t\tgo deleteSecrets(clientset, &namespace, &wg)\n\t}\n\t// Delete All Configmaps\n\tif helpers.CheckDeleteResourceAllowed(\"configmaps\") {\n\t\tgo deleteConfigMaps(clientset, &namespace, &wg)\n\t}\n\t// wait for processes to finish\n\twg.Wait()\n}", "func (d Driver) DestroyWorker(project, branch string) error {\n\tdPtr := &d\n\treturn dPtr.remove(context.Background(), d.containerID)\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.Address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.Address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.Address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (s *Server) stopWorkers() {\n\tfor k, w := range s.workers {\n\t\tw.stop()\n\n\t\t// fix nil exception\n\t\tdelete(s.workers, k)\n\t}\n}", "func (s *Server) StopWorkers() {\n\tfor _, v := range s.shardWorkers {\n\t\tclose(v.StopChan)\n\t}\n\n\ts.shardWorkers = nil\n}", "func (m *ManagerImpl) StopWorkers() {\n\tm.processor.StopWorkers()\n}", "func (_m *IProvider) KillAllWorkerProcesses() {\n\t_m.Called()\n}", "func (m *Manager) Delete() {\n\tm.machine.Infof(m.machine.Name(), \"Stopping manager\")\n\tm.cancel()\n\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tfor _, w := range m.watchers {\n\t\tw.Delete()\n\t}\n}", "func (s *Server) CleanupForDestroy() {\n\ts.CtxCancel()\n\ts.Events().Destroy()\n\ts.DestroyAllSinks()\n\ts.Websockets().CancelAll()\n\ts.powerLock.Destroy()\n}", "func (mr *MapReduce) KillWorkers() []int {\n\tl := make([]int, 0)\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false || reply.OK == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl = append(l, reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (manager *syncerManager) garbageCollectSyncer() {\n\tmanager.mu.Lock()\n\tdefer manager.mu.Unlock()\n\tfor key, syncer := range manager.syncerMap {\n\t\tif syncer.IsStopped() && !syncer.IsShuttingDown() {\n\t\t\tdelete(manager.syncerMap, key)\n\t\t}\n\t}\n}", "func (bq *InMemoryBuildQueue) TerminateWorkers(ctx context.Context, request *buildqueuestate.TerminateWorkersRequest) (*emptypb.Empty, error) {\n\tvar completionWakeups []chan struct{}\n\tbq.enter(bq.clock.Now())\n\tfor _, scq := range bq.sizeClassQueues {\n\t\tfor workerKey, w := range scq.workers {\n\t\t\tif workerMatchesPattern(workerKey.getWorkerID(), request.WorkerIdPattern) {\n\t\t\t\tw.terminating = true\n\t\t\t\tif t := w.currentTask; t != nil {\n\t\t\t\t\t// The task will be at the\n\t\t\t\t\t// EXECUTING stage, so it can\n\t\t\t\t\t// only transition to COMPLETED.\n\t\t\t\t\tcompletionWakeups = append(completionWakeups, t.stageChangeWakeup)\n\t\t\t\t} else if w.wakeup != nil {\n\t\t\t\t\t// Wake up the worker, so that\n\t\t\t\t\t// it's dequeued. This prevents\n\t\t\t\t\t// additional tasks to be\n\t\t\t\t\t// assigned to it.\n\t\t\t\t\tw.wakeUp(scq)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tbq.leave()\n\n\tfor _, completionWakeup := range completionWakeups {\n\t\tselect {\n\t\tcase <-completionWakeup:\n\t\t\t// Worker has become idle.\n\t\tcase <-ctx.Done():\n\t\t\t// Client has canceled the request.\n\t\t\treturn nil, util.StatusFromContext(ctx)\n\t\t}\n\t}\n\treturn &emptypb.Empty{}, nil\n}", "func (pm *Manager) cleanReservedPortsWorker() {\n\tfor {\n\t\ttime.Sleep(CleanReservedPortsInterval)\n\t\tpm.mu.Lock()\n\t\tfor name, ctx := range pm.reservedPorts {\n\t\t\tif ctx.Closed && time.Since(ctx.UpdateTime) > MaxPortReservedDuration {\n\t\t\t\tdelete(pm.reservedPorts, name)\n\t\t\t}\n\t\t}\n\t\tpm.mu.Unlock()\n\t}\n}", "func (m *manager) Shutdown() {\n\t// Cancel the context to stop any requests\n\tm.cancel()\n\n\t// Go through and shut everything down\n\tfor _, i := range m.instances {\n\t\ti.cleanup()\n\t}\n}", "func (d *OrderedDaemon) stopWorkers() {\n\td.lock.RLock()\n\tdefer d.lock.RUnlock()\n\n\t// stop all the workers\n\tif len(d.shutdownOrderWorker) > 0 {\n\t\t// initialize with the priority of the first worker\n\t\tprevPriority := d.workers[d.shutdownOrderWorker[0]].shutdownOrder\n\t\tfor _, name := range d.shutdownOrderWorker {\n\t\t\tworker := d.workers[name]\n\t\t\tif !worker.running.IsSet() {\n\t\t\t\t// the worker's shutdown channel will be automatically garbage collected\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// if the current worker has a lower priority...\n\t\t\tif worker.shutdownOrder < prevPriority {\n\t\t\t\t// wait for every worker in the previous shutdown priority to terminate\n\t\t\t\td.wgPerSameShutdownOrder[prevPriority].Wait()\n\t\t\t\tprevPriority = worker.shutdownOrder\n\t\t\t}\n\t\t\tif d.logger != nil {\n\t\t\t\td.logger.Debugf(\"Stopping Background Worker: %s ...\", name)\n\t\t\t}\n\t\t\tclose(worker.shutdownSignal)\n\t\t}\n\t\t// wait for the last priority to finish\n\t\td.wgPerSameShutdownOrder[prevPriority].Wait()\n\t}\n}", "func finalizer(w *Worker) {\n\tlog.Printf(\"Destroy worker %v\\n\", w.ID)\n}", "func (m *manager) Shutdown() {\n\t// Cancel the context to stop any requests\n\tm.cancel()\n\n\tm.instancesMu.RLock()\n\tdefer m.instancesMu.RUnlock()\n\n\t// Go through and shut everything down\n\tfor _, i := range m.instances {\n\t\ti.cleanup()\n\t}\n}", "func (pm partitionMap) cleanup() {\n\tfor ns, partitions := range pm {\n\t\tfor i := range partitions.Replicas {\n\t\t\tfor j := range partitions.Replicas[i] {\n\t\t\t\tpartitions.Replicas[i][j] = nil\n\t\t\t}\n\t\t\tpartitions.Replicas[i] = nil\n\t\t}\n\n\t\tpartitions.Replicas = nil\n\t\tpartitions.regimes = nil\n\n\t\tdelete(pm, ns)\n\t}\n}", "func (d *Deployer) Destroy(dep *Deployment, printServerLogs bool) {\n\tfor _, hsDep := range dep.HS {\n\t\tif printServerLogs {\n\t\t\tprintLogs(d.Docker, hsDep.ContainerID, hsDep.ContainerID)\n\t\t}\n\t\terr := d.Docker.ContainerKill(context.Background(), hsDep.ContainerID, \"KILL\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Destroy: Failed to destroy container %s : %s\\n\", hsDep.ContainerID, err)\n\t\t}\n\t\terr = d.Docker.ContainerRemove(context.Background(), hsDep.ContainerID, types.ContainerRemoveOptions{\n\t\t\tForce: true,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Destroy: Failed to remove container %s : %s\\n\", hsDep.ContainerID, err)\n\t\t}\n\t}\n}", "func (cr *Celery) GenerateWorkers() []*CeleryWorker {\n\tlabels := map[string]string{\n\t\t\"celery-app\": cr.Name,\n\t\t\"type\": \"worker\",\n\t}\n\tdefaultImage := cr.Spec.Image\n\tbrokerAddr := cr.Status.BrokerAddress\n\tworkers := make([]*CeleryWorker, 0)\n\tfor i, workerSpec := range cr.Spec.Workers {\n\t\tif workerSpec.Image == \"\" {\n\t\t\tworkerSpec.Image = defaultImage\n\t\t}\n\t\tworkerSpec.BrokerAddress = brokerAddr\n\t\tworker := &CeleryWorker{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: fmt.Sprintf(\"%s-worker-%d\", cr.GetName(), i+1),\n\t\t\t\tNamespace: cr.GetNamespace(),\n\t\t\t\tLabels: labels,\n\t\t\t},\n\t\t\tSpec: workerSpec,\n\t\t}\n\t\tworkers = append(workers, worker)\n\t}\n\treturn workers\n}", "func (m *Manager) Cleanup() error {\n\tclose(m.stop)\n\tfor _, clean := range m.c.Cleaners {\n\t\tif err := clean(m); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn m.env.Stop()\n}", "func (m *Manager) Stop() {\n\tm.serverMutex.Lock()\n\tdefer m.serverMutex.Unlock()\n\n\tm.server = nil\n\n\tm.dropAllNeighbors()\n\n\tm.messageWorkerPool.Stop()\n\tm.messageRequestWorkerPool.Stop()\n}", "func (set HwlocCPUSet) Destroy() {\n\tset.BitMap.Destroy()\n}", "func WaitDestroy(s *state.State) error {\n\ts.Logger.Info(\"Waiting for all machines to get deleted...\")\n\n\treturn wait.PollUntilContextTimeout(s.Context, 5*time.Second, 5*time.Minute, false, func(ctx context.Context) (bool, error) {\n\t\tlist := &clusterv1alpha1.MachineList{}\n\t\tif err := s.DynamicClient.List(ctx, list, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil {\n\t\t\treturn false, fail.KubeClient(err, \"getting %T\", list)\n\t\t}\n\t\tif len(list.Items) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t})\n}", "func (setup *SimpleTestSetup) TearDown() {\n\tsetup.harnessPool.DisposeAll()\n\tsetup.harnessWalletPool.DisposeAll()\n\t//setup.nodeGoBuilder.Dispose()\n\tsetup.WorkingDir.Dispose()\n}", "func (m *Machine) Delete() {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.manager.Delete()\n\n\tif m.backoffTimer != nil {\n\t\tm.backoffTimer.Stop()\n\t}\n\n\tif m.cancel != nil {\n\t\tm.Infof(\"runner\", \"Stopping\")\n\t\tm.cancel()\n\t}\n\n\tm.startTime = time.Time{}\n}", "func (cc *ClusterController) cleanup(c *cassandrav1alpha1.Cluster) error {\n\n\tfor _, r := range c.Spec.Datacenter.Racks {\n\t\tservices, err := cc.serviceLister.Services(c.Namespace).List(util.RackSelector(r, c))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error listing member services: %s\", err.Error())\n\t\t}\n\t\t// Get rack status. If it doesn't exist, the rack isn't yet created.\n\t\tstsName := util.StatefulSetNameForRack(r, c)\n\t\tsts, err := cc.statefulSetLister.StatefulSets(c.Namespace).Get(stsName)\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error getting statefulset %s: %s\", stsName, err.Error())\n\t\t}\n\t\tmemberCount := *sts.Spec.Replicas\n\t\tmemberServiceCount := int32(len(services))\n\t\t// If there are more services than members, some services need to be cleaned up\n\t\tif memberServiceCount > memberCount {\n\t\t\tmaxIndex := memberCount - 1\n\t\t\tfor _, svc := range services {\n\t\t\t\tsvcIndex, err := util.IndexFromName(svc.Name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Errorf(\"Unexpected error while parsing index from name %s : %s\", svc.Name, err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif svcIndex > maxIndex {\n\t\t\t\t\terr := cc.cleanupMemberResources(svc.Name, r, c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"error cleaning up member resources: %s\", err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlogger.Infof(\"%s/%s - Successfully cleaned up cluster.\", c.Namespace, c.Name)\n\treturn nil\n}", "func (this *Healthcheck) UpdateWorkers(targets []core.Target) {\n\n\tresult := []*Worker{}\n\n\t// Keep or add needed workers\n\tfor _, t := range targets {\n\t\tvar keep *Worker\n\t\tfor i := range this.workers {\n\t\t\tc := this.workers[i]\n\t\t\tif t.EqualTo(c.target) {\n\t\t\t\tkeep = c\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif keep == nil {\n\t\t\tkeep = &Worker{\n\t\t\t\ttarget: t,\n\t\t\t\tstop: make(chan bool),\n\t\t\t\tout: this.Out,\n\t\t\t\tcfg: this.cfg,\n\t\t\t\tcheck: this.check,\n\t\t\t\tLastResult: CheckResult{\n\t\t\t\t\tLive: true,\n\t\t\t\t},\n\t\t\t}\n\t\t\tkeep.Start()\n\t\t}\n\t\tresult = append(result, keep)\n\t}\n\n\t// Stop needed workers\n\tfor i := range this.workers {\n\t\tc := this.workers[i]\n\t\tremove := true\n\t\tfor _, t := range targets {\n\t\t\tif c.target.EqualTo(t) {\n\t\t\t\tremove = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif remove {\n\t\t\tc.Stop()\n\t\t}\n\t}\n\n\tthis.workers = result\n\n}", "func cleanup() {\n\tfor _, cmd := range runningApps {\n\t\tcmd.Process.Kill()\n\t}\n}", "func removeWorkers(addrs []dist.Address) error {\n\tdirLock.Lock()\n\tdefer dirLock.Unlock()\n\n\t// cs 101 here we come\n\tres := make([]*dist.Address, 0)\n\tfor i := range directory {\n\t\trm := false\n\t\tfor k := range addrs {\n\t\t\tif directory[i].Equal(addrs[k]) {\n\t\t\t\trm = true\n\t\t\t}\n\t\t}\n\t\tif !rm {\n\t\t\tif directory[i].Valid() {\n\t\t\t\tres = append(res, directory[i])\n\t\t\t}\n\t\t}\n\t}\n\tdirectory = res\n\treturn nil\n}", "func (tr *TestRunner) CleanUp() error {\n\tfor imsi := range tr.imsis {\n\t\terr := deleteSubscribersFromHSS(imsi)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor _, instance := range tr.activePCRFs {\n\t\terr := clearSubscribersFromPCRFPerInstance(instance)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor _, instance := range tr.activeOCSs {\n\t\terr := clearSubscribersFromOCSPerInstance(instance)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (a Apps) Destroy() error {\n\tfor _, app := range a {\n\t\tcmd, err := app.Destroy(false)\n\t\tif err != nil {\n\t\t\tapp.log.WithFields(logrus.Fields{\n\t\t\t\t\"app\": app.Name,\n\t\t\t\t\"cmd\": cmd,\n\t\t\t\t\"error\": err,\n\t\t\t}).Fatal(\"Failed running destroy\")\n\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (am *Manager) Clean() {\n\tfor name, m := range am.Materials {\n\t\tLogger.Printf(\"Manager: deleting Material '%s'\\n\", name)\n\t\tm.Clean()\n\t\tdelete(am.Materials, name)\n\t}\n\tfor name, m := range am.Meshes {\n\t\tLogger.Printf(\"Manager: deleting Mesh '%s'\\n\", name)\n\t\tm.Clean()\n\t\tdelete(am.Meshes, name)\n\t}\n\tfor set, prog := range am.Programs {\n\t\tLogger.Printf(\"Manager: deleting Program '%v'\\n\", set)\n\t\tgl.DeleteProgram(prog)\n\t\tdelete(am.Programs, set)\n\t}\n\tfor name, shader := range am.Shaders {\n\t\tLogger.Printf(\"Manager: deleting Shader '%s'\\n\", name)\n\t\tgl.DeleteShader(shader)\n\t\tdelete(am.Shaders, name)\n\t}\n\tfor name, tex := range am.Textures {\n\t\tLogger.Printf(\"Manager: deleting Texture '%s'\\n\", name)\n\t\ttex.Clean()\n\t\tdelete(am.Textures, name)\n\t}\n}", "func Cleanup(monitors []models.Application) {\n\tapps := database.Applications()\n\tfor i := range apps {\n\t\tapp := apps[i]\n\n\t\tif contains(app.Name, monitors) == false {\n\t\t\tdatabase.DeleteApplication(app.ID)\n\t\t\tdatabase.DeleteChecks(app.ID)\n\t\t}\n\t}\n}", "func (c *csiManager) Shutdown() {\n\t// Shut down the run loop\n\tc.shutdownCtxCancelFn()\n\n\t// Wait for plugin manager shutdown to complete so that we\n\t// don't try to shutdown instance managers while runLoop is\n\t// doing a resync\n\t<-c.shutdownCh\n\n\t// Shutdown all the instance managers in parallel\n\tvar wg sync.WaitGroup\n\tfor _, pluginMap := range c.instances {\n\t\tfor _, mgr := range pluginMap {\n\t\t\twg.Add(1)\n\t\t\tgo func(mgr *instanceManager) {\n\t\t\t\tmgr.shutdown()\n\t\t\t\twg.Done()\n\t\t\t}(mgr)\n\t\t}\n\t}\n\twg.Wait()\n}", "func DestroyResources(resources []DestroyableResource, dryRun bool, parallel int) int {\n\tnumOfResourcesToDelete := len(resources)\n\tnumOfDeletedResources := 0\n\n\tvar retryableResourceErrors []RetryDestroyError\n\n\tjobQueue := make(chan DestroyableResource, numOfResourcesToDelete)\n\n\tworkerResults := make(chan workerResult, numOfResourcesToDelete)\n\n\tfor workerID := 1; workerID <= parallel; workerID++ {\n\t\tgo worker(workerID, dryRun, jobQueue, workerResults)\n\t}\n\n\tlog.Debug(\"start distributing resources to workers for this run\")\n\n\tfor _, r := range resources {\n\t\tjobQueue <- r\n\t}\n\n\tclose(jobQueue)\n\n\tfor i := 1; i <= numOfResourcesToDelete; i++ {\n\t\tresult := <-workerResults\n\n\t\tif result.resourceHasBeenDeleted {\n\t\t\tnumOfDeletedResources++\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif result.Err != nil {\n\t\t\tretryableResourceErrors = append(retryableResourceErrors, *result.Err)\n\t\t}\n\t}\n\n\tif len(retryableResourceErrors) > 0 && numOfDeletedResources > 0 {\n\t\tvar resourcesToRetry []DestroyableResource\n\t\tfor _, retryErr := range retryableResourceErrors {\n\t\t\tresourcesToRetry = append(resourcesToRetry, retryErr.Resource)\n\t\t}\n\n\t\tnumOfDeletedResources += DestroyResources(resourcesToRetry, dryRun, parallel)\n\t}\n\n\tif len(retryableResourceErrors) > 0 && numOfDeletedResources == 0 {\n\t\tinternal.LogTitle(fmt.Sprintf(\"failed to delete the following resources (retries exceeded): %d\",\n\t\t\tlen(retryableResourceErrors)))\n\n\t\tfor _, err := range retryableResourceErrors {\n\t\t\tlog.WithError(err).WithField(\"id\", err.Resource.ID()).Warn(internal.Pad(err.Resource.Type()))\n\t\t}\n\t}\n\n\treturn numOfDeletedResources\n}", "func (dm *Manager) Manage(\n\tctx context.Context,\n\tworker func(context.Context, *Container) error,\n\tlabels ...string,\n) error {\n\n\ttype workerHandle struct {\n\t\tdone chan struct{}\n\t\tcancel context.CancelFunc\n\t}\n\n\t// Manage workers.\n\tmanagers := make(map[string]workerHandle)\n\n\tdefer func() {\n\t\t// cancel the remaining managers\n\t\tfor _, m := range managers {\n\t\t\tm.cancel()\n\t\t}\n\t\t// wait for the running managers to exit\n\t\tfor _, m := range managers {\n\t\t\t<-m.done\n\t\t}\n\t}()\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tstop := func(container string) {\n\t\tif m, ok := managers[container]; ok {\n\t\t\tm.cancel()\n\t\t\tdelete(managers, container)\n\n\t\t\ttimeout := time.NewTimer(workerShutdownTimeout)\n\t\t\tdefer timeout.Stop()\n\n\t\t\tticker := time.NewTicker(workerShutdownTick)\n\t\t\tdefer ticker.Stop()\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-m.done:\n\t\t\t\t\treturn\n\t\t\t\tcase <-timeout.C:\n\t\t\t\t\tdm.S().Panicw(\"timed out waiting for container worker to stop\", \"container\", container)\n\t\t\t\t\treturn\n\t\t\t\tcase <-ticker.C:\n\t\t\t\t\tdm.S().Errorw(\"waiting for container worker to stop\", \"container\", container)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tstart := func(container string) {\n\t\tif _, ok := managers[container]; ok {\n\t\t\treturn\n\t\t}\n\n\t\tcctx, cancel := context.WithCancel(ctx)\n\t\tdone := make(chan struct{})\n\t\tmanagers[container] = workerHandle{\n\t\t\tdone: done,\n\t\t\tcancel: cancel,\n\t\t}\n\t\tgo func() {\n\t\t\tdefer close(done)\n\t\t\thandle := dm.NewHandle(container)\n\t\t\terr := worker(cctx, handle)\n\t\t\tif err != nil {\n\t\t\t\thandle.S().Errorf(\"sidecar worker failed: %s\", err)\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Manage existing containers.\n\tnow := time.Now()\n\n\tlistFilter := filters.NewArgs()\n\tfor _, l := range labels {\n\t\tlistFilter.Add(\"label\", l)\n\t}\n\tnodes, err := dm.Client.ContainerList(ctx, types.ContainerListOptions{\n\t\tQuiet: true,\n\t\tLimit: -1,\n\t\tFilters: listFilter,\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, n := range nodes {\n\t\tstart(n.ID)\n\t}\n\n\teventFilter := listFilter.Clone()\n\teventFilter.Add(\"type\", \"container\")\n\teventFilter.Add(\"event\", \"start\")\n\teventFilter.Add(\"event\", \"stop\")\n\n\t// Manage new containers.\n\teventCh, errs := dm.Client.Events(ctx, types.EventsOptions{\n\t\tFilters: eventFilter,\n\t\tSince: now.Format(time.RFC3339Nano),\n\t})\n\n\tfor {\n\t\tselect {\n\t\tcase event := <-eventCh:\n\t\t\tswitch event.Status {\n\t\t\tcase \"start\":\n\t\t\t\tstart(event.ID)\n\t\t\tcase \"stop\":\n\t\t\t\tstop(event.ID)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"unexpected event: type=%s, status=%s\", event.Type, event.Status)\n\t\t\t}\n\t\tcase err := <-errs:\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (b *Builder) Shutdown() []error {\n\terrors := []error{}\n\tfor entry := b.localInstances.Back(); entry != nil; entry = entry.Prev() {\n\t\tif info, ok := (entry.Value).(*ProcessorInfo); !ok {\n\t\t\terrors = append(errors, fmt.Errorf(\"unexpected processor info entry in instances map\"))\n\t\t} else if err := info.instance.Shutdown(); err != nil {\n\t\t\terrors = append(errors, err)\n\t\t}\n\t}\n\treturn errors\n}", "func (e *EventBus) Destroy() {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\n\t// Stop every pool that exists for a given callback topic.\n\tfor _, cp := range e.pools {\n\t\tcp.pool.Stop()\n\t}\n\n\te.pools = make(map[string]*CallbackPool)\n}", "func (e *Engine) shutdownVservers() {\n\tfor _, v := range e.vservers {\n\t\tv.stop()\n\t}\n\tfor name, v := range e.vservers {\n\t\t<-v.stopped\n\t\tdelete(e.vservers, name)\n\t}\n\te.vserverLock.Lock()\n\te.vserverSnapshots = make(map[string]*seesaw.Vserver)\n\te.vserverLock.Unlock()\n}", "func cleanUpNodes(provisioner provision.Provisioner) {\n\n\tfor _, machine := range provisioner.GetMachinesAll() {\n\t\tnodeName := machine.Name\n\t\texistNode := false\n\t\tfor _, node := range provisioner.Cluster.Nodes {\n\t\t\tif node.Name == nodeName {\n\t\t\t\tnode.Credential = \"\"\n\t\t\t\tnode.PublicIP = \"\"\n\t\t\t\tnode.PrivateIP = \"\"\n\t\t\t\texistNode = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif existNode {\n\t\t\tif err := provisioner.DrainAndDeleteNode(nodeName); err != nil {\n\t\t\t\tlogger.Warnf(\"[%s.%s] %s\", provisioner.Cluster.Namespace, provisioner.Cluster.Name, err.Error())\n\t\t\t}\n\t\t}\n\t}\n\tif err := provisioner.Cluster.PutStore(); err != nil {\n\t\tlogger.Warnf(\"[%s.%s] Failed to update a cluster-entity. (cause='%v')\", provisioner.Cluster.Namespace, provisioner.Cluster.Name, err)\n\t}\n\tlogger.Infof(\"[%s.%s] Garbage data has been cleaned.\", provisioner.Cluster.Namespace, provisioner.Cluster.Name)\n}", "func (jj *Juju) Destroy(user, service string) (*simplejson.Json, error) {\n id := jj.id(user, service)\n report := JSON(fmt.Sprintf(`{\"time\": \"%s\"}`, time.Now()))\n log.Infof(\"destroy juju service: %s\\n\", id)\n\n //Note For now this is massive and basic destruction\n unitArgs := []string{\"destroy-unit\", id + \"/0\", \"--show-log\"}\n serviceArgs := []string{\"destroy-service\", id, \"--show-log\"}\n\n cmd := exec.Command(\"juju\", \"status\", id, \"--format\", \"json\")\n output, err := cmd.CombinedOutput()\n if err != nil { return EmptyJSON(), err }\n status, err := simplejson.NewJson(output)\n machineID, err := status.GetPath(\"services\", id, \"units\", id+\"/0\", \"machine\").String()\n if err != nil { return EmptyJSON(), err }\n machineArgs := []string{\"destroy-machine\", machineID, \"--show-log\"}\n\n client, err := goresque.Dial(redisURL)\n if err != nil { return EmptyJSON(), err }\n log.Infof(\"enqueue destroy-unit\")\n client.Enqueue(workerClass, \"fork\", jj.Path, unitArgs)\n time.Sleep(5 * time.Second)\n log.Infof(\"enqueue destroy-service\")\n client.Enqueue(workerClass, \"fork\", jj.Path, serviceArgs)\n time.Sleep(5 * time.Second)\n log.Infof(\"enqueue destroy-machine\")\n client.Enqueue(workerClass, \"fork\", jj.Path, machineArgs)\n\n report.Set(\"provider\", \"juju\")\n report.Set(\"unit destroyed\", id + \"/0\")\n report.Set(\"service destroyed\", id)\n report.Set(\"machine destroyed\", machineID)\n report.Set(\"unit arguments\", unitArgs)\n report.Set(\"service arguments\", serviceArgs)\n report.Set(\"machine arguments\", machineArgs)\n return report, nil\n}", "func Clean(c Config) {\n\n\tSetup(&c)\n\tContainers, _ := model.DockerContainerList()\n\n\tfor _, Container := range Containers {\n\t\ttarget := false\n\t\tif l := Container.Labels[\"pygmy.enable\"]; l == \"true\" || l == \"1\" {\n\t\t\ttarget = true\n\t\t}\n\t\tif l := Container.Labels[\"pygmy\"]; l == \"pygmy\" {\n\t\t\ttarget = true\n\t\t}\n\n\t\tif target {\n\t\t\terr := model.DockerKill(Container.ID)\n\t\t\tif err == nil {\n\t\t\t\tfmt.Printf(\"Successfully killed %v.\\n\", Container.Names[0])\n\t\t\t}\n\n\t\t\terr = model.DockerRemove(Container.ID)\n\t\t\tif err == nil {\n\t\t\t\tfmt.Printf(\"Successfully removed %v.\\n\", Container.Names[0])\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, network := range c.Networks {\n\t\tmodel.DockerNetworkRemove(&network)\n\t\tif s, _ := model.DockerNetworkStatus(&network); s {\n\t\t\tfmt.Printf(\"Successfully removed network %v\\n\", network.Name)\n\t\t} else {\n\t\t\tfmt.Printf(\"Network %v was not removed\\n\", network.Name)\n\t\t}\n\t}\n\n\tfor _, resolver := range c.Resolvers {\n\t\tresolver.Clean()\n\t}\n}", "func (s *Reconciler) Delete(ctx context.Context) error {\n\tvmSpec := &virtualmachines.Spec{\n\t\tName: s.scope.Machine.Name,\n\t}\n\n\t// Getting a vm object does not work here so let's assume\n\t// an instance is really being deleted\n\tif s.scope.Machine.Annotations == nil {\n\t\ts.scope.Machine.Annotations = make(map[string]string)\n\t}\n\ts.scope.Machine.Annotations[MachineInstanceStateAnnotationName] = string(machinev1.VMStateDeleting)\n\tvmStateDeleting := machinev1.VMStateDeleting\n\ts.scope.MachineStatus.VMState = &vmStateDeleting\n\n\terr := s.virtualMachinesSvc.Delete(ctx, vmSpec)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to delete machine: %w\", err)\n\t}\n\n\tosDiskSpec := &disks.Spec{\n\t\tName: azure.GenerateOSDiskName(s.scope.Machine.Name),\n\t}\n\terr = s.disksSvc.Delete(ctx, osDiskSpec)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\tName: s.scope.Machine.Name,\n\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\tReason: err.Error(),\n\t\t})\n\t\treturn fmt.Errorf(\"failed to delete OS disk: %w\", err)\n\t}\n\n\tif s.scope.MachineConfig.Vnet == \"\" {\n\t\treturn fmt.Errorf(\"MachineConfig vnet is missing on machine %s\", s.scope.Machine.Name)\n\t}\n\n\tnetworkInterfaceSpec := &networkinterfaces.Spec{\n\t\tName: azure.GenerateNetworkInterfaceName(s.scope.Machine.Name),\n\t\tVnetName: s.scope.MachineConfig.Vnet,\n\t}\n\n\terr = s.networkInterfacesSvc.Delete(ctx, networkInterfaceSpec)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\tName: s.scope.Machine.Name,\n\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\tReason: err.Error(),\n\t\t})\n\t\treturn fmt.Errorf(\"Unable to delete network interface: %w\", err)\n\t}\n\n\tif s.scope.MachineConfig.PublicIP {\n\t\tpublicIPName, err := azure.GenerateMachinePublicIPName(s.scope.MachineConfig.Name, s.scope.Machine.Name)\n\t\tif err != nil {\n\t\t\t// Only when the generated name is longer than allowed by the Azure portal\n\t\t\t// That can happen only when\n\t\t\t// - machine name is changed (can't happen without creating a new CR)\n\t\t\t// - cluster name is changed (could happen but then we will get different name anyway)\n\t\t\t// - machine CR was created with too long public ip name (in which case no instance was created)\n\t\t\tklog.Info(\"Generated public IP name was too long, skipping deletion of the resource\")\n\t\t\treturn nil\n\t\t}\n\n\t\terr = s.publicIPSvc.Delete(ctx, &publicips.Spec{\n\t\t\tName: publicIPName,\n\t\t})\n\t\tif err != nil {\n\t\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\t\tName: s.scope.Machine.Name,\n\t\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\t\tReason: err.Error(),\n\t\t\t})\n\t\t\treturn fmt.Errorf(\"unable to delete Public IP: %w\", err)\n\t\t}\n\t}\n\n\t// Delete the availability set with the given name if no virtual machines are attached to it.\n\tif err := s.availabilitySetsSvc.Delete(ctx, &availabilitysets.Spec{\n\t\tName: s.getAvailibilitySetName(),\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"failed to delete availability set: %w\", err)\n\t}\n\n\treturn nil\n}", "func tearDownVMs(t *testing.T, images []string, vmNum int, isSyncOffload bool) {\n\tfor i := 0; i < vmNum; i++ {\n\t\tlog.Infof(\"Shutting down VM %d, images: %s\", i, images[i%len(images)])\n\t\tvmIDString := strconv.Itoa(i)\n\t\tmessage, err := funcPool.RemoveInstance(vmIDString, images[i%len(images)], isSyncOffload)\n\t\trequire.NoError(t, err, \"Function returned error, \"+message)\n\t}\n}", "func (c *swimCluster) Destroy() {\n\tfor _, node := range c.nodes {\n\t\tnode.Destroy()\n\t}\n\tfor _, ch := range c.channels {\n\t\tch.Close()\n\t}\n}", "func (d *Dispatcher) StopAllWorkers() {\n\tfor _ = range d.workers {\n\t\td.queue <- nil\n\t}\n}", "func (s *JobApiTestSuite) cleanUp() {\n\ttest.DeleteAllRuns(s.runClient, s.resourceNamespace, s.T())\n\ttest.DeleteAllJobs(s.jobClient, s.resourceNamespace, s.T())\n\ttest.DeleteAllPipelines(s.pipelineClient, s.T())\n\ttest.DeleteAllExperiments(s.experimentClient, s.resourceNamespace, s.T())\n}", "func (n *Network) Cleanup() {\n\tdefer func() {\n\t\tlock.Unlock()\n\t\tn.T.Log(\"released test network lock\")\n\t}()\n\n\tn.T.Log(\"cleaning up test network...\")\n\n\tfor _, v := range n.Validators {\n\t\tif v.tmNode != nil && v.tmNode.IsRunning() {\n\t\t\t_ = v.tmNode.Stop()\n\t\t}\n\n\t\tif v.api != nil {\n\t\t\t_ = v.api.Close()\n\t\t}\n\n\t\tif v.grpc != nil {\n\t\t\tv.grpc.Stop()\n\t\t\tif v.grpcWeb != nil {\n\t\t\t\t_ = v.grpcWeb.Close()\n\t\t\t}\n\t\t}\n\t}\n\n\tif n.Config.CleanupDir {\n\t\t_ = os.RemoveAll(n.BaseDir)\n\t}\n\n\tn.T.Log(\"finished cleaning up test network\")\n}", "func (s *Server) RunWorkers() {\n\n\ts.shardWorkers = make([]*shardWorker, len(s.readyShards))\n\tfor i := 0; i < len(s.shardWorkers); i++ {\n\t\ts.shardWorkers[i] = &shardWorker{\n\t\t\tGCCHan: make(chan *GuildCreateEvt),\n\t\t\tStopChan: make(chan bool),\n\t\t\tserver: s,\n\t\t}\n\t\tgo s.shardWorkers[i].chunkQueueHandler()\n\t}\n\n\tgo s.eventQueuePuller()\n}", "func (lw *Manager) CleanUp(w *Waiter) {\n\tlw.mu.Lock()\n\tq := lw.waitingQueues[w.startTS]\n\tlw.mu.Unlock()\n\tif q != nil {\n\t\tq.removeWaiter(w)\n\t}\n}", "func (wq *WorkQueue) Clean() (workunits []*Workunit) {\n\tworkunt_list, err := wq.all.GetWorkunits()\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, work := range workunt_list {\n\t\tid := work.Workunit_Unique_Identifier\n\t\tif work == nil || work.Info == nil {\n\t\t\tworkunits = append(workunits, work)\n\t\t\twq.Queue.Delete(id)\n\t\t\twq.Checkout.Delete(id)\n\t\t\twq.Suspend.Delete(id)\n\t\t\twq.all.Delete(id)\n\t\t\tid_str, _ := id.String()\n\t\t\tlogger.Error(\"error: in WorkQueue workunit %s is nil, deleted from queue\", id_str)\n\t\t}\n\t}\n\treturn\n}", "func (am *AssetManager) Clean() {\n\tfor name, model := range am.Models {\n\t\tmodel.Delete()\n\t\tdelete(am.Models, name)\n\t}\n\tfor name, tex := range am.Textures {\n\t\ttex.Delete()\n\t\tdelete(am.Textures, name)\n\t}\n\tfor name, prog := range am.Programs {\n\t\tprog.Delete()\n\t\tdelete(am.Programs, name)\n\t}\n}", "func (f *TestFramework) DestroyMachineSet() error {\n\tlog.Print(\"Destroying MachineSets\")\n\tif f.machineSet == nil {\n\t\tlog.Print(\"unable to find MachineSet to be deleted, was skip VM setup option selected ?\")\n\t\tlog.Print(\"MachineSets/Machines needs to be deleted manually \\nNot deleting MachineSets...\")\n\t\treturn nil\n\t}\n\terr := f.machineClient.MachineSets(\"openshift-machine-api\").Delete(context.TODO(), f.machineSet.Name, metav1.DeleteOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to delete MachineSet %v\", err)\n\t}\n\tlog.Print(\"MachineSets Destroyed\")\n\treturn nil\n}", "func (p *PodmanTestIntegration) Cleanup() {\n\tp.StopVarlink()\n\t// TODO\n\t// Stop all containers\n\t// Rm all containers\n\n\tif err := os.RemoveAll(p.TempDir); err != nil {\n\t\tfmt.Printf(\"%q\\n\", err)\n\t}\n\n\t// Clean up the registries configuration file ENV variable set in Create\n\tresetRegistriesConfigEnv()\n}", "func cleanup() {\n\tserver.Applications = []*types.ApplicationMetadata{}\n}", "func (m *ParallelMaster) Shutdown() {\n\tatomic.StoreInt32(&m.active, 0)\n\n\tfor i := uint(0); i < uint(m.totalWorkers); i++ {\n\t\tworker := <-m.freeWorkers\n\t\tcallWorker(worker, \"Shutdown\", new(interface{}), new(interface{}))\n\t}\n\n\tm.rpcListener.Close()\n\tclose(m.freeWorkers)\n}", "func (r *RealRunner) Clean() error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tfor pid, p := range r.processes {\n\t\tif err := p.Kill(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdelete(r.processes, pid)\n\t}\n\treturn nil\n}", "func (dm *DaemonManager) Run(workers int, stopCh <-chan struct{}) {\n\tgo dm.dcController.Run(stopCh)\n\tgo dm.podController.Run(stopCh)\n\tgo dm.nodeController.Run(stopCh)\n\tfor i := 0; i < workers; i++ {\n\t\tgo util.Until(dm.worker, time.Second, stopCh)\n\t}\n\t<-stopCh\n\tglog.Infof(\"Shutting down Daemon Controller Manager\")\n\tdm.queue.ShutDown()\n}", "func Shutdown() {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tfor _, v := range instances {\n\t\tv.Shutdown()\n\t}\n}", "func cleanUp() {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tsignal.Notify(c, syscall.SIGTERM)\n\tsignal.Notify(c, syscall.SIGKILL)\n\tgo func() {\n\t\t<-c\n\t\t_ = pool.Close()\n\t\tos.Exit(0)\n\t}()\n}", "func (r *ContainerizedWorkloadReconciler) cleanupResources(ctx context.Context,\n\tworkload *oamv1alpha2.ContainerizedWorkload, deployUID, serviceUID *types.UID) error {\n\tlog := r.Log.WithValues(\"gc deployment\", workload.Name)\n\tvar deploy appsv1.Deployment\n\tvar service corev1.Service\n\tfor _, res := range workload.Status.Resources {\n\t\tuid := res.UID\n\t\tif res.Kind == KindDeployment {\n\t\t\tif uid != *deployUID {\n\t\t\t\tlog.Info(\"Found an orphaned deployment\", \"deployment UID\", *deployUID, \"orphaned UID\", uid)\n\t\t\t\tdn := client.ObjectKey{Name: res.Name, Namespace: workload.Namespace}\n\t\t\t\tif err := r.Get(ctx, dn, &deploy); err != nil {\n\t\t\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := r.Delete(ctx, &deploy); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlog.Info(\"Removed an orphaned deployment\", \"deployment UID\", *deployUID, \"orphaned UID\", uid)\n\t\t\t}\n\t\t} else if res.Kind == KindService {\n\t\t\tif uid != *serviceUID {\n\t\t\t\tlog.Info(\"Found an orphaned service\", \"orphaned UID\", uid)\n\t\t\t\tsn := client.ObjectKey{Name: res.Name, Namespace: workload.Namespace}\n\t\t\t\tif err := r.Get(ctx, sn, &service); err != nil {\n\t\t\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := r.Delete(ctx, &service); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlog.Info(\"Removed an orphaned service\", \"orphaned UID\", uid)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func ValidateWorkers(workers []core.Worker, infra *api.InfrastructureConfig, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor i, worker := range workers {\n\t\tpath := fldPath.Index(i)\n\n\t\tif worker.Volume == nil {\n\t\t\tallErrs = append(allErrs, field.Required(path.Child(\"volume\"), \"must not be nil\"))\n\t\t} else {\n\t\t\tallErrs = append(allErrs, validateVolume(worker.Volume, path.Child(\"volume\"))...)\n\t\t}\n\n\t\tif length := len(worker.DataVolumes); length > maxDataVolumeCount {\n\t\t\tallErrs = append(allErrs, field.TooMany(path.Child(\"dataVolumes\"), length, maxDataVolumeCount))\n\t\t}\n\t\tfor j, volume := range worker.DataVolumes {\n\t\t\tdataVolPath := path.Child(\"dataVolumes\").Index(j)\n\t\t\tallErrs = append(allErrs, validateDataVolume(&volume, dataVolPath)...)\n\t\t}\n\n\t\t// Zones validation\n\t\tif infra.Zoned && len(worker.Zones) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(path.Child(\"zones\"), \"at least one zone must be configured for zoned clusters\"))\n\t\t\tcontinue\n\t\t}\n\n\t\tif !infra.Zoned && len(worker.Zones) > 0 {\n\t\t\tallErrs = append(allErrs, field.Required(path.Child(\"zones\"), \"zones must not be specified for non zoned clusters\"))\n\t\t\tcontinue\n\t\t}\n\n\t\tzones := sets.New[string]()\n\t\tfor j, zone := range worker.Zones {\n\t\t\tif zones.Has(zone) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"zones\").Index(j), zone, \"must only be specified once per worker group\"))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tzones.Insert(zone)\n\t\t}\n\n\t\tif !helper.IsUsingSingleSubnetLayout(infra) {\n\t\t\tinfraZones := sets.Set[string]{}\n\t\t\tfor _, zone := range infra.Networks.Zones {\n\t\t\t\tinfraZones.Insert(helper.InfrastructureZoneToString(zone.Name))\n\t\t\t}\n\n\t\t\tfor zoneIndex, workerZone := range worker.Zones {\n\t\t\t\tif !infraZones.Has(workerZone) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"zones\").Index(zoneIndex), workerZone, \"zone configuration must be specified in \\\"infrastructureConfig.networks.zones\\\"\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}", "func (c *controller) Run(workers int, stopCh <-chan struct{}) {\n\tdefer runtimeutil.HandleCrash()\n\n\tglog.Info(\"Starting service-catalog controller\")\n\n\tvar waitGroup sync.WaitGroup\n\n\tfor i := 0; i < workers; i++ {\n\t\tcreateWorker(c.clusterServiceBrokerQueue, \"ClusterServiceBroker\", maxRetries, true, c.reconcileClusterServiceBrokerKey, stopCh, &waitGroup)\n\t\tcreateWorker(c.clusterServiceClassQueue, \"ClusterServiceClass\", maxRetries, true, c.reconcileClusterServiceClassKey, stopCh, &waitGroup)\n\t\tcreateWorker(c.clusterServicePlanQueue, \"ClusterServicePlan\", maxRetries, true, c.reconcileClusterServicePlanKey, stopCh, &waitGroup)\n\t\tcreateWorker(c.instanceQueue, \"ServiceInstance\", maxRetries, true, c.reconcileServiceInstanceKey, stopCh, &waitGroup)\n\t\tcreateWorker(c.bindingQueue, \"ServiceBinding\", maxRetries, true, c.reconcileServiceBindingKey, stopCh, &waitGroup)\n\t\tcreateWorker(c.instancePollingQueue, \"InstancePoller\", maxRetries, false, c.requeueServiceInstanceForPoll, stopCh, &waitGroup)\n\n\t\tif utilfeature.DefaultFeatureGate.Enabled(scfeatures.NamespacedServiceBroker) {\n\t\t\tcreateWorker(c.serviceBrokerQueue, \"ServiceBroker\", maxRetries, true, c.reconcileServiceBrokerKey, stopCh, &waitGroup)\n\t\t}\n\n\t\tif utilfeature.DefaultFeatureGate.Enabled(scfeatures.AsyncBindingOperations) {\n\t\t\tcreateWorker(c.bindingPollingQueue, \"BindingPoller\", maxRetries, false, c.requeueServiceBindingForPoll, stopCh, &waitGroup)\n\t\t}\n\t}\n\n\t// this creates a worker specifically for monitoring\n\t// configmaps, as we don't have the watching polling queue\n\t// infrastructure set up for one configmap. Instead this is a\n\t// simple polling based worker\n\tc.createConfigMapMonitorWorker(stopCh, &waitGroup)\n\n\t<-stopCh\n\tglog.Info(\"Shutting down service-catalog controller\")\n\n\tc.clusterServiceBrokerQueue.ShutDown()\n\tc.clusterServiceClassQueue.ShutDown()\n\tc.clusterServicePlanQueue.ShutDown()\n\tc.instanceQueue.ShutDown()\n\tc.bindingQueue.ShutDown()\n\tc.instancePollingQueue.ShutDown()\n\tc.bindingPollingQueue.ShutDown()\n\n\tif utilfeature.DefaultFeatureGate.Enabled(scfeatures.NamespacedServiceBroker) {\n\t\tc.serviceBrokerQueue.ShutDown()\n\t}\n\n\twaitGroup.Wait()\n\tglog.Info(\"Shutdown service-catalog controller\")\n}", "func (w *watcher) cleanupWorker() {\n\tfor {\n\t\t// Wait a full period\n\t\ttime.Sleep(w.cleanupTimeout)\n\n\t\tselect {\n\t\tcase <-w.ctx.Done():\n\t\t\tw.stopped.Done()\n\t\t\treturn\n\t\tdefault:\n\t\t\t// Check entries for timeout\n\t\t\tvar toDelete []string\n\t\t\ttimeout := time.Now().Add(-w.cleanupTimeout)\n\t\t\tw.RLock()\n\t\t\tfor key, lastSeen := range w.deleted {\n\t\t\t\tif lastSeen.Before(timeout) {\n\t\t\t\t\tlogp.Debug(\"docker\", \"Removing container %s after cool down timeout\", key)\n\t\t\t\t\ttoDelete = append(toDelete, key)\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.RUnlock()\n\n\t\t\t// Delete timed out entries:\n\t\t\tfor _, key := range toDelete {\n\t\t\t\tcontainer := w.Container(key)\n\t\t\t\tif container != nil {\n\t\t\t\t\tw.bus.Publish(bus.Event{\n\t\t\t\t\t\t\"delete\": true,\n\t\t\t\t\t\t\"container\": container,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tw.Lock()\n\t\t\tfor _, key := range toDelete {\n\t\t\t\tdelete(w.deleted, key)\n\t\t\t\tdelete(w.containers, key)\n\t\t\t\tif w.shortID {\n\t\t\t\t\tdelete(w.containers, key[:shortIDLen])\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.Unlock()\n\t\t}\n\t}\n}", "func (wp *WorkerPool) SetWorkers(wrks []Worker){\n\twp.workerList = wrks\n}", "func (manager *syncerManager) ShutDown() {\n\tmanager.mu.Lock()\n\tdefer manager.mu.Unlock()\n\tfor _, s := range manager.syncerMap {\n\t\ts.Stop()\n\t}\n}", "func (db *mongoDatabase) Destroy(opts *DestroyOptions) error {\n\tif err := opts.Valid(); err != nil {\n\t\treturn err\n\t}\n\n\terr := new(multierror.Error)\n\n\tfor _, id := range opts.Stack.Machines {\n\t\tif e := modelhelper.DeleteMachine(id); e != nil {\n\t\t\terr = multierror.Append(err, e)\n\t\t}\n\t}\n\n\tif e := modelhelper.DeleteComputeStack(opts.Stack.Id.Hex()); e != nil {\n\t\terr = multierror.Append(err, e)\n\t}\n\n\treturn err.ErrorOrNil()\n}", "func (p *Provider) Reset(vms vm.List) error {\n\t// Map from project to map of zone to list of machines in that project/zone.\n\tprojectZoneMap := make(map[string]map[string][]string)\n\tfor _, v := range vms {\n\t\tif v.Provider != ProviderName {\n\t\t\treturn errors.Errorf(\"%s received VM instance from %s\", ProviderName, v.Provider)\n\t\t}\n\t\tif projectZoneMap[v.Project] == nil {\n\t\t\tprojectZoneMap[v.Project] = make(map[string][]string)\n\t\t}\n\n\t\tprojectZoneMap[v.Project][v.Zone] = append(projectZoneMap[v.Project][v.Zone], v.Name)\n\t}\n\n\tvar g errgroup.Group\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)\n\tdefer cancel()\n\tfor project, zoneMap := range projectZoneMap {\n\t\tfor zone, names := range zoneMap {\n\t\t\targs := []string{\n\t\t\t\t\"compute\", \"instances\", \"reset\",\n\t\t\t}\n\n\t\t\targs = append(args, \"--project\", project)\n\t\t\targs = append(args, \"--zone\", zone)\n\t\t\targs = append(args, names...)\n\n\t\t\tg.Go(func() error {\n\t\t\t\tcmd := exec.CommandContext(ctx, \"gcloud\", args...)\n\n\t\t\t\toutput, err := cmd.CombinedOutput()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"Command: gcloud %s\\nOutput: %s\", args, output)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\t}\n\n\treturn g.Wait()\n}", "func GenerateMachineDeploymentsManifest(s *state.State) (string, error) {\n\tif len(s.Cluster.DynamicWorkers) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\tobjs := []runtime.Object{}\n\tfor _, workerset := range s.Cluster.DynamicWorkers {\n\t\tmachinedeployment, err := createMachineDeployment(s.Cluster, workerset)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tmachinedeployment.TypeMeta = metav1.TypeMeta{\n\t\t\tAPIVersion: clusterv1alpha1.SchemeGroupVersion.String(),\n\t\t\tKind: \"MachineDeployment\",\n\t\t}\n\n\t\tobjs = append(objs, machinedeployment)\n\t}\n\n\treturn templates.KubernetesToYAML(objs)\n}", "func CleanUp(ctx context.Context, cfg *config.Config, pipeline *pipelines.Pipeline, name names.Name) error {\n\tkubectlPath, err := cfg.Tools[config.Kubectl].Resolve()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd := proc.GracefulCommandContext(ctx, kubectlPath, \"delete\",\n\t\t\"all\",\n\t\t\"-l\", k8s.StackLabel+\"=\"+name.DNSName(),\n\t)\n\tif err := cmd.Run(); err != nil {\n\t\treturn fmt.Errorf(\"could not delete k8s resources: %v\", err)\n\t}\n\treturn nil\n}", "func (b *Builder) Cleanup() {\n\tb.mu.Lock()\n\tfor r := range b.running {\n\t\tr.Cleanup()\n\t}\n\tb.mu.Unlock()\n\tif !b.Preserve {\n\t\tdefer os.RemoveAll(b.Dir)\n\t}\n}", "func (p *Plugin) Cleanup(kubeclient kubernetes.Interface) {\n\tp.cleanedUp = true\n\tgracePeriod := int64(1)\n\tdeletionPolicy := metav1.DeletePropagationBackground\n\n\tlistOptions := p.listOptions()\n\tdeleteOptions := metav1.DeleteOptions{\n\t\tGracePeriodSeconds: &gracePeriod,\n\t\tPropagationPolicy: &deletionPolicy,\n\t}\n\n\t// Delete the DaemonSet created by this plugin\n\terr := kubeclient.ExtensionsV1beta1().DaemonSets(p.Namespace).DeleteCollection(\n\t\t&deleteOptions,\n\t\tlistOptions,\n\t)\n\tif err != nil {\n\t\terrlog.LogError(errors.Wrapf(err, \"could not delete DaemonSet %v for daemonset plugin %v\", p.daemonSetName(), p.GetName()))\n\t}\n\n\t// Delete the ConfigMap created by this plugin\n\terr = kubeclient.CoreV1().ConfigMaps(p.Namespace).DeleteCollection(\n\t\t&deleteOptions,\n\t\tlistOptions,\n\t)\n\tif err != nil {\n\t\terrlog.LogError(errors.Wrapf(err, \"could not delete ConfigMap %v for daemonset plugin %v\", p.configMapName(), p.GetName()))\n\t}\n}", "func (manager *Manager) Shutdown() {\n\tmanager.Proxy.Shutdown()\n\n\tfor _, connectionManager := range manager.ConnectionManagers {\n\t\tconnectionManager.Shutdown()\n\t}\n}", "func (i *Instance) Cleanup() {\n\tif err := i.client.DeleteInstance(i.Project, i.Zone, i.Name); err != nil {\n\t\tfmt.Printf(\"Error deleting instance: %v\\n\", err)\n\t}\n}", "func (p *Pool) Stop() {\n\tfor _, worker := range p.Workers {\n\t\tworker.Stop()\n\t}\n\tp.RunningBackground <-true\n}", "func (eng *Engine) Destroy() {\n\tfor _, rt := range eng.applied {\n\t\trt.destroy()\n\t}\n}", "func (l *LoadBalancerEmulator) Cleanup() ([]string, error) {\n\treturn l.applyOnLBServices(l.cleanupService)\n}", "func (c *Controller) Run(threadiness int, stopCh <-chan struct{}) error {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.workqueue.ShutDown()\n\n\t// Start the informer factories to begin populating the informer caches\n\tklog.Info(\"Starting Load Balancer controller\")\n\n\t// Wait for the caches to be synced before starting workers\n\tklog.Info(\"Waiting for informer caches to sync\")\n\tif ok := cache.WaitForCacheSync(stopCh, c.servicesSynced); !ok {\n\t\treturn fmt.Errorf(\"failed to wait for caches to sync\")\n\t}\n\tklog.Info(\"Informer caches are synchronized, enqueueing job to remove the cleanup barrier\")\n\n\tklog.Info(\"Starting workers\")\n\tgo wait.Until(c.worker.Run, time.Second, stopCh)\n\n\t// 907s is chosen because:\n\t//\n\t// - it is prime, which randomizes the cleanups relative ordering against\n\t// other jobs.\n\t// - it is greater than three times the sync interval of the informer\n\t//\n\t// This way, we can be reasonably confident that we have heard about all\n\t// currently active services before we attempt to clean any seemingly\n\t// unused ports.\n\t//\n\t// In the past, there have been problems with ports being deleted even\n\t// though they were still in use by services. This had been caused by the\n\t// cleanup job running too early, despite the fact that we block on the\n\t// informer sync above; apparently, the informer sync wait sometimes\n\t// returns too early or we are missing events for some other, unclear\n\t// reason.\n\t//\n\t// In order to mitigate this problem, we now ensure that the first cleanup\n\t// happens only after three sync intervals (900 seconds).\n\tgo wait.Until(c.periodicCleanup, 907*time.Second, stopCh)\n\n\tklog.Info(\"Started workers\")\n\t<-stopCh\n\tklog.Info(\"Shutting down workers\")\n\n\treturn nil\n}", "func (c *ProjectFinalizerController) Run(stopCh <-chan struct{}, workers int) {\n\tdefer runtime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\t// Wait for the stores to fill\n\tif !cache.WaitForCacheSync(stopCh, c.controller.HasSynced) {\n\t\treturn\n\t}\n\n\tglog.V(5).Infof(\"Starting workers\")\n\tfor i := 0; i < workers; i++ {\n\t\tgo c.worker()\n\t}\n\t<-stopCh\n\tglog.V(1).Infof(\"Shutting down\")\n}", "func performCleanup(ctx context.Context, clientMap map[string]kubernetes.Interface, flags flags) error {\n\tfor _, cluster := range flags.memberClusters {\n\t\tc := clientMap[cluster]\n\t\tif err := cleanupClusterResources(ctx, c, cluster, flags.memberClusterNamespace); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed cleaning up cluster %s namespace %s: %w\", cluster, flags.memberClusterNamespace, err)\n\t\t}\n\t}\n\tc := clientMap[flags.centralCluster]\n\tif err := cleanupClusterResources(ctx, c, flags.centralCluster, flags.centralClusterNamespace); err != nil {\n\t\treturn xerrors.Errorf(\"failed cleaning up cluster %s namespace %s: %w\", flags.centralCluster, flags.centralClusterNamespace, err)\n\t}\n\treturn nil\n}", "func (m *member) Terminate(t *testing.T) {\n\tm.s.Stop()\n\tfor _, hs := range m.hss {\n\t\ths.CloseClientConnections()\n\t\ths.Close()\n\t}\n\tif err := os.RemoveAll(m.ServerConfig.DataDir); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func cleanUpTaskQueue() {\n\tlog.Println(\"Signalling Task Workers for CleanUp\")\n\n\tfor i := uint8(0); i < NumberOfTaskWorkers; i++ {\n\t\tzeroMQWorkerChannelIn <- true\n\t}\n\n\tlog.Println(\"Signalling Finished Waiting for response!\")\n\tfor i := uint8(0); i < NumberOfTaskWorkers; i++ {\n\t\t<-zeroMQWorkerChannelOut\n\t}\n\n\tlog.Println(\"Task Workers Cleanup Complete!\")\n\n\tlog.Println(\"Clearing Proxy\")\n\n\t// Set a Control\n\tzeroMQProxyControl, err := zeromq.MainZeroMQ.NewSocket(zmq4.Type(zmq4.REQ))\n\tif err != nil {\n\t\tlog.Fatalf(\"Error Clearing Proxy! Err: %v\\n\", err)\n\t}\n\n\terr = zeroMQProxyControl.Bind(zeromq.ZeromqMask + ProxyControlPort)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error Clearing Proxy! Err: %v\\n\", err)\n\t}\n\n\tzeroMQProxyControl.Send(\"TERMINATE\", zmq4.Flag(0))\n\tzeroMQProxyControl.Recv(zmq4.Flag(0))\n\n\tlog.Println(\"Clearing Proxy Complete!\")\n}" ]
[ "0.6304216", "0.626198", "0.626198", "0.626198", "0.60066", "0.5894493", "0.5889124", "0.58310187", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.57876456", "0.5772434", "0.56566495", "0.56443316", "0.5613604", "0.5529262", "0.5445959", "0.54036295", "0.53909564", "0.53738517", "0.53616863", "0.5354619", "0.530596", "0.52813846", "0.51862425", "0.5166823", "0.5157727", "0.5147629", "0.5139252", "0.5136502", "0.51335716", "0.5082757", "0.5063258", "0.50457597", "0.50453264", "0.5037611", "0.5027076", "0.5025537", "0.50061435", "0.49835023", "0.4976687", "0.4962522", "0.49582097", "0.49516472", "0.49496472", "0.4942959", "0.49409297", "0.4932638", "0.4901299", "0.49001807", "0.48985824", "0.48970324", "0.48966348", "0.48948556", "0.48942018", "0.48915267", "0.4874682", "0.48714358", "0.48692518", "0.48678476", "0.48677215", "0.4863963", "0.484804", "0.4821592", "0.48151612", "0.48122168", "0.48094028", "0.48090768", "0.4802615", "0.47976238", "0.47970122", "0.47920313", "0.47808284", "0.47780028", "0.477793", "0.47695932", "0.4743372", "0.47403035", "0.47380072", "0.47262585", "0.4714136", "0.47123194", "0.47097313", "0.4709158", "0.4702718", "0.47014618", "0.46996728", "0.4698815", "0.46882614", "0.46850872", "0.46799558", "0.46735936" ]
0.7957886
0
WaitDestroy waits for all Machines to be deleted
func WaitDestroy(s *state.State) error { s.Logger.Info("Waiting for all machines to get deleted...") return wait.PollUntilContextTimeout(s.Context, 5*time.Second, 5*time.Minute, false, func(ctx context.Context) (bool, error) { list := &clusterv1alpha1.MachineList{} if err := s.DynamicClient.List(ctx, list, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil { return false, fail.KubeClient(err, "getting %T", list) } if len(list.Items) != 0 { return false, nil } return true, nil }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bc *BaseCluster) Destroy() {\n\tfor _, m := range bc.Machines() {\n\t\tbc.numMachines--\n\t\tm.Destroy()\n\t}\n}", "func WaitForDeletion(ctx context.Context, mcpKey types.NamespacedName, timeout time.Duration) error {\n\treturn wait.PollImmediate(5*time.Second, timeout, func() (bool, error) {\n\t\tmcp := &machineconfigv1.MachineConfigPool{}\n\t\tif err := testclient.Client.Get(ctx, mcpKey, mcp); apierrors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func waitAndCleanup() {\n\ttime.Sleep(1 * time.Second)\n\n\t// Disconnect from switches.\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tvrtrAgents[i].Delete()\n\t\tvxlanAgents[i].Delete()\n\t\tvlanAgents[i].Delete()\n\t}\n\tfor i := 0; i < NUM_VLRTR_AGENT; i++ {\n\t\tvlrtrAgents[i].Delete()\n\t}\n\tfor i := 0; i < NUM_HOST_BRIDGE; i++ {\n\t\thostBridges[i].Delete()\n\t}\n\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tbrName := \"vrtrBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tbrName := \"vxlanBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[NUM_AGENT+i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_AGENT; i++ {\n\t\tbrName := \"vlanBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[(2*NUM_AGENT)+i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_VLRTR_AGENT; i++ {\n\t\tbrName := \"vlrtrBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[(3*NUM_AGENT)+i].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n\tfor i := 0; i < NUM_HOST_BRIDGE; i++ {\n\t\tbrName := \"hostBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tlog.Infof(\"Deleting OVS bridge: %s\", brName)\n\t\terr := ovsDrivers[HB_AGENT_INDEX].DeleteBridge(brName)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error deleting the bridge. Err: %v\", err)\n\t\t}\n\t}\n}", "func WaitForCleanup() error {\n\tctx := context.Background()\n\tcli, err := client.NewEnvClient()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar (\n\t\tinterval = time.NewTicker(1 * time.Second)\n\t\ttimeout = time.NewTimer(1 * time.Minute)\n\t)\n\n\tfor range interval.C {\n\t\tselect {\n\t\tcase <-timeout.C:\n\t\t\treturn errors.New(\"timed out waiting for all easycontainers containers to get removed\")\n\t\tdefault:\n\t\t\t// only grab the containers created by easycontainers\n\t\t\targs := filters.NewArgs()\n\t\t\targs.Add(\"name\", \"/\"+prefix)\n\n\t\t\tcontainers, err := cli.ContainerList(ctx, types.ContainerListOptions{\n\t\t\t\tFilters: args,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif len(containers) == 0 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *Machine) WaitForPVCsDelete(namespace string) error {\n\treturn wait.PollImmediate(m.PollInterval, m.PollTimeout, func() (bool, error) {\n\t\treturn m.PVCsDeleted(namespace)\n\t})\n}", "func DestroyWorkers(s *state.State) error {\n\tif !s.Cluster.MachineController.Deploy {\n\t\ts.Logger.Info(\"Skipping deleting workers because machine-controller is disabled in configuration.\")\n\n\t\treturn nil\n\t}\n\tif s.DynamicClient == nil {\n\t\treturn fail.NoKubeClient()\n\t}\n\n\tctx := context.Background()\n\n\t// Annotate nodes with kubermatic.io/skip-eviction=true to skip eviction\n\ts.Logger.Info(\"Annotating nodes to skip eviction...\")\n\tnodes := &corev1.NodeList{}\n\tif err := s.DynamicClient.List(ctx, nodes); err != nil {\n\t\treturn fail.KubeClient(err, \"listing Nodes\")\n\t}\n\n\tfor _, node := range nodes.Items {\n\t\tnodeKey := dynclient.ObjectKey{Name: node.Name}\n\n\t\tretErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\t\tn := corev1.Node{}\n\t\t\tif err := s.DynamicClient.Get(ctx, nodeKey, &n); err != nil {\n\t\t\t\treturn fail.KubeClient(err, \"getting %T %s\", n, nodeKey)\n\t\t\t}\n\n\t\t\tif n.Annotations == nil {\n\t\t\t\tn.Annotations = map[string]string{}\n\t\t\t}\n\t\t\tn.Annotations[\"kubermatic.io/skip-eviction\"] = \"true\"\n\n\t\t\treturn fail.KubeClient(s.DynamicClient.Update(ctx, &n), \"updating %T %s\", n, nodeKey)\n\t\t})\n\n\t\tif retErr != nil {\n\t\t\treturn retErr\n\t\t}\n\t}\n\n\t// Delete all MachineDeployment objects\n\ts.Logger.Info(\"Deleting MachineDeployment objects...\")\n\tmdList := &clusterv1alpha1.MachineDeploymentList{}\n\tif err := s.DynamicClient.List(ctx, mdList, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil {\n\t\tif !errorsutil.IsNotFound(err) {\n\t\t\treturn fail.KubeClient(err, \"listing %T\", mdList)\n\t\t}\n\t}\n\n\tfor i := range mdList.Items {\n\t\tif err := s.DynamicClient.Delete(ctx, &mdList.Items[i]); err != nil {\n\t\t\tmd := mdList.Items[i]\n\n\t\t\treturn fail.KubeClient(err, \"deleting %T %s\", md, dynclient.ObjectKeyFromObject(&md))\n\t\t}\n\t}\n\n\t// Delete all MachineSet objects\n\ts.Logger.Info(\"Deleting MachineSet objects...\")\n\tmsList := &clusterv1alpha1.MachineSetList{}\n\tif err := s.DynamicClient.List(ctx, msList, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil {\n\t\tif !errorsutil.IsNotFound(err) {\n\t\t\treturn fail.KubeClient(err, \"getting %T\", mdList)\n\t\t}\n\t}\n\n\tfor i := range msList.Items {\n\t\tif err := s.DynamicClient.Delete(ctx, &msList.Items[i]); err != nil {\n\t\t\tif !errorsutil.IsNotFound(err) {\n\t\t\t\tms := msList.Items[i]\n\n\t\t\t\treturn fail.KubeClient(err, \"deleting %T %s\", ms, dynclient.ObjectKeyFromObject(&ms))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Delete all Machine objects\n\ts.Logger.Info(\"Deleting Machine objects...\")\n\tmList := &clusterv1alpha1.MachineList{}\n\tif err := s.DynamicClient.List(ctx, mList, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil {\n\t\tif !errorsutil.IsNotFound(err) {\n\t\t\treturn fail.KubeClient(err, \"getting %T\", mList)\n\t\t}\n\t}\n\n\tfor i := range mList.Items {\n\t\tif err := s.DynamicClient.Delete(ctx, &mList.Items[i]); err != nil {\n\t\t\tif !errorsutil.IsNotFound(err) {\n\t\t\t\tma := mList.Items[i]\n\n\t\t\t\treturn fail.KubeClient(err, \"deleting %T %s\", ma, dynclient.ObjectKeyFromObject(&ma))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func WaitForZKClusterToTerminate(t *testing.T, k8client client.Client, z *zkapi.ZookeeperCluster) error {\n\tlog.Printf(\"waiting for zookeeper cluster to terminate: %s\", z.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(z.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(map[string]string{\"app\": z.GetName()})},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"zookeeper cluster terminated: %s\", z.Name)\n\treturn nil\n}", "func WaitForClusterToTerminate(t *testing.T, f *framework.Framework, ctx *framework.TestCtx, z *api.ZookeeperCluster) error {\n\tt.Logf(\"waiting for zookeeper cluster to terminate: %s\", z.Name)\n\n\tlistOptions := metav1.ListOptions{\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\"app\": z.GetName()}).String(),\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList, err := f.KubeClient.CoreV1().Pods(z.Namespace).List(goctx.TODO(), listOptions)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tt.Logf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList, err := f.KubeClient.CoreV1().PersistentVolumeClaims(z.Namespace).List(goctx.TODO(), listOptions)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tt.Logf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.Logf(\"zookeeper cluster terminated: %s\", z.Name)\n\treturn nil\n}", "func (v VirtualMachine) Delete() error {\n\ttctx, tcancel := context.WithTimeout(context.Background(), time.Minute*5)\n\tdefer tcancel()\n\n\tpowerState, err := v.vm.PowerState(context.Background())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Getting power state: %s\", powerState)\n\t}\n\n\tif powerState == \"poweredOn\" || powerState == \"suspended\" {\n\t\tpowerOff, err := v.vm.PowerOff(context.Background())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Shutting down virtual machine: %s\", err)\n\t\t}\n\n\t\terr = powerOff.Wait(tctx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Waiting for machine to shut down: %s\", err)\n\t\t}\n\t}\n\n\tdestroy, err := v.vm.Destroy(context.Background())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Destroying virtual machine: %s\", err)\n\t}\n\n\terr = destroy.Wait(tctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Waiting for machine to destroy: %s\", err)\n\t}\n\n\treturn nil\n}", "func assertDeletedWaitForCleanup(t *testing.T, cl client.Client, thing client.Object) {\n\tt.Helper()\n\tthingName := types.NamespacedName{\n\t\tName: thing.GetName(),\n\t\tNamespace: thing.GetNamespace(),\n\t}\n\tassertDeleted(t, cl, thing)\n\tif err := wait.PollImmediate(5*time.Second, 2*time.Minute, func() (bool, error) {\n\t\tif err := cl.Get(context.TODO(), thingName, thing); err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\treturn false, nil\n\t}); err != nil {\n\t\tt.Fatalf(\"Timed out waiting for %s to be cleaned up: %v\", thing.GetName(), err)\n\t}\n}", "func (c *swimCluster) Destroy() {\n\tfor _, node := range c.nodes {\n\t\tnode.Destroy()\n\t}\n\tfor _, ch := range c.channels {\n\t\tch.Close()\n\t}\n}", "func (t *TestSpec) Destroy(delay time.Duration, base string) error {\n\tmanifestToDestroy := []string{\n\t\tt.GetManifestsPath(base),\n\t\tfmt.Sprintf(\"%s/%s\", base, t.NetworkPolicyName()),\n\t\tt.Destination.GetManifestPath(t, base),\n\t}\n\n\tdone := time.After(delay)\n\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\tfor _, manifest := range manifestToDestroy {\n\t\t\t\tt.Kub.Delete(manifest)\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *PoolManager) vmWaitingCleanupLook() {\n\tlogger := log.WithName(\"vmWaitingCleanupLook\")\n\tc := time.Tick(3 * time.Second)\n\tlogger.Info(\"starting cleanup loop for waiting mac addresses\")\n\tfor _ = range c {\n\t\tp.poolMutex.Lock()\n\n\t\tconfigMap, err := p.kubeClient.CoreV1().ConfigMaps(p.managerNamespace).Get(context.TODO(), names.WAITING_VMS_CONFIGMAP, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"failed to get config map\", \"configMapName\", names.WAITING_VMS_CONFIGMAP)\n\t\t\tp.poolMutex.Unlock()\n\t\t\tcontinue\n\t\t}\n\n\t\tconfigMapUpdateNeeded := false\n\t\tif configMap.Data == nil {\n\t\t\tlogger.V(1).Info(\"the configMap is empty\", \"configMapName\", names.WAITING_VMS_CONFIGMAP, \"macPoolMap\", p.macPoolMap)\n\t\t\tp.poolMutex.Unlock()\n\t\t\tcontinue\n\t\t}\n\n\t\tfor macAddress, allocationTime := range configMap.Data {\n\t\t\tt, err := time.Parse(time.RFC3339, allocationTime)\n\t\t\tif err != nil {\n\t\t\t\t// TODO: remove the mac from the wait map??\n\t\t\t\tlogger.Error(err, \"failed to parse allocation time\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlogger.Info(\"data:\", \"configMapName\", names.WAITING_VMS_CONFIGMAP, \"configMap.Data\", configMap.Data, \"macPoolMap\", p.macPoolMap)\n\n\t\t\tif time.Now().After(t.Add(time.Duration(p.waitTime) * time.Second)) {\n\t\t\t\tconfigMapUpdateNeeded = true\n\t\t\t\tdelete(configMap.Data, macAddress)\n\t\t\t\tmacAddress = strings.Replace(macAddress, \"-\", \":\", 5)\n\t\t\t\tdelete(p.macPoolMap, macAddress)\n\t\t\t\tlogger.Info(\"released mac address in waiting loop\", \"macAddress\", macAddress)\n\t\t\t}\n\t\t}\n\n\t\tif configMapUpdateNeeded {\n\t\t\t_, err = p.kubeClient.CoreV1().ConfigMaps(p.managerNamespace).Update(context.TODO(), configMap, metav1.UpdateOptions{})\n\t\t}\n\n\t\tif err == nil {\n\t\t\tlogger.Info(\"the configMap successfully updated\", \"configMapName\", names.WAITING_VMS_CONFIGMAP, \"macPoolMap\", p.macPoolMap)\n\t\t} else {\n\t\t\tlogger.Info(\"the configMap failed to update\", \"configMapName\", names.WAITING_VMS_CONFIGMAP, \"macPoolMap\", p.macPoolMap)\n\t\t}\n\n\t\tp.poolMutex.Unlock()\n\t}\n}", "func (m *Machine) Delete() {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.manager.Delete()\n\n\tif m.backoffTimer != nil {\n\t\tm.backoffTimer.Stop()\n\t}\n\n\tif m.cancel != nil {\n\t\tm.Infof(\"runner\", \"Stopping\")\n\t\tm.cancel()\n\t}\n\n\tm.startTime = time.Time{}\n}", "func (m *Manager) RemoveAllAndWait() {\n\tctrls := m.removeAll()\n\tfor _, ctrl := range ctrls {\n\t\t<-ctrl.terminated\n\t}\n}", "func (m *Manager) RemoveAllAndWait() {\n\tctrls := m.removeAll()\n\tfor _, ctrl := range ctrls {\n\t\t<-ctrl.terminated\n\t}\n}", "func (s *Server) CleanupForDestroy() {\n\ts.CtxCancel()\n\ts.Events().Destroy()\n\ts.DestroyAllSinks()\n\ts.Websockets().CancelAll()\n\ts.powerLock.Destroy()\n}", "func (llrb *LLRB) Destroy() {\n\tclose(llrb.finch)\n\tfor llrb.dodestory() == false {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\tinfof(\"%v destroyed\\n\", llrb.logprefix)\n}", "func (m *Machine) WaitForPVsDelete(labels string) error {\n\treturn wait.PollImmediate(m.PollInterval, m.PollTimeout, func() (bool, error) {\n\t\treturn m.PVsDeleted(labels)\n\t})\n}", "func (jj *Juju) Destroy(user, service string) (*simplejson.Json, error) {\n id := jj.id(user, service)\n report := JSON(fmt.Sprintf(`{\"time\": \"%s\"}`, time.Now()))\n log.Infof(\"destroy juju service: %s\\n\", id)\n\n //Note For now this is massive and basic destruction\n unitArgs := []string{\"destroy-unit\", id + \"/0\", \"--show-log\"}\n serviceArgs := []string{\"destroy-service\", id, \"--show-log\"}\n\n cmd := exec.Command(\"juju\", \"status\", id, \"--format\", \"json\")\n output, err := cmd.CombinedOutput()\n if err != nil { return EmptyJSON(), err }\n status, err := simplejson.NewJson(output)\n machineID, err := status.GetPath(\"services\", id, \"units\", id+\"/0\", \"machine\").String()\n if err != nil { return EmptyJSON(), err }\n machineArgs := []string{\"destroy-machine\", machineID, \"--show-log\"}\n\n client, err := goresque.Dial(redisURL)\n if err != nil { return EmptyJSON(), err }\n log.Infof(\"enqueue destroy-unit\")\n client.Enqueue(workerClass, \"fork\", jj.Path, unitArgs)\n time.Sleep(5 * time.Second)\n log.Infof(\"enqueue destroy-service\")\n client.Enqueue(workerClass, \"fork\", jj.Path, serviceArgs)\n time.Sleep(5 * time.Second)\n log.Infof(\"enqueue destroy-machine\")\n client.Enqueue(workerClass, \"fork\", jj.Path, machineArgs)\n\n report.Set(\"provider\", \"juju\")\n report.Set(\"unit destroyed\", id + \"/0\")\n report.Set(\"service destroyed\", id)\n report.Set(\"machine destroyed\", machineID)\n report.Set(\"unit arguments\", unitArgs)\n report.Set(\"service arguments\", serviceArgs)\n report.Set(\"machine arguments\", machineArgs)\n return report, nil\n}", "func (v *Vagrant) Teardown() {\n\tfor _, node := range v.nodes {\n\t\tvnode, ok := node.(*SSHNode)\n\t\tif !ok {\n\t\t\tlog.Errorf(\"invalid node type encountered: %T\", vnode)\n\t\t\tcontinue\n\t\t}\n\t\tvnode.Cleanup()\n\t}\n\tvCmd := &VagrantCommand{ContivNodes: v.expectedNodes}\n\toutput, err := vCmd.RunWithOutput(\"destroy\", \"-f\")\n\tif err != nil {\n\t\tlog.Errorf(\"Vagrant destroy failed. Error: %s Output: \\n%s\\n\",\n\t\t\terr, output)\n\t}\n\n\tv.nodes = map[string]TestbedNode{}\n\tv.expectedNodes = 0\n}", "func (a *Actuator) Delete(c *clusterv1.Cluster, m *clusterv1.Machine) error {\n\tglog.Infof(\"Deleting machine %s for cluster %s.\", m.Name, c.Name)\n\n\tif a.machineSetupConfigGetter == nil {\n\t\treturn a.handleMachineError(m, apierrors.InvalidMachineConfiguration(\"valid machineSetupConfigGetter is required\"), deleteEventAction)\n\t}\n\n\t// First get provider config\n\tmachineConfig, err := a.machineProviderConfig(m.Spec.ProviderConfig)\n\tif err != nil {\n\t\treturn a.handleMachineError(m, apierrors.InvalidMachineConfiguration(\"Cannot unmarshal machine's providerConfig field: %v\", err), deleteEventAction)\n\t}\n\n\t// Now validate\n\tif err := a.validateMachine(m, machineConfig); err != nil {\n\t\treturn a.handleMachineError(m, err, deleteEventAction)\n\t}\n\n\t// Check if the machine exists (here we mean it is not bootstrapping.)\n\texists, err := a.Exists(c, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !exists {\n\t\tglog.Infof(\"Machine %s for cluster %s does not exists (maybe it is still bootstrapping), skipping.\", m.Name, c.Name)\n\t\treturn nil\n\t}\n\n\t// The exists case here.\n\tglog.Infof(\"Machine %s for cluster %s exists.\", m.Name, c.Name)\n\n\tconfigParams := &MachineParams{\n\t\tRoles: machineConfig.Roles,\n\t\tVersions: m.Spec.Versions,\n\t}\n\n\tmetadata, err := a.getMetadata(c, m, configParams, machineConfig.SSHConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Metadata retrieved: machine %s for cluster %s\", m.Name, c.Name)\n\n\tprivateKey, passPhrase, err := a.getPrivateKey(c, m.Namespace, machineConfig.SSHConfig.SecretName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Running shutdown script: machine %s for cluster %s...\", m.Name, c.Name)\n\n\tsshClient := ssh.NewSSHProviderClient(privateKey, passPhrase, machineConfig.SSHConfig)\n\n\tif err = sshClient.WriteFile(metadata.ShutdownScript, \"/var/tmp/shutdownscript.sh\"); err != nil {\n\t\tglog.Errorf(\"Error copying shutdown script: %v\", err)\n\t\treturn err\n\t}\n\n\tif err = sshClient.ProcessCMD(\"chmod +x /var/tmp/shutdownscript.sh && bash /var/tmp/shutdownscript.sh\"); err != nil {\n\t\tglog.Errorf(\"running shutdown script error: %v\", err)\n\t\treturn err\n\t}\n\n\ta.eventRecorder.Eventf(m, corev1.EventTypeNormal, \"Deleted\", \"Deleted Machine %v\", m.Name)\n\treturn nil\n}", "func vSphereRemoveHost(ctx context.Context, obj *object.HostSystem) error {\n\tdisconnectTask, err := obj.Disconnect(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := disconnectTask.Wait(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tdestroyTask, err := obj.Destroy(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn destroyTask.Wait(ctx)\n}", "func (o *ClusterUninstaller) destroyImages() error {\n\tfirstPassList, err := o.listImages()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(firstPassList.list()) == 0 {\n\t\treturn nil\n\t}\n\n\titems := o.insertPendingItems(imageTypeName, firstPassList.list())\n\tfor _, item := range items {\n\t\to.Logger.Debugf(\"destroyImages: firstPassList: %v / %v\", item.name, item.id)\n\t}\n\n\tctx, cancel := o.contextWithTimeout()\n\tdefer cancel()\n\n\tfor _, item := range items {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\to.Logger.Debugf(\"destroyImages: case <-ctx.Done()\")\n\t\t\treturn o.Context.Err() // we're cancelled, abort\n\t\tdefault:\n\t\t}\n\n\t\tbackoff := wait.Backoff{\n\t\t\tDuration: 15 * time.Second,\n\t\t\tFactor: 1.1,\n\t\t\tCap: leftInContext(ctx),\n\t\t\tSteps: math.MaxInt32}\n\t\terr = wait.ExponentialBackoffWithContext(ctx, backoff, func(context.Context) (bool, error) {\n\t\t\terr2 := o.deleteImage(item)\n\t\t\tif err2 == nil {\n\t\t\t\treturn true, err2\n\t\t\t}\n\t\t\to.errorTracker.suppressWarning(item.key, err2, o.Logger)\n\t\t\treturn false, err2\n\t\t})\n\t\tif err != nil {\n\t\t\to.Logger.Fatal(\"destroyImages: ExponentialBackoffWithContext (destroy) returns \", err)\n\t\t}\n\t}\n\n\tif items = o.getPendingItems(imageTypeName); len(items) > 0 {\n\t\tfor _, item := range items {\n\t\t\to.Logger.Debugf(\"destroyImages: found %s in pending items\", item.name)\n\t\t}\n\t\treturn errors.Errorf(\"destroyImages: %d undeleted items pending\", len(items))\n\t}\n\n\tbackoff := wait.Backoff{\n\t\tDuration: 15 * time.Second,\n\t\tFactor: 1.1,\n\t\tCap: leftInContext(ctx),\n\t\tSteps: math.MaxInt32}\n\terr = wait.ExponentialBackoffWithContext(ctx, backoff, func(context.Context) (bool, error) {\n\t\tsecondPassList, err2 := o.listImages()\n\t\tif err2 != nil {\n\t\t\treturn false, err2\n\t\t}\n\t\tif len(secondPassList) == 0 {\n\t\t\t// We finally don't see any remaining instances!\n\t\t\treturn true, nil\n\t\t}\n\t\tfor _, item := range secondPassList {\n\t\t\to.Logger.Debugf(\"destroyImages: found %s in second pass\", item.name)\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\to.Logger.Fatal(\"destroyImages: ExponentialBackoffWithContext (list) returns \", err)\n\t}\n\n\treturn nil\n}", "func (m *Mqtt) Destroy() error {\n\tm.token = m.client.Unsubscribe(\"go-mqtt/sample\")\n\tm.token.Wait()\n\tm.client.Disconnect(250)\n\treturn m.token.Error()\n}", "func (s *StepCreateVM) Cleanup(state multistep.StateBag) {\n\t_, cancelled := state.GetOk(multistep.StateCancelled)\n\t_, halted := state.GetOk(multistep.StateHalted)\n\tif !cancelled && !halted {\n\t\treturn\n\t}\n\n\tif vm, ok := state.GetOk(\"vm\"); ok {\n\t\tui := state.Get(\"ui\").(packer.Ui)\n\t\td := state.Get(\"driver\").(*Driver)\n\n\t\tui.Say(\"Destroying VM...\")\n\n\t\terr := d.DestroyVM(vm.(*object.VirtualMachine))\n\t\tif err != nil {\n\t\t\tui.Error(err.Error())\n\t\t}\n\t}\n}", "func (l *HostStateListener) cleanUpContainers(stateIDs []string, getLock bool) {\n\tplog.WithField(\"stateids\", stateIDs).Debug(\"cleaning up containers\")\n\t// Start shutting down all of the containers in parallel\n\twg := &sync.WaitGroup{}\n\tfor _, s := range stateIDs {\n\t\tcontainerExit := func() <-chan time.Time {\n\t\t\tif getLock {\n\t\t\t\tl.mu.RLock()\n\t\t\t\tdefer l.mu.RUnlock()\n\t\t\t}\n\t\t\t_, cExit := l.getExistingThread(s)\n\t\t\treturn cExit\n\t\t}()\n\t\twg.Add(1)\n\t\tgo func(stateID string, cExit <-chan time.Time) {\n\t\t\tdefer wg.Done()\n\t\t\tl.shutDownContainer(stateID, cExit)\n\t\t}(s, containerExit)\n\t}\n\n\t// Remove the threads from our internal thread list\n\t// Need to get the lock here if we don't already have it\n\tfunc() {\n\t\tif getLock {\n\t\t\tl.mu.Lock()\n\t\t\tdefer l.mu.Unlock()\n\t\t}\n\t\tfor _, s := range stateIDs {\n\t\t\tl.removeExistingThread(s)\n\t\t}\n\t}()\n\n\t// Wait for all containers to shut down\n\twg.Wait()\n}", "func (p *Pool) Destroy() {\n\tvar sig struct{}\n\tp.exitChan <- sig\n}", "func (o *ClusterUninstaller) destroyVPCs() error {\n\tfirstPassList, err := o.listVPCs()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(firstPassList.list()) == 0 {\n\t\treturn nil\n\t}\n\n\titems := o.insertPendingItems(vpcTypeName, firstPassList.list())\n\n\tctx, cancel := o.contextWithTimeout()\n\tdefer cancel()\n\n\tfor _, item := range items {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\to.Logger.Debugf(\"destroyVPCs: case <-ctx.Done()\")\n\t\t\treturn o.Context.Err() // we're cancelled, abort\n\t\tdefault:\n\t\t}\n\n\t\tbackoff := wait.Backoff{\n\t\t\tDuration: 15 * time.Second,\n\t\t\tFactor: 1.1,\n\t\t\tCap: leftInContext(ctx),\n\t\t\tSteps: math.MaxInt32}\n\t\terr = wait.ExponentialBackoffWithContext(ctx, backoff, func(context.Context) (bool, error) {\n\t\t\terr2 := o.deleteVPC(item)\n\t\t\tif err2 == nil {\n\t\t\t\treturn true, err2\n\t\t\t}\n\t\t\to.errorTracker.suppressWarning(item.key, err2, o.Logger)\n\t\t\treturn false, err2\n\t\t})\n\t\tif err != nil {\n\t\t\to.Logger.Fatal(\"destroyVPCs: ExponentialBackoffWithContext (destroy) returns \", err)\n\t\t}\n\t}\n\n\tif items = o.getPendingItems(vpcTypeName); len(items) > 0 {\n\t\tfor _, item := range items {\n\t\t\to.Logger.Debugf(\"destroyVPCs: found %s in pending items\", item.name)\n\t\t}\n\t\treturn errors.Errorf(\"destroyVPCs: %d undeleted items pending\", len(items))\n\t}\n\n\tbackoff := wait.Backoff{\n\t\tDuration: 15 * time.Second,\n\t\tFactor: 1.1,\n\t\tCap: leftInContext(ctx),\n\t\tSteps: math.MaxInt32}\n\terr = wait.ExponentialBackoffWithContext(ctx, backoff, func(context.Context) (bool, error) {\n\t\tsecondPassList, err2 := o.listVPCs()\n\t\tif err2 != nil {\n\t\t\treturn false, err2\n\t\t}\n\t\tif len(secondPassList) == 0 {\n\t\t\t// We finally don't see any remaining instances!\n\t\t\treturn true, nil\n\t\t}\n\t\tfor _, item := range secondPassList {\n\t\t\to.Logger.Debugf(\"destroyVPCs: found %s in second pass\", item.name)\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\to.Logger.Fatal(\"destroyVPCs: ExponentialBackoffWithContext (list) returns \", err)\n\t}\n\n\treturn nil\n}", "func (m *member) Terminate(t *testing.T) {\n\tm.s.Stop()\n\tfor _, hs := range m.hss {\n\t\ths.CloseClientConnections()\n\t\ths.Close()\n\t}\n\tif err := os.RemoveAll(m.ServerConfig.DataDir); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (m *Manager) Delete() {\n\tm.machine.Infof(m.machine.Name(), \"Stopping manager\")\n\tm.cancel()\n\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tfor _, w := range m.watchers {\n\t\tw.Delete()\n\t}\n}", "func (o *ClusterUninstaller) destroyDisks() error {\n\tfound, err := o.listDisks()\n\tif err != nil {\n\t\treturn err\n\t}\n\titems := o.insertPendingItems(\"disk\", found)\n\tfor _, item := range items {\n\t\terr := o.deleteDisk(item)\n\t\tif err != nil {\n\t\t\to.errorTracker.suppressWarning(item.key, err, o.Logger)\n\t\t}\n\t}\n\n\tfor _, item := range items {\n\t\terr := o.waitForDiskDeletion(item)\n\t\tif err != nil {\n\t\t\to.errorTracker.suppressWarning(item.key, err, o.Logger)\n\t\t}\n\t}\n\n\tif items = o.getPendingItems(\"disk\"); len(items) > 0 {\n\t\treturn errors.Errorf(\"%d items pending\", len(items))\n\t}\n\treturn nil\n}", "func (f *TestFramework) DestroyMachineSet() error {\n\tlog.Print(\"Destroying MachineSets\")\n\tif f.machineSet == nil {\n\t\tlog.Print(\"unable to find MachineSet to be deleted, was skip VM setup option selected ?\")\n\t\tlog.Print(\"MachineSets/Machines needs to be deleted manually \\nNot deleting MachineSets...\")\n\t\treturn nil\n\t}\n\terr := f.machineClient.MachineSets(\"openshift-machine-api\").Delete(context.TODO(), f.machineSet.Name, metav1.DeleteOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to delete MachineSet %v\", err)\n\t}\n\tlog.Print(\"MachineSets Destroyed\")\n\treturn nil\n}", "func (rhost *rhostData) destroy() {\n\tif rhost.connected {\n\t\trhost.connected = false\n\t\trhost.wg.Done()\n\t}\n}", "func (tc *testContext) waitForServicesConfigMapDeletion(cmName string) error {\n\terr := wait.PollImmediate(retry.Interval, retry.ResourceChangeTimeout, func() (bool, error) {\n\t\t_, err := tc.client.K8s.CoreV1().ConfigMaps(wmcoNamespace).Get(context.TODO(), cmName, meta.GetOptions{})\n\t\tif err == nil {\n\t\t\t// Retry if the resource is found\n\t\t\treturn false, nil\n\t\t}\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, fmt.Errorf(\"error retrieving ConfigMap: %s: %w\", cmName, err)\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error waiting for ConfigMap deletion %s/%s: %w\", wmcoNamespace, cmName, err)\n\t}\n\treturn nil\n}", "func exitHostMM(ctx context.Context, host *object.HostSystem, timeout int32) {\n\ttask, err := host.ExitMaintenanceMode(ctx, timeout)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\t_, err = task.WaitForResult(ctx, nil)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tframework.Logf(\"Host: %v exited from maintenance mode\", host)\n}", "func (d *Deployer) Destroy(dep *Deployment, printServerLogs bool) {\n\tfor _, hsDep := range dep.HS {\n\t\tif printServerLogs {\n\t\t\tprintLogs(d.Docker, hsDep.ContainerID, hsDep.ContainerID)\n\t\t}\n\t\terr := d.Docker.ContainerKill(context.Background(), hsDep.ContainerID, \"KILL\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Destroy: Failed to destroy container %s : %s\\n\", hsDep.ContainerID, err)\n\t\t}\n\t\terr = d.Docker.ContainerRemove(context.Background(), hsDep.ContainerID, types.ContainerRemoveOptions{\n\t\t\tForce: true,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Destroy: Failed to remove container %s : %s\\n\", hsDep.ContainerID, err)\n\t\t}\n\t}\n}", "func (s *Reconciler) Delete(ctx context.Context) error {\n\tvmSpec := &virtualmachines.Spec{\n\t\tName: s.scope.Machine.Name,\n\t}\n\n\t// Getting a vm object does not work here so let's assume\n\t// an instance is really being deleted\n\tif s.scope.Machine.Annotations == nil {\n\t\ts.scope.Machine.Annotations = make(map[string]string)\n\t}\n\ts.scope.Machine.Annotations[MachineInstanceStateAnnotationName] = string(machinev1.VMStateDeleting)\n\tvmStateDeleting := machinev1.VMStateDeleting\n\ts.scope.MachineStatus.VMState = &vmStateDeleting\n\n\terr := s.virtualMachinesSvc.Delete(ctx, vmSpec)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to delete machine: %w\", err)\n\t}\n\n\tosDiskSpec := &disks.Spec{\n\t\tName: azure.GenerateOSDiskName(s.scope.Machine.Name),\n\t}\n\terr = s.disksSvc.Delete(ctx, osDiskSpec)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\tName: s.scope.Machine.Name,\n\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\tReason: err.Error(),\n\t\t})\n\t\treturn fmt.Errorf(\"failed to delete OS disk: %w\", err)\n\t}\n\n\tif s.scope.MachineConfig.Vnet == \"\" {\n\t\treturn fmt.Errorf(\"MachineConfig vnet is missing on machine %s\", s.scope.Machine.Name)\n\t}\n\n\tnetworkInterfaceSpec := &networkinterfaces.Spec{\n\t\tName: azure.GenerateNetworkInterfaceName(s.scope.Machine.Name),\n\t\tVnetName: s.scope.MachineConfig.Vnet,\n\t}\n\n\terr = s.networkInterfacesSvc.Delete(ctx, networkInterfaceSpec)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\tName: s.scope.Machine.Name,\n\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\tReason: err.Error(),\n\t\t})\n\t\treturn fmt.Errorf(\"Unable to delete network interface: %w\", err)\n\t}\n\n\tif s.scope.MachineConfig.PublicIP {\n\t\tpublicIPName, err := azure.GenerateMachinePublicIPName(s.scope.MachineConfig.Name, s.scope.Machine.Name)\n\t\tif err != nil {\n\t\t\t// Only when the generated name is longer than allowed by the Azure portal\n\t\t\t// That can happen only when\n\t\t\t// - machine name is changed (can't happen without creating a new CR)\n\t\t\t// - cluster name is changed (could happen but then we will get different name anyway)\n\t\t\t// - machine CR was created with too long public ip name (in which case no instance was created)\n\t\t\tklog.Info(\"Generated public IP name was too long, skipping deletion of the resource\")\n\t\t\treturn nil\n\t\t}\n\n\t\terr = s.publicIPSvc.Delete(ctx, &publicips.Spec{\n\t\t\tName: publicIPName,\n\t\t})\n\t\tif err != nil {\n\t\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\t\tName: s.scope.Machine.Name,\n\t\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\t\tReason: err.Error(),\n\t\t\t})\n\t\t\treturn fmt.Errorf(\"unable to delete Public IP: %w\", err)\n\t\t}\n\t}\n\n\t// Delete the availability set with the given name if no virtual machines are attached to it.\n\tif err := s.availabilitySetsSvc.Delete(ctx, &availabilitysets.Spec{\n\t\tName: s.getAvailibilitySetName(),\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"failed to delete availability set: %w\", err)\n\t}\n\n\treturn nil\n}", "func (p *MockDeployPlugin) Destroy(cluster *lang.Cluster, deployName string, params util.NestedParameterMap, eventLog *event.Log) error {\n\ttime.Sleep(p.SleepTime)\n\treturn nil\n}", "func (c *APIClient) WaitIstioMeshDeleted(orgID, workspaceID, meshID, timeout int) error {\n\tfor i := 1; i < timeout; i++ {\n\t\t_, err := c.GetIstioMesh(orgID, workspaceID, meshID)\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"404\") {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\treturn fmt.Errorf(\"timeout (%d seconds) reached before isto mesh deleted\", timeout)\n}", "func WaitTerminations(done chan bool) {\n\tremaining := SegmentListeners\n\tfor remaining > 0 {\n\t\tlog.Printf(\"WaitTerminations: waiting for %d listeners\\n\", remaining)\n\t\t_ = <-done\n\t\tremaining--\n\t}\n}", "func (m *Machine) WaitForStatefulSetDelete(namespace string, name string) error {\n\treturn wait.PollImmediate(m.PollInterval, m.PollTimeout, func() (bool, error) {\n\t\tfound, err := m.StatefulSetExist(namespace, name)\n\t\treturn !found, err\n\t})\n}", "func DelContainerForceMultyTime(c *check.C, cname string) {\n\tdone := make(chan bool, 1)\n\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tdefer ticker.Stop()\n\n\ttimeout := make(chan bool)\n\tgo func() {\n\t\ttime.Sleep(3 * time.Second)\n\t\ttimeout <- true\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn\n\t\tcase <-timeout:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tresp, _ := DelContainerForce(c, cname)\n\t\t\tif resp.StatusCode == 204 {\n\t\t\t\tdone <- true\n\t\t\t}\n\t\t}\n\t}\n}", "func (c CommitterProbe) WaitCleanup() {\n\tc.cleanWg.Wait()\n}", "func Test_Static_Pool_Destroy_And_Close_While_Wait(t *testing.T) {\n\tctx := context.Background()\n\tp, err := Initialize(\n\t\tctx,\n\t\tfunc() *exec.Cmd { return exec.Command(\"php\", \"../tests/client.php\", \"delay\", \"pipes\") },\n\t\tpipe.NewPipeFactory(),\n\t\t&Config{\n\t\t\tNumWorkers: 1,\n\t\t\tAllocateTimeout: time.Second,\n\t\t\tDestroyTimeout: time.Second,\n\t\t},\n\t)\n\n\tassert.NotNil(t, p)\n\tassert.NoError(t, err)\n\n\tgo func() {\n\t\t_, errP := p.Exec(&payload.Payload{Body: []byte(\"100\")})\n\t\tif errP != nil {\n\t\t\tt.Errorf(\"error executing payload: error %v\", err)\n\t\t}\n\t}()\n\ttime.Sleep(time.Millisecond * 100)\n\n\tp.Destroy(ctx)\n\t_, err = p.Exec(&payload.Payload{Body: []byte(\"100\")})\n\tassert.Error(t, err)\n}", "func (d *Death) WaitForDeath(closable ...io.Closer) (err error) {\n\td.wg.Wait()\n\td.log.Info(\"Shutdown started...\")\n\tcount := len(closable)\n\td.log.Debug(\"Closing \", count, \" objects\")\n\tif count > 0 {\n\t\treturn d.closeInMass(closable...)\n\t}\n\treturn nil\n}", "func waitForInit() error {\n\tstart := time.Now()\n\tmaxEnd := start.Add(time.Minute)\n\tfor {\n\t\t// Check for existence of vpcCniInitDonePath\n\t\tif _, err := os.Stat(vpcCniInitDonePath); err == nil {\n\t\t\t// Delete the done file in case of a reboot of the node or restart of the container (force init container to run again)\n\t\t\tif err := os.Remove(vpcCniInitDonePath); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// If file deletion fails, log and allow retry\n\t\t\tlog.Errorf(\"Failed to delete file: %s\", vpcCniInitDonePath)\n\t\t}\n\t\tif time.Now().After(maxEnd) {\n\t\t\treturn errors.Errorf(\"time exceeded\")\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func TestWaitUntilRunning(t *testing.T) {\n\tts := memorytopo.NewServer(\"cell1\")\n\tm := NewManager(ts)\n\n\t// Start it 3 times i.e. restart it 2 times.\n\tfor i := 1; i <= 3; i++ {\n\t\t// Run the manager in the background.\n\t\twg, _, cancel := StartManager(m)\n\n\t\t// Shut it down and wait for the shutdown to complete.\n\t\tcancel()\n\t\twg.Wait()\n\t}\n}", "func (rem *Remote) Destroy() {\n\trem.Manager.Destroy()\n}", "func (m *TimeServiceManager) Kill() {\n\tif len(m.Instances) > 0 {\n\t\tfmt.Printf(\"There are %d instances. \", len(m.Instances))\n\t\tn := rand.Intn(len(m.Instances))\n\t\tfmt.Printf(\"Killing Instance %d\\n\", n)\n\t\tclose(m.Instances[n].Dead)\n\t\tm.Instances = append(m.Instances[:n], m.Instances[n+1:]...)\n\t} else {\n\t\tfmt.Println(\"No instance to kill\")\n\t}\n}", "func waitForMachineSetToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForMachineSetStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(machineSet *capiv1alpha1.MachineSet) bool { return machineSet != nil },\n\t)\n}", "func (e *EventBus) Destroy() {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\n\t// Stop every pool that exists for a given callback topic.\n\tfor _, cp := range e.pools {\n\t\tcp.pool.Stop()\n\t}\n\n\te.pools = make(map[string]*CallbackPool)\n}", "func WaitForDeletion(profileKey types.NamespacedName, timeout time.Duration) error {\n\treturn wait.PollImmediate(time.Second, timeout, func() (bool, error) {\n\t\tprof := &performancev2.PerformanceProfile{}\n\t\tif err := testclient.Client.Get(context.TODO(), profileKey, prof); errors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func WaitForBKClusterToTerminate(t *testing.T, k8client client.Client, b *bkapi.BookkeeperCluster) error {\n\tlog.Printf(\"waiting for Bookkeeper cluster to terminate: %s\", b.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(b.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(map[string]string{\"bookkeeper_cluster\": b.GetName()})},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"bookkeeper cluster terminated: %s\", b.Name)\n\treturn nil\n}", "func (t *SubprocessTest) destroy() (err error) {\n\t// Make sure we clean up after ourselves after everything else below.\n\n\t// Close what is necessary.\n\tfor _, c := range t.ToClose {\n\t\tif c == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\togletest.ExpectEq(nil, c.Close())\n\t}\n\n\t// If we didn't try to mount the file system, there's nothing further to do.\n\tif t.mountSampleErr == nil {\n\t\treturn nil\n\t}\n\n\t// In the background, initiate an unmount.\n\tunmountErrChan := make(chan error)\n\tgo func() {\n\t\tunmountErrChan <- unmount(t.Dir)\n\t}()\n\n\t// Make sure we wait for the unmount, even if we've already returned early in\n\t// error. Return its error if we haven't seen any other error.\n\tdefer func() {\n\t\t// Wait.\n\t\tunmountErr := <-unmountErrChan\n\t\tif unmountErr != nil {\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"unmount:\", unmountErr)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = fmt.Errorf(\"unmount: %v\", unmountErr)\n\t\t\treturn\n\t\t}\n\n\t\t// Clean up.\n\t\togletest.ExpectEq(nil, os.Remove(t.Dir))\n\t}()\n\n\t// Wait for the subprocess.\n\tif err := <-t.mountSampleErr; err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func waitUntilRDSClusterDeleted(rdsClientSess *rds.RDS, restoreParams map[string]string) error {\n\n\trdsClusterName := restoreParams[\"restoreRDS\"]\n\n\tinput := &rds.DescribeDBClustersInput{\n\t\tDBClusterIdentifier: aws.String(rdsClusterName),\n\t}\n\n\t// Check if Cluster exists\n\t_, err := rdsClientSess.DescribeDBClusters(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tif aerr.Code() == rds.ErrCodeDBClusterNotFoundFault {\n\t\t\t\tfmt.Println(rds.ErrCodeDBClusterNotFoundFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Wait RDS cluster deletion err %v\", err)\n\t\t\t} else {\n\t\t\t\t// Print the error, cast err to awserr.Error to get the Code and Message from an error.\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn fmt.Errorf(\"Wait RDS cluster deletion err %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: DEBUG - fmt.Println(result)\n\tfmt.Printf(\"Wait until RDS cluster [%v] is fully deleted...\\n\", rdsClusterName)\n\n\tstart := time.Now()\n\n\tmaxWaitAttempts := 120\n\n\t// Check until deleted\n\tfor waitAttempt := 0; waitAttempt < maxWaitAttempts; waitAttempt++ {\n\t\telapsedTime := time.Since(start).Seconds()\n\n\t\tif waitAttempt > 0 {\n\t\t\tformattedTime := strings.Split(fmt.Sprintf(\"%6v\", elapsedTime), \".\")\n\t\t\tfmt.Printf(\"Cluster deletion elapsed time: %vs\\n\", formattedTime[0])\n\t\t}\n\n\t\tresp, err := rdsClientSess.DescribeDBClusters(input)\n\t\tif err != nil {\n\t\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\t\tif aerr.Code() == rds.ErrCodeDBClusterNotFoundFault {\n\t\t\t\t\tfmt.Println(\"RDS Cluster deleted successfully\")\n\t\t\t\t\treturn nil\n\t\t\t\t} else {\n\t\t\t\t\t// Print the error, cast err to awserr.Error to get the Code and Message from an error.\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn fmt.Errorf(\"Wait RDS cluster deletion err %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfmt.Printf(\"Cluster status: [%s]\\n\", *resp.DBClusters[0].Status)\n\t\tif *resp.DBClusters[0].Status == \"terminated\" {\n\t\t\tfmt.Printf(\"RDS cluster [%v] deleted successfully\\n\", rdsClusterName)\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(30 * time.Second)\n\t}\n\n\t// Timeout Err\n\treturn fmt.Errorf(\"RDS Cluster [%v] could not be deleted, exceed max wait attemps\\n\", rdsClusterName)\n}", "func waitForMachineSetToNotExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForObjectToNotExist(\n\t\tnamespace, name,\n\t\tfunc(namespace, name string) (metav1.Object, error) {\n\t\t\treturn getMachineSet(capiClient, namespace, name)\n\t\t},\n\t)\n}", "func (c *VMReplicaSet) orphan(cm *controller.VirtualMachineControllerRefManager, rs *virtv1.VirtualMachineReplicaSet, vms []*virtv1.VirtualMachine) error {\n\n\tvar wg sync.WaitGroup\n\terrChan := make(chan error, len(vms))\n\twg.Add(len(vms))\n\n\tfor _, vm := range vms {\n\t\tgo func(vm *virtv1.VirtualMachine) {\n\t\t\tdefer wg.Done()\n\t\t\terr := cm.ReleaseVirtualMachine(vm)\n\t\t\tif err != nil {\n\t\t\t\terrChan <- err\n\t\t\t}\n\t\t}(vm)\n\t}\n\twg.Wait()\n\tselect {\n\tcase err := <-errChan:\n\t\treturn err\n\tdefault:\n\t}\n\treturn nil\n}", "func (w *worker) Terminate() {\n\tfor _, v := range w.allGateways {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.allMasters {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.allNodes {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.concernedGateways {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.concernedMasters {\n\t\tv.Released()\n\t}\n\tfor _, v := range w.concernedNodes {\n\t\tv.Released()\n\t}\n\tif w.availableGateway != nil {\n\t\tw.availableGateway.Released()\n\t}\n\tif w.availableMaster != nil {\n\t\tw.availableMaster.Released()\n\t}\n\tif w.availableNode != nil {\n\t\tw.availableNode.Released()\n\t}\n}", "func WaitForDeletion(pod *corev1.Pod, timeout time.Duration) error {\n\treturn wait.PollImmediate(time.Second, timeout, func() (bool, error) {\n\t\tif err := testclient.Client.Get(context.TODO(), client.ObjectKeyFromObject(pod), pod); errors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func (gi *GrpcInvoker) Destroy() {\n\tgi.quitOnce.Do(func() {\n\t\tgi.BaseInvoker.Destroy()\n\t\tclient := gi.getClient()\n\t\tif client != nil {\n\t\t\tgi.setClient(nil)\n\t\t\tclient.Close()\n\t\t}\n\t})\n}", "func WaitForDeletion(cs *testclient.ClientSet, pod *corev1.Pod, timeout time.Duration) error {\n\treturn wait.PollImmediate(time.Second, timeout, func() (bool, error) {\n\t\t_, err := cs.Pods(pod.Namespace).Get(pod.Name, metav1.GetOptions{})\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func Destroy(name string, t ObjectType, deferred bool) error {\n\tcmd := &Cmd{\n\t\tObjset_type: uint64(t),\n\t}\n\treturn NvlistIoctl(zfsHandle.Fd(), ZFS_IOC_DESTROY, name, cmd, nil, nil, nil)\n}", "func WaitUntilDeleted(ctx context.Context, client client.Client, namespace, name string) error {\n\tmr := &resourcesv1alpha1.ManagedResource{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\tif err := kutil.WaitUntilResourceDeleted(ctx, client, mr, IntervalWait); err != nil {\n\t\tresourcesAppliedCondition := gardencorev1beta1helper.GetCondition(mr.Status.Conditions, resourcesv1alpha1.ResourcesApplied)\n\t\tif resourcesAppliedCondition != nil && resourcesAppliedCondition.Status != gardencorev1beta1.ConditionTrue &&\n\t\t\t(resourcesAppliedCondition.Reason == resourcesv1alpha1.ConditionDeletionFailed || resourcesAppliedCondition.Reason == resourcesv1alpha1.ConditionDeletionPending) {\n\t\t\tdeleteError := fmt.Errorf(\"error while waiting for all resources to be deleted: %w:\\n%s\", err, resourcesAppliedCondition.Message)\n\t\t\treturn gardencorev1beta1helper.DetermineError(deleteError, deleteError.Error())\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "func waitForSignals(unixSock string) {\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)\n\n\tfor sig := range signals {\n\t\tlogrus.Debugf(\"Received signal %s , clean up...\", sig)\n\t\tif _, err := os.Stat(unixSock); err == nil {\n\t\t\tlogrus.Debugf(\"Remove %s\", unixSock)\n\t\t\tif err := os.Remove(unixSock); err != nil {\n\t\t\t\tlogrus.Errorf(\"Remove %s failed: %s\", unixSock, err.Error())\n\t\t\t}\n\t\t}\n\n\t\tos.Exit(0)\n\t}\n}", "func (p *Provider) Reset(vms vm.List) error {\n\t// Map from project to map of zone to list of machines in that project/zone.\n\tprojectZoneMap := make(map[string]map[string][]string)\n\tfor _, v := range vms {\n\t\tif v.Provider != ProviderName {\n\t\t\treturn errors.Errorf(\"%s received VM instance from %s\", ProviderName, v.Provider)\n\t\t}\n\t\tif projectZoneMap[v.Project] == nil {\n\t\t\tprojectZoneMap[v.Project] = make(map[string][]string)\n\t\t}\n\n\t\tprojectZoneMap[v.Project][v.Zone] = append(projectZoneMap[v.Project][v.Zone], v.Name)\n\t}\n\n\tvar g errgroup.Group\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)\n\tdefer cancel()\n\tfor project, zoneMap := range projectZoneMap {\n\t\tfor zone, names := range zoneMap {\n\t\t\targs := []string{\n\t\t\t\t\"compute\", \"instances\", \"reset\",\n\t\t\t}\n\n\t\t\targs = append(args, \"--project\", project)\n\t\t\targs = append(args, \"--zone\", zone)\n\t\t\targs = append(args, names...)\n\n\t\t\tg.Go(func() error {\n\t\t\t\tcmd := exec.CommandContext(ctx, \"gcloud\", args...)\n\n\t\t\t\toutput, err := cmd.CombinedOutput()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"Command: gcloud %s\\nOutput: %s\", args, output)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\t}\n\n\treturn g.Wait()\n}", "func WaitForNamespacesDeleted(ctx context.Context, c clientset.Interface, namespaces []string, timeout time.Duration) error {\n\tginkgo.By(fmt.Sprintf(\"Waiting for namespaces %+v to vanish\", namespaces))\n\tnsMap := map[string]bool{}\n\tfor _, ns := range namespaces {\n\t\tnsMap[ns] = true\n\t}\n\t//Now POLL until all namespaces have been eradicated.\n\treturn wait.PollWithContext(ctx, 2*time.Second, timeout,\n\t\tfunc(ctx context.Context) (bool, error) {\n\t\t\tnsList, err := c.CoreV1().Namespaces().List(ctx, metav1.ListOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tfor _, item := range nsList.Items {\n\t\t\t\tif _, ok := nsMap[item.Name]; ok {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n}", "func WaitForPravegaClusterToTerminate(t *testing.T, k8client client.Client, p *api.PravegaCluster) error {\n\tlog.Printf(\"waiting for pravega cluster to terminate: %s\", p.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(p.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(p.LabelsForPravegaCluster())},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"pravega cluster terminated: %s\", p.Name)\n\treturn nil\n}", "func tearDownVMs(t *testing.T, images []string, vmNum int, isSyncOffload bool) {\n\tfor i := 0; i < vmNum; i++ {\n\t\tlog.Infof(\"Shutting down VM %d, images: %s\", i, images[i%len(images)])\n\t\tvmIDString := strconv.Itoa(i)\n\t\tmessage, err := funcPool.RemoveInstance(vmIDString, images[i%len(images)], isSyncOffload)\n\t\trequire.NoError(t, err, \"Function returned error, \"+message)\n\t}\n}", "func (p *BuildAhTest) Cleanup() {\n\t// Nuke tempdir\n\tif err := os.RemoveAll(p.TempDir); err != nil {\n\t\tfmt.Printf(\"%q\\n\", err)\n\t}\n\tcleanup := p.BuildAh([]string{\"rmi\", \"-a\", \"-f\"})\n\tcleanup.WaitWithDefaultTimeout()\n}", "func (r *Reconciler) deleteMachine(\n\tctx context.Context,\n\tlog *zap.SugaredLogger,\n\tprov cloudprovidertypes.Provider,\n\tproviderName providerconfigtypes.CloudProvider,\n\tmachine *clusterv1alpha1.Machine,\n\tskipEviction bool,\n) (*reconcile.Result, error) {\n\tvar (\n\t\tshouldEvict bool\n\t\terr error\n\t)\n\n\tif !skipEviction {\n\t\tshouldEvict, err = r.shouldEvict(ctx, log, machine)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tshouldCleanUpVolumes, err := r.shouldCleanupVolumes(ctx, log, machine, providerName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar evictedSomething, deletedSomething bool\n\tvar volumesFree = true\n\tif shouldEvict {\n\t\tevictedSomething, err = eviction.New(machine.Status.NodeRef.Name, r.client, r.kubeClient).Run(ctx, log)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to evict node %s: %w\", machine.Status.NodeRef.Name, err)\n\t\t}\n\t}\n\tif shouldCleanUpVolumes {\n\t\tdeletedSomething, volumesFree, err = poddeletion.New(machine.Status.NodeRef.Name, r.client, r.kubeClient).Run(ctx, log)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to delete pods bound to volumes running on node %s: %w\", machine.Status.NodeRef.Name, err)\n\t\t}\n\t}\n\n\tif evictedSomething || deletedSomething || !volumesFree {\n\t\treturn &reconcile.Result{RequeueAfter: 10 * time.Second}, nil\n\t}\n\n\tif result, err := r.deleteCloudProviderInstance(ctx, log, prov, machine); result != nil || err != nil {\n\t\treturn result, err\n\t}\n\n\t// Delete the node object only after the instance is gone, `deleteCloudProviderInstance`\n\t// returns with a nil-error after it triggers the instance deletion but it is async for\n\t// some providers hence the instance deletion may not been executed yet\n\t// `FinalizerDeleteInstance` stays until the instance is really gone thought, so we check\n\t// for that here\n\tif sets.NewString(machine.Finalizers...).Has(FinalizerDeleteInstance) {\n\t\treturn nil, nil\n\t}\n\n\tnodes, err := r.retrieveNodesRelatedToMachine(ctx, log, machine)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := r.deleteNodeForMachine(ctx, log, nodes, machine); err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.metrics.Deprovisioning.Observe(time.Until(machine.DeletionTimestamp.Time).Abs().Seconds())\n\n\treturn nil, nil\n}", "func testWindowsNodeDeletion(t *testing.T) {\n\ttestCtx, err := NewTestContext()\n\trequire.NoError(t, err)\n\n\t// set expected node count to zero, since all Windows Nodes should be deleted in the test\n\texpectedNodeCount := int32(0)\n\t// Get all the Machines created by the e2e tests\n\t// For platform=none, the resulting slice is empty\n\te2eMachineSets, err := testCtx.client.Machine.MachineSets(clusterinfo.MachineAPINamespace).List(context.TODO(),\n\t\tmeta.ListOptions{LabelSelector: clusterinfo.MachineE2ELabel + \"=true\"})\n\trequire.NoError(t, err, \"error listing MachineSets\")\n\tvar windowsMachineSetWithLabel *mapi.MachineSet\n\tfor _, machineSet := range e2eMachineSets.Items {\n\t\tif machineSet.Spec.Selector.MatchLabels[clusterinfo.MachineOSIDLabel] == \"Windows\" {\n\t\t\twindowsMachineSetWithLabel = &machineSet\n\t\t\tbreak\n\t\t}\n\t}\n\t// skip the scale down step if there is no MachineSet with Windows label\n\tif windowsMachineSetWithLabel != nil {\n\t\t// Scale the Windows MachineSet to 0\n\t\twindowsMachineSetWithLabel.Spec.Replicas = &expectedNodeCount\n\t\t_, err = testCtx.client.Machine.MachineSets(clusterinfo.MachineAPINamespace).Update(context.TODO(),\n\t\t\twindowsMachineSetWithLabel, meta.UpdateOptions{})\n\t\trequire.NoError(t, err, \"error updating Windows MachineSet\")\n\n\t\t// we are waiting 10 minutes for all windows machines to get deleted.\n\t\terr = testCtx.waitForWindowsNodes(expectedNodeCount, true, false, false)\n\t\trequire.NoError(t, err, \"Windows node deletion failed\")\n\t}\n\tt.Run(\"BYOH node removal\", testCtx.testBYOHRemoval)\n\n\t// Cleanup all the MachineSets created by us.\n\tfor _, machineSet := range e2eMachineSets.Items {\n\t\tassert.NoError(t, testCtx.deleteMachineSet(&machineSet), \"error deleting MachineSet\")\n\t}\n\t// Phase is ignored during deletion, in this case we are just waiting for Machines to be deleted.\n\t_, err = testCtx.waitForWindowsMachines(int(expectedNodeCount), \"\", true)\n\trequire.NoError(t, err, \"Machine controller Windows machine deletion failed\")\n\n\t// TODO: Currently on vSphere it is impossible to delete a Machine after its node has been deleted.\n\t// This special casing should be removed as part of https://issues.redhat.com/browse/WINC-635\n\tif testCtx.GetType() != config.VSpherePlatformType {\n\t\t_, err = testCtx.waitForWindowsMachines(int(expectedNodeCount), \"\", false)\n\t\trequire.NoError(t, err, \"ConfigMap controller Windows machine deletion failed\")\n\t}\n\n\t// Test if prometheus configuration is updated to have no node entries in the endpoints object\n\tt.Run(\"Prometheus configuration\", testPrometheus)\n\n\t// Cleanup windows-instances ConfigMap\n\ttestCtx.deleteWindowsInstanceConfigMap()\n\n\t// Cleanup secrets created by us.\n\terr = testCtx.client.K8s.CoreV1().Secrets(\"openshift-machine-api\").Delete(context.TODO(), \"windows-user-data\", meta.DeleteOptions{})\n\trequire.NoError(t, err, \"could not delete userData secret\")\n\n\terr = testCtx.client.K8s.CoreV1().Secrets(\"openshift-windows-machine-config-operator\").Delete(context.TODO(), secrets.PrivateKeySecret, meta.DeleteOptions{})\n\trequire.NoError(t, err, \"could not delete privateKey secret\")\n\n\t// Cleanup wmco-test namespace created by us.\n\terr = testCtx.deleteNamespace(testCtx.workloadNamespace)\n\trequire.NoError(t, err, \"could not delete test namespace\")\n}", "func (c *Client) destroyContainer(ctx context.Context, id string, timeout int64) (*Message, error) {\n\t// TODO(ziren): if we just want to stop a container,\n\t// we may need lease to lock the snapshot of container,\n\t// in case, it be deleted by gc.\n\twrapperCli, err := c.Get(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get a containerd grpc client: %v\", err)\n\t}\n\n\tctx = leases.WithLease(ctx, wrapperCli.lease.ID)\n\n\tif !c.lock.TrylockWithRetry(ctx, id) {\n\t\treturn nil, errtypes.ErrLockfailed\n\t}\n\tdefer c.lock.Unlock(id)\n\n\tpack, err := c.watch.get(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if you call DestroyContainer to stop a container, will skip the hooks.\n\t// the caller need to execute the all hooks.\n\tpack.l.Lock()\n\tpack.skipStopHooks = true\n\tpack.l.Unlock()\n\tdefer func() {\n\t\tpack.l.Lock()\n\t\tpack.skipStopHooks = false\n\t\tpack.l.Unlock()\n\t}()\n\n\twaitExit := func() *Message {\n\t\treturn c.ProbeContainer(ctx, id, time.Duration(timeout)*time.Second)\n\t}\n\n\tvar msg *Message\n\n\t// TODO: set task request timeout by context timeout\n\tif err := pack.task.Kill(ctx, syscall.SIGTERM, containerd.WithKillAll); err != nil {\n\t\tif !errdefs.IsNotFound(err) {\n\t\t\treturn nil, errors.Wrap(err, \"failed to kill task\")\n\t\t}\n\t\tgoto clean\n\t}\n\t// wait for the task to exit.\n\tmsg = waitExit()\n\n\tif err := msg.RawError(); err != nil && errtypes.IsTimeout(err) {\n\t\t// timeout, use SIGKILL to retry.\n\t\tif err := pack.task.Kill(ctx, syscall.SIGKILL, containerd.WithKillAll); err != nil {\n\t\t\tif !errdefs.IsNotFound(err) {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to kill task\")\n\t\t\t}\n\t\t\tgoto clean\n\t\t}\n\t\tmsg = waitExit()\n\t}\n\n\t// ignore the error is stop time out\n\t// TODO: how to design the stop error is time out?\n\tif err := msg.RawError(); err != nil && !errtypes.IsTimeout(err) {\n\t\treturn nil, err\n\t}\n\nclean:\n\t// for normal destroy process, task.Delete() and container.Delete()\n\t// is done in ctrd/watch.go, after task exit. clean is task effect only\n\t// when unexcepted error happened in task exit process.\n\tif _, err := pack.task.Delete(ctx); err != nil {\n\t\tif !errdefs.IsNotFound(err) {\n\t\t\tlogrus.Errorf(\"failed to delete task %s again: %v\", pack.id, err)\n\t\t}\n\t}\n\tif err := pack.container.Delete(ctx); err != nil {\n\t\tif !errdefs.IsNotFound(err) {\n\t\t\treturn msg, errors.Wrap(err, \"failed to delete container\")\n\t\t}\n\t}\n\n\tlogrus.Infof(\"success to destroy container: %s\", id)\n\n\treturn msg, c.watch.remove(ctx, id)\n}", "func UntilVolumeCreated(t *testing.T) {\n\tnames := helpers.GetNames(\"UntilVolume\", 0, 1, 1, 2, 1, 0, 0, 0)\n\tnames.TearDown()\n\tdefer names.TearDown()\n\n\tout, err := helpers.GetOutput(\"safescale network list\")\n\trequire.Nil(t, err)\n\t_ = out\n\n\tfmt.Println(\"Creating network \" + names.Networks[0])\n\n\tout, err = helpers.GetOutput(\"safescale network create \" + names.Networks[0] + \" --cidr 192.168.47.0/24\")\n\trequire.Nil(t, err)\n\t_ = out\n\n\tout, err = helpers.GetOutput(\"safescale network create \" + names.Networks[0] + \" --cidr 192.168.47.0/24\")\n\trequire.NotNil(t, err)\n\trequire.True(t, strings.Contains(out, \"already exist\"))\n\n\tfmt.Println(\"Creating VM \" + names.Hosts[0])\n\n\tout, err = helpers.GetOutput(\"safescale host create \" + names.Hosts[0] + \" --public --net \" + names.Networks[0])\n\trequire.Nil(t, err)\n\t_ = out\n\n\tout, err = helpers.GetOutput(\"safescale host create \" + names.Hosts[0] + \" --public --net \" + names.Networks[0])\n\trequire.NotNil(t, err)\n\trequire.True(t, strings.Contains(out, \"already exist\") || strings.Contains(out, \"already used\"))\n\n\tout, err = helpers.GetOutput(\"safescale host inspect \" + names.Hosts[0])\n\trequire.Nil(t, err)\n\t_ = out\n\n\tfmt.Println(\"Creating VM \" + names.Hosts[1])\n\n\tout, err = helpers.GetOutput(\"safescale host create \" + names.Hosts[1] + \" --public --net \" + names.Networks[0])\n\trequire.Nil(t, err)\n\t_ = out\n\n\tout, err = helpers.GetOutput(\"safescale host create \" + names.Hosts[1] + \" --public --net \" + names.Networks[0])\n\trequire.NotNil(t, err)\n\trequire.True(t, strings.Contains(out, \"already exist\") || strings.Contains(out, \"already used\"))\n\n\tout, err = helpers.GetOutput(\"safescale volume list\")\n\trequire.Nil(t, err)\n\trequire.True(t, strings.Contains(out, \"null\"))\n\n\tfmt.Println(\"Creating Volume \" + names.Volumes[0])\n\n\tout, err = helpers.GetOutput(\"safescale volume create \" + names.Volumes[0])\n\trequire.Nil(t, err)\n\t_ = out\n\n\tout, err = helpers.GetOutput(\"safescale volume list\")\n\trequire.Nil(t, err)\n\trequire.True(t, strings.Contains(out, names.Volumes[0]))\n}", "func (cc *ClusterController) cleanup(c *cassandrav1alpha1.Cluster) error {\n\n\tfor _, r := range c.Spec.Datacenter.Racks {\n\t\tservices, err := cc.serviceLister.Services(c.Namespace).List(util.RackSelector(r, c))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error listing member services: %s\", err.Error())\n\t\t}\n\t\t// Get rack status. If it doesn't exist, the rack isn't yet created.\n\t\tstsName := util.StatefulSetNameForRack(r, c)\n\t\tsts, err := cc.statefulSetLister.StatefulSets(c.Namespace).Get(stsName)\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error getting statefulset %s: %s\", stsName, err.Error())\n\t\t}\n\t\tmemberCount := *sts.Spec.Replicas\n\t\tmemberServiceCount := int32(len(services))\n\t\t// If there are more services than members, some services need to be cleaned up\n\t\tif memberServiceCount > memberCount {\n\t\t\tmaxIndex := memberCount - 1\n\t\t\tfor _, svc := range services {\n\t\t\t\tsvcIndex, err := util.IndexFromName(svc.Name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Errorf(\"Unexpected error while parsing index from name %s : %s\", svc.Name, err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif svcIndex > maxIndex {\n\t\t\t\t\terr := cc.cleanupMemberResources(svc.Name, r, c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"error cleaning up member resources: %s\", err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlogger.Infof(\"%s/%s - Successfully cleaned up cluster.\", c.Namespace, c.Name)\n\treturn nil\n}", "func (r *ReconcileCluster) isDeleteReady(ctx context.Context, cluster *v1alpha2.Cluster) error {\n\t// TODO(vincepri): List and delete MachineDeployments, MachineSets, Machines, and\n\t// block deletion until they're all deleted.\n\n\tif cluster.Spec.InfrastructureRef != nil {\n\t\t_, err := external.Get(r.Client, cluster.Spec.InfrastructureRef, cluster.Namespace)\n\t\tif err != nil && !apierrors.IsNotFound(err) {\n\t\t\treturn errors.Wrapf(err, \"failed to get %s %q for Cluster %q in namespace %q\",\n\t\t\t\tpath.Join(cluster.Spec.InfrastructureRef.APIVersion, cluster.Spec.InfrastructureRef.Kind),\n\t\t\t\tcluster.Spec.InfrastructureRef.Name, cluster.Name, cluster.Namespace)\n\t\t} else if err == nil {\n\t\t\treturn &capierrors.RequeueAfterError{RequeueAfter: 10 * time.Second}\n\t\t}\n\t}\n\n\treturn nil\n}", "func cleanupLoop(maxAgeSeconds float64) {\n\tfor {\n\t\ttime.Sleep(60 * time.Second)\n\t\tt := time.Now()\n\t\tfor project, creationTime := range dataTimestamp {\n\t\t\tmutex.Lock()\n\t\t\tif t.Sub(creationTime).Seconds() >= maxAgeSeconds {\n\t\t\t\tdelete(projectStatus, project)\n\t\t\t\tdelete(dataTimestamp, project)\n\t\t\t}\n\t\t\tmutex.Unlock()\n\t\t}\n\t}\n}", "func (a *MemberAwaitility) WaitUntilNSTemplateSetDeleted(name string) error {\n\treturn wait.Poll(a.RetryInterval, a.Timeout, func() (done bool, err error) {\n\t\tnsTmplSet := &toolchainv1alpha1.NSTemplateSet{}\n\t\tif err := a.Client.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: a.Namespace}, nsTmplSet); err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\ta.T.Logf(\"deleted NSTemplateSet '%s'\", name)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\ta.T.Logf(\"waiting for deletion of NSTemplateSet '%s'\", name)\n\t\treturn false, nil\n\t})\n}", "func PoolDestroy(name string) error {\n\tcmd := &Cmd{}\n\treturn NvlistIoctl(zfsHandle.Fd(), ZFS_IOC_POOL_DESTROY, name, cmd, nil, nil, nil)\n}", "func (p libvirtPlugin) Destroy(id instance.ID) error {\n\tl := log.WithField(\"instance\", id)\n\tl.Info(\"Destroying VM\")\n\n\tconn, err := libvirt.NewConnect(p.URI)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Connecting to libvirt\")\n\t}\n\tdefer conn.Close()\n\n\td, err := p.lookupInstanceByID(conn, id)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Looking up domain\")\n\t}\n\n\tif err := destroyMetadataDisk(conn, d); err != nil {\n\t\tl.Errorf(\"Failed to destroy metadata disk: %s\", err)\n\t\t// Continue so we at least try and destroy the domain\n\t}\n\n\tif err := d.Destroy(); err != nil {\n\t\treturn errors.Wrap(err, \"Destroying domain\")\n\t}\n\n\treturn nil\n}", "func (w *watcher) cleanupWorker() {\n\tfor {\n\t\t// Wait a full period\n\t\ttime.Sleep(w.cleanupTimeout)\n\n\t\tselect {\n\t\tcase <-w.ctx.Done():\n\t\t\tw.stopped.Done()\n\t\t\treturn\n\t\tdefault:\n\t\t\t// Check entries for timeout\n\t\t\tvar toDelete []string\n\t\t\ttimeout := time.Now().Add(-w.cleanupTimeout)\n\t\t\tw.RLock()\n\t\t\tfor key, lastSeen := range w.deleted {\n\t\t\t\tif lastSeen.Before(timeout) {\n\t\t\t\t\tlogp.Debug(\"docker\", \"Removing container %s after cool down timeout\", key)\n\t\t\t\t\ttoDelete = append(toDelete, key)\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.RUnlock()\n\n\t\t\t// Delete timed out entries:\n\t\t\tfor _, key := range toDelete {\n\t\t\t\tcontainer := w.Container(key)\n\t\t\t\tif container != nil {\n\t\t\t\t\tw.bus.Publish(bus.Event{\n\t\t\t\t\t\t\"delete\": true,\n\t\t\t\t\t\t\"container\": container,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tw.Lock()\n\t\t\tfor _, key := range toDelete {\n\t\t\t\tdelete(w.deleted, key)\n\t\t\t\tdelete(w.containers, key)\n\t\t\t\tif w.shortID {\n\t\t\t\t\tdelete(w.containers, key[:shortIDLen])\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.Unlock()\n\t\t}\n\t}\n}", "func (s *LocalTests) deleteMachine(c *gc.C, machineId string) {\n\terr := s.testClient.StopMachine(machineId)\n\tc.Assert(err, gc.IsNil)\n\n\t// wait for machine to be stopped\n\tfor !s.pollMachineState(c, machineId, \"stopped\") {\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\terr = s.testClient.DeleteMachine(machineId)\n\tc.Assert(err, gc.IsNil)\n}", "func destroyKnative() {\n\n\t//Make command options for Knative Setup\n\tco := utils.NewCommandOptions()\n\n\t//Install Openshift Serveless and Knative Serving\n\tco.Commands = append(co.Commands, \"https://raw.githubusercontent.com/redhat-iot/iot-dev/master/yamls/knative/setup/knative-eventing.yaml\")\n\n\tco.Commands = append(co.Commands, \"https://raw.githubusercontent.com/redhat-iot/iot-dev/master/yamls/knative/setup/knative-serving.yaml\")\n\tIOStreams, _, out, _ := genericclioptions.NewTestIOStreams()\n\n\tco.SwitchContext(\"knative-eventing\")\n\n\tlog.Info(\"Remove Openshift Serverless Operator and Knative Serving\")\n\tfor commandNumber, command := range co.Commands {\n\t\tif commandNumber == 1 {\n\t\t\tco.SwitchContext(\"knative-serving\")\n\t\t}\n\t\tcmd := delete.NewCmdDelete(co.CurrentFactory, IOStreams)\n\t\tcmd.Flags().Set(\"filename\", command)\n\t\tcmd.Run(cmd, []string{})\n\t\tlog.Info(out.String())\n\t\tout.Reset()\n\t\t//Allow time for Operator to distribute to all namespaces\n\t}\n\n\t/*\n\n\t\tcurrentCSV, err := exec.Command(\"bash\", \"-c\", \"./oc get subscription serverless-operator -n openshift-operators -o jsonpath='{.status.currentCSV}'\").Output()\n\t\terr = exec.Command(\"./oc\", \"delete\", \"subscription\", \"serverless-operator\", \"-n\", \"openshift-operators\").Run()\n\t\tif err != nil {\n\t\t\t//Ignore Resource Not found error and continue, but still notify the user\n\t\t\tlog.Println(err)\n\t\t}\n\t\terr = exec.Command(\"./oc\", \"delete\", \"clusterserviceversion\", string(currentCSV), \"-n\", \"openshift-operators\").Run()\n\t\tif err != nil {\n\t\t\t//Igonore Resource Not found error and continue, but still notify the user\n\t\t\tlog.Println(err)\n\t\t}\n\t\tos.Remove(\"oc\")\n\t*/\n\n}", "func deleteOrphanedAutoCreatedKAMs(resController *ClusterWatcher) error {\n\tif logger.IsEnabled(LogTypeEntry) {\n\t\tlogger.Log(CallerName(), LogTypeEntry, \"Delete orphaned auto-created KAMs\")\n\t}\n\n\tgvr, ok := resController.getWatchGVR(kindActionMappingGVR)\n\tif !ok {\n\t\terr := fmt.Errorf(\"Unable to get GVR for KAM\")\n\t\tif logger.IsEnabled(LogTypeError) {\n\t\t\tlogger.Log(CallerName(), LogTypeError, fmt.Sprintf(\"Error in deleteOrphanedAutoCreatedKAMs: %s\", err))\n\t\t}\n\t\treturn err\n\t}\n\tvar intf = resController.plugin.dynamicClient.Resource(gvr)\n\n\t// fetch the current resource\n\tvar unstructuredList *unstructured.UnstructuredList\n\tvar err error\n\tunstructuredList, err = intf.List(metav1.ListOptions{LabelSelector: \"kappnav.kam.auto-created=true\"})\n\tif err != nil {\n\t\t// TODO: check error code. Most likely resource does not exist\n\t\treturn err\n\t}\n\n\tfor _, unstructuredObj := range unstructuredList.Items {\n\t\tvar kamResInfo = &resourceInfo{}\n\t\tresController.parseResource(&unstructuredObj, kamResInfo)\n\t\tif logger.IsEnabled(LogTypeDebug) {\n\t\t\tlogger.Log(CallerName(), LogTypeDebug,\n\t\t\t\tfmt.Sprintf(\"DeleteOrphanedAutoCreatedKAMs kam: %s\", kamResInfo.name))\n\t\t}\n\n\t\tif autoCreateKAMMap != nil {\n\t\t\tmaps := autoCreateKAMMap[kamResInfo.namespace]\n\t\t\texists, _ := maps[kamResInfo.name]\n\n\t\t\t// delete auto-create kam if no resource exists in the map\n\t\t\tif exists != kamTrue {\n\t\t\t\tif logger.IsEnabled(LogTypeDebug) {\n\t\t\t\t\tlogger.Log(CallerName(), LogTypeDebug,\n\t\t\t\t\t\tfmt.Sprintf(\"Deleting the auto-created KAM: %s/%s\", kamResInfo.namespace, kamResInfo.name))\n\t\t\t\t}\n\t\t\t\terr := deleteResource(resController, kamResInfo)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif logger.IsEnabled(LogTypeError) {\n\t\t\t\t\t\tlogger.Log(CallerName(), LogTypeError,\n\t\t\t\t\t\t\tfmt.Sprintf(\"Error deleting orphaned kam: %s/%s. Error: %s\", kamResInfo.namespace, kamResInfo.name, err))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif logger.IsEnabled(LogTypeInfo) {\n\t\t\t\t\t\tlogger.Log(CallerName(), LogTypeInfo,\n\t\t\t\t\t\t\tfmt.Sprintf(\"Deleted orphaned auto-created kam %s/%s\", kamResInfo.namespace, kamResInfo.name))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif logger.IsEnabled(LogTypeExit) {\n\t\tlogger.Log(CallerName(), LogTypeExit, \"Delete orphaned auto-created KAMs\")\n\t}\n\treturn nil\n}", "func (c *bdCommon) destroy(ctx context.Context, stack *thrapb.Stack) []*thrapb.ActionResult {\n\tar := make([]*thrapb.ActionResult, 0, len(stack.Components))\n\n\tfor _, comp := range stack.Components {\n\t\tr := &thrapb.ActionResult{\n\t\t\tAction: \"destroy\",\n\t\t\tResource: comp.ID,\n\t\t\tError: c.crt.Remove(ctx, comp.ID+\".\"+stack.ID),\n\t\t}\n\t\tar = append(ar, r)\n\t}\n\n\treturn ar\n}", "func Cleanup() {\n\tif _, err := _etcdClient.Delete(context.Background(), \"\", clientv3.WithPrefix()); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func assertCleanup(ns string, selectors ...string) {\n\tvar e error\n\tverifyCleanupFunc := func() (bool, error) {\n\t\te = nil\n\t\tfor _, selector := range selectors {\n\t\t\tresources := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"rc,svc\", \"-l\", selector, \"--no-headers\")\n\t\t\tif resources != \"\" {\n\t\t\t\te = fmt.Errorf(\"Resources left running after stop:\\n%s\", resources)\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tpods := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"pods\", \"-l\", selector, \"-o\", \"go-template={{ range .items }}{{ if not .metadata.deletionTimestamp }}{{ .metadata.name }}{{ \\\"\\\\n\\\" }}{{ end }}{{ end }}\")\n\t\t\tif pods != \"\" {\n\t\t\t\te = fmt.Errorf(\"Pods left unterminated after stop:\\n%s\", pods)\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t}\n\terr := wait.PollImmediate(500*time.Millisecond, 1*time.Minute, verifyCleanupFunc)\n\tif err != nil {\n\t\tframework.Failf(e.Error())\n\t}\n}", "func (c *LoadAgentCluster) Shutdown() {\n\tvar wg sync.WaitGroup\n\twg.Add(len(c.agents))\n\tfor _, ag := range c.agents {\n\t\tgo func(ag *client.Agent) {\n\t\t\tdefer wg.Done()\n\t\t\tif _, err := ag.Destroy(); err != nil {\n\t\t\t\tc.log.Error(\"cluster: failed to stop agent\", mlog.Err(err))\n\t\t\t}\n\t\t}(ag)\n\t}\n\twg.Wait()\n}", "func (s *Cloudformation) WaitUntilStackDeleted() (err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tstackInputs := cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(s.StackName()),\n\t}\n\n\terr = svc.WaitUntilStackDeleteComplete(&stackInputs)\n\treturn\n}", "func removeRBDLocks(instance *ec2.Instance) {\n\taddress, found := hosts[instance.InstanceId]\n\tif !found {\n\t\tglog.Errorf(\"The instance: %s was not found in the hosts map\", instance.InstanceId)\n\t\treturn\n\t}\n\tglog.Infof(\"Instance: %s, address: %s, state: %s, checking for locks\", instance.InstanceId, address, instance.State.Name)\n\n\tvar deleted = false\n\n\tfor i := 0; i < 3; i++ {\n\t\terr := rbdClient.UnlockClient(address)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to unlock the images, attempting again if possible\")\n\t\t\t<-time.After(time.Duration(5) * time.Second)\n\t\t}\n\t\tdeleted = true\n\t}\n\n\tif !deleted {\n\t\tglog.Errorf(\"Failed to unlock any images that could have been held by client: %s\", address)\n\t}\n\n\t// step: delete from the hosts map\n\tdelete(hosts, instance.InstanceId)\n}", "func TestKillRandom(t *testing.T) {\n\tprocAttr := new(os.ProcAttr)\n\tprocAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}\n\n\tclusterSize := 9\n\targGroup, etcds, err := createCluster(clusterSize, procAttr, false)\n\n\tif err != nil {\n\t\tt.Fatal(\"cannot create cluster\")\n\t}\n\n\tdefer destroyCluster(etcds)\n\n\tleaderChan := make(chan string, 1)\n\n\ttime.Sleep(3 * time.Second)\n\n\tgo leaderMonitor(clusterSize, 4, leaderChan)\n\n\ttoKill := make(map[int]bool)\n\n\tfor i := 0; i < 20; i++ {\n\t\tfmt.Printf(\"TestKillRandom Round[%d/20]\\n\", i)\n\n\t\tj := 0\n\t\tfor {\n\n\t\t\tr := rand.Int31n(9)\n\t\t\tif _, ok := toKill[int(r)]; !ok {\n\t\t\t\tj++\n\t\t\t\ttoKill[int(r)] = true\n\t\t\t}\n\n\t\t\tif j > 3 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\n\t\tfor num, _ := range toKill {\n\t\t\tetcds[num].Kill()\n\t\t\tetcds[num].Release()\n\t\t}\n\n\t\t<-leaderChan\n\n\t\tfor num, _ := range toKill {\n\t\t\tetcds[num], err = os.StartProcess(\"etcd\", argGroup[num], procAttr)\n\t\t}\n\n\t\ttoKill = make(map[int]bool)\n\t}\n\n\t<-leaderChan\n\n}", "func (b *Botanist) WaitUntilContainerRuntimeResourcesDeleted(ctx context.Context) error {\n\tvar (\n\t\tlastError *gardencorev1beta1.LastError\n\t\tcontainerRuntimes = &extensionsv1alpha1.ContainerRuntimeList{}\n\t)\n\n\tif err := b.K8sSeedClient.Client().List(ctx, containerRuntimes, client.InNamespace(b.Shoot.SeedNamespace)); err != nil {\n\t\treturn err\n\t}\n\n\tfns := make([]flow.TaskFn, 0, len(containerRuntimes.Items))\n\tfor _, containerRuntime := range containerRuntimes.Items {\n\t\tif containerRuntime.GetDeletionTimestamp() == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar (\n\t\t\tname = containerRuntime.Name\n\t\t\tnamespace = containerRuntime.Namespace\n\t\t)\n\n\t\tfns = append(fns, func(ctx context.Context) error {\n\t\t\tif err := retry.UntilTimeout(ctx, DefaultInterval, shoot.ExtensionDefaultTimeout, func(ctx context.Context) (bool, error) {\n\t\t\t\tretrievedContainerRuntime := extensionsv1alpha1.ContainerRuntime{}\n\t\t\t\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(namespace, name), &retrievedContainerRuntime); err != nil {\n\t\t\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t\t\treturn retry.Ok()\n\t\t\t\t\t}\n\t\t\t\t\treturn retry.SevereError(err)\n\t\t\t\t}\n\n\t\t\t\tif lastErr := retrievedContainerRuntime.Status.LastError; lastErr != nil {\n\t\t\t\t\tb.Logger.Errorf(\"Container runtime %s did not get deleted yet, lastError is: %s\", name, lastErr.Description)\n\t\t\t\t\tlastError = lastErr\n\t\t\t\t}\n\n\t\t\t\treturn retry.MinorError(gardencorev1beta1helper.WrapWithLastError(fmt.Errorf(\"container runtime %s is still present\", name), lastError))\n\t\t\t}); err != nil {\n\t\t\t\tmessage := \"Failed waiting for container runtime delete\"\n\t\t\t\tif lastError != nil {\n\t\t\t\t\treturn gardencorev1beta1helper.DetermineError(errors.New(lastError.Description), fmt.Sprintf(\"%s: %s\", message, lastError.Description))\n\t\t\t\t}\n\t\t\t\treturn gardencorev1beta1helper.DetermineError(err, fmt.Sprintf(\"%s: %s\", message, err.Error()))\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\treturn flow.Parallel(fns...)(ctx)\n}", "func (b *Botanist) WaitUntilNodesDeleted(ctx context.Context) error {\n\treturn retry.Until(ctx, 5*time.Second, func(ctx context.Context) (done bool, err error) {\n\t\tnodesList := &corev1.NodeList{}\n\t\tif err := b.K8sShootClient.Client().List(ctx, nodesList); err != nil {\n\t\t\treturn retry.SevereError(err)\n\t\t}\n\n\t\tif len(nodesList.Items) == 0 {\n\t\t\treturn retry.Ok()\n\t\t}\n\n\t\tb.Logger.Infof(\"Waiting until all nodes have been deleted in the shoot cluster...\")\n\t\treturn retry.MinorError(fmt.Errorf(\"not all nodes have been deleted in the shoot cluster\"))\n\t})\n}", "func TestAllocRunner_TerminalUpdate_Destroy(t *testing.T) {\n\tci.Parallel(t)\n\talloc := mock.BatchAlloc()\n\ttr := alloc.AllocatedResources.Tasks[alloc.Job.TaskGroups[0].Tasks[0].Name]\n\talloc.Job.TaskGroups[0].RestartPolicy.Attempts = 0\n\talloc.Job.TaskGroups[0].Tasks[0].RestartPolicy.Attempts = 0\n\t// Ensure task takes some time\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Driver = \"mock_driver\"\n\ttask.Config[\"run_for\"] = \"10s\"\n\talloc.AllocatedResources.Tasks[task.Name] = tr\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tdefer destroy(ar)\n\tgo ar.Run()\n\tupd := conf.StateUpdater.(*MockStateUpdater)\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\t\tif last.ClientStatus != structs.AllocClientStatusRunning {\n\t\t\treturn false, fmt.Errorf(\"got status %v; want %v\", last.ClientStatus, structs.AllocClientStatusRunning)\n\t\t}\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n\n\t// Update the alloc to be terminal which should cause the alloc runner to\n\t// stop the tasks and wait for a destroy.\n\tupdate := ar.alloc.Copy()\n\tupdate.DesiredStatus = structs.AllocDesiredStatusStop\n\tar.Update(update)\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\n\t\t// Check the status has changed.\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got client status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\t// Check the alloc directory still exists\n\t\tif _, err := os.Stat(ar.allocDir.AllocDir); err != nil {\n\t\t\treturn false, fmt.Errorf(\"alloc dir destroyed: %v\", ar.allocDir.AllocDir)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n\n\t// Send the destroy signal and ensure the AllocRunner cleans up.\n\tar.Destroy()\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\n\t\t// Check the status has changed.\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got client status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\t// Check the alloc directory was cleaned\n\t\tif _, err := os.Stat(ar.allocDir.AllocDir); err == nil {\n\t\t\treturn false, fmt.Errorf(\"alloc dir still exists: %v\", ar.allocDir.AllocDir)\n\t\t} else if !os.IsNotExist(err) {\n\t\t\treturn false, fmt.Errorf(\"stat err: %v\", err)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n}", "func KillWorkloads(clientset kubernetes.Interface) {\n\t// Look for namespace or default to default namespace\n\tnamespace := helpers.GetEnv(\"NAMESPACE\", \"default\")\n\t// Wait Group To handle the waiting for all deletes to complete\n\tvar wg sync.WaitGroup\n\twg.Add(5)\n\t// Delete all Deployments\n\tif helpers.CheckDeleteResourceAllowed(\"deployments\") {\n\t\tgo deleteDeployments(clientset, &namespace, &wg)\n\t}\n\t// Delete all Statefulsets\n\tif helpers.CheckDeleteResourceAllowed(\"statefulsets\") {\n\t\tgo deleteStatefulsets(clientset, &namespace, &wg)\n\t}\n\t// Delete Services\n\tif helpers.CheckDeleteResourceAllowed(\"services\") {\n\t\tgo deleteServices(clientset, &namespace, &wg)\n\t}\n\t// Delete All Secrets\n\tif helpers.CheckDeleteResourceAllowed(\"secrets\") {\n\t\tgo deleteSecrets(clientset, &namespace, &wg)\n\t}\n\t// Delete All Configmaps\n\tif helpers.CheckDeleteResourceAllowed(\"configmaps\") {\n\t\tgo deleteConfigMaps(clientset, &namespace, &wg)\n\t}\n\t// wait for processes to finish\n\twg.Wait()\n}", "func (s *service) waitForExit(cmd *exec.Cmd) {\n\tif err := cmd.Wait(); err != nil {\n\t\tlogrus.Debugf(\"Envoy terminated: %v\", err.Error())\n\t} else {\n\t\tlogrus.Debug(\"Envoy process exited\")\n\t}\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\tdelete(s.cmdMap, cmd)\n}", "func (a Apps) Destroy() error {\n\tfor _, app := range a {\n\t\tcmd, err := app.Destroy(false)\n\t\tif err != nil {\n\t\t\tapp.log.WithFields(logrus.Fields{\n\t\t\t\t\"app\": app.Name,\n\t\t\t\t\"cmd\": cmd,\n\t\t\t\t\"error\": err,\n\t\t\t}).Fatal(\"Failed running destroy\")\n\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (e *Environment) Destroy() error {\n\t// We set it to stopping than offline to prevent crash detection from being triggered.\n\te.SetState(environment.ProcessStoppingState)\n\n\terr := e.client.ContainerRemove(context.Background(), e.Id, types.ContainerRemoveOptions{\n\t\tRemoveVolumes: true,\n\t\tRemoveLinks: false,\n\t\tForce: true,\n\t})\n\n\te.SetState(environment.ProcessOfflineState)\n\n\t// Don't trigger a destroy failure if we try to delete a container that does not\n\t// exist on the system. We're just a step ahead of ourselves in that case.\n\t//\n\t// @see https://github.com/pterodactyl/panel/issues/2001\n\tif err != nil && client.IsErrNotFound(err) {\n\t\treturn nil\n\t}\n\n\treturn err\n}", "func deletePodAndWaitForVolsToDetach(ctx context.Context, client clientset.Interface, namespace string, pod *v1.Pod) {\n\tginkgo.By(fmt.Sprintf(\"Deleting pod: %s\", pod.Name))\n\tvolhandles := []string{}\n\tfor _, vol := range pod.Spec.Volumes {\n\t\tpv := getPvFromClaim(client, namespace, vol.PersistentVolumeClaim.ClaimName)\n\t\tvolhandles = append(volhandles, pv.Spec.CSI.VolumeHandle)\n\n\t}\n\terr := fpod.DeletePodWithWait(client, pod)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tfor _, volHandle := range volhandles {\n\t\tginkgo.By(\"Verify volume is detached from the node\")\n\t\tisDiskDetached, err := e2eVSphere.waitForVolumeDetachedFromNode(client, volHandle, pod.Spec.NodeName)\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tgomega.Expect(isDiskDetached).To(gomega.BeTrue(), fmt.Sprintf(\"Volume %q is not detached from the node %q\", volHandle, pod.Spec.NodeName))\n\t}\n}", "func Test_Static_Pool_Slow_Destroy(t *testing.T) {\n\tp, err := Initialize(\n\t\tcontext.Background(),\n\t\tfunc() *exec.Cmd { return exec.Command(\"php\", \"../tests/slow-destroy.php\", \"echo\", \"pipes\") },\n\t\tpipe.NewPipeFactory(),\n\t\t&Config{\n\t\t\tNumWorkers: 5,\n\t\t\tAllocateTimeout: time.Second,\n\t\t\tDestroyTimeout: time.Second,\n\t\t},\n\t)\n\n\tassert.NoError(t, err)\n\tassert.NotNil(t, p)\n\n\tp.Destroy(context.Background())\n}" ]
[ "0.65745693", "0.62703717", "0.62244946", "0.6161704", "0.60007936", "0.59899086", "0.57228744", "0.57008475", "0.567827", "0.56474024", "0.5596537", "0.55710554", "0.5490832", "0.5463808", "0.5462064", "0.5462064", "0.5438312", "0.5418636", "0.54070365", "0.5403932", "0.53660274", "0.5349717", "0.5330852", "0.52951485", "0.5268077", "0.5267356", "0.52608323", "0.52602494", "0.52596587", "0.5246797", "0.5245758", "0.52388424", "0.5238593", "0.52378666", "0.52375025", "0.52365243", "0.5235231", "0.5217944", "0.5201435", "0.5176623", "0.5174985", "0.5168728", "0.51634073", "0.51619345", "0.51534975", "0.514595", "0.5126944", "0.5126774", "0.51092106", "0.5108924", "0.51043725", "0.5098054", "0.5091963", "0.5091717", "0.50839376", "0.5076857", "0.50457245", "0.50307846", "0.50292486", "0.5022505", "0.50106514", "0.5006638", "0.500452", "0.49972105", "0.49946114", "0.4990956", "0.49888918", "0.49854335", "0.49813792", "0.4976736", "0.49762982", "0.49635243", "0.49612102", "0.49581292", "0.49545822", "0.49526906", "0.49492246", "0.49464327", "0.49442768", "0.49439073", "0.4938832", "0.492988", "0.49234495", "0.49226913", "0.49153486", "0.49127087", "0.49073142", "0.49012437", "0.4900286", "0.4894278", "0.48911053", "0.4887985", "0.48852283", "0.4880859", "0.48760846", "0.48754144", "0.48735985", "0.48731175", "0.48727545", "0.48610416" ]
0.7794994
0
waitForMachineController waits for machinecontroller to become running
func waitForMachineController(ctx context.Context, client dynclient.Client) error { condFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{ Namespace: resources.MachineControllerNameSpace, LabelSelector: labels.SelectorFromSet(map[string]string{ appLabelKey: resources.MachineControllerName, }), }) return fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), "waiting for machine-controller to became ready") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func waitForMachineState(api *cloudapi.Client, id, state string, timeout time.Duration) error {\n\treturn waitFor(\n\t\tfunc() (bool, error) {\n\t\t\tcurrentState, err := readMachineState(api, id)\n\t\t\treturn currentState == state, err\n\t\t},\n\t\tmachineStateChangeCheckInterval,\n\t\tmachineStateChangeTimeout,\n\t)\n}", "func WaitReady(ctx *util.Context) error {\n\tif !ctx.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\tctx.Logger.Infoln(\"Waiting for machine-controller to come up…\")\n\n\t// Wait a bit to let scheduler to react\n\ttime.Sleep(10 * time.Second)\n\n\tif err := WaitForWebhook(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller-webhook did not come up\")\n\t}\n\n\tif err := WaitForMachineController(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller did not come up\")\n\t}\n\treturn nil\n}", "func waitForWebhook(ctx context.Context, client dynclient.Client) error {\n\tcondFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{\n\t\tNamespace: resources.MachineControllerNameSpace,\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\n\t\t\tappLabelKey: resources.MachineControllerWebhookName,\n\t\t}),\n\t})\n\n\treturn fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), \"waiting for machine-controller webhook to became ready\")\n}", "func WaitReady(s *state.State) error {\n\tif !s.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\ts.Logger.Infoln(\"Waiting for machine-controller to come up...\")\n\n\tif err := cleanupStaleResources(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForWebhook(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForMachineController(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\treturn waitForCRDs(s)\n}", "func waitForMachineSetToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForMachineSetStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(machineSet *capiv1alpha1.MachineSet) bool { return machineSet != nil },\n\t)\n}", "func TestWaitUntilRunning(t *testing.T) {\n\tts := memorytopo.NewServer(\"cell1\")\n\tm := NewManager(ts)\n\n\t// Start it 3 times i.e. restart it 2 times.\n\tfor i := 1; i <= 3; i++ {\n\t\t// Run the manager in the background.\n\t\twg, _, cancel := StartManager(m)\n\n\t\t// Shut it down and wait for the shutdown to complete.\n\t\tcancel()\n\t\twg.Wait()\n\t}\n}", "func CheckMachine(machine string) error {\n\tbars := make([]*pb.ProgressBar, 0)\n\tvar wg sync.WaitGroup\n\tvar path = getPath()\n\tvar machinePath = filepath.Join(path, machine, machine+\".vbox\")\n\n\tfmt.Println(\"[+] Checking virtual machine\")\n\t// checking file location\n\tif !fileExists(machinePath) {\n\t\trepository, err := repo.NewRepositoryVM()\n\n\t\t// checking local repository\n\t\tif repository.GetURL() == \"\" {\n\t\t\treturn errors.New(\"URL is not set for downloading VBox image\")\n\t\t}\n\n\t\tdst := filepath.Join(repository.Dir(), repository.GetVersion())\n\t\tfileName := repository.Name()\n\n\t\t// download virtual machine\n\t\tif !fileExists(filepath.Join(dst, fileName)) {\n\t\t\tfmt.Println(\"[+] Starting virtual machine download\")\n\t\t\tvar bar1 *pb.ProgressBar\n\t\t\tvar err error\n\n\t\t\tfileName, bar1, err = repo.DownloadAsync(repository, &wg)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbar1.Prefix(fmt.Sprintf(\"[+] Download %-15s\", fileName))\n\t\t\tif bar1.Total > 0 {\n\t\t\t\tbars = append(bars, bar1)\n\t\t\t}\n\t\t\tpool, err := pb.StartPool(bars...)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\twg.Wait()\n\t\t\tpool.Stop()\n\n\t\t\ttime.Sleep(time.Second * 2)\n\t\t}\n\n\t\t// unzip virtual machine\n\t\terr = help.Unzip(filepath.Join(dst, fileName), path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\tif !isActive(machinePath) {\n\t\tfmt.Printf(\"[+] Registering %s\\n\", machine)\n\t\t_, err := help.ExecCmd(\"VBoxManage\",\n\t\t\t[]string{\n\t\t\t\t\"registervm\",\n\t\t\t\tfmt.Sprintf(\"%s\", machinePath),\n\t\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(\"[+] Done\")\n\t}\n\treturn nil\n}", "func (b *Botanist) WaitForControllersToBeActive(ctx context.Context) error {\n\ttype controllerInfo struct {\n\t\tname string\n\t\tlabels map[string]string\n\t}\n\n\ttype checkOutput struct {\n\t\tcontrollerName string\n\t\tready bool\n\t\terr error\n\t}\n\n\tvar (\n\t\tcontrollers = []controllerInfo{}\n\t\tpollInterval = 5 * time.Second\n\t)\n\n\t// Check whether the kube-controller-manager deployment exists\n\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(b.Shoot.SeedNamespace, v1beta1constants.DeploymentNameKubeControllerManager), &appsv1.Deployment{}); err == nil {\n\t\tcontrollers = append(controllers, controllerInfo{\n\t\t\tname: v1beta1constants.DeploymentNameKubeControllerManager,\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"app\": \"kubernetes\",\n\t\t\t\t\"role\": \"controller-manager\",\n\t\t\t},\n\t\t})\n\t} else if client.IgnoreNotFound(err) != nil {\n\t\treturn err\n\t}\n\n\treturn retry.UntilTimeout(context.TODO(), pollInterval, 90*time.Second, func(ctx context.Context) (done bool, err error) {\n\t\tvar (\n\t\t\twg sync.WaitGroup\n\t\t\tout = make(chan *checkOutput)\n\t\t)\n\n\t\tfor _, controller := range controllers {\n\t\t\twg.Add(1)\n\n\t\t\tgo func(controller controllerInfo) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tpodList := &corev1.PodList{}\n\t\t\t\terr := b.K8sSeedClient.Client().List(ctx, podList,\n\t\t\t\t\tclient.InNamespace(b.Shoot.SeedNamespace),\n\t\t\t\t\tclient.MatchingLabels(controller.labels))\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check that only one replica of the controller exists.\n\t\t\t\tif len(podList.Items) != 1 {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for %s to have exactly one replica\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Check that the existing replica is not in getting deleted.\n\t\t\t\tif podList.Items[0].DeletionTimestamp != nil {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for a new replica of %s\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check if the controller is active by reading its leader election record.\n\t\t\t\tleaderElectionRecord, err := common.ReadLeaderElectionRecord(b.K8sShootClient, resourcelock.EndpointsResourceLock, metav1.NamespaceSystem, controller.name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif delta := metav1.Now().UTC().Sub(leaderElectionRecord.RenewTime.Time.UTC()); delta <= pollInterval-time.Second {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, ready: true}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tb.Logger.Infof(\"Waiting for %s to be active\", controller.name)\n\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t}(controller)\n\t\t}\n\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tclose(out)\n\t\t}()\n\n\t\tfor result := range out {\n\t\t\tif result.err != nil {\n\t\t\t\treturn retry.SevereError(fmt.Errorf(\"could not check whether controller %s is active: %+v\", result.controllerName, result.err))\n\t\t\t}\n\t\t\tif !result.ready {\n\t\t\t\treturn retry.MinorError(fmt.Errorf(\"controller %s is not active\", result.controllerName))\n\t\t\t}\n\t\t}\n\n\t\treturn retry.Ok()\n\t})\n}", "func waitForCRDs(s *state.State) error {\n\tcondFn := clientutil.CRDsReadyCondition(s.Context, s.DynamicClient, CRDNames())\n\terr := wait.PollUntilContextTimeout(s.Context, 5*time.Second, 3*time.Minute, false, condFn.WithContext())\n\n\treturn fail.KubeClient(err, \"waiting for machine-controller CRDs to became ready\")\n}", "func (c *EC2) WaitUntilSystemStatusOk(input *DescribeInstanceStatusInput) error {\n\treturn c.WaitUntilSystemStatusOkWithContext(aws.BackgroundContext(), input)\n}", "func waitForApiServerToBeUp(svcMasterIp string, sshClientConfig *ssh.ClientConfig,\n\ttimeout time.Duration) error {\n\tkubeConfigPath := GetAndExpectStringEnvVar(gcKubeConfigPath)\n\twaitErr := wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\tcmd := fmt.Sprintf(\"kubectl get ns,sc --kubeconfig %s\",\n\t\t\tkubeConfigPath)\n\t\tframework.Logf(\"Invoking command '%v' on host %v\", cmd,\n\t\t\tsvcMasterIp)\n\t\tcmdResult, err := sshExec(sshClientConfig, svcMasterIp,\n\t\t\tcmd)\n\t\tframework.Logf(\"result %v\", cmdResult)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif err == nil {\n\t\t\tframework.Logf(\"Apiserver is fully up\")\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn waitErr\n}", "func (rcc *rotateCertsCmd) waitForControlPlaneReadiness() error {\n\tlog.Info(\"Checking health of control plane components\")\n\tpods := make([]string, 0)\n\tfor _, n := range rcc.cs.Properties.GetMasterVMNameList() {\n\t\tfor _, c := range []string{kubeAddonManager, kubeAPIServer, kubeControllerManager, kubeScheduler} {\n\t\t\tpods = append(pods, fmt.Sprintf(\"%s-%s\", c, n))\n\t\t}\n\t}\n\tif err := ops.WaitForReady(rcc.kubeClient, metav1.NamespaceSystem, pods, rotateCertsDefaultInterval, rotateCertsDefaultTimeout, rcc.nodes); err != nil {\n\t\treturn errors.Wrap(err, \"waiting for control plane containers to reach the Ready state within the timeout period\")\n\t}\n\treturn nil\n}", "func (s *LocalTests) createMachine(c *gc.C) *cloudapi.Machine {\n\tmachine, err := s.testClient.CreateMachine(cloudapi.CreateMachineOpts{Package: localPackageName, Image: localImageID})\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(machine, gc.NotNil)\n\n\t// wait for machine to be provisioned\n\tfor !s.pollMachineState(c, machine.Id, \"running\") {\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\treturn machine\n}", "func AddMachineControllerToManager(ctx *context.ControllerManagerContext, mgr manager.Manager) error {\n\n\tvar (\n\t\tcontrolledType = &infrav1.VSphereMachine{}\n\t\tcontrolledTypeName = reflect.TypeOf(controlledType).Elem().Name()\n\t\tcontrolledTypeGVK = infrav1.GroupVersion.WithKind(controlledTypeName)\n\n\t\tcontrollerNameShort = fmt.Sprintf(\"%s-controller\", strings.ToLower(controlledTypeName))\n\t\tcontrollerNameLong = fmt.Sprintf(\"%s/%s/%s\", ctx.Namespace, ctx.Name, controllerNameShort)\n\t)\n\n\t// Build the controller context.\n\tcontrollerContext := &context.ControllerContext{\n\t\tControllerManagerContext: ctx,\n\t\tName: controllerNameShort,\n\t\tRecorder: record.New(mgr.GetEventRecorderFor(controllerNameLong)),\n\t\tLogger: ctx.Logger.WithName(controllerNameShort),\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\t// Watch the controlled, infrastructure resource.\n\t\tFor(controlledType).\n\t\t// Watch any VSphereVM resources owned by the controlled type.\n\t\tWatches(\n\t\t\t&source.Kind{Type: &infrav1.VSphereVM{}},\n\t\t\t&handler.EnqueueRequestForOwner{OwnerType: controlledType, IsController: false},\n\t\t).\n\t\t// Watch the CAPI resource that owns this infrastructure resource.\n\t\tWatches(\n\t\t\t&source.Kind{Type: &clusterv1.Machine{}},\n\t\t\t&handler.EnqueueRequestsFromMapFunc{\n\t\t\t\tToRequests: clusterutilv1.MachineToInfrastructureMapFunc(controlledTypeGVK),\n\t\t\t},\n\t\t).\n\t\t// Watch a GenericEvent channel for the controlled resource.\n\t\t//\n\t\t// This is useful when there are events outside of Kubernetes that\n\t\t// should cause a resource to be synchronized, such as a goroutine\n\t\t// waiting on some asynchronous, external task to complete.\n\t\tWatches(\n\t\t\t&source.Channel{Source: ctx.GetGenericEventChannelFor(controlledTypeGVK)},\n\t\t\t&handler.EnqueueRequestForObject{},\n\t\t).\n\t\tComplete(machineReconciler{ControllerContext: controllerContext})\n}", "func waitForHelmRunning(ctx context.Context, configPath string) error {\n\tfor {\n\t\tcmd := exec.Command(\"helm\", \"ls\", \"--kubeconfig\", configPath)\n\t\tvar out bytes.Buffer\n\t\tcmd.Stderr = &out\n\t\tcmd.Run()\n\t\tif out.String() == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.Wrap(ctx.Err(), \"timed out waiting for helm to become ready\")\n\t\tcase <-time.After(5 * time.Second):\n\t\t}\n\t}\n}", "func AddMachineControllerToManager(ctx *context.ControllerManagerContext, mgr manager.Manager) error {\n\n\tvar (\n\t\tcontrolledType = &infrav1.VSphereMachine{}\n\t\tcontrolledTypeName = reflect.TypeOf(controlledType).Elem().Name()\n\t\tcontrolledTypeGVK = infrav1.GroupVersion.WithKind(controlledTypeName)\n\n\t\tcontrollerNameShort = fmt.Sprintf(\"%s-controller\", strings.ToLower(controlledTypeName))\n\t\tcontrollerNameLong = fmt.Sprintf(\"%s/%s/%s\", ctx.Namespace, ctx.Name, controllerNameShort)\n\t)\n\n\t// Build the controller context.\n\tcontrollerContext := &context.ControllerContext{\n\t\tControllerManagerContext: ctx,\n\t\tName: controllerNameShort,\n\t\tRecorder: record.New(mgr.GetEventRecorderFor(controllerNameLong)),\n\t\tLogger: ctx.Logger.WithName(controllerNameShort),\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\t// Watch the controlled, infrastructure resource.\n\t\tFor(controlledType).\n\t\t// Watch the CAPI resource that owns this infrastructure resource.\n\t\tWatches(\n\t\t\t&source.Kind{Type: &clusterv1.Machine{}},\n\t\t\t&handler.EnqueueRequestsFromMapFunc{\n\t\t\t\tToRequests: clusterutilv1.MachineToInfrastructureMapFunc(controlledTypeGVK),\n\t\t\t},\n\t\t).\n\t\t// Watch a GenericEvent channel for the controlled resource.\n\t\t//\n\t\t// This is useful when there are events outside of Kubernetes that\n\t\t// should cause a resource to be synchronized, such as a goroutine\n\t\t// waiting on some asynchronous, external task to complete.\n\t\tWatches(\n\t\t\t&source.Channel{Source: ctx.GetGenericEventChannelFor(controlledTypeGVK)},\n\t\t\t&handler.EnqueueRequestForObject{},\n\t\t).\n\t\tComplete(machineReconciler{ControllerContext: controllerContext})\n}", "func (c *Controller) waitForShutdown(stopCh <-chan struct{}) {\n\t<-stopCh\n\tc.Queue.ShutDown()\n\tlog.Debug(\"pgcluster Contoller: received stop signal, worker queue told to shutdown\")\n}", "func Wait(dev *model.Dev, okStatusList []config.UpState) error {\n\toktetoLog.Spinner(\"Activating your development container...\")\n\toktetoLog.StartSpinner()\n\tdefer oktetoLog.StopSpinner()\n\n\tstop := make(chan os.Signal, 1)\n\tsignal.Notify(stop, os.Interrupt)\n\texit := make(chan error, 1)\n\n\tgo func() {\n\n\t\tticker := time.NewTicker(500 * time.Millisecond)\n\t\tfor {\n\t\t\tstatus, err := config.GetState(dev.Name, dev.Namespace)\n\t\t\tif err != nil {\n\t\t\t\texit <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif status == config.Failed {\n\t\t\t\texit <- fmt.Errorf(\"your development container has failed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, okStatus := range okStatusList {\n\t\t\t\tif status == okStatus {\n\t\t\t\t\texit <- nil\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\t<-ticker.C\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-stop:\n\t\toktetoLog.Infof(\"CTRL+C received, starting shutdown sequence\")\n\t\toktetoLog.StopSpinner()\n\t\treturn oktetoErrors.ErrIntSig\n\tcase err := <-exit:\n\t\tif err != nil {\n\t\t\toktetoLog.Infof(\"exit signal received due to error: %s\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Controller) waitForShutdown(stopCh <-chan struct{}) {\n\t<-stopCh\n\tc.workqueue.ShutDown()\n\tlog.Debug(\"Namespace Contoller: received stop signal, worker queue told to shutdown\")\n}", "func (r *volumeReactor) waitForIdle() {\n\tr.ctrl.runningOperations.WaitForCompletion()\n\t// Check every 10ms if the controller does something and stop if it's\n\t// idle.\n\toldChanges := -1\n\tfor {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t\tchanges := r.GetChangeCount()\n\t\tif changes == oldChanges {\n\t\t\t// No changes for last 10ms -> controller must be idle.\n\t\t\tbreak\n\t\t}\n\t\toldChanges = changes\n\t}\n}", "func (r *volumeReactor) waitForIdle() {\n\tr.ctrl.runningOperations.WaitForCompletion()\n\t// Check every 10ms if the controller does something and stop if it's\n\t// idle.\n\toldChanges := -1\n\tfor {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t\tchanges := r.getChangeCount()\n\t\tif changes == oldChanges {\n\t\t\t// No changes for last 10ms -> controller must be idle.\n\t\t\tbreak\n\t\t}\n\t\toldChanges = changes\n\t}\n}", "func waitForConductor(ctx context.Context, client *gophercloud.ServiceClient) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for conductor API to become available...\")\n\t\t\tdriverCount := 0\n\n\t\t\tdrivers.ListDrivers(client, drivers.ListDriversOpts{\n\t\t\t\tDetail: false,\n\t\t\t}).EachPage(func(page pagination.Page) (bool, error) {\n\t\t\t\tactual, err := drivers.ExtractDrivers(page)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tdriverCount += len(actual)\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\t// If we have any drivers, conductor is up.\n\t\t\tif driverCount > 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func (k *kubelet) waitForNodeReady() error {\n\tkc, _ := k.config.AdminConfig.ToYAMLString() //nolint:errcheck // This is checked in Validate().\n\n\tc, err := client.NewClient([]byte(kc))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating kubernetes client: %w\", err)\n\t}\n\n\treturn c.WaitForNodeReady(k.config.Name)\n}", "func (f *TestFramework) getWindowsMachines(vmCount int, skipVMSetup bool) ([]mapi.Machine, error) {\n\tlog.Print(\"Waiting for Machines...\")\n\twindowsOSLabel := \"machine.openshift.io/os-id\"\n\tvar provisionedMachines []mapi.Machine\n\t// it takes approximately 12 minutes in the CI for all the machines to appear.\n\ttimeOut := 12 * time.Minute\n\tif skipVMSetup {\n\t\ttimeOut = 1 * time.Minute\n\t}\n\tstartTime := time.Now()\n\tfor i := 0; time.Since(startTime) <= timeOut; i++ {\n\t\tallMachines := &mapi.MachineList{}\n\t\tallMachines, err := f.machineClient.Machines(\"openshift-machine-api\").List(context.TODO(), metav1.ListOptions{LabelSelector: windowsOSLabel})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list machines: %v\", err)\n\t\t}\n\t\tprovisionedMachines = []mapi.Machine{}\n\n\t\tphaseProvisioned := \"Provisioned\"\n\n\t\tfor _, machine := range allMachines.Items {\n\t\t\tinstanceStatus := machine.Status\n\t\t\tif instanceStatus.Phase != nil && *instanceStatus.Phase == phaseProvisioned {\n\t\t\t\tprovisionedMachines = append(provisionedMachines, machine)\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(5 * time.Second)\n\t}\n\tif skipVMSetup {\n\t\tif vmCount == 0 {\n\t\t\treturn nil, fmt.Errorf(\"no Windows VMs found\")\n\t\t}\n\t\treturn provisionedMachines, nil\n\t}\n\tif vmCount == len(provisionedMachines) {\n\t\treturn provisionedMachines, nil\n\t}\n\treturn nil, fmt.Errorf(\"expected VM count %d but got %d\", vmCount, len(provisionedMachines))\n}", "func waitForSystemTime() {\n\ttime.Sleep(150 * time.Millisecond)\n}", "func Control(mk utils.CommandMaker, clk utils.Timer, lg Logger) {\n\tmaker = mk\n\tclock = clk\n\tlogger = lg\n\n\tacquireData()\n\n\terr := initClient()\n\tif err != nil {\n\t\tlogger.LogFatalf(\"Control: unable to initialize gRPC client: %v\", err)\n\t}\n\n\tdefer destroyEnvironment()\n\n\tinitEnvironment()\n\ttok, err := getToken()\n\tif err != nil {\n\t\tlogger.LogFatalf(\"Control: could not acquire device token: %v\", err)\n\t}\n\tdeviceToken = tok\n\tps := makeProbes()\n\trwg, err := startResolver()\n\tif err != nil {\n\t\tlogger.LogFatalf(\"Control: unable to start resolver: %v\", err)\n\t}\n\tpwg := startProbes(ps)\n\n\terr = communicate()\n\tif err != nil {\n\t\tlogger.LogErrorf(\"Control: communication error, %v\", err)\n\t}\n\n\tstopProbes(pwg)\n\tstopResolver(rwg)\n\n\terr = confirmStop()\n\n\t// Connection was lost to the controller, so assume it has terminated and delete VM instance\n\tif err != nil {\n\t\tdeleteVM()\n\t}\n}", "func WaitDestroy(s *state.State) error {\n\ts.Logger.Info(\"Waiting for all machines to get deleted...\")\n\n\treturn wait.PollUntilContextTimeout(s.Context, 5*time.Second, 5*time.Minute, false, func(ctx context.Context) (bool, error) {\n\t\tlist := &clusterv1alpha1.MachineList{}\n\t\tif err := s.DynamicClient.List(ctx, list, dynclient.InNamespace(resources.MachineControllerNameSpace)); err != nil {\n\t\t\treturn false, fail.KubeClient(err, \"getting %T\", list)\n\t\t}\n\t\tif len(list.Items) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t})\n}", "func waitForSystemdActiveState(units []string, maxAttempts int) (errch chan error) {\n\terrchan := make(chan error)\n\tvar wg sync.WaitGroup\n\tfor _, name := range units {\n\t\twg.Add(1)\n\t\tgo checkSystemdActiveState(name, maxAttempts, &wg, errchan)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(errchan)\n\t}()\n\n\treturn errchan\n}", "func StartControllers(s *options.MCMServer,\n\tcontrolCoreKubeconfig *rest.Config,\n\ttargetCoreKubeconfig *rest.Config,\n\tcontrolMachineClientBuilder machinecontroller.ClientBuilder,\n\tcontrolCoreClientBuilder corecontroller.ClientBuilder,\n\ttargetCoreClientBuilder corecontroller.ClientBuilder,\n\trecorder record.EventRecorder,\n\tstop <-chan struct{}) error {\n\n\tklog.V(5).Info(\"Getting available resources\")\n\tavailableResources, err := getAvailableResources(controlCoreClientBuilder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontrolMachineClient := controlMachineClientBuilder.ClientOrDie(controllerManagerAgentName).MachineV1alpha1()\n\n\tcontrolCoreKubeconfig = rest.AddUserAgent(controlCoreKubeconfig, controllerManagerAgentName)\n\tcontrolCoreClient, err := kubernetes.NewForConfig(controlCoreKubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\n\ttargetCoreKubeconfig = rest.AddUserAgent(targetCoreKubeconfig, controllerManagerAgentName)\n\ttargetCoreClient, err := kubernetes.NewForConfig(targetCoreKubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\n\tif availableResources[machineGVR] || availableResources[machineSetGVR] || availableResources[machineDeploymentGVR] {\n\t\tklog.V(5).Infof(\"Creating shared informers; resync interval: %v\", s.MinResyncPeriod)\n\n\t\tcontrolMachineInformerFactory := machineinformers.NewFilteredSharedInformerFactory(\n\t\t\tcontrolMachineClientBuilder.ClientOrDie(\"control-machine-shared-informers\"),\n\t\t\ts.MinResyncPeriod.Duration,\n\t\t\ts.Namespace,\n\t\t\tnil,\n\t\t)\n\n\t\tcontrolCoreInformerFactory := coreinformers.NewFilteredSharedInformerFactory(\n\t\t\tcontrolCoreClientBuilder.ClientOrDie(\"control-core-shared-informers\"),\n\t\t\ts.MinResyncPeriod.Duration,\n\t\t\ts.Namespace,\n\t\t\tnil,\n\t\t)\n\n\t\ttargetCoreInformerFactory := coreinformers.NewSharedInformerFactory(\n\t\t\ttargetCoreClientBuilder.ClientOrDie(\"target-core-shared-informers\"),\n\t\t\ts.MinResyncPeriod.Duration,\n\t\t)\n\n\t\t// All shared informers are v1alpha1 API level\n\t\tmachineSharedInformers := controlMachineInformerFactory.Machine().V1alpha1()\n\n\t\tklog.V(5).Infof(\"Creating controllers...\")\n\t\tmcmcontroller, err := mcmcontroller.NewController(\n\t\t\ts.Namespace,\n\t\t\tcontrolMachineClient,\n\t\t\tcontrolCoreClient,\n\t\t\ttargetCoreClient,\n\t\t\ttargetCoreInformerFactory.Core().V1().PersistentVolumeClaims(),\n\t\t\ttargetCoreInformerFactory.Core().V1().PersistentVolumes(),\n\t\t\tcontrolCoreInformerFactory.Core().V1().Secrets(),\n\t\t\ttargetCoreInformerFactory.Core().V1().Nodes(),\n\t\t\tmachineSharedInformers.OpenStackMachineClasses(),\n\t\t\tmachineSharedInformers.AWSMachineClasses(),\n\t\t\tmachineSharedInformers.AzureMachineClasses(),\n\t\t\tmachineSharedInformers.GCPMachineClasses(),\n\t\t\tmachineSharedInformers.AlicloudMachineClasses(),\n\t\t\tmachineSharedInformers.PacketMachineClasses(),\n\t\t\tmachineSharedInformers.Machines(),\n\t\t\tmachineSharedInformers.MachineSets(),\n\t\t\tmachineSharedInformers.MachineDeployments(),\n\t\t\trecorder,\n\t\t\ts.SafetyOptions,\n\t\t\ts.NodeConditions,\n\t\t\ts.BootstrapTokenAuthExtraGroups,\n\t\t\ts.DeleteMigratedMachineClass,\n\t\t\ts.AutoscalerScaleDownAnnotationDuringRollout,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.V(1).Info(\"Starting shared informers\")\n\n\t\tcontrolMachineInformerFactory.Start(stop)\n\t\tcontrolCoreInformerFactory.Start(stop)\n\t\ttargetCoreInformerFactory.Start(stop)\n\n\t\tklog.V(5).Info(\"Running controller\")\n\t\tgo mcmcontroller.Run(int(s.ConcurrentNodeSyncs), stop)\n\n\t} else {\n\t\treturn fmt.Errorf(\"unable to start machine controller: API GroupVersion %q or %q or %q is not available; \\nFound: %#v\", machineGVR, machineSetGVR, machineDeploymentGVR, availableResources)\n\t}\n\n\tselect {}\n}", "func (machine *Machine) Create(e *expect.GExpect, root *Root, server *Server) error {\n\ttasks := []*Task{\n\t\t{\n\t\t\tInputs: []string{\n\t\t\t\t`cd('/')`,\n\t\t\t\t`pwd()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\t`edit:/`,\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`\nif '%s' == 'UnixMachine':\n\tcmo.createUnixMachine('%s')\n\tprint 'XxXsuccessXxX'\nelif '%[1]s' == 'Machine':\n\tcmo.createUnixMachine('%[2]s')\n\tprint 'XxXsuccessXxX'\nelse:\n\tprint 'XxXfailedXxX'\n`, machine.Type, machine.Name),\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\t`XxXsuccessXxX`,\n\t\t\t\t`weblogic.descriptor.BeanAlreadyExistsException: Bean already exists`,\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cd('/Machines/%s/NodeManager/%[1]s')`, machine.Name),\n\t\t\t\t`pwd()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`'edit:/Machines/%s/NodeManager/%[1]s'`, machine.Name),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cmo.setListenAddress('%s')`, machine.Host),\n\t\t\t\t`cmo.getListenAddress()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`'%s'`, machine.Host),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cmo.setListenPort(%s)`, machine.Port),\n\t\t\t\t`cmo.getListenPort()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`%s`, machine.Port),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cmo.setNMType('%s')`, machine.Protocol),\n\t\t\t\t`cmo.getNMType()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(\"'%s'\", machine.Protocol),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cd('/Servers/%s')`, server.Name),\n\t\t\t\t`pwd()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`'edit:/Servers/%s'`, server.Name),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cmo.setMachine(getMBean('/Machines/%s'))`, machine.Name),\n\t\t\t\t`cmo.getMachine()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`\\[MBeanServerInvocationHandler\\]com.bea:Name=%s,Type=%s`, machine.Name, machine.Type),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t}\n\tfor _, task := range tasks {\n\t\tif err := RunTask(task, \"Machine-Create\", e); err != nil {\n\t\t\tserver.ReturnStatus = ret.Failed\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (m *Manager) waitForFinish() {\n\tm.state.wg.Wait()\n}", "func waitForRunning(s drmaa.Session, jobId string, hostCh chan string) {\n\t// Wait for running job\n\td, _ := time.ParseDuration(\"500ms\")\n\tps, _ := s.JobPs(jobId)\n\tfor ps != drmaa.PsRunning {\n\t\ttime.Sleep(d)\n\t\tps, _ = s.JobPs(jobId)\n\t}\n\n\t// Get hostname\n\tjobStatus, err := gestatus.GetJobStatus(&s, jobId)\n\tif err != nil {\n\t\tfmt.Printf(\"Error in getting hostname for job %s: %s\\n\", jobId, err.Error())\n\t\thostCh <- \"\"\n\t\treturn\n\t}\n\thostname := jobStatus.DestinationHostList()\n\thostCh <- strings.Join(hostname, \"\")\n}", "func (v *MachineVM) Stop(name string, _ machine.StopOptions) error {\n\t// check if the qmp socket is there. if not, qemu instance is gone\n\tif _, err := os.Stat(v.QMPMonitor.Address); os.IsNotExist(err) {\n\t\t// Right now it is NOT an error to stop a stopped machine\n\t\tlogrus.Debugf(\"QMP monitor socket %v does not exist\", v.QMPMonitor.Address)\n\t\treturn nil\n\t}\n\tqmpMonitor, err := qmp.NewSocketMonitor(v.QMPMonitor.Network, v.QMPMonitor.Address, v.QMPMonitor.Timeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Simple JSON formation for the QAPI\n\tstopCommand := struct {\n\t\tExecute string `json:\"execute\"`\n\t}{\n\t\tExecute: \"system_powerdown\",\n\t}\n\tinput, err := json.Marshal(stopCommand)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := qmpMonitor.Connect(); err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := qmpMonitor.Disconnect(); err != nil {\n\t\t\tlogrus.Error(err)\n\t\t}\n\t}()\n\tif _, err = qmpMonitor.Run(input); err != nil {\n\t\treturn err\n\t}\n\tqemuSocketFile, pidFile, err := v.getSocketandPid()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := os.Stat(pidFile); os.IsNotExist(err) {\n\t\tlogrus.Infof(\"pid file %s does not exist\", pidFile)\n\t\treturn nil\n\t}\n\tpidString, err := ioutil.ReadFile(pidFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpidNum, err := strconv.Atoi(string(pidString))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp, err := os.FindProcess(pidNum)\n\tif p == nil && err != nil {\n\t\treturn err\n\t}\n\t// Kill the process\n\tif err := p.Kill(); err != nil {\n\t\treturn err\n\t}\n\t// Remove the pidfile\n\tif err := os.Remove(pidFile); err != nil && !errors.Is(err, os.ErrNotExist) {\n\t\tlogrus.Warn(err)\n\t}\n\t// Remove socket\n\treturn os.Remove(qemuSocketFile)\n}", "func (envManager *TestEnvManager) WaitUntilReady() (bool, error) {\n\tlog.Println(\"Start checking components' status\")\n\tretry := u.Retrier{\n\t\tBaseDelay: 1 * time.Second,\n\t\tMaxDelay: 10 * time.Second,\n\t\tRetries: 8,\n\t}\n\n\tready := false\n\tretryFn := func(_ context.Context, i int) error {\n\t\tfor _, comp := range envManager.testEnv.GetComponents() {\n\t\t\tif alive, err := comp.IsAlive(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to comfirm compoment %s is alive %v\", comp.GetName(), err)\n\t\t\t} else if !alive {\n\t\t\t\treturn fmt.Errorf(\"component %s is not alive\", comp.GetName())\n\t\t\t}\n\t\t}\n\n\t\tready = true\n\t\tlog.Println(\"All components are ready\")\n\t\treturn nil\n\t}\n\n\t_, err := retry.Retry(context.Background(), retryFn)\n\treturn ready, err\n}", "func (rcc *rotateCertsCmd) waitForKubeSystemReadiness() error {\n\tlog.Info(\"Checking health of all kube-system pods\")\n\ttimeout := time.Duration(len(rcc.nodes)) * time.Duration(float64(time.Minute)*1.25)\n\tif rotateCertsDefaultTimeout > timeout {\n\t\ttimeout = rotateCertsDefaultTimeout\n\t}\n\tif err := ops.WaitForAllInNamespaceReady(rcc.kubeClient, metav1.NamespaceSystem, rotateCertsDefaultInterval, timeout, rcc.nodes); err != nil {\n\t\treturn errors.Wrap(err, \"waiting for kube-system containers to reach the Ready state within the timeout period\")\n\t}\n\treturn nil\n}", "func waitForClusterProvisioned(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForClusterStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(cluster *capiv1alpha1.Cluster) bool {\n\t\t\tstatus, err := controller.ClusterStatusFromClusterAPI(cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn status.Provisioned\n\t\t},\n\t)\n}", "func (mgr *l3Manager) waitBackend() {\n\tlog.Printf(\"L3: Waiting backend to terminate\")\n\t<-mgr.done\n\tlog.Printf(\"L3: Backend terminated\")\n}", "func (c *ClientManager) WaitInstanceUntilReady(id int, until time.Time) error {\n\tfor {\n\t\tvirtualGuest, found, err := c.GetInstance(id, \"id, lastOperatingSystemReload[id,modifyDate], activeTransaction[id,transactionStatus.name], provisionDate, powerState.keyName\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !found {\n\t\t\treturn bosherr.WrapErrorf(err, \"SoftLayer virtual guest '%d' does not exist\", id)\n\t\t}\n\n\t\tlastReload := virtualGuest.LastOperatingSystemReload\n\t\tactiveTxn := virtualGuest.ActiveTransaction\n\t\tprovisionDate := virtualGuest.ProvisionDate\n\n\t\t// if lastReload != nil && lastReload.ModifyDate != nil {\n\t\t// \tfmt.Println(\"lastReload: \", (*lastReload.ModifyDate).Format(time.RFC3339))\n\t\t// }\n\t\t// if activeTxn != nil && activeTxn.TransactionStatus != nil && activeTxn.TransactionStatus.Name != nil {\n\t\t// \tfmt.Println(\"activeTxn: \", *activeTxn.TransactionStatus.Name)\n\t\t// }\n\t\t// if provisionDate != nil {\n\t\t// \tfmt.Println(\"provisionDate: \", (*provisionDate).Format(time.RFC3339))\n\t\t// }\n\n\t\treloading := activeTxn != nil && lastReload != nil && *activeTxn.Id == *lastReload.Id\n\t\tif provisionDate != nil && !reloading {\n\t\t\t// fmt.Println(\"power state:\", *virtualGuest.PowerState.KeyName)\n\t\t\tif *virtualGuest.PowerState.KeyName == \"RUNNING\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tnow := time.Now()\n\t\tif now.After(until) {\n\t\t\treturn bosherr.Errorf(\"Power on virtual guest with id %d Time Out!\", *virtualGuest.Id)\n\t\t}\n\n\t\tmin := math.Min(float64(10.0), float64(until.Sub(now)))\n\t\ttime.Sleep(time.Duration(min) * time.Second)\n\t}\n}", "func Run(s *options.MCMServer) error {\n\t// To help debugging, immediately log version\n\tklog.V(4).Infof(\"Version: %+v\", version.Get())\n\tif err := s.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\n\t//kubeconfig for the cluster for which machine-controller-manager will create machines.\n\ttargetkubeconfig, err := clientcmd.BuildConfigFromFlags(\"\", s.TargetKubeconfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontrolkubeconfig := targetkubeconfig\n\n\tif s.ControlKubeconfig != \"\" {\n\t\tif s.ControlKubeconfig == \"inClusterConfig\" {\n\t\t\t//use inClusterConfig when controller is running inside clus\n\t\t\tcontrolkubeconfig, err = clientcmd.BuildConfigFromFlags(\"\", \"\")\n\t\t} else {\n\t\t\t//kubeconfig for the seedcluster where MachineCRDs are supposed to be registered.\n\t\t\tcontrolkubeconfig, err = clientcmd.BuildConfigFromFlags(\"\", s.ControlKubeconfig)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// PROTOBUF WONT WORK\n\t// kubeconfig.ContentConfig.ContentType = s.ContentType\n\t// Override kubeconfig qps/burst settings from flags\n\ttargetkubeconfig.QPS = s.KubeAPIQPS\n\tcontrolkubeconfig.QPS = s.KubeAPIQPS\n\ttargetkubeconfig.Burst = int(s.KubeAPIBurst)\n\tcontrolkubeconfig.Burst = int(s.KubeAPIBurst)\n\ttargetkubeconfig.Timeout = targetkubeconfigTimeout\n\tcontrolkubeconfig.Timeout = controlkubeconfigTimeout\n\n\tkubeClientControl, err := kubernetes.NewForConfig(\n\t\trest.AddUserAgent(controlkubeconfig, \"machine-controller-manager\"),\n\t)\n\tif err != nil {\n\t\tklog.Fatalf(\"Invalid API configuration for kubeconfig-control: %v\", err)\n\t}\n\n\tleaderElectionClient := kubernetes.NewForConfigOrDie(rest.AddUserAgent(controlkubeconfig, \"machine-leader-election\"))\n\tklog.V(4).Info(\"Starting http server and mux\")\n\tgo startHTTP(s)\n\n\trecorder := createRecorder(kubeClientControl)\n\n\trun := func(ctx context.Context) {\n\t\tvar stop <-chan struct{}\n\t\t// Control plane client used to interact with machine APIs\n\t\tcontrolMachineClientBuilder := machinecontroller.SimpleClientBuilder{\n\t\t\tClientConfig: controlkubeconfig,\n\t\t}\n\t\t// Control plane client used to interact with core kubernetes objects\n\t\tcontrolCoreClientBuilder := corecontroller.SimpleControllerClientBuilder{\n\t\t\tClientConfig: controlkubeconfig,\n\t\t}\n\t\t// Target plane client used to interact with core kubernetes objects\n\t\ttargetCoreClientBuilder := corecontroller.SimpleControllerClientBuilder{\n\t\t\tClientConfig: targetkubeconfig,\n\t\t}\n\n\t\terr := StartControllers(\n\t\t\ts,\n\t\t\tcontrolkubeconfig,\n\t\t\ttargetkubeconfig,\n\t\t\tcontrolMachineClientBuilder,\n\t\t\tcontrolCoreClientBuilder,\n\t\t\ttargetCoreClientBuilder,\n\t\t\trecorder,\n\t\t\tstop,\n\t\t)\n\n\t\tklog.Fatalf(\"error running controllers: %v\", err)\n\t\tpanic(\"unreachable\")\n\n\t}\n\n\tif !s.LeaderElection.LeaderElect {\n\t\trun(nil)\n\t\tpanic(\"unreachable\")\n\t}\n\n\tid, err := os.Hostname()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trl, err := resourcelock.New(\n\t\ts.LeaderElection.ResourceLock,\n\t\ts.Namespace,\n\t\t\"machine-controller-manager\",\n\t\tleaderElectionClient.CoreV1(),\n\t\tleaderElectionClient.CoordinationV1(),\n\t\tresourcelock.ResourceLockConfig{\n\t\t\tIdentity: id,\n\t\t\tEventRecorder: recorder,\n\t\t},\n\t)\n\tif err != nil {\n\t\tklog.Fatalf(\"error creating lock: %v\", err)\n\t}\n\n\tctx := context.TODO()\n\tleaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{\n\t\tLock: rl,\n\t\tLeaseDuration: s.LeaderElection.LeaseDuration.Duration,\n\t\tRenewDeadline: s.LeaderElection.RenewDeadline.Duration,\n\t\tRetryPeriod: s.LeaderElection.RetryPeriod.Duration,\n\t\tCallbacks: leaderelection.LeaderCallbacks{\n\t\t\tOnStartedLeading: run,\n\t\t\tOnStoppedLeading: func() {\n\t\t\t\tklog.Fatalf(\"leaderelection lost\")\n\t\t\t},\n\t\t},\n\t})\n\tpanic(\"unreachable\")\n}", "func instanceController() {\n\t// terminate is used for killing an instance of a task.\n\tcommands := map[string]*exec.Cmd{}\n\tvar terminate = func(name string, cmd *exec.Cmd) {\n\t\tif cmd.Process == nil {\n\t\t\treturn\n\t\t}\n\n\t\tpid := cmd.Process.Pid\n\t\terr := cmd.Process.Kill()\n\t\tif err == nil {\n\t\t\tcmd.Process.Wait()\n\t\t}\n\t\tdelete(commands, name)\n\t\tlog.Trace.Printf(`Active instance of \"%s\" (PID %d) has been terminated.`, name, pid)\n\t}\n\n\t// Clean up on termination.\n\tdefer func() {\n\t\tfor name, cmd := range commands {\n\t\t\tterminate(name, cmd)\n\t\t}\n\t\tstopped <- true\n\t}()\n\n\t// Waiting till we are asked to run/restart some tasks or exit\n\t// and following the orders.\n\tfor {\n\t\tswitch m := <-channel; m.action {\n\t\tcase \"start\":\n\t\t\t// Check whether we have already had an instance of the\n\t\t\t// requested task.\n\t\t\tcmd, ok := commands[m.name]\n\t\t\tif ok {\n\t\t\t\t// If so, terminate it first.\n\t\t\t\tterminate(m.name, cmd)\n\t\t\t}\n\n\t\t\t// If this is the first time this command is requested\n\t\t\t// to be run, initialize things.\n\t\t\tn, as := parseTask(m.task)\n\t\t\tlog.Trace.Printf(`Preparing \"%s\"...`, n)\n\t\t\tcmd = exec.Command(n, as...)\n\t\t\tcmd.Stderr = os.Stderr\n\t\t\tcmd.Stdout = os.Stdout\n\n\t\t\t// Starting the task.\n\t\t\tlog.Trace.Printf(\"Starting a new instance of `%s` (%v)...\", n, as)\n\t\t\terr := cmd.Start()\n\t\t\tif err != nil {\n\t\t\t\tlog.Error.Printf(\"Failed to start a command `%s`, error: %v.\", n, err)\n\t\t\t}\n\t\t\tcommands[m.name] = cmd // Register the command so we can terminate it.\n\t\tcase \"exit\":\n\t\t\treturn\n\t\t}\n\t}\n}", "func (v *MachineVM) Start(name string, _ machine.StartOptions) error {\n\tvar (\n\t\tconn net.Conn\n\t\terr error\n\t\tqemuSocketConn net.Conn\n\t\twait time.Duration = time.Millisecond * 500\n\t)\n\n\tif err := v.startHostNetworking(); err != nil {\n\t\treturn errors.Errorf(\"unable to start host networking: %q\", err)\n\t}\n\n\trtPath, err := getRuntimeDir()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If the temporary podman dir is not created, create it\n\tpodmanTempDir := filepath.Join(rtPath, \"podman\")\n\tif _, err := os.Stat(podmanTempDir); os.IsNotExist(err) {\n\t\tif mkdirErr := os.MkdirAll(podmanTempDir, 0755); mkdirErr != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tqemuSocketPath, _, err := v.getSocketandPid()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// If the qemusocketpath exists and the vm is off/down, we should rm\n\t// it before the dial as to avoid a segv\n\tif err := os.Remove(qemuSocketPath); err != nil && !errors.Is(err, os.ErrNotExist) {\n\t\tlogrus.Warn(err)\n\t}\n\tfor i := 0; i < 6; i++ {\n\t\tqemuSocketConn, err = net.Dial(\"unix\", qemuSocketPath)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(wait)\n\t\twait++\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfd, err := qemuSocketConn.(*net.UnixConn).File()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tattr := new(os.ProcAttr)\n\tfiles := []*os.File{os.Stdin, os.Stdout, os.Stderr, fd}\n\tattr.Files = files\n\tlogrus.Debug(v.CmdLine)\n\tcmd := v.CmdLine\n\n\t// Disable graphic window when not in debug mode\n\t// Done in start, so we're not suck with the debug level we used on init\n\tif logrus.GetLevel() != logrus.DebugLevel {\n\t\tcmd = append(cmd, \"-display\", \"none\")\n\t}\n\n\t_, err = os.StartProcess(v.CmdLine[0], cmd, attr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Waiting for VM ...\")\n\tsocketPath, err := getRuntimeDir()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// The socket is not made until the qemu process is running so here\n\t// we do a backoff waiting for it. Once we have a conn, we break and\n\t// then wait to read it.\n\tfor i := 0; i < 6; i++ {\n\t\tconn, err = net.Dial(\"unix\", filepath.Join(socketPath, \"podman\", v.Name+\"_ready.sock\"))\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(wait)\n\t\twait++\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = bufio.NewReader(conn).ReadString('\\n')\n\treturn err\n}", "func waitForMachineSetToNotExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForObjectToNotExist(\n\t\tnamespace, name,\n\t\tfunc(namespace, name string) (metav1.Object, error) {\n\t\t\treturn getMachineSet(capiClient, namespace, name)\n\t\t},\n\t)\n}", "func waitForGlusterContainer() error {\n\n\t//Check if docker gluster container is up and running\n\tfor {\n\t\tglusterServerContainerVal, err := helpers.GetSystemDockerNode(\"gluster-server\")\n\t\tif err != nil {\n\t\t\trwolog.Error(\"Error in checking docker gluster container for status \", err.Error())\n\t\t\treturn err\n\t\t}\n\n\t\tif len(glusterServerContainerVal) > 0 {\n\t\t\tbreak\n\t\t} else {\n\t\t\trwolog.Debug(\"Sleeping for 10 seconds to get gluster docker container up\")\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t}\n\treturn nil\n}", "func waitForResult() {\n\twork := make(chan string)\n\n\tgo func() {\n\t\ttime.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)\n\t\twork <- \"Done\"\n\t}()\n\n\ttime.Sleep(time.Second)\n\tmanager := <-work\n\n\tfmt.Printf(\"%+v\\n\", manager)\n}", "func (mod *Module)WaitTillStartupDone(){\n\tfor mod.hasRunStartup == false{//wait for startup to stop running\n\t\ttime.Sleep(time.Millisecond*10)\n\t}\n}", "func (d *vimInstallerInUbuntu) WaitForStart() (ok bool, err error) {\n\tok = true\n\treturn\n}", "func (c *Client) doWaitForStatus(eniID string, checkNum, checkInterval int, finalStatus string) error {\n\tfor i := 0; i < checkNum; i++ {\n\t\ttime.Sleep(time.Second * time.Duration(checkInterval))\n\t\tenis, err := c.queryENI(eniID, \"\", \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, eni := range enis {\n\t\t\tif *eni.NetworkInterfaceId == eniID {\n\t\t\t\tswitch *eni.State {\n\t\t\t\tcase ENI_STATUS_AVAILABLE:\n\t\t\t\t\tswitch finalStatus {\n\t\t\t\t\tcase ENI_STATUS_ATTACHED:\n\t\t\t\t\t\tif eni.Attachment != nil && eni.Attachment.InstanceId != nil {\n\t\t\t\t\t\t\tblog.Infof(\"eni %s is attached\", eniID)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblog.Infof(\"eni %s is not attached\", eniID)\n\t\t\t\t\tcase ENI_STATUS_DETACHED:\n\t\t\t\t\t\tif eni.Attachment == nil {\n\t\t\t\t\t\t\tblog.Infof(\"eni %s is detached\", eniID)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblog.Infof(\"eni %s is not detached\", eniID)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tblog.Infof(\"eni %s is %s now\", eniID, *eni.State)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase ENI_STATUS_PENDING, ENI_STATUS_ATTACHING, ENI_STATUS_DETACHING, ENI_STATUS_DELETING:\n\t\t\t\t\tblog.Infof(\"eni %s is %s\", eniID, *eni.State)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tblog.Errorf(\"timeout when wait for eni %s\", eniID)\n\treturn fmt.Errorf(\"timeout when wait for eni %s\", eniID)\n}", "func waitForPods(cs *framework.ClientSet, expectedTotal, min, max int32) error {\n\terr := wait.PollImmediate(1*time.Second, 5*time.Minute, func() (bool, error) {\n\t\td, err := cs.AppsV1Interface.Deployments(\"openshift-machine-config-operator\").Get(context.TODO(), \"etcd-quorum-guard\", metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\t// By this point the deployment should exist.\n\t\t\tfmt.Printf(\" error waiting for etcd-quorum-guard deployment to exist: %v\\n\", err)\n\t\t\treturn true, err\n\t\t}\n\t\tif d.Status.Replicas < 1 {\n\t\t\tfmt.Println(\"operator deployment has no replicas\")\n\t\t\treturn false, nil\n\t\t}\n\t\tif d.Status.Replicas == expectedTotal &&\n\t\t\td.Status.AvailableReplicas >= min &&\n\t\t\td.Status.AvailableReplicas <= max {\n\t\t\tfmt.Printf(\" Deployment is ready! %d %d\\n\", d.Status.Replicas, d.Status.AvailableReplicas)\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor pod, info := range pods {\n\t\tif info.status == \"Running\" {\n\t\t\tnode := info.node\n\t\t\tif node == \"\" {\n\t\t\t\treturn fmt.Errorf(\"Pod %s not associated with a node\", pod)\n\t\t\t}\n\t\t\tif _, ok := nodes[node]; !ok {\n\t\t\t\treturn fmt.Errorf(\"pod %s running on %s, not a master\", pod, node)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (d *conntrackInstallerInUbuntu) WaitForStart() (ok bool, err error) {\n\tok = true\n\treturn\n}", "func (vm *VirtualMachine) WaitUntilReady(client SkytapClient) (*VirtualMachine, error) {\n\treturn vm.WaitUntilInState(client, []string{RunStateStop, RunStateStart, RunStatePause}, false)\n}", "func WaitForCondition(mcpName string, conditionType machineconfigv1.MachineConfigPoolConditionType, conditionStatus corev1.ConditionStatus) {\n\n\tvar cnfNodes []corev1.Node\n\trunningOnSingleNode, err := cluster.IsSingleNode()\n\tExpectWithOffset(1, err).ToNot(HaveOccurred())\n\t// checking in eventually as in case of single node cluster the only node may\n\t// be rebooting\n\tEventuallyWithOffset(1, func() error {\n\t\tmcp, err := GetByName(mcpName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed getting MCP by name\")\n\t\t}\n\n\t\tnodeLabels := mcp.Spec.NodeSelector.MatchLabels\n\t\tkey, _ := components.GetFirstKeyAndValue(nodeLabels)\n\t\treq, err := labels.NewRequirement(key, selection.Exists, []string{})\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed creating node selector\")\n\t\t}\n\n\t\tselector := labels.NewSelector()\n\t\tselector = selector.Add(*req)\n\t\tcnfNodes, err = nodes.GetBySelector(selector)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed getting nodes by selector\")\n\t\t}\n\n\t\ttestlog.Infof(\"MCP %q is targeting %v node(s)\", mcp.Name, len(cnfNodes))\n\t\treturn nil\n\t}, cluster.ComputeTestTimeout(10*time.Minute, runningOnSingleNode), 5*time.Second).ShouldNot(HaveOccurred(), \"Failed to find CNF nodes by MCP %q\", mcpName)\n\n\t// timeout should be based on the number of worker-cnf nodes\n\ttimeout := time.Duration(len(cnfNodes)*mcpUpdateTimeoutPerNode) * time.Minute\n\tif len(cnfNodes) == 0 {\n\t\ttimeout = 2 * time.Minute\n\t}\n\n\tEventuallyWithOffset(1, func() corev1.ConditionStatus {\n\t\treturn GetConditionStatus(mcpName, conditionType)\n\t}, cluster.ComputeTestTimeout(timeout, runningOnSingleNode), 30*time.Second).Should(Equal(conditionStatus), \"Failed to find condition status by MCP %q\", mcpName)\n}", "func (c *controller) waitKnativeServiceReady(\n\tctx context.Context,\n\tsvcName string,\n\tnamespace string,\n) error {\n\t// Init ticker to check status every second\n\tticker := time.NewTicker(time.Second)\n\tdefer ticker.Stop()\n\n\t// Init knative ServicesGetter\n\tservices := c.knServingClient.Services(namespace)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tterminationMessage := c.getKnativePodTerminationMessage(svcName, namespace)\n\t\t\tif terminationMessage == \"\" {\n\t\t\t\t// Pod was not created (as with invalid image names), get status messages from the knative service.\n\t\t\t\tsvc, err := services.Get(svcName, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\tterminationMessage = err.Error()\n\t\t\t\t} else {\n\t\t\t\t\tterminationMessage = getKnServiceStatusMessages(svc)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"timeout waiting for service %s to be ready:\\n%s\", svcName, terminationMessage)\n\t\tcase <-ticker.C:\n\t\t\tsvc, err := services.Get(svcName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to get service status for %s: %v\", svcName, err)\n\t\t\t}\n\n\t\t\tif svc.Status.IsReady() {\n\t\t\t\t// Service is completely ready\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n}", "func (a *Actuator) Create(c *clusterv1.Cluster, m *clusterv1.Machine) error {\n\tglog.Infof(\"Creating machine %s for cluster %s.\", m.Name, c.Name)\n\tif a.machineSetupConfigGetter == nil {\n\t\treturn a.handleMachineError(m, apierrors.InvalidMachineConfiguration(\"valid machineSetupConfigGetter is required\"), createEventAction)\n\t}\n\n\t// First get provider config\n\tmachineConfig, err := a.machineProviderConfig(m.Spec.ProviderConfig)\n\tif err != nil {\n\t\treturn a.handleMachineError(m, apierrors.InvalidMachineConfiguration(\"Cannot unmarshal machine's providerConfig field: %v\", err), createEventAction)\n\t}\n\n\t// Now validate\n\tif err := a.validateMachine(m, machineConfig); err != nil {\n\t\treturn a.handleMachineError(m, err, createEventAction)\n\t}\n\n\t// check if the machine exists (here we mean we haven't provisioned it yet.)\n\texists, err := a.Exists(c, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif exists {\n\t\tglog.Infof(\"Machine %s for cluster %s exists, skipping.\", m.Name, c.Name)\n\t\treturn nil\n\t}\n\n\t// The doesn't exist case here.\n\tglog.Infof(\"Machine %s for cluster %s doesn't exist.\", m.Name, c.Name)\n\n\tconfigParams := &MachineParams{\n\t\tRoles: machineConfig.Roles,\n\t\tVersions: m.Spec.Versions,\n\t}\n\n\tmetadata, err := a.getMetadata(c, m, configParams, machineConfig.SSHConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Metadata retrieved: machine %s for cluster %s\", m.Name, c.Name)\n\n\t// Here we deploy and run the scripts to the node.\n\tprivateKey, passPhrase, err := a.getPrivateKey(c, m.Namespace, machineConfig.SSHConfig.SecretName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Running startup script: machine %s for cluster %s...\", m.Name, c.Name)\n\n\tsshClient := ssh.NewSSHProviderClient(privateKey, passPhrase, machineConfig.SSHConfig)\n\n\tif err = sshClient.WriteFile(metadata.StartupScript, \"/var/tmp/startupscript.sh\"); err != nil {\n\t\tglog.Errorf(\"Error copying startup script: %v\", err)\n\t\treturn err\n\t}\n\n\tif err = sshClient.ProcessCMD(\"chmod +x /var/tmp/startupscript.sh && bash /var/tmp/startupscript.sh\"); err != nil {\n\t\tglog.Errorf(\"running startup script error: %v\", err)\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Annotating machine %s for cluster %s.\", m.Name, c.Name)\n\n\t// TODO find a way to do this in the cluster controller\n\tif util.IsMaster(m) {\n\t\terr = a.updateClusterObjectEndpoint(c, m)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// create kubeconfig secret\n\t\terr = a.createKubeconfigSecret(c, m, sshClient)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ta.eventRecorder.Eventf(m, corev1.EventTypeNormal, \"Created\", \"Created Machine %v\", m.Name)\n\treturn a.updateAnnotations(c, m)\n}", "func waitForServer(client *http.Client, serverAddress string) error {\n\tvar err error\n\t// wait for the server to come up\n\tfor i := 0; i < 10; i++ {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\t_, err = client.Get(\"http://\" + serverAddress)\n\t\tif err == nil {\n\t\t\treturn nil // server is up now\n\t\t}\n\t}\n\treturn fmt.Errorf(\"timed out waiting for server %s to come up: %w\", serverAddress, err)\n}", "func (s *LocalTests) deleteMachine(c *gc.C, machineId string) {\n\terr := s.testClient.StopMachine(machineId)\n\tc.Assert(err, gc.IsNil)\n\n\t// wait for machine to be stopped\n\tfor !s.pollMachineState(c, machineId, \"stopped\") {\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\terr = s.testClient.DeleteMachine(machineId)\n\tc.Assert(err, gc.IsNil)\n}", "func TestRequestStopFromMovingUp(t *testing.T) {\n\t// setup\n\tdwController := setup(t, 2, Up, []common.PiPin{common.OpenerStop})\n\n\t// test\n\tdwController.SetStopRequested() // send the stop request\n\twaitForStatus(t, 2, 2, Stopped, dwController, 3*time.Second) // verify that the dumbwaiter is now stopped\n}", "func (m *Machine) waitForSocket(timeout time.Duration, exitchan chan error) error {\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\n\tticker := time.NewTicker(10 * time.Millisecond)\n\n\tdefer func() {\n\t\tcancel()\n\t\tticker.Stop()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase err := <-exitchan:\n\t\t\treturn err\n\t\tcase <-ticker.C:\n\t\t\tif _, err := os.Stat(m.Cfg.SocketPath); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Send test HTTP request to make sure socket is available\n\t\t\tif _, err := m.client.GetMachineConfiguration(); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (c *Controller) Run(ctx context.Context) error {\n\t// Start the informer factories to begin populating the informer caches\n\tc.log.Infof(\"starting step control loop, node name: %s\", c.nodeName)\n\n\t// 初始化runner\n\tc.log.Info(\"init controller engine\")\n\tif err := engine.Init(c.wc, c.informer.Recorder()); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.sync(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tc.waitDown(ctx)\n\treturn nil\n}", "func (c *controller) WaitAndUpdateNodesStatus(ctx context.Context, wg *sync.WaitGroup, removeUninitializedTaint bool) {\n\tapproveCtx, approveCancel := context.WithCancel(ctx)\n\tdefer func() {\n\t\tapproveCancel()\n\t\tc.log.Infof(\"WaitAndUpdateNodesStatus finished\")\n\t\twg.Done()\n\t}()\n\t// starting approve csrs\n\tgo c.ApproveCsrs(approveCtx)\n\n\tc.log.Infof(\"Waiting till all nodes will join and update status to assisted installer\")\n\t_ = utils.WaitForPredicateParamsWithContext(ctx, LongWaitTimeout, GeneralWaitInterval, c.waitAndUpdateNodesStatus, removeUninitializedTaint)\n}", "func waitForHosts(path string) {\n\toldPwd := sh.Pwd()\n\tsh.Cd(path)\n\tlog.Debug(\"Ensuring ansible-playbook can be executed properly\")\n\tsh.SetE(exec.Command(\"ansible-playbook\", \"--version\"))\n\tpathToPlaybook := \"./playbooks/wait-for-hosts.yml\"\n\tansibleCommand := []string{\n\t\t\"-i\", \"plugins/inventory/terraform.py\",\n\t\t\"-e\", \"ansible_python_interpreter=\" + strings.TrimSpace(pythonBinary),\n\t\t\"-e\", \"@security.yml\",\n\t\tpathToPlaybook,\n\t}\n\tcmd := exec.Command(\"ansible-playbook\", ansibleCommand...)\n\tlog.Info(\"Waiting for SSH access to hosts...\")\n\toutStr, err := ExecuteWithOutput(cmd)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"command\": cmd.Args,\n\t\t\t\"output\": outStr,\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatalf(\"Couldn't execute playbook %s\", pathToPlaybook)\n\t}\n\tsh.Cd(oldPwd)\n}", "func waitForAPI(ctx context.Context, client *gophercloud.ServiceClient) {\n\thttpClient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}\n\n\t// NOTE: Some versions of Ironic inspector returns 404 for /v1/ but 200 for /v1,\n\t// which seems to be the default behavior for Flask. Remove the trailing slash\n\t// from the client endpoint.\n\tendpoint := strings.TrimSuffix(client.Endpoint, \"/\")\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for API to become available...\")\n\n\t\t\tr, err := httpClient.Get(endpoint)\n\t\t\tif err == nil {\n\t\t\t\tstatusCode := r.StatusCode\n\t\t\t\tr.Body.Close()\n\t\t\t\tif statusCode == http.StatusOK {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func (m *MeshReconciler) waitForCRD(name string, client runtimeclient.Client) error {\n\tm.logger.WithField(\"name\", name).Debug(\"waiting for CRD\")\n\n\tbackoffConfig := backoff.ConstantBackoffConfig{\n\t\tDelay: time.Duration(backoffDelaySeconds) * time.Second,\n\t\tMaxRetries: backoffMaxretries,\n\t}\n\tbackoffPolicy := backoff.NewConstantBackoffPolicy(backoffConfig)\n\n\tvar crd apiextensionsv1beta1.CustomResourceDefinition\n\terr := backoff.Retry(func() error {\n\t\terr := client.Get(context.Background(), types.NamespacedName{\n\t\t\tName: name,\n\t\t}, &crd)\n\t\tif err != nil {\n\t\t\treturn errors.WrapIf(err, \"could not get CRD\")\n\t\t}\n\n\t\tfor _, condition := range crd.Status.Conditions {\n\t\t\tif condition.Type == apiextensionsv1beta1.Established {\n\t\t\t\tif condition.Status == apiextensionsv1beta1.ConditionTrue {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn errors.New(\"CRD is not established yet\")\n\t}, backoffPolicy)\n\n\treturn err\n}", "func (a *Application) Wait() {\n\t<-a.terminated\n\tlog.Printf(\"[TEST] thats all folks\")\n}", "func (m *Machine) startVMM(ctx context.Context) error {\n\tm.logger.Printf(\"Called startVMM(), setting up a VMM on %s\", m.Cfg.SocketPath)\n\tstartCmd := m.cmd.Start\n\n\tm.logger.Debugf(\"Starting %v\", m.cmd.Args)\n\n\tvar err error\n\tif m.Cfg.NetNS != \"\" && m.Cfg.JailerCfg == nil {\n\t\t// If the VM needs to be started in a netns but no jailer netns was configured,\n\t\t// start the vmm child process in the netns directly here.\n\t\terr = ns.WithNetNSPath(m.Cfg.NetNS, func(_ ns.NetNS) error {\n\t\t\treturn startCmd()\n\t\t})\n\t} else {\n\t\t// Else, just start the process normally as it's either not in a netns or will\n\t\t// be placed in one by the jailer process instead.\n\t\terr = startCmd()\n\t}\n\n\tif err != nil {\n\t\tm.logger.Errorf(\"Failed to start VMM: %s\", err)\n\n\t\tm.fatalErr = err\n\t\tclose(m.exitCh)\n\n\t\treturn err\n\t}\n\tm.logger.Debugf(\"VMM started socket path is %s\", m.Cfg.SocketPath)\n\n\tm.cleanupFuncs = append(m.cleanupFuncs,\n\t\tfunc() error {\n\t\t\tif err := os.Remove(m.Cfg.SocketPath); !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t)\n\n\terrCh := make(chan error)\n\tgo func() {\n\t\twaitErr := m.cmd.Wait()\n\t\tif waitErr != nil {\n\t\t\tm.logger.Warnf(\"firecracker exited: %s\", waitErr.Error())\n\t\t} else {\n\t\t\tm.logger.Printf(\"firecracker exited: status=0\")\n\t\t}\n\n\t\tcleanupErr := m.doCleanup()\n\t\tif cleanupErr != nil {\n\t\t\tm.logger.Errorf(\"failed to cleanup after VM exit: %v\", cleanupErr)\n\t\t}\n\n\t\terrCh <- multierror.Append(waitErr, cleanupErr).ErrorOrNil()\n\n\t\t// Notify subscribers that there will be no more values.\n\t\t// When err is nil, two reads are performed (waitForSocket and close exitCh goroutine),\n\t\t// second one never ends as it tries to read from empty channel.\n\t\tclose(errCh)\n\t}()\n\n\tm.setupSignals()\n\n\t// Wait for firecracker to initialize:\n\terr = m.waitForSocket(time.Duration(m.client.firecrackerInitTimeout)*time.Second, errCh)\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"Firecracker did not create API socket %s\", m.Cfg.SocketPath)\n\t\tm.fatalErr = err\n\t\tclose(m.exitCh)\n\n\t\treturn err\n\t}\n\n\t// This goroutine is used to kill the process by context cancelletion,\n\t// but doesn't tell anyone about that.\n\tgo func() {\n\t\t<-ctx.Done()\n\t\terr := m.stopVMM()\n\t\tif err != nil {\n\t\t\tm.logger.WithError(err).Errorf(\"failed to stop vm %q\", m.Cfg.VMID)\n\t\t}\n\t}()\n\n\t// This goroutine is used to tell clients that the process is stopped\n\t// (gracefully or not).\n\tgo func() {\n\t\tm.fatalErr = <-errCh\n\t\tm.logger.Debugf(\"closing the exitCh %v\", m.fatalErr)\n\t\tclose(m.exitCh)\n\t}()\n\n\tm.logger.Debugf(\"returning from startVMM()\")\n\treturn nil\n}", "func waitForInit() error {\n\tstart := time.Now()\n\tmaxEnd := start.Add(time.Minute)\n\tfor {\n\t\t// Check for existence of vpcCniInitDonePath\n\t\tif _, err := os.Stat(vpcCniInitDonePath); err == nil {\n\t\t\t// Delete the done file in case of a reboot of the node or restart of the container (force init container to run again)\n\t\t\tif err := os.Remove(vpcCniInitDonePath); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// If file deletion fails, log and allow retry\n\t\t\tlog.Errorf(\"Failed to delete file: %s\", vpcCniInitDonePath)\n\t\t}\n\t\tif time.Now().After(maxEnd) {\n\t\t\treturn errors.Errorf(\"time exceeded\")\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func (j *Juju) ControllerReady() (bool, error) {\n\ttmp := \"JUJU_DATA=\" + JujuDataPrefix + j.Name\n\tcmd := exec.Command(\"juju\", \"models\", \"--format=json\")\n\tcmd.Env = append(os.Environ(), tmp)\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"ControllerReady error: %v: %s\", err, err.(*exec.ExitError).Stderr)\n\t}\n\n\terr = json.Unmarshal([]byte(out), &jModels)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"ControllerReady unmarshal error: %v: %s\", err, err.(*exec.ExitError).Stderr)\n\t}\n\n\tlog.Debugf(\"ControllerReady: %+v\", jModels)\n\tfor k := range jModels.Models {\n\t\tif jModels.Models[k].ShortName == j.Name {\n\t\t\tstatus := jModels.Models[k].Status[\"current\"]\n\t\t\tif status == \"available\" {\n\t\t\t\tlog.WithFields(logrus.Fields{\"name\": j.Name}).Info(\"Controller Ready\")\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t}\n\tlog.WithFields(logrus.Fields{\"name\": j.Name}).Info(\"Controller Not Ready\")\n\treturn false, nil\n}", "func WaitForBKClusterToTerminate(t *testing.T, k8client client.Client, b *bkapi.BookkeeperCluster) error {\n\tlog.Printf(\"waiting for Bookkeeper cluster to terminate: %s\", b.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(b.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(map[string]string{\"bookkeeper_cluster\": b.GetName()})},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"bookkeeper cluster terminated: %s\", b.Name)\n\treturn nil\n}", "func waitForClusterReady(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForClusterStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(cluster *capiv1alpha1.Cluster) bool {\n\t\t\tstatus, err := controller.ClusterStatusFromClusterAPI(cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn status.Ready\n\t\t},\n\t)\n}", "func (ins *EC2RemoteClient) makeReady() error {\n\t// Check Instance is running - will error if instance doesn't exist\n\tresult, err := ins.ec2Client.DescribeInstanceStatus(&ec2.DescribeInstanceStatusInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting instance status : %s\", err)\n\t}\n\n\t// Start instance if needed\n\tif len(result.InstanceStatuses) == 0 || *result.InstanceStatuses[0].InstanceState.Name != \"running\" {\n\t\terr = ins.startInstance()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error starting instance : %s\", err)\n\t\t}\n\t}\n\n\t// Get Public IP address from ec2\n\terr = ins.getIPAddress()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting IP address : %s\", err)\n\t}\n\n\t// Set up SSH connection\n\tins.cmdClient, err = sshCmdClient.NewSSHCmdClient(ins.instanceIP, ins.sshCredentials)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Check we can at least run a trivial command\n\texitStatus, err := ins.RunCommand(\"true\")\n\tif err != nil || exitStatus != 0 {\n\t\treturn fmt.Errorf(\"Error running commands on instance : %s\", err)\n\t}\n\n\treturn err\n}", "func waitForKnativeCrdsRegistered(timeout, interval time.Duration) error {\n\telapsed := time.Duration(0)\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(interval):\n\t\t\tif err := kubectl(nil, \"get\", \"images.caching.internal.knative.dev\"); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\telapsed += interval\n\t\t\tif elapsed > timeout {\n\t\t\t\treturn errors.Errorf(\"failed to confirm knative crd registration after %v\", timeout)\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *LocalTests) pollMachineState(c *gc.C, machineId, state string) bool {\n\tmachineConfig, err := s.testClient.GetMachine(machineId)\n\tc.Assert(err, gc.IsNil)\n\treturn strings.EqualFold(machineConfig.State, state)\n}", "func (s *ServiceManager) Wait() (err error) {\n\tcases := s.buildSelectCases()\n\n\t// waits for the ServiceManager to confirm running state\n\t<-s.waitForRunning\n\t// waitForRunning will never be used again, discard memory\n\tclose(s.waitForRunning)\n\ts.waitForRunning = nil\n\n\trunning := true\n\tfor running {\n\t\t// chosen is the index of the selected case\n\t\t// recv is the value obtained, which will always be a SignalControl function\n\t\t// ok = false if the channel is closed\n\t\tchosen, recv, ok := reflect.Select(cases)\n\t\tif !ok {\n\t\t\t// not OK: channel was closed, remove from the list as we'll never receive any messages on it\n\t\t\t// It makes no sense to listen to it any more\n\t\t\tl := 0\n\t\t\ts.mu.Lock()\n\t\t\ts.removeSignaler(chosen)\n\t\t\tl = len(s.signalers)\n\t\t\ts.mu.Unlock()\n\t\t\tif l == 0 {\n\t\t\t\t// we're out of channels, stop the for loop\n\t\t\t\t// We'll need to wait for the server to end-itself. Closing channels does not stop the service,\n\t\t\t\t// but only the means of stopping that service\n\t\t\t\terr = <-s.waitForIteratorDone\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// we need to re-build the missing cases as now one is missing\n\t\t\tcases = s.buildSelectCases()\n\t\t\tcontinue\n\t\t}\n\n\t\t// Channel was not closed, we received a message\n\t\tswitch chanType := recv.Interface().(type) {\n\t\tcase SignalControl:\n\t\t\t// Our signal was OK, channel is not closed. Let's see what it says:\n\t\t\tswitch chanType(s) {\n\t\t\tcase GracefulRestart:\n\t\t\t\t// We need to gracefully restart\n\t\t\t\t// Trigger cancelling the context\n\t\t\t\t// We copy the value and set it to nil here to avoid having the inner go-routine call cancel a second time\n\t\t\t\ts.mu.Lock()\n\t\t\t\ts.state = StateRestarting\n\t\t\t\tif s.cancelFunc != nil {\n\t\t\t\t\ts.cancelFunc()\n\t\t\t\t\ts.cancelFunc = nil\n\t\t\t\t}\n\t\t\t\ts.mu.Unlock()\n\n\t\t\tcase GracefulStop:\n\t\t\t\t// We need to stop the service\n\t\t\t\trunning = false\n\n\t\t\t\ts.mu.Lock()\n\t\t\t\ts.state = StateDying\n\t\t\t\tif s.cancelFunc != nil {\n\t\t\t\t\ts.cancelFunc()\n\t\t\t\t\ts.cancelFunc = nil\n\t\t\t\t}\n\t\t\t\ts.mu.Unlock()\n\n\t\t\t\t// We're stopping, we need to wait for the goroutine to signal that it completed\n\t\t\t\terr = <-s.waitForIteratorDone\n\t\t\t}\n\t\tcase error:\n\t\t\t// This means our routine completed and is no longer running\n\t\t\trunning = false\n\t\t\ts.setState(StateDying)\n\n\t\t\t// The main service routine ended so we CANNOT wait for the goroutine to signal that it completed as it's already done\n\t\t\t// this also means that the context has already cleaned itself up, so no need to call s.cancelFunc\n\t\t\t// chanType could be nil, meaning no error\n\t\t\terr = chanType\n\n\t\t}\n\t}\n\n\t// Recover goroutine leak, if any\n\ts.cancelSignalers()\n\n\ts.setState(StateDead)\n\n\tclose(s.waitForIteratorDone)\n\n\treturn\n}", "func waitForPodsToBeInTerminatingPhase(sshClientConfig *ssh.ClientConfig, svcMasterIP string,\n\tpodName string, namespace string, timeout time.Duration) error {\n\tkubeConfigPath := GetAndExpectStringEnvVar(gcKubeConfigPath)\n\twaitErr := wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\tcmd := fmt.Sprintf(\"kubectl get pod %s --kubeconfig %s -n %s --no-headers|awk '{print $3}'\",\n\t\t\tpodName, kubeConfigPath, namespace)\n\t\tframework.Logf(\"Invoking command '%v' on host %v\", cmd,\n\t\t\tsvcMasterIP)\n\t\tcmdResult, err := sshExec(sshClientConfig, svcMasterIP,\n\t\t\tcmd)\n\t\tif err != nil || cmdResult.Code != 0 {\n\t\t\tfssh.LogResult(cmdResult)\n\t\t\treturn false, fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\t\tcmd, svcMasterIP, err)\n\t\t}\n\n\t\tframework.Logf(\"result %v\", cmdResult)\n\t\tframework.Logf(\"stdout %s\", cmdResult.Stdout)\n\t\tpodPhase := strings.TrimSpace(cmdResult.Stdout)\n\t\tif podPhase == \"Terminating\" {\n\t\t\tframework.Logf(\"Pod %s is in terminating state\", podName)\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn waitErr\n}", "func (t *keepalivedService) InitMachine(node service.Node, client util.SSHClient, sctx *service.ServiceContext, deps service.ServiceDependencies, flags service.ServiceFlags) error {\n\tlog := deps.Logger.With().Str(\"host\", node.Name).Logger()\n\n\t// Setup controlplane on this host?\n\tif !node.IsControlPlane || flags.ControlPlane.APIServerVirtualIP == \"\" {\n\t\tlog.Info().Msg(\"No keepalived on this machine\")\n\t\treturn nil\n\t}\n\n\tcfg, err := t.createConfig(node, client, sctx, deps, flags)\n\tif err != nil {\n\t\treturn maskAny(err)\n\t}\n\n\t// Create & Upload keepalived.conf\n\tlog.Info().Msgf(\"Uploading %s Config\", t.Name())\n\tif err := createConfigFile(client, deps, cfg); err != nil {\n\t\treturn maskAny(err)\n\t}\n\tif err := createAPIServerCheck(client, deps, cfg); err != nil {\n\t\treturn maskAny(err)\n\t}\n\n\t// Restart keepalived\n\tif _, err := client.Run(log, \"sudo systemctl restart \"+serviceName, \"\", true); err != nil {\n\t\tlog.Warn().Err(err).Msg(\"Failed to restart keepalived server\")\n\t}\n\n\treturn nil\n}", "func WaitForClusterToTerminate(t *testing.T, f *framework.Framework, ctx *framework.TestCtx, z *api.ZookeeperCluster) error {\n\tt.Logf(\"waiting for zookeeper cluster to terminate: %s\", z.Name)\n\n\tlistOptions := metav1.ListOptions{\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\"app\": z.GetName()}).String(),\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList, err := f.KubeClient.CoreV1().Pods(z.Namespace).List(goctx.TODO(), listOptions)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tt.Logf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList, err := f.KubeClient.CoreV1().PersistentVolumeClaims(z.Namespace).List(goctx.TODO(), listOptions)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tt.Logf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.Logf(\"zookeeper cluster terminated: %s\", z.Name)\n\treturn nil\n}", "func waitForCRDEstablishment(clientset apiextensionsclient.Interface) error {\n\treturn wait.Poll(500*time.Millisecond, 60*time.Second, func() (bool, error) {\n\t\tsparkAppCrd, err := getCRD(clientset)\n\t\tfor _, cond := range sparkAppCrd.Status.Conditions {\n\t\t\tswitch cond.Type {\n\t\t\tcase apiextensionsv1beta1.Established:\n\t\t\t\tif cond.Status == apiextensionsv1beta1.ConditionTrue {\n\t\t\t\t\treturn true, err\n\t\t\t\t}\n\t\t\tcase apiextensionsv1beta1.NamesAccepted:\n\t\t\t\tif cond.Status == apiextensionsv1beta1.ConditionFalse {\n\t\t\t\t\tfmt.Printf(\"Name conflict: %v\\n\", cond.Reason)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false, err\n\t})\n}", "func (vp *Pinnable) WaitForDiskLoad() {\n\tvp.Loader.Wait()\n}", "func (r clusterReconciler) controlPlaneMachineToCluster(ctx context.Context, o client.Object) []ctrl.Request {\n\tvsphereMachine, ok := o.(*infrav1.VSphereMachine)\n\tif !ok {\n\t\tr.Logger.Error(nil, fmt.Sprintf(\"expected a VSphereMachine but got a %T\", o))\n\t\treturn nil\n\t}\n\tif !infrautilv1.IsControlPlaneMachine(vsphereMachine) {\n\t\treturn nil\n\t}\n\tif len(vsphereMachine.Status.Addresses) == 0 {\n\t\treturn nil\n\t}\n\t// Get the VSphereMachine's preferred IP address.\n\tif _, err := infrautilv1.GetMachinePreferredIPAddress(vsphereMachine); err != nil {\n\t\tif err == infrautilv1.ErrNoMachineIPAddr {\n\t\t\treturn nil\n\t\t}\n\t\tr.Logger.Error(err, \"failed to get preferred IP address for VSphereMachine\",\n\t\t\t\"namespace\", vsphereMachine.Namespace, \"name\", vsphereMachine.Name)\n\t\treturn nil\n\t}\n\n\t// Fetch the CAPI Cluster.\n\tcluster, err := clusterutilv1.GetClusterFromMetadata(ctx, r.Client, vsphereMachine.ObjectMeta)\n\tif err != nil {\n\t\tr.Logger.Error(err, \"VSphereMachine is missing cluster label or cluster does not exist\",\n\t\t\t\"namespace\", vsphereMachine.Namespace, \"name\", vsphereMachine.Name)\n\t\treturn nil\n\t}\n\n\tif conditions.IsTrue(cluster, clusterv1.ControlPlaneInitializedCondition) {\n\t\treturn nil\n\t}\n\n\tif !cluster.Spec.ControlPlaneEndpoint.IsZero() {\n\t\treturn nil\n\t}\n\n\t// Fetch the VSphereCluster\n\tvsphereCluster := &infrav1.VSphereCluster{}\n\tvsphereClusterKey := client.ObjectKey{\n\t\tNamespace: vsphereMachine.Namespace,\n\t\tName: cluster.Spec.InfrastructureRef.Name,\n\t}\n\tif err := r.Client.Get(ctx, vsphereClusterKey, vsphereCluster); err != nil {\n\t\tr.Logger.Error(err, \"failed to get VSphereCluster\",\n\t\t\t\"namespace\", vsphereClusterKey.Namespace, \"name\", vsphereClusterKey.Name)\n\t\treturn nil\n\t}\n\n\tif !vsphereCluster.Spec.ControlPlaneEndpoint.IsZero() {\n\t\treturn nil\n\t}\n\n\treturn []ctrl.Request{{\n\t\tNamespacedName: types.NamespacedName{\n\t\t\tNamespace: vsphereClusterKey.Namespace,\n\t\t\tName: vsphereClusterKey.Name,\n\t\t},\n\t}}\n}", "func (f *Framework) WaitForVMToBeProcessing(vmiName string) error {\n\treturn f.WaitForVMImportConditionInStatus(2*time.Second, time.Minute, vmiName, v2vv1alpha1.Processing, corev1.ConditionTrue)\n}", "func (a *Actuator) Delete(c *clusterv1.Cluster, m *clusterv1.Machine) error {\n\tglog.Infof(\"Deleting machine %s for cluster %s.\", m.Name, c.Name)\n\n\tif a.machineSetupConfigGetter == nil {\n\t\treturn a.handleMachineError(m, apierrors.InvalidMachineConfiguration(\"valid machineSetupConfigGetter is required\"), deleteEventAction)\n\t}\n\n\t// First get provider config\n\tmachineConfig, err := a.machineProviderConfig(m.Spec.ProviderConfig)\n\tif err != nil {\n\t\treturn a.handleMachineError(m, apierrors.InvalidMachineConfiguration(\"Cannot unmarshal machine's providerConfig field: %v\", err), deleteEventAction)\n\t}\n\n\t// Now validate\n\tif err := a.validateMachine(m, machineConfig); err != nil {\n\t\treturn a.handleMachineError(m, err, deleteEventAction)\n\t}\n\n\t// Check if the machine exists (here we mean it is not bootstrapping.)\n\texists, err := a.Exists(c, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !exists {\n\t\tglog.Infof(\"Machine %s for cluster %s does not exists (maybe it is still bootstrapping), skipping.\", m.Name, c.Name)\n\t\treturn nil\n\t}\n\n\t// The exists case here.\n\tglog.Infof(\"Machine %s for cluster %s exists.\", m.Name, c.Name)\n\n\tconfigParams := &MachineParams{\n\t\tRoles: machineConfig.Roles,\n\t\tVersions: m.Spec.Versions,\n\t}\n\n\tmetadata, err := a.getMetadata(c, m, configParams, machineConfig.SSHConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Metadata retrieved: machine %s for cluster %s\", m.Name, c.Name)\n\n\tprivateKey, passPhrase, err := a.getPrivateKey(c, m.Namespace, machineConfig.SSHConfig.SecretName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infof(\"Running shutdown script: machine %s for cluster %s...\", m.Name, c.Name)\n\n\tsshClient := ssh.NewSSHProviderClient(privateKey, passPhrase, machineConfig.SSHConfig)\n\n\tif err = sshClient.WriteFile(metadata.ShutdownScript, \"/var/tmp/shutdownscript.sh\"); err != nil {\n\t\tglog.Errorf(\"Error copying shutdown script: %v\", err)\n\t\treturn err\n\t}\n\n\tif err = sshClient.ProcessCMD(\"chmod +x /var/tmp/shutdownscript.sh && bash /var/tmp/shutdownscript.sh\"); err != nil {\n\t\tglog.Errorf(\"running shutdown script error: %v\", err)\n\t\treturn err\n\t}\n\n\ta.eventRecorder.Eventf(m, corev1.EventTypeNormal, \"Deleted\", \"Deleted Machine %v\", m.Name)\n\treturn nil\n}", "func Monitor() {\n\tfor {\n\t\tif container.State(container.Management) == container.Running {\n\t\t\tcommon.RunNRecover(server)\n\t\t} else {\n\t\t\tcommon.RunNRecover(client)\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n}", "func waitReady(project, name, region string) error {\n\twait := time.Minute * 4\n\tdeadline := time.Now().Add(wait)\n\tfor time.Now().Before(deadline) {\n\t\tsvc, err := getService(project, name, region)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to query Service for readiness: %w\", err)\n\t\t}\n\n\t\tfor _, cond := range svc.Status.Conditions {\n\t\t\tif cond.Type == \"Ready\" {\n\t\t\t\tif cond.Status == \"True\" {\n\t\t\t\t\treturn nil\n\t\t\t\t} else if cond.Status == \"False\" {\n\t\t\t\t\treturn fmt.Errorf(\"reason=%s message=%s\", cond.Reason, cond.Message)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second * 2)\n\t}\n\treturn fmt.Errorf(\"the service did not become ready in %s, check Cloud Console for logs to see why it failed\", wait)\n}", "func (s *EcsService) WaitForEcsInstance(instanceId string, status Status, timeout int) error {\n\tif timeout <= 0 {\n\t\ttimeout = DefaultTimeout\n\t}\n\tfor {\n\t\tinstance, err := s.DescribeInstance(instanceId)\n\t\tif err != nil && !NotFoundError(err) {\n\t\t\treturn err\n\t\t}\n\t\tif instance.Status == string(status) {\n\t\t\t//Sleep one more time for timing issues\n\t\t\ttime.Sleep(DefaultIntervalMedium * time.Second)\n\t\t\tbreak\n\t\t}\n\t\ttimeout = timeout - DefaultIntervalShort\n\t\tif timeout <= 0 {\n\t\t\treturn GetTimeErrorFromString(GetTimeoutMessage(\"ECS Instance\", string(status)))\n\t\t}\n\t\ttime.Sleep(DefaultIntervalShort * time.Second)\n\n\t}\n\treturn nil\n}", "func WaitForService(address string, logger *log.Logger) bool {\n\n\tfor i := 0; i < 12; i++ {\n\t\tconn, err := net.Dial(\"tcp\", address)\n\t\tif err != nil {\n\t\t\tlogger.Println(\"Connection error:\", err)\n\t\t} else {\n\t\t\tconn.Close()\n\t\t\tlogger.Println(fmt.Sprintf(\"Connected to %s\", address))\n\t\t\treturn true\n\t\t}\n\t\ttime.Sleep(5 * time.Second)\n\t}\n\n\treturn false\n}", "func (vm *VirtualMachine) WaitUntilInState(client SkytapClient, desiredStates []string, requireStateChange bool) (*VirtualMachine, error) {\n\tr, err := WaitUntilInState(client, desiredStates, vm, requireStateChange)\n\tv := r.(*VirtualMachine)\n\treturn v, err\n}", "func (c *myClient) waitForEnvironmentsReady(p, t int, envList ...string) (err error) {\n\n\tlogger.Infof(\"Waiting up to %v seconds for the environments to be ready\", t)\n\ttimeOut := 0\n\tfor timeOut < t {\n\t\tlogger.Info(\"Waiting for the environments\")\n\t\ttime.Sleep(time.Duration(p) * time.Second)\n\t\ttimeOut = timeOut + p\n\t\tif err = c.checkForBusyEnvironments(envList); err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif timeOut >= t {\n\t\terr = fmt.Errorf(\"waitForEnvironmentsReady timed out\")\n\t}\n\treturn err\n}", "func machineCommand(actionName string, host *host.Host, errorChan chan<- error) {\n\t// TODO: These actions should have their own type.\n\tcommands := map[string](func() error){\n\t\t\"configureAuth\": host.ConfigureAuth,\n\t\t\"start\": host.Start,\n\t\t\"stop\": host.Stop,\n\t\t\"restart\": host.Restart,\n\t\t\"kill\": host.Kill,\n\t\t\"upgrade\": host.Upgrade,\n\t\t\"ip\": printIP(host),\n\t}\n\n\tlog.Debugf(\"command=%s machine=%s\", actionName, host.Name)\n\n\tif err := commands[actionName](); err != nil {\n\t\terrorChan <- err\n\t\treturn\n\t}\n\n\terrorChan <- nil\n}", "func WaitForDeletion(ctx context.Context, mcpKey types.NamespacedName, timeout time.Duration) error {\n\treturn wait.PollImmediate(5*time.Second, timeout, func() (bool, error) {\n\t\tmcp := &machineconfigv1.MachineConfigPool{}\n\t\tif err := testclient.Client.Get(ctx, mcpKey, mcp); apierrors.IsNotFound(err) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}", "func (c *Compute) wait(operation *compute.Operation) error {\n\tfor {\n\t\top, err := c.ZoneOperations.Get(c.Project, c.Zone, operation.Name).Do()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get operation: %v\", operation.Name, err)\n\t\t}\n\t\tlog.Printf(\"operation %q status: %s\", operation.Name, op.Status)\n\t\tif op.Status == \"DONE\" {\n\t\t\tif op.Error != nil {\n\t\t\t\treturn fmt.Errorf(\"operation error: %v\", *op.Error.Errors[0])\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\treturn nil\n}", "func deviceSetUp(ctx context.Context, user, pass, p12Path string, key *rsa.PublicKey) (err error) {\n\tconst uiSetupTimeout = 90 * time.Second\n\n\ttesting.ContextLog(ctx, \"Restarting ui job\")\n\tsctx, cancel := context.WithTimeout(ctx, uiSetupTimeout)\n\tdefer cancel()\n\n\tif err = upstart.StopJob(sctx, \"ui\"); err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t// In case of error, run EnsureJobRunning with the original\n\t\t// context to recover the job for the following tests.\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t\t// Ignore error.\n\t\tupstart.EnsureJobRunning(ctx, \"ui\")\n\t}()\n\tif err = session.ClearDeviceOwnership(sctx); err != nil {\n\t\treturn err\n\t}\n\tif err = cryptohome.CreateVault(sctx, user, pass); err != nil {\n\t\treturn err\n\t}\n\tif err = createOwnerKey(sctx, user, p12Path, key); err != nil {\n\t\treturn err\n\t}\n\terr = upstart.EnsureJobRunning(sctx, \"ui\")\n\treturn\n}", "func (r *Reconciler) update() error {\n\tif err := validateMachine(*r.machine); err != nil {\n\t\treturn fmt.Errorf(\"%v: failed validating machine provider spec: %w\", r.machine.GetName(), err)\n\t}\n\n\tif r.providerStatus.TaskRef != \"\" {\n\t\tmoTask, err := r.session.GetTask(r.Context, r.providerStatus.TaskRef)\n\t\tif err != nil {\n\t\t\tif !isRetrieveMONotFound(r.providerStatus.TaskRef, err) {\n\t\t\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\t\t\tName: r.machine.Name,\n\t\t\t\t\tNamespace: r.machine.Namespace,\n\t\t\t\t\tReason: \"GetTask finished with error\",\n\t\t\t\t})\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif moTask != nil {\n\t\t\tif taskIsFinished, err := taskIsFinished(moTask); err != nil {\n\t\t\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\t\t\tName: r.machine.Name,\n\t\t\t\t\tNamespace: r.machine.Namespace,\n\t\t\t\t\tReason: \"Task finished with error\",\n\t\t\t\t})\n\t\t\t\treturn fmt.Errorf(\"%v task %v finished with error: %w\", moTask.Info.DescriptionId, moTask.Reference().Value, err)\n\t\t\t} else if !taskIsFinished {\n\t\t\t\treturn fmt.Errorf(\"%v task %v has not finished\", moTask.Info.DescriptionId, moTask.Reference().Value)\n\t\t\t}\n\t\t}\n\t}\n\n\tvmRef, err := findVM(r.machineScope)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\tName: r.machine.Name,\n\t\t\tNamespace: r.machine.Namespace,\n\t\t\tReason: \"FindVM finished with error\",\n\t\t})\n\t\tif !isNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn fmt.Errorf(\"vm not found on update: %w\", err)\n\t}\n\n\tvm := &virtualMachine{\n\t\tContext: r.machineScope.Context,\n\t\tObj: object.NewVirtualMachine(r.machineScope.session.Client.Client, vmRef),\n\t\tRef: vmRef,\n\t}\n\n\tif err := vm.reconcileTags(r.Context, r.session, r.machine); err != nil {\n\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\tName: r.machine.Name,\n\t\t\tNamespace: r.machine.Namespace,\n\t\t\tReason: \"ReconcileTags finished with error\",\n\t\t})\n\t\treturn fmt.Errorf(\"failed to reconcile tags: %w\", err)\n\t}\n\n\tif err := r.reconcileMachineWithCloudState(vm, r.providerStatus.TaskRef); err != nil {\n\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\tName: r.machine.Name,\n\t\t\tNamespace: r.machine.Namespace,\n\t\t\tReason: \"ReconcileWithCloudState finished with error\",\n\t\t})\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func WaitForZKClusterToTerminate(t *testing.T, k8client client.Client, z *zkapi.ZookeeperCluster) error {\n\tlog.Printf(\"waiting for zookeeper cluster to terminate: %s\", z.Name)\n\n\tlistOptions := []client.ListOption{\n\t\tclient.InNamespace(z.GetNamespace()),\n\t\tclient.MatchingLabelsSelector{Selector: labels.SelectorFromSet(map[string]string{\"app\": z.GetName()})},\n\t}\n\n\t// Wait for Pods to terminate\n\terr := wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpodList := corev1.PodList{}\n\t\terr = k8client.List(goctx.TODO(), &podList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tnames = append(names, pod.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pods to terminate, running pods (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for PVCs to terminate\n\terr = wait.Poll(RetryInterval, TerminateTimeout, func() (done bool, err error) {\n\t\tpvcList := corev1.PersistentVolumeClaimList{}\n\t\terr = k8client.List(goctx.TODO(), &pvcList, listOptions...)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tvar names []string\n\t\tfor i := range pvcList.Items {\n\t\t\tpvc := &pvcList.Items[i]\n\t\t\tnames = append(names, pvc.Name)\n\t\t}\n\t\tlog.Printf(\"waiting for pvc to terminate (%v)\", names)\n\t\tif len(names) != 0 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"zookeeper cluster terminated: %s\", z.Name)\n\treturn nil\n}", "func waitTerm() {\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)\n\t<-signals\n}", "func (avisess *AviSession) CheckControllerStatus() (bool, *http.Response, error) {\n\turl := avisess.prefix + \"/api/cluster/status\"\n\tvar isControllerUp bool\n\tfor round := 0; round < avisess.ctrlStatusCheckRetryCount; round++ {\n\t\tcheckReq, err := http.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"CheckControllerStatus Error %v while generating http request.\", err)\n\t\t\treturn false, nil, err\n\t\t}\n\t\t//Getting response from controller's API\n\t\tif stateResp, err := avisess.client.Do(checkReq); err == nil {\n\t\t\tdefer stateResp.Body.Close()\n\t\t\t//Checking controller response\n\t\t\tif stateResp.StatusCode != 503 && stateResp.StatusCode != 502 && stateResp.StatusCode != 500 {\n\t\t\t\tisControllerUp = true\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tglog.Infof(\"CheckControllerStatus Error while generating http request %d %v\",\n\t\t\t\t\tstateResp.StatusCode, err)\n\t\t\t}\n\t\t} else {\n\t\t\tglog.Errorf(\"CheckControllerStatus Error while generating http request %v %v\", url, err)\n\t\t}\n\t\t// if controller status check interval is not set during client init, use the default SDK\n\t\t// behaviour.\n\t\tif avisess.ctrlStatusCheckRetryInterval == 0 {\n\t\t\ttime.Sleep(getMinTimeDuration((time.Duration(math.Exp(float64(round))*3) * time.Second), (time.Duration(30) * time.Second)))\n\t\t} else {\n\t\t\t// controller status will be polled at intervals specified during client init.\n\t\t\ttime.Sleep(time.Duration(avisess.ctrlStatusCheckRetryInterval) * time.Second)\n\t\t}\n\t\tglog.Errorf(\"CheckControllerStatus Controller %v Retrying. round %v..!\", url, round)\n\t}\n\treturn isControllerUp, &http.Response{Status: \"408 Request Timeout\", StatusCode: 408}, nil\n}", "func waitForCanclation(returnChn, abortWait, cancel chan bool, cmd *exec.Cmd) {\n\tselect {\n\tcase <-cancel:\n\t\tcmd.Process.Kill()\n\t\treturnChn <- true\n\tcase <-abortWait:\n\t}\n}", "func waitRun(contID string) error {\n\treturn daemon.WaitInspectWithArgs(dockerBinary, contID, \"{{.State.Running}}\", \"true\", 5*time.Second)\n}", "func waitForStart(server *Server) {\n\treader := bufio.NewReader(os.Stdin)\n\ttext, _ := reader.ReadString('\\n')\n\tfmt.Println(\"IS start exec :: \", text)\n\tserver.executor.summary.startTime = time.Now().UnixNano()\n\tif text == \"start\\n\" {\n\t\tcmd := pb.ExecutionCommand{\n\t\t\tType: startExec,\n\t\t}\n\t\tfor clinetID := range server.clientStreams {\n\t\t\tserver.sendCommand(clinetID, &cmd)\n\t\t}\n\t}\n}", "func (m *Manager) WaitUntilRunning() {\n\tfor {\n\t\tm.mu.Lock()\n\n\t\tif m.ctx != nil {\n\t\t\tm.mu.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\tstarted := m.started\n\t\tm.mu.Unlock()\n\n\t\t// Block until we have been started.\n\t\t<-started\n\t}\n}", "func (monitor *controllerMonitor) Run(stopCh <-chan struct{}) {\n\tklog.Info(\"Starting Antrea Controller Monitor\")\n\tcontrollerCRD := monitor.getControllerCRD()\n\tvar err error = nil\n\tfor {\n\t\tif controllerCRD == nil {\n\t\t\tcontrollerCRD, err = monitor.createControllerCRD()\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to create controller monitoring CRD %v : %v\", controllerCRD, err)\n\t\t\t}\n\t\t} else {\n\t\t\tcontrollerCRD, err = monitor.updateControllerCRD(controllerCRD)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to update controller monitoring CRD %v : %v\", controllerCRD, err)\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(60 * time.Second)\n\t}\n\t<-stopCh\n}", "func (s *service) waitForExit(cmd *exec.Cmd) {\n\tif err := cmd.Wait(); err != nil {\n\t\tlogrus.Debugf(\"Envoy terminated: %v\", err.Error())\n\t} else {\n\t\tlogrus.Debug(\"Envoy process exited\")\n\t}\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\tdelete(s.cmdMap, cmd)\n}" ]
[ "0.6205696", "0.59781384", "0.5872165", "0.57533246", "0.55674094", "0.5406494", "0.5349306", "0.53339887", "0.5305528", "0.52262676", "0.5192839", "0.5190781", "0.5143582", "0.51317656", "0.51000625", "0.5088618", "0.5088441", "0.50841904", "0.50794375", "0.5047249", "0.5038419", "0.5022287", "0.50213796", "0.5021335", "0.49914318", "0.4971571", "0.49654624", "0.49598977", "0.49256894", "0.49251145", "0.49142373", "0.49043137", "0.49011794", "0.48972362", "0.48959342", "0.48815775", "0.48780358", "0.48753121", "0.48709854", "0.47951576", "0.478834", "0.4786452", "0.47605163", "0.4760398", "0.47594568", "0.47584164", "0.4749738", "0.47480434", "0.4739915", "0.47296783", "0.47253802", "0.47208923", "0.47125015", "0.47111455", "0.4686496", "0.46852222", "0.46783885", "0.46695852", "0.4660244", "0.46586442", "0.465318", "0.4651734", "0.4646618", "0.4644959", "0.46425438", "0.4642191", "0.46369225", "0.46344405", "0.4616925", "0.46164346", "0.46106884", "0.46068853", "0.4588287", "0.45811284", "0.4574711", "0.45721564", "0.45679966", "0.45665905", "0.4556364", "0.45547473", "0.45413214", "0.4537627", "0.4530127", "0.45296282", "0.452934", "0.45228323", "0.45186418", "0.45185494", "0.4518417", "0.4511832", "0.45113492", "0.4500638", "0.44912755", "0.4490125", "0.44884044", "0.4486715", "0.4482242", "0.4472711", "0.44716763", "0.44629666" ]
0.79245347
0
waitForWebhook waits for machinecontrollerwebhook to become running
func waitForWebhook(ctx context.Context, client dynclient.Client) error { condFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{ Namespace: resources.MachineControllerNameSpace, LabelSelector: labels.SelectorFromSet(map[string]string{ appLabelKey: resources.MachineControllerWebhookName, }), }) return fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), "waiting for machine-controller webhook to became ready") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func waitFor(ctx context.Context, eventName string) error {\n\tch := make(chan struct{})\n\tcctx, cancel := context.WithCancel(ctx)\n\tchromedp.ListenTarget(cctx, func(ev interface{}) {\n\t\tswitch e := ev.(type) {\n\t\tcase *page.EventLifecycleEvent:\n\t\t\tif e.Name == eventName {\n\t\t\t\tcancel()\n\t\t\t\tclose(ch)\n\t\t\t}\n\t\t}\n\t})\n\tselect {\n\tcase <-ch:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\n}", "func waitForAPI(ctx context.Context, client *gophercloud.ServiceClient) {\n\thttpClient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}\n\n\t// NOTE: Some versions of Ironic inspector returns 404 for /v1/ but 200 for /v1,\n\t// which seems to be the default behavior for Flask. Remove the trailing slash\n\t// from the client endpoint.\n\tendpoint := strings.TrimSuffix(client.Endpoint, \"/\")\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for API to become available...\")\n\n\t\t\tr, err := httpClient.Get(endpoint)\n\t\t\tif err == nil {\n\t\t\t\tstatusCode := r.StatusCode\n\t\t\t\tr.Body.Close()\n\t\t\t\tif statusCode == http.StatusOK {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func ensureVWHReady(){\n\tMustRunWithTimeout(certsReadyTime, \"kubectl create ns check-webhook\")\n\tMustRun(\"kubectl delete ns check-webhook\")\n}", "func waitWebhookConfigurationReady(f *framework.Framework, namespace string) error {\n\tcmClient := f.VclusterClient.CoreV1().ConfigMaps(namespace + \"-markers\")\n\treturn wait.PollUntilContextTimeout(f.Context, 100*time.Millisecond, 30*time.Second, true, func(ctx context.Context) (bool, error) {\n\t\tmarker := &corev1.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: string(uuid.NewUUID()),\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tuniqueName: \"true\",\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t_, err := cmClient.Create(ctx, marker, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\t// The always-deny webhook does not provide a reason, so check for the error string we expect\n\t\t\tif strings.Contains(err.Error(), \"denied\") {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\t// best effort cleanup of markers that are no longer needed\n\t\t_ = cmClient.Delete(ctx, marker.GetName(), metav1.DeleteOptions{})\n\t\tf.Log.Infof(\"Waiting for webhook configuration to be ready...\")\n\t\treturn false, nil\n\t})\n}", "func waitForMachineController(ctx context.Context, client dynclient.Client) error {\n\tcondFn := clientutil.PodsReadyCondition(ctx, client, dynclient.ListOptions{\n\t\tNamespace: resources.MachineControllerNameSpace,\n\t\tLabelSelector: labels.SelectorFromSet(map[string]string{\n\t\t\tappLabelKey: resources.MachineControllerName,\n\t\t}),\n\t})\n\n\treturn fail.KubeClient(wait.PollUntilContextTimeout(ctx, 5*time.Second, 3*time.Minute, false, condFn.WithContext()), \"waiting for machine-controller to became ready\")\n}", "func (mod *Module)WaitTillStartupDone(){\n\tfor mod.hasRunStartup == false{//wait for startup to stop running\n\t\ttime.Sleep(time.Millisecond*10)\n\t}\n}", "func WaitReady(ctx *util.Context) error {\n\tif !ctx.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\tctx.Logger.Infoln(\"Waiting for machine-controller to come up…\")\n\n\t// Wait a bit to let scheduler to react\n\ttime.Sleep(10 * time.Second)\n\n\tif err := WaitForWebhook(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller-webhook did not come up\")\n\t}\n\n\tif err := WaitForMachineController(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller did not come up\")\n\t}\n\treturn nil\n}", "func Run(ctx context.Context, mgr manager.Manager, handlerMap map[string]admission.Handler) error {\n\tif err := mgr.AddReadyzCheck(\"webhook-ready\", health.Checker); err != nil {\n\t\treturn fmt.Errorf(\"unable to add readyz check\")\n\t}\n\n\tc, err := webhookcontroller.New(mgr.GetConfig(), handlerMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\tc.Start(ctx)\n\t}()\n\n\ttimer := time.NewTimer(time.Second * 20)\n\tdefer timer.Stop()\n\tselect {\n\tcase <-webhookcontroller.Inited():\n\t\treturn waitReady()\n\tcase <-timer.C:\n\t\treturn fmt.Errorf(\"failed to start webhook controller for waiting more than 5s\")\n\t}\n\n\tserver := mgr.GetWebhookServer()\n\tserver.Host = \"0.0.0.0\"\n\tserver.Port = webhookutil.GetPort()\n\tserver.CertDir = webhookutil.GetCertDir()\n\treturn nil\n}", "func (bot *Bot) startWebhook() (err error) {\n\terr = bot.createServer()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"startWebhook: %w\", err)\n\t}\n\n\tbot.err = make(chan error)\n\n\tgo func() {\n\t\tbot.err <- bot.webhook.Start()\n\t}()\n\n\terr = bot.DeleteWebhook()\n\tif err != nil {\n\t\tlog.Println(\"startWebhook:\", err.Error())\n\t}\n\n\terr = bot.setWebhook()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"startWebhook: %w\", err)\n\t}\n\n\treturn <-bot.err\n}", "func (wh *Webhook) Run(stop <-chan struct{}) error {\n\tlogger := wh.Logger\n\tctx := logging.WithLogger(context.Background(), logger)\n\n\tdrainer := &handlers.Drainer{\n\t\tInner: wh,\n\t\tQuietPeriod: wh.Options.GracePeriod,\n\t}\n\n\tserver := &http.Server{\n\t\tErrorLog: log.New(&zapWrapper{logger}, \"\", 0),\n\t\tHandler: drainer,\n\t\tAddr: fmt.Sprint(\":\", wh.Options.Port),\n\t\tTLSConfig: wh.tlsConfig,\n\t\tReadHeaderTimeout: time.Minute, //https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6\n\t}\n\n\tvar serve = server.ListenAndServe\n\n\tif server.TLSConfig != nil && wh.testListener != nil {\n\t\tserve = func() error {\n\t\t\treturn server.ServeTLS(wh.testListener, \"\", \"\")\n\t\t}\n\t} else if server.TLSConfig != nil {\n\t\tserve = func() error {\n\t\t\treturn server.ListenAndServeTLS(\"\", \"\")\n\t\t}\n\t} else if wh.testListener != nil {\n\t\tserve = func() error {\n\t\t\treturn server.Serve(wh.testListener)\n\t\t}\n\t}\n\n\teg, ctx := errgroup.WithContext(ctx)\n\teg.Go(func() error {\n\t\tif err := serve(); err != nil && !errors.Is(err, http.ErrServerClosed) {\n\t\t\tlogger.Errorw(\"ListenAndServe for admission webhook returned error\", zap.Error(err))\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\n\tselect {\n\tcase <-stop:\n\t\teg.Go(func() error {\n\t\t\t// As we start to shutdown, disable keep-alives to avoid clients hanging onto connections.\n\t\t\tserver.SetKeepAlivesEnabled(false)\n\n\t\t\t// Start failing readiness probes immediately.\n\t\t\tlogger.Info(\"Starting to fail readiness probes...\")\n\t\t\tdrainer.Drain()\n\n\t\t\treturn server.Shutdown(context.Background())\n\t\t})\n\n\t\t// Wait for all outstanding go routined to terminate, including our new one.\n\t\treturn eg.Wait()\n\n\tcase <-ctx.Done():\n\t\treturn fmt.Errorf(\"webhook server bootstrap failed %w\", ctx.Err())\n\t}\n}", "func waitForEvent(t *testing.T, wsc *client.WSClient, eventid string, dieOnTimeout bool, f func(), check func(string, interface{}) error) {\n\t// go routine to wait for webscoket msg\n\tgoodCh := make(chan interface{})\n\terrCh := make(chan error)\n\n\t// Read message\n\tgo func() {\n\t\tvar err error\n\tLOOP:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase r := <-wsc.ResultsCh:\n\t\t\t\tresult := new(ctypes.TMResult)\n\t\t\t\twire.ReadJSONPtr(result, r, &err)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrCh <- err\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\t\t\t\tevent, ok := (*result).(*ctypes.ResultEvent)\n\t\t\t\tif ok && event.Name == eventid {\n\t\t\t\t\tgoodCh <- event.Data\n\t\t\t\t\tbreak LOOP\n\t\t\t\t}\n\t\t\tcase err := <-wsc.ErrorsCh:\n\t\t\t\terrCh <- err\n\t\t\t\tbreak LOOP\n\t\t\tcase <-wsc.Quit:\n\t\t\t\tbreak LOOP\n\t\t\t}\n\t\t}\n\t}()\n\n\t// do stuff (transactions)\n\tf()\n\n\t// wait for an event or timeout\n\ttimeout := time.NewTimer(10 * time.Second)\n\tselect {\n\tcase <-timeout.C:\n\t\tif dieOnTimeout {\n\t\t\twsc.Stop()\n\t\t\tpanic(Fmt(\"%s event was not received in time\", eventid))\n\t\t}\n\t\t// else that's great, we didn't hear the event\n\t\t// and we shouldn't have\n\tcase eventData := <-goodCh:\n\t\tif dieOnTimeout {\n\t\t\t// message was received and expected\n\t\t\t// run the check\n\t\t\tif err := check(eventid, eventData); err != nil {\n\t\t\t\tpanic(err) // Show the stack trace.\n\t\t\t}\n\t\t} else {\n\t\t\twsc.Stop()\n\t\t\tpanic(Fmt(\"%s event was not expected\", eventid))\n\t\t}\n\tcase err := <-errCh:\n\t\tpanic(err) // Show the stack trace.\n\n\t}\n}", "func (c *Config) waitForFlannelFile(newLogger micrologger.Logger) error {\n\t// wait for file creation\n\tfor count := 0; ; count++ {\n\t\t// don't wait forever, if file is not created within retry limit, exit with failure\n\t\tif count > MaxRetry {\n\t\t\treturn microerror.Maskf(invalidFlannelFileError, \"After 100sec flannel file is not created. Exiting\")\n\t\t}\n\t\t// check if file exists\n\t\tif _, err := os.Stat(c.Flag.Service.FlannelFile); !os.IsNotExist(err) {\n\t\t\tbreak\n\t\t}\n\t\t_ = newLogger.Log(\"debug\", fmt.Sprintf(\"Waiting for file '%s' to be created.\", c.Flag.Service.FlannelFile))\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\t// all good\n\treturn nil\n}", "func waitForMachineState(api *cloudapi.Client, id, state string, timeout time.Duration) error {\n\treturn waitFor(\n\t\tfunc() (bool, error) {\n\t\t\tcurrentState, err := readMachineState(api, id)\n\t\t\treturn currentState == state, err\n\t\t},\n\t\tmachineStateChangeCheckInterval,\n\t\tmachineStateChangeTimeout,\n\t)\n}", "func waitForHelmRunning(ctx context.Context, configPath string) error {\n\tfor {\n\t\tcmd := exec.Command(\"helm\", \"ls\", \"--kubeconfig\", configPath)\n\t\tvar out bytes.Buffer\n\t\tcmd.Stderr = &out\n\t\tcmd.Run()\n\t\tif out.String() == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.Wrap(ctx.Err(), \"timed out waiting for helm to become ready\")\n\t\tcase <-time.After(5 * time.Second):\n\t\t}\n\t}\n}", "func waitForApiServerToBeUp(svcMasterIp string, sshClientConfig *ssh.ClientConfig,\n\ttimeout time.Duration) error {\n\tkubeConfigPath := GetAndExpectStringEnvVar(gcKubeConfigPath)\n\twaitErr := wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\tcmd := fmt.Sprintf(\"kubectl get ns,sc --kubeconfig %s\",\n\t\t\tkubeConfigPath)\n\t\tframework.Logf(\"Invoking command '%v' on host %v\", cmd,\n\t\t\tsvcMasterIp)\n\t\tcmdResult, err := sshExec(sshClientConfig, svcMasterIp,\n\t\t\tcmd)\n\t\tframework.Logf(\"result %v\", cmdResult)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif err == nil {\n\t\t\tframework.Logf(\"Apiserver is fully up\")\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn waitErr\n}", "func triggerOnChaosHTTPProbe(probe v1alpha1.ProbeAttributes, clients clients.ClientSets, chaosresult *types.ResultDetails, chaosDetails *types.ChaosDetails) {\n\n\tvar isExperimentFailed bool\n\tduration := chaosDetails.ChaosDuration\n\t// waiting for initial delay\n\tif probe.RunProperties.InitialDelaySeconds != 0 {\n\t\tlog.Infof(\"[Wait]: Waiting for %vs before probe execution\", probe.RunProperties.InitialDelaySeconds)\n\t\ttime.Sleep(time.Duration(probe.RunProperties.InitialDelaySeconds) * time.Second)\n\t\tduration = math.Maximum(0, duration-probe.RunProperties.InitialDelaySeconds)\n\t}\n\n\tvar endTime <-chan time.Time\n\ttimeDelay := time.Duration(duration) * time.Second\n\n\t// it trigger the http probe for the entire duration of chaos and it fails, if any error encounter\n\t// it marked the error for the probes, if any\nloop:\n\tfor {\n\t\tendTime = time.After(timeDelay)\n\t\tselect {\n\t\tcase <-endTime:\n\t\t\tlog.Infof(\"[Chaos]: Time is up for the %v probe\", probe.Name)\n\t\t\tendTime = nil\n\t\t\tbreak loop\n\t\tdefault:\n\t\t\terr = triggerHTTPProbe(probe, chaosresult)\n\t\t\t// record the error inside the probeDetails, we are maintaining a dedicated variable for the err, inside probeDetails\n\t\t\tif err != nil {\n\t\t\t\tfor index := range chaosresult.ProbeDetails {\n\t\t\t\t\tif chaosresult.ProbeDetails[index].Name == probe.Name {\n\t\t\t\t\t\tchaosresult.ProbeDetails[index].IsProbeFailedWithError = err\n\t\t\t\t\t\tisExperimentFailed = true\n\t\t\t\t\t\tbreak loop\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// waiting for the probe polling interval\n\t\t\ttime.Sleep(time.Duration(probe.RunProperties.ProbePollingInterval) * time.Second)\n\t\t}\n\t}\n\t// if experiment fails and stopOnfailure is provided as true then it will patch the chaosengine for abort\n\t// if experiment fails but stopOnfailure is provided as false then it will continue the execution\n\t// and failed the experiment in the end\n\tif isExperimentFailed && probe.RunProperties.StopOnFailure {\n\t\tif err := stopChaosEngine(probe, clients, chaosresult, chaosDetails); err != nil {\n\t\t\tlog.Errorf(\"unable to patch chaosengine to stop, err: %v\", err)\n\t\t}\n\t}\n}", "func (st *AKSAddonPreflightStep) Execute(_ context.Context, _ []string, log logr.Logger) {\n\tconst (\n\t\tnamespace = \"kube-system\"\n\t\tname = \"preflight\"\n\t)\n\tvar err error\n\n\tlog.Info(\"start\")\n\n\tst.update(v1.StateRunning, \"check api-server connection\")\n\n\t// Remove possible leftover probe pod.\n\ts, _ := st.Kubectl.PodState(st.KCPath, namespace, name)\n\tif s != \"\" {\n\t\t// Pod already present, delete it\n\t\terr = st.Kubectl.PodDelete(st.KCPath, namespace, name)\n\t\tif err != nil {\n\t\t\tst.error2(err, \"delete pod\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Run probe.\n\t// TODO parameterize image (consider using envop config for this)\n\terr = st.Kubectl.PodRun(st.KCPath, namespace, name, \"docker.io/curlimages/curl:7.72.0\",\n\t\t\"until curl -ksS --max-time 2 https://kubernetes.default | grep Status ; do date -Iseconds; sleep 5 ; done\")\n\tif err != nil {\n\t\tst.error2(err, \"run pod\")\n\t\treturn\n\t}\n\t// Check for completion.\n\ts = \"\"\n\tend := time.Now().Add(time.Minute)\n\tfor exp := backoff.NewExponential(10 * time.Second); !time.Now().After(end); exp.Sleep() {\n\t\ts, err = st.Kubectl.PodState(st.KCPath, namespace, name)\n\t\t// err is included in Msg below\n\t\tif s == \"PodCompleted\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif s != \"PodCompleted\" {\n\t\t// Return with state Running so this step gets picked up again.\n\t\tvar errMsg string\n\t\tif err != nil {\n\t\t\terrMsg = fmt.Sprintf(\": %s\", err.Error())\n\t\t} else {\n\t\t\terrMsg = fmt.Sprintf(\": %s\", s)\n\t\t}\n\t\tst.update(v1.StateRunning, fmt.Sprintf(\"waiting for %s pod completion%s\", name, errMsg))\n\t\treturn\n\t}\n\n\tst.update(v1.StateReady, fmt.Sprintf(\"%s completed\", name))\n}", "func main() {\n\tc, err := client.Dial(client.Options{\n\t\tHostPort: client.DefaultHostPort,\n\t})\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to create client\", err)\n\t}\n\tdefer c.Close()\n\n\tworkflowOptions := client.StartWorkflowOptions{\n\t\tID: updatabletimer.WorkflowID,\n\t\tTaskQueue: updatabletimer.TaskQueue,\n\t}\n\n\twakeUpTime := time.Now().Add(30 * time.Second)\n\twe, err := c.ExecuteWorkflow(context.Background(), workflowOptions, updatabletimer.Workflow, wakeUpTime)\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to start workflow\", err)\n\t}\n\tlog.Println(\"Started workflow that is going to block on an updatable timer\",\n\t\t\"WorkflowID\", we.GetID(), \"RunID\", we.GetRunID(), \"WakeUpTime\", wakeUpTime)\n}", "func waitForDeployment(getDeploymentFunc func() (*appsv1.Deployment, error), interval, timeout time.Duration) error {\n\treturn wait.PollImmediate(interval, timeout, func() (bool, error) {\n\t\tdeployment, err := getDeploymentFunc()\n\t\tif err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\tframework.Logf(\"deployment not found, continue waiting: %s\", err)\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tframework.Logf(\"error while deploying, error %s\", err)\n\t\t\treturn false, err\n\t\t}\n\t\tframework.Logf(\"deployment status %s\", &deployment.Status)\n\t\treturn util.DeploymentComplete(deployment, &deployment.Status), nil\n\t})\n}", "func waitForDeployToProcess(currentVersion time.Time, name, ip string) bool {\n\tebo := backoff.NewExponentialBackOff()\n\tebo.MaxElapsedTime = 10 * time.Second\n\tdeployError := backoff.Retry(safe.OperationWithRecover(func() error {\n\t\t// Configuration should have deployed successfully, confirm version match.\n\t\tnewVersion, exists, newErr := getDeployedVersion(ip)\n\t\tif newErr != nil {\n\t\t\treturn fmt.Errorf(\"could not get newly deployed configuration version: %v\", newErr)\n\t\t}\n\t\tif exists {\n\t\t\tif currentVersion.Equal(newVersion) {\n\t\t\t\t// The version we are trying to deploy is confirmed.\n\t\t\t\t// Return nil, to break out of the ebo.\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"deployment was not successful\")\n\t}), ebo)\n\n\tif deployError == nil {\n\t\t// The version we are trying to deploy is confirmed.\n\t\t// Return true, so that it will be removed from the deploy queue.\n\t\tlog.Debugf(\"Successfully deployed version for pod %s: %s\", name, currentVersion)\n\t\treturn true\n\t}\n\treturn false\n}", "func (a *Application) Wait() {\n\t<-a.terminated\n\tlog.Printf(\"[TEST] thats all folks\")\n}", "func main() {\n\tvar parameters WhSvrParameters\n\n\t// get command line parameters\n\tflag.IntVar(&parameters.port, \"port\", 8443, \"Webhook server port.\")\n\tflag.StringVar(&parameters.certFile, \"tlsCertFile\", \"/etc/admissioner/certs/cert.pem\", \"File containing the x509 Certificate for HTTPS.\")\n\tflag.StringVar(&parameters.keyFile, \"tlsKeyFile\", \"/etc/admissioner/certs/key.pem\", \"File containing the x509 private key to --tlsCertFile.\")\n\tflag.Parse()\n\n\tpair, err := tls.LoadX509KeyPair(parameters.certFile, parameters.keyFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tcert, err := x509.ParseCertificate(pair.Certificate[0])\n\tctx := context.WithValue(context.Background(), CtxCert, cert)\n\n\twhsvr := &WebhookServer{\n\t\tserver: &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%v\", parameters.port),\n\t\t\tTLSConfig: &tls.Config{Certificates: []tls.Certificate{pair}},\n\t\t\tBaseContext: func(listener net.Listener) context.Context {\n\t\t\t\treturn ctx\n\t\t\t},\n\t\t},\n\t}\n\n\t// define http server and server handler\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/mutate\", whsvr.serve)\n\twhsvr.server.Handler = mux\n\n\t// start webhook server in new routine\n\tgo func() {\n\t\tif err := whsvr.server.ListenAndServeTLS(\"\", \"\"); err != nil {\n\t\t\tglog.Errorf(\"Failed to listen and serve webhook server: %v\", err)\n\t\t}\n\t}()\n\n\tglog.Info(\"Server started\")\n\n\t// listening OS shutdown singal\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)\n\t<-signalChan\n\n\tglog.Infof(\"Got OS shutdown signal, shutting down webhook server gracefully...\")\n\twhsvr.server.Shutdown(context.Background())\n}", "func waitForInit() error {\n\tstart := time.Now()\n\tmaxEnd := start.Add(time.Minute)\n\tfor {\n\t\t// Check for existence of vpcCniInitDonePath\n\t\tif _, err := os.Stat(vpcCniInitDonePath); err == nil {\n\t\t\t// Delete the done file in case of a reboot of the node or restart of the container (force init container to run again)\n\t\t\tif err := os.Remove(vpcCniInitDonePath); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// If file deletion fails, log and allow retry\n\t\t\tlog.Errorf(\"Failed to delete file: %s\", vpcCniInitDonePath)\n\t\t}\n\t\tif time.Now().After(maxEnd) {\n\t\t\treturn errors.Errorf(\"time exceeded\")\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func WaitForStopEvent(bc BackgroundContext, w WaitForStopEventConfiguration) {\n\tfor {\n\t\tselect {\n\t\tcase stopEvent := <-bc.Stop:\n\t\t\thandleStopEvent(stopEvent, bc, w)\n\t\t\treturn\n\t\tdefault:\n\t\t\tw.OnWait(bc, w)\n\t\t}\n\t\ttime.Sleep(w.WaitTime)\n\t}\n}", "func (m *Manager) WaitUntilRunning() {\n\tfor {\n\t\tm.mu.Lock()\n\n\t\tif m.ctx != nil {\n\t\t\tm.mu.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\tstarted := m.started\n\t\tm.mu.Unlock()\n\n\t\t// Block until we have been started.\n\t\t<-started\n\t}\n}", "func waitForConductor(ctx context.Context, client *gophercloud.ServiceClient) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for conductor API to become available...\")\n\t\t\tdriverCount := 0\n\n\t\t\tdrivers.ListDrivers(client, drivers.ListDriversOpts{\n\t\t\t\tDetail: false,\n\t\t\t}).EachPage(func(page pagination.Page) (bool, error) {\n\t\t\t\tactual, err := drivers.ExtractDrivers(page)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tdriverCount += len(actual)\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\t// If we have any drivers, conductor is up.\n\t\t\tif driverCount > 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func (c *Controller) waitForShutdown(stopCh <-chan struct{}) {\n\t<-stopCh\n\tc.Queue.ShutDown()\n\tlog.Debug(\"pgcluster Contoller: received stop signal, worker queue told to shutdown\")\n}", "func TestRequestStopFromMovingUp(t *testing.T) {\n\t// setup\n\tdwController := setup(t, 2, Up, []common.PiPin{common.OpenerStop})\n\n\t// test\n\tdwController.SetStopRequested() // send the stop request\n\twaitForStatus(t, 2, 2, Stopped, dwController, 3*time.Second) // verify that the dumbwaiter is now stopped\n}", "func (s *SourceControl) WaitForStopTestingOnly(dummy *string, reply *bool) error {\n\tfor s.isSourceActive {\n\t\ts.handlePossibleStoppedSource()\n\t\ttime.Sleep(1 * time.Millisecond)\n\t}\n\treturn nil\n}", "func Wait(dev *model.Dev, okStatusList []config.UpState) error {\n\toktetoLog.Spinner(\"Activating your development container...\")\n\toktetoLog.StartSpinner()\n\tdefer oktetoLog.StopSpinner()\n\n\tstop := make(chan os.Signal, 1)\n\tsignal.Notify(stop, os.Interrupt)\n\texit := make(chan error, 1)\n\n\tgo func() {\n\n\t\tticker := time.NewTicker(500 * time.Millisecond)\n\t\tfor {\n\t\t\tstatus, err := config.GetState(dev.Name, dev.Namespace)\n\t\t\tif err != nil {\n\t\t\t\texit <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif status == config.Failed {\n\t\t\t\texit <- fmt.Errorf(\"your development container has failed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, okStatus := range okStatusList {\n\t\t\t\tif status == okStatus {\n\t\t\t\t\texit <- nil\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\t<-ticker.C\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-stop:\n\t\toktetoLog.Infof(\"CTRL+C received, starting shutdown sequence\")\n\t\toktetoLog.StopSpinner()\n\t\treturn oktetoErrors.ErrIntSig\n\tcase err := <-exit:\n\t\tif err != nil {\n\t\t\toktetoLog.Infof(\"exit signal received due to error: %s\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func waitForWatchListener(ctx context.Context, t *testing.T, xdsC *fakeclient.Client, wantTarget string) {\n\tt.Helper()\n\n\tgotTarget, err := xdsC.WaitForWatchListener(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchService failed with error: %v\", err)\n\t}\n\tif gotTarget != wantTarget {\n\t\tt.Fatalf(\"xdsClient.WatchService() called with target: %v, want %v\", gotTarget, wantTarget)\n\t}\n}", "func (s *service) serviceResponseCheckLoop() {\n\tgo func() {\n\t\tfor {\n\n\t\t\tfor s.connection == nil || !s.connected {\n\t\t\t\ttime.Sleep(5 * 1E9) // We have time for the feedback loop, let's just wait\n\t\t\t}\n\n\t\t\t// Check service response for returned errors\n\t\t\tvar status uint8\n\t\t\tvar identifier uint32\n\t\t\tif s.queue.Env != Test {\n\t\t\t\tstatus, identifier = checkServiceResponse(s.connection)\n\t\t\t} else {\n\t\t\t\t// For testing purposes\n\t\t\t\tstatus, identifier = checkServiceResponse(bytes.NewBuffer([]byte{}))\n\t\t\t}\n\n\t\t\ts.handleServiceError(status, identifier)\n\t\t}\n\t}()\n}", "func waitForGlusterContainer() error {\n\n\t//Check if docker gluster container is up and running\n\tfor {\n\t\tglusterServerContainerVal, err := helpers.GetSystemDockerNode(\"gluster-server\")\n\t\tif err != nil {\n\t\t\trwolog.Error(\"Error in checking docker gluster container for status \", err.Error())\n\t\t\treturn err\n\t\t}\n\n\t\tif len(glusterServerContainerVal) > 0 {\n\t\t\tbreak\n\t\t} else {\n\t\t\trwolog.Debug(\"Sleeping for 10 seconds to get gluster docker container up\")\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t}\n\treturn nil\n}", "func (envManager *TestEnvManager) WaitUntilReady() (bool, error) {\n\tlog.Println(\"Start checking components' status\")\n\tretry := u.Retrier{\n\t\tBaseDelay: 1 * time.Second,\n\t\tMaxDelay: 10 * time.Second,\n\t\tRetries: 8,\n\t}\n\n\tready := false\n\tretryFn := func(_ context.Context, i int) error {\n\t\tfor _, comp := range envManager.testEnv.GetComponents() {\n\t\t\tif alive, err := comp.IsAlive(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to comfirm compoment %s is alive %v\", comp.GetName(), err)\n\t\t\t} else if !alive {\n\t\t\t\treturn fmt.Errorf(\"component %s is not alive\", comp.GetName())\n\t\t\t}\n\t\t}\n\n\t\tready = true\n\t\tlog.Println(\"All components are ready\")\n\t\treturn nil\n\t}\n\n\t_, err := retry.Retry(context.Background(), retryFn)\n\treturn ready, err\n}", "func waitForShutdown(ctx context.Context, srv *http.Server,\n\tlog *zap.SugaredLogger) {\n\tinterruptChan := make(chan os.Signal, 1)\n\tsignal.Notify(interruptChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)\n\n\t// Block until we receive our signal.\n\tsig := <-interruptChan\n\tlog.Debugw(\"Termination signal received\", \"signal\", sig)\n\n\t// Create a deadline to wait for.\n\tctx, cancel := context.WithTimeout(ctx, time.Second*10)\n\tdefer cancel()\n\tsrv.Shutdown(ctx)\n\n\tlog.Infof(\"Shutting down\")\n}", "func WaitForChromeVoxStopSpeaking(ctx context.Context, chromeVoxConn *chrome.Conn) error {\n\tif err := testing.Poll(ctx, func(ctx context.Context) error {\n\t\tvar isSpeaking bool\n\t\tif err := chromeVoxConn.Eval(ctx, \"cvox.ChromeVox.tts.isSpeaking()\", &isSpeaking); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif isSpeaking {\n\t\t\treturn errors.New(\"ChromeVox is speaking\")\n\t\t}\n\t\treturn nil\n\t}, &testing.PollOptions{Timeout: 30 * time.Second}); err != nil {\n\t\treturn errors.Wrap(err, \"timed out waiting for ChromeVox to finish speaking\")\n\t}\n\treturn nil\n}", "func WaitForNotify() {\n\tcount++\n\t<-done\n}", "func (d *conntrackInstallerInUbuntu) WaitForStart() (ok bool, err error) {\n\tok = true\n\treturn\n}", "func waitForMachineSetToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForMachineSetStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(machineSet *capiv1alpha1.MachineSet) bool { return machineSet != nil },\n\t)\n}", "func (b *Bot) WaitForHalt() {\n\tb.msgDispatchers.Wait()\n\tb.dispatcher.WaitForCompletion()\n\tb.serversProtect.RLock()\n\tfor _, srv := range b.servers {\n\t\tsrv.dispatcher.WaitForCompletion()\n\t}\n\tb.serversProtect.RUnlock()\n}", "func (p Plugin) Webhook() error {\n\treadyToListen := false\n\tbot, err := p.Bot()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tmux := p.Handler(bot)\n\n\tif p.Config.Tunnel {\n\t\tif p.Config.Debug {\n\t\t\tgotunnelme.Debug = true\n\t\t}\n\n\t\tdomain, err := p.getTunnelDomain()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\ttunnel := gotunnelme.NewTunnel()\n\t\turl, err := tunnel.GetUrl(domain)\n\t\tif err != nil {\n\t\t\tpanic(\"Could not get localtunnel.me URL. \" + err.Error())\n\t\t}\n\t\tgo func() {\n\t\t\tfor !readyToListen {\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t}\n\t\t\tc := color.New(color.FgYellow)\n\t\t\tc.Println(\"Tunnel URL:\", url)\n\t\t\terr := tunnel.CreateTunnel(p.Config.Port)\n\t\t\tif err != nil {\n\t\t\t\tpanic(\"Could not create tunnel. \" + err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\n\treadyToListen = true\n\tif p.Config.Port != 443 && !p.Config.AutoTLS {\n\t\tlog.Println(\"Line Webhook Server Listin on \" + strconv.Itoa(p.Config.Port) + \" port\")\n\t\tif err := http.ListenAndServe(\":\"+strconv.Itoa(p.Config.Port), mux); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tif p.Config.AutoTLS && len(p.Config.Host) != 0 {\n\t\tlog.Println(\"Line Webhook Server Listin on 443 port, hostname: \" + strings.Join(p.Config.Host, \", \"))\n\t\treturn http.Serve(autocert.NewListener(p.Config.Host...), mux)\n\t}\n\n\treturn nil\n}", "func waitForRunning(s drmaa.Session, jobId string, hostCh chan string) {\n\t// Wait for running job\n\td, _ := time.ParseDuration(\"500ms\")\n\tps, _ := s.JobPs(jobId)\n\tfor ps != drmaa.PsRunning {\n\t\ttime.Sleep(d)\n\t\tps, _ = s.JobPs(jobId)\n\t}\n\n\t// Get hostname\n\tjobStatus, err := gestatus.GetJobStatus(&s, jobId)\n\tif err != nil {\n\t\tfmt.Printf(\"Error in getting hostname for job %s: %s\\n\", jobId, err.Error())\n\t\thostCh <- \"\"\n\t\treturn\n\t}\n\thostname := jobStatus.DestinationHostList()\n\thostCh <- strings.Join(hostname, \"\")\n}", "func (tfcm *TestFCM) wait(count int) {\n\ttime.Sleep(time.Duration(count) * tfcm.timeout)\n}", "func waitForShutdown() {\n\tsigint := make(chan os.Signal, 1)\n\t// syscall.SIGTERM is not pressent on all plattforms. Since the autoupdate\n\t// service is only run on linux, this is ok. If other plattforms should be\n\t// supported, os.Interrupt should be used instead.\n\tsignal.Notify(sigint, syscall.SIGINT, syscall.SIGTERM)\n\t<-sigint\n\tgo func() {\n\t\t<-sigint\n\t\tos.Exit(1)\n\t}()\n}", "func waitForShutdown() {\n\tsigint := make(chan os.Signal, 1)\n\t// syscall.SIGTERM is not pressent on all plattforms. Since the autoupdate\n\t// service is only run on linux, this is ok. If other plattforms should be\n\t// supported, os.Interrupt should be used instead.\n\tsignal.Notify(sigint, syscall.SIGINT, syscall.SIGTERM)\n\t<-sigint\n\tgo func() {\n\t\t<-sigint\n\t\tos.Exit(1)\n\t}()\n}", "func (c *myClient) waitForEnvironmentsReady(p, t int, envList ...string) (err error) {\n\n\tlogger.Infof(\"Waiting up to %v seconds for the environments to be ready\", t)\n\ttimeOut := 0\n\tfor timeOut < t {\n\t\tlogger.Info(\"Waiting for the environments\")\n\t\ttime.Sleep(time.Duration(p) * time.Second)\n\t\ttimeOut = timeOut + p\n\t\tif err = c.checkForBusyEnvironments(envList); err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif timeOut >= t {\n\t\terr = fmt.Errorf(\"waitForEnvironmentsReady timed out\")\n\t}\n\treturn err\n}", "func (c *Client) doWaitForStatus(eniID string, checkNum, checkInterval int, finalStatus string) error {\n\tfor i := 0; i < checkNum; i++ {\n\t\ttime.Sleep(time.Second * time.Duration(checkInterval))\n\t\tenis, err := c.queryENI(eniID, \"\", \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, eni := range enis {\n\t\t\tif *eni.NetworkInterfaceId == eniID {\n\t\t\t\tswitch *eni.State {\n\t\t\t\tcase ENI_STATUS_AVAILABLE:\n\t\t\t\t\tswitch finalStatus {\n\t\t\t\t\tcase ENI_STATUS_ATTACHED:\n\t\t\t\t\t\tif eni.Attachment != nil && eni.Attachment.InstanceId != nil {\n\t\t\t\t\t\t\tblog.Infof(\"eni %s is attached\", eniID)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblog.Infof(\"eni %s is not attached\", eniID)\n\t\t\t\t\tcase ENI_STATUS_DETACHED:\n\t\t\t\t\t\tif eni.Attachment == nil {\n\t\t\t\t\t\t\tblog.Infof(\"eni %s is detached\", eniID)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblog.Infof(\"eni %s is not detached\", eniID)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tblog.Infof(\"eni %s is %s now\", eniID, *eni.State)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase ENI_STATUS_PENDING, ENI_STATUS_ATTACHING, ENI_STATUS_DETACHING, ENI_STATUS_DELETING:\n\t\t\t\t\tblog.Infof(\"eni %s is %s\", eniID, *eni.State)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tblog.Errorf(\"timeout when wait for eni %s\", eniID)\n\treturn fmt.Errorf(\"timeout when wait for eni %s\", eniID)\n}", "func (app *Application) runAndWaitForShutdownEvent() {\n\tapp.logger.Info(\"Everything is ready. Begin running and processing data.\")\n\n\t// Plug SIGTERM signal into a channel.\n\tsignalsChannel := make(chan os.Signal, 1)\n\tsignal.Notify(signalsChannel, os.Interrupt, syscall.SIGTERM)\n\n\t// set the channel to stop testing.\n\tapp.stopTestChan = make(chan struct{})\n\t// notify tests that it is ready.\n\tclose(app.readyChan)\n\n\tselect {\n\tcase err := <-app.asyncErrorChannel:\n\t\tapp.logger.Error(\"Asynchronous error received, terminating process\", zap.Error(err))\n\tcase s := <-signalsChannel:\n\t\tapp.logger.Info(\"Received signal from OS\", zap.String(\"signal\", s.String()))\n\tcase <-app.stopTestChan:\n\t\tapp.logger.Info(\"Received stop test request\")\n\t}\n}", "func main() {\n\trand.Seed(time.Now().UnixNano())\n\n\tvar conf DaemonConf\n\tconf = DaemonConf{\n\t\tHttpport: \"8080\",\n\t\tAuthToken: randomString(8),\n\t}\n\terr := cfgp.Parse(&conf)\n\tif err != nil {\n\t\tlog.Fatalln(\"parsing conf\", err)\n\t}\n\n\tbadExitCode := false\n\tSetupLoggers(os.Stdout, os.Stderr)\n\n\tif conf.NewRelicToken != \"\" && conf.NewRelicAppID != \"\" {\n\t\tgo FetchNewRelic(conf.NewRelicToken, conf.NewRelicAppID)\n\t}\n\n\tapi := slack.New(conf.SlackToken)\n\trtm := api.NewRTM()\n\tif conf.SlackToken != \"\" {\n\t\tgo rtm.ManageConnection()\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer func() {\n\t\t\t\twg.Done()\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\t// TODO try a last message sending to Slack via REST\n\t\t\t\t\t// user PostMessage\n\t\t\t\t\tErrorLogger.Println(r)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tServeRTM(rtm)\n\t\t}()\n\t}\n\n\thttp.HandleFunc(\"/status\", StatusHandlerFunc)\n\thttp.HandleFunc(\n\t\t\"/gh-webhooks\",\n\t\tGHWebhooksHandlerFunc(rtm.IncomingEvents),\n\t)\n\thttp.HandleFunc(\n\t\t\"/message\",\n\t\tMustAuth(\n\t\t\tconf.AuthToken,\n\t\t\tGenericMessageHandler(rtm.IncomingEvents),\n\t\t),\n\t)\n\thttp.HandleFunc(\n\t\t\"/new-relic\",\n\t\tNewRelicHandler(rtm.IncomingEvents),\n\t)\n\taddrString := fmt.Sprintf(\"%s:%s\", conf.Httpaddress, conf.Httpport)\n\tInfoLogger.Println(\"start listening on:\", addrString)\n\tif err := http.ListenAndServe(addrString, nil); err != nil {\n\t\tErrorLogger.Println(err)\n\t\tbadExitCode = true\n\t}\n\n\twg.Wait()\n\t// FIXME send a message to RTM goroutine or deadlock\n\tif badExitCode {\n\t\tos.Exit(1)\n\t}\n}", "func webhookHandler(w http.ResponseWriter, r *http.Request) {\n\t// parse request body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tfmt.Println(string(body))\n\t// decoder := json.NewDecoder(r.Body)\n\t// Get student public URL\n\t// run Webdriver IO test against the URL and get its result\n\t// Store result and SHA\n\t// publish status to Github\n\tfmt.Println(\"Hello\")\n}", "func main() {\n\n\tcfg := webhook.LoadConfiguration(\"./config/\")\n\tqueue := webhook.NewMessagingQueue(cfg.QueueURI, cfg.ExchangeName, cfg.PoolConfig)\n\thook := webhook.NewWebHook(queue)\n\n\tiris.Post(\"/\" + cfg.EndpointName, hook.Process)\n\tgo cleanup(queue)\n\n\tiris.Listen(fmt.Sprintf(\":%d\", cfg.WebServerPort))\n\n}", "func triggerContinuousHTTPProbe(probe v1alpha1.ProbeAttributes, clients clients.ClientSets, chaosresult *types.ResultDetails, chaosDetails *types.ChaosDetails) {\n\tvar isExperimentFailed bool\n\t// waiting for initial delay\n\tif probe.RunProperties.InitialDelaySeconds != 0 {\n\t\tlog.Infof(\"[Wait]: Waiting for %vs before probe execution\", probe.RunProperties.InitialDelaySeconds)\n\t\ttime.Sleep(time.Duration(probe.RunProperties.InitialDelaySeconds) * time.Second)\n\t}\n\n\t// it trigger the http probe for the entire duration of chaos and it fails, if any error encounter\n\t// it marked the error for the probes, if any\nloop:\n\tfor {\n\t\terr = triggerHTTPProbe(probe, chaosresult)\n\t\t// record the error inside the probeDetails, we are maintaining a dedicated variable for the err, inside probeDetails\n\t\tif err != nil {\n\t\t\tfor index := range chaosresult.ProbeDetails {\n\t\t\t\tif chaosresult.ProbeDetails[index].Name == probe.Name {\n\t\t\t\t\tchaosresult.ProbeDetails[index].IsProbeFailedWithError = err\n\t\t\t\t\tlog.Errorf(\"The %v http probe has been Failed, err: %v\", probe.Name, err)\n\t\t\t\t\tisExperimentFailed = true\n\t\t\t\t\tbreak loop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// waiting for the probe polling interval\n\t\ttime.Sleep(time.Duration(probe.RunProperties.ProbePollingInterval) * time.Second)\n\t}\n\t// if experiment fails and stopOnfailure is provided as true then it will patch the chaosengine for abort\n\t// if experiment fails but stopOnfailure is provided as false then it will continue the execution\n\t// and failed the experiment in the end\n\tif isExperimentFailed && probe.RunProperties.StopOnFailure {\n\t\tif err := stopChaosEngine(probe, clients, chaosresult, chaosDetails); err != nil {\n\t\t\tlog.Errorf(\"unable to patch chaosengine to stop, err: %v\", err)\n\t\t}\n\t}\n}", "func waitReady(project, name, region string) error {\n\twait := time.Minute * 4\n\tdeadline := time.Now().Add(wait)\n\tfor time.Now().Before(deadline) {\n\t\tsvc, err := getService(project, name, region)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to query Service for readiness: %w\", err)\n\t\t}\n\n\t\tfor _, cond := range svc.Status.Conditions {\n\t\t\tif cond.Type == \"Ready\" {\n\t\t\t\tif cond.Status == \"True\" {\n\t\t\t\t\treturn nil\n\t\t\t\t} else if cond.Status == \"False\" {\n\t\t\t\t\treturn fmt.Errorf(\"reason=%s message=%s\", cond.Reason, cond.Message)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second * 2)\n\t}\n\treturn fmt.Errorf(\"the service did not become ready in %s, check Cloud Console for logs to see why it failed\", wait)\n}", "func WaitForRun(ctx context.Context, actions WorkflowRuns, owner, repo, path string, runID int64) (string, error) {\n\tticker := time.NewTicker(1 * time.Minute)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\trun, _, err := actions.GetWorkflowRunByID(ctx, owner, repo, runID)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", trace.Wrap(err, \"Failed polling run\")\n\t\t\t}\n\n\t\t\tlog.Printf(\"Workflow status: %s\", run.GetStatus())\n\n\t\t\tif run.GetStatus() == \"completed\" {\n\t\t\t\treturn run.GetConclusion(), nil\n\t\t\t}\n\n\t\tcase <-ctx.Done():\n\t\t\treturn \"\", ctx.Err()\n\t\t}\n\t}\n}", "func (m *Manager) Wait(ctx context.Context, uuid string) error {\n\t// Find the workflow.\n\trw, err := m.runningWorkflow(uuid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Just wait for it.\n\tselect {\n\tcase <-rw.done:\n\t\tbreak\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\treturn nil\n}", "func TestWaitUntilRunning(t *testing.T) {\n\tts := memorytopo.NewServer(\"cell1\")\n\tm := NewManager(ts)\n\n\t// Start it 3 times i.e. restart it 2 times.\n\tfor i := 1; i <= 3; i++ {\n\t\t// Run the manager in the background.\n\t\twg, _, cancel := StartManager(m)\n\n\t\t// Shut it down and wait for the shutdown to complete.\n\t\tcancel()\n\t\twg.Wait()\n\t}\n}", "func (c *Controller) waitForShutdown(stopCh <-chan struct{}) {\n\t<-stopCh\n\tc.workqueue.ShutDown()\n\tlog.Debug(\"Namespace Contoller: received stop signal, worker queue told to shutdown\")\n}", "func (f *FakeCmdRunner) Wait() error {\n\treturn f.Err\n}", "func waitForPromise() {\n\tfor {\n\t\t<-waitPromisChan\n\t\twaiting = true\n\t\ttime.Sleep(2 * time.Second)\n\t\twaiting = false\n\t\tcheckPromises()\n\t}\n}", "func (m *wsNotificationManager) WaitForShutdown() {\n\tm.wg.Wait()\n}", "func waitForShutdown(srv *http.Server) {\n\tinterruptChan := make(chan os.Signal, 1)\n\tsignal.Notify(interruptChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)\n\n\t// Block until we receive our signal.\n\t<-interruptChan\n\n\t// Create a deadline to wait for.\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tdefer cancel()\n\tsrv.Shutdown(ctx)\n\n\tlog.Println(\"Shutting down\")\n\tos.Exit(0)\n}", "func waitRun(contID string) error {\n\treturn daemon.WaitInspectWithArgs(dockerBinary, contID, \"{{.State.Running}}\", \"true\", 5*time.Second)\n}", "func initAndRun(exitCode int) {\n\tinitTestingEnv()\n\tif blockingCtx := waitForEnvoy(); blockingCtx != nil {\n\t\t<-blockingCtx.Done()\n\t\terr := blockingCtx.Err()\n\t\tif err == nil || errors.Is(err, context.Canceled) {\n\t\t\tlog(\"Blocking finished, Envoy has started\")\n\t\t} else if errors.Is(err, context.DeadlineExceeded) {\n\t\t\tpanic(errors.New(\"timeout reached while waiting for Envoy to start\"))\n\t\t} else {\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n\tif exitCode >= 0 {\n\t\tkill(exitCode)\n\t}\n}", "func waitForEvent(t *testing.T, con *websocket.Conn, eventid string, dieOnTimeout bool, f func(), check func(string, []byte) error) {\n\t// go routine to wait for webscoket msg\n\tgoodCh := make(chan []byte)\n\terrCh := make(chan error)\n\tquitCh := make(chan struct{})\n\tdefer close(quitCh)\n\n\t// Read message\n\tgo func() {\n\t\tfor {\n\t\t\t_, p, err := con.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\terrCh <- err\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\t// if the event id isnt what we're waiting on\n\t\t\t\t// ignore it\n\t\t\t\tvar response ctypes.Response\n\t\t\t\tvar err error\n\t\t\t\twire.ReadJSON(&response, p, &err)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrCh <- err\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tevent, ok := response.Result.(*ctypes.ResultEvent)\n\t\t\t\tif ok && event.Event == eventid {\n\t\t\t\t\tgoodCh <- p\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\t// do stuff (transactions)\n\tf()\n\n\t// wait for an event or timeout\n\ttimeout := time.NewTimer(10 * time.Second)\n\tselect {\n\tcase <-timeout.C:\n\t\tif dieOnTimeout {\n\t\t\tcon.Close()\n\t\t\tt.Fatalf(\"%s event was not received in time\", eventid)\n\t\t}\n\t\t// else that's great, we didn't hear the event\n\t\t// and we shouldn't have\n\tcase p := <-goodCh:\n\t\tif dieOnTimeout {\n\t\t\t// message was received and expected\n\t\t\t// run the check\n\t\t\terr := check(eventid, p)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t\tpanic(err) // Show the stack trace.\n\t\t\t}\n\t\t} else {\n\t\t\tcon.Close()\n\t\t\tt.Fatalf(\"%s event was not expected\", eventid)\n\t\t}\n\tcase err := <-errCh:\n\t\tt.Fatal(err)\n\t\tpanic(err) // Show the stack trace.\n\t}\n}", "func (d *vimInstallerInUbuntu) WaitForStart() (ok bool, err error) {\n\tok = true\n\treturn\n}", "func waitForGuestbookResponse(ctx context.Context, c clientset.Interface, cmd, arg, expectedResponse string, timeout time.Duration, ns string) bool {\n\tfor start := time.Now(); time.Since(start) < timeout && ctx.Err() == nil; time.Sleep(5 * time.Second) {\n\t\tres, err := makeRequestToGuestbook(ctx, c, cmd, arg, ns)\n\t\tif err == nil && res == expectedResponse {\n\t\t\treturn true\n\t\t}\n\t\tframework.Logf(\"Failed to get response from guestbook. err: %v, response: %s\", err, res)\n\t}\n\treturn false\n}", "func waitForURL(c *C, url string) error {\n\tclient := http.DefaultClient\n\tretries := 100\n\tfor retries > 0 {\n\t\tretries--\n\t\ttime.Sleep(200 * time.Millisecond)\n\t\tresp, err := client.Get(url)\n\t\tif err != nil {\n\t\t\tc.Logf(\"Got error, retries left: %d (error: %v)\", retries, err)\n\t\t\tcontinue\n\t\t}\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tc.Logf(\"Body is: %s\", body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tif resp.StatusCode == 200 {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}", "func (api *API) ProcessWebhook(c echo.Context) error {\n\tdata, err := ioutil.ReadAll(c.Request().Body)\n\tif err != nil {\n\t\tresponse := &MessageResponse{Status: enums.StatusError, Message: err.Error()}\n\t\treturn c.JSON(http.StatusBadRequest, response)\n\t}\n\tdefer func() { _ = c.Request().Body.Close() }()\n\tp, err := api.services.WebhookDispatcher.GetWebhookProcessor(c.Request().Context(), c.Request().Header, data)\n\tif err != nil {\n\t\tresponse := &MessageResponse{Status: enums.StatusError, Message: err.Error()}\n\t\treturn c.JSON(http.StatusBadRequest, response)\n\t}\n\n\tgo func() {\n\t\tif err := p.Process(c.Request().Context(), c.Request().Header, data); err != nil {\n\t\t\tlogger := logging.FromContext(c.Request().Context())\n\t\t\tlogger.WithField(\"error\", err).Warn(\"could not process webhook\")\n\t\t}\n\t}()\n\treturn c.JSON(http.StatusOK, &MessageResponse{Message: \"ok\"})\n}", "func (target *WebhookTarget) initWebhook() error {\n\targs := target.args\n\ttransport := target.transport\n\n\tif args.ClientCert != \"\" && args.ClientKey != \"\" {\n\t\tmanager, err := certs.NewManager(context.Background(), args.ClientCert, args.ClientKey, tls.LoadX509KeyPair)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmanager.ReloadOnSignal(syscall.SIGHUP) // allow reloads upon SIGHUP\n\t\ttransport.TLSClientConfig.GetClientCertificate = manager.GetClientCertificate\n\t}\n\ttarget.httpClient = &http.Client{Transport: transport}\n\n\tyes, err := target.isActive()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !yes {\n\t\treturn errNotConnected\n\t}\n\n\treturn nil\n}", "func waitForFailure(f *framework.Framework, name string, timeout time.Duration) {\n\tgomega.Expect(e2epod.WaitForPodCondition(f.ClientSet, f.Namespace.Name, name, fmt.Sprintf(\"%s or %s\", v1.PodSucceeded, v1.PodFailed), timeout,\n\t\tfunc(pod *v1.Pod) (bool, error) {\n\t\t\tswitch pod.Status.Phase {\n\t\t\tcase v1.PodFailed:\n\t\t\t\treturn true, nil\n\t\t\tcase v1.PodSucceeded:\n\t\t\t\treturn true, fmt.Errorf(\"pod %q successed with reason: %q, message: %q\", name, pod.Status.Reason, pod.Status.Message)\n\t\t\tdefault:\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t},\n\t)).To(gomega.Succeed(), \"wait for pod %q to fail\", name)\n}", "func waitForCRDEstablishment(clientset apiextensionsclient.Interface) error {\n\treturn wait.Poll(500*time.Millisecond, 60*time.Second, func() (bool, error) {\n\t\tsparkAppCrd, err := getCRD(clientset)\n\t\tfor _, cond := range sparkAppCrd.Status.Conditions {\n\t\t\tswitch cond.Type {\n\t\t\tcase apiextensionsv1beta1.Established:\n\t\t\t\tif cond.Status == apiextensionsv1beta1.ConditionTrue {\n\t\t\t\t\treturn true, err\n\t\t\t\t}\n\t\t\tcase apiextensionsv1beta1.NamesAccepted:\n\t\t\t\tif cond.Status == apiextensionsv1beta1.ConditionFalse {\n\t\t\t\t\tfmt.Printf(\"Name conflict: %v\\n\", cond.Reason)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false, err\n\t})\n}", "func (a *app) waitShutdown() {\n\t<-a.completeChan\n}", "func waitAndRouteNFTApprovedEvent(timeout time.Duration, asyncRes queue.TaskResult, tokenID *big.Int, confirmations chan<- *watchTokenMinted) {\n\t_, err := asyncRes.Get(timeout)\n\tconfirmations <- &watchTokenMinted{tokenID, err}\n}", "func waitForPodsToBeInTerminatingPhase(sshClientConfig *ssh.ClientConfig, svcMasterIP string,\n\tpodName string, namespace string, timeout time.Duration) error {\n\tkubeConfigPath := GetAndExpectStringEnvVar(gcKubeConfigPath)\n\twaitErr := wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\tcmd := fmt.Sprintf(\"kubectl get pod %s --kubeconfig %s -n %s --no-headers|awk '{print $3}'\",\n\t\t\tpodName, kubeConfigPath, namespace)\n\t\tframework.Logf(\"Invoking command '%v' on host %v\", cmd,\n\t\t\tsvcMasterIP)\n\t\tcmdResult, err := sshExec(sshClientConfig, svcMasterIP,\n\t\t\tcmd)\n\t\tif err != nil || cmdResult.Code != 0 {\n\t\t\tfssh.LogResult(cmdResult)\n\t\t\treturn false, fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\t\tcmd, svcMasterIP, err)\n\t\t}\n\n\t\tframework.Logf(\"result %v\", cmdResult)\n\t\tframework.Logf(\"stdout %s\", cmdResult.Stdout)\n\t\tpodPhase := strings.TrimSpace(cmdResult.Stdout)\n\t\tif podPhase == \"Terminating\" {\n\t\t\tframework.Logf(\"Pod %s is in terminating state\", podName)\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn waitErr\n}", "func WaitUntil(c *check.C, f CheckFunc) {\n\tc.Log(\"wait start\")\n\tfor i := 0; i < waitMaxRetry; i++ {\n\t\tif f(c) {\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(waitRetrySleep)\n\t}\n\tc.Fatal(\"wait timeout\")\n}", "func metadataWait() {\n\tfor {\n\t\treq, err := http.NewRequest(\"GET\", \"http://metadata.google.internal/computeMetadata/v1/instance/attributes/pushrev?wait_for_change=true\", nil)\n\t\tif err != nil {\n\t\t\tsklog.Errorf(\"Failed to create request: %s\", err)\n\t\t\tcontinue\n\t\t}\n\t\treq.Header.Set(\"Metadata-Flavor\", \"Google\")\n\t\t// We use the default client which should never timeout.\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err != nil || resp.StatusCode != 200 {\n\t\t\tsklog.Errorf(\"wait_for_change failed: %s\", err)\n\t\t\tif resp != nil {\n\t\t\t\tsklog.Errorf(\"Response: %+v\", *resp)\n\t\t\t}\n\t\t\ttime.Sleep(time.Minute)\n\t\t\tcontinue\n\t\t}\n\t\tmetadataTriggerCh <- true\n\t\tsklog.Infof(\"Pull triggered via metadata.\")\n\t}\n}", "func (node *VincTriggerNode) WaitForEvent(nodeEventStream chan model.ReactorEvent) {\n\tnode.SetReactorRunning(true)\n\ttimeout := time.Second * time.Duration(node.config.Timeout)\n\tvar timer *time.Timer\n\tif timeout == 0 {\n\t\ttimer = time.NewTimer(time.Hour * 24)\n\t\ttimer.Stop()\n\t}else {\n\t\ttimer = time.NewTimer(timeout)\n\t}\n\tdefer func() {\n\t\tnode.SetReactorRunning(false)\n\t\tnode.GetLog().Debug(\"Msg processed by the node \")\n\t\ttimer.Stop()\n\t}()\n\tfor {\n\t\tif timeout > 0 {\n\t\t\ttimer.Reset(timeout)\n\t\t}\n\t\tselect {\n\t\tcase newMsg := <-node.msgInStream:\n\t\t\tvar eventValue string\n\t\t\tif newMsg.Payload.Type == \"cmd.pd7.request\" {\n\t\t\t\trequest := primefimp.Request{}\n\t\t\t\terr := newMsg.Payload.GetObjectValue(&request)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif request.Component == \"shortcut\" && request.Cmd == \"set\" {\n\t\t\t\t\tnode.GetLog().Info(\"shortcut\")\n\t\t\t\t\tif node.config.EventType == \"shortcut\" {\n\t\t\t\t\t\teventValue = fmt.Sprintf(\"%.0f\",request.Id)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}else if newMsg.Payload.Type == \"evt.pd7.notify\" {\n\t\t\t\tnotify := primefimp.Notify{}\n\t\t\t\terr := newMsg.Payload.GetObjectValue(&notify)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif notify.Component == \"hub\" && notify.Cmd == \"set\" {\n\t\t\t\t\tif node.config.EventType == \"mode\" {\n\t\t\t\t\t\thub := notify.GetModeChange()\n\t\t\t\t\t\tif hub != nil {\n\t\t\t\t\t\t\teventValue = hub.Current\n\t\t\t\t\t\t}else {\n\t\t\t\t\t\t\tnode.GetLog().Info(\"ERROR 2\")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif eventValue != \"\" {\n\t\t\t\tnode.GetLog().Infof(\"Home event = %s\",eventValue)\n\t\t\t\tif !node.config.IsValueFilterEnabled || ((eventValue == node.config.ValueFilter) && node.config.IsValueFilterEnabled) {\n\t\t\t\t\tnode.GetLog().Debug(\"Starting flow\")\n\t\t\t\t\trMsg := model.Message{Payload: fimpgo.FimpMessage{Value: eventValue, ValueType: fimpgo.VTypeString}}\n\t\t\t\t\tnewEvent := model.ReactorEvent{Msg: rMsg, TransitionNodeId: node.Meta().SuccessTransition}\n\t\t\t\t\t// Flow is executed within flow runner goroutine\n\t\t\t\t\tnode.FlowRunner()(newEvent)\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase <-timer.C:\n\t\t\tnode.GetLog().Debug(\"Timeout \")\n\t\t\tnewEvent := model.ReactorEvent{TransitionNodeId: node.Meta().TimeoutTransition}\n\t\t\tnode.GetLog().Debug(\"Starting new flow (timeout)\")\n\t\t\tnode.FlowRunner()(newEvent)\n\t\t\tnode.GetLog().Debug(\"Flow started (timeout) \")\n\t\tcase signal := <-node.FlowOpCtx().TriggerControlSignalChannel:\n\t\t\tnode.GetLog().Debug(\"Control signal \")\n\t\t\tif signal == model.SIGNAL_STOP {\n\t\t\t\tnode.GetLog().Info(\"VincTrigger stopped by SIGNAL_STOP \")\n\t\t\t\treturn\n\t\t\t}else {\n\t\t\t\ttime.Sleep(50*time.Millisecond)\n\t\t\t}\n\t\t}\n\n\t}\n}", "func TestWebHook(t *testing.T) {\n\tg := gomega.NewGomegaWithT(t)\n\tg.Expect(createCertificates(t)).NotTo(gomega.HaveOccurred())\n\n\t// create manager\n\tmgr, err := manager.New(cfg, manager.Options{\n\t\tMetricsBindAddress: \"0\",\n\t})\n\tg.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tc = mgr.GetClient()\n\n\t// add webhook to manager\n\tAdd(mgr)\n\n\t// start manager\n\tstopMgr, mgrStopped := StartTestManager(mgr, g)\n\tdefer func() {\n\t\tclose(stopMgr)\n\t\tmgrStopped.Wait()\n\t}()\n\n\tg.Expect(c.Create(context.TODO(), fnConfig)).NotTo(gomega.HaveOccurred())\n\n\ttestInvalidFunc(t)\n\ttestHandleDefaults(t)\n}", "func WaitForService(org string, waitService string, waitTimeout int, pattern string) {\n\n\tconst UpdateThreshold = 5 // How many service check iterations before updating the user with a msg on the console.\n\tconst ServiceUpThreshold = 5 // How many service check iterations before deciding that the service is up.\n\n\t// get message printer\n\tmsgPrinter := i18n.GetMessagePrinter()\n\n\t// Verify that the input makes sense.\n\tif waitTimeout < 0 {\n\t\tcliutils.Fatal(cliutils.CLI_INPUT_ERROR, msgPrinter.Sprintf(\"--timeout must be a positive integer.\"))\n\t}\n\n\t// 1. Wait for the /service API to return a service with url that matches the input\n\t// 2. While waiting, report when at least 1 agreement is formed\n\n\tmsgPrinter.Printf(\"Waiting for up to %v seconds for service %v/%v to start...\", waitTimeout, org, waitService)\n\tmsgPrinter.Println()\n\n\t// Save the most recent set of services here.\n\tservices := api.AllServices{}\n\n\t// Start monitoring the agent's /service API, looking for the presence of the input waitService.\n\tupdateCounter := UpdateThreshold\n\tserviceUp := 0\n\tserviceFailed := false\n\tnow := uint64(time.Now().Unix())\n\tfor (uint64(time.Now().Unix())-now < uint64(waitTimeout) || serviceUp > 0) && !serviceFailed {\n\t\ttime.Sleep(time.Duration(3) * time.Second)\n\t\tif _, err := cliutils.HorizonGet(\"service\", []int{200}, &services, true); err != nil {\n\t\t\tcliutils.Fatal(cliutils.CLI_GENERAL_ERROR, err.Error())\n\t\t}\n\n\t\t// Active services are services that have at least been started. When the execution time becomes non-zero\n\t\t// it means the service container is started. The container could still fail quickly after it is started.\n\t\tinstances := services.Instances[\"active\"]\n\t\tfor _, serviceInstance := range instances {\n\n\t\t\tif !(serviceInstance.SpecRef == waitService && serviceInstance.Org == org) {\n\t\t\t\t// Skip elements for other services\n\t\t\t\tcontinue\n\n\t\t\t} else if serviceInstance.ExecutionStartTime != 0 {\n\t\t\t\t// The target service is started. If stays up then declare victory and return.\n\t\t\t\tif serviceUp >= ServiceUpThreshold {\n\t\t\t\t\tmsgPrinter.Printf(\"Service %v/%v is started.\", org, waitService)\n\t\t\t\t\tmsgPrinter.Println()\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// The service could fail quickly if we happened to catch it just as it was starting, so make sure\n\t\t\t\t// the service stays up.\n\t\t\t\tserviceUp += 1\n\n\t\t\t} else if serviceUp > 0 {\n\t\t\t\t// The service has been up for at least 1 iteration, so it's absence means that it failed.\n\t\t\t\tserviceUp = 0\n\t\t\t\tmsgPrinter.Printf(\"The service %v/%v has failed.\", org, waitService)\n\t\t\t\tmsgPrinter.Println()\n\t\t\t\tserviceFailed = true\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\n\t\t// Service is not there yet. Update the user on progress, and wait for a bit.\n\t\tupdateCounter = updateCounter - 1\n\t\tif updateCounter <= 0 && !serviceFailed {\n\t\t\tupdateCounter = UpdateThreshold\n\t\t\tmsgPrinter.Printf(\"Waiting for service %v/%v to start executing.\", org, waitService)\n\t\t\tmsgPrinter.Println()\n\t\t}\n\t}\n\n\t// If we got to this point, then there is a problem.\n\tmsgPrinter.Printf(\"Timeout waiting for service %v/%v to successfully start. Analyzing possible reasons for the timeout...\", org, waitService)\n\tmsgPrinter.Println()\n\n\t// Let's see if we can provide the user with some help figuring out what's going on.\n\tfound := false\n\tfor _, serviceInstance := range services.Instances[\"active\"] {\n\n\t\t// 1. Maybe the service is there but just hasnt started yet.\n\t\tif serviceInstance.SpecRef == waitService && serviceInstance.Org == org {\n\t\t\tmsgPrinter.Printf(\"Service %v/%v is deployed to the node, but not executing yet.\", org, waitService)\n\t\t\tmsgPrinter.Println()\n\t\t\tfound = true\n\n\t\t\t// 2. Maybe the service has encountered an error.\n\t\t\tif serviceInstance.ExecutionStartTime == 0 && serviceInstance.ExecutionFailureCode != 0 {\n\t\t\t\tmsgPrinter.Printf(\"Service %v/%v execution failed: %v.\", org, waitService, serviceInstance.ExecutionFailureDesc)\n\t\t\t\tmsgPrinter.Println()\n\t\t\t\tserviceFailed = true\n\t\t\t} else {\n\t\t\t\tmsgPrinter.Printf(\"Service %v/%v might need more time to start executing, continuing analysis.\", org, waitService)\n\t\t\t\tmsgPrinter.Println()\n\t\t\t}\n\t\t\tbreak\n\n\t\t}\n\t}\n\n\t// 3. The service might not even be there at all.\n\tif !found {\n\t\tmsgPrinter.Printf(\"Service %v/%v is not deployed to the node, continuing analysis.\", org, waitService)\n\t\tmsgPrinter.Println()\n\t}\n\n\t// 4. Are there any agreements being made? Check for only non-archived agreements. Skip this if we know the service failed\n\t// because we know there are agreements.\n\tif !serviceFailed {\n\t\tmsgPrinter.Println()\n\t\tags := agreement.GetAgreements(false)\n\t\tif len(ags) != 0 {\n\t\t\tmsgPrinter.Printf(\"Currently, there are %v active agreements on this node. Use `hzn agreement list' to see the agreements that have been formed so far.\", len(ags))\n\t\t\tmsgPrinter.Println()\n\t\t} else {\n\t\t\tmsgPrinter.Printf(\"Currently, there are no active agreements on this node.\")\n\t\t\tmsgPrinter.Println()\n\t\t}\n\t}\n\n\t// 5. Scan the event log for errors related to this service. This should always be done if the service did not come up\n\t// successfully.\n\teLogs := make([]persistence.EventLogRaw, 0)\n\tcliutils.HorizonGet(\"eventlog?severity=error\", []int{200}, &eLogs, true)\n\tmsgPrinter.Println()\n\tif len(eLogs) == 0 {\n\t\tmsgPrinter.Printf(\"Currently, there are no errors recorded in the node's event log.\")\n\t\tmsgPrinter.Println()\n\t\tif pattern == \"\" {\n\t\t\tmsgPrinter.Printf(\"Use the 'hzn deploycheck all -b' or 'hzn deploycheck all -B' command to verify that node, service configuration and deployment policy is compatible.\")\n\t\t} else {\n\t\t\tmsgPrinter.Printf(\"Use the 'hzn deploycheck all -p' command to verify that node, service configuration and pattern is compatible.\")\n\t\t}\n\t\tmsgPrinter.Println()\n\t} else {\n\t\tmsgPrinter.Printf(\"The following errors were found in the node's event log and are related to %v/%v. Use 'hzn eventlog list -s severity=error -l' to see the full detail of the errors.\", org, waitService)\n\t\tmsgPrinter.Println()\n\n\t\t// Scan the log for events related to the service we're waiting for.\n\t\tsel := persistence.Selector{\n\t\t\tOp: \"=\",\n\t\t\tMatchValue: waitService,\n\t\t}\n\t\tmatch := make(map[string][]persistence.Selector)\n\t\tmatch[\"service_url\"] = []persistence.Selector{sel}\n\n\t\tfor _, el := range eLogs {\n\t\t\tt := time.Unix(int64(el.Timestamp), 0)\n\t\t\tprintLog := false\n\t\t\tif strings.Contains(el.Message, waitService) {\n\t\t\t\tprintLog = true\n\t\t\t} else if es, err := persistence.GetRealEventSource(el.SourceType, el.Source); err != nil {\n\t\t\t\tcliutils.Fatal(cliutils.CLI_GENERAL_ERROR, \"unable to convert eventlog source, error: %v\", err)\n\t\t\t} else if (*es).Matches(match) {\n\t\t\t\tprintLog = true\n\t\t\t}\n\n\t\t\t// Put relevant events on the console.\n\t\t\tif printLog {\n\t\t\t\tmsgPrinter.Printf(\"%v: %v\", t.Format(\"2006-01-02 15:04:05\"), el.Message)\n\t\t\t\tmsgPrinter.Println()\n\t\t\t}\n\t\t}\n\t}\n\n\t// Done analyzing\n\tmsgPrinter.Printf(\"Analysis complete.\")\n\tmsgPrinter.Println()\n\n\treturn\n}", "func (c *ClientManager) WaitInstanceUntilReady(id int, until time.Time) error {\n\tfor {\n\t\tvirtualGuest, found, err := c.GetInstance(id, \"id, lastOperatingSystemReload[id,modifyDate], activeTransaction[id,transactionStatus.name], provisionDate, powerState.keyName\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !found {\n\t\t\treturn bosherr.WrapErrorf(err, \"SoftLayer virtual guest '%d' does not exist\", id)\n\t\t}\n\n\t\tlastReload := virtualGuest.LastOperatingSystemReload\n\t\tactiveTxn := virtualGuest.ActiveTransaction\n\t\tprovisionDate := virtualGuest.ProvisionDate\n\n\t\t// if lastReload != nil && lastReload.ModifyDate != nil {\n\t\t// \tfmt.Println(\"lastReload: \", (*lastReload.ModifyDate).Format(time.RFC3339))\n\t\t// }\n\t\t// if activeTxn != nil && activeTxn.TransactionStatus != nil && activeTxn.TransactionStatus.Name != nil {\n\t\t// \tfmt.Println(\"activeTxn: \", *activeTxn.TransactionStatus.Name)\n\t\t// }\n\t\t// if provisionDate != nil {\n\t\t// \tfmt.Println(\"provisionDate: \", (*provisionDate).Format(time.RFC3339))\n\t\t// }\n\n\t\treloading := activeTxn != nil && lastReload != nil && *activeTxn.Id == *lastReload.Id\n\t\tif provisionDate != nil && !reloading {\n\t\t\t// fmt.Println(\"power state:\", *virtualGuest.PowerState.KeyName)\n\t\t\tif *virtualGuest.PowerState.KeyName == \"RUNNING\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tnow := time.Now()\n\t\tif now.After(until) {\n\t\t\treturn bosherr.Errorf(\"Power on virtual guest with id %d Time Out!\", *virtualGuest.Id)\n\t\t}\n\n\t\tmin := math.Min(float64(10.0), float64(until.Sub(now)))\n\t\ttime.Sleep(time.Duration(min) * time.Second)\n\t}\n}", "func (tt *Tester) Catchup() {\n\ttt.waitStartup()\n\ttt.waitForClients()\n}", "func (wh *Webhooks) Run(ctx context.Context) {\n\twh.workersNum.Inc()\n\tdefer wh.workersNum.Dec()\n\tfor {\n\t\tenqueuedItem, err := wh.queue.Pop(ctx)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\twh.queuedNum.Dec()\n\t\ttmpFile, err := wh.openStoredRequestFile(enqueuedItem)\n\t\tif err != nil {\n\t\t\tlog.Println(\"failed to process\", enqueuedItem.RequestFile, \"-\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\twh.processRequestAsync(ctx, enqueuedItem.Manifest, tmpFile)\n\t\t_ = tmpFile.Close()\n\t\t_ = os.RemoveAll(tmpFile.Name())\n\t}\n}", "func (trello *Trello) EnsureHook(callbackURL string) {\n /* Check if we have a hook already */\n var data []webhookInfo\n GenGET(trello, \"/token/\" + trello.Token + \"/webhooks/\", &data)\n found := false\n\n for _, v := range data {\n /* Check if we have a hook for our own URL at same model */\n if v.Model == trello.BoardId {\n if v.URL == callbackURL {\n log.Print(\"Hook found, nothing to do here.\")\n found = true\n break\n }\n }\n }\n\n /* If not, install one */\n if !found {\n /* TODO: save hook reference and uninstall maybe? */\n GenPOSTForm(trello, \"/webhooks/\", nil, url.Values{\n \"name\": { \"trellohub for \" + trello.BoardId },\n \"idModel\": { trello.BoardId },\n \"callbackURL\": { callbackURL } })\n\n log.Print(\"Webhook installed.\")\n } else {\n log.Print(\"Reusing existing webhook.\")\n }\n}", "func (n *Netlify) WaitUntilDeployLive(ctx context.Context, d *models.Deploy) (*models.Deploy, error) {\n\treturn n.waitForState(ctx, d, \"ready\")\n}", "func WaitReady(s *state.State) error {\n\tif !s.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\ts.Logger.Infoln(\"Waiting for machine-controller to come up...\")\n\n\tif err := cleanupStaleResources(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForWebhook(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForMachineController(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\treturn waitForCRDs(s)\n}", "func (p *Pebble) WaitReady(t *testing.T) {\n\tif p.pebbleCMD.Process == nil {\n\t\tt.Fatal(\"Pebble not started\")\n\t}\n\turl := p.DirectoryURL()\n\tRetry(t, 10, 10*time.Millisecond, func() error {\n\t\tctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)\n\t\tdefer cancel()\n\n\t\tt.Log(\"Checking pebble readiness\")\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp, err := p.httpClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp.Body.Close()\n\t\treturn nil\n\t})\n}", "func (t *ElapsedTimeout) Wait(context.Context) error { return nil }", "func waitForStatus(t *testing.T, path string, statusCode int) <-chan error {\n\t// give our process 2 seconds to respond with the correct status\n\t// this should be ample.\n\tctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\n\tsig := make(chan error, 1)\n\tgo func() {\n\t\tvar res *http.Response\n\t\tdefer cancel() // ensure we cancel the context to stop memory leaks\n\t\tdefer func() { close(sig) }() // ensure the channel is closed too.\n\n\t\t// while we have no response or the status code doesnt match\n\t\tfor res == nil || res.StatusCode != statusCode {\n\t\t\t// continue to perform HTTP requests against our local server\n\t\t\t// until we either receive a HTTP OK or a context timeout.\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tsig <- ctx.Err()\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\treq := newRequest(t, path)\n\t\t\t\tres, _ = http.DefaultClient.Do(req.WithContext(ctx))\n\t\t\t}\n\t\t}\n\n\t\tsig <- nil\n\t}()\n\n\treturn sig\n}", "func (b *Botanist) WaitForControllersToBeActive(ctx context.Context) error {\n\ttype controllerInfo struct {\n\t\tname string\n\t\tlabels map[string]string\n\t}\n\n\ttype checkOutput struct {\n\t\tcontrollerName string\n\t\tready bool\n\t\terr error\n\t}\n\n\tvar (\n\t\tcontrollers = []controllerInfo{}\n\t\tpollInterval = 5 * time.Second\n\t)\n\n\t// Check whether the kube-controller-manager deployment exists\n\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(b.Shoot.SeedNamespace, v1beta1constants.DeploymentNameKubeControllerManager), &appsv1.Deployment{}); err == nil {\n\t\tcontrollers = append(controllers, controllerInfo{\n\t\t\tname: v1beta1constants.DeploymentNameKubeControllerManager,\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"app\": \"kubernetes\",\n\t\t\t\t\"role\": \"controller-manager\",\n\t\t\t},\n\t\t})\n\t} else if client.IgnoreNotFound(err) != nil {\n\t\treturn err\n\t}\n\n\treturn retry.UntilTimeout(context.TODO(), pollInterval, 90*time.Second, func(ctx context.Context) (done bool, err error) {\n\t\tvar (\n\t\t\twg sync.WaitGroup\n\t\t\tout = make(chan *checkOutput)\n\t\t)\n\n\t\tfor _, controller := range controllers {\n\t\t\twg.Add(1)\n\n\t\t\tgo func(controller controllerInfo) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tpodList := &corev1.PodList{}\n\t\t\t\terr := b.K8sSeedClient.Client().List(ctx, podList,\n\t\t\t\t\tclient.InNamespace(b.Shoot.SeedNamespace),\n\t\t\t\t\tclient.MatchingLabels(controller.labels))\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check that only one replica of the controller exists.\n\t\t\t\tif len(podList.Items) != 1 {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for %s to have exactly one replica\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Check that the existing replica is not in getting deleted.\n\t\t\t\tif podList.Items[0].DeletionTimestamp != nil {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for a new replica of %s\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check if the controller is active by reading its leader election record.\n\t\t\t\tleaderElectionRecord, err := common.ReadLeaderElectionRecord(b.K8sShootClient, resourcelock.EndpointsResourceLock, metav1.NamespaceSystem, controller.name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif delta := metav1.Now().UTC().Sub(leaderElectionRecord.RenewTime.Time.UTC()); delta <= pollInterval-time.Second {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, ready: true}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tb.Logger.Infof(\"Waiting for %s to be active\", controller.name)\n\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t}(controller)\n\t\t}\n\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tclose(out)\n\t\t}()\n\n\t\tfor result := range out {\n\t\t\tif result.err != nil {\n\t\t\t\treturn retry.SevereError(fmt.Errorf(\"could not check whether controller %s is active: %+v\", result.controllerName, result.err))\n\t\t\t}\n\t\t\tif !result.ready {\n\t\t\t\treturn retry.MinorError(fmt.Errorf(\"controller %s is not active\", result.controllerName))\n\t\t\t}\n\t\t}\n\n\t\treturn retry.Ok()\n\t})\n}", "func waitFotPayloadDeath(c *client.Client, payloadAnchor string) (recov interface{}) {\n\t// defer func() { // catch panics caused by unexpected death of the server hosting the payload\n\t// \trecov = recover()\n\t// }()\n\tt := c.Walk(client.Split(payloadAnchor)) // Access the process anchor of the currently-running payload of the virus.\n\tt.Get().(client.Proc).Wait() // Wait until the payload process exits.\n\tt.Scrub() // scrub payload anchor from old process element\n\ttime.Sleep(2*time.Second) // Wait a touch to slow down the spin\n\treturn\n}", "func (webhook *Webhook) Run(ctx context.Context, listen string) error {\n\tif !webhook.isSetup {\n\t\tif err := webhook.Setup(ctx); err != nil {\n\t\t\treturn fmt.Errorf(\"setup webhook: %v\", err)\n\t\t}\n\t}\n\n\tserver := &http.Server{\n\t\tAddr: listen,\n\t\tHandler: webhook,\n\t}\n\n\tgo func() {\n\t\t<-ctx.Done()\n\n\t\twebhook.log(\"shutdown server...\")\n\n\t\tcloseCtx, close := context.WithTimeout(context.Background(), 10*time.Second)\n\t\tdefer close()\n\n\t\tif err := server.Shutdown(closeCtx); err != nil {\n\t\t\twebhook.log(\"server shutdown error: %v\", err)\n\t\t}\n\t}()\n\n\twebhook.log(\"starting webhook server on %s\", listen)\n\n\tif err := server.ListenAndServe(); err != http.ErrServerClosed {\n\t\treturn fmt.Errorf(\"server error: %v\", err)\n\t}\n\n\treturn nil\n}", "func (c *wsClient) WaitForShutdown() {\n\tc.wg.Wait()\n}", "func (e *EvtFailureDetector) Start() {\n\te.timeoutSignal = time.NewTicker(e.delay)\n\tgo func() {\n\t\tfor {\n\t\t\te.testingHook() // DO NOT REMOVE THIS LINE. A no-op when not testing.\n\t\t\tselect {\n\t\t\tcase incHB := <-e.hbIn: //heartbeath comming in\n\t\t\t\t// TODO(student): Handle incoming heartbeat\n\t\t\t\tif incHB.Request && incHB.To == e.id {\n\t\t\t\t\t//If heartbeat is actual meant for us and it is a request, send reply back to sender\n\t\t\t\t\thbReply := Heartbeat{To: incHB.From, From: e.id, Request: false}\n\t\t\t\t\t//fmt.Printf(\"\\nfd.go recived incoming HB and creates reply: {To: %d From: %d Request: %v}\\n\", incHB.From, e.id, false)\n\t\t\t\t\te.ReplyHeartbeat(hbReply)\n\t\t\t\t} else if incHB.Request == false && incHB.To == e.id {\n\t\t\t\t\t//incHB is a reply (incHB.Request == false)\n\t\t\t\t\t//incHB is addressed to us (incHB.To == e.id)\n\t\t\t\t\t//Set incHB.From to alive\n\t\t\t\t\te.alive[incHB.From] = true\n\t\t\t\t}\n\t\t\tcase <-e.timeoutSignal.C:\n\t\t\t\te.timeout()\n\t\t\tcase <-e.stop:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func (w Waiter) Wait() error {\n\tw.logger.Debug(waiterLogTag, \"Waiting for instance to reach running state\")\n\tw.logger.Debug(waiterLogTag, \"Using schedule %v\", w.watchSchedule)\n\n\tfor _, timeGap := range w.watchSchedule {\n\t\tw.logger.Debug(waiterLogTag, \"Sleeping for %v\", timeGap)\n\t\tw.sleepFunc(timeGap)\n\n\t\tstate, err := w.agentClient.GetState()\n\t\tif err != nil {\n\t\t\treturn bosherr.WrapError(err, \"Sending get_state\")\n\t\t}\n\n\t\t// todo stopped state\n\t\tif state.JobState == \"running\" {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn ErrNotRunning\n}", "func (TelegramBotApp *TelegramBotApp) setupWebhook() (tgbotapi.UpdatesChannel, error) {\n\t_, err := TelegramBotApp.bot.SetWebhook(tgbotapi.NewWebhook(TelegramBotApp.conf.WebhookURL + \"/\" + TelegramBotApp.bot.Token))\n\tif err != nil {\n\t\tlog.Fatal(\"[!] Webhook problem: \", err)\n\t\t//return nil, err\n\t}\n\tupdates := TelegramBotApp.bot.ListenForWebhook(\"/\" + TelegramBotApp.bot.Token)\n\tgo http.ListenAndServe(\":\"+TelegramBotApp.conf.Port, nil)\n\n\tfmt.Println(\"[+] Webhook method selected\")\n\n\treturn updates, nil\n\n}", "func waitUntilPodStatus(provider *vkAWS.FargateProvider, podName string, desiredStatus v1.PodPhase) error {\n\tctx := context.Background()\n\tcontext.WithTimeout(ctx, time.Duration(time.Second*60))\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t\tstatus, err := provider.GetPodStatus(\"default\", podName)\n\t\t\tif err != nil {\n\t\t\t\tif strings.Contains(err.Error(), \"is not found\") {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif status.Phase == desiredStatus {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t}\n\t}\n}", "func (c *Compute) wait(operation *compute.Operation) error {\n\tfor {\n\t\top, err := c.ZoneOperations.Get(c.Project, c.Zone, operation.Name).Do()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get operation: %v\", operation.Name, err)\n\t\t}\n\t\tlog.Printf(\"operation %q status: %s\", operation.Name, op.Status)\n\t\tif op.Status == \"DONE\" {\n\t\t\tif op.Error != nil {\n\t\t\t\treturn fmt.Errorf(\"operation error: %v\", *op.Error.Errors[0])\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\treturn nil\n}", "func (rest *Restful) WaitShutdown() {\n\n\tif rest == nil {\n\t\treturn\n\t}\n\n\tirqSig := make(chan os.Signal, 1)\n\tsignal.Notify(irqSig, syscall.SIGINT, syscall.SIGTERM)\n\n\tselect {\n\t// interrupt handler sig term to shutdown\n\tcase sig := <-irqSig:\n\t\tglog.Infof(\"Shutdown request from a signal %v\", sig)\n\t// shutdown request\n\tcase sig := <-rest.shutdownRequest:\n\t\tglog.Infof(\"Shutdown request (/shutdownGrpc %v)\", sig)\n\t}\n\n\tatomic.StoreInt32(&rest.healthy, 0)\n\tglog.Infof(\"sending shutdown command to rest server ...\")\n\n\t//Create shutdownGrpc context with 10 second timeout\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\terr := rest.restServer.Shutdown(ctx)\n\tif err != nil {\n\t\tglog.Infof(\"Shutdown request error: %v\", err)\n\t}\n}", "func (c *Crawler) WaitForCompletion() {\n\tc.wg.Wait()\n}", "func (d *Scheduler) Run() {\n\tgo d.webhookSched.Run()\n\tlog.Println(\"Starting scheduler...\")\n\tif err := d.updateChecks(); err != nil {\n\t\tpanic(err)\n\t}\n\tnow := time.Now().UTC()\n\td.running = true\n\tvar checkTime time.Time\n\tfor {\n\t\tsort.Sort(byTime(d.checks))\n\t\tif d.checks == nil {\n\t\t\td.updateChecks()\n\t\t}\n\t\tif d.checks != nil && len(d.checks) == 0 {\n\t\t\t// Sleep for 5 years until the config change\n\t\t\tcheckTime = now.AddDate(5, 0, 0)\n\t\t} else {\n\t\t\tcheckTime = d.checks[0].Next\n\t\t}\n\t\tselect {\n\t\tcase now = <-time.After(checkTime.Sub(now)):\n\t\t\tfor _, check := range d.checks {\n\t\t\t\tif now.Sub(check.Next) < 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif !check.Next.IsZero() {\n\t\t\t\t\tcheck.Prev = check.Next\n\t\t\t\t}\n\t\t\t\tgo func(check *Check) {\n\t\t\t\t\toldStatus := check.Up\n\t\t\t\t\tLeaderCheck(d.raft, check)\n\t\t\t\t\tif !check.Next.IsZero() {\n\t\t\t\t\t\tcheck.LastCheck = check.Next.Unix()\n\t\t\t\t\t}\n\t\t\t\t\t// Re-compute the uptime percentage\n\t\t\t\t\tif check.TimeDown > 0 {\n\t\t\t\t\t\ttotal := check.Interval * check.Pings\n\t\t\t\t\t\tcheck.Uptime = float32(int64(total)-check.TimeDown) / float32(total)\n\t\t\t\t\t\tlog.Printf(\"uptime:%+v\", check)\n\t\t\t\t\t}\n\t\t\t\t\tif check.Up != oldStatus {\n\t\t\t\t\t\tlog.Printf(\"Check %v status changed from %v to %v\", check.ID, oldStatus, check.Up)\n\t\t\t\t\t\tvar wg sync.WaitGroup\n\t\t\t\t\t\twg.Add(3)\n\t\t\t\t\t\tgo func(check *Check) {\n\t\t\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\t\t\tif d.raft.Producer == nil {\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tjs, err := json.Marshal(check)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif err := d.raft.Producer.Publish(\"neverdown\", js); err != nil {\n\t\t\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}(check)\n\t\t\t\t\t\tgo func(check *Check) {\n\t\t\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\t\t\tif err := NotifyEmails(check); err != nil {\n\t\t\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}(check)\n\t\t\t\t\t\tgo func(check *Check) {\n\t\t\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\t\t\tif err := ExecuteWebhooks(d.raft, d.webhookSched, check); err != nil {\n\t\t\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}(check)\n\t\t\t\t\t\twg.Wait()\n\t\t\t\t\t}\n\t\t\t\t\tif err := d.raft.ExecCommand(check.ToPostCmd()); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}(check)\n\t\t\t\tcheck.ComputeNext(now)\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase <-d.stop:\n\t\t\td.running = false\n\t\t\treturn\n\t\tcase <-d.Reloadch:\n\t\t\td.updateChecks()\n\t\t}\n\t}\n}" ]
[ "0.5618916", "0.5599623", "0.5432932", "0.54272896", "0.5426101", "0.54169494", "0.5409126", "0.54035944", "0.5363949", "0.527401", "0.5210134", "0.52003247", "0.51873827", "0.5170767", "0.5069141", "0.50672245", "0.50620365", "0.50183946", "0.49992928", "0.49969497", "0.49778023", "0.496999", "0.4888483", "0.48504257", "0.4845085", "0.4839114", "0.4830706", "0.48160857", "0.48133752", "0.48124412", "0.4803358", "0.48008236", "0.4799799", "0.4770499", "0.47629687", "0.47618487", "0.47602043", "0.47599518", "0.47580105", "0.47533765", "0.47503945", "0.474931", "0.47342688", "0.47329265", "0.47329265", "0.47018346", "0.4700666", "0.4695227", "0.46941465", "0.4693167", "0.46920648", "0.46895605", "0.4688183", "0.4683382", "0.4680622", "0.46727717", "0.46714687", "0.46685308", "0.46675727", "0.4660781", "0.46507967", "0.46500924", "0.4642966", "0.4640279", "0.4638939", "0.46316776", "0.46306103", "0.4627456", "0.46256787", "0.46194065", "0.46188343", "0.4617556", "0.46170422", "0.4616899", "0.46167544", "0.46130544", "0.46106446", "0.4609445", "0.46085274", "0.4605413", "0.46041542", "0.46031883", "0.4595507", "0.45875573", "0.45807275", "0.457972", "0.45779213", "0.45693925", "0.45687068", "0.45577043", "0.4557321", "0.45562536", "0.45543084", "0.45522678", "0.4550274", "0.4527794", "0.45273313", "0.4522969", "0.4517023", "0.45130283" ]
0.78812975
0
Create creates a new user. The receiver is modified to the ID of the new user.
func (id *User) Create(tx *sql.Tx) error { sql := `INSERT INTO "user" DEFAULT VALUES RETURNING id` return tx.QueryRow(sql).Scan(id) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 (handler *UserHandler) Create(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tpayload := &User{}\n\n\tif err := json.NewDecoder(req.Body).Decode(payload); err != nil {\n\t\thandler.Formatter.JSON(w, http.StatusBadRequest, util.NewError(\"1001\",\n\t\t\t\"Invalid JSON payload supplied.\", err.Error()))\n\t\treturn\n\t}\n\n\tif err := payload.Validate(); err != nil {\n\t\thandler.Formatter.JSON(w, http.StatusBadRequest, util.NewError(\"1002\",\n\t\t\t\"Unable to validate the payload provided.\", err.Error()))\n\t\treturn\n\t}\n\n\tuser, err := handler.UserService.CreateUser(payload)\n\n\tif err != nil {\n\t\thandler.Formatter.JSON(w, http.StatusBadRequest, util.NewError(\"1003\",\n\t\t\t\"Unable to create a new user.\", err.Error()))\n\t\treturn\n\t}\n\n\thandler.Formatter.JSON(w, http.StatusCreated, user.hidePassword())\n}", "func (h *User) Create(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close()\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tR.JSON500(w)\n\t\treturn\n\t}\n\n\tuser, err := validator.UserCreate(body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tR.JSON400(w)\n\t\treturn\n\t}\n\n\terr = h.Storage.CreateUser(user)\n\t// @todo this might be also 400 response since email can be a duplicate\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tR.JSON500(w)\n\t\treturn\n\t}\n\n\tR.JSON200OK(w)\n}", "func Create(u *User) (*User, error) {\n\tif u == nil {\n\t\treturn nil, errors.New(\"user is nil\")\n\t}\n\tu.ID = 0\n\tres, err := client.Post(\"/\", u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnewUser := new(User)\n\tif err := res.ReadJSON(newUser); err != nil {\n\t\treturn nil, err\n\t}\n\treturn newUser, nil\n}", "func (c *UsersClient) Create(ctx context.Context, user models.User) (*models.User, int, error) {\n\tvar status int\n\tbody, err := json.Marshal(user)\n\tif err != nil {\n\t\treturn nil, status, err\n\t}\n\tresp, status, _, err := c.BaseClient.Post(ctx, base.PostHttpRequestInput{\n\t\tBody: body,\n\t\tValidStatusCodes: []int{http.StatusCreated},\n\t\tUri: base.Uri{\n\t\t\tEntity: \"/users\",\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 newUser models.User\n\tif err := json.Unmarshal(respBody, &newUser); err != nil {\n\t\treturn nil, status, err\n\t}\n\treturn &newUser, status, nil\n}", "func (s UserResource) Create(obj interface{}, r api2go.Request) (api2go.Responder, error) {\n\tuser, ok := obj.(model.User)\n\tif !ok {\n\t\treturn &Response{}, api2go.NewHTTPError(errors.New(\"Invalid instance given\"), \"Invalid instance given\", http.StatusBadRequest)\n\t}\n\n\tid, err := s.UserStorage.Insert(user)\n\tif err != nil {\n\t\treturn &Response{}, api2go.NewHTTPError(errors.New(\"Faild to create a user\"), \"Faild to create a user\", http.StatusInternalServerError)\n\t}\n\terr = user.SetID(id)\n\tif err != nil {\n\t\treturn &Response{}, api2go.NewHTTPError(errors.New(\"Non-integer ID given\"), \"Non-integer ID given\", http.StatusInternalServerError)\n\t}\n\n\treturn &Response{Res: user, Code: http.StatusCreated}, nil\n}", "func (u *User) Create(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\tctx, span := trace.StartSpan(ctx, \"handlers.User.Create\")\n\tdefer span.End()\n\n\tv, ok := ctx.Value(web.KeyValues).(*web.Values)\n\tif !ok {\n\t\treturn web.NewShutdownError(\"web value missing from context\")\n\t}\n\n\tvar nu user.NewUser\n\tif err := web.Decode(r, &nu); err != nil {\n\t\treturn errors.Wrap(err, \"\")\n\t}\n\n\tusr, err := user.Create(ctx, u.db, nu, v.Now)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"User: %+v\", &usr)\n\t}\n\n\treturn web.Respond(ctx, w, usr, http.StatusCreated)\n}", "func (s *userService) Create(ctx context.Context, user *pb.User) (rsp *pb.Response, err error) {\n\tt := time.Now().UnixNano() / 1e6\n\tprettyID, err := uuid.NewUUID()\n\tif err != nil {\n\t\treturn\n\t}\n\tuser.PrettyId = prettyID.String()\n\tuser.CreateTime = t\n\tuser.UpdateTime = t\n\tif err = s.dao.CreateUser(ctx, user); err != nil {\n\t\treturn\n\t}\n\tuser.Password = \"\"\n\trsp = &pb.Response{\n\t\tUser: user,\n\t}\n\treturn\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 (u *userServer) Create(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserResponse, error) {\n\tc, err := u.connect(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer c.Close()\n\n\tresult, err := c.ExecContext(ctx, \"INSERT INTO User(`FirstName`, `LastName`, `Address`) VALUES (?, ?, ?)\", req.User.FirstName, req.User.LastName, req.User.Address)\n\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Unknown, \"failed to insert into User table\"+err.Error())\n\t}\n\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Unknown, \"failed to retrieve last inserted record for User\"+err.Error())\n\t}\n\n\treturn &pb.CreateUserResponse{\n\t\tId: id,\n\t}, nil\n}", "func (u *usecase) Create(ctx context.Context, user *User) error {\n\tvalidate = validator.New()\n\tif err := validate.Struct(user); err != nil {\n\t\tvalidationErrors := err.(validator.ValidationErrors)\n\t\treturn validationErrors\n\t}\n\n\tuser.ID = u.newID()\n\tif err := u.repository.Create(ctx, user); err != nil {\n\t\treturn errors.Wrap(err, \"error creating new user\")\n\t}\n\n\treturn nil\n}", "func (u *UserHandler) Create(c *fiber.Ctx) error {\n\tuser := models.User{}\n\terr := c.BodyParser(&user)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = u.Repo.Create(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.Status(fiber.StatusOK).JSON(user)\n}", "func (manager *usersManager) Create(\n\tctx context.Context,\n\topts *ablbind.TransactOpts,\n) (\n\t[8]byte,\n\terror,\n) {\n\treceipt, err := manager.UsersContract.Create(ctx, opts)\n\tif err != nil {\n\t\treturn [8]byte{}, errors.Wrap(err, \"failed to transact\")\n\t}\n\n\tevt, err := manager.UsersContract.ParseSignedUpFromReceipt(receipt)\n\tif err != nil {\n\t\treturn [8]byte{}, errors.Wrap(err, \"failed to parse a event from the receipt\")\n\t}\n\n\tmanager.log.Info(\"User created.\", logger.Attrs{\"user-id\": fmt.Sprintf(\"%x\", evt[0].UserId)})\n\treturn evt[0].UserId, nil\n}", "func Create(c *gin.Context) {\n\tlog.Info(\"User Create function called.\", lager.Data{\"X-Request-Id\": util.GetReqId(c)})\n\tvar r CreateRequest\n\tif err := c.Bind(&r); err != nil {\n\t\tSendResponse(c, errno.ErrBind, nil)\n\t\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 (u *User) Create(db utils.SqlxGetter) (*events_proto.Event, error) {\n\tif u.Id != 0 {\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"can't create existing user\")\n\t}\n\tif err := utils.HandleDBError(db.Get(u,\n\t\t\"INSERT INTO users (username, email, banned, password_hash) VALUES ($1, $2, $3, $4) RETURNING *\",\n\t\tu.Username, u.Email, u.Banned, u.PasswordHash)); err != nil {\n\t\treturn nil, errors.Wrap(err, \"db.Get failed\")\n\t}\n\treturn events.NewEvent(&u.User, events_proto.Event_CREATED, events_proto.Service_ACCOUNTS, nil), nil\n}", "func (u *User) Create(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\tvar newU NewUser\n\n\tif err := web.Unmarshal(r.Body, &newU); err != nil {\n\t\treturn errors.Wrap(err, \"\")\n\t}\n\n\tid, err := uuid.NewV4()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuserDetails := UserDetails{\n\t\tUserName: newU.UserName,\n\t\tEmail: newU.Email,\n\t\tID: id.String(),\n\t}\n\n\tencodedData, err := json.Marshal(userDetails)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdbConn := u.MasterDB\n\n\t// Save User by ID\n\tfID := func(db *leveldb.DB) error {\n\t\t// TODO: while inserting validate if email already exists by checking with email index\n\t\treturn db.Put([]byte(userDetails.ID), encodedData, nil)\n\t}\n\n\t// Save User by Email\n\tfEmail := func(db *leveldb.DB) error {\n\t\t// TODO: while inserting validate if already exists or not\n\t\treturn db.Put([]byte(userDetails.Email), []byte(userDetails.ID), nil)\n\t}\n\n\tif err := dbConn.Execute(fID); err != nil {\n\t\treturn errors.Wrap(err, \"\")\n\t}\n\n\tif err := dbConn.Execute(fEmail); err != nil {\n\t\t// TODO: if error remove the data from ID as well and throw error\n\t\treturn errors.Wrap(err, \"\")\n\t}\n\n\tstatus := struct {\n\t\tID string `json:\"id\"`\n\t}{\n\t\tID: userDetails.ID,\n\t}\n\tweb.Respond(ctx, log, w, status, http.StatusCreated)\n\treturn nil\n}", "func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"/users POST handled\")\n\n\treq := &CreateRequest{}\n\tif err := util.ScanRequest(r, req); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tuser := &schema.User{\n\t\tName: req.Name,\n\t}\n\n\tif err := h.model.Validate(user); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tres, err := h.model.Create(user)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err := util.JSONWrite(w, res, http.StatusCreated); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n}", "func Create(c *gin.Context) {\n\tvar user models.User\n\tif err := c.ShouldBindJSON(&user); err != nil {\n\t\trestErr := rest_errors.NewBadRequestError(\"invalid json body\")\n\t\tc.JSON(restErr.Status, restErr)\n\t\treturn\n\t}\n\n\tresult, saveErr := services.UsersService.CreateUser(user)\n\tif saveErr != nil {\n\t\tc.JSON(saveErr.Status, saveErr)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusCreated, result.Marshal(c.GetHeader(\"X-Public\") == \"false\"))\n}", "func (user *User) Create() *errors.RestError {\n\t// check if user already exists or email passed has already been registered or not\n\tcurrent := usersDB[user.ID]\n\tif current != nil {\n\t\tif current.Email == user.Email {\n\t\t\treturn errors.BadRequestError(fmt.Sprintf(\"email %s already registered\", user.Email))\n\t\t}\n\t\treturn errors.BadRequestError(fmt.Sprintf(\"user %d already exists\", user.ID))\n\t}\n\tuser.DateCreated = date.GetNowString()\n\tusersDB[user.ID] = user\n\treturn nil\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 (uc UserController) CreateUser(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tu := models.User{}\n\tjson.NewDecoder(req.Body).Decode(&u)\n\n\tu.ID = \"007\"\n\n\tuj, err := json.Marshal(u)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tw.Header().Set(\"Contenty-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated) // STATYS 201\n\tfmt.Fprintf(w, \"%s\\n\", uj)\n}", "func (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 (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 UserCreate(w http.ResponseWriter, r *http.Request) {\n\terr := json.NewDecoder(r.Body).Decode(&user)\n\tif err != nil {\n\t\tm.Message = fmt.Sprintf(\"Error al leer el usuario a registrarse: %s\", err)\n\t\tm.Code = http.StatusBadRequest\n\t\tcommons.DisplayMessage(w, m)\n\t\treturn\n\t}\n\tif user.Password != user.ConfirmPassword {\n\t\tm.Message = \"Las contraseña no coinciden\"\n\t\tm.Code = http.StatusBadRequest\n\t\tcommons.DisplayMessage(w, m)\n\t\treturn\n\t}\n\tuser.Password = password\n\tavatarmd5 := md5.Sum([]byte(user.Password))\n\tavatarstr := fmt.Sprintf(\"%x\", avatarmd5)\n\tuser.Avatar = \"https://gravatar.com/avatar/\" + avatarstr + \"?s=100\"\n\tdatabase := configuration.GetConnection()\n\tdefer database.Close()\n\terr = database.Create(&user).Error\n\tif err != nil {\n\t\tm.Message = fmt.Sprintf(\"Error al crear el registro: %s\", err)\n\t\tm.Code = http.StatusBadRequest\n\t\tcommons.DisplayMessage(w, m)\n\t\treturn\n\t}\n\tm.Message = \"Usuario creado con éxito\"\n\tm.Code = http.StatusCreated\n\tcommons.DisplayMessage(w, m)\n}", "func (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 Create(n NewUser, now time.Time) (*User, error) {\n\n\thash, err := bcrypt.GenerateFromPassword([]byte(n.Password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"generating password hash\")\n\t}\n\n\tu := User{\n\t\tID: uuid.New().String(),\n\t\tName: n.Name,\n\t\tEmail: n.Email,\n\t\tPasswordHash: hash,\n\t\tDateCreated: now.UTC(),\n\t\tDateUpdated: now.UTC(),\n\t}\n\n\treturn &u, nil\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tvar user models.User\n\tbodyRequest, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(bodyRequest, &user); err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tif err := user.Prepare(true); err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tif err := validateUniqueDataUser(user, true); err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tdb, err := database.Connect()\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t}\n\tdefer db.Close()\n\n\trepository := repository.NewRepositoryUser(db)\n\n\tuser.Id, err = repository.Insert(user)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, http.StatusCreated, user)\n\n}", "func (context Context) CreateUser(id, password, name string) (string, error) {\n\n\tif id == \"\" {\n\t\tpanic(\"id argument cannot be empty\")\n\t}\n\tif password == \"\" {\n\t\tpanic(\"password argument cannot be empty\")\n\t}\n\tif nameRegex.MatchString(name) == false {\n\t\treturn \"\", errors.New(\"invalid user name\")\n\t}\n\n\thasher := sha256.New()\n\thasher.Write([]byte(password))\n\tpasswordHash := hex.EncodeToString(hasher.Sum(nil))\n\n\tuser := types.User{\n\t\tID: id,\n\t\tName: name,\n\t\tPasswordHash: passwordHash,\n\t}\n\n\tuserBytes, err := json.Marshal(&user)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tresp, err := context.sendAPIPostRequest(\"users\", bytes.NewReader(userBytes), \"application/json\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn id, nil\n}", "func (u *UserServiceHandler) Create(ctx context.Context, email, name, password, apiEnabled string, acls []string) (*User, error) {\n\n\turi := \"/v1/user/create\"\n\n\tvalues := url.Values{\n\t\t\"email\": {email},\n\t\t\"name\": {name},\n\t\t\"password\": {password},\n\t\t\"acls[]\": acls,\n\t}\n\n\tif apiEnabled != \"\" {\n\t\tvalues.Add(\"api_enabled\", apiEnabled)\n\t}\n\n\treq, err := u.client.NewRequest(ctx, http.MethodPost, uri, values)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := new(User)\n\n\terr = u.client.DoWithContext(ctx, req, user)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser.Name = name\n\tuser.Email = email\n\tuser.APIEnabled = apiEnabled\n\tuser.ACL = acls\n\n\treturn user, nil\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\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 (uc UserController) CreateUser(c rest.Context) rest.ResponseSender {\n\tvar user User\n\n\tc.BindJSONEntity(&user)\n\n\tusers = append(users, user)\n\n\tuc.db.execute(fmt.Sprintf(\"INSERT INTO User (`firstName`, `lastName`) VALUES ('%v', '%v')\", user.FirstName, user.LastName))\n\n\treturn rest.NewCreatedJSONResponse(user)\n}", "func (handler *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {\n\n\tvar newUser entities.User\n\terr := json.NewDecoder(r.Body).Decode(&newUser)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(entities.Error{\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tid, err := handler.usecases.CreateUser(newUser)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(entities.Error{\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tnewUserIDResponse := entities.NewUserIDResponse{\n\t\tID: id,\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(&newUserIDResponse)\n}", "func (u *User) Create() error {\n\tif handler == nil {\n\t\treturn errHandlerNotSet\n\t}\n\tpossible := handler.NewRecord(u)\n\tif possible {\n\t\tif err := handler.Create(u).Error; err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\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 (user *User) Create() map[string]interface{} {\n\n\tfmt.Println(user, \"the user object\")\n\tif resp, ok := user.Validate(); !ok {\n\t\treturn resp\n\t}\n\n\thashedPassword, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)\n\tuser.Password = string(hashedPassword)\n\n\tGetDB().Create(user)\n\n\tif user.ID <= 0 {\n\t\treturn utils.Message(false, \"Failed to create user, connection error.\")\n\t}\n\n\t//Create new JWT token for the newly registered user\n\tclaims := GenerateUserClaims(user.ID, user.Email)\n\n\ttoken := jwt.NewWithClaims(jwt.GetSigningMethod(\"HS256\"), claims)\n\ttokenString, _ := token.SignedString([]byte(os.Getenv(\"PASSPHRASE\")))\n\tuser.Token = tokenString\n\n\tuser.Password = \"\" //delete password\n\n\tresponse := utils.Message(true, \"user has been created\")\n\tresponse[\"user\"] = user\n\treturn response\n}", "func (uc UserController) CreateUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\t// Stub an user to be populated from the body\n\tu := models.User{}\n\n\t// Populate the user data\n\tjson.NewDecoder(r.Body).Decode(&u)\n\n\t// Add an Id\n\tu.Id = bson.NewObjectId()\n\n\thPass, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\treturn\n\t}\n\tu.HashPassword = hPass\n\t// clear the incoming text password\n\tu.Password = \"\"\n\n\t// Write the user to mongo\n\terr = uc.session.DB(\"todos\").C(\"users\").Insert(&u)\n\n\t// clear hashed password\n\tu.HashPassword = nil\n\n\t// Marshal provided interface into JSON structure\n\tuj, _ := json.Marshal(u)\n\n\t// Write content-type, statuscode, payload\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(201)\n\tfmt.Fprintf(w, \"%s\", uj)\n}", "func CreateUser(res http.ResponseWriter, req *http.Request) {\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar user models.User\n\tif err := json.NewDecoder(req.Body).Decode(&user); err != nil {\n\t\tmsg := \"Error while reading input body\"\n\n\t\tutils.ReturnErrorResponse(http.StatusBadRequest, msg, \"\", nil, nil, res)\n\t\treturn\n\t}\n\n\t// Helper function to generate encrypted password hash\n\tpasswordHash := helpers.GeneratePasswordHash(user.Password)\n\n\tif passwordHash == \"\" {\n\t\tmsg := \"Error occurred while hashing the password\"\n\n\t\tutils.ReturnErrorResponse(http.StatusBadRequest, msg, \"\", nil, nil, res)\n\t\treturn\n\t}\n\n\tuser.ID = bson.NewObjectId()\n\tuser.Password = passwordHash\n\n\terr := db.CreateUser(user)\n\tif err != nil {\n\t\tmsg := \"Error occurred while creating user\"\n\n\t\tutils.ReturnErrorResponse(http.StatusBadRequest, msg, \"\", nil, nil, res)\n\t\treturn\n\t}\n\n\tmsg := \"User created successfully\"\n\tutils.ReturnSuccessReponse(http.StatusCreated, msg, user.ID, res)\n\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tdecoder := json.NewDecoder(r.Body)\n\tvar update models.User\n\terr := decoder.Decode(&update)\n\tu, err := user.CreateUser(update, r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttpext.SuccessDataAPI(w, \"Ok\", u)\n}", "func (u *Users) Create(w http.ResponseWriter, r *http.Request) {\n\tvar vd views.Data\n\tvar form SignupForm\n\tvd.Yield = &form\n\tif err := parse(r, &form); err != nil {\n\t\tvd.SetAlert(err)\n\t\tu.NewView.Render(w, r, vd)\n\t\treturn\n\t}\n\tuser := models.User{\n\t\tName: form.Name,\n\t\tEmail: form.Email,\n\t\tPassword: form.Password,\n\t}\n\tif err := u.UserService.Create(&user); err != nil {\n\t\tvd.SetAlert(err)\n\t\tu.NewView.Render(w, r, vd)\n\t\treturn\n\t}\n\tu.emailer.Welcome(user.Name, user.Email)\n\terr := u.signIn(w, &user)\n\tif err != nil {\n\t\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n\t\treturn\n\t}\n\thttp.Redirect(w, r, \"/galleries\", http.StatusFound)\n}", "func (r *UsersService) Create(usercreaterequest *UserCreateRequest) *UsersCreateCall {\n\tc := &UsersCreateCall{s: r.s, opt_: make(map[string]interface{})}\n\tc.usercreaterequest = usercreaterequest\n\treturn c\n}", "func UserCreate(request *http.Request) (res *model.Result) {\n\tvar form userRequest\n\tmodel.FormToJson(request.Body, &form)\n\tif uerr := validateRegister(&form); uerr != nil {\n\t\tres = model.GetErrorResult(uerr)\n\t\treturn\n\t}\n\tnew_user := UserModel{\n\t\tName: form.Name,\n\t\tEmail: form.Email,\n\t\tPassword: form.Password,\n\t}\n\tif err := new_user.create(); err != nil {\n\t\tres = model.GetErrorResult(map[string]string{\"all\": err.Error()})\n\t\treturn\n\t}\n\tcommon.SendEmailUserRegistration(form.Email)\n\tres = model.GetOk(common.Mess().Regfin)\n\treturn\n}", "func CreateUser(id int, email string, pass string, bName string,\n\tbAccNum int, bRoutNum int) {\n\tvar count int = 0\n\n\tfor count < len(userList) {\n\t\tif userList[count].uID == id {\n\t\t\tfmt.Println(\"That user id is taken. Please choose a new ID.\")\n\t\t\treturn\n\t\t} else {\n\t\t\tcount++\n\t\t}\n\t}\n\n\tpANew := payAccount{\n\t\tbankName: bName,\n\t\taccountNumber: bAccNum,\n\t\troutingNumber: bRoutNum,\n\t}\n\tuNew := user{\n\t\tuID: id,\n\t\tuEmail: email,\n\t\tuPassword: pass,\n\t\tuBankAccount: pANew,\n\t}\n\tAddUserToDatabase(uNew)\n}", "func (us *UserService) Create(ctx context.Context, u *user.User) error {\n\tctx, cancel := context.WithTimeout(ctx, waitTime*time.Second)\n\tdefer cancel()\n\n\tif !u.ValidateEmail() {\n\t\treturn response.ErrInvalidEmail\n\t}\n\n\tif u.Password != \"\" {\n\t\terr := u.EncryptPassword()\n\t\tif err != nil {\n\t\t\tus.log.Error(err)\n\t\t\treturn response.ErrCouldNotInsert\n\t\t}\n\t}\n\n\tif u.ID.IsZero() {\n\t\tu.ID = primitive.NewObjectID()\n\t}\n\n\tu.Active = true\n\tu.CreatedAt = time.Now()\n\tu.UpdatedAt = time.Now()\n\n\tif err := us.repository.Create(ctx, u); err != nil {\n\t\tus.log.Error(err)\n\t\treturn response.ErrCouldNotInsert\n\t}\n\tu.Password = \"\"\n\treturn nil\n}", "func Create(c *gin.Context) {\n\tlog.Info(\"User Create function called.\", lager.Data{\"X-Request-Id\": util.GetReqID(c)})\n\tvar r CreateRequest\n\tif err := c.Bind(&r); err != nil {\n\t\tSendResponse(c, errno.ErrBind, nil)\n\t}\n\n\tu := model.UserModel{\n\t\t//BaseModel: model.BaseModel{},\n\t\tUsername: r.Username,\n\t\tPassword: r.Password,\n\t}\n\t//fmt.Println()\n\t//log.Info(r.Username)\n\t//log.Info(r.Password)\n\n\tif err := u.Validate(); err != nil {\n\t\tSendResponse(c, errno.ErrValidation, nil)\n\t}\n\n\tif err := u.Encrypt(); err != nil {\n\t\tSendResponse(c, errno.ErrEncrypt, nil)\n\t}\n\n\tif err := u.Create(); err != nil {\n\t\tSendResponse(c, errno.ErrDatabase, nil)\n\t}\n\n\trsp := CreateResponse{\n\t\tUsername: r.Username,\n\t}\n\tSendResponse(c, nil, rsp)\n}", "func (h *userHandler) createUser(ctx context.Context, rw http.ResponseWriter, r *http.Request) {\n\n\tvar user = &model.User{}\n\n\terr := json.NewDecoder(r.Body).Decode(user)\n\tif err != nil {\n\n\t\th.serv.writeResponse(ctx, rw, err.Error(), http.StatusBadRequest, nil)\n\n\t\treturn\n\n\t}\n\n\tif user.Login == \"\" || user.Password == \"\" {\n\n\t\th.serv.writeResponse(ctx, rw, \"Login or password are empty\", http.StatusBadRequest, nil)\n\n\t\treturn\n\t}\n\n\terr = h.registerUser(ctx, user)\n\tif err != nil {\n\n\t\th.serv.writeResponse(ctx, rw, err.Error(), http.StatusBadRequest, nil)\n\n\t\treturn\n\t}\n\n\th.serv.writeResponse(ctx, rw, \"user was created: \"+user.Login, http.StatusCreated, user)\n\n}", "func (h *Handler) createUser(c *gin.Context) handlerResponse {\n\n\tvar newUser types.User\n\tif err := c.ShouldBindJSON(&newUser); err != nil {\n\t\treturn handleBadRequest(err)\n\t}\n\tstoredUser, err := h.service.User.Create(newUser, h.who(c))\n\tif err != nil {\n\t\treturn handleError(err)\n\t}\n\t// Remove password so we do not show in response\n\tstoredUser.Password = \"\"\n\treturn handleCreated(storedUser)\n}", "func (c *UsersController) Create(ctx *app.CreateUsersContext) error {\n\t// UsersController_Create: start_implement\n\n\t// Put your logic here\n\t// initialize new user struct object\n\tuser := &types.User{\n\t\tCognitoAuthUserID: ctx.Payload.CognitoAuthUserID,\n\t\tWallet: &types.Wallet{},\n\t}\n\n\t// insert the AWS cognito user ID into the coindrop_auth table\n\terr := c.db.AddUserID(user.CognitoAuthUserID)\n\tif err != nil {\n\t\tlog.Errorf(\"[controller/user] %v\", err)\n\t\treturn ctx.BadRequest(&app.StandardError{\n\t\t\tCode: 400,\n\t\t\tMessage: \"could not insert user to db\",\n\t\t})\n\t}\n\n\tlog.Printf(\"[controller/user] successfully added coindrop user: %v\\n\", user.CognitoAuthUserID)\n\n\tres := &app.User{\n\t\tID: \"\",\n\t\tCognitoAuthUserID: &user.CognitoAuthUserID,\n\t\tWalletAddress: &user.Wallet.Address,\n\t}\n\n\treturn ctx.OK(res)\n\t// UsersController_Create: end_implement\n}", "func Create(c *gin.Context) {\n\tvar user users.User\n\n\t// ShouldBindJSON - read request body and unmarshals the []bytes to user\n\tif err := c.ShouldBindJSON(&user); err != nil {\n\t\tbdErr := errors.NewBadRequestError(fmt.Sprintf(\"invalid json body: %s\", err.Error()))\n\t\tc.JSON(bdErr.Status, bdErr)\n\t\treturn\n\t}\n\n\tresult, err := services.UserServ.CreateUser(user)\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\tisPublic := c.GetHeader(\"X-Public\") == \"true\"\n\tc.JSON(http.StatusCreated, result.Marshall(isPublic))\n}", "func (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 (u *User) Create(ctx context.Context, user entity.User) (int, error) {\n\tuser.Salt = u.hasher.Salt()\n\n\tpass, err := u.hasher.Hash(user.Password, user.Salt)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tuser.Password = pass\n\n\treturn u.client.Create(ctx, user)\n}", "func Create() echo.HandlerFunc {\n\treturn emailAndPasswordRequired(\n\t\tfunc(context echo.Context) error {\n\n\t\t\temail := context.FormValue(\"email\")\n\t\t\tpassword := context.FormValue(\"password\")\n\t\t\tfirstname := context.FormValue(\"firstname\")\n\t\t\tlastname := context.FormValue(\"lastname\")\n\n\t\t\terr := emailx.Validate(email)\n\t\t\tif err != nil {\n\t\t\t\treturn context.JSON(http.StatusBadRequest, errors.New(\"Invalid email parameter in POST body\"))\n\t\t\t}\n\n\t\t\tif firstname == \"\" {\n\t\t\t\treturn context.JSON(http.StatusBadRequest, errors.New(\"Missing firstname parameter in POST body\"))\n\t\t\t}\n\t\t\tif lastname == \"\" {\n\t\t\t\treturn context.JSON(http.StatusBadRequest, errors.New(\"Missing lastname parameter in POST body\"))\n\t\t\t}\n\n\t\t\tuser, err := New(email, firstname, lastname, password)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn context.JSON(http.StatusInternalServerError, errors.New(\"User creation error\"))\n\t\t\t}\n\n\t\t\terr = Save(&user)\n\t\t\tif err != nil {\n\t\t\t\tif err.Error() == \"cannot create document, unique constraint violated\" {\n\t\t\t\t\treturn context.JSON(http.StatusConflict, errors.New(\"User already exists\"))\n\t\t\t\t}\n\t\t\t\treturn context.JSON(http.StatusInternalServerError, errors.New(\"User account creation failed - cannot be saved\"))\n\t\t\t}\n\t\t\tuser.Hash = \"\" // dont return the hash, for security concerns\n\n\t\t\treturn context.JSON(http.StatusCreated, formatUser(&user))\n\t\t})\n}", "func (s *UsersService) Create(userIn NewUser, createAsActive bool) (*User, *Response, error) {\n\n\tu := fmt.Sprintf(\"users?activate=%v\", createAsActive)\n\n\treq, err := s.client.NewRequest(\"POST\", u, userIn)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tnewUser := new(User)\n\tresp, err := s.client.Do(req, newUser)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn newUser, resp, err\n}", "func (r *RepositoryUsersCRUD) Create(user models.User) (models.User, error) {\n\tvar err error\n\tdone := make(chan bool)\n\tgo func(ch chan<- bool) {\n\t\tdefer close(ch)\n\t\terr = r.model.Create(&user).Error\n\t\tif err != nil {\n\t\t\tch <- false\n\t\t\treturn\n\t\t}\n\t\tch <- true\n\t}(done)\n\tif channels.OK(done) {\n\t\treturn user, nil\n\t}\n\treturn models.User{}, err\n}", "func (s *UsersService) Create(ctx context.Context, realm string, user *User) (*http.Response, error) {\n\tu := fmt.Sprintf(\"admin/realms/%s/users\", realm)\n\treq, err := s.keycloak.NewRequest(http.MethodPost, u, user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.keycloak.Do(ctx, req, nil)\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 (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 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 (i *UsersInteractor) Create(user User) (int, error) {\n\tif len(user.Name) == 0 {\n\t\treturn 0, errors.New(\"username can't be empty\")\n\t}\n\tid, err := i.users.Store(user)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn id, nil\n}", "func (s *FriendshipService) Create(params *FriendshipCreateParams) (*User, *http.Response, error) {\n\tuser := new(User)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Post(\"create.json\").QueryStruct(params).Receive(user, apiError)\n\treturn user, resp, relevantError(err, *apiError)\n}", "func (c *UserClient) Create() *UserCreate {\n\tmutation := newUserMutation(c.config, OpCreate)\n\treturn &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UserClient) Create() *UserCreate {\n\tmutation := newUserMutation(c.config, OpCreate)\n\treturn &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UserClient) Create() *UserCreate {\n\tmutation := newUserMutation(c.config, OpCreate)\n\treturn &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UserClient) Create() *UserCreate {\n\tmutation := newUserMutation(c.config, OpCreate)\n\treturn &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UserClient) Create() *UserCreate {\n\tmutation := newUserMutation(c.config, OpCreate)\n\treturn &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UserClient) Create() *UserCreate {\n\tmutation := newUserMutation(c.config, OpCreate)\n\treturn &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UserClient) Create() *UserCreate {\n\tmutation := newUserMutation(c.config, OpCreate)\n\treturn &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UserClient) Create() *UserCreate {\n\tmutation := newUserMutation(c.config, OpCreate)\n\treturn &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UserClient) Create() *UserCreate {\n\tmutation := newUserMutation(c.config, OpCreate)\n\treturn &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UserClient) Create() *UserCreate {\n\tmutation := newUserMutation(c.config, OpCreate)\n\treturn &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UserClient) Create() *UserCreate {\n\tmutation := newUserMutation(c.config, OpCreate)\n\treturn &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func Create(user User) error {\n\t\n}", "func (user *User) Create() (err error) {\n\tstmt, err := database.DB.Prepare(\"INSERT INTO users (uuid, fname, lname, email, password, created_at) VALUES (?, ?, ?, ?, ?, ?)\")\n\tif err != nil {\n\t\tlog.Println(\"Prepare statement error\", err)\n\t\treturn\n\t}\n\tdefer stmt.Close()\n\tres, err := stmt.Exec(\n\t\tdatabase.GenerateUUID(),\n\t\tuser.FName,\n\t\tuser.LName,\n\t\tuser.Email,\n\t\tdatabase.Encrypt(user.Password),\n\t\ttime.Now(),\n\t)\n\tif err != nil {\n\t\tlog.Println(\"Unable to insert data\", err)\n\t}\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\tlog.Println(\"Unable to retrieve user\", err)\n\t} else {\n\t\tlog.Printf(\"User created with id:%d\", id)\n\t}\n\treturn\n}", "func (ctx *CreateUserContext) Created(r *User) error {\n\tctx.ResponseData.Header().Set(\"Content-Type\", \"application/vnd.user+json\")\n\treturn ctx.ResponseData.Service.Send(ctx.Context, 201, r)\n}", "func (r *UserRepository) Create(ctx context.Context, ent entity.User) (created entity.User, err error) {\n\terr = ent.GenID()\n\tif err != nil {\n\t\treturn\n\t}\n\terr = r.DB(ctx).Create(&ent).Error\n\tif err != nil {\n\t\treturn\n\t}\n\terr = r.DB(ctx).Take(&created, \"id = ?\", ent.ID).Error\n\treturn created, err\n}", "func (uc UserController) CreateUser(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tu := models.User{}\n\n\tjson.NewDecoder(r.Body).Decode(&u)\n\n\t// create bson ID\n\t// u.ID = bson.NewObjectId().String()\n\n\t// store the user in mongodb\n\tusers[u.ID] = u\n\n\tuj, _ := json.Marshal(u)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated) // 201\n\tfmt.Fprintf(w, \"%s\\n\", uj)\n}", "func (k Keeper) CreateUser(ctx sdk.Context, msg types.MsgCreateUser) {\n\t// Create the user if it doesnt already exist for creator address\n\tif !k.UserExists(ctx, msg.Creator.String()) {\n\t\tcount := k.GetUserCount(ctx)\n\t\tvar user = types.User{\n\t\t\tCreator: msg.Creator,\n\t\t\tID: msg.Creator.String(),\n\t\t\tUsername: msg.Username,\n\t\t\tBio: msg.Bio,\n\t\t}\n\n\t\tstore := ctx.KVStore(k.storeKey)\n\t\tkey := []byte(types.UserPrefix + user.ID)\n\t\tvalue := k.cdc.MustMarshalBinaryLengthPrefixed(user)\n\t\tstore.Set(key, value)\n\n\t\t// Update user count\n\t\tk.SetUserCount(ctx, count+1)\n\t}\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\r\n\tdefer r.Body.Close()\r\n\tvar user model.User\r\n\r\n\tif err := json.NewDecoder(r.Body).Decode(&user); err != nil {\r\n\t\tlog.Println(err)\r\n\t\tu.RespondWithError(w, http.StatusBadRequest, \"Invalid request payload\")\r\n\t\treturn\r\n\t}\r\n\r\n\tif resp, ok := validate(&user); !ok {\r\n\t\tlog.Println(resp)\r\n\t\tu.RespondWithError(w, http.StatusBadRequest, resp)\r\n\t\treturn\r\n\t}\r\n\r\n\thashedPassword, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)\r\n\tuser.Password = string(hashedPassword)\r\n\r\n\tif err := dao.DBConn.InsertUser(user); err != nil {\r\n\t\tlog.Println(err)\r\n\t\tu.RespondWithError(w, http.StatusInternalServerError, err.Error())\r\n\t\treturn\r\n\t}\r\n\r\n\tuser.Token = model.GenerateToken(user.Email)\r\n\r\n\t// Delete password before response\r\n\tuser.Password = \"\"\r\n\r\n\tu.RespondWithJSON(w, http.StatusOK, user)\r\n}", "func (s *Service) Create(c context.Context, req *user.CreateReq) (*user.Resp, error) {\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !s.rbac.EnforceTenantAndRole(c, twisk.AccessRole(req.RoleId), req.TenantId) {\n\t\treturn nil, unauthorizedErr\n\t}\n\n\tif !s.sec.Password(req.Password, req.FirstName, req.LastName, req.Email) {\n\t\treturn nil, twirp.InternalError(\"password is not secure enough\")\n\t}\n\n\tusr, err := s.udb.Create(s.dbcl.WithContext(c), twisk.User{\n\t\tFirstName: req.FirstName,\n\t\tLastName: req.LastName,\n\t\tUsername: req.Username,\n\t\tEmail: strings.ToLower(req.Email),\n\t\tPassword: s.sec.Hash(req.Password),\n\t\tTenantID: req.TenantId,\n\t\tRoleID: req.RoleId,\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn usr.Proto(), nil\n}", "func (u *UsersClient) Create(ctx context.Context, userObj *envelope.User,\n\tsignup apitypes.Signup) (envelope.UserInf, error) {\n\n\tv := &url.Values{}\n\tif signup.InviteCode != \"\" {\n\t\tv.Set(\"code\", signup.InviteCode)\n\t}\n\tif signup.OrgInvite && signup.OrgName != \"\" {\n\t\tv.Set(\"org\", signup.OrgName)\n\t}\n\tif signup.Email != \"\" {\n\t\tv.Set(\"email\", signup.Email)\n\t}\n\n\te := envelope.Unsigned{}\n\terr := u.client.RoundTrip(ctx, \"POST\", \"/users\", v, &userObj, &e)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn envelope.ConvertUser(&e)\n}", "func (v UsersResource) Create(c buffalo.Context) error {\n\t// Allocate an empty User\n\tuser := &models.User{}\n\n\t// Bind user to the html form elements\n\tif err := c.Bind(user); err != nil {\n\t\treturn 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 fmt.Errorf(\"no transaction found\")\n\t}\n\n\t// Validate the data from the html form\n\tverrs, err := tx.ValidateAndCreate(user)\n\tif err != nil {\n\t\treturn 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(http.StatusUnprocessableEntity, r.Auto(c, user))\n\t}\n\n\t// If there are no errors set a success message\n\tc.Flash().Add(\"success\", T.Translate(c, \"user.created.success\"))\n\t// and redirect to the users index page\n\treturn c.Render(http.StatusCreated, r.Auto(c, user))\n}", "func CreateUser(c *gin.Context, client *statsd.Client) {\n\tlog.Info(\"creating user\")\n\tvar user entity.User\n\tc.BindJSON(&user)\n\n\tvar checkUser entity.User\n\tif err := model.GetUserByUsername(&checkUser, *user.Username, client); err == nil {\n\t\tlog.Error(\"the email has been registered\")\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"error\": \"the email has been registered!\",\n\t\t})\n\t\treturn\n\t}\n\n\terr := model.CreateUser(&user, client)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t} else {\n\t\tc.JSON(http.StatusCreated, gin.H{\n\t\t\t\"id\": user.ID,\n\t\t\t\"first_name\": user.FirstName,\n\t\t\t\"last_name\": user.LastName,\n\t\t\t\"username\": user.Username,\n\t\t\t\"account_created\": user.AccountCreated,\n\t\t\t\"account_updated\": user.AccountUpdated,\n\t\t})\n\t}\n\tlog.Info(\"user created\")\n}", "func CreateUser(user model.User) {\n\tfmt.Println(user)\n}", "func (uc UserController) CreateUser(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\n\tu := models.User{}\n\n\tjson.NewDecoder(r.Body).Decode(&u) //decode the request body\n\n\t//create bson ID\n\tu.ID = bson.NewObjectId()\n\n\t//store the user in mongodb\n\tuc.session.DB(\"go-web-dev-db\").C(\"users\").Insert(u)\n\n\t//remarshal\n\tuj, _ := json.Marshal(u)\n\n\tw.Header().Set(\"Content-Type\", \"application.json\")\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintf(w, \"%s\\n\", uj)\n}", "func (u *UsersClient) Create(ctx context.Context, userObj *SignupEnvelope,\n\tsignup apitypes.Signup) (*envelope.User, error) {\n\n\tv := &url.Values{}\n\tif signup.InviteCode != \"\" {\n\t\tv.Set(\"code\", signup.InviteCode)\n\t}\n\tif signup.OrgInvite && signup.OrgName != \"\" {\n\t\tv.Set(\"org\", signup.OrgName)\n\t}\n\tif signup.Email != \"\" {\n\t\tv.Set(\"email\", signup.Email)\n\t}\n\treq, err := u.client.NewRequest(\"POST\", \"/users\", v, userObj)\n\tif err != nil {\n\t\tlog.Printf(\"Error making api request: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tuser := envelope.User{}\n\t_, err = u.client.Do(ctx, req, &user)\n\tif err != nil {\n\t\tlog.Printf(\"Error making api request: %s\", err)\n\t\treturn nil, err\n\t}\n\n\terr = validateSelf(&user)\n\tif err != nil {\n\t\tlog.Printf(\"Invalid user object: %s\", err)\n\t\treturn nil, err\n\t}\n\n\treturn &user, nil\n}", "func (uc UserController) CreateUser(c *doze.Context) doze.ResponseSender {\n\tvar user User\n\n\tc.BindJSONEntity(&user)\n\n\tusers = append(users, user)\n\n\tuc.db.execute(fmt.Sprintf(\"INSERT INTO User (`firstName`, `lastName`) VALUES ('%v', '%v')\", user.FirstName, user.LastName))\n\n\treturn doze.NewCreatedJSONResponse(user)\n}", "func (us *UserService) Create(ctx context.Context, user User) (int64, error) {\n\treturn us.userRepository.Create(ctx, user)\n}", "func (c Client) CreateUser(ctx context.Context, user api.User, password string) (api.Identifier, error) {\n\tuser.ID = xid.New().Bytes()\n\tif _, err := c.db.ExecContext(ctx, \"insert into users (id, email, password, first_name, last_name) values ($1, $2, $3, $4)\", user.ID, user.Email, password, user.FirstName, user.LastName); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn user.ID, nil\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\treq := &models.User{}\n\tif err := DecodeRequestBody(r, req); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"Error while decoding the request body\" + err.Error()))\n\t\treturn\n\t}\n\tif _, err := dal.GetUsers(req.Name); err == nil {\n\t\tw.WriteHeader(http.StatusConflict)\n\t\tw.Write([]byte(\"already existing user\"))\n\t\treturn\n\t}\n\tif err := dal.CreateUser(req); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t}\n}", "func (repo *UserRepo) Create(user domain.Register) (domain.User, error) {\n\tvar m struct {\n\t\tCreateUser struct {\n\t\t\tId graphql.String\n\t\t\tName graphql.String\n\t\t\tUsername graphql.String\n\t\t\tPicture graphql.String\n\t\t} `graphql:\"createUser(input:{name: $name, username: $username, role: $role, tokenID: $tokenID, provider: $provider, picture: $picture, status: \\\"active\\\"})\"`\n\t}\n\n\tvars := map[string]interface{}{\n\t\t\"name\": graphql.String(user.Name),\n\t\t\"username\": graphql.String(user.Username),\n\t\t\"picture\": graphql.String(user.Picture),\n\t\t\"role\": graphql.String(user.Role),\n\t\t\"provider\": graphql.String(user.Provider),\n\t\t\"tokenID\": graphql.String(user.TokenID),\n\t}\n\n\terr := repo.client.Mutate(context.Background(), &m, vars)\n\tif err != nil {\n\t\treturn domain.User{}, err\n\t}\n\n\treturn domain.User{\n\t\tId: string(m.CreateUser.Id),\n\t\tName: string(m.CreateUser.Name),\n\t\tUsername: string(m.CreateUser.Username),\n\t\tPicture: string(m.CreateUser.Picture),\n\t}, nil\n}", "func (up *userProvider) Create(ctx context.Context, user *models.User) error {\n\terr := up.userStore.Create(ctx, user)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (service *UserService) Create(data *models.User) (*models.User, error) {\n\treturn service.repository.Create(data)\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 (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}", "func (h *Handler) CreateUser(c *fiber.Ctx) error {\n\tvar service = services.NewUserService()\n\tvar usr = &user.User{}\n\tif err := c.BodyParser(usr); err != nil {\n\t\treturn c.Status(422).JSON(fiber.Map{\"status\": \"error\", \"message\": err})\n\t}\n\n\tnewUser, err := service.CreateUser(usr)\n\tif err != nil {\n\t\treturn c.Status(400).JSON(fiber.Map{\"status\": \"error\", \"message\": err.Error()})\n\t}\n\n\treturn c.JSON(fiber.Map{\"status\": \"success\", \"message\": \"Created usr\", \"data\": newUser})\n}", "func (us *UserService) Create(u *User) (int, error) {\n\tif us.UserInterceptor != nil {\n\t\tif err := us.UserInterceptor.PreCreate(u); err != nil {\n\t\t\treturn -1, httperror.InternalServerError(fmt.Errorf(\"error while executing user interceptor 'PreCreate' error %v\", err))\n\t\t}\n\t}\n\n\tif err := u.validate(us, us.Config.MinPasswordLength, VDupUsername|VDupEmail|VPassword); err != nil {\n\t\treturn -1, err\n\t}\n\n\tsalt := crypt.GenerateSalt()\n\tsaltedPassword := append(u.PlainPassword[:], salt[:]...)\n\tpassword, err := crypt.CryptPassword([]byte(saltedPassword))\n\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\tu.Salt = salt\n\tu.Password = password\n\n\tuserID, err := us.Datasource.Create(u)\n\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\tif us.UserInterceptor != nil {\n\t\terrUserInterceptor := us.UserInterceptor.PostCreate(u)\n\t\tlogger.Log.Errorf(\"error while executing PostCreate user interceptor method %v\", errUserInterceptor)\n\t}\n\n\tsalt = nil\n\tsaltedPassword = nil\n\tu.PlainPassword = nil\n\n\treturn userID, nil\n}", "func CreateUser(w http.ResponseWriter, r *http.Request){\n\n\t\tu := User{}\n\n\t\terr:= json.NewDecoder(r.Body).Decode(&u)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\t// Checks if name is Empty\n\t\tfmt.Printf(\"name: [%+v]\\n\", u.Name)\n\t\tif u.Name == \"\" {\n\t\t\tfmt.Println(\"Empty string\")\n\t\t\tw.Write([]byte(`{\"status\":\"Invalid Name\"}`))\n\t\t\treturn\n\t\t}\n\n\n\t\t//start validation for username\n\t\tvar isStringAlphabetic = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`).MatchString\n\t\tif !isStringAlphabetic(u.Name){\n\t\t\tfmt.Println(\"is not alphanumeric\")\n\t\t\tw.Write([]byte(`{\"status\":\"Invalid Name\"}`))\n\t\t\treturn\n\t\t}\n\n\t\t//make the Name Uppercase\n\t\tu.Name = strings.ToUpper(u.Name)\n\n\t\t// check if username already exists\n\t\tuser := userExist(u.Name)\n\t\tif user != (User{}) {\n\t\t\tfmt.Println(\"Name already exists\")\n\t\t\tw.Write([]byte(`{\"status\":\"Name Exists\"}`))\n\t\t\treturn\n\t\t}\n\n\t\t//if it does exist create the user with a random ID and score = 0\n\t\tuuid, err := uuid.NewV4()\n\t\tu.ID = uuid.String()\n\t\tu.Score = 0\n\n\t\tquery := \"INSERT INTO users (id, name, score) VALUES ($1, $2, $3);\"\n\t\t_, err = db.Exec(query, u.ID, u.Name, u.Score);\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(201)\n\t\tjson.NewEncoder(w).Encode(u)\n\n}", "func createUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar user User\n\tif err := json.NewDecoder(r.Body).Decode(&user); err != nil {\n\t\tpanic(err)\n\t}\n\t//Todo (Farouk): Mock ID - not safe\n\tuser.ID = strconv.Itoa(rand.Intn(1000000))\n\tusers = append(users, user)\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(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\trepo := users.NewUserRepository(db)\n\tuser := &users.User{}\n\tdecoder := json.NewDecoder(r.Body)\n\n\tif err := decoder.Decode(user); err != nil {\n\t\tutils.JsonResponse(w, utils.ErrorResponse{Error: err.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\trepo.AddUser(user)\n\tutils.JsonResponse(w, user, http.StatusCreated)\n}", "func (us *UserUseCase) Create() (*models.User, error) {\n\treturn nil, nil\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}" ]
[ "0.7483689", "0.747625", "0.7386321", "0.73594594", "0.7348308", "0.73337317", "0.73107886", "0.73019266", "0.73012894", "0.7237672", "0.72374344", "0.7225838", "0.72086954", "0.71893203", "0.71826047", "0.71743757", "0.7169192", "0.7163983", "0.7156776", "0.7093787", "0.7080919", "0.7080439", "0.70788527", "0.7075948", "0.70723593", "0.70684457", "0.70400095", "0.70341927", "0.7029163", "0.7014509", "0.69873756", "0.69864243", "0.69844246", "0.6984148", "0.6982423", "0.6982309", "0.6980898", "0.6974391", "0.6968007", "0.69626", "0.69589853", "0.69551015", "0.6947038", "0.6946824", "0.6946377", "0.6933565", "0.6927141", "0.6923517", "0.6922812", "0.69180673", "0.69166", "0.6908282", "0.6904082", "0.68993896", "0.689151", "0.68878156", "0.6877959", "0.6877757", "0.6864466", "0.6862891", "0.6862891", "0.6862891", "0.6862891", "0.6862891", "0.6862891", "0.6862891", "0.6862891", "0.6862891", "0.6862891", "0.6862891", "0.6854865", "0.6839753", "0.68371886", "0.68312335", "0.6826647", "0.68263155", "0.68205225", "0.68106014", "0.68089527", "0.680823", "0.6806324", "0.68056387", "0.6804879", "0.680472", "0.680395", "0.67843586", "0.67841697", "0.67832214", "0.677994", "0.6779148", "0.67753845", "0.67736566", "0.6772628", "0.6750653", "0.67430955", "0.67391324", "0.6738343", "0.6731673", "0.6730984", "0.67296743", "0.6726137" ]
0.0
-1
Read the existing appNums out of what we published/checkpointed. Also read what we have persisted before a reboot Store in reserved map since we will be asked to allocate them later. Set bit in bitmap.
func appNumAllocatorInit(ctx *zedrouterContext) { pubAppNetworkStatus := ctx.pubAppNetworkStatus pubUuidToNum := ctx.pubUuidToNum items := pubUuidToNum.GetAll() for key, st := range items { status := cast.CastUuidToNum(st) if status.Key() != key { log.Errorf("appNumAllocatorInit key/UUID mismatch %s vs %s; ignored %+v\n", key, status.Key(), status) continue } if status.NumType != "appNum" { continue } log.Infof("appNumAllocatorInit found %v\n", status) appNum := status.Number uuid := status.UUID // If we have a config for the UUID we should mark it as // allocated; otherwise mark it as reserved. // XXX however, on startup we are not likely to have any // config yet. if AllocReservedAppNumBits.IsSet(appNum) { log.Errorf("AllocReservedAppNumBits already set for %s num %d\n", uuid.String(), appNum) continue } log.Infof("Reserving appNum %d for %s\n", appNum, uuid) AllocReservedAppNumBits.Set(appNum) // Clear InUse uuidtonum.UuidToNumFree(ctx.pubUuidToNum, uuid) } // In case zedrouter process restarted we fill in InUse from // AppNetworkStatus items = pubAppNetworkStatus.GetAll() for key, st := range items { status := cast.CastAppNetworkStatus(st) if status.Key() != key { log.Errorf("appNumAllocatorInit key/UUID mismatch %s vs %s; ignored %+v\n", key, status.Key(), status) continue } appNum := status.AppNum uuid := status.UUIDandVersion.UUID // If we have a config for the UUID we should mark it as // allocated; otherwise mark it as reserved. // XXX however, on startup we are not likely to have any // config yet. if !AllocReservedAppNumBits.IsSet(appNum) { log.Fatalf("AllocReservedAppNumBits not set for %s num %d\n", uuid.String(), appNum) continue } log.Infof("Marking InUse appNum %d for %s\n", appNum, uuid) // Set InUse uuidtonum.UuidToNumAllocate(ctx.pubUuidToNum, uuid, appNum, false, "appNum") } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func appNumOnUNetInit(ctx *zedrouterContext) {\n\n\t// initialize the base\n\tappNumBase = make(map[string]*types.Bitmap)\n\n\tpubAppNetworkStatus := ctx.pubAppNetworkStatus\n\tpub := ctx.pubUUIDPairAndIfIdxToNum\n\tnumType := appNumOnUNetType\n\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\tlog.Functionf(\"appNumOnUNetInit found %v\", appNumMap)\n\t\tappNum := appNumMap.Number\n\t\tbaseID := appNumMap.BaseID\n\t\tappID := appNumMap.AppID\n\t\tifIdx := appNumMap.IfIdx\n\n\t\t// If we have a config for the UUID Pair, we should mark it as\n\t\t// allocated; otherwise mark it as reserved.\n\t\t// XXX however, on startup we are not likely to have any\n\t\t// config yet.\n\t\tbaseMap := appNumOnUNetBaseCreate(baseID)\n\t\tif baseMap.IsSet(appNum) {\n\t\t\tlog.Errorf(\"Bitmap is already set for %s num %d\",\n\t\t\t\ttypes.UUIDPairAndIfIdxToNumKey(baseID, appID, ifIdx), appNum)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Functionf(\"Reserving appNum %d for %s\",\n\t\t\tappNum, types.UUIDPairAndIfIdxToNumKey(baseID, appID, ifIdx))\n\t\tbaseMap.Set(appNum)\n\t\t// Clear InUse\n\t\tuuidpairtonum.NumFree(log, pub, baseID, appID, ifIdx)\n\t}\n\t// In case zedrouter process restarted we fill in InUse from\n\t// AppNetworkStatus, underlay network entries\n\titems = pubAppNetworkStatus.GetAll()\n\tfor _, item := range items {\n\t\tstatus := item.(types.AppNetworkStatus)\n\t\tappID := status.UUIDandVersion.UUID\n\n\t\t// If we have a config for the UUID we should mark it as\n\t\t// allocated; otherwise mark it as reserved.\n\t\t// XXX however, on startup we are not likely to have any\n\t\t// config yet.\n\t\tfor i := range status.UnderlayNetworkList {\n\t\t\tulStatus := &status.UnderlayNetworkList[i]\n\t\t\tbaseID := ulStatus.Network\n\t\t\tbaseMap := appNumOnUNetBaseGet(baseID)\n\t\t\tif baseMap == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tappNum, err := uuidpairtonum.NumGet(log, pub,\n\t\t\t\tbaseID, appID, numType, ulStatus.IfIdx)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !baseMap.IsSet(appNum) {\n\t\t\t\tlog.Fatalf(\"Bitmap is not set for %s num %d\",\n\t\t\t\t\ttypes.UUIDPairAndIfIdxToNumKey(baseID, appID, ulStatus.IfIdx), appNum)\n\t\t\t}\n\t\t\tlog.Functionf(\"Marking InUse for appNum %d\",\n\t\t\t\tappNum)\n\t\t\t// Set InUse\n\t\t\tuuidpairtonum.NumAllocate(log, pub, baseID,\n\t\t\t\tappID, appNum, false, numType, ulStatus.IfIdx)\n\t\t}\n\t}\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 ReadConfiAppNum(filenamePath string) int {\n\n\tvar appNum int\n\tflag, flag1 := true, true\n\tfile, err := os.Open(filenamePath)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tscanner.Split(bufio.ScanWords)\n\n\tfor flag {\n\t\tscanner.Scan()\n\t\tif scanner.Text() != \"END\" {\n\t\t\tif scanner.Text() == \"Application\" {\n\n\t\t\t\tfor flag1 {\n\t\t\t\t\tscanner.Scan()\n\t\t\t\t\tif scanner.Text() == \"number\" {\n\t\t\t\t\t\tscanner.Scan()\n\t\t\t\t\t\tflag1 = false\n\t\t\t\t\t\tnum := scanner.Text()\n\n\t\t\t\t\t\tappNum, err = strconv.Atoi(num)\n\t\t\t\t\t} else if scanner.Text() == \"END\" {\n\t\t\t\t\t\tflag1 = false\n\t\t\t\t\t\tflag = false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if scanner.Text() == \"END\" {\n\t\t\t\tflag1 = false\n\t\t\t\tflag = false\n\t\t\t}\n\t\t} else if scanner.Text() == \"END\" {\n\t\t\tflag1 = false\n\t\t\tflag = false\n\t\t}\n\n\t\tflag = false\n\t}\n\treturn appNum\n\n}", "func appNumOnUNetBaseGet(baseID uuid.UUID) *types.Bitmap {\n\tif baseMap, exist := appNumBase[baseID.String()]; exist {\n\t\treturn baseMap\n\t}\n\treturn nil\n}", "func appNumOnUNetRefCount(ctx *zedrouterContext, networkID uuid.UUID) int {\n\tappNumMap := appNumOnUNetBaseGet(networkID)\n\tif appNumMap == nil {\n\t\tlog.Fatalf(\"appNumOnUNetRefCount: non map\")\n\t}\n\tpub := ctx.pubUUIDPairAndIfIdxToNum\n\tnumType := appNumOnUNetType\n\titems := pub.GetAll()\n\tcount := 0\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.BaseID == networkID {\n\t\t\tlog.Functionf(\"appNumOnUNetRefCount(%s): found: %v\",\n\t\t\t\tnetworkID, appNumMap)\n\t\t\tcount++\n\t\t}\n\t}\n\tlog.Functionf(\"appNumOnUNetRefCount(%s) found %d\", networkID, count)\n\treturn count\n}", "func appNumOnUNetBaseCreate(baseID uuid.UUID) *types.Bitmap {\n\tif appNumOnUNetBaseGet(baseID) == nil {\n\t\tlog.Functionf(\"appNumOnUNetBaseCreate (%s)\", baseID.String())\n\t\tappNumBase[baseID.String()] = new(types.Bitmap)\n\t}\n\treturn appNumOnUNetBaseGet(baseID)\n}", "func (k *Instance) RestoreScaledAppsReplicas() error {\n\tsharedDeps, sharedSS, err := k.GetPXSharedApps()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.Infof(\"found %d deployments and %d statefulsets to restore\", len(sharedDeps), len(sharedSS))\n\n\tfor _, d := range sharedDeps {\n\t\tdeploymentName := d.Name\n\t\tdeploymentNamespace := d.Namespace\n\t\tlogrus.Infof(\"restoring app: [%s] %s\", d.Namespace, d.Name)\n\t\tt := func() (interface{}, bool, error) {\n\t\t\tdCopy, err := k.kubeClient.AppsV1().Deployments(deploymentNamespace).Get(context.TODO(), deploymentName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\tif errors.IsNotFound(err) {\n\t\t\t\t\treturn nil, false, nil // done as deployment is deleted\n\t\t\t\t}\n\n\t\t\t\treturn nil, true, err\n\t\t\t}\n\n\t\t\tdCopy = dCopy.DeepCopy()\n\t\t\tif dCopy.Annotations == nil {\n\t\t\t\treturn nil, false, nil // done as this is not an app we touched\n\t\t\t}\n\n\t\t\tval, present := dCopy.Annotations[replicaMemoryKey]\n\t\t\tif !present || len(val) == 0 {\n\t\t\t\tlogrus.Infof(\"not restoring app: [%s] %s as no annotation found to track replica count\", deploymentNamespace, deploymentName)\n\t\t\t\treturn nil, false, nil // done as this is not an app we touched\n\t\t\t}\n\n\t\t\tparsedVal := intstr.Parse(val)\n\t\t\tif parsedVal.Type != intstr.Int {\n\t\t\t\treturn nil, false /*retry won't help */, fmt.Errorf(\"failed to parse saved replica count: %v\", val)\n\t\t\t}\n\n\t\t\tdelete(dCopy.Annotations, replicaMemoryKey)\n\t\t\tdCopy.Spec.Replicas = &parsedVal.IntVal\n\n\t\t\t_, err = k.kubeClient.AppsV1().Deployments(dCopy.Namespace).Update(context.TODO(), dCopy, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, true, err\n\t\t\t}\n\n\t\t\treturn nil, false, nil\n\t\t}\n\n\t\tif _, err := task.DoRetryWithTimeout(t, deploymentUpdateTimeout, defaultRetryInterval); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, s := range sharedSS {\n\t\tlogrus.Infof(\"restoring app: [%s] %s\", s.Namespace, s.Name)\n\n\t\tt := func() (interface{}, bool, error) {\n\t\t\tsCopy, err := k.kubeClient.AppsV1().StatefulSets(s.Namespace).Get(context.TODO(), s.Name, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\tif errors.IsNotFound(err) {\n\t\t\t\t\treturn nil, false, nil // done as statefulset is deleted\n\t\t\t\t}\n\n\t\t\t\treturn nil, true, err\n\t\t\t}\n\n\t\t\tsCopy = sCopy.DeepCopy()\n\t\t\tif sCopy.Annotations == nil {\n\t\t\t\treturn nil, false, nil // done as this is not an app we touched\n\t\t\t}\n\n\t\t\tval, present := sCopy.Annotations[replicaMemoryKey]\n\t\t\tif !present || len(val) == 0 {\n\t\t\t\treturn nil, false, nil // done as this is not an app we touched\n\t\t\t}\n\n\t\t\tparsedVal := intstr.Parse(val)\n\t\t\tif parsedVal.Type != intstr.Int {\n\t\t\t\treturn nil, false, fmt.Errorf(\"failed to parse saved replica count: %v\", val)\n\t\t\t}\n\n\t\t\tdelete(sCopy.Annotations, replicaMemoryKey)\n\t\t\tsCopy.Spec.Replicas = &parsedVal.IntVal\n\n\t\t\t_, err = k.kubeClient.AppsV1().StatefulSets(sCopy.Namespace).Update(context.TODO(), sCopy, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, true, err\n\t\t\t}\n\n\t\t\treturn nil, false, nil\n\t\t}\n\n\t\tif _, err := task.DoRetryWithTimeout(t, statefulSetUpdateTimeout, defaultRetryInterval); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (im InterestMap) GetApps() []int {\n\tapps := make(map[int]struct{})\n\tfor t, _ := range im {\n\t\tapps[t.AppID] = struct{}{}\n\t}\n\n\tvar app_ids []int\n\tfor k, _ := range apps {\n\t\tapp_ids = append(app_ids, k)\n\t}\n\tsort.Ints(app_ids)\n\treturn app_ids\n}", "func IncOpenedApps() {\n\tif globalCollector.IsOn() {\n\t\tglobalCollector.totOpenedApps.Inc()\n\t}\n}", "func (app *App) Num() (numApp int, err error) {\n\tif err := app.tre.session.Query(`SELECT count(*) FROM applications LIMIT 1`).\n\t\tConsistency(gocql.One).Scan(&numApp); err != nil {\n\t\tfmt.Printf(\"Num Error: %s\\n\", err.Error())\n\t}\n\treturn\n}", "func ReadAppAndDepnConfi(dependold [][]int, appNumOld int) ([]appproperties.ApplProperty, [][]int, int, int) {\n\tvar appfile, appfileConstraint, depndfile string\n\tif appNumOld < 200 {\n\t\t//fmt.Println(\"/Users/abdullah/go/src/github.com/appSchedul/souceFile/depndConfiNewArrive20.cog\")\n\t\tappfile = \"/Users/abdullah/go/src/github.com/appSchedul/souceFile/appConfiNewArrive20.cog\"\n\t\tappfileConstraint = \"/Users/abdullah/go/src/github.com/appSchedul/souceFile/appConstNewArrive20.cog\"\n\t\tdepndfile = \"/Users/abdullah/go/src/github.com/appSchedul/souceFile/depndConfiNewArrive20.cog\"\n\t} else {\n\t\t//fmt.Println(\"/Users/abdullah/go/src/github.com/appSchedul/souceFile/depndConfiNewArrive200.cog\")\n\t\tappfile = \"/Users/abdullah/go/src/github.com/appSchedul/souceFile/appConfiNewArrive20.cog\"\n\t\tappfileConstraint = \"/Users/abdullah/go/src/github.com/appSchedul/souceFile/appConstNewArrive20.cog\"\n\t\tdepndfile = \"/Users/abdullah/go/src/github.com/appSchedul/souceFile/depndConfiNewArrive200.cog\"\n\t}\n\tvar ap string // application name fill the struct\n\tvar apCPU int // application cpu fill the struct\n\tvar apRAM int // application ram fill the struct\n\tvar apIO string // application io fill the struct\n\tj := 0\n\tappNum := readappnum.ReadConfiAppNum(appfile) //read application number form the file\n\tappName := make([]string, appNum)\n\tappName = readappname.ReadConfiAppname(appfile) //read application name form the file\n\tvar applic = make([]appproperties.ApplProperty, appNum) //build applications infromation calss\n\tfor i := appNumOld; i < appNumOld+appNum; i++ { //fill application from config file\n\n\t\tap = \"A\" + strconv.Itoa(j)\n\t\tapCPU = appfillconstraints.ReadAppConstraintsCPU(appfileConstraint, ap)\n\t\tapRAM = appfillconstraints.ReadAppConstraintsRAM(appfileConstraint, ap)\n\t\tapIO = appfillconstraints.ReadAppConstraintsIO(appfileConstraint, ap)\n\t\tap = \"A\" + strconv.Itoa(i)\n\t\tapplic[j].ApplPropertyFu(appName[j], ap, 1, apCPU, apRAM, apIO) //fill the application spicification array\n\t\tj++\n\t}\n\t//finsh reading application informations\n\n\t//start reading applications dependencies\n\tvar depen = make([][]int, appNum)\n\tvar newAppDepen = make([][]int, appNum)\n\tdepen = appdepe.ReadConfiAppDep(appfile, depndfile, appNumOld)\n\t//m := 0\n\tfor i := 0; i < appNum; i++ {\n\t\tnewAppDepen[i] = depen[i] //this the dependencies of the new arrival applications\n\t}\n\n\t// comaining the dependencies matrix old application dependencies and new arrival applications dependencies\n\tcompAppdepen := make([][]int, appNum+appNumOld)\n\n\tfor i := 0; i < appNum+appNumOld; i++ {\n\t\tcompAppdepen[i] = make([]int, appNum+appNumOld)\n\n\t\tfor j := 0; j < appNum+appNumOld; j++ {\n\n\t\t\tif i < appNumOld {\n\t\t\t\tif j < appNumOld {\n\t\t\t\t\tcompAppdepen[i][j] = dependold[i][j]\n\t\t\t\t} else {\n\t\t\t\t\tcompAppdepen[i][j] = 0\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\tcompAppdepen[i][j] = newAppDepen[i-appNumOld][j]\n\n\t\t\t}\n\t\t}\n\n\t}\n\n\tdepndNum := appdepe.ReadDependNum(compAppdepen, appNum+appNumOld) //count the dpendentst number\n\treturn applic, compAppdepen, depndNum, appNum + appNumOld\n}", "func (m *AppVulnerabilityTask) SetMobileAppCount(value *int32)() {\n err := m.GetBackingStore().Set(\"mobileAppCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *AppVulnerabilityTask) GetMobileAppCount()(*int32) {\n val, err := m.GetBackingStore().Get(\"mobileAppCount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func (m *ServiceMgr) savePrimaryStore(app application) (info *runtimeInfo) {\n\tappName := app.Name\n\tinfo = &runtimeInfo{}\n\tlogging.Infof(\"Saving application %v to primary store\", appName)\n\n\tif rebStatus := m.checkRebalanceStatus(); rebStatus.Code != m.statusCodes.ok.Code {\n\t\tinfo.Code = rebStatus.Code\n\t\tinfo.Info = rebStatus.Info\n\t\treturn\n\t}\n\n\tif m.checkIfDeployed(appName) {\n\t\tinfo.Code = m.statusCodes.errAppDeployed.Code\n\t\tinfo.Info = fmt.Sprintf(\"App with same name %s is already deployed, skipping save request\", appName)\n\t\treturn\n\t}\n\n\tif app.DeploymentConfig.SourceBucket == app.DeploymentConfig.MetadataBucket {\n\t\tinfo.Code = m.statusCodes.errSrcMbSame.Code\n\t\tinfo.Info = fmt.Sprintf(\"Source bucket same as metadata bucket. source_bucket : %s metadata_bucket : %s\", app.DeploymentConfig.SourceBucket, app.DeploymentConfig.MetadataBucket)\n\t\treturn\n\t}\n\n\tnsServerEndpoint := net.JoinHostPort(util.Localhost(), m.restPort)\n\tcinfo, err := util.FetchNewClusterInfoCache(nsServerEndpoint)\n\tif err != nil {\n\t\tinfo.Code = m.statusCodes.errConnectNsServer.Code\n\t\tinfo.Info = fmt.Sprintf(\"Failed to initialise cluster info cache, err: %v\", err)\n\t\treturn\n\t}\n\n\tif cinfo.GetBucketUUID(app.DeploymentConfig.SourceBucket) == \"\" {\n\t\tinfo.Code = m.statusCodes.errSrcBucketMissing.Code\n\t\tinfo.Info = fmt.Sprintf(\"Supplied source bucket: %v doesn't exist\", app.DeploymentConfig.SourceBucket)\n\t\treturn\n\t}\n\n\tif cinfo.GetBucketUUID(app.DeploymentConfig.MetadataBucket) == \"\" {\n\t\tinfo.Code = m.statusCodes.errMetaBucketMissing.Code\n\t\tinfo.Info = fmt.Sprintf(\"Supplied metadata bucket: %v doesn't exist\", app.DeploymentConfig.MetadataBucket)\n\t\treturn\n\t}\n\n\tisMemcached, err := cinfo.IsMemcached(app.DeploymentConfig.SourceBucket)\n\tif err != nil {\n\t\tinfo.Code = m.statusCodes.errBucketTypeCheck.Code\n\t\tinfo.Info = fmt.Sprintf(\"Failed to check bucket type using cluster info cache, err: %v\", err)\n\t\treturn\n\t}\n\n\tif isMemcached {\n\t\tinfo.Code = m.statusCodes.errMemcachedBucket.Code\n\t\tinfo.Info = \"Source bucket is memcached, should be either couchbase or ephemeral\"\n\t\treturn\n\t}\n\n\tbuilder := flatbuffers.NewBuilder(0)\n\n\tvar bNames []flatbuffers.UOffsetT\n\n\tfor i := 0; i < len(app.DeploymentConfig.Buckets); i++ {\n\t\talias := builder.CreateString(app.DeploymentConfig.Buckets[i].Alias)\n\t\tbName := builder.CreateString(app.DeploymentConfig.Buckets[i].BucketName)\n\n\t\tcfg.BucketStart(builder)\n\t\tcfg.BucketAddAlias(builder, alias)\n\t\tcfg.BucketAddBucketName(builder, bName)\n\t\tcsBucket := cfg.BucketEnd(builder)\n\n\t\tbNames = append(bNames, csBucket)\n\t}\n\n\tcfg.DepCfgStartBucketsVector(builder, len(bNames))\n\tfor i := 0; i < len(bNames); i++ {\n\t\tbuilder.PrependUOffsetT(bNames[i])\n\t}\n\tbuckets := builder.EndVector(len(bNames))\n\n\tmetaBucket := builder.CreateString(app.DeploymentConfig.MetadataBucket)\n\tsourceBucket := builder.CreateString(app.DeploymentConfig.SourceBucket)\n\n\tcfg.DepCfgStart(builder)\n\tcfg.DepCfgAddBuckets(builder, buckets)\n\tcfg.DepCfgAddMetadataBucket(builder, metaBucket)\n\tcfg.DepCfgAddSourceBucket(builder, sourceBucket)\n\tdepcfg := cfg.DepCfgEnd(builder)\n\n\tappCode := builder.CreateString(app.AppHandlers)\n\taName := builder.CreateString(app.Name)\n\n\tcfg.ConfigStart(builder)\n\tcfg.ConfigAddId(builder, uint32(app.ID))\n\tcfg.ConfigAddAppCode(builder, appCode)\n\tcfg.ConfigAddAppName(builder, aName)\n\tcfg.ConfigAddDepCfg(builder, depcfg)\n\tconfig := cfg.ConfigEnd(builder)\n\n\tbuilder.Finish(config)\n\n\tappContent := builder.FinishedBytes()\n\n\tif len(appContent) > maxHandlerSize {\n\t\tinfo.Code = m.statusCodes.errAppCodeSize.Code\n\t\tinfo.Info = fmt.Sprintf(\"App: %s Handler Code size is more than 128K\", appName)\n\t\treturn\n\t}\n\n\tc := &consumer.Consumer{}\n\tcompilationInfo, err := c.SpawnCompilationWorker(app.AppHandlers, string(appContent), appName, m.adminHTTPPort)\n\tif err != nil || !compilationInfo.CompileSuccess {\n\t\tres, mErr := json.Marshal(&compilationInfo)\n\t\tif mErr != nil {\n\t\t\tinfo.Code = m.statusCodes.errMarshalResp.Code\n\t\t\tinfo.Info = fmt.Sprintf(\"App: %s Failed to marshal compilation status, err: %v\", appName, mErr)\n\t\t\treturn\n\t\t}\n\n\t\tinfo.Code = m.statusCodes.errHandlerCompile.Code\n\t\tinfo.Info = fmt.Sprintf(\"%v\\n\", string(res))\n\t\treturn\n\t}\n\n\tsettingsPath := metakvAppSettingsPath + appName\n\tsettings := app.Settings\n\n\tmData, mErr := json.Marshal(&settings)\n\tif mErr != nil {\n\t\tinfo.Code = m.statusCodes.errMarshalResp.Code\n\t\tinfo.Info = fmt.Sprintf(\"App: %s Failed to marshal settings, err: %v\", appName, mErr)\n\t\treturn\n\t}\n\n\tmkvErr := util.MetakvSet(settingsPath, mData, nil)\n\tif mkvErr != nil {\n\t\tinfo.Code = m.statusCodes.errSetSettingsPs.Code\n\t\tinfo.Info = fmt.Sprintf(\"App: %s Failed to store updated settings in metakv, err: %v\", appName, mkvErr)\n\t\treturn\n\t}\n\n\t//Delete stale entry\n\terr = util.DeleteAppContent(metakvAppsPath, metakvChecksumPath, appName)\n\tif err != nil {\n\t\tinfo.Code = m.statusCodes.errSaveAppPs.Code\n\t\tinfo.Info = fmt.Sprintf(\"Failed to clean up stale entry for app: %v err: %v\", appName, err)\n\t\treturn\n\t}\n\n\terr = util.WriteAppContent(metakvAppsPath, metakvChecksumPath, appName, appContent)\n\tif err != nil {\n\t\tinfo.Code = m.statusCodes.errSaveAppPs.Code\n\t\tinfo.Info = fmt.Sprintf(\"App: %v failed to write to metakv, err: %v\", appName, err)\n\t\treturn\n\t}\n\n\tinfo.Code = m.statusCodes.ok.Code\n\tinfo.Info = \"Stored application config in metakv\"\n\treturn\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 (counter *Counters) IncOpenedApps() {\n\tcounter.totOpenedApps.Inc()\n}", "func loadRegistryEntries(r io.Reader, numEntries int64, b bitfield, upgradeV100 bool) (map[modules.RegistryEntryID]*value, error) {\n\t// Load the remaining entries.\n\tvar entry [PersistedEntrySize]byte\n\tentries := make(map[modules.RegistryEntryID]*value)\n\tfor index := int64(1); index < numEntries; index++ {\n\t\t_, err := io.ReadFull(r, entry[:])\n\t\tif err != nil {\n\t\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"failed to read entry %v of %v\", index, numEntries))\n\t\t}\n\t\tvar pe persistedEntry\n\t\terr = pe.Unmarshal(entry[:])\n\t\tif err != nil {\n\t\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"failed to parse entry %v of %v\", index, numEntries))\n\t\t}\n\t\tif pe.Key == noKey {\n\t\t\tcontinue // ignore unused entries\n\t\t}\n\t\t// Set the type if it's not set.\n\t\tif upgradeV100 && pe.Type == modules.RegistryTypeInvalid {\n\t\t\tpe.Type = modules.RegistryTypeWithoutPubkey\n\t\t} else if pe.Type == modules.RegistryTypeInvalid {\n\t\t\treturn nil, modules.ErrInvalidRegistryEntryType\n\t\t}\n\t\t// Add the entry to the store.\n\t\tv, err := pe.Value(index)\n\t\tif err != nil {\n\t\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"failed to get key-value pair from entry %v of %v\", index, numEntries))\n\t\t}\n\t\tentries[v.mapKey()] = v\n\t\t// Track it in the bitfield.\n\t\terr = b.Set(uint64(index) - 1)\n\t\tif err != nil {\n\t\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"failed to mark entry %v of %v as used in bitfield\", index, numEntries))\n\t\t}\n\t}\n\treturn entries, nil\n}", "func existingTaskNumbers() []int {\n\n\tlist := make([]int, 0)\n\ttasks, err := ioutil.ReadDir(\"./coursedata/tasks\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn list\n\t}\n\n\tfor _, f := range tasks {\n\t\tif f.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tfName := f.Name()\n\t\tfNumStr := fName[5 : len(fName)-3]\n\t\tfNum, _ := strconv.Atoi(fNumStr)\n\t\tlist = append(list, fNum)\n\t}\n\treturn list\n}", "func IncCreatedApps() {\n\tif globalCollector.IsOn() {\n\t\tglobalCollector.totCreatedApps.Inc()\n\t}\n}", "func (m *AndroidManagedStoreApp) SetUsedLicenseCount(value *int32)() {\n err := m.GetBackingStore().Set(\"usedLicenseCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *DeviceEnrollmentWindowsHelloForBusinessConfiguration) GetPinPreviousBlockCount()(*int32) {\n val, err := m.GetBackingStore().Get(\"pinPreviousBlockCount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func (b *profileBuilder) readMapping() {\n\tif !machVMInfo(b.addMapping) {\n\t\tb.addMappingEntry(0, 0, 0, \"\", \"\", true)\n\t}\n}", "func (m *ImportedWindowsAutopilotDeviceIdentityState) GetAdditionalData()(map[string]any) {\n val , err := m.backingStore.Get(\"additionalData\")\n if err != nil {\n panic(err)\n }\n if val == nil {\n var value = make(map[string]any);\n m.SetAdditionalData(value);\n }\n return val.(map[string]any)\n}", "func getSerialNumber(app *AppContext) error {\n\terr := app.burnerLogDB.View(func(tx *bolt.Tx) error {\n\t\ttemp := tx.Bucket([]byte(\"serial\")).Get([]byte(\"serial\"))\n\t\tapp.serialNumber, _ = strconv.Atoi(string(temp))\n\t\treturn nil\n\t})\n\treturn err\n}", "func (m *AndroidManagedStoreApp) GetUsedLicenseCount()(*int32) {\n val, err := m.GetBackingStore().Get(\"usedLicenseCount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func getMockAppWithBalance(t *testing.T, numGenAccs int, balance int64) (mockApp *MockApp,\n\taddrKeysSlice mock.AddrKeysSlice) {\n\tmapp := mock.NewApp()\n\tregisterCodec(mapp.Cdc)\n\n\tmockApp = &MockApp{\n\t\tApp: mapp,\n\t\tkeyOrder: sdk.NewKVStoreKey(OrderStoreKey),\n\n\t\tkeyToken: sdk.NewKVStoreKey(token.StoreKey),\n\t\tkeyLock: sdk.NewKVStoreKey(token.KeyLock),\n\t\tkeyDex: sdk.NewKVStoreKey(dex.StoreKey),\n\t\tkeyTokenPair: sdk.NewKVStoreKey(dex.TokenPairStoreKey),\n\n\t\tkeySupply: sdk.NewKVStoreKey(supply.StoreKey),\n\t}\n\n\tfeeCollector := supply.NewEmptyModuleAccount(auth.FeeCollectorName)\n\tblacklistedAddrs := make(map[string]bool)\n\tblacklistedAddrs[feeCollector.String()] = true\n\n\tmockApp.bankKeeper = bank.NewBaseKeeper(mockApp.AccountKeeper,\n\t\tmockApp.ParamsKeeper.Subspace(bank.DefaultParamspace),\n\t\tblacklistedAddrs)\n\n\tmaccPerms := map[string][]string{\n\t\tauth.FeeCollectorName: nil,\n\t\ttoken.ModuleName: {supply.Minter, supply.Burner},\n\t}\n\tmockApp.supplyKeeper = supply.NewKeeper(mockApp.Cdc, mockApp.keySupply, mockApp.AccountKeeper,\n\t\tmockApp.bankKeeper, maccPerms)\n\n\tmockApp.tokenKeeper = token.NewKeeper(\n\t\tmockApp.bankKeeper,\n\t\tmockApp.ParamsKeeper.Subspace(token.DefaultParamspace),\n\t\tauth.FeeCollectorName,\n\t\tmockApp.supplyKeeper,\n\t\tmockApp.keyToken,\n\t\tmockApp.keyLock,\n\t\tmockApp.Cdc,\n\t\ttrue, mockApp.AccountKeeper)\n\n\tmockApp.dexKeeper = dex.NewKeeper(\n\t\tauth.FeeCollectorName,\n\t\tmockApp.supplyKeeper,\n\t\tmockApp.ParamsKeeper.Subspace(dex.DefaultParamspace),\n\t\tmockApp.tokenKeeper,\n\t\tnil,\n\t\tmockApp.bankKeeper,\n\t\tmockApp.keyDex,\n\t\tmockApp.keyTokenPair,\n\t\tmockApp.Cdc)\n\n\tmockApp.orderKeeper = NewKeeper(\n\t\tmockApp.tokenKeeper,\n\t\tmockApp.supplyKeeper,\n\t\tmockApp.dexKeeper,\n\t\tmockApp.ParamsKeeper.Subspace(DefaultParamspace),\n\t\tauth.FeeCollectorName,\n\t\tmockApp.keyOrder,\n\t\tmockApp.Cdc,\n\t\ttrue,\n\t\tmonitor.NopOrderMetrics())\n\n\tmockApp.Router().AddRoute(RouterKey, NewOrderHandler(mockApp.orderKeeper))\n\tmockApp.QueryRouter().AddRoute(QuerierRoute, NewQuerier(mockApp.orderKeeper))\n\n\tmockApp.SetBeginBlocker(getBeginBlocker(mockApp.orderKeeper))\n\tmockApp.SetEndBlocker(getEndBlocker(mockApp.orderKeeper))\n\tmockApp.SetInitChainer(getInitChainer(mockApp.App, mockApp.supplyKeeper,\n\t\t[]exported.ModuleAccountI{feeCollector}))\n\n\tdecCoins, err := sdk.ParseDecCoins(fmt.Sprintf(\"%d%s,%d%s\",\n\t\tbalance, common.NativeToken, balance, common.TestToken))\n\trequire.Nil(t, err)\n\tcoins := decCoins\n\n\tkeysSlice, genAccs := CreateGenAccounts(numGenAccs, coins)\n\taddrKeysSlice = keysSlice\n\n\t// todo: checkTx in mock app\n\tmockApp.SetAnteHandler(nil)\n\n\tapp := mockApp\n\trequire.NoError(t, app.CompleteSetup(\n\t\tapp.keyOrder,\n\t\tapp.keyToken,\n\t\tapp.keyDex,\n\t\tapp.keyTokenPair,\n\t\tapp.keyLock,\n\t\tapp.keySupply,\n\t))\n\tmock.SetGenesis(mockApp.App, genAccs)\n\n\tfor i := 0; i < numGenAccs; i++ {\n\t\tmock.CheckBalance(t, app.App, keysSlice[i].Address, coins)\n\t\tmockApp.TotalCoinsSupply = mockApp.TotalCoinsSupply.Add2(coins)\n\t}\n\n\treturn mockApp, addrKeysSlice\n}", "func (throttler *Throttler) RecentAppsMap() (result map[string](*base.RecentApp)) {\n\tresult = make(map[string](*base.RecentApp))\n\n\tfor recentAppKey, item := range throttler.recentApps.Items() {\n\t\trecentApp := base.NewRecentApp(item.Object.(time.Time))\n\t\tresult[recentAppKey] = recentApp\n\t}\n\treturn result\n}", "func LoadAppData(appData *common.ExtAppData) {\n\tlogWriter := os.Stdout\n\tlogger := log.NewLoggerWithPrefix(logWriter, \"extApp\").WithLevel(log.Level(4))\n\t//load txs\n\tbidCreate := common.ExtTx{\n\t\tTx: bid_action.CreateBidTx{},\n\t\tMsg: &bid_action.CreateBid{},\n\t}\n\tbidCancel := common.ExtTx{\n\t\tTx: bid_action.CancelBidTx{},\n\t\tMsg: &bid_action.CancelBid{},\n\t}\n\tbidExpire := common.ExtTx{\n\t\tTx: bid_action.ExpireBidTx{},\n\t\tMsg: &bid_action.ExpireBid{},\n\t}\n\tcounterOffer := common.ExtTx{\n\t\tTx: bid_action.CounterOfferTx{},\n\t\tMsg: &bid_action.CounterOffer{},\n\t}\n\tbidderDecision := common.ExtTx{\n\t\tTx: bid_action.BidderDecisionTx{},\n\t\tMsg: &bid_action.BidderDecision{},\n\t}\n\townerDecision := common.ExtTx{\n\t\tTx: bid_action.OwnerDecisionTx{},\n\t\tMsg: &bid_action.OwnerDecision{},\n\t}\n\tappData.ExtTxs = append(appData.ExtTxs, bidCreate)\n\tappData.ExtTxs = append(appData.ExtTxs, bidCancel)\n\tappData.ExtTxs = append(appData.ExtTxs, bidExpire)\n\tappData.ExtTxs = append(appData.ExtTxs, counterOffer)\n\tappData.ExtTxs = append(appData.ExtTxs, bidderDecision)\n\tappData.ExtTxs = append(appData.ExtTxs, ownerDecision)\n\n\t//load stores\n\tif dupName, ok := appData.ExtStores[\"extBidMaster\"]; ok {\n\t\tlogger.Errorf(\"Trying to register external store %s failed, same name already exists\", dupName)\n\t\treturn\n\t} else {\n\t\tappData.ExtStores[\"extBidMaster\"] = bid_data.NewBidMasterStore(appData.ChainState)\n\t}\n\n\t//load services\n\tbalances := balance.NewStore(\"b\", storage.NewState(appData.ChainState))\n\tdomains := ons.NewDomainStore(\"ons\", storage.NewState(appData.ChainState))\n\tolt := balance.Currency{Id: 0, Name: \"OLT\", Chain: chain.ONELEDGER, Decimal: 18, Unit: \"nue\"}\n\tcurrencies := balance.NewCurrencySet()\n\terr := currencies.Register(olt)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to register currency %s\", olt.Name, err)\n\t\treturn\n\t}\n\tappData.ExtServiceMap[bid_rpc_query.Name()] = bid_rpc_query.NewService(balances, currencies, domains, logger, bid_data.NewBidMasterStore(appData.ChainState))\n\tappData.ExtServiceMap[bid_rpc_tx.Name()] = bid_rpc_tx.NewService(balances, logger)\n\n\t//load beginner and ender functions\n\terr = appData.ExtBlockFuncs.Add(common.BlockBeginner, bid_block_func.AddExpireBidTxToQueue)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to load block beginner func\", err)\n\t\treturn\n\t}\n\terr = appData.ExtBlockFuncs.Add(common.BlockEnder, bid_block_func.PopExpireBidTxFromQueue)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to load block ender func\", err)\n\t\treturn\n\t}\n\n}", "func (m *OnlineMeetingInfo) GetTollFreeNumbers()([]string) {\n val, err := m.GetBackingStore().Get(\"tollFreeNumbers\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func get_order_app_data_per_app(action string, app_name string, inter string, app_data map[string]map[string]interface{}) (int, map[string]string){\n\torder := get_action_order(action, app_data[app_name][inter])\n\tstart, _ := app_data[app_name][\"Start\"].(string)\n\tstop, _ := app_data[app_name][\"Stop\"].(string)\n\tcheck, _ := app_data[app_name][\"Check\"].(string)\n\tdata := map[string]string{\"Start\" : start,\n\t\t\"Stop\" : stop,\n\t\t\"Check\" : check,\n\t\t\"Name\" : app_name,}\n\treturn order, data\n}", "func repinMap(bpffsPath string, name string, spec *ebpf.MapSpec) error {\n\tfile := filepath.Join(bpffsPath, name)\n\tpinned, err := ebpf.LoadPinnedMap(file, nil)\n\n\t// Given map was not pinned, nothing to do.\n\tif errors.Is(err, unix.ENOENT) {\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"map not found at path %s: %v\", name, err)\n\t}\n\n\tif pinned.Type() == spec.Type &&\n\t\tpinned.KeySize() == spec.KeySize &&\n\t\tpinned.ValueSize() == spec.ValueSize &&\n\t\tpinned.Flags() == spec.Flags &&\n\t\tpinned.MaxEntries() == spec.MaxEntries {\n\t\treturn nil\n\t}\n\n\tdest := file + bpffsPending\n\n\tlog.WithFields(logrus.Fields{\n\t\tlogfields.BPFMapName: name,\n\t\tlogfields.BPFMapPath: file,\n\t}).Infof(\"New version of map has different properties, re-pinning with '%s' suffix\", bpffsPending)\n\n\t// Atomically re-pin the map to the its new path.\n\tif err := pinned.Pin(dest); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *MacOSMinimumOperatingSystem) GetAdditionalData()(map[string]any) {\n val , err := m.backingStore.Get(\"additionalData\")\n if err != nil {\n panic(err)\n }\n if val == nil {\n var value = make(map[string]any);\n m.SetAdditionalData(value);\n }\n return val.(map[string]any)\n}", "func (m *DeviceEnrollmentWindowsHelloForBusinessConfiguration) SetPinPreviousBlockCount(value *int32)() {\n err := m.GetBackingStore().Set(\"pinPreviousBlockCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func checkAppAndACL(ctx *zedrouterContext, instData *networkAttrs) {\n\tpub := ctx.pubAppNetworkStatus\n\titems := pub.GetAll()\n\tfor _, st := range items {\n\t\tstatus := st.(types.AppNetworkStatus)\n\t\tappID := status.UUIDandVersion.UUID\n\t\tfor i, ulStatus := range status.UnderlayNetworkList {\n\t\t\tlog.Tracef(\"===FlowStats: (index %d) AppNum %d, VifInfo %v, IP addr %v, Hostname %s\\n\",\n\t\t\t\ti, status.AppNum, ulStatus.VifInfo, ulStatus.AllocatedIPAddr, ulStatus.HostName)\n\n\t\t\tulconfig := ulStatus.UnderlayNetworkConfig\n\t\t\t// build an App-IPaddress/intfs cache indexed by App-number\n\t\t\ttmpAppInfo := appInfo{\n\t\t\t\tipaddr: net.ParseIP(ulStatus.AllocatedIPAddr),\n\t\t\t\tintf: ulStatus.Name,\n\t\t\t\tlocalintf: ulStatus.Bridge,\n\t\t\t}\n\t\t\tnetstatus := lookupNetworkInstanceStatus(ctx, ulconfig.Network.String())\n\t\t\tif netstatus != nil {\n\t\t\t\tif netstatus.Type == types.NetworkInstanceTypeSwitch {\n\t\t\t\t\tif _, ok := netstatus.IPAssignments[ulStatus.Mac]; ok {\n\t\t\t\t\t\ttmpAppInfo.ipaddr = netstatus.IPAssignments[ulStatus.Mac]\n\t\t\t\t\t\tlog.Tracef(\"===FlowStats: switchnet, get ip %v\\n\", tmpAppInfo.ipaddr)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tinstData.appIPinfo[status.AppNum] = append(instData.appIPinfo[status.AppNum], tmpAppInfo)\n\n\t\t\t// Fill in the bnNet indexed by bridge-name, used for loop through bridges, and Scope\n\t\t\tintfAttr := bridgeAttr{\n\t\t\t\tbridge: ulStatus.Bridge,\n\t\t\t\tnetUUID: ulconfig.Network,\n\t\t\t}\n\t\t\tinstData.bnNet[ulStatus.Bridge] = intfAttr\n\n\t\t\t// build an App list cache, used for loop through all the Apps\n\t\t\tif instData.appNet[status.AppNum] == nilUUID {\n\t\t\t\tinstData.appNet[status.AppNum] = status.UUIDandVersion.UUID\n\t\t\t\tlog.Tracef(\"===FlowStats: appNet appNum %d, uuid %v\\n\", status.AppNum, instData.appNet[status.AppNum])\n\t\t\t}\n\n\t\t\t// build an acl cache indexed by app/aclnum, from flow MARK, we can get this aclAttr info\n\t\t\ttmpMap := instData.ipaclattr[status.AppNum]\n\t\t\tif tmpMap == nil {\n\t\t\t\ttmpMap := make(map[int]aclAttr)\n\t\t\t\tinstData.ipaclattr[status.AppNum] = tmpMap\n\t\t\t}\n\t\t\trules := getNetworkACLRules(ctx, appID, ulStatus.Name)\n\t\t\tfor _, rule := range rules.ACLRules {\n\t\t\t\tif (rule.IsUserConfigured == false || rule.IsMarkingRule == true) &&\n\t\t\t\t\trule.IsDefaultDrop == false {\n\t\t\t\t\t// only include user defined rules and default drop rules\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tvar tempAttr aclAttr\n\t\t\t\ttempAttr.aclNum = uint32(rule.RuleID)\n\t\t\t\ttempAttr.chainName = rule.ActionChainName\n\t\t\t\ttempAttr.aclName = rule.RuleName\n\t\t\t\ttempAttr.tableName = rule.Table\n\t\t\t\ttempAttr.bridge = ulStatus.Bridge\n\t\t\t\ttempAttr.intfname = ulStatus.Name\n\n\t\t\t\tif _, ok := instData.ipaclattr[status.AppNum][int(rule.RuleID)]; !ok { // fake j as the aclNUM\n\t\t\t\t\tinstData.ipaclattr[status.AppNum][int(rule.RuleID)] = tempAttr\n\t\t\t\t} else {\n\t\t\t\t\tpreAttr := instData.ipaclattr[status.AppNum][int(rule.RuleID)]\n\t\t\t\t\t// the the entry exist, and already has the aclNum and bridge name, skip\n\t\t\t\t\tif preAttr.aclNum == 0 || preAttr.bridge == \"\" {\n\t\t\t\t\t\tinstData.ipaclattr[status.AppNum][int(rule.RuleID)] = tempAttr\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (am *ArtifactMap) fillAppMap(appData *AppData, lookFor string) error {\n\tif appData == nil || appData.Data == nil {\n\t\treturn errors.New(\"empty AppData struct\")\n\t}\n\n\tif len(appData.Data) == 0 {\n\t\treturn nil\n\t}\n\n\tam.mu.Lock()\n\tdefer am.mu.Unlock()\n\tif am.AppList == nil {\n\t\tam.AppList = make([]*ArtifactEntry, 0, len(appData.Data))\n\t}\n\n\tfor _, i := range appData.Data {\n\t\t// This distinction is needed since QSCB and QCS list apps\n\t\t// slightly differently. The app Title is in a \"Title\" field\n\t\t// in QSCB, whereas it's in a \"name\" field in QCS.\n\t\tswitch lookFor {\n\t\tcase \"Title\":\n\t\t\tam.appTitleToID.Store(i.Title, i.ID)\n\t\t\tam.AppList = append(am.AppList, &ArtifactEntry{i.Title, i.ID, i.ItemID})\n\t\tcase \"name\":\n\t\t\tam.appTitleToID.Store(i.Name, i.ID)\n\t\t\tam.appTitleToItemID.Store(i.Name, i.ItemID)\n\t\t\tam.AppList = append(am.AppList, &ArtifactEntry{i.Name, i.ID, i.ItemID})\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"%s type not supported\", lookFor)\n\t\t}\n\t}\n\tsort.Sort(am.AppList)\n\treturn nil\n}", "func (r *ApplicationSetReconciler) buildAppSyncMap(ctx context.Context, applicationSet argov1alpha1.ApplicationSet, appDependencyList [][]string, appMap map[string]argov1alpha1.Application) (map[string]bool, error) {\n\tappSyncMap := map[string]bool{}\n\tsyncEnabled := true\n\n\t// healthy stages and the first non-healthy stage should have sync enabled\n\t// every stage after should have sync disabled\n\n\tfor i := range appDependencyList {\n\t\t// set the syncEnabled boolean for every Application in the current step\n\t\tfor _, appName := range appDependencyList[i] {\n\t\t\tappSyncMap[appName] = syncEnabled\n\t\t}\n\n\t\t// detect if we need to halt before progressing to the next step\n\t\tfor _, appName := range appDependencyList[i] {\n\n\t\t\tidx := findApplicationStatusIndex(applicationSet.Status.ApplicationStatus, appName)\n\t\t\tif idx == -1 {\n\t\t\t\t// no Application status found, likely because the Application is being newly created\n\t\t\t\tsyncEnabled = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tappStatus := applicationSet.Status.ApplicationStatus[idx]\n\n\t\t\tif app, ok := appMap[appName]; ok {\n\n\t\t\t\tsyncEnabled = appSyncEnabledForNextStep(&applicationSet, app, appStatus)\n\t\t\t\tif !syncEnabled {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// application name not found in the list of applications managed by this ApplicationSet, maybe because it's being deleted\n\t\t\t\tsyncEnabled = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn appSyncMap, nil\n}", "func process(ch <-chan AppInfo, wg *sync.WaitGroup,\n clients map[string]*memcache.Client, numErrors *uint64) {\n for {\n app := <-ch\n location := app.dev_type\n wrapper := app.app\n\n /* key to store */\n key := fmt.Sprintf(\"%s:%s\", location, app.dev_id)\n\n if app.dev_type == \"quit\" {\n wg.Done()\n return\n }\n\n /* Marshall UserApps instance to get value to store */\n if data, err := proto.Marshal(\n &apps.UserApps{Apps: wrapper.Apps, Lat: &wrapper.Lat, Lon: &wrapper.Lon});\n err == nil {\n if clients[location].Set(&memcache.Item{Key: key, Value: data}) != nil {\n atomic.AddUint64(numErrors, 1)\n }\n }\n }\n}", "func (m *MicrosoftStoreForBusinessApp) SetUsedLicenseCount(value *int32)() {\n err := m.GetBackingStore().Set(\"usedLicenseCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *Calculator) loadPRepInfo() (map[string]*pRepEnable, error) {\n\tprepInfo := make(map[string]*pRepEnable)\n\tfor iter := c.base.Filter(icreward.VotedKey.Build()); iter.Has(); iter.Next() {\n\t\to, key, err := iter.Get()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkeySplit, err := containerdb.SplitKeys(key)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\taddr, err := common.NewAddress(keySplit[1])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tobj := icreward.ToVoted(o)\n\t\tif obj.Enable() == false {\n\t\t\t// do not collect disabled P-Rep\n\t\t\tcontinue\n\t\t}\n\t\tprepInfo[string(addr.Bytes())] = new(pRepEnable)\n\t}\n\n\treturn prepInfo, nil\n}", "func startApp(appName string) {\n\tassignRoles()\n\tCache = make(map[int]interface{}) //truncate the cache\n\tAcker = make(map[int]*Ack) //truncate the Acker cache\n\tStopApp = false\n\tcurrAppName = appName\n\tif appName == \"wordCount\" {\n\t\tcurrApp = &wordCount{\n\t\t\tresult: map[string]int{},\n\t\t\tmessageId: 0,\n\t\t\tackVal: 0,\n\t\t}\n\t}\n}", "func (m *OnlineMeetingInfo) SetTollFreeNumbers(value []string)() {\n err := m.GetBackingStore().Set(\"tollFreeNumbers\", value)\n if err != nil {\n panic(err)\n }\n}", "func GetSnapshot() (k, Lk, Xk, Mk, Kk *big.Int, err error) {\n\turl := \"https://nalusi-b235sdkoha-de.a.run.app/nalupi?spreadsheetID=1FMUFV2z_MaccKswNLh3-x2vDeBY3RRNNzzAusjh848c&a1Range=Data!A:E\"\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, nil, err\n\t}\n\tvar respBody [][]string\n\tbody, err := ioutil.ReadAll(response.Body)\n\terr = json.Unmarshal(body, &respBody)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, nil, err\n\t}\n\tvar ok bool\n\tk, ok = big.NewInt(0).SetString(respBody[1][0], 10)\n\tif !ok {\n\t\treturn nil, nil, nil, nil, nil, errors.New(\"Unable to convert string to big.Int\")\n\t}\n\tLk, ok = big.NewInt(0).SetString(respBody[1][1], 10)\n\tif !ok {\n\t\treturn nil, nil, nil, nil, nil, errors.New(\"Unable to convert string to big.Int\")\n\t}\n\tXk, ok = big.NewInt(0).SetString(respBody[1][2], 10)\n\tif !ok {\n\t\treturn nil, nil, nil, nil, nil, errors.New(\"Unable to convert string to big.Int\")\n\t}\n\tMk, ok = big.NewInt(0).SetString(respBody[1][3], 10)\n\tif !ok {\n\t\treturn nil, nil, nil, nil, nil, errors.New(\"Unable to convert string to big.Int\")\n\t}\n\tKk, ok = big.NewInt(0).SetString(respBody[1][4], 10)\n\tif !ok {\n\t\treturn nil, nil, nil, nil, nil, errors.New(\"Unable to convert string to big.Int\")\n\t}\n\treturn k, Lk, Xk, Mk, Kk, nil\n}", "func appNumOnUNetBaseDelete(ctx *zedrouterContext, baseID uuid.UUID) {\n\tappNumMap := appNumOnUNetBaseGet(baseID)\n\tif appNumMap == nil {\n\t\tlog.Fatalf(\"appNumOnUNetBaseDelete: non-existent\")\n\t}\n\t// check whether there are still some apps on\n\t// this network\n\tpub := ctx.pubUUIDPairAndIfIdxToNum\n\tnumType := appNumOnUNetType\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.BaseID == baseID {\n\t\t\tlog.Fatalf(\"appNumOnUNetBaseDelete(%s): remaining: %v\",\n\t\t\t\tbaseID, appNumMap)\n\t\t}\n\t}\n\tlog.Functionf(\"appNumOnUNetBaseDelete (%s)\", baseID.String())\n\tdelete(appNumBase, baseID.String())\n}", "func (counter *Counters) OpenedApps() uint64 {\n\treturn counter.totOpenedApps.Current()\n}", "func (m *ServiceMgr) savePrimaryStore(app *application) (info *runtimeInfo) {\n\tlogPrefix := \"ServiceMgr::savePrimaryStore\"\n\n\tinfo = &runtimeInfo{}\n\tlogging.Infof(\"%s Function: %s saving to primary store\", logPrefix, app.Name)\n\n\tif lifeCycleOpsInfo := m.checkLifeCycleOpsDuringRebalance(); lifeCycleOpsInfo.Code != m.statusCodes.ok.Code {\n\t\tinfo.Code = lifeCycleOpsInfo.Code\n\t\tinfo.Info = lifeCycleOpsInfo.Info\n\t\treturn\n\t}\n\n\tif m.checkIfDeployed(app.Name) && m.superSup.GetAppState(app.Name) != common.AppStatePaused {\n\t\tinfo.Code = m.statusCodes.errAppDeployed.Code\n\t\tinfo.Info = fmt.Sprintf(\"Function: %s another function with same name is already deployed, skipping save request\", app.Name)\n\t\tlogging.Errorf(\"%s %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\n\tif app.DeploymentConfig.SourceBucket == app.DeploymentConfig.MetadataBucket {\n\t\tinfo.Code = m.statusCodes.errSrcMbSame.Code\n\t\tinfo.Info = fmt.Sprintf(\"Function: %s source bucket same as metadata bucket. source_bucket : %s metadata_bucket : %s\",\n\t\t\tapp.Name, app.DeploymentConfig.SourceBucket, app.DeploymentConfig.MetadataBucket)\n\t\tlogging.Errorf(\"%s %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\n\tmhVersion := eventingVerMap[\"mad-hatter\"]\n\tif filterFeedBoundary(app.Settings) == common.DcpFromPrior && !m.compareEventingVersion(mhVersion) {\n\t\tinfo.Code = m.statusCodes.errClusterVersion.Code\n\t\tinfo.Info = fmt.Sprintf(\"All eventing nodes in the cluster must be on version %d.%d or higher for using 'from prior' deployment feed boundary\",\n\t\t\tmhVersion.major, mhVersion.minor)\n\t\tlogging.Warnf(\"%s Version compat check failed: %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\n\tif filterFeedBoundary(app.Settings) == common.DcpFromPrior && m.superSup.GetAppState(app.Name) != common.AppStatePaused {\n\t\tinfo.Code = m.statusCodes.errInvalidConfig.Code\n\t\tinfo.Info = fmt.Sprintf(\"Function: %s feed boundary: from_prior is only allowed if function is in paused state\", app.Name)\n\n\t\tlogging.Errorf(\"%s %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\n\tif m.superSup.GetAppState(app.Name) == common.AppStatePaused {\n\t\tswitch filterFeedBoundary(app.Settings) {\n\t\tcase common.DcpFromNow, common.DcpEverything:\n\t\t\tinfo.Code = m.statusCodes.errInvalidConfig.Code\n\t\t\tinfo.Info = fmt.Sprintf(\"Function: %s only from_prior feed boundary is allowed during resume\", app.Name)\n\t\t\tlogging.Errorf(\"%s %s\", logPrefix, info.Info)\n\t\t\treturn\n\t\tcase common.DcpStreamBoundary(\"\"):\n\t\t\tapp.Settings[\"dcp_stream_boundary\"] = \"from_prior\"\n\t\tdefault:\n\t\t}\n\t}\n\n\tapp.SrcMutationEnabled = m.isSrcMutationEnabled(&app.DeploymentConfig)\n\tif app.SrcMutationEnabled && !m.compareEventingVersion(mhVersion) {\n\t\tinfo.Code = m.statusCodes.errClusterVersion.Code\n\t\tinfo.Info = fmt.Sprintf(\"All eventing nodes in the cluster must be on version %d.%d or higher for allowing mutations against source bucket\",\n\t\t\tmhVersion.major, mhVersion.minor)\n\t\tlogging.Warnf(\"%s Version compat check failed: %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\n\tif app.SrcMutationEnabled {\n\t\tif enabled, err := util.IsSyncGatewayEnabled(logPrefix, app.DeploymentConfig.SourceBucket, m.restPort); err == nil && enabled {\n\t\t\tinfo.Code = m.statusCodes.errSyncGatewayEnabled.Code\n\t\t\tinfo.Info = fmt.Sprintf(\"SyncGateway is enabled on: %s, deployement of source bucket mutating handler will cause Intra Bucket Recursion\", app.DeploymentConfig.SourceBucket)\n\t\t\treturn\n\t\t}\n\t}\n\n\tlogging.Infof(\"%v Function UUID: %v for function name: %v stored in primary store\", logPrefix, app.FunctionID, app.Name)\n\n\tappContent := m.encodeAppPayload(app)\n\n\tcompressPayload := m.checkCompressHandler()\n\tpayload, err := util.MaybeCompress(appContent, compressPayload)\n\tif err != nil {\n\t\tinfo.Code = m.statusCodes.errSaveAppPs.Code\n\t\tinfo.Info = fmt.Sprintf(\"Function: %s Error in compressing: %v\", app.Name, err)\n\t\tlogging.Errorf(\"%s %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\tif len(payload) > util.MaxFunctionSize() {\n\t\tinfo.Code = m.statusCodes.errAppCodeSize.Code\n\t\tinfo.Info = fmt.Sprintf(\"Function: %s handler Code size is more than %d. Code Size: %d\", app.Name, util.MaxFunctionSize(), len(payload))\n\t\tlogging.Errorf(\"%s %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\n\tc := &consumer.Consumer{}\n\tvar handlerHeaders []string\n\tif headers, exists := app.Settings[\"handler_headers\"]; exists {\n\t\thandlerHeaders = util.ToStringArray(headers)\n\t} else {\n\t\thandlerHeaders = common.GetDefaultHandlerHeaders()\n\t}\n\n\tvar n1qlParams string\n\tif consistency, exists := app.Settings[\"n1ql_consistency\"]; exists {\n\t\tn1qlParams = \"{ 'consistency': '\" + consistency.(string) + \"' }\"\n\t}\n\tparsedCode, _ := parser.TranspileQueries(app.AppHandlers, n1qlParams)\n\n\thandlerFooters := util.ToStringArray(app.Settings[\"handler_footers\"])\n\tcompilationInfo, err := c.SpawnCompilationWorker(parsedCode, string(appContent), app.Name, m.adminHTTPPort,\n\t\thandlerHeaders, handlerFooters)\n\tif err != nil || !compilationInfo.CompileSuccess {\n\t\tinfo.Code = m.statusCodes.errHandlerCompile.Code\n\t\tinfo.Info = compilationInfo\n\t\treturn\n\t}\n\n\tusingTimer := parser.UsingTimer(parsedCode)\n\tapp.Settings[\"using_timer\"] = usingTimer\n\tapp.UsingTimer = usingTimer\n\n\tlogging.Infof(\"%s Function: %s using_timer: %s\", logPrefix, app.Name, usingTimer)\n\n\tappContent = m.encodeAppPayload(app)\n\tsettingsPath := metakvAppSettingsPath + app.Name\n\tsettings := app.Settings\n\n\tmData, mErr := json.MarshalIndent(&settings, \"\", \" \")\n\tif mErr != nil {\n\t\tinfo.Code = m.statusCodes.errMarshalResp.Code\n\t\tinfo.Info = fmt.Sprintf(\"Function: %s failed to marshal settings, err: %v\", app.Name, mErr)\n\t\tlogging.Errorf(\"%s %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\n\tmkvErr := util.MetakvSet(settingsPath, mData, nil)\n\tif mkvErr != nil {\n\t\tinfo.Code = m.statusCodes.errSetSettingsPs.Code\n\t\tinfo.Info = fmt.Sprintf(\"Function: %s failed to store updated settings in metakv, err: %v\", app.Name, mkvErr)\n\t\tlogging.Errorf(\"%s %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\n\t//Delete stale entry\n\terr = util.DeleteStaleAppContent(metakvAppsPath, app.Name)\n\tif err != nil {\n\t\tinfo.Code = m.statusCodes.errSaveAppPs.Code\n\t\tinfo.Info = fmt.Sprintf(\"Function: %s failed to clean up stale entry, err: %v\", app.Name, err)\n\t\tlogging.Errorf(\"%s %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\n\terr = util.WriteAppContent(metakvAppsPath, metakvChecksumPath, app.Name, appContent, compressPayload)\n\tif err != nil {\n\t\tinfo.Code = m.statusCodes.errSaveAppPs.Code\n\t\tlogging.Errorf(\"%s Function: %s unable to save to primary store, err: %v\", logPrefix, app.Name, err)\n\t\treturn\n\t}\n\n\twInfo, err := m.determineWarnings(app, compilationInfo)\n\tif err != nil {\n\t\tinfo.Code = m.statusCodes.errGetConfig.Code\n\t\tinfo.Info = fmt.Sprintf(\"Function: %s failed to determine warnings, err : %v\", app.Name, err)\n\t\treturn\n\t}\n\n\tinfo.Code = m.statusCodes.ok.Code\n\tinfo.Info = *wInfo\n\treturn\n}", "func (m *MicrosoftStoreForBusinessApp) GetUsedLicenseCount()(*int32) {\n val, err := m.GetBackingStore().Get(\"usedLicenseCount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func (r *RepoStruct) SetInternalRelApp(appRelName, appName string) (updated *bool, _ error) {\n\tif err := r.initApp(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif v, found := r.Apps[appRelName]; found {\n\t\tappName = v // Set always declared one.\n\t}\n\n\tif app, err := r.forge.ForjCore.Apps.Found(appName); err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to set %s:%s. %s.\", appRelName, appName, err)\n\t} else if v, found := r.apps[appRelName]; !found || (found && v.name != appName) {\n\t\tr.apps[appRelName] = app\n\t\tupdated = new(bool)\n\t\t*updated = true\n\t}\n\n\treturn\n}", "func (throttler *Throttler) throttledAppsSnapshot() map[string]cache.Item {\n\treturn throttler.throttledApps.Items()\n}", "func MapBitmapToIndices(bitmap []byte) []int64 {\n\tif len(bitmap) == 0 {\n\t\treturn []int64{}\n\t}\n\n\toutput := make([]int64, len(bitmap)*8)\n\tcount := 0\n\n\tfor i, byte_at := range bitmap {\n\t\t// Skip empty bytes\n\t\tif byte_at == 0x00 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// All the bits are on!\n\t\tif byte_at == 0xFF {\n\t\t\ti_8 := int64(i * 8)\n\t\t\tj := 0\n\n\t\t\t// 0\n\t\t\toutput[count+j] = i_8 + int64(j)\n\t\t\tj++\n\n\t\t\t// 1\n\t\t\toutput[count+j] = i_8 + int64(j)\n\t\t\tj++\n\n\t\t\t// 2\n\t\t\toutput[count+j] = i_8 + int64(j)\n\t\t\tj++\n\n\t\t\t// 3\n\t\t\toutput[count+j] = i_8 + int64(j)\n\t\t\tj++\n\n\t\t\t// 4\n\t\t\toutput[count+j] = i_8 + int64(j)\n\t\t\tj++\n\n\t\t\t// 5\n\t\t\toutput[count+j] = i_8 + int64(j)\n\t\t\tj++\n\n\t\t\t// 6\n\t\t\toutput[count+j] = i_8 + int64(j)\n\t\t\tj++\n\n\t\t\t// 7\n\t\t\toutput[count+j] = i_8 + int64(j)\n\t\t\tj++\n\n\t\t\tcount += j\n\t\t\tcontinue\n\t\t}\n\n\t\t// Perform BitShift operations and figure out which bits are on\n\t\tfor j := 0; j < 8; j++ {\n\t\t\t//\n\t\t\t// WARNING!! We are counting from Left --> Right here!\n\t\t\t//\n\t\t\tmask := byte(1) << uint(7-j)\n\n\t\t\tposition := i*8 + j\n\n\t\t\tif mask&(byte_at) != 0 {\n\t\t\t\toutput[count] = int64(position)\n\t\t\t\tcount++\n\t\t\t} else {\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the slice of live ids\n\treturn output[0:count]\n}", "func newMemPCApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseApp)) *memoryPCApp {\n\tapp := newMemoryPCBaseApp(logger, db, baseAppOptions...)\n\t// setup subspaces\n\tauthSubspace := sdk.NewSubspace(auth.DefaultParamspace)\n\tnodesSubspace := sdk.NewSubspace(nodesTypes.DefaultParamspace)\n\tappsSubspace := sdk.NewSubspace(appsTypes.DefaultParamspace)\n\tpocketSubspace := sdk.NewSubspace(pocketTypes.DefaultParamspace)\n\t// The AuthKeeper handles address -> account lookups\n\tapp.accountKeeper = auth.NewKeeper(\n\t\tapp.cdc,\n\t\tapp.keys[auth.StoreKey],\n\t\tauthSubspace,\n\t\tmoduleAccountPermissions,\n\t)\n\t// The nodesKeeper keeper handles pocket core nodes\n\tapp.nodesKeeper = nodesKeeper.NewKeeper(\n\t\tapp.cdc,\n\t\tapp.keys[nodesTypes.StoreKey],\n\t\tapp.accountKeeper,\n\t\tnodesSubspace,\n\t\tnodesTypes.DefaultCodespace,\n\t)\n\t// The apps keeper handles pocket core applications\n\tapp.appsKeeper = appsKeeper.NewKeeper(\n\t\tapp.cdc,\n\t\tapp.keys[appsTypes.StoreKey],\n\t\tapp.nodesKeeper,\n\t\tapp.accountKeeper,\n\t\tappsSubspace,\n\t\tappsTypes.DefaultCodespace,\n\t)\n\t// The main pocket core\n\tapp.pocketKeeper = pocketKeeper.NewPocketCoreKeeper(\n\t\tapp.keys[pocketTypes.StoreKey],\n\t\tapp.cdc,\n\t\tapp.nodesKeeper,\n\t\tapp.appsKeeper,\n\t\tgetInMemHostedChains(),\n\t\tpocketSubspace,\n\t)\n\t// The governance keeper\n\tapp.govKeeper = govKeeper.NewKeeper(\n\t\tapp.cdc,\n\t\tapp.keys[pocketTypes.StoreKey],\n\t\tapp.tkeys[pocketTypes.StoreKey],\n\t\tgovTypes.DefaultCodespace,\n\t\tapp.accountKeeper,\n\t\tauthSubspace, nodesSubspace, appsSubspace, pocketSubspace,\n\t)\n\tapp.pocketKeeper.Keybase = getInMemoryKeybase()\n\tapp.pocketKeeper.TmNode = getInMemoryTMClient()\n\tapp.mm = module.NewManager(\n\t\tauth.NewAppModule(app.accountKeeper),\n\t\tnodes.NewAppModule(app.nodesKeeper),\n\t\tapps.NewAppModule(app.appsKeeper),\n\t\tpocket.NewAppModule(app.pocketKeeper),\n\t\tgov.NewAppModule(app.govKeeper),\n\t)\n\tapp.mm.SetOrderBeginBlockers(nodesTypes.ModuleName, appsTypes.ModuleName, pocketTypes.ModuleName)\n\tapp.mm.SetOrderEndBlockers(nodesTypes.ModuleName, appsTypes.ModuleName)\n\tapp.mm.SetOrderInitGenesis(\n\t\tnodesTypes.ModuleName,\n\t\tappsTypes.ModuleName,\n\t\tpocketTypes.ModuleName,\n\t\tauth.ModuleName,\n\t\tgov.ModuleName,\n\t)\n\tapp.mm.RegisterRoutes(app.Router(), app.QueryRouter())\n\tapp.SetInitChainer(app.InitChainer)\n\tapp.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper))\n\tapp.SetBeginBlocker(app.BeginBlocker)\n\tapp.SetEndBlocker(app.EndBlocker)\n\tapp.MountKVStores(app.keys)\n\tapp.MountTransientStores(app.tkeys)\n\terr := app.LoadLatestVersion(app.keys[bam.MainStoreKey])\n\tif err != nil {\n\t\tcmn.Exit(err.Error())\n\t}\n\treturn app\n}", "func resMemoIn(n int) int {\n\thash := make(map[int]int)\n\treturn resMemo(n, hash)\n}", "func (this *AppCollection) load(item *storage.AppItem) error {\n this.apps[item.Name()] = NewApp(AppInfo{name: item.Name(), protocol: item.Protocol(), address: item.Address()})\n return nil\n}", "func (app *ArteryApp) ExportAppStateAndValidators(\n\tforZeroHeight bool, jailWhiteList []string,\n) (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) {\n\n\t// as if they could withdraw from the start of the next block\n\tctx := app.NewContext(true, abci.Header{Height: app.LastBlockHeight()})\n\n\tif forZeroHeight {\n\t\tapp.prepForZeroHeightGenesis(ctx, jailWhiteList)\n\t}\n\n\tgenState := app.mm.ExportGenesis(ctx)\n\tappState, err = codec.MarshalJSONIndent(app.cdc, genState)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// We should never have genesis validators per se.\n\t// All validators should be added via noding module instead.\n\treturn appState, nil, nil\n}", "func initInteralMap() error {\n\n\t//Get all unfinished scans from the database\n\tquery := bson.M{\"status\":false}\n\tsearchResult , err := db.SearchEntries(query,0,-1)\n\tif err != nil {\n\t\tlog.Log(SCANNER_NAME , fmt.Sprintf(\" We received an error during Getting all unfinished Scans from the database : %v\",err))\n\t\treturn err\n\t}\n\t//if there are unfinished scans in the database , loop over them and insert them one by one into the map\n\t//and add them into the channel\n\tif len(searchResult) > 0 {\n\t\tfor _ , currentScan := range searchResult {\n\t\t\t//Append the current unfinished scan into the database\n\t\t\t//set progress to zero\n\t\t\tcurrentScan.Progress = 0\n\t\t\tappendNewScan(&currentScan,false)\n\t\t\taddScanToChannel(&currentScan)\n\n\t\t}\n\t}\n\treturn nil\n}", "func (am *AppManager) GetAppData(appGUID string) AppInfo {\n\t//logger.Printf(\"Searching for %s\\n\", appGUID)\n\treq := readRequest{appGUID, make(chan AppInfo)}\n\tam.readChannel <- req\n\tai := <-req.responseChan\n\t//logger.Printf(\"Recevied response for %s: %+v\", appGUID, ai)\n\treturn ai\n}", "func (counter *Counters) CreatedApps() uint64 {\n\treturn counter.totCreatedApps.Current()\n}", "func BenchmarkIntMapAppend(b *testing.B) {\n\tmmap := make(map[int]int)\n\n\tfor n := 0; n < b.N; n++ {\n\t\tmmap[n] = n\n\t}\n\n}", "func pinApps(ctx context.Context, tconn *chrome.TestConn, apps []apps.App, container *nodewith.Finder) error {\n\tprevLocations, err := buttonLocations(ctx, tconn)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot get location for buttons\")\n\t}\n\tfor _, app := range apps {\n\t\tif err := launcher.PinAppToShelf(tconn, app, container)(ctx); err != nil {\n\t\t\treturn errors.Wrapf(err, \"fail to pin app %q to shelf\", app.Name)\n\t\t}\n\n\t\t// Verify that pinned Application appears on the Shelf.\n\t\tui := uiauto.New(tconn)\n\t\tfinder := nodewith.Name(app.Name).ClassName(shelfAppButton)\n\t\tif err := ui.WithTimeout(10 * time.Second).WaitUntilExists(finder)(ctx); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to find app %v on shelf\", app.Name)\n\t\t}\n\n\t\tif err := ui.WaitForLocation(finder)(ctx); err != nil {\n\t\t\terrors.Wrap(err, \"failed to wait for location changes\")\n\t\t}\n\n\t\t// Verify that existing pinned apps go to the left after a new app is pinned.\n\t\tif err := buttonsShiftLeft(ctx, tconn, prevLocations); err != nil {\n\t\t\treturn errors.Wrap(err, \"buttons were not left shifted after pinning new applications\")\n\t\t}\n\t\tprevLocations, err = buttonLocations(ctx, tconn)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"cannot get location for buttons\")\n\t\t}\n\t}\n\treturn nil\n}", "func (p* ScreenManager)ChangeProg(forward bool){\r\n if(len(p.RunningApps)<2){//Impossibru!!! -_-\r\n fmt.Printf(\"ERROR: Only one or zero progs running\\n\")\r\n return\r\n }\r\n names,index:=p.ProgNameList()\r\n //Deattach current prog\r\n if(index>-1){\r\n if(forward){\r\n p.ActiveApp=names[(index+1)%len(p.RunningApps)]\r\n }else{\r\n p.RunningApps[p.ActiveApp].Display=make(chan gomonochromebitmap.MonoBitmap,1) //Make active app writing to another chan TODO copy here when chancing\r\n if(index>0){\r\n p.ActiveApp=names[index-1]\r\n }else{\r\n p.ActiveApp=names[len(p.RunningApps)-1]\r\n }\r\n }\r\n }else{\r\n p.ActiveApp=names[0]\r\n }\r\n fmt.Printf(\"\\n\\n!!!!! ACTIVE APP IS NOW %v !!!!!\\n\",p.ActiveApp)\r\n}", "func (s *segmentSnapshot) DocNumbersLive() *roaring.Bitmap {\n\trv := roaring.NewBitmap()\n\trv.AddRange(0, s.segment.Count())\n\tif s.deleted != nil {\n\t\trv.AndNot(s.deleted)\n\t}\n\treturn rv\n}", "func (m *MicrosoftManagedDesktop) GetAdditionalData()(map[string]any) {\n val , err := m.backingStore.Get(\"additionalData\")\n if err != nil {\n panic(err)\n }\n if val == nil {\n var value = make(map[string]any);\n m.SetAdditionalData(value);\n }\n return val.(map[string]any)\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 storeSerialNumber(app *AppContext) error {\n\tlog.Debugf(\"Storing serial number: %d\", app.serialNumber)\n\terr := app.burnerLogDB.Update(func(tx *bolt.Tx) error {\n\t\terr := tx.Bucket([]byte(\"serial\")).Put([]byte(\"serial\"), []byte(strconv.Itoa(app.serialNumber)))\n\t\treturn errors.Wrap(err, \"storeSerialNumber:Put\")\n\t})\n\treturn errors.Wrap(err, \"storeSerialNumber:Update\")\n}", "func (m *Office365ServicesUserCounts) GetOffice365Inactive()(*int64) {\n val, err := m.GetBackingStore().Get(\"office365Inactive\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int64)\n }\n return nil\n}", "func (s *Service) itemNum(plat int8) int {\n\t// cnt is items number\n\tcnt := 6\n\tif plat == model.PlatAndroid || plat == model.PlatAndroidI || plat == model.PlatAndroidG {\n\t\tcnt = 4\n\t} else if plat == model.PlatIPad || plat == model.PlatIPadI {\n\t\tcnt = 8\n\t} else if plat == model.PlatAndroidTV {\n\t\tcnt = 16\n\t}\n\treturn cnt\n}", "func (m *DeviceManagementApplicabilityRuleOsEdition) GetAdditionalData()(map[string]any) {\n val , err := m.backingStore.Get(\"additionalData\")\n if err != nil {\n panic(err)\n }\n if val == nil {\n var value = make(map[string]any);\n m.SetAdditionalData(value);\n }\n return val.(map[string]any)\n}", "func (m *DeviceHealthAttestationState) GetRestartCount()(*int64) {\n val, err := m.GetBackingStore().Get(\"restartCount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int64)\n }\n return nil\n}", "func (counter *Counters) IncCreatedApps() {\n\tcounter.totCreatedApps.Inc()\n}", "func (docOffset projectorOffset) updateInprog(projectorBit int32) bson.M {\n\treturn bson.M{\n\t\t\"$bit\": bson.M{\"inProg\": bson.M{\"or\": projectorBit}},\n\t}\n}", "func (h *DevicePluginHandlerImpl) readCheckpoint() error {\n\tfilepath := h.devicePluginManager.CheckpointFile()\n\tcontent, err := ioutil.ReadFile(filepath)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"failed to read checkpoint file %q: %v\", filepath, err)\n\t}\n\tglog.V(2).Infof(\"Read checkpoint file %s\\n\", filepath)\n\tvar data checkpointData\n\tif err := json.Unmarshal(content, &data); err != nil {\n\t\treturn fmt.Errorf(\"failed to unmarshal checkpoint data: %v\", err)\n\t}\n\tfor _, entry := range data.Entries {\n\t\tglog.V(2).Infof(\"Get checkpoint entry: %v %v %v %v\\n\", entry.PodUID, entry.ContainerName, entry.ResourceName, entry.DeviceID)\n\t\tif h.allocatedDevices[entry.ResourceName] == nil {\n\t\t\th.allocatedDevices[entry.ResourceName] = make(podDevices)\n\t\t}\n\t\th.allocatedDevices[entry.ResourceName].insert(entry.PodUID, entry.ContainerName, entry.DeviceID)\n\t}\n\treturn nil\n}", "func initData() {\n\tallMap = make(map[string]int64, 0)\n\terrMap = make(map[string]int64, 0)\n}", "func readModulesFromBundle() *map[string][]byte {\n\tbundleFile, err := os.Open(bundlePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer bundleFile.Close()\n\n\tmodules := map[string][]byte{}\n\n\tmagicNumber := readFile(bundleFile, 0)\n\tcheckMagicNumber(magicNumber)\n\n\tentryCount := readFile(bundleFile, UINT32_LENGTH)\n\tstartupCountLength := int(readFile(bundleFile, UINT32_LENGTH*2))\n\n\tentries := map[int]entry{}\n\n\tentryTableStart := UINT32_LENGTH * 3\n\tposition := entryTableStart\n\n\tfor entryId := 0; entryId < int(entryCount); entryId++ {\n\t\tentry := entry{\n\t\t\toffset: int(readFile(bundleFile, position)),\n\t\t\tlength: int(readFile(bundleFile, position+UINT32_LENGTH)),\n\t\t}\n\n\t\tentries[entryId] = entry\n\t\tposition += UINT32_LENGTH * 2\n\t}\n\n\tmoduleStart := position\n\n\tfor index, entry := range entries {\n\t\tstart := moduleStart + entry.offset\n\n\t\tmoduleData := readFileAtOffset(bundleFile, start, entry.length)\n\t\tif len(moduleData) > 0 {\n\t\t\tmoduleData = moduleData[:len(moduleData)-1]\n\t\t}\n\n\t\tmodules[strconv.Itoa(index)] = moduleData\n\t}\n\n\tstartupSize := (moduleStart + startupCountLength - 1) - moduleStart\n\tmodules[\"startup\"] = readFileAtOffset(bundleFile, moduleStart, startupSize)\n\n\treturn &modules\n}", "func (cer *CER) Applications() []uint32 {\n\treturn cer.appID\n}", "func (m *AppVulnerabilityTask) GetMobileApps()([]AppVulnerabilityMobileAppable) {\n val, err := m.GetBackingStore().Get(\"mobileApps\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]AppVulnerabilityMobileAppable)\n }\n return nil\n}", "func (c *Client) initRefNum() {\n\tringCounter := ring.New(maxRefNum)\n\tfor i := 0; i < maxRefNum; i++ {\n\t\tringCounter.Value = []byte(fmt.Sprintf(\"%02d\", i))\n\t\tringCounter = ringCounter.Next()\n\t}\n\tc.ringCounter = ringCounter\n}", "func (m *DeviceCompliancePolicySettingStateSummary) GetNotApplicableDeviceCount()(*int32) {\n val, err := m.GetBackingStore().Get(\"notApplicableDeviceCount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func (b *profileBuilder) readMapping() {\n\tdata, _ := os.ReadFile(\"/proc/self/maps\")\n\tparseProcSelfMaps(data, b.addMapping)\n\tif len(b.mem) == 0 { // pprof expects a map entry, so fake one.\n\t\tb.addMappingEntry(0, 0, 0, \"\", \"\", true)\n\t\t// TODO(hyangah): make addMapping return *memMap or\n\t\t// take a memMap struct, and get rid of addMappingEntry\n\t\t// that takes a bunch of positional arguments.\n\t}\n}", "func (am *ArtifactMap) EmptyApps() {\n\tam.mu.Lock()\n\tdefer am.mu.Unlock()\n\n\tam.appTitleToID = &sync.Map{}\n\tam.appTitleToItemID = &sync.Map{}\n\tam.AppList = nil\n}", "func (m *Office365ServicesUserCounts) GetOffice365Active()(*int64) {\n val, err := m.GetBackingStore().Get(\"office365Active\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int64)\n }\n return nil\n}", "func (m *Office365ServicesUserCounts) GetOneDriveInactive()(*int64) {\n val, err := m.GetBackingStore().Get(\"oneDriveInactive\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int64)\n }\n return nil\n}", "func readVolumeBitMap(devicebytes []byte, startBlock uint16) (VolumeBitMap, error) {\n\tblocks := uint16(len(devicebytes) / 512 / 4096)\n\tvbm := NewVolumeBitMap(startBlock, blocks)\n\tfor i := 0; i < len(vbm); i++ {\n\t\tif err := disk.UnmarshalBlock(devicebytes, &vbm[i], vbm[i].GetBlock()); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot read block %d (device block %d) of Volume Bit Map: %v\", i, vbm[i].GetBlock(), err)\n\t\t}\n\t}\n\treturn vbm, nil\n}", "func populateMap(m map[int]string, nameMap map[string]intBool, file string) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\tbufr := bufio.NewReader(f)\n\tfor {\n\t\tline, err := bufr.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tparts := strings.SplitN(line, \":\", 4)\n\t\tif len(parts) >= 3 {\n\t\t\tidstr := parts[2]\n\t\t\tid, err := strconv.Atoi(idstr)\n\t\t\tif err == nil {\n\t\t\t\tm[id] = parts[0]\n\t\t\t\tif nameMap != nil {\n\t\t\t\t\tnameMap[parts[0]] = intBool{id, true}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *AndroidManagedStoreApp) SetTotalLicenseCount(value *int32)() {\n err := m.GetBackingStore().Set(\"totalLicenseCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m Memo) AppIndex() uint16 {\n\ta := uint16(m[1]) >> 2\n\tb := uint16(m[2]) << 6\n\tc := uint16(m[3]) & 0x3 << 14\n\treturn a | b | c\n}", "func (u data) findPendingApplication(email string) (application Application, err error) {\n\trecord := u.db.Preload(\"ChangeHistory\", func(db *gorm.DB) *gorm.DB {\n\t\treturn db.Order(\"change_history.id ASC\")\n\t}).Preload(\"ChangeHistory.Nodes\").Preload(\"ChangeHistory.Images\").Where(\"username = ? and current_status = 0\", NormalizeMail(email)).Find(&application)\n\tif record.RecordNotFound() {\n\t\terr = errCannotFindPendingApp\n\t\treturn\n\t}\n\tif errs := record.GetErrors(); len(errs) > 0 {\n\t\tfor err := range errs {\n\t\t\tlog.Errorf(\"Error occurred while fetching pending application by user email %v - %v\", email, err)\n\t\t}\n\t\terr = errUnableToRead\n\t\treturn\n\t}\n\n\treturn\n}", "func onebitwritesymbol(arr []Bvec, sym *Sym) {\n\tvar i int\n\tvar j int\n\tvar word uint32\n\n\tn := len(arr)\n\toff := 0\n\toff += 4 // number of bitmaps, to fill in later\n\tbv := arr[0]\n\toff = duint32(sym, off, uint32(bv.n)) // number of bits in each bitmap\n\tfor i = 0; i < n; i++ {\n\t\t// bitmap words\n\t\tbv = arr[i]\n\n\t\tif bv.b == nil {\n\t\t\tbreak\n\t\t}\n\t\tfor j = 0; int32(j) < bv.n; j += 32 {\n\t\t\tword = bv.b[j/32]\n\n\t\t\t// Runtime reads the bitmaps as byte arrays. Oblige.\n\t\t\toff = duint8(sym, off, uint8(word))\n\n\t\t\toff = duint8(sym, off, uint8(word>>8))\n\t\t\toff = duint8(sym, off, uint8(word>>16))\n\t\t\toff = duint8(sym, off, uint8(word>>24))\n\t\t}\n\t}\n\n\tduint32(sym, 0, uint32(i)) // number of bitmaps\n\tggloblsym(sym, int32(off), obj.RODATA)\n}", "func storeGuess(guess int){\n\tvar guessedNums [20]int\n\tfor i, _ := range guessedNums {\n\t\tguessedNums[i] = guess\n\t}\n\t//test to see output on console\n\t//fmt.Printf(\"stored guess: %d\", guess)\n}", "func (b *profileBuilder) readMapping() {\n\tdata, _ := ioutil.ReadFile(\"/proc/self/maps\")\n\tparseProcSelfMaps(data, b.addMapping)\n\tif len(b.mem) == 0 { // pprof expects a map entry, so fake one.\n\t\tb.addMappingEntry(0, 0, 0, \"\", \"\", true)\n\t\t// TODO(hyangah): make addMapping return *memMap or\n\t\t// take a memMap struct, and get rid of addMappingEntry\n\t\t// that takes a bunch of positional arguments.\n\t}\n}", "func GenerateWorkLoad(length int) []int {\n\tarr := make([]int, length)\n\tfor i := 0; i < length; i++ {\n\t\tarr[i] = ImageCache()\n\t}\n\treturn arr\n}", "func (o AccessCustomPageOutput) AppCount() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *AccessCustomPage) pulumi.IntPtrOutput { return v.AppCount }).(pulumi.IntPtrOutput)\n}", "func (m *MicrosoftStoreForBusinessApp) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.MobileApp.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetContainedApps() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetContainedApps()))\n for i, v := range m.GetContainedApps() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"containedApps\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetLicenseType() != nil {\n cast := (*m.GetLicenseType()).String()\n err = writer.WriteStringValue(\"licenseType\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"licensingType\", m.GetLicensingType())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"packageIdentityName\", m.GetPackageIdentityName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"productKey\", m.GetProductKey())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"totalLicenseCount\", m.GetTotalLicenseCount())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"usedLicenseCount\", m.GetUsedLicenseCount())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *ImportedWindowsAutopilotDeviceIdentityState) SetAdditionalData(value map[string]any)() {\n err := m.GetBackingStore().Set(\"additionalData\", value)\n if err != nil {\n panic(err)\n }\n}", "func AppStateFromGenesisFileFn(\n\tr *rand.Rand, _ []simulation.Account, _ time.Time,\n) (json.RawMessage, []simulation.Account, string) {\n\n\tvar genesis tmtypes.GenesisDoc\n\tcdc := MakeCodec()\n\n\tbytes, err := ioutil.ReadFile(genesisFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tcdc.MustUnmarshalJSON(bytes, &genesis)\n\n\tvar appState GenesisState\n\tcdc.MustUnmarshalJSON(genesis.AppState, &appState)\n\n\taccounts := genaccounts.GetGenesisStateFromAppState(cdc, appState.toMap(cdc))\n\n\tvar newAccs []simulation.Account\n\tfor _, acc := range accounts {\n\t\t// Pick a random private key, since we don't know the actual key\n\t\t// This should be fine as it's only used for mock Tendermint validators\n\t\t// and these keys are never actually used to sign by mock Tendermint.\n\t\tprivkeySeed := make([]byte, 15)\n\t\tr.Read(privkeySeed)\n\n\t\tprivKey := secp256k1.GenPrivKeySecp256k1(privkeySeed)\n\t\tnewAccs = append(newAccs, simulation.Account{PrivKey: privKey, PubKey: privKey.PubKey(), Address: acc.Address})\n\t}\n\n\treturn genesis.AppState, newAccs, genesis.ChainID\n}", "func (m *AppVulnerabilityTask) GetManagedDeviceCount()(*int32) {\n val, err := m.GetBackingStore().Get(\"managedDeviceCount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func SystemcounterReadList(buf []byte, dest []Systemcounter) int {\n\tb := 0\n\tfor i := 0; i < len(dest); i++ {\n\t\tdest[i] = Systemcounter{}\n\t\tb += SystemcounterRead(buf[b:], &dest[i])\n\t}\n\treturn xgb.Pad(b)\n}", "func (throttler *Throttler) markRecentApp(appName string, remoteAddr string) {\n\trecentAppKey := fmt.Sprintf(\"%s/%s\", appName, remoteAddr)\n\tthrottler.recentApps.Set(recentAppKey, time.Now(), cache.DefaultExpiration)\n}", "func getSyncMapReadyForSending(m *sync.Map){\n\tfor{\n\t\ttime.Sleep(time.Millisecond)\n\n\t\ttmpMap := make(map[string][]int)\n m.Range(func(k, v interface{}) bool {\n tmpMap[k.(string)] = v.([]int)\n return true\n })\n\n jsonTemp, err := json.Marshal(tmpMap)\n\t\tif err != nil{\n\t\t\tpanic(err)\n\t\t}\n\n\t\tUpdatesString = string(jsonTemp)\n\t}\n}", "func TestSchedulerRecoveryWithoutAppInfo(t *testing.T) {\n\t// Register RM\n\tconfigData := `\npartitions:\n -\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\tms := &mockScheduler{}\n\tdefer ms.Stop()\n\n\terr := ms.Init(configData, false)\n\tassert.NilError(t, err, \"RegisterResourceManager failed\")\n\n\t// Register nodes, and add apps\n\t// here we only report back existing allocations, without registering applications\n\terr = ms.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\tExistingAllocations: []*si.Allocation{\n\t\t\t\t\t{\n\t\t\t\t\t\tAllocationKey: \"allocation-key-01\",\n\t\t\t\t\t\tUUID: \"UUID01\",\n\t\t\t\t\t\tApplicationID: \"app-01\",\n\t\t\t\t\t\tPartitionName: \"default\",\n\t\t\t\t\t\tQueueName: \"root.a\",\n\t\t\t\t\t\tNodeID: \"node-1:1234\",\n\t\t\t\t\t\tResourcePerAlloc: &si.Resource{\n\t\t\t\t\t\t\tResources: map[string]*si.Quantity{\n\t\t\t\t\t\t\t\tresources.MEMORY: {\n\t\t\t\t\t\t\t\t\tValue: 1024,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tresources.VCORE: {\n\t\t\t\t\t\t\t\t\tValue: 1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\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\tRmID: \"rm:123\",\n\t})\n\n\tassert.NilError(t, err, \"UpdateRequest nodes and apps failed\")\n\n\t// waiting for recovery\n\t// node-1 should be rejected as some of allocations cannot be recovered\n\tms.mockRM.waitForRejectedNode(t, \"node-1:1234\", 1000)\n\tms.mockRM.waitForAcceptedNode(t, \"node-2:1234\", 1000)\n\n\t// verify partitionInfo resources\n\tpartitionInfo := ms.clusterInfo.GetPartition(\"[rm:123]default\")\n\tassert.Equal(t, partitionInfo.GetTotalNodeCount(), 1)\n\tassert.Equal(t, partitionInfo.GetTotalApplicationCount(), 0)\n\tassert.Equal(t, partitionInfo.GetTotalAllocationCount(), 0)\n\tassert.Equal(t, partitionInfo.GetNode(\"node-2:1234\").GetAllocatedResource().Resources[resources.MEMORY],\n\t\tresources.Quantity(0))\n\n\t// register the node again, with application info attached\n\terr = ms.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\tExistingAllocations: []*si.Allocation{\n\t\t\t\t\t{\n\t\t\t\t\t\tAllocationKey: \"allocation-key-01\",\n\t\t\t\t\t\tUUID: \"UUID01\",\n\t\t\t\t\t\tApplicationID: \"app-01\",\n\t\t\t\t\t\tPartitionName: \"default\",\n\t\t\t\t\t\tQueueName: \"root.a\",\n\t\t\t\t\t\tNodeID: \"node-1:1234\",\n\t\t\t\t\t\tResourcePerAlloc: &si.Resource{\n\t\t\t\t\t\t\tResources: map[string]*si.Quantity{\n\t\t\t\t\t\t\t\tresources.MEMORY: {\n\t\t\t\t\t\t\t\t\tValue: 100,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tresources.VCORE: {\n\t\t\t\t\t\t\t\t\tValue: 1,\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\tNewApplications: newAddAppRequest(map[string]string{\"app-01\": \"root.a\"}),\n\t\tRmID: \"rm:123\",\n\t})\n\n\tassert.NilError(t, err, \"UpdateRequest re-register nodes and app failed\")\n\n\tms.mockRM.waitForAcceptedNode(t, \"node-1:1234\", 1000)\n\n\tassert.Equal(t, partitionInfo.GetTotalNodeCount(), 2)\n\tassert.Equal(t, partitionInfo.GetTotalApplicationCount(), 1)\n\tassert.Equal(t, partitionInfo.GetTotalAllocationCount(), 1)\n\tassert.Equal(t, partitionInfo.GetNode(\"node-1:1234\").GetAllocatedResource().Resources[resources.MEMORY], resources.Quantity(100))\n\tassert.Equal(t, partitionInfo.GetNode(\"node-1:1234\").GetAllocatedResource().Resources[resources.VCORE], resources.Quantity(1))\n\tassert.Equal(t, partitionInfo.GetNode(\"node-2:1234\").GetAllocatedResource().Resources[resources.MEMORY], resources.Quantity(0))\n\tassert.Equal(t, partitionInfo.GetNode(\"node-2:1234\").GetAllocatedResource().Resources[resources.VCORE], resources.Quantity(0))\n\n\tt.Log(\"verifying scheduling queues\")\n\trecoveredQueueRoot := ms.getSchedulingQueue(\"root\")\n\trecoveredQueue := ms.getSchedulingQueue(\"root.a\")\n\tassert.Equal(t, recoveredQueue.QueueInfo.GetAllocatedResource().Resources[resources.MEMORY], resources.Quantity(100))\n\tassert.Equal(t, recoveredQueue.QueueInfo.GetAllocatedResource().Resources[resources.VCORE], resources.Quantity(1))\n\tassert.Equal(t, recoveredQueueRoot.QueueInfo.GetAllocatedResource().Resources[resources.MEMORY], resources.Quantity(100))\n\tassert.Equal(t, recoveredQueueRoot.QueueInfo.GetAllocatedResource().Resources[resources.VCORE], resources.Quantity(1))\n}", "func (m *MemBook) Read(_ context.Context, isbns []string) (books map[string]models.Book, err error) {\n\n\t// Create the return map.\n\tbooks = make(map[string]models.Book, len(isbns))\n\n\t// Lock the book data for async safe use.\n\tm.mux.RLock()\n\tdefer m.mux.RUnlock()\n\n\t// Check for the empty case.\n\tif len(isbns) == 0 {\n\n\t\t// Copy all book data.\n\t\tfor isbn, book := range m.books {\n\t\t\tbooks[isbn] = *book\n\t\t}\n\t} else {\n\n\t\t// Iterate through the give ISBNs. Copy the requested ones.\n\t\tfor _, isbn := range isbns {\n\t\t\tbook, ok := m.books[isbn]\n\t\t\tif !ok {\n\t\t\t\treturn nil, ErrISBNNotFound\n\t\t\t}\n\t\t\tbooks[isbn] = *book\n\t\t}\n\t}\n\n\treturn books, nil\n}", "func (f ProcessInstanceIDFetcher) Fetch(logger lager.Logger, appGUID string) (map[int]string, error) {\n\tlogger = logger.Session(\"process-instance-id-fetch\", lager.Data{\"app-guid\": appGUID})\n\tlogger.Info(\"start\")\n\tdefer logger.Info(\"end\")\n\n\tstart := time.Now().Add(-30 * time.Second)\n\tend := time.Now()\n\n\tprocessInstanceIDs := map[int]string{}\n\n\tfor i := 0; i < maxReadTries; i++ {\n\t\tenvelopes, err := f.client.Read(context.Background(), appGUID, start,\n\t\t\tlogcache.WithDescending(),\n\t\t\tlogcache.WithEnvelopeTypes(logcache_v1.EnvelopeType_GAUGE),\n\t\t\tlogcache.WithNameFilter(\"absolute_entitlement\"),\n\t\t\tlogcache.WithEndTime(end),\n\t\t\tlogcache.WithLimit(f.limit),\n\t\t)\n\n\t\tif err != nil {\n\t\t\tlogger.Error(\"log-cache-read-failed\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, envelope := range envelopes {\n\t\t\tinstanceID, err := strconv.Atoi(envelope.InstanceId)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Info(\"ignoring-corrupt-instance-id\", lager.Data{\"envelope\": envelope})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tprocessInstanceID := envelope.Tags[\"process_instance_id\"]\n\t\t\tif len(processInstanceID) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif _, exists := processInstanceIDs[instanceID]; !exists {\n\t\t\t\tprocessInstanceIDs[instanceID] = processInstanceID\n\t\t\t}\n\t\t}\n\n\t\tif len(envelopes) < f.limit {\n\t\t\tbreak\n\t\t}\n\n\t\tlogger.Info(\"more-metrics-to-fetch\", lager.Data{\"iteration\": i, \"max-iterations\": maxReadTries, \"page-size\": f.limit})\n\t\tend = time.Unix(0, envelopes[len(envelopes)-1].Timestamp)\n\t}\n\n\treturn processInstanceIDs, nil\n}" ]
[ "0.63212216", "0.55052525", "0.5487842", "0.5469241", "0.5096306", "0.4942264", "0.4932391", "0.49198318", "0.47389328", "0.47235832", "0.4666213", "0.4537478", "0.45159277", "0.44901553", "0.44859603", "0.44783434", "0.44477382", "0.4390468", "0.4382944", "0.43749502", "0.43154022", "0.4283657", "0.42788708", "0.42785084", "0.42721108", "0.42619833", "0.42576125", "0.42507142", "0.42466253", "0.42444825", "0.42439127", "0.42351973", "0.42317137", "0.42296413", "0.42065966", "0.4194858", "0.41931728", "0.41892824", "0.41880178", "0.41769543", "0.41728893", "0.4166377", "0.41651842", "0.4161645", "0.41565597", "0.4156512", "0.41395968", "0.41247335", "0.41118428", "0.4110324", "0.41062263", "0.40997022", "0.4097907", "0.40857092", "0.40847483", "0.40812933", "0.407888", "0.4078374", "0.40766603", "0.40629938", "0.40522185", "0.40509498", "0.40395918", "0.4039345", "0.4039136", "0.4036634", "0.402956", "0.40255275", "0.40254828", "0.40232632", "0.40182567", "0.40169638", "0.40116194", "0.40046778", "0.39979085", "0.39931622", "0.39886305", "0.39877906", "0.39812186", "0.39785197", "0.39763808", "0.397397", "0.3971893", "0.39671943", "0.39652485", "0.39648208", "0.39643145", "0.396153", "0.39608252", "0.39575458", "0.39573556", "0.39529774", "0.39494392", "0.39451027", "0.3938457", "0.39368984", "0.39344382", "0.39316404", "0.3929852", "0.39269322" ]
0.53405076
4
If an entry is not inUse and and its CreateTime were before the agent started, then we free it up.
func appNumAllocatorGC(ctx *zedrouterContext) { pubUuidToNum := ctx.pubUuidToNum log.Infof("appNumAllocatorGC") freedCount := 0 items := pubUuidToNum.GetAll() for _, st := range items { status := cast.CastUuidToNum(st) if status.NumType != "appNum" { continue } if status.InUse { continue } if status.CreateTime.After(ctx.agentStartTime) { continue } log.Infof("appNumAllocatorGC: freeing %+v", status) appNumFree(ctx, status.UUID) freedCount++ } log.Infof("appNumAllocatorGC freed %d", freedCount) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Cache) CleanupExpired() {\n\tgo func() {\n\t\tfor {\n\t\t\tfor k, v := range c.Map {\n\t\t\t\tif v.RegTime.Add(time.Minute * 1).Before(time.Now()) {\n\t\t\t\t\tc.Remove(k)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttime.Sleep(time.Second * 10)\n\t\t}\n\t}()\n}", "func (c *Cache) cleanup(ttl time.Duration) {\n\tvalids := map[string]*cacheEntry{}\n\tnow := time.Now()\n\tfor token, entry := range c.entries {\n\t\tif entry.jwt.IsValid(c.leeway) {\n\t\t\tif entry.accessed.Add(ttl).After(now) {\n\t\t\t\t// Everything fine.\n\t\t\t\tvalids[token] = entry\n\t\t\t}\n\t\t}\n\t}\n\tc.entries = valids\n}", "func (instance *cache) unsafeFreeEntry(key string) fail.Error {\n\tif _, ok := instance.reserved[key]; !ok {\n\t\treturn fail.NotAvailableError(\"the cache entry '%s' is not reserved\", key)\n\t}\n\n\tvar (\n\t\tce *Entry\n\t\tok bool\n\t)\n\tif ce, ok = instance.cache[key]; ok {\n\t\tdelete(instance.cache, key)\n\t\tdelete(instance.reserved, key)\n\t\tce.unlock()\n\t}\n\n\treturn nil\n}", "func (instance *cache) FreeEntry(key string) (xerr fail.Error) {\n\tif instance.isNull() {\n\t\treturn fail.InvalidInstanceError()\n\t}\n\tif key = strings.TrimSpace(key); key == \"\" {\n\t\treturn fail.InvalidParameterCannotBeEmptyStringError(\"key\")\n\t}\n\n\tinstance.lock.Lock()\n\tdefer instance.lock.Unlock()\n\n\treturn instance.unsafeFreeEntry(key)\n}", "func (c *ttlCache) purge() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tfor key, value := range c.entries {\n\t\tif value.expireTime.Before(time.Now()) {\n\t\t\tdelete(c.entries, key)\n\t\t}\n\t}\n\n}", "func (rq *requestQueue) cleanup(now metav1.Time) {\n\trq.lock.Lock()\n\tdefer rq.lock.Unlock()\n\tnewRequestList := &requestLinkedList{}\n\tnewRequestMap := map[string]request{}\n\trq.requestList.Range(func(requestID string) bool {\n\t\treq := rq.requestMap[requestID]\n\t\t// Checking expiration\n\t\tif now.After(req.expiration.Time) {\n\t\t\tlogrus.Infof(\"request id %s expired\", req.id)\n\t\t\treturn true\n\t\t}\n\t\t// Keeping\n\t\tnewRequestList.Append(requestID)\n\t\tnewRequestMap[requestID] = req\n\t\treturn true\n\t})\n\trq.requestMap = newRequestMap\n\trq.requestList = newRequestList\n}", "func (rp *resourcePool) Maintain() {\n\trp.Lock()\n\tdefer rp.Unlock()\n\n\tif rp.closed {\n\t\treturn\n\t}\n\n\tfor curr := rp.end; curr != nil; curr = curr.prev {\n\t\tif rp.expiredFn(curr.value) {\n\t\t\trp.remove(curr)\n\t\t\trp.closeFn(curr.value)\n\t\t\trp.totalSize--\n\t\t}\n\t}\n\n\tfor rp.totalSize < rp.minSize {\n\t\trp.add(nil)\n\t\trp.totalSize++\n\t}\n\n\t// reset the timer for the background cleanup routine\n\tif rp.maintainTimer == nil {\n\t\trp.maintainTimer = time.AfterFunc(rp.maintainInterval, rp.Maintain)\n\t}\n\tif !rp.maintainTimer.Stop() {\n\t\trp.maintainTimer = time.AfterFunc(rp.maintainInterval, rp.Maintain)\n\t\treturn\n\t}\n\trp.maintainTimer.Reset(rp.maintainInterval)\n}", "func (ins *Cache) releseCap(now time.Time) {\n\tif now.Sub(ins.released) < time.Duration(24)*time.Hour {\n\t\treturn\n\t}\n\tstorage := new(sync.Map)\n\tscanAll :=\n\t\tfunc(key, value interface{}) (continueIteration bool) {\n\t\t\tcontinueIteration = true\n\t\t\ti, ok := value.(*item)\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif i.expire.Before(now) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tstorage.Store(key, value)\n\t\t\treturn\n\t\t}\n\tins.storage.Range(scanAll)\n\tins.storage = storage\n\tins.released = now\n}", "func (d *Datastore) cleanup() {\n\tn := time.Now()\n\tfor key, item := range d.items {\n\t\tif item.time.Add(d.threshold).Before(n) {\n\t\t\tdelete(d.items, key)\n\t\t}\n\t}\n}", "func (bq *InMemoryBuildQueue) enter(t time.Time) {\n\tbq.lock.Lock()\n\tif t.After(bq.now) {\n\t\tbq.now = t\n\t\tbq.cleanupQueue.run(bq.now)\n\t}\n}", "func (m *LocalExecutorManager) purgeExpiredEntries() {\n\tfor {\n\t\tfunc() {\n\t\t\tm.Lock()\n\t\t\tcutoverLimit := time.Now().Add(-24 * time.Hour)\n\t\t\tfor id, executorStatus := range m.id2ExecutorStatus {\n\t\t\t\tif executorStatus.LastAccessTime.Before(cutoverLimit) {\n\t\t\t\t\tdelete(m.id2ExecutorStatus, id)\n\t\t\t\t}\n\t\t\t}\n\t\t\tm.Unlock()\n\t\t\ttime.Sleep(1 * time.Hour)\n\t\t}()\n\t}\n}", "func (t *BeatTracker) Free() {\n\tif t.o == nil {\n\t\treturn\n\t}\n\tC.del_aubio_beattracking(t.o)\n\tt.o = nil\n}", "func (r *registry) cleanUpFinished() time.Duration {\n\tstartTime := time.Now()\n\tif r.entries.taskCount.Load() == 0 {\n\t\tif r.entries.len() <= entriesSizeHW {\n\t\t\treturn cleanupInterval\n\t\t}\n\t}\n\tanyTaskDeleted := false\n\ttoRemove := make([]string, 0, 100)\n\tr.entries.forEach(func(entry baseEntry) bool {\n\t\tvar (\n\t\t\txact = entry.Get()\n\t\t\teID = xact.ID()\n\t\t)\n\n\t\tif !xact.Finished() {\n\t\t\treturn true\n\t\t}\n\n\t\t// if entry is type of task the task must be cleaned up always - no extra\n\t\t// checks besides it is finished at least entryOldAge ago.\n\t\t//\n\t\t// We need to check if the entry is not the most recent entry for\n\t\t// given kind. If it is we want to keep it anyway.\n\t\tswitch cmn.XactsMeta[entry.Kind()].Type {\n\t\tcase cmn.XactTypeGlobal:\n\t\t\tentry := r.entries.findUnlocked(XactQuery{Kind: entry.Kind(), OnlyRunning: true})\n\t\t\tif entry != nil && entry.Get().ID() == eID {\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase cmn.XactTypeBck:\n\t\t\tbck := cluster.NewBckEmbed(xact.Bck())\n\t\t\tcmn.Assert(bck.HasProvider())\n\t\t\tentry := r.entries.findUnlocked(XactQuery{Kind: entry.Kind(), Bck: bck, OnlyRunning: true})\n\t\t\tif entry != nil && entry.Get().ID() == eID {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\tif xact.EndTime().Add(entryOldAge).Before(startTime) {\n\t\t\t// xaction has finished more than entryOldAge ago\n\t\t\ttoRemove = append(toRemove, eID.String())\n\t\t\tif cmn.XactsMeta[entry.Kind()].Type == cmn.XactTypeTask {\n\t\t\t\tanyTaskDeleted = true\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t\treturn true\n\t})\n\n\tfor _, id := range toRemove {\n\t\tr.entries.remove(id)\n\t}\n\n\t// free all memory taken by cleaned up tasks\n\t// Tasks like ListObjects ones may take up huge amount of memory, so they\n\t// must be cleaned up as soon as possible\n\tif anyTaskDeleted {\n\t\tcmn.FreeMemToOS(time.Second)\n\t}\n\treturn cleanupInterval\n}", "func (s *storage) cleanExpired(sources pb.SyncMapping, actives pb.SyncMapping) {\nnext:\n\tfor _, entry := range sources {\n\t\tfor _, act := range actives {\n\t\t\tif act.CurInstanceID == entry.CurInstanceID {\n\t\t\t\tcontinue next\n\t\t\t}\n\t\t}\n\n\t\tdelOp := delMappingOp(entry.ClusterName, entry.OrgInstanceID)\n\t\tif _, err := s.engine.Do(context.Background(), delOp); err != nil {\n\t\t\tlog.Errorf(err, \"Delete instance clusterName=%s instanceID=%s failed\", entry.ClusterName, entry.OrgInstanceID)\n\t\t}\n\n\t\ts.deleteInstance(entry.CurInstanceID)\n\t}\n}", "func (c *Cache) Purge() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tc.heap = newHeap(c.capacity, c.cmp)\n\tc.items = make(itemsMap, c.capacity)\n}", "func (tl *TimeLord) Destroy() {\n\tglobalMut.Lock()\n\tdefer globalMut.Unlock()\n\ttl.unwarp()\n\ttl.guard = nil\n\ttimeLordExists = false\n}", "func (m *TrxMgr) cleanExpiredWaiting() {\n\t// when the waiting pool is small, we don't need cleaning\n\tif len(m.waiting) < sWaitingCountWaterMark {\n\t\treturn\n\t}\n\t// we avoid frequent cleaning\n\tif headBlockTime := atomic.LoadUint32(&m.headTime); headBlockTime > 0 && time.Since(m.lastCleanTime) > sMinCleanupInterval {\n\t\tm.lastCleanTime = time.Now()\n\t\tfor k, e := range m.waiting {\n\t\t\tif err := e.CheckExpiration(headBlockTime); err != nil {\n\t\t\t\tm.deliverEntry(e)\n\t\t\t}\n\t\t\tdelete(m.waiting, k)\n\t\t}\n\t}\n}", "func (p *ArgsEnvsCacheEntry) Retain() {\n\tp.refCount++\n}", "func (c *C) makeSpace(needed int64) {\n\tfor c.mu.availableMem < needed {\n\t\t// Evict entries as necessary, putting them in the free list.\n\t\tc.evict().insertAfter(&c.mu.free)\n\t}\n}", "func (fr *flowRegistry) releaseEntryLocked(id FlowID) {\n\tentry := fr.flows[id]\n\tif entry.refCount > 1 {\n\t\tentry.refCount--\n\t} else {\n\t\tif entry.refCount != 1 {\n\t\t\tpanic(fmt.Sprintf(\"invalid refCount: %d\", entry.refCount))\n\t\t}\n\t\tdelete(fr.flows, id)\n\t}\n}", "func (e *eventManager) cleanup() {\n\tnow := time.Now()\n\n\tif now.Sub(e.lastRun).Seconds() < eventExpiry {\n\t\treturn\n\t}\n\n\tfor s, ev := range e.events {\n\t\tif now.Sub(ev.at).Seconds() > eventExpiry {\n\t\t\tdelete(e.events, s)\n\t\t}\n\t}\n\n\te.lastRun = now\n}", "func (p *Resolver) DeleteEntry(pid uint32, exitTime time.Time) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tp.deleteEntry(pid, exitTime)\n}", "func (table *CacheTable) expirationCheck() {\n\ttable.Lock()\n\tif table.cleanUpTimer != nil {\n\t\ttable.cleanUpTimer.Stop()\n\t}\n\n\tif table.cleanUpInterval > 0 {\n\t\ttable.log(\"Expiration check triggered after\", table.cleanUpInterval, \"for table\", table.name)\n\n\t} else {\n\t\ttable.log(\"Expiration check installed for table\", table.name)\n\t}\n\n\t// Cache value so we don't keep blocking the mutex.\n\titems := table.items\n\ttable.Unlock()\n\t// To be more accurate with timers, we would need to update 'now' on every\n\t// loop iteration. Not sure it's really efficient though.\n\tsmallestDuration := 0 * time.Second\n\tfor key, item := range items {\n\t\t// Cache values so we don't keep blocking the mutex.\n\t\titem.RLock()\n\t\tlifeSpan := item.lifeSpan\n\t\taccessedOn := item.accessdOn\n\t\titem.RUnlock()\n\t\tif lifeSpan == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tnow := time.Now()\n\t\tif now.Sub(accessedOn) >= lifeSpan {\n\t\t\ttable.Delete(key)\n\t\t} else {\n\t\t\tif smallestDuration == 0 || lifeSpan-now.Sub(accessedOn) < smallestDuration {\n\t\t\t\tsmallestDuration = lifeSpan - now.Sub(accessedOn)\n\t\t\t}\n\t\t}\n\n\t}\n\n\ttable.Lock()\n\ttable.cleanUpInterval = smallestDuration\n\tif smallestDuration > 0 {\n\t\ttable.cleanUpTimer = time.AfterFunc(smallestDuration, func() {\n\t\t\tgo table.expirationCheck()\n\t\t})\n\t}\n\ttable.Unlock()\n}", "func (s *LRUCache) FinishErase(e *LRUHandle) bool {\n if e != nil {\n if !e.in_cache {\n panic(\"FinishErase() error\")\n }\n s.LRU_Remove(e)\n e.in_cache = false\n s.usage_ -= e.charge\n s.Unref(e)\n }\n return e != nil\n}", "func (ca *myCache) DeleteExpiredData() {\n now := time.Now().UnixNano()\n ca.mu.Lock()\n defer ca.mu.Unlock()\n\n for k,v := range ca.dataBlocks {\n if v.ExpirateTime >0 && now > v.ExpirateTime {\n ca.delete(k)\n }\n }\n}", "func HandleCleanup(w http.ResponseWriter, r *http.Request) {\n\thc := NewHTTPContext(r, w) // HTTPContext\n\tc := gae.NewContext(hc) //GAE Context\n\tstamp := int64(time.Now().UnixNano() / Msec)\n\tq := datastore.NewQuery(\"Share\").Filter(\"expires >\", stamp)\n\n\tvar shares []Share\n\tkeys, err := q.GetAll(c, &shares)\n\tif err != nil {\n\t\tlog.Printf(\"Error during cleanip: %s\", err)\n\t\treturn\n\t}\n\n\tif len(keys) > 0 {\n\t\tlog.Printf(\"Found %d expired shares\", len(shares))\n\t\tfor i, key := range keys {\n\t\t\tshares[i].DSK = key\n\t\t\tshares[i].Delete(c)\n\t\t\tlog.Printf(\"Share '%s' deleted\", shares[i].Key)\n\t\t}\n\t}\n}", "func (e *Entry) InUse() bool {\n\treturn e.inUse\n}", "func (cls *CachedLocations) Release(ctx *Context, sys *System, name string) error {\n\tLog(INFO, ctx, \"CachedLocations.Release\", \"name\", name)\n\tvar err error\n\tcls.Lock()\n\tloc, dead := cls.expire(ctx, sys, name, true)\n\tif dead {\n\t\tLog(INFO, ctx, \"CachedLocations.Release\", \"name\", name, \"cached\", \"expired\")\n\t\tif loc != nil {\n\t\t\terr = sys.CloseLocation(ctx, name)\n\t\t}\n\t} else {\n\t\tLog(INFO, ctx, \"CachedLocations.Release\", \"name\", name, \"cached\", \"live\")\n\t}\n\tcls.Unlock()\n\treturn err\n}", "func (c *cache) purge() {\n\tp := make([]item, c.maxSize)\n\tt := time.Now()\n\tn := 0\n\tfor i := 0; i < c.curSize; i++ {\n\t\tif t.Sub(c.stories[i].t) < c.timeout {\n\t\t\tp[n] = c.stories[i]\n\t\t\tn++\n\t\t}\n\t}\n\tc.mutx.Lock()\n\tdefer c.mutx.Unlock()\n\tc.stories = p\n\tc.curSize = n\n}", "func (c *directClient) DelEntry(ctx context.Context, entry *disc.Entry) error {\n\tc.mx.Lock()\n\tdefer c.mx.Unlock()\n\tdelete(c.entries, entry.Static)\n\treturn nil\n}", "func (m *memory) Delete(ref int, lastmod time.Time) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tnow := time.Now()\n\n\tfor i, r := range m.reservations {\n\t\tif r.ID != ref {\n\t\t\tcontinue\n\t\t}\n\n\t\tif r.LastModified.After(lastmod) {\n\t\t\treturn errors.New(\"resource modified\")\n\t\t}\n\n\t\tif r.Start.After(now) {\n\t\t\tm.reservations = append(m.reservations[:i], m.reservations[i+1:]...)\n\n\t\t\terr := m.store.Delete(ref)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlog.Println(\"deleted\", ref)\n\n\t\t\treturn nil\n\t\t}\n\n\t\tif r.Loan {\n\t\t\tr.Loan = false\n\t\t\tr.End = now\n\t\t\tr.LastModified = time.Now().Round(time.Second)\n\n\t\t\terr := m.store.Update(r.ID, r)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlog.Println(\"ended\", ref)\n\n\t\t\treturn nil\n\t\t}\n\n\t\tif r.Start.Before(now) && r.End.After(now) {\n\t\t\tr.End = now\n\t\t\tr.LastModified = time.Now().Round(time.Second)\n\n\t\t\terr := m.store.Update(r.ID, r)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlog.Println(\"ended\", ref)\n\n\t\t\treturn nil\n\t\t}\n\n\t\tif r.End.Before(now) {\n\t\t\treturn errors.New(\"resource already expired\")\n\t\t}\n\t}\n\n\treturn errors.New(\"resource not found\")\n}", "func (c *C) getEntry() *entry {\n\tif e := c.mu.free.next; e != &c.mu.free {\n\t\te.remove()\n\t\treturn e\n\t}\n\t// No free entries, we must evict an entry.\n\treturn c.evict()\n}", "func (cache *EntryCache) GC() {\n\tcache.oldEntries = cache.entries\n\tcache.entries = make(map[int]*Entry)\n}", "func housekeepListCache(p *proxyrunner) time.Duration {\n\tif p.gmm.MemPressure() <= memsys.MemPressureModerate {\n\t\treturn bucketPrefixStaleTime\n\t}\n\n\tnow := mono.NanoTime()\n\tlistCache.mtx.Lock()\n\tdefer listCache.mtx.Unlock()\n\n\tfor k, v := range listCache.reqs {\n\t\tif v.lastUsage+int64(bucketPrefixStaleTime) < now {\n\t\t\tdelete(listCache.reqs, k)\n\t\t}\n\t}\n\n\treturn bucketPrefixStaleTime\n}", "func (c *C) evict() *entry {\n\te := c.mu.used.prev\n\tif e == &c.mu.used {\n\t\tpanic(\"no more used entries\")\n\t}\n\te.remove()\n\tc.mu.availableMem += e.memoryEstimate()\n\tdelete(c.mu.m, e.SQL)\n\te.clear()\n\n\treturn e\n}", "func (d *DeadNonceList) RemoveExpiredEntry() {\n\tif d.expiringEntries.Len() > 0 {\n\t\thash := d.expiringEntries.Front().Value.(uint64)\n\t\tdelete(d.list, hash)\n\t\td.expiringEntries.Remove(d.expiringEntries.Front())\n\t}\n}", "func (oo *OnuDeviceEntry) FreeTcont(ctx context.Context, allocID uint16) {\n\tlogger.Debugw(ctx, \"free-tcont\", log.Fields{\"device-id\": oo.deviceID, \"alloc\": allocID})\n\too.MutexPersOnuConfig.Lock()\n\tdefer oo.MutexPersOnuConfig.Unlock()\n\tdelete(oo.SOnuPersistentData.PersTcontMap, allocID)\n}", "func (c *CacheTable) Clean() {\r\n\tif nil != c.cleanTime {\r\n\t\tc.cleanTime.Stop()\r\n\t}\r\n\r\n\t//Copy map\r\n\titems := c.pool\r\n\r\n\t//Get min duration\r\n\tminDuration := 0 * time.Second\r\n\tclean_st := time.Now()\r\n\tfor key, item := range items {\r\n\t\tnowTime := time.Now()\r\n\t\tif item.lifeSpan <= nowTime.Sub(item.accessOn) {\r\n\t\t\tc.Delete(key)\r\n\t\t} else {\r\n\t\t\tif 0 == minDuration || item.lifeSpan-nowTime.Sub(item.accessOn) < minDuration {\r\n\t\t\t\tminDuration = item.lifeSpan - nowTime.Sub(item.accessOn)\r\n\t\t\t\t//log.Println(\"innnn %f\", minDuration.Seconds())\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif minDuration <= 0 {\r\n\t\treturn\r\n\t}\r\n\r\n\tlog.Println(\"LoopCost %f\", time.Now().Sub(clean_st).Seconds())\r\n\tc.cleanInterval = minDuration\r\n\t//Check if need do clean\r\n\tc.cleanTime = time.AfterFunc(minDuration, func() {\r\n\t\tgo c.Clean()\r\n\t})\r\n}", "func (k *KVItem) Free() {\n\tif k.tiledbKVItem != nil {\n\t\tC.tiledb_kv_item_free(&k.tiledbKVItem)\n\t}\n}", "func (instance *cache) MarkAsFreed(id string) {\n\tif instance == nil {\n\t\treturn\n\t}\n\n\tif id == \"\" {\n\t\treturn\n\t}\n\n\tinstance.lock.RLock()\n\tdefer instance.lock.RUnlock()\n\n\tif ce, ok := instance.cache[id]; ok {\n\t\tce.UnlockContent()\n\t}\n}", "func (tracer *Instance) Release() {\n\ttracer.collections.Del(tracer.key())\n}", "func (e *entry) clear() {\n\te.CachedData = CachedData{}\n}", "func (rate *Ratelimiter) cleanup() (empty bool) {\n\trate.mu.Lock()\n\tdefer rate.mu.Unlock()\n\n\tfor key, entry := range rate.tableIPv4 {\n\t\tentry.mu.Lock()\n\t\tif rate.timeNow().Sub(entry.lastTime) > garbageCollectTime {\n\t\t\tdelete(rate.tableIPv4, key)\n\t\t}\n\t\tentry.mu.Unlock()\n\t}\n\n\tfor key, entry := range rate.tableIPv6 {\n\t\tentry.mu.Lock()\n\t\tif rate.timeNow().Sub(entry.lastTime) > garbageCollectTime {\n\t\t\tdelete(rate.tableIPv6, key)\n\t\t}\n\t\tentry.mu.Unlock()\n\t}\n\n\treturn len(rate.tableIPv4) == 0 && len(rate.tableIPv6) == 0\n}", "func (r *PackageAggRow) ClearAvailable() { r.Data.Available = nil }", "func (d *DeviceInfoCache) Release(deviceInfo DeviceInfo) error {\n\n\t//this information record might be used by more than one SSM\n\tif deviceInfo._refCount == 0 {\n\t\treturn errors.New(\"reference count\")\n\t}\n\n\t// decrement the reference count\n\tdeviceInfo._refCount--\n\td.cache[deviceInfo._cacheKey.HashKey()] = deviceInfo\n\treturn nil\n}", "func (sd *StateDB) purge() {\n\t// TODO\n\t// purge will cause a panic problem, so temporaly comments the code.\n\t//\n\t// panic: [fatal error: concurrent map writes]\n\t// reason: the reason is that [sd.beats] is been concurrently called and\n\t// there is no lock handling this parameter.\n\n\t// for addr, lastbeat := range sd.beats {\n\t// \t// skip dirty states\n\t// \tif _, in := sd.journal.dirties[addr]; in {\n\t// \t\tcontinue\n\t// \t}\n\t// \tif _, in := sd.dirtyset[addr]; in {\n\t// \t\tcontinue\n\t// \t}\n\t// \tif time.Since(lastbeat) > sd.conf.BeatExpireTime {\n\t// \t\tsd.deleteStateObject(addr)\n\t// \t}\n\t// }\n}", "func (c *LRU) Purge() {\n\tfor e := c.evictList.Front(); e != nil; e = e.Next() {\n\t\tif c.onEvict != nil {\n\t\t\tc.onEvict(e.Value.(*utils.Entry))\n\t\t}\n\t}\n\tc.items = make(map[interface{}]*Records)\n\tc.evictList.Init()\n}", "func (c *cache) purgeOld(maxAge time.Duration) {\n\tc.itemMu.Lock()\n\tdefer c.itemMu.Unlock()\n\tcutoff := time.Now().Add(-maxAge)\n\tfor name, item := range c.item {\n\t\t// If not locked and access time too long ago - delete the file\n\t\tdt := item.atime.Sub(cutoff)\n\t\t// fs.Debugf(name, \"atime=%v cutoff=%v, dt=%v\", item.atime, cutoff, dt)\n\t\tif item.opens == 0 && dt < 0 {\n\t\t\tosPath := filepath.Join(c.root, filepath.FromSlash(name))\n\t\t\terr := os.Remove(osPath)\n\t\t\tif err != nil {\n\t\t\t\tfs.Errorf(name, \"Failed to remove from cache: %v\", err)\n\t\t\t} else {\n\t\t\t\tfs.Debugf(name, \"Removed from cache\")\n\t\t\t}\n\t\t\t// Remove the entry\n\t\t\tdelete(c.item, name)\n\t\t}\n\t}\n}", "func (rf *Raft) Kill() {\n\tatomic.StoreInt32(&rf.dead, 1)\n\t// Your code here, if desired.\n\t//Once.Do(func() {\n\t//\tlog.Println(\n\t//\t\tatomic.LoadInt32(&AppendEntriesCounts),\n\t//\t\tatomic.LoadInt32(&AppendEntriesFailed),\n\t//\t\tatomic.LoadInt32(&StartsCounts),\n\t//\t\tatomic.LoadInt32(&BroadcastAppendCounts),\n\t//\n\t//\t)\n\t//})\n}", "func (c *Cache) Cleanup() error {\n\treturn c.doSync(func() {\n\t\tif c.entries == nil {\n\t\t\treturn\n\t\t}\n\t\tc.cleanup(c.ttl)\n\t}, defaultTimeout)\n}", "func (s *CacheLastPasswordSent) cleanup() {\n\ttickEvery := time.NewTicker(1 * time.Minute)\n\tdefer tickEvery.Stop()\n\n\tclearOutAfter := time.Duration(10 * time.Minute)\n\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-s.stop:\n\t\t\tbreak Loop\n\t\tcase <-tickEvery.C:\n\t\t}\n\n\t\ts.mu.Lock()\n\t\tnow := time.Now().UTC()\n\t\tfor key, t := range s.data {\n\t\t\tif now.Sub(t) >= clearOutAfter {\n\t\t\t\tdelete(s.data, key)\n\t\t\t}\n\t\t}\n\t\ts.mu.Unlock()\n\t}\n}", "func (mem *Member) CleanupMember(memberId uint8, oldTime time.Time) {\n\tif memberId == mem.memberID {\n\t\treturn\n\t}\n\n\ttime.Sleep(time.Duration(Configuration.Settings.cleanupTimeout) * time.Second)\n\n\tif currEntry, ok := mem.membershipList[memberId]; ok {\n\t\tdifference := time.Now().Sub(currEntry.Timestamp)\n\t\tthreshold := time.Duration(Configuration.Settings.cleanupTimeout) * time.Second\n\t\tif difference >= threshold {\n\t\t\tdelete(mem.membershipList, memberId)\n\t\t\tInfo.Println(\"Cleaned up member: \", memberId)\n\t\t}\n\t}\n}", "func (c *Cache) Purge() {\n\tc.lockMap()\n\tdefer c.mutex.Unlock()\n\tfor key, val := range c.data {\n\t\tif c.expired(val) {\n\t\t\tc.remove(key)\n\t\t}\n\t}\n}", "func (h *Handler) Cleanup() error {\n\tvar err error\n\n\tif h.Config.Type == inMemory {\n\t\terr = backends.ReleaseGroupCacheRes()\n\t}\n\n\treturn err\n}", "func (w *WindowedMap) ExpireOldEntries() {\n\tif len(w.uidList) != len(w.uidMap) {\n\t\tpanic(*w)\n\t}\n\tnow := w.clock.Now()\n\tfor len(w.uidList) > 0 && !w.uidList[0].expire.After(now) {\n\t\tdelete(w.uidMap, w.uidList[0].uid)\n\t\theap.Remove(&w.uidList, 0)\n\t}\n}", "func FlushEntry(pool ServerPool, spec db.Specifier) {\n\tpool.Delete(spec)\n}", "func (kv *ShardKV) Kill() {\n kv.dead = true\n kv.l.Close()\n kv.px.Kill()\n}", "func (e *neighborEntry) removeLocked() {\n\te.mu.neigh.UpdatedAt = e.cache.nic.stack.clock.NowMonotonic()\n\te.dispatchRemoveEventLocked()\n\t// Set state to unknown to invalidate this entry if it's cached in a Route.\n\te.setStateLocked(Unknown)\n\te.cancelTimerLocked()\n\t// TODO(https://gvisor.dev/issues/5583): test the case where this function is\n\t// called during resolution; that can happen in at least these scenarios:\n\t//\n\t//\t- manual address removal during resolution\n\t//\n\t//\t- neighbor cache eviction during resolution\n\te.notifyCompletionLocked(&tcpip.ErrAborted{})\n}", "func (c Cache) gc(shutdown <-chan struct{}, tickerCh <-chan time.Time) bool {\n\tselect {\n\tcase <-shutdown:\n\t\treturn false\n\tcase <-tickerCh:\n\t\t// garbage collect the numberCache\n\t\tfor id, point := range c.numberCache {\n\t\t\tif point.used {\n\t\t\t\t// for points that have been used, mark them as unused\n\t\t\t\tpoint.used = false\n\t\t\t\tc.numberCache[id] = point\n\t\t\t} else {\n\t\t\t\t// for points that have not been used, delete points\n\t\t\t\tdelete(c.numberCache, id)\n\t\t\t}\n\t\t}\n\t\t// garbage collect the summaryCache\n\t\tfor id, point := range c.summaryCache {\n\t\t\tif point.used {\n\t\t\t\t// for points that have been used, mark them as unused\n\t\t\t\tpoint.used = false\n\t\t\t\tc.summaryCache[id] = point\n\t\t\t} else {\n\t\t\t\t// for points that have not been used, delete points\n\t\t\t\tdelete(c.summaryCache, id)\n\t\t\t}\n\t\t}\n\t\t// garbage collect the histogramCache\n\t\tfor id, point := range c.histogramCache {\n\t\t\tif point.used {\n\t\t\t\t// for points that have been used, mark them as unused\n\t\t\t\tpoint.used = false\n\t\t\t\tc.histogramCache[id] = point\n\t\t\t} else {\n\t\t\t\t// for points that have not been used, delete points\n\t\t\t\tdelete(c.histogramCache, id)\n\t\t\t}\n\t\t}\n\t\t// garbage collect the exponentialHistogramCache\n\t\tfor id, point := range c.exponentialHistogramCache {\n\t\t\tif point.used {\n\t\t\t\t// for points that have been used, mark them as unused\n\t\t\t\tpoint.used = false\n\t\t\t\tc.exponentialHistogramCache[id] = point\n\t\t\t} else {\n\t\t\t\t// for points that have not been used, delete points\n\t\t\t\tdelete(c.exponentialHistogramCache, id)\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func (sb *shardBuffer) evictOldestEntry(e *entry) {\n\tsb.mu.Lock()\n\tdefer sb.mu.Unlock()\n\n\tif len(sb.queue) == 0 || e != sb.queue[0] {\n\t\t// Entry is already removed e.g. by remove(). Ignore it.\n\t\treturn\n\t}\n\n\t// Evict the entry.\n\t//\n\t// NOTE: We're not waiting for the request to finish in order to unblock the\n\t// timeout thread as fast as possible. However, the slot of the evicted\n\t// request is only returned after it has finished i.e. the buffer may stay\n\t// full in the meantime. This is a design tradeoff to keep things simple and\n\t// avoid additional pressure on the primary tablet.\n\tsb.unblockAndWait(e, nil /* err */, true /* releaseSlot */, false /* blockingWait */)\n\tsb.queue = sb.queue[1:]\n\tstatsKeyWithReason := append(sb.statsKey, evictedWindowExceeded)\n\trequestsEvicted.Add(statsKeyWithReason, 1)\n}", "func (c *cache) StartCleaner() {\n\tfor {\n\t\ttime.Sleep(50 * time.Millisecond)\n\t\tc.Exps.m.Lock()\n\t\tif c.Exps.Len() != 0 {\n\t\t\t// closest expiration\n\t\t\texpiration := c.Exps.Expirations[0]\n\t\t\tfor ; expiration.Expires.Before(time.Now()); expiration = c.Exps.Expirations[0] {\n\t\t\t\tif expiration.Expires.Before(time.Now()) {\n\t\t\t\t\theap.Pop(&c.Exps)\n\t\t\t\t\tc.m.Lock()\n\t\t\t\t\tc.delete(expiration.Field)\n\t\t\t\t\tc.m.Unlock()\n\t\t\t\t\tif c.Exps.Len() == 0 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tc.Exps.m.Unlock()\n\t}\n}", "func (diffStore *utxoDiffStore) clearOldEntries() {\n\tdiffStore.mtx.HighPriorityWriteLock()\n\tdefer diffStore.mtx.HighPriorityWriteUnlock()\n\n\tvirtualBlueScore := diffStore.dag.VirtualBlueScore()\n\tminBlueScore := virtualBlueScore - maxBlueScoreDifferenceToKeepLoaded\n\tif maxBlueScoreDifferenceToKeepLoaded > virtualBlueScore {\n\t\tminBlueScore = 0\n\t}\n\n\ttips := diffStore.dag.virtual.tips()\n\n\ttoRemove := make(map[*blockNode]struct{})\n\tfor node := range diffStore.loaded {\n\t\tif node.blueScore < minBlueScore && !tips.contains(node) {\n\t\t\ttoRemove[node] = struct{}{}\n\t\t}\n\t}\n\tfor node := range toRemove {\n\t\tdelete(diffStore.loaded, node)\n\t}\n}", "func (s *Store) GC() {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tfor k, v := range s.m {\n\t\tif v.IsExpired() {\n\t\t\tdelete(s.m, k)\n\t\t}\n\t}\n}", "func (f *IndexFile) Retain() { f.wg.Add(1) }", "func (f *FakeProcTableImpl) RemoveEntry(pvName string) (CleanupState, *time.Time, error) {\n\tf.RemoveCount++\n\treturn f.realTable.RemoveEntry(pvName)\n}", "func (oo *OnuDeviceEntry) AllocateFreeTcont(ctx context.Context, allocID uint16) (uint16, bool, error) {\n\tlogger.Debugw(ctx, \"allocate-free-tcont\", log.Fields{\"device-id\": oo.deviceID, \"allocID\": allocID,\n\t\t\"allocated-instances\": oo.SOnuPersistentData.PersTcontMap})\n\n\too.MutexPersOnuConfig.Lock()\n\tdefer oo.MutexPersOnuConfig.Unlock()\n\tif entityID, ok := oo.SOnuPersistentData.PersTcontMap[allocID]; ok {\n\t\t//tcont already allocated before, return the used instance-id\n\t\treturn entityID, true, nil\n\t}\n\t//First allocation of tcont. Find a free instance\n\tif tcontInstKeys := oo.pOnuDB.GetSortedInstKeys(ctx, me.TContClassID); len(tcontInstKeys) > 0 {\n\t\tlogger.Debugw(ctx, \"allocate-free-tcont-db-keys\", log.Fields{\"device-id\": oo.deviceID, \"keys\": tcontInstKeys})\n\t\tfor _, instID := range tcontInstKeys {\n\t\t\tinstExist := false\n\t\t\t//If this instance exist in map, it means it is not empty. It is allocated before\n\t\t\tfor _, v := range oo.SOnuPersistentData.PersTcontMap {\n\t\t\t\tif v == instID {\n\t\t\t\t\tinstExist = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !instExist {\n\t\t\t\too.SOnuPersistentData.PersTcontMap[allocID] = instID\n\t\t\t\treturn instID, false, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn 0, false, fmt.Errorf(fmt.Sprintf(\"no-free-tcont-left-for-device-%s\", oo.deviceID))\n}", "func (cls *CachedLocations) expire(ctx *Context, sys *System, name string, released bool) (*Location, bool) {\n\t// Assumes lock\n\tLog(INFO, ctx, \"CachedLocations.expire\", \"name\", name)\n\tcl, have := cls.locs[name]\n\tvar loc *Location\n\tdead := false\n\tif have {\n\t\tcl.Lock()\n\t\tcl.Pending = !released\n\t\tLog(INFO, ctx, \"CachedLocations.expire\", \"name\", name, \"cached\", \"exists\")\n\t\tif cl.Pending || cl.Expires.After(time.Now()) {\n\t\t\tLog(INFO, ctx, \"CachedLocations.expire\", \"name\", name, \"cached\", \"live\")\n\t\t\tloc = cl.Location\n\t\t} else {\n\t\t\tLog(INFO, ctx, \"CachedLocations.expire\", \"name\", name, \"cached\", \"expired\")\n\t\t\tdelete(cls.locs, name)\n\t\t}\n\t\tcl.Unlock()\n\t}\n\treturn loc, dead\n}", "func Release(h *Headers) {\n\tvar ma nullInt64\n\tvar sma nullInt64\n\th.b = h.b[:0]\n\th.public = false\n\th.private = false\n\th.maxAge = ma\n\th.sharedMaxAge = sma\n\th.noCache = false\n\th.noStore = false\n\th.noTransform = false\n\th.mustRevalidate = false\n\th.proxyRevalidate = false\n\n\tpool.Put(h)\n}", "func (tracker *UsageTracker) CleanUp(cutoff time.Time) {\n\ttoDelete := make([]string, 0)\n\tfor key, usageRecord := range tracker.usage {\n\t\tif !usageRecord.usingTooMany {\n\t\t\tusageRecord.using = filterOutOld(usageRecord.using, cutoff)\n\t\t}\n\t\tif !usageRecord.usedByTooMany {\n\t\t\tusageRecord.usedBy = filterOutOld(usageRecord.usedBy, cutoff)\n\t\t}\n\t\tif !usageRecord.usingTooMany && !usageRecord.usedByTooMany && len(usageRecord.using) == 0 && len(usageRecord.usedBy) == 0 {\n\t\t\ttoDelete = append(toDelete, key)\n\t\t}\n\t}\n\tfor _, key := range toDelete {\n\t\tdelete(tracker.usage, key)\n\t}\n}", "func DeleteEntry(interval float64) {\n\tfor {\n\t\tvar nodes []string\n\t\ttable.Range(func(key, value interface{}) bool {\n\t\t\tnewkey := fmt.Sprintf(\"%v\", key)\n\t\t\tnewvalue := value.(membership)\n\t\t\tif (float64(time.Now().Unix()-newvalue.Time) > interval && key != myid) || newvalue.Status == false {\n\t\t\t\tnodes = append(nodes, newkey)\n\t\t\t\tif newvalue.Status == true {\n\t\t\t\t\tFailuredet.Println(newkey)\n\t\t\t\t}\n\t\t\t\tChangeStatus(newkey)\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\t//the time between time out and clean\n\t\ttime.Sleep(2e9)\n\t\tfor _, node := range nodes {\n\t\t\ttable.Delete(node)\n\t\t\tip := getIpFromID(node)\n\t\t\treReplicate(indexOfstring(ip, straddr))\n\t\t}\n\t}\n}", "func (c *TwoQueueCache[K, V]) ensureSpace(recentEvict bool) {\n\t// If we have space, nothing to do\n\trecentLen := c.recent.Len()\n\tfreqLen := c.frequent.Len()\n\tif recentLen+freqLen < c.size {\n\t\treturn\n\t}\n\n\t// If the recent buffer is larger than\n\t// the target, evict from there\n\tif recentLen > 0 && (recentLen > c.recentSize || (recentLen == c.recentSize && !recentEvict)) {\n\t\tk, _, _ := c.recent.RemoveOldest()\n\t\tc.recentEvict.Add(k, struct{}{})\n\t\treturn\n\t}\n\n\t// Remove from the frequent list otherwise\n\tc.frequent.RemoveOldest()\n}", "func (a *App) Purge() {\r\n\t// As we gonna loop and change this varibale we\r\n\t// lock it during all the purging process\r\n\ta.Transactions.Lock()\r\n\tdefer a.Transactions.Unlock()\r\n\r\n\t// Eventhough that we only need to change\r\n\t// the stats in some cases, its ok to lock during\r\n\t// the entire process, so noone can access to\r\n\t// partial information\r\n\ta.Stats.Lock()\r\n\tdefer a.Stats.Unlock()\r\n\r\n\tnow := time.Now()\r\n\r\n\t// Loop while there are invalid txs\r\n\tfor {\r\n\t\tif len(a.Transactions.T) == 0 {\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\tpivot := a.Transactions.T[0]\r\n\r\n\t\t// If the last tx is in the PurgTime interval\r\n\t\t// then we are ok, no need to purge txs\r\n\t\tif now.Sub(pivot.Timestamp) < a.PurgeTime {\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\t// Update the stats\r\n\t\ta.Stats.S.Sum -= pivot.Amount\r\n\t\ta.Stats.S.Count -= 1\r\n\r\n\t\t// Update the average\r\n\t\tif a.Stats.S.Count == 0 {\r\n\t\t\ta.Stats.S.Avg = 0.0\r\n\t\t} else {\r\n\t\t\ta.Stats.S.Avg = a.Stats.S.Sum / float64(a.Stats.S.Count)\r\n\t\t}\r\n\r\n\t\t// Min update only when queue has elements\r\n\t\tif minQueueLen := len(a.Stats.S.MinQueue); minQueueLen > 0 {\r\n\t\t\ttmp := binaryDelete(a.Stats.S.MinQueue, pivot.Amount, descendingOrder)\r\n\t\t\ta.Stats.S.MinQueue = tmp\r\n\r\n\t\t\tif minQueueLen == 1 {\r\n\t\t\t\ta.Stats.S.Min = MaxFloat64\r\n\t\t\t} else {\r\n\t\t\t\ta.Stats.S.Min = a.Stats.S.MinQueue[minQueueLen-2]\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Max update, equivalent to the Min\r\n\t\tif maxQueueLen := len(a.Stats.S.MaxQueue); maxQueueLen > 0 {\r\n\t\t\ttmp := binaryDelete(a.Stats.S.MaxQueue, pivot.Amount, ascendingOrder)\r\n\t\t\ta.Stats.S.MaxQueue = tmp\r\n\r\n\t\t\tif maxQueueLen == 1 {\r\n\t\t\t\ta.Stats.S.Max = -MaxFloat64\r\n\t\t\t} else {\r\n\t\t\t\ta.Stats.S.Max = a.Stats.S.MaxQueue[maxQueueLen-2]\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Remove the old tx\r\n\t\ta.Transactions.T = a.Transactions.T[1:]\r\n\t}\r\n}", "func (et EntryType) IsInUse() bool {\n\treturn et&128 > 0\n}", "func (stackEntry *valuePayloadPropagationStackEntry) Release() {\n\tstackEntry.CachedPayload.Release()\n\tstackEntry.CachedPayloadMetadata.Release()\n\tstackEntry.CachedTransaction.Release()\n\tstackEntry.CachedTransactionMetadata.Release()\n}", "func (p *request) Release() {\n\tp.ctx = nil\n\tp.Entry = nil\n\tp.read = false\n\trequestPool.Put(p)\n}", "func (r *singleRule) deleteExpiredOnce() {\n\tr.usedRecordsIndex.Range(func(k, v interface{}) bool {\n\t\tr.locker.Lock()\n\t\tindex := v.(int)\n\t\tif index < len(r.records) && index >= 0 {\n\t\t\tr.records[index].deleteExpired()\n\t\t\tif r.records[index].usedSize() == 0 {\n\t\t\t\tr.usedRecordsIndex.Delete(k)\n\t\t\t\tr.notRecordsIndex[index] = struct{}{}\n\t\t\t}\n\t\t} else {\n\t\t\tr.usedRecordsIndex.Delete(k)\n\t\t}\n\t\tr.locker.Unlock()\n\t\treturn true\n\t})\n}", "func (rf *Raft) Kill() {\n atomic.StoreInt32(&rf.dead, 1)\n}", "func (pce *ppdCacheEntry) free() {\n\tpce.mutex.Lock()\n\tdefer pce.mutex.Unlock()\n\n\tC.free(unsafe.Pointer(pce.printername))\n}", "func (aio *AsyncIO) freeEvent(re *runningEvent, iocb *iocb, err error) error {\n\t// help gc free memory early\n\tre.data = nil\n\n\t// remove the iocb from running pool\n\taio.running.Remove(pointer2string(unsafe.Pointer(re.iocb)))\n\n\t// put the iocb back into the available pool\n\taio.available.Set(pointer2string(unsafe.Pointer(re.iocb)), re.iocb)\n\n\t// update the stat in request pool\n\tri, ok := aio.request.Get(int2string(int64(re.reqID)))\n\tif !ok {\n\t\treturn ErrReqIDNotFound\n\t}\n\tr, ok := ri.(*requestState)\n\tif !ok {\n\t\treturn ErrReqIDNotFound\n\t}\n\tr.done = true\n\tr.bytes = int64(re.wrote)\n\tif err != nil {\n\t\tr.err = err\n\t}\n\n\treturn nil\n}", "func (p *ResourcePool) doFree(a Alloc) error {\n\tid := a.ID()\n\tif p.allocs[id] != a {\n\t\treturn nil\n\t}\n\tdelete(p.allocs, id)\n\treturn p.manager.Kill(a)\n}", "func (p *ArgsEnvsCacheEntry) Release() {\n\tp.refCount--\n\tif p.refCount > 0 {\n\t\treturn\n\t}\n\n\tp.release()\n}", "func entryFinalizer(e *Entry) {\n\truntime.SetFinalizer(e, func(e *Entry) { gobject.Unref(e) })\n}", "func entryCompletionFinalizer(ec *EntryCompletion) {\n\truntime.SetFinalizer(ec, func(ec *EntryCompletion) { gobject.Unref(ec) })\n}", "func (p *Provider) GC(duration time.Duration) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\tfor {\n\t\telem := p.list.Back()\n\t\tif elem == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// if the time has passed. session was expired, then delete the session and its memory place\n\t\t// we are not destroy the session completely for the case this is re-used after\n\t\tsess := elem.Value.(*session)\n\t\tif time.Now().After(sess.lastAccessedTime.Add(duration)) {\n\t\t\tp.list.Remove(elem)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (x *Value) Free() {\n\tif x != nil && x.allocs23e8c9e3 != nil {\n\t\tx.allocs23e8c9e3.(*cgoAllocMap).Free()\n\t\tx.ref23e8c9e3 = nil\n\t}\n}", "func (px *Paxos) freeMemory() {\n // Assertion: px is already locked by the callee\n\n // reproduction of Min() without requesting a lock\n // Question: Can I do this without duplciating code?\n min := px.done[px.me]\n for i := 0; i < len(px.done); i++ {\n if px.done[i] < min {\n min = px.done[i]\n }\n }\n min += 1\n\n for i, _ := range px.Instances {\n if i < min {\n delete(px.Instances, i)\n }\n }\n}", "func (s *Memory) CleanEntries() {\n\tdefer s.lock()()\n\ts.entries = []logger.Entry{}\n}", "func (m *TimeServiceManager) Kill() {\n\tif len(m.Instances) > 0 {\n\t\tfmt.Printf(\"There are %d instances. \", len(m.Instances))\n\t\tn := rand.Intn(len(m.Instances))\n\t\tfmt.Printf(\"Killing Instance %d\\n\", n)\n\t\tclose(m.Instances[n].Dead)\n\t\tm.Instances = append(m.Instances[:n], m.Instances[n+1:]...)\n\t} else {\n\t\tfmt.Println(\"No instance to kill\")\n\t}\n}", "func (s *store) deleteAfter(cutoff time.Time) {\n\ts.DeleteExpiredKeys(cutoff)\n\ts.worldMu.Lock()\n\tdefer s.worldMu.Unlock()\n\n\t// When the length of the heap is zero, there are no more temporary\n\t// keys in it, therefore timer won't be started until a new record\n\t// will be added to a heap.\n\tif s.expireHeap.Len() == 0 {\n\t\treturn\n\t}\n\n\t// Peek next timer form the heap and schedule an expiration timer.\n\telem := s.expireHeap.Peek().(*timeHeapElement)\n\tlog.DebugLogf(\"store/DELETE_AFTER\",\n\t\t\"re-scheduling next run of timer in %s\", elem.Time)\n\ts.expireTimer.AfterFunc(elem.Time, func() {\n\t\ts.deleteAfter(elem.Time)\n\t})\n}", "func (c *ClusterStateImpl) deleteEntryOfAsg(asgName string) bool {\n\tdeleted := false\n\tClusterStateStore.Range(func(key interface{}, value interface{}) bool {\n\t\tkeyName, _ := key.(string)\n\t\tif strings.Contains(keyName, asgName) {\n\t\t\tClusterStateStore.Delete(keyName)\n\t\t\tdeleted = true\n\t\t}\n\t\treturn true\n\t})\n\treturn deleted\n}", "func (x *Size) Free() {\n\tif x != nil && x.allocs626288d != nil {\n\t\tx.allocs626288d.(*cgoAllocMap).Free()\n\t\tx.ref626288d = nil\n\t}\n}", "func (instance *cache) unsafeReserveEntry(key string) (xerr fail.Error) {\n\tif _, ok := instance.reserved[key]; ok {\n\t\treturn fail.NotAvailableError(\"the cache entry '%s' is already reserved\", key)\n\t}\n\tif _, ok := instance.cache[key]; ok {\n\t\treturn fail.DuplicateError(callstack.DecorateWith(\"\", \"\", fmt.Sprintf(\"there is already an entry in the cache with key '%s'\", key), 0))\n\t}\n\n\tce := newEntry(&reservation{key: key})\n\tce.lock()\n\tinstance.cache[key] = &ce\n\tinstance.reserved[key] = struct{}{}\n\treturn nil\n}", "func (rf *Raft) Kill() {\n atomic.StoreInt32(&rf.dead, 1)\n // Your code here, if desired.\n}", "func (d Data) Kill(key uint32) {\n\td.mutex.Lock()\n\tdelete(d.data, key)\n\tdelete(d.counts, key)\n\td.mutex.Unlock()\n}", "func RemoveEntryFromIPSet(setName string) {\n\t_, exists := ipsetInventoryMap[setName]\n\tif exists {\n\t\tnumIPSetEntries.Dec()\n\t\tipsetInventoryMap[setName]--\n\t\tif ipsetInventoryMap[setName] == 0 {\n\t\t\tremoveFromIPSetInventory(setName)\n\t\t} else {\n\t\t\tupdateIPSetInventory(setName)\n\t\t}\n\t}\n}", "func newTracker(maxAge, evaluationInterval time.Duration, minimumPortScanned int) (t *Tracker) {\n\tt = &Tracker{\n\t\tportScanners: make(chan *TrackerEntry),\n\t\tminimumPortScanned: minimumPortScanned,\n\t\tmaxAge: maxAge,\n\t\tm: make(map[string]*TrackerEntry),\n\t}\n\tgo func() {\n\t\tfor now := range time.Tick(evaluationInterval) {\n\t\t\tt.l.Lock()\n\t\t\tfor k, v := range t.m {\n\t\t\t\tif now.After(v.expiry) {\n\t\t\t\t\tlog.Infof(\"removing %q because entry is expired\", k)\n\t\t\t\t\tdelete(t.m, k)\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.l.Unlock()\n\t\t}\n\t}()\n\treturn\n}", "func (m *metricAerospikeNamespaceMemoryFree) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}", "func (c *Cache) purge() {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif c.onEvicted != nil {\n\t\tfor _, v := range c.getElements() {\n\t\t\tc.onEvicted(v.Value)\n\t\t}\n\t}\n\tc.evictList = list.New()\n}", "func (x *PDFXrefEntry) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}", "func (r *PackageRow) ClearAvailable() { r.Data.Available = nil }", "func (c *SimpleCache) processExpiry() {\n\tc.Lock.Lock()\n\tfor c.Queue.Len() > 0 && c.Queue.Items[0].ExpireAt < time.Now().Unix() {\n\t\tdelete(c.Data, c.Queue.Items[0].Key)\n\t\tc.Queue.pop()\n\t}\n\tc.Lock.Unlock()\n}" ]
[ "0.5817108", "0.5692876", "0.5678534", "0.5577531", "0.55638546", "0.5552982", "0.5491385", "0.5486231", "0.54780245", "0.546433", "0.5434327", "0.5383813", "0.53178895", "0.527339", "0.52312803", "0.5225152", "0.521923", "0.52158886", "0.5204025", "0.51703554", "0.51700693", "0.51532936", "0.5138599", "0.5115332", "0.50938725", "0.5077031", "0.50679064", "0.5043598", "0.5042831", "0.5037693", "0.500979", "0.5008076", "0.5007664", "0.5002541", "0.49755847", "0.49491644", "0.4945472", "0.4937342", "0.49307474", "0.49150243", "0.4899194", "0.4895903", "0.48935845", "0.489142", "0.4890285", "0.48815942", "0.48685825", "0.48640278", "0.48489362", "0.48453444", "0.48226616", "0.48193052", "0.4814924", "0.48147237", "0.481468", "0.48144463", "0.48036405", "0.48015758", "0.47909042", "0.47847626", "0.47777358", "0.47774857", "0.47772855", "0.4776392", "0.47729", "0.4772191", "0.47679392", "0.4767856", "0.47662473", "0.47543696", "0.47523063", "0.47517496", "0.47396588", "0.4735058", "0.47198987", "0.47182554", "0.47152677", "0.47075614", "0.47060764", "0.46964675", "0.469185", "0.4685979", "0.4679083", "0.4673764", "0.46680623", "0.4665832", "0.46556005", "0.46527258", "0.46498016", "0.4647705", "0.4642744", "0.4641483", "0.4641009", "0.46401143", "0.4639723", "0.4626225", "0.46258223", "0.4625099", "0.4622192", "0.46215096", "0.46196464" ]
0.0
-1
DefaultKeymap returns a copy of the default Keymap Useful if inspection/customization is needed.
func DefaultKeymap() Keymap { return Keymap{ ansi.NEWLINE: (*Core).Enter, ansi.CARRIAGE_RETURN: (*Core).Enter, ansi.CTRL_C: (*Core).Interrupt, ansi.CTRL_D: (*Core).DeleteOrEOF, ansi.CTRL_H: (*Core).Backspace, ansi.BACKSPACE: (*Core).Backspace, ansi.CTRL_L: (*Core).Clear, ansi.CTRL_T: (*Core).SwapChars, ansi.CTRL_B: (*Core).MoveLeft, ansi.CTRL_F: (*Core).MoveRight, ansi.CTRL_P: (*Core).HistoryBack, ansi.CTRL_N: (*Core).HistoryForward, ansi.CTRL_U: (*Core).CutLineLeft, ansi.CTRL_K: (*Core).CutLineRight, ansi.CTRL_A: (*Core).MoveBeginning, ansi.CTRL_E: (*Core).MoveEnd, ansi.CTRL_W: (*Core).CutPrevWord, ansi.CTRL_Y: (*Core).Paste, // Escape sequences ansi.START_ESCAPE_SEQ: nil, ansi.META_B: (*Core).MoveWordLeft, ansi.META_LEFT: (*Core).MoveWordLeft, ansi.META_F: (*Core).MoveWordRight, ansi.META_RIGHT: (*Core).MoveWordRight, ansi.LEFT: (*Core).MoveLeft, ansi.RIGHT: (*Core).MoveRight, ansi.UP: (*Core).HistoryBack, ansi.DOWN: (*Core).HistoryForward, // Extended escape ansi.START_EXTENDED_ESCAPE_SEQ: nil, ansi.START_EXTENDED_ESCAPE_SEQ_3: nil, ansi.DELETE: (*Core).Delete, // Delete key } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewDefaultKeyMap() *KeyMap {\n\treturn &KeyMap{\n\t\tYes: []string{\"y\", \"Y\"},\n\t\tNo: []string{\"n\", \"N\"},\n\t\tSelectYes: []string{\"left\"},\n\t\tSelectNo: []string{\"right\"},\n\t\tToggle: []string{\"tab\"},\n\t\tSubmit: []string{\"enter\"},\n\t\tAbort: []string{\"ctrl+c\"},\n\t}\n}", "func DefaultFuncMap() template.FuncMap {\n\treturn template.FuncMap{\n\t\t\"go\": ToGo,\n\t\t\"goPrivate\": ToGoPrivate,\n\t\t\"lcFirst\": LcFirst,\n\t\t\"ucFirst\": UcFirst,\n\t}\n}", "func NewDefaultMap[K comparable, V any](f func(K) V) DefaultMap[K, V] {\n\treturn DefaultMap[K, V]{map[K]V{}, f}\n}", "func DefaultClusterMap() *ClusterMap {\n\treturn &ClusterMap{\n\t\tMap: make(map[string]*Cluster),\n\t}\n}", "func (e *Env) DefineDefaultMap(k string) (interface{}, error) {\n\tv := make(map[interface{}]interface{})\n\treturn v, e.Define(k, v)\n}", "func (manager *KeysManager) DefaultKey() *jose.JSONWebKey {\n\tif len(manager.KeyList) > 0 {\n\t\treturn manager.KeyList[0]\n\t} else {\n\t\treturn nil\n\t}\n}", "func DefaultMapper() *MapConvert {\n\tonce.Do(func() {\n\t\tv := viper.New()\n\t\tv.SetConfigType(\"yaml\")\n\t\tv.ReadConfig(defaultMappings())\n\t\tdefaultMap = &MapConvert{}\n\t\tif v.IsSet(\"gc_types\") {\n\t\t\tdefaultMap.GCTypes = gcTypes(v, make([]string, 0))\n\t\t}\n\t\tif v.IsSet(\"memory_bytes\") {\n\t\t\tdefaultMap.MemoryTypes = memoryTypes(v, make(map[string]string))\n\t\t}\n\t})\n\treturn defaultMap\n}", "func NewDefaultIDSetMap() *DefaultIDSetMap {\n\treturn &DefaultIDSetMap{}\n}", "func (i GinJwtSignAlgorithm) KeyMap() map[GinJwtSignAlgorithm]string {\n\treturn _GinJwtSignAlgorithmValueToKeyMap\n}", "func NewMapEngineDefault() *MapEngine {\n\tindex := NewS2Storage(17, 35)\n\treturn &MapEngine{\n\t\tedges: make(map[int64]map[int64]*Edge),\n\t\tvertices: make(map[int64]*Vertex),\n\t\ts2Storage: index,\n\t}\n}", "func DefaultsToMap() common.StringMap {\n\tcurrentDefaults = Defaults()\n\tif currentDefaults.ShellPath == \"\" {\n\t\ttempPath, err := common.GetBashPath(\"\")\n\t\tif err == nil {\n\t\t\tcurrentDefaults.ShellPath = tempPath\n\t\t} else {\n\t\t\tcurrentDefaults.ShellPath = globals.ShellPathValue\n\t\t}\n\t}\n\treturn common.StringMap{\n\t\t\"Version\": currentDefaults.Version,\n\t\t\"version\": currentDefaults.Version,\n\t\t\"SandboxHome\": currentDefaults.SandboxHome,\n\t\t\"sandbox-home\": currentDefaults.SandboxHome,\n\t\t\"SandboxBinary\": currentDefaults.SandboxBinary,\n\t\t\"sandbox-binary\": currentDefaults.SandboxBinary,\n\t\t\"UseSandboxCatalog\": currentDefaults.UseSandboxCatalog,\n\t\t\"use-sandbox-catalog\": currentDefaults.UseSandboxCatalog,\n\t\t\"LogSBOperations\": currentDefaults.LogSBOperations,\n\t\t\"log-sb-operations\": currentDefaults.LogSBOperations,\n\t\t\"LogDirectory\": currentDefaults.LogDirectory,\n\t\t\"log-directory\": currentDefaults.LogDirectory,\n\t\t\"ShellPath\": currentDefaults.ShellPath,\n\t\t\"shell-path\": currentDefaults.ShellPath,\n\t\t\"CookbookDirectory\": currentDefaults.CookbookDirectory,\n\t\t\"cookbook-directory\": currentDefaults.CookbookDirectory,\n\t\t\"MasterSlaveBasePort\": currentDefaults.MasterSlaveBasePort,\n\t\t\"master-slave-base-port\": currentDefaults.MasterSlaveBasePort,\n\t\t\"GroupReplicationBasePort\": currentDefaults.GroupReplicationBasePort,\n\t\t\"group-replication-base-port\": currentDefaults.GroupReplicationBasePort,\n\t\t\"GroupReplicationSpBasePort\": currentDefaults.GroupReplicationSpBasePort,\n\t\t\"group-replication-sp-base-port\": currentDefaults.GroupReplicationSpBasePort,\n\t\t\"FanInReplicationBasePort\": currentDefaults.FanInReplicationBasePort,\n\t\t\"fan-in-replication-base-port\": currentDefaults.FanInReplicationBasePort,\n\t\t\"AllMastersReplicationBasePort\": currentDefaults.AllMastersReplicationBasePort,\n\t\t\"all-masters-replication-base-port\": currentDefaults.AllMastersReplicationBasePort,\n\t\t\"MultipleBasePort\": currentDefaults.MultipleBasePort,\n\t\t\"multiple-base-port\": currentDefaults.MultipleBasePort,\n\t\t\"PxcBasePort\": currentDefaults.PxcBasePort,\n\t\t\"pxc-base-port\": currentDefaults.PxcBasePort,\n\t\t\"NdbBasePort\": currentDefaults.NdbBasePort,\n\t\t\"ndb-base-port\": currentDefaults.NdbBasePort,\n\t\t\"NdbClusterPort\": currentDefaults.NdbClusterPort,\n\t\t\"ndb-cluster-port\": currentDefaults.NdbClusterPort,\n\t\t\"GroupPortDelta\": currentDefaults.GroupPortDelta,\n\t\t\"group-port-delta\": currentDefaults.GroupPortDelta,\n\t\t\"MysqlXPortDelta\": currentDefaults.MysqlXPortDelta,\n\t\t\"mysqlx-port-delta\": currentDefaults.MysqlXPortDelta,\n\t\t\"AdminPortDelta\": currentDefaults.AdminPortDelta,\n\t\t\"admin-port-delta\": currentDefaults.AdminPortDelta,\n\t\t\"MasterName\": currentDefaults.MasterName,\n\t\t\"master-name\": currentDefaults.MasterName,\n\t\t\"MasterAbbr\": currentDefaults.MasterAbbr,\n\t\t\"master-abbr\": currentDefaults.MasterAbbr,\n\t\t\"NodePrefix\": currentDefaults.NodePrefix,\n\t\t\"node-prefix\": currentDefaults.NodePrefix,\n\t\t\"SlavePrefix\": currentDefaults.SlavePrefix,\n\t\t\"slave-prefix\": currentDefaults.SlavePrefix,\n\t\t\"SlaveAbbr\": currentDefaults.SlaveAbbr,\n\t\t\"slave-abbr\": currentDefaults.SlaveAbbr,\n\t\t\"SandboxPrefix\": currentDefaults.SandboxPrefix,\n\t\t\"sandbox-prefix\": currentDefaults.SandboxPrefix,\n\t\t\"ImportedSandboxPrefix\": currentDefaults.ImportedSandboxPrefix,\n\t\t\"imported-sandbox-prefix\": currentDefaults.ImportedSandboxPrefix,\n\t\t\"MasterSlavePrefix\": currentDefaults.MasterSlavePrefix,\n\t\t\"master-slave-prefix\": currentDefaults.MasterSlavePrefix,\n\t\t\"GroupPrefix\": currentDefaults.GroupPrefix,\n\t\t\"group-prefix\": currentDefaults.GroupPrefix,\n\t\t\"GroupSpPrefix\": currentDefaults.GroupSpPrefix,\n\t\t\"group-sp-prefix\": currentDefaults.GroupSpPrefix,\n\t\t\"MultiplePrefix\": currentDefaults.MultiplePrefix,\n\t\t\"multiple-prefix\": currentDefaults.MultiplePrefix,\n\t\t\"FanInPrefix\": currentDefaults.FanInPrefix,\n\t\t\"fan-in-prefix\": currentDefaults.FanInPrefix,\n\t\t\"AllMastersPrefix\": currentDefaults.AllMastersPrefix,\n\t\t\"all-masters-prefix\": currentDefaults.AllMastersPrefix,\n\t\t\"ReservedPorts\": currentDefaults.ReservedPorts,\n\t\t\"reserved-ports\": currentDefaults.ReservedPorts,\n\t\t\"RemoteRepository\": currentDefaults.RemoteRepository,\n\t\t\"remote-repository\": currentDefaults.RemoteRepository,\n\t\t\"RemoteIndexFile\": currentDefaults.RemoteIndexFile,\n\t\t\"remote-index-file\": currentDefaults.RemoteIndexFile,\n\t\t\"RemoteCompletionUrl\": currentDefaults.RemoteCompletionUrl,\n\t\t\"remote-completion-url\": currentDefaults.RemoteCompletionUrl,\n\t\t\"RemoteTarballUrl\": currentDefaults.RemoteTarballUrl,\n\t\t\"remote-tarball-url\": currentDefaults.RemoteTarballUrl,\n\t\t\"remote-tarballs\": currentDefaults.RemoteTarballUrl,\n\t\t\"remote-github\": currentDefaults.RemoteTarballUrl,\n\t\t\"PxcPrefix\": currentDefaults.PxcPrefix,\n\t\t\"pxc-prefix\": currentDefaults.PxcPrefix,\n\t\t\"NdbPrefix\": currentDefaults.NdbPrefix,\n\t\t\"ndb-prefix\": currentDefaults.NdbPrefix,\n\t\t\"DefaultSandboxExecutable\": currentDefaults.DefaultSandboxExecutable,\n\t\t\"default-sandbox-executable\": currentDefaults.DefaultSandboxExecutable,\n\t\t\"download-url\": currentDefaults.DownloadUrl,\n\t\t\"DownloadUrl\": currentDefaults.DownloadUrl,\n\t\t\"download-name-macos\": currentDefaults.DownloadNameMacOs,\n\t\t\"DownloadNameMacOs\": currentDefaults.DownloadNameMacOs,\n\t\t\"download-name-linux\": currentDefaults.DownloadNameLinux,\n\t\t\"DownloadNameLinux\": currentDefaults.DownloadNameLinux,\n\t\t\"Timestamp\": currentDefaults.Timestamp,\n\t\t\"timestamp\": currentDefaults.Timestamp,\n\t}\n}", "func DefaultMetadataMap(objType string, hasPrivileges bool, hasOwner bool, hasComment bool, hasSecurityLabel bool) backup.MetadataMap {\n\treturn backup.MetadataMap{\n\t\tbackup.UniqueID{ClassID: ClassIDFromObjectName(objType), Oid: 1}: DefaultMetadata(objType, hasPrivileges, hasOwner, hasComment, hasSecurityLabel),\n\t}\n}", "func DefaultKeyGetter(c *gin.Context) (string, bool) {\n\treturn c.ClientIP(), true\n}", "func KeyToDefaultPath(key Key) (string, error) {\n\treturn key.defaultPath()\n}", "func (i SNSProtocol) KeyMap() map[SNSProtocol]string {\n\treturn _SNSProtocolValueToKeyMap\n}", "func (me XsdGoPkgHasElems_Key) KeyDefault() TstyleStateEnumType { return TstyleStateEnumType(\"normal\") }", "func IsDefaultKey(key string) bool {\n\tfor _, k := range defaultKeys {\n\t\tif k == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func DefaultConfigMapName(controllerName string) string {\n\treturn fmt.Sprintf(\"%s-configmap\", controllerName)\n}", "func DefaultConfigMapName(controllerName string) string {\n\treturn fmt.Sprintf(\"%s-configmap\", controllerName)\n}", "func NewMap(store map[string]*rsa.PrivateKey) *KeyStore {\n\treturn &KeyStore{\n\t\tstore: store,\n\t}\n}", "func (i GinBindType) KeyMap() map[GinBindType]string {\n\treturn _GinBindTypeValueToKeyMap\n}", "func (me XsdGoPkgHasElem_Key) KeyDefault() TstyleStateEnumType { return TstyleStateEnumType(\"normal\") }", "func getDefaultKey(keystore string) (string, error) {\n\n\tfiles, err := ioutil.ReadDir(keystore)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar monikers []string\n\n\tfor _, file := range files {\n\t\tif filepath.Ext(file.Name()) == \".json\" {\n\t\t\tmonikers = append(monikers, strings.TrimSuffix(\n\t\t\t\tfile.Name(),\n\t\t\t\tfilepath.Ext(file.Name()),\n\t\t\t))\n\t\t}\n\t}\n\n\tif len(monikers) == 0 {\n\t\treturn \"\", errors.New(\"No keys found. Use 'monet keys new' to generate keys \")\n\t}\n\n\tif len(monikers) == 1 {\n\t\treturn monikers[0], nil\n\t}\n\n\tcommon.ErrorMessage(\"You have multiple available keys. Specify one using the --key parameter.\")\n\tcommon.InfoMessage(monikers)\n\n\treturn \"\", errors.New(\"key to use is ambiguous\")\n\n}", "func (w *Wallet) defaultScopeManagers() (\n\tmap[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager, er.R) {\n\n\tscopedMgrs := make(map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager)\n\tfor _, scope := range waddrmgr.DefaultKeyScopes {\n\t\tscopedMgr, err := w.Manager.FetchScopedKeyManager(scope)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tscopedMgrs[scope] = scopedMgr\n\t}\n\n\treturn scopedMgrs, nil\n}", "func (o BucketEncryptionOutput) DefaultKmsKeyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketEncryption) *string { return v.DefaultKmsKeyName }).(pulumi.StringPtrOutput)\n}", "func (o *UserDisco) SetDefaultKeyId(v string) {\n\to.DefaultKeyId = &v\n}", "func (ini INI) DefaultSectionGetKey(k string) (string, error) {\n\treturn ini.SectionGetKey(defaultSection, k)\n}", "func (m Map) HasDefault() bool {\n\treturn true\n}", "func GetAuthDefaultSettingsConfigMap() *corev1.ConfigMap {\n\treturn &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: SettingsAuthConfigMapName,\n\t\t\tNamespace: SettingsAuthConfigMapNamespace,\n\t\t},\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: ConfigMapKindName,\n\t\t\tAPIVersion: ConfigMapAPIVersion,\n\t\t},\n\t\tData: GetAuthDefaultSettings().GetData(),\n\t}\n}", "func (info Terminfo) KeyMap() map[string]string {\n\tr := make(map[string]string, maxKeys)\n\tr[\"F1\"] = info.Keys[KeyF1]\n\tr[\"F2\"] = info.Keys[KeyF2]\n\tr[\"F3\"] = info.Keys[KeyF3]\n\tr[\"F4\"] = info.Keys[KeyF4]\n\tr[\"F5\"] = info.Keys[KeyF5]\n\tr[\"F6\"] = info.Keys[KeyF6]\n\tr[\"F7\"] = info.Keys[KeyF7]\n\tr[\"F8\"] = info.Keys[KeyF8]\n\tr[\"F9\"] = info.Keys[KeyF9]\n\tr[\"F10\"] = info.Keys[KeyF10]\n\tr[\"F11\"] = info.Keys[KeyF11]\n\tr[\"F12\"] = info.Keys[KeyF12]\n\tr[\"Insert\"] = info.Keys[KeyInsert]\n\tr[\"Delete\"] = info.Keys[KeyDelete]\n\tr[\"Home\"] = info.Keys[KeyHome]\n\tr[\"End\"] = info.Keys[KeyEnd]\n\tr[\"PageUp\"] = info.Keys[KeyPageUp]\n\tr[\"PageDown\"] = info.Keys[KeyPageDown]\n\tr[\"Up\"] = info.Keys[KeyUp]\n\tr[\"Down\"] = info.Keys[KeyDown]\n\tr[\"Left\"] = info.Keys[KeyLeft]\n\tr[\"Right\"] = info.Keys[KeyRight]\n\treturn r\n}", "func UseDefaultKey(value bool) Option {\n\treturn option.New(optkeyDefault, value)\n}", "func (o SparseDependencyMapsList) DefaultOrder() []string {\n\n\treturn []string{}\n}", "func (j *DSRocketchat) UseDefaultMapping(ctx *Ctx, raw bool) bool {\n\treturn true\n}", "func GetDefaultKeyFilePath() string {\n\tif runtime.GOOS == \"windows\" {\n\t\treturn windowsServerKeyPath\n\t}\n\treturn nixServerKeyPath\n}", "func (i SNSPlatformApplicationAttribute) KeyMap() map[SNSPlatformApplicationAttribute]string {\n\treturn _SNSPlatformApplicationAttributeValueToKeyMap\n}", "func (o BucketEncryptionPtrOutput) DefaultKmsKeyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketEncryption) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.DefaultKmsKeyName\n\t}).(pulumi.StringPtrOutput)\n}", "func (j *DSGit) UseDefaultMapping(ctx *Ctx, raw bool) bool {\n\treturn raw\n}", "func (o BucketEncryptionPtrOutput) DefaultKmsKeyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketEncryption) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.DefaultKmsKeyName\n\t}).(pulumi.StringPtrOutput)\n}", "func GetMapKey(UsernameHashed, PasswordHashed string) []byte {\r\n\treturn []byte(path.Join(keyPrefix4SubTree, UsernameHashed, PasswordHashed))\r\n}", "func WithDefaultKeyFile(keyFile string, isPublic bool) string {\n\tvar err error\n\n\tif keyFile != \"\" {\n\t\treturn VerifySigningKeyInput(keyFile, isPublic)\n\t}\n\t// get default file names if input is empty\n\tif keyFile, err = GetDefaultSigningKeyFile(isPublic); err != nil {\n\t\tFatal(CLI_GENERAL_ERROR, err.Error())\n\t\t// convert to absolute path\n\t} else if keyFile, err = filepath.Abs(keyFile); err != nil {\n\t\tFatal(CLI_GENERAL_ERROR, i18n.GetMessagePrinter().Sprintf(\"Failed to get absolute path for file %v. %v\", keyFile, err))\n\t\t// check file exist\n\t} else if _, err := os.Stat(keyFile); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn \"\"\n\t\t} else {\n\t\t\tFatal(CLI_GENERAL_ERROR, i18n.GetMessagePrinter().Sprintf(\"Error checking absolute path for file %v. %v\", keyFile, err))\n\t\t}\n\t}\n\treturn keyFile\n}", "func (DummyStore) GetMap(key string) (map[string]interface{}, error) {\n\treturn nil, nil\n}", "func (o BucketEncryptionOutput) DefaultKmsKeyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketEncryption) string { return v.DefaultKmsKeyName }).(pulumi.StringOutput)\n}", "func (o DependencyMapsList) DefaultOrder() []string {\n\n\treturn []string{}\n}", "func GetKeys(data map[string]string) []string {\n\tkeys := defaultKeys\n\tif data != nil && len(data) > len(defaultKeys) {\n\t\tfor name := range data {\n\t\t\tif !IsDefaultKey(name) {\n\t\t\t\tkeys = append(keys, name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn keys\n}", "func Map() map[string]interface{} {\n\treturn DefaultConfig.Map()\n}", "func (o *DependencyMap) DefaultOrder() []string {\n\n\treturn []string{}\n}", "func (e EnvironmentImageMapV0) WithDefaults() interface{} {\n\tcpu := CPUImage\n\tgpu := GPUImage\n\tif e.RawCPU != nil {\n\t\tcpu = *e.RawCPU\n\t}\n\tif e.RawGPU != nil {\n\t\tgpu = *e.RawGPU\n\t}\n\treturn EnvironmentImageMapV0{RawCPU: &cpu, RawGPU: &gpu}\n}", "func DefaultQueueKeysFunc(_ runtime.Object) []string {\n\treturn []string{DefaultQueueKey}\n}", "func NewGetKeyPairsDefault(code int) *GetKeyPairsDefault {\n\treturn &GetKeyPairsDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (svc *ServiceDefinition) ProvisionDefaultOverrides() map[string]interface{} {\n\treturn viper.GetStringMap(svc.ProvisionDefaultOverrideProperty())\n}", "func SetDefaultAttributes(attrOriginal map[string]string) (map[string]string, error) {\n\tattr := make(map[string]string)\n\tfor k, v := range attrOriginal {\n\t\tattr[k] = v\n\t}\n\n\tsetDefaultIfEmpty(attr, csiapi.IssuerKindKey, cmapi.IssuerKind)\n\tsetDefaultIfEmpty(attr, csiapi.IssuerGroupKey, certmanager.GroupName)\n\n\tsetDefaultIfEmpty(attr, csiapi.IsCAKey, \"false\")\n\tsetDefaultIfEmpty(attr, csiapi.DurationKey, cmapi.DefaultCertificateDuration.String())\n\n\tsetDefaultIfEmpty(attr, csiapi.CAFileKey, \"ca.crt\")\n\tsetDefaultIfEmpty(attr, csiapi.CertFileKey, \"tls.crt\")\n\tsetDefaultIfEmpty(attr, csiapi.KeyFileKey, \"tls.key\")\n\n\tsetDefaultIfEmpty(attr, csiapi.KeyUsagesKey, strings.Join([]string{string(cmapi.UsageDigitalSignature), string(cmapi.UsageKeyEncipherment)}, \",\"))\n\n\treturn attr, nil\n}", "func (j *DSGitHub) UseDefaultMapping(ctx *Ctx, raw bool) bool {\n\treturn raw\n}", "func New() Hashmap {\n\treturn Hashmap{make([]node, defaultSize), defaultSize, 0}\n}", "func (o SparseOAUTHKeysList) DefaultOrder() []string {\n\n\treturn []string{}\n}", "func New() *OMap {\n\treturn &OMap{\n\t\tkeys: make([]string, 0),\n\t\tbaseMap: make(map[string]interface{}, 0),\n\t}\n}", "func (i SNSSubscribeAttribute) KeyMap() map[SNSSubscribeAttribute]string {\n\treturn _SNSSubscribeAttributeValueToKeyMap\n}", "func DefaultClient() *Client {\n\treturn &Client{Key}\n}", "func NewAccessKeyWithDefaults() *AccessKey {\n\tthis := AccessKey{}\n\treturn &this\n}", "func DefaultRedisConfiguration() map[string]string {\n\treturn map[string]string{\"redis.conf\": redisConfContent}\n}", "func GetDefaultSigningKeyFile(isPublic bool) (string, error) {\n\t// we have to use $HOME for now because os/user is not implemented on some plateforms\n\thome_dir := os.Getenv(\"HOME\")\n\tif home_dir == \"\" {\n\t\thome_dir = \"/tmp/keys\"\n\t}\n\n\tif isPublic {\n\t\treturn filepath.Join(home_dir, DEFAULT_PUBLIC_KEY_FILE), nil\n\t} else {\n\t\treturn filepath.Join(home_dir, DEFAULT_PRIVATE_KEY_FILE), nil\n\t}\n}", "func (ss SectionSlice) Defaults() DefaultMap {\n\tvar dm = make(DefaultMap)\n\tfor _, s := range ss {\n\t\tfor _, g := range s.Groups {\n\t\t\tfor _, f := range g.Fields {\n\t\t\t\tdm[ScopeKey(Path(s.ID, g.ID, f.ID))] = f.Default\n\t\t\t}\n\t\t}\n\t}\n\treturn dm\n}", "func DefaultJWKS() []byte {\n\t// Create a temporary file containing the JSON web key set:\n\tbigE := big.NewInt(int64(jwtPublicKey.E))\n\tbigN := jwtPublicKey.N\n\treturn []byte(fmt.Sprintf(\n\t\t`{\n\t\t\t\"keys\": [{\n\t\t\t\t\"kid\": \"123\",\n\t\t\t\t\"kty\": \"RSA\",\n\t\t\t\t\"alg\": \"RS256\",\n\t\t\t\t\"e\": \"%s\",\n\t\t\t\t\"n\": \"%s\"\n\t\t\t}]\n\t\t}`,\n\t\tbase64.RawURLEncoding.EncodeToString(bigE.Bytes()),\n\t\tbase64.RawURLEncoding.EncodeToString(bigN.Bytes()),\n\t))\n}", "func (ini INI) DefaultSectionGet() (map[string]string, error) {\n\treturn ini.SectionGet(defaultSection)\n}", "func testAccAwsEbsDefaultKmsKeyAwsManagedDefaultKey() (*arn.ARN, error) {\n\tconn := testAccProvider.Meta().(*AWSClient).kmsconn\n\n\talias, err := findKmsAliasByName(conn, \"alias/aws/ebs\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taliasARN, err := arn.Parse(aws.StringValue(alias.AliasArn))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tarn := arn.ARN{\n\t\tPartition: aliasARN.Partition,\n\t\tService: aliasARN.Service,\n\t\tRegion: aliasARN.Region,\n\t\tAccountID: aliasARN.AccountID,\n\t\tResource: fmt.Sprintf(\"key/%s\", aws.StringValue(alias.TargetKeyId)),\n\t}\n\n\treturn &arn, nil\n}", "func NewGameMap() GameMap {\n\t//Return a new game map of a single level for now\n\tl := NewLevel()\n\tlevels := make([]Level, 0)\n\tlevels = append(levels, l)\n\td := Dungeon{Name: \"default\", Levels: levels}\n\tdungeons := make([]Dungeon, 0)\n\tdungeons = append(dungeons, d)\n\tgm := GameMap{Dungeons: dungeons, CurrentLevel: l}\n\treturn gm\n\n}", "func GetKeyTagMap(src map[string]interface{}) map[string]interface{} {\n\tres := NewEmptyTagMap()\n\tres[\"inname\"] = \"key\"\n\tres[\"exname\"] = \"key\"\n\tres[\"type\"] = src[\"keytype\"]\n\tres[\"length\"] = src[\"keylength\"]\n\tres[\"scale\"] = src[\"keyscale\"]\n\tres[\"precision\"] = src[\"keyprecision\"]\n\tres[\"fieldid\"] = src[\"keyfieldid\"]\n\treturn res\n}", "func DefaultTables() IPTables {\n\treturn IPTables{\n\t\tTables: map[string]Table{\n\t\t\ttablenameNat: Table{\n\t\t\t\tBuiltinChains: map[Hook]Chain{\n\t\t\t\t\tPrerouting: unconditionalAcceptChain(chainNamePrerouting),\n\t\t\t\t\tInput: unconditionalAcceptChain(chainNameInput),\n\t\t\t\t\tOutput: unconditionalAcceptChain(chainNameOutput),\n\t\t\t\t\tPostrouting: unconditionalAcceptChain(chainNamePostrouting),\n\t\t\t\t},\n\t\t\t\tDefaultTargets: map[Hook]Target{\n\t\t\t\t\tPrerouting: UnconditionalAcceptTarget{},\n\t\t\t\t\tInput: UnconditionalAcceptTarget{},\n\t\t\t\t\tOutput: UnconditionalAcceptTarget{},\n\t\t\t\t\tPostrouting: UnconditionalAcceptTarget{},\n\t\t\t\t},\n\t\t\t\tUserChains: map[string]Chain{},\n\t\t\t},\n\t\t\ttablenameMangle: Table{\n\t\t\t\tBuiltinChains: map[Hook]Chain{\n\t\t\t\t\tPrerouting: unconditionalAcceptChain(chainNamePrerouting),\n\t\t\t\t\tOutput: unconditionalAcceptChain(chainNameOutput),\n\t\t\t\t},\n\t\t\t\tDefaultTargets: map[Hook]Target{\n\t\t\t\t\tPrerouting: UnconditionalAcceptTarget{},\n\t\t\t\t\tOutput: UnconditionalAcceptTarget{},\n\t\t\t\t},\n\t\t\t\tUserChains: map[string]Chain{},\n\t\t\t},\n\t\t},\n\t\tPriorities: map[Hook][]string{\n\t\t\tPrerouting: []string{tablenameMangle, tablenameNat},\n\t\t\tOutput: []string{tablenameMangle, tablenameNat},\n\t\t},\n\t}\n}", "func DefaultIDSetMapWith(m map[int]*IDSet) *DefaultIDSetMap {\n\treturn &DefaultIDSetMap{m: m}\n}", "func New() hctx.Map {\n\treturn hctx.Map{\n\t\tPathForKey: PathFor,\n\t}\n}", "func (config *wrapper) GetPrefixedMap(section string, prefix string) map[string]string {\n\tvals := config.cfg.Section(section).KeysHash()\n\tvar output = make(map[string]string)\n\tfor key, val := range vals {\n\t\tif strings.HasPrefix(key, prefix) {\n\t\t\toutput[strings.Replace(key, prefix+\".\", \"\", 1)] = val\n\t\t}\n\t}\n\treturn output\n}", "func New() Map {\n\treturn empty\n}", "func (_Votes *VotesCallerSession) LogKeyDefault() (string, error) {\n\treturn _Votes.Contract.LogKeyDefault(&_Votes.CallOpts)\n}", "func DefaultParams() *Params {\n\tp := Params{\n\t\tKeyLength: 512,\n\t\tInternalSaltLength: 256,\n\t\tExternalSaltLength: 256,\n\t\tArgon2Memory: 64 * 1024,\n\t\tArgon2Iterations: 3,\n\t\tArgon2Parallelism: 4}\n\treturn &p\n}", "func (_Votes *VotesSession) LogKeyDefault() (string, error) {\n\treturn _Votes.Contract.LogKeyDefault(&_Votes.CallOpts)\n}", "func (o IopingSpecVolumeVolumeSourceConfigMapOutput) DefaultMode() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceConfigMap) *int { return v.DefaultMode }).(pulumi.IntPtrOutput)\n}", "func flattenUrlMapDefaultRouteActionRequestMirrorPolicyMap(c *Client, i interface{}) map[string]UrlMapDefaultRouteActionRequestMirrorPolicy {\n\ta, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn map[string]UrlMapDefaultRouteActionRequestMirrorPolicy{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn map[string]UrlMapDefaultRouteActionRequestMirrorPolicy{}\n\t}\n\n\titems := make(map[string]UrlMapDefaultRouteActionRequestMirrorPolicy)\n\tfor k, item := range a {\n\t\titems[k] = *flattenUrlMapDefaultRouteActionRequestMirrorPolicy(c, item.(map[string]interface{}))\n\t}\n\n\treturn items\n}", "func (a KeyAlgorithm) DefaultSize() int {\n\tswitch a {\n\tcase ECDSAKey:\n\t\treturn 256\n\tcase RSAKey:\n\t\treturn 4096\n\t}\n\treturn 0\n}", "func (_Votes *VotesCaller) LogKeyDefault(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _Votes.contract.Call(opts, out, \"logKeyDefault\")\n\treturn *ret0, err\n}", "func KeyToDefaultDeletePath(key Key) (string, error) {\n\treturn key.defaultDeletePath()\n}", "func DefaultMainKubeClient(metricStorage *metric_storage.MetricStorage, metricLabels map[string]string) klient.Client {\n\tclient := klient.New()\n\tclient.WithContextName(app.KubeContext)\n\tclient.WithConfigPath(app.KubeConfig)\n\tclient.WithRateLimiterSettings(app.KubeClientQps, app.KubeClientBurst)\n\tclient.WithMetricStorage(metricStorage)\n\tclient.WithMetricLabels(DefaultIfEmpty(metricLabels, DefaultMainKubeClientMetricLabels))\n\treturn client\n}", "func (o BucketEncryptionResponseOutput) DefaultKmsKeyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketEncryptionResponse) string { return v.DefaultKmsKeyName }).(pulumi.StringOutput)\n}", "func (o *OAUTHKey) DefaultOrder() []string {\n\n\treturn []string{}\n}", "func (o OAUTHKeysList) DefaultOrder() []string {\n\n\treturn []string{}\n}", "func (r *KeystoneAPI) Default() {\n\tkeystoneapilog.Info(\"default\", \"name\", r.Name)\n\n\tr.Spec.Default()\n}", "func DefaultSignerOptions() SignerOptions {\n\treturn SignerOptions{\n\t\tConfigMapNamespace: api.NamespacePublic,\n\t\tConfigMapName: bootstrapapi.ConfigMapClusterInfo,\n\t\tTokenSecretNamespace: api.NamespaceSystem,\n\t}\n}", "func flattenUrlMapDefaultRouteActionMap(c *Client, i interface{}) map[string]UrlMapDefaultRouteAction {\n\ta, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn map[string]UrlMapDefaultRouteAction{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn map[string]UrlMapDefaultRouteAction{}\n\t}\n\n\titems := make(map[string]UrlMapDefaultRouteAction)\n\tfor k, item := range a {\n\t\titems[k] = *flattenUrlMapDefaultRouteAction(c, item.(map[string]interface{}))\n\t}\n\n\treturn items\n}", "func (r *K3sControlPlaneTemplate) Default() {\n\tinfrabootstrapv1.DefaultK3sConfigSpec(&r.Spec.Template.Spec.K3sConfigSpec)\n\n\tr.Spec.Template.Spec.RolloutStrategy = defaultRolloutStrategy(r.Spec.Template.Spec.RolloutStrategy)\n}", "func Default(key string, value interface{}) {\n\tviper.SetDefault(key, value)\n}", "func flattenUrlMapDefaultUrlRedirectMap(c *Client, i interface{}) map[string]UrlMapDefaultUrlRedirect {\n\ta, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn map[string]UrlMapDefaultUrlRedirect{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn map[string]UrlMapDefaultUrlRedirect{}\n\t}\n\n\titems := make(map[string]UrlMapDefaultUrlRedirect)\n\tfor k, item := range a {\n\t\titems[k] = *flattenUrlMapDefaultUrlRedirect(c, item.(map[string]interface{}))\n\t}\n\n\treturn items\n}", "func newMap() map[interface{}]interface{} {\n\treturn map[interface{}]interface{}{}\n}", "func NewApiKeyWithDefaults() *ApiKey {\n\tthis := ApiKey{}\n\treturn &this\n}", "func getDefaultVariables() (defaultVariables map[string]string, err error) {\n\tdefaultVariables = make(map[string]string)\n\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn defaultVariables, err\n\t}\n\tdefaultVariables[\"workdir\"] = dir\n\n\tdefaultVariables[\"date\"] = time.Now().Format(\"2006-01-02\")\n\n\treturn defaultVariables, nil\n}", "func NewDeleteAPIKeyDefault(code int) *DeleteAPIKeyDefault {\n\treturn &DeleteAPIKeyDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (p *stdinParser) defineKeyMap(key prompt.Key, remapped []byte) {\n\tp.keyMap[key] = remapped\n}", "func NewMap() Map {\n\treturn &sortedMap{}\n}", "func (c *ConfigPolicyNode) Defaults() map[string]ctypes.ConfigValue {\n\tdefaults := map[string]ctypes.ConfigValue{}\n\tfor name, rule := range c.rules {\n\t\tif def := rule.Default(); def != nil {\n\t\t\tdefaults[name] = def\n\t\t}\n\t}\n\treturn defaults\n}", "func (ini INI) DefaultSectionSetKey(k, v string) {\n\tini.SectionSetKey(defaultSection, k, v)\n}", "func NewDefaultCommand() *cobra.Command {\n\tcmd := cobra.Command{\n\t\tUse: path.Base(os.Args[0]),\n\t\tShort: \"kwir\",\n\t\tLong: \"Kube Webhook Image Rewriter (kwir) is a mutating admission webhook manager that rewrites container's images based on config rules\",\n\t\tSilenceUsage: true,\n\t}\n\n\tviper.SetEnvPrefix(\"KWIR\")\n\tviper.AutomaticEnv()\n\n\tcmd.AddCommand(newVersionCommand())\n\tcmd.AddCommand(newKwirCommand())\n\n\treturn &cmd\n}", "func (o FioSpecVolumeVolumeSourceConfigMapOutput) DefaultMode() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceConfigMap) *int { return v.DefaultMode }).(pulumi.IntPtrOutput)\n}", "func NewDefaultDialedKlient() (*Klient, error) {\n\treturn NewDialedKlient(NewKlientOptions())\n}" ]
[ "0.74792606", "0.6471782", "0.6430026", "0.6413645", "0.6204454", "0.6148289", "0.611857", "0.5991836", "0.5914652", "0.5903464", "0.5883921", "0.5832911", "0.5769057", "0.56442523", "0.5629255", "0.5577586", "0.5549471", "0.54746073", "0.54746073", "0.5446178", "0.5425417", "0.5406213", "0.534115", "0.5318725", "0.53133285", "0.52719474", "0.5269875", "0.5261475", "0.5217889", "0.5213057", "0.5203952", "0.52035445", "0.51935315", "0.5191167", "0.51782024", "0.5156804", "0.514897", "0.5141691", "0.5138247", "0.51291996", "0.51004213", "0.50958604", "0.5088658", "0.5086607", "0.5081069", "0.50724053", "0.5069452", "0.5065091", "0.50628906", "0.50572604", "0.50545615", "0.504717", "0.50462055", "0.50005025", "0.49968633", "0.49833518", "0.4976506", "0.49658534", "0.49532133", "0.4951803", "0.49498254", "0.4947625", "0.49408066", "0.49400422", "0.4936101", "0.491658", "0.49161804", "0.49071544", "0.4896566", "0.4896158", "0.4882244", "0.48786098", "0.48753935", "0.48707289", "0.485968", "0.48514432", "0.48445648", "0.48437673", "0.48400757", "0.4837579", "0.48264623", "0.48240608", "0.48115796", "0.4804841", "0.4801652", "0.47947064", "0.47924456", "0.47923145", "0.47904825", "0.47898263", "0.47849193", "0.47823483", "0.47818667", "0.4774752", "0.4769102", "0.47655874", "0.47623134", "0.47618613", "0.47589937", "0.47382155" ]
0.75022745
0
CreateFileSystem invokes the dfs.CreateFileSystem API synchronously
func (client *Client) CreateFileSystem(request *CreateFileSystemRequest) (response *CreateFileSystemResponse, err error) { response = CreateCreateFileSystemResponse() err = client.DoAction(request, response) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (manager *mockFileSystemManager) CreateFileSystem(ctx context.Context, groupName string, filesystemName string, timeout *int32, xMsDate string, datalakeName string) (*autorest.Response, error) {\n\tfs := fileSystemResource{\n\t\tresourceGroupName: groupName,\n\t\tstorageAccountName: datalakeName,\n\t\tfilesystemName: filesystemName,\n\t}\n\n\tmanager.fileSystemResource = append(manager.fileSystemResource, fs)\n\tmockresponse := helpers.GetRestResponse(http.StatusOK)\n\n\treturn &mockresponse, nil\n}", "func (client StorageGatewayClient) CreateFileSystem(ctx context.Context, request CreateFileSystemRequest) (response CreateFileSystemResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\n\tif !(request.OpcRetryToken != nil && *request.OpcRetryToken != \"\") {\n\t\trequest.OpcRetryToken = common.String(common.RetryToken())\n\t}\n\n\tociResponse, err = common.Retry(ctx, request, client.createFileSystem, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = CreateFileSystemResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = CreateFileSystemResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(CreateFileSystemResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into CreateFileSystemResponse\")\n\t}\n\treturn\n}", "func (z *zfsctl) CreateFileSystem(ctx context.Context, name string, properties map[string]string) *execute {\n\targs := []string{\"create\", \"-p\"}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (c *MockFileStorageClient) CreateFileSystem(ctx context.Context, details filestorage.CreateFileSystemDetails) (*filestorage.FileSystem, error) {\n\treturn &filestorage.FileSystem{Id: &fileSystemID}, nil\n}", "func FileSystemCreate(f types.Filesystem) error {\n\tvar cmd *exec.Cmd\n\tvar debugCMD string\n\n\tswitch f.Mount.Format {\n\tcase \"swap\":\n\t\tcmd = exec.Command(\"/sbin/mkswap\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkswap\", f.Mount.Device)\n\tcase \"ext4\", \"ext3\", \"ext2\":\n\t\t// Add filesystem flags\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-t\")\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Format)\n\n\t\t// Add force\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-F\")\n\n\t\t// Add Device to formate\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Device)\n\n\t\t// Format disk\n\t\tcmd = exec.Command(\"/sbin/mke2fs\", f.Mount.Create.Options...)\n\t\tfor i := range f.Mount.Create.Options {\n\t\t\tdebugCMD = fmt.Sprintf(\"%s %s\", debugCMD, f.Mount.Create.Options[i])\n\t\t}\n\tcase \"vfat\":\n\t\tcmd = exec.Command(\"/sbin/mkfs.fat\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkfs.fat\", f.Mount.Device)\n\tdefault:\n\t\tlog.Warnf(\"Unknown filesystem type [%s]\", f.Mount.Format)\n\t}\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\n\treturn nil\n}", "func (client *Client) CreateFileSystemWithCallback(request *CreateFileSystemRequest, callback func(response *CreateFileSystemResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFileSystemResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFileSystem(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client StorageGatewayClient) createFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (client *Client) CreateFileSystemWithChan(request *CreateFileSystemRequest) (<-chan *CreateFileSystemResponse, <-chan error) {\n\tresponseChan := make(chan *CreateFileSystemResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateFileSystem(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func CreateCreateFileSystemRequest() (request *CreateFileSystemRequest) {\n\trequest = &CreateFileSystemRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"CreateFileSystem\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateFileSystemInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateFileSystem\", params, optFns, c.addOperationCreateFileSystemMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateFileSystemOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func CreateFilesystem(e *efs.EFS, n string) (*efs.FileSystemDescription, error) {\n\tcreateParams := &efs.CreateFileSystemInput{\n\t\tCreationToken: aws.String(n),\n\t}\n\tcreateResp, err := e.CreateFileSystem(createParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for the filesystem to become available.\n\tfor {\n\t\tfs, err := DescribeFilesystem(e, n)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(fs.FileSystems) > 0 {\n\t\t\tif *fs.FileSystems[0].LifeCycleState == efsAvail {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n\treturn createResp, nil\n}", "func (*FileSystemBase) Create(path string, flags int, mode uint32) (int, uint64) {\n\treturn -ENOSYS, ^uint64(0)\n}", "func (fsOnDisk) Create(name string) (File, error) { return os.Create(name) }", "func (z *ZfsH) CreateFilesystem(name string, properties map[string]string) (*Dataset, error) {\n\targs := make([]string, 1, 4)\n\targs[0] = \"create\"\n\n\tif properties != nil {\n\t\targs = append(args, propsSlice(properties)...)\n\t}\n\n\targs = append(args, name)\n\t_, err := z.zfs(args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn z.GetDataset(name)\n}", "func MakeFsOnDisk() FileSystem { return filesys.MakeFsOnDisk() }", "func (realFS) Create(name string) (File, error) { return os.Create(name) }", "func (fs *FileSystem) Create(name string) (afero.File, error) {\n\tlogger.Println(\"Create\", name)\n\tname = normalizePath(name)\n\tpath := filepath.Dir(name)\n\n\tif err := fs.MkdirAll(path, os.ModeDir); err != nil {\n\t\treturn nil, &os.PathError{Op: \"create\", Path: name, Err: err}\n\t}\n\n\tfs.Lock()\n\tfileData := CreateFile(name)\n\tfs.data[name] = fileData\n\tfs.Unlock()\n\n\treturn NewFileHandle(fs, fileData), nil\n}", "func (fsys *FS) Create(filePath string, flags int, mode uint32) (errc int, fh uint64) {\n\tdefer fs.Trace(filePath, \"flags=0x%X, mode=0%o\", flags, mode)(\"errc=%d, fh=0x%X\", &errc, &fh)\n\tleaf, parentDir, errc := fsys.lookupParentDir(filePath)\n\tif errc != 0 {\n\t\treturn errc, fhUnset\n\t}\n\t_, handle, err := parentDir.Create(leaf)\n\tif err != nil {\n\t\treturn translateError(err), fhUnset\n\t}\n\treturn 0, fsys.openFilesWr.Open(handle)\n}", "func Create(fsys fs.FS, name string) (WriterFile, error) {\n\tcfs, ok := fsys.(CreateFS)\n\tif !ok {\n\t\treturn nil, &fs.PathError{Op: \"create\", Path: name, Err: fmt.Errorf(\"not implemented on type %T\", fsys)}\n\t}\n\treturn cfs.Create(name)\n}", "func newFileSystem(basedir string, mkdir osMkdirAll) (*FS, error) {\n\tif err := mkdir(basedir, 0700); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &FS{basedir: basedir}, nil\n}", "func (s *Service) Create(parent *basefs.File, name string, isDir bool) (*basefs.File, error) {\n\tparentID := \"\"\n\tvar megaParent *mega.Node\n\tif parent == nil {\n\t\tmegaParent = s.megaCli.FS.GetRoot()\n\t} else {\n\t\tparentID = parent.ID\n\t\tmegaParent = parent.Data.(*MegaPath).Node\n\t}\n\n\tnewName := parentID + \"/\" + name\n\tif isDir {\n\t\tnewNode, err := s.megaCli.CreateDir(name, megaParent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\t}\n\n\t// Create tempFile, since mega package does not accept a reader\n\tf, err := ioutil.TempFile(os.TempDir(), \"megafs\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Close() // we don't need the descriptor, only the name\n\n\tprogress := make(chan int, 1)\n\t// Upload empty file\n\tnewNode, err := s.megaCli.UploadFile(f.Name(), megaParent, name, &progress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t<-progress\n\n\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\n}", "func (fs ReverseHttpFs) Create(n string) (afero.File, error) {\n\treturn nil, syscall.EPERM\n}", "func (storage *B2Storage) CreateDirectory(threadIndex int, dir string) (err error) {\n return nil\n}", "func (fs *VolatileFileSystem) CreateFile(name string, data []byte) error {\n\tvar flags C.int = C.SQLITE_OPEN_EXCLUSIVE | C.SQLITE_OPEN_CREATE\n\n\tiFd, rc := fs.vfs.Open(name, flags)\n\tif rc != C.SQLITE_OK {\n\t\treturn Error{\n\t\t\tCode: ErrIoErr,\n\t\t\tExtendedCode: ErrNoExtended(rc),\n\t\t}\n\t}\n\n\tfile, _ := fs.vfs.FileByFD(iFd)\n\tfile.mu.Lock()\n\tfile.data = data\n\tfile.mu.Unlock()\n\n\treturn nil\n}", "func (fs osFS) Create(path string) (io.WriteCloser, error) {\n\tf, err := os.Create(fs.resolve(path))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif fi.IsDir() {\n\t\treturn nil, fmt.Errorf(\"Open: %s is a directory\", path)\n\t}\n\n\treturn f, nil\n}", "func (fs *FileSystem) CreateFile(fileName string, data string, parentInodeNum int, fileType int) error {\n\n\t// Validation of the arguments\n\t// TODO same name file in the directory.\n\tif err := fs.validateCreationRequest(fileName); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while validating : \", err)\n\t\treturn err\n\t}\n\tdataBlockRequired := int(math.Ceil(float64(len(data) / DataBlockSize)))\n\t// Check resources available or not\n\tif err := resourceAvailable(fs, dataBlockRequired); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while check availabilty of resource : \", err)\n\t\treturn err\n\t}\n\n\tfmt.Println(\"filename\", fileName, \"datablockrequired\", dataBlockRequired)\n\t// Get Parent Inode\n\tparInode, err := getInodeInfo(parentInodeNum)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to get parent inode \", err)\n\t\treturn err\n\t}\n\n\t// check parent inode has space to accomodate new file/ directory inside it.\n\t// here 4 is used because 1 for comma and 3 bytes representing inode number.\n\tif len(parInode) < (InodeBlockSize - 4) {\n\t\treturn fmt.Errorf(\"Parent inode doesn't have space left to accomodate new file in it\")\n\t}\n\n\t// Allocate an inode and intialise\n\tif dataBlockRequired != 0 {\n\t\tdataBlockRequired++\n\t}\n\tinode := inode{fs.nextFreeInode[0], fileType, parentInodeNum, fs.nextFreeDataBlock[:dataBlockRequired]}\n\n\tfmt.Println(\"inode\", inode)\n\t// Update fst with new inode entries.\n\tfs.UpdateFst(inode)\n\n\t// Add entry in FST in memory\n\tfs.fileSystemTable[fileName] = inode.inodeNum\n\n\tparentInode := parseInode(parInode)\n\tparentInode.dataList = append(parentInode.dataList, inode.inodeNum)\n\n\t// Update the dumpFile with the file content.\n\tif err := UpdateDumpFile(inode, data, fileName, parentInode, parentInodeNum); err != nil {\n\t\tfmt.Println(\"unable to update the disk : \", err)\n\t\treturn err\n\t}\n\n\t// TODO : After successfull creation of file, update the directory data block accordingly..\n\n\tfmt.Println(\"successful updation in disk\", inode)\n\n\treturn nil\n}", "func (fsi *fsIOPool) Create(path string) (wlk *lock.LockedFile, err error) {\n\tif err = checkPathLength(path); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Creates parent if missing.\n\tif err = mkdirAll(pathutil.Dir(path), 0777); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Attempt to create the file.\n\twlk, err = lock.LockedOpenFile(path, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\tswitch {\n\t\tcase os.IsPermission(err):\n\t\t\treturn nil, errFileAccessDenied\n\t\tcase isSysErrIsDir(err):\n\t\t\treturn nil, errIsNotRegular\n\t\tcase isSysErrPathNotFound(err):\n\t\t\treturn nil, errFileAccessDenied\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Success.\n\treturn wlk, nil\n}", "func (fs *bundleFs) Create(name string) (afero.File, error) {\n\treturn nil, ErrReadOnly\n}", "func CreateCreateFileSystemResponse() (response *CreateFileSystemResponse) {\n\tresponse = &CreateFileSystemResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func createFile(fs fileSystem, fileName string) (file, error) {\n\treturn fs.Create(fileName)\n}", "func NewFileSystem(token string, debug bool) *FileSystem {\n\toauthClient := oauth2.NewClient(\n\t\toauth2.NoContext,\n\t\toauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}),\n\t)\n\tclient := putio.NewClient(oauthClient)\n\tclient.UserAgent = defaultUserAgent\n\n\treturn &FileSystem{\n\t\tputio: client,\n\t\tlogger: NewLogger(\"putiofs: \", debug),\n\t}\n}", "func (s *storager) Create(ctx context.Context, location string, mode os.FileMode, reader io.Reader, isDir bool, options ...storage.Option) error {\n\troot := s.Root\n\tif isDir {\n\t\t_, err := root.Folder(location, mode)\n\t\treturn err\n\t}\n\treturn s.Upload(ctx, location, mode, reader)\n}", "func (fs *dsFileSys) Create(name string) (fsi.File, error) {\n\n\t// WriteFile & Create\n\tdir, bname := fs.SplitX(name)\n\n\tf := DsFile{}\n\tf.fSys = fs\n\tf.BName = common.Filify(bname)\n\tf.Dir = dir\n\tf.MModTime = time.Now()\n\tf.MMode = 0644\n\n\t// let all the properties by set by fs.saveFileByPath\n\terr := f.Sync()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// return &f, nil\n\tff := fsi.File(&f)\n\treturn ff, err\n\n}", "func (s Storage) Create(path string) (io.ReadWriteCloser, error) {\n\tloc, err := s.fullPath(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdir, _ := filepath.Split(loc)\n\t_, err = os.Stat(dir)\n\n\tif err != nil && os.IsNotExist(err) {\n\t\terr = os.MkdirAll(dir, 0766)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn os.OpenFile(loc, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0766)\n}", "func (dir *HgmDir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\treturn nil, nil, fuse.Errno(syscall.EROFS)\n}", "func (fs *Fs) Create(name string) (*os.File, error) {\n\treturn os.Create(name) // #nosec G304\n}", "func (fl *FolderList) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (_ fs.Node, _ fs.Handle, err error) {\n\tfl.fs.vlog.CLogf(ctx, libkb.VLog1, \"FL Create\")\n\ttlfName := tlf.CanonicalName(req.Name)\n\tdefer func() { err = fl.processError(ctx, libkbfs.WriteMode, tlfName, err) }()\n\tif strings.HasPrefix(req.Name, \"._\") {\n\t\t// Quietly ignore writes to special macOS files, without\n\t\t// triggering a notification.\n\t\treturn nil, nil, syscall.ENOENT\n\t}\n\treturn nil, nil, libkbfs.NewWriteUnsupportedError(tlfhandle.BuildCanonicalPath(fl.PathType(), string(tlfName)))\n}", "func CreateListFileSystemsRequest() (request *ListFileSystemsRequest) {\n\trequest = &ListFileSystemsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"ListFileSystems\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (fsys *gcsFS) Create(name string) (WriterFile, error) {\n\tf, err := fsys.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.(*GCSFile), nil\n}", "func (fs osFsEval) Create(path string) (*os.File, error) {\n\treturn os.Create(path)\n}", "func (fs *FileSystem) Create(name string) (absfs.File, error) {\n\treturn fs.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0777)\n}", "func (f *FakeFileSystem) Create(file string) (io.WriteCloser, error) {\n\tf.CreateFile = file\n\treturn &f.CreateContent, f.CreateError\n}", "func NewFileSystem(fs http.FileSystem, name string) FileSystem {\n\treturn Trace(&fileSystem{fs}, name)\n}", "func (z *zfsctl) MountFileSystem(ctx context.Context, name, options, opts string, all bool) *execute {\n\targs := []string{\"mount\"}\n\tif len(options) > 0 {\n\t\targs = append(args, options)\n\t}\n\tif len(opts) > 0 {\n\t\targs = append(args, opts)\n\t}\n\tif all {\n\t\targs = append(args, \"-a\")\n\t} else {\n\t\targs = append(args, name)\n\t}\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (linux *Linux) FileCreate(filePath string) error {\n\tif !linux.FileExists(filePath) {\n\t\tfile, err := os.Create(linux.applyChroot(filePath))\n\t\tdefer file.Close()\n\t\treturn err\n\t}\n\treturn os.ErrExist\n}", "func (c *Client) Create(path gfs.Path) error {\n\tvar reply gfs.CreateFileReply\n\terr := util.Call(c.master, \"Master.RPCCreateFile\", gfs.CreateFileArg{path}, &reply)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func createDirectories() error {\n\n\tvar brickPath = glusterBrickPath + \"/\" + glusterVolumeName\n\tvar mountPath = glusterMountPath + \"/\" + glusterVolumeName\n\tvar volumePath = glusterDockerVolumePath\n\n\tdirPath := []string{brickPath, mountPath, volumePath}\n\n\tfor i := 0; i < len(dirPath); i++ {\n\t\tif helpers.Exists(dirPath[i]) == false {\n\t\t\terr := helpers.CreateDir(dirPath[i])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (ks *KopiaSnapshotter) ConnectOrCreateFilesystem(path string) error {\n\treturn nil\n}", "func (cs *ControllerServer) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) {\n\tname := req.GetName()\n\tif len(name) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"CreateVolume name must be provided\")\n\t}\n\tif err := cs.validateVolumeCapabilities(req.GetVolumeCapabilities()); err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\treqCapacity := req.GetCapacityRange().GetRequiredBytes()\n\tnfsVol, err := cs.newNFSVolume(name, reqCapacity, req.GetParameters())\n\tif err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\tvar volCap *csi.VolumeCapability\n\tif len(req.GetVolumeCapabilities()) > 0 {\n\t\tvolCap = req.GetVolumeCapabilities()[0]\n\t} // 执行挂载 命令\n\t// Mount nfs base share so we can create a subdirectory\n\tif err = cs.internalMount(ctx, nfsVol, volCap); err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to mount nfs server: %v\", err.Error())\n\t}\n\tdefer func() {\n\t\tif err = cs.internalUnmount(ctx, nfsVol); err != nil {\n\t\t\tklog.Warningf(\"failed to unmount nfs server: %v\", err.Error())\n\t\t}\n\t}()\n\n\t// Create subdirectory under base-dir\n\t// TODO: revisit permissions\n\tinternalVolumePath := cs.getInternalVolumePath(nfsVol)\n\tif err = os.Mkdir(internalVolumePath, 0777); err != nil && !os.IsExist(err) {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to make subdirectory: %v\", err.Error())\n\t}\n\t// Remove capacity setting when provisioner 1.4.0 is available with fix for\n\t// https://github.com/kubernetes-csi/external-provisioner/pull/271\n\treturn &csi.CreateVolumeResponse{Volume: cs.nfsVolToCSI(nfsVol, reqCapacity)}, nil\n}", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\td.fs.logger.Debugf(\"File create request for %v\\n\", d)\n\n\tu, err := d.fs.putio.Files.Upload(ctx, strings.NewReader(\"\"), req.Name, d.ID)\n\tif err != nil {\n\t\td.fs.logger.Printf(\"Upload failed: %v\\n\", err)\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\t// possibly a torrent file is uploaded. torrent files are picked up by the\n\t// Put.io API and pushed into the transfer queue. Original torrent file is\n\t// not keeped.\n\tif u.Transfer != nil {\n\t\treturn nil, nil, fuse.ENOENT\n\t}\n\n\tif u.File == nil {\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\tf := &File{fs: d.fs, File: u.File}\n\n\treturn f, f, nil\n}", "func createFormatFS(fsPath string) error {\n\tfsFormatPath := pathJoin(fsPath, minioMetaBucket, formatConfigFile)\n\n\t// Attempt a write lock on formatConfigFile `format.json`\n\t// file stored in minioMetaBucket(.minio.sys) directory.\n\tlk, err := lock.TryLockedOpenFile((fsFormatPath), os.O_RDWR|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn traceError(err)\n\t}\n\t// Close the locked file upon return.\n\tdefer lk.Close()\n\n\t// Load format on disk, checks if we are unformatted\n\t// writes the new format.json\n\tvar format = &formatConfigV1{}\n\terr = format.LoadFormat(lk)\n\tif errorCause(err) == errUnformattedDisk {\n\t\t_, err = newFSFormat().WriteTo(lk)\n\t\treturn err\n\t}\n\treturn err\n}", "func (self *File_Client) CreateDir(path interface{}, name interface{}) error {\n\n\trqst := &filepb.CreateDirRequest{\n\t\tPath: Utility.ToString(path),\n\t\tName: Utility.ToString(name),\n\t}\n\n\t_, err := self.c.CreateDir(context.Background(), rqst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (fs *EmbedFs) Create(path string) (file, error) {\n\treturn nil, ErrNotAvail\n}", "func NewFileSystem() FileSystem {\r\n\treturn &osFileSystem{}\r\n}", "func (c *fileSystemClient) CreateVolumeForWrite(ctx context.Context, in *fs.CreateVolumeForWriteRequest, opts ...grpc.CallOption) (*fs.CreateVolumeForWriteResponse, error) {\n\treturn c.c.CreateVolumeForWrite(ctx, in, opts...)\n}", "func NewFileSystem() FileSystem {\n\treturn &fs{\n\t\trunner: NewCommandRunner(),\n\t}\n}", "func (f *Fs) mkdir(ctx context.Context, dirPath string) (err error) {\n\t// defer log.Trace(dirPath, \"\")(\"err=%v\", &err)\n\terr = f._mkdir(ctx, dirPath)\n\tif apiErr, ok := err.(*api.Error); ok {\n\t\t// parent does not exist so create it first then try again\n\t\tif apiErr.StatusCode == http.StatusConflict {\n\t\t\terr = f.mkParentDir(ctx, dirPath)\n\t\t\tif err == nil {\n\t\t\t\terr = f._mkdir(ctx, dirPath)\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func (fs *Mysqlfs) Create(filename string) (billy.File, error) {\n\treturn fs.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)\n}", "func Create(name string) (*os.File, error)", "func (s *mockFSServer) Create(ctx context.Context, r *proto.CreateRequest) (*proto.CreateResponse, error) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.filesCreated[r.Path] = false\n\n\treturn new(proto.CreateResponse), nil\n}", "func Create(path string, data []byte) error {\n\tif err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(path, data, 0755)\n}", "func (d *Definition) Create() error {\n\terrChan := make(chan error)\n\ttree := d.ResourceTree\n\n\t// Check definition context exists\n\tif _, err := os.Stat(tree.Root().ID()); err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t`Definition Create: Expected context: \"%s\" to exist.`,\n\t\t\ttree.Root().Name(),\n\t\t)\n\t}\n\n\tgo func() {\n\t\tdefer close(errChan)\n\t\ttree.Traverse(func(r Resource) {\n\t\t\terrChan <- r.Create(d.Options)\n\t\t})\n\t}()\n\n\tfor err := range errChan {\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Definition Create: %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewFileSystemClient() (FileSystemClient, error) {\n\taddress := os.Getenv(constants.EnvFileSystemAddress)\n\tif address == \"\" {\n\t\treturn nil, fmt.Errorf(\"Environment variable '%s' not set\", constants.EnvFileSystemAddress)\n\t}\n\n\t// Create a connection\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a client\n\tc := fs.NewFileSystemClient(conn)\n\n\treturn &fileSystemClient{c: c, conn: conn}, nil\n}", "func (obj *ocsCephFilesystems) ensureCreated(r *StorageClusterReconciler, instance *ocsv1.StorageCluster) (reconcile.Result, error) {\n\treconcileStrategy := ReconcileStrategy(instance.Spec.ManagedResources.CephFilesystems.ReconcileStrategy)\n\tif reconcileStrategy == ReconcileStrategyIgnore {\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\tcephFilesystems, err := r.newCephFilesystemInstances(instance)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\tfor _, cephFilesystem := range cephFilesystems {\n\t\texisting := cephv1.CephFilesystem{}\n\t\terr = r.Client.Get(context.TODO(), types.NamespacedName{Name: cephFilesystem.Name, Namespace: cephFilesystem.Namespace}, &existing)\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\tif reconcileStrategy == ReconcileStrategyInit {\n\t\t\t\treturn reconcile.Result{}, nil\n\t\t\t}\n\t\t\tif existing.DeletionTimestamp != nil {\n\t\t\t\tr.Log.Info(\"Unable to restore CephFileSystem because it is marked for deletion.\", \"CephFileSystem\", klog.KRef(existing.Namespace, existing.Name))\n\t\t\t\treturn reconcile.Result{}, fmt.Errorf(\"failed to restore initialization object %s because it is marked for deletion\", existing.Name)\n\t\t\t}\n\n\t\t\tr.Log.Info(\"Restoring original CephFilesystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\texisting.ObjectMeta.OwnerReferences = cephFilesystem.ObjectMeta.OwnerReferences\n\t\t\texisting.Spec = cephFilesystem.Spec\n\t\t\terr = r.Client.Update(context.TODO(), &existing)\n\t\t\tif err != nil {\n\t\t\t\tr.Log.Error(err, \"Unable to update CephFileSystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\t\tcase errors.IsNotFound(err):\n\t\t\tr.Log.Info(\"Creating CephFileSystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\terr = r.Client.Create(context.TODO(), cephFilesystem)\n\t\t\tif err != nil {\n\t\t\t\tr.Log.Error(err, \"Unable to create CephFileSystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn reconcile.Result{}, nil\n}", "func (fb *FileBase) Create(ID string) (io.WriteCloser, error) {\n\treturn fb.fs.Create(filepath.Join(fb.root, ID))\n}", "func (ts *TaskService) Create(ctx context.Context, req *taskAPI.CreateTaskRequest) (*taskAPI.CreateTaskResponse, error) {\n\tdefer logPanicAndDie(log.G(ctx))\n\tlogger := log.G(ctx).WithFields(logrus.Fields{\"id\": req.ID, \"bundle\": req.Bundle})\n\tlogger.Info(\"create\")\n\n\textraData, err := unmarshalExtraData(req.Options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbundleDir := bundle.Dir(filepath.Join(containerRootDir, req.ID))\n\terr = bundleDir.Create()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = bundleDir.OCIConfig().Write(extraData.JsonSpec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO replace with proper drive mounting once that PR is merged. Right now, all containers in\n\t// this VM start up with the same rootfs image no matter their configuration\n\terr = bundleDir.MountRootfs(\"/dev/vdb\", \"ext4\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a runc shim to manage this task\n\t// TODO if we update to the v2 runc implementation in containerd, we can use a single\n\t// runc service instance to manage all tasks instead of creating a new one for each\n\truncService, err := runc.New(ctx, req.ID, ts.eventExchange)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Override the incoming stdio FIFOs, which have paths from the host that we can't use\n\tfifoSet, err := cio.NewFIFOSetInDir(bundleDir.RootPath(), req.ID, req.Terminal)\n\tif err != nil {\n\t\tlog.G(ctx).WithError(err).Error(\"failed opening stdio FIFOs\")\n\t\treturn nil, err\n\t}\n\n\t// Don't try to connect any io streams that weren't requested by the client\n\tif req.Stdin == \"\" {\n\t\tfifoSet.Stdin = \"\"\n\t}\n\n\tif req.Stdout == \"\" {\n\t\tfifoSet.Stdout = \"\"\n\t}\n\n\tif req.Stderr == \"\" {\n\t\tfifoSet.Stderr = \"\"\n\t}\n\n\ttask, err := ts.taskManager.AddTask(ctx, req.ID, runcService, bundleDir, extraData, fifoSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger.Debug(\"calling runc create\")\n\n\t// Override some of the incoming paths, which were set on the Host and thus not valid here in the Guest\n\treq.Bundle = bundleDir.RootPath()\n\treq.Rootfs = nil\n\treq.Stdin = fifoSet.Stdin\n\treq.Stdout = fifoSet.Stdout\n\treq.Stderr = fifoSet.Stderr\n\n\t// Just provide runc the options it knows about, not our wrapper\n\treq.Options = task.ExtraData().GetRuncOptions()\n\n\t// Start the io proxy and wait for initialization to complete before starting\n\t// the task to ensure we capture all task output\n\terr = <-task.StartStdioProxy(ctx, vm.VSockToFIFO, acceptVSock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := task.Create(ctx, req)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"error creating container\")\n\t\treturn nil, err\n\t}\n\n\tlogger.WithField(\"pid\", resp.Pid).Debugf(\"create succeeded\")\n\treturn resp, nil\n}", "func (p *Path) create() error {\n\tif _, err := fs.Stat(p.name); os.IsNotExist(err) {\n\t\terr := fs.MkdirAll(p.name, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"Created missing directory:\", p.name)\n\t}\n\treturn nil\n}", "func (f *Fs) createFile(ctx context.Context, pathID, leaf, mimeType string) (newID string, err error) {\n\tvar resp *http.Response\n\topts := rest.Opts{\n\t\tMethod: \"POST\",\n\t\tRootURL: pathID,\n\t\tNoResponse: true,\n\t}\n\tmkdir := api.CreateFile{\n\t\tName: f.opt.Enc.FromStandardName(leaf),\n\t\tMediaType: mimeType,\n\t}\n\terr = f.pacer.Call(func() (bool, error) {\n\t\tresp, err = f.srv.CallXML(ctx, &opts, &mkdir, nil)\n\t\treturn shouldRetry(ctx, resp, err)\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp.Header.Get(\"Location\"), nil\n}", "func (m *FileSystem) Create(file string) (io.Writer, error) {\n\tret := m.ctrl.Call(m, \"Create\", file)\n\tret0, _ := ret[0].(io.Writer)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (a *FileStorageApiService) CreateDirectoryExecute(r ApiCreateDirectoryRequest) (SingleNode, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue SingleNode\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.Ctx, \"FileStorageApiService.CreateDirectory\")\n\tif localBasePath == \"/\" {\n\t localBasePath = \"\"\n\t}\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v2/file_storage/buckets/{bucket_id}/create_directory\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"bucket_id\"+\"}\", _neturl.PathEscape(parameterToString(r.P_bucketId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.P_nodeRequest == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"nodeRequest is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.P_nodeRequest\n\treq, err := a.client.prepareRequest(r.Ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func CreateRecursive(ctx context.Context, conn *ZkConn, zkPath string, value []byte, flags int32, aclv []zk.ACL, maxCreationDepth int) (string, error) {\n\tpathCreated, err := conn.Create(ctx, zkPath, value, flags, aclv)\n\tif err == zk.ErrNoNode {\n\t\tif maxCreationDepth == 0 {\n\t\t\treturn \"\", zk.ErrNoNode\n\t\t}\n\n\t\t// Make sure that nodes are either \"file\" or\n\t\t// \"directory\" to mirror file system semantics.\n\t\tdirAclv := make([]zk.ACL, len(aclv))\n\t\tfor i, acl := range aclv {\n\t\t\tdirAclv[i] = acl\n\t\t\tdirAclv[i].Perms = PermDirectory\n\t\t}\n\t\tparentPath := path.Dir(zkPath)\n\t\t_, err = CreateRecursive(ctx, conn, parentPath, nil, 0, dirAclv, maxCreationDepth-1)\n\t\tif err != nil && err != zk.ErrNodeExists {\n\t\t\treturn \"\", err\n\t\t}\n\t\tpathCreated, err = conn.Create(ctx, zkPath, value, flags, aclv)\n\t}\n\treturn pathCreated, err\n}", "func (ts *TaskService) Create(requestCtx context.Context, req *taskAPI.CreateTaskRequest) (*taskAPI.CreateTaskResponse, error) {\n\tdefer logPanicAndDie(log.G(requestCtx))\n\ttaskID := req.ID\n\texecID := \"\" // the exec ID of the initial process in a task is an empty string by containerd convention\n\n\tlogger := log.G(requestCtx).WithField(\"TaskID\", taskID).WithField(\"ExecID\", execID)\n\tlogger.Info(\"create\")\n\n\textraData, err := unmarshalExtraData(req.Options)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to unmarshal extra data\")\n\t}\n\n\t// Just provide runc the options it knows about, not our wrapper\n\treq.Options = extraData.RuncOptions\n\n\t// Override the bundle dir and rootfs paths, which were set on the Host and thus not valid here in the Guest\n\tbundleDir := bundle.Dir(filepath.Join(containerRootDir, taskID))\n\terr = bundleDir.Create()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create bundle dir\")\n\t}\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tremoveErr := os.RemoveAll(bundleDir.RootPath())\n\t\t\tif removeErr != nil {\n\t\t\t\tlogger.WithError(removeErr).Error(\"failed to cleanup bundle dir\")\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = bundleDir.OCIConfig().Write(extraData.JsonSpec)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to write oci config file\")\n\t}\n\n\tdriveID := strings.TrimSpace(extraData.DriveID)\n\tdrive, ok := ts.driveHandler.GetDrive(driveID)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Drive %q could not be found\", driveID)\n\t}\n\n\tconst (\n\t\tmaxRetries = 100\n\t\tretryDelay = 10 * time.Millisecond\n\t)\n\n\t// We retry here due to guest kernel needing some time to populate the guest\n\t// drive.\n\t// https://github.com/firecracker-microvm/firecracker/issues/1159\n\tfor i := 0; i < maxRetries; i++ {\n\t\tif err = bundleDir.MountRootfs(drive.Path(), \"ext4\", nil); isRetryableMountError(err) {\n\t\t\tlogger.WithError(err).Warnf(\"retrying to mount rootfs %q\", drive.Path())\n\n\t\t\ttime.Sleep(retryDelay)\n\t\t\tcontinue\n\t\t}\n\n\t\tbreak\n\t}\n\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to mount rootfs %q\", drive.Path())\n\t}\n\n\treq.Bundle = bundleDir.RootPath()\n\treq.Rootfs = nil\n\n\tvar ioConnectorSet vm.IOProxy\n\n\tif vm.IsAgentOnlyIO(req.Stdout, logger) {\n\t\tioConnectorSet = vm.NewNullIOProxy()\n\t} else {\n\t\t// Override the incoming stdio FIFOs, which have paths from the host that we can't use\n\t\tfifoSet, err := cio.NewFIFOSetInDir(bundleDir.RootPath(), fifoName(taskID, execID), req.Terminal)\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"failed opening stdio FIFOs\")\n\t\t\treturn nil, errors.Wrap(err, \"failed to open stdio FIFOs\")\n\t\t}\n\n\t\tvar stdinConnectorPair *vm.IOConnectorPair\n\t\tif req.Stdin != \"\" {\n\t\t\treq.Stdin = fifoSet.Stdin\n\t\t\tstdinConnectorPair = &vm.IOConnectorPair{\n\t\t\t\tReadConnector: vm.VSockAcceptConnector(extraData.StdinPort),\n\t\t\t\tWriteConnector: vm.FIFOConnector(fifoSet.Stdin),\n\t\t\t}\n\t\t}\n\n\t\tvar stdoutConnectorPair *vm.IOConnectorPair\n\t\tif req.Stdout != \"\" {\n\t\t\treq.Stdout = fifoSet.Stdout\n\t\t\tstdoutConnectorPair = &vm.IOConnectorPair{\n\t\t\t\tReadConnector: vm.FIFOConnector(fifoSet.Stdout),\n\t\t\t\tWriteConnector: vm.VSockAcceptConnector(extraData.StdoutPort),\n\t\t\t}\n\t\t}\n\n\t\tvar stderrConnectorPair *vm.IOConnectorPair\n\t\tif req.Stderr != \"\" {\n\t\t\treq.Stderr = fifoSet.Stderr\n\t\t\tstderrConnectorPair = &vm.IOConnectorPair{\n\t\t\t\tReadConnector: vm.FIFOConnector(fifoSet.Stderr),\n\t\t\t\tWriteConnector: vm.VSockAcceptConnector(extraData.StderrPort),\n\t\t\t}\n\t\t}\n\n\t\tioConnectorSet = vm.NewIOConnectorProxy(stdinConnectorPair, stdoutConnectorPair, stderrConnectorPair)\n\t}\n\n\tresp, err := ts.taskManager.CreateTask(requestCtx, req, ts.runcService, ioConnectorSet)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create runc shim for task\")\n\t}\n\n\tlogger.WithField(\"pid\", resp.Pid).Debugf(\"create succeeded\")\n\treturn resp, nil\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\troot = parsePath(root)\n\tclient := fshttp.NewClient(ctx)\n\tf := &Fs{\n\t\tname: name,\n\t\troot: root,\n\t\topt: *opt,\n\t\tsrv: rest.NewClient(client).SetRoot(rootURL),\n\t\tpacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),\n\t\tm: m,\n\t\tauthExpiry: parseExpiry(opt.AuthorizationExpiry),\n\t}\n\tf.features = (&fs.Features{\n\t\tCaseInsensitive: true,\n\t\tCanHaveEmptyDirectories: true,\n\t}).Fill(ctx, f)\n\tf.srv.SetSigner(f.getAuth) // use signing hook to get the auth\n\tf.srv.SetErrorHandler(errorHandler)\n\n\t// Get rootID\n\tif f.opt.RootID == \"\" {\n\t\tuser, err := f.getUser(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.opt.RootID = user.SyncFolders\n\t\tif strings.HasSuffix(f.opt.RootID, \"/contents\") {\n\t\t\tf.opt.RootID = f.opt.RootID[:len(f.opt.RootID)-9]\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"unexpected rootID %q\", f.opt.RootID)\n\t\t}\n\t\t// Cache the results\n\t\tf.m.Set(\"root_id\", f.opt.RootID)\n\t\tf.opt.DeletedID = user.Deleted\n\t\tf.m.Set(\"deleted_id\", f.opt.DeletedID)\n\t}\n\tf.dirCache = dircache.New(root, f.opt.RootID, f)\n\n\t// Find the current root\n\terr = f.dirCache.FindRoot(ctx, false)\n\tif err != nil {\n\t\t// Assume it is a file\n\t\tnewRoot, remote := dircache.SplitPath(root)\n\t\toldDirCache := f.dirCache\n\t\tf.dirCache = dircache.New(newRoot, f.opt.RootID, f)\n\t\tf.root = newRoot\n\t\tresetF := func() {\n\t\t\tf.dirCache = oldDirCache\n\t\t\tf.root = root\n\t\t}\n\t\t// Make new Fs which is the parent\n\t\terr = f.dirCache.FindRoot(ctx, false)\n\t\tif err != nil {\n\t\t\t// No root so return old f\n\t\t\tresetF()\n\t\t\treturn f, nil\n\t\t}\n\t\t_, err := f.newObjectWithInfo(ctx, remote, nil)\n\t\tif err != nil {\n\t\t\tif err == fs.ErrorObjectNotFound {\n\t\t\t\t// File doesn't exist so return old f\n\t\t\t\tresetF()\n\t\t\t\treturn f, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\t// return an error with an fs which points to the parent\n\t\treturn f, fs.ErrorIsFile\n\t}\n\treturn f, nil\n}", "func (f *Fs) Create(name string) (afero.File, error) {\n\treturn f.AferoFs.Create(name)\n}", "func (mzk *MockZK) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {\n\tmzk.Args = append(mzk.Args, []interface{}{\n\t\t\"create\",\n\t\tpath,\n\t\tdata,\n\t\tflags,\n\t\tacl,\n\t})\n\treturn mzk.CreateFn(path, data, flags, acl)\n}", "func CreateFiles(fS *FileCollection, ts int64, filelock chan int64) {\n\tvar lt time.Time\n\tvar err error\n\n\tselect {\n\tcase <- time.After(5 * time.Second):\n\t\t//If 5 seconds pass without getting the proper lock, abort\n\t\tlog.Printf(\"partdisk.CreateFiles(): timeout waiting for lock\\n\")\n\t\treturn\n\tcase chts := <- filelock:\n\t\tif chts == ts { //Got the lock and it matches the timestamp received\n\t\t\t//Proceed\n\t\t\tfS.flid = ts\n\t\t\tdefer func(){\n\t\t\t\tfilelock <- 0 //Release lock\n\t\t\t}()\n\t\t\tlt = time.Now() //Start counting how long does the parts creation take\n\t\t\tlog.Printf(\"CreateFiles(): lock obtained, timestamps match: %d\\n\",ts)\n\t\t} else {\n\t\t\tlog.Printf(\"CreateFiles(): lock obtained, but timestamps missmatch: %d - %d\\n\", ts,chts)\n\t\t\tfilelock <- chts\n\t\t\treturn\n\t\t}\n\t}\n\t//Lock obtained proper, create/delete the files\n\terr = adrefiles(fS)\n\tif err != nil {\n\t\tlog.Printf(\"CreateFiles(): Error creating file: %s\\n\",err.Error())\n\t\treturn\n\t}\n\tlog.Printf(\"CreateFiles(): Request %d completed in %d seconds\\n\",ts,int64(time.Since(lt).Seconds()))\n}", "func (p *Tmpfs) Create(ctx driver.Context, id types.VolumeID) (*types.Volume, error) {\n\tctx.Log.Debugf(\"Tmpfs create volume: %s\", id.Name)\n\n\t// parse the mount path\n\tmountPath := path.Join(dataDir, id.Name)\n\n\treturn types.NewVolumeFromID(mountPath, \"\", id), nil\n}", "func MakeFileSystem(idp string, typef byte) {\n\tvar flgfound bool = false\n\tmpartition := Mounted{}\n\tfor _, mp := range sliceMP {\n\t\tidm := \"vd\" + string(mp.Letter) + strconv.FormatInt(mp.Number, 10)\n\t\tif idp == idm {\n\t\t\tflgfound = true\n\t\t\tmpartition = mp\n\t\t\tbreak\n\t\t}\n\t}\n\tif flgfound {\n\t\tvar bname [16]byte\n\t\tpartition := mpartition.Part\n\t\t// Se realiza el formateo de la partición\n\t\tif typef == 'u' {\n\t\t\twriteByteArray(mpartition.Path, partition.PartStart, partition.PartSize)\n\t\t}\n\t\t// Current Position Disk Partition\n\t\tvar cpd int64\n\t\t// Se obtiene el tamaño de las estructuras y la cantidad (#Estructuras)\n\t\tsStrc, cStrc := GetNumberOfStructures(partition.PartSize)\n\t\t// Se creará el Super Boot\n\t\tnewSB := SuperBoot{}\n\t\t// Nombre HD\n\t\tcopy(bname[:], mpartition.Name)\n\t\tnewSB.NombreHd = bname\n\t\tnewSB.FechaCreacion = getCurrentTime()\n\t\tnewSB.FechaUltimoMontaje = mpartition.TMount\n\t\tnewSB.ConteoMontajes = 1\n\t\t// Cantidad de estructuras creadas\n\t\tnewSB.CantArbolVirtual = 1\n\t\tnewSB.CantDetalleDirectorio = 1\n\t\tnewSB.CantidadInodos = 1\n\t\tnewSB.CantidadBloques = 2\n\t\t// Cantidad de estructuras ocupadas...\n\t\tnewSB.ArbolesVirtualesLibres = cStrc - 1\n\t\tnewSB.DetallesDirectorioLibres = cStrc - 1\n\t\tnewSB.InodosLibres = (cStrc * 5) - 1\n\t\tnewSB.BloquesLibres = (cStrc * 20) - 2 // Por los dos bloques del archivo user.txt\n\t\t// Inicio BMap AVD = Inicio_Particion + SizeSB\n\t\tcpd = partition.PartStart + sStrc.sizeSB\n\t\tnewSB.AptBmapArbolDirectorio = cpd\n\t\t// Inicio AVD = Inicio BitMap AVD + #Estructuras\n\t\tcpd = cpd + cStrc\n\t\tnewSB.AptArbolDirectorio = cpd\n\t\t// Inicio BMap DDir = Inicio AVD + (sizeAVD*#Estructuras)\n\t\tcpd = cpd + (sStrc.sizeAV * cStrc)\n\t\tnewSB.AptBmapDetalleDirectorio = cpd\n\t\t// Inicio DDir = Inicio BMap DDir + #Estructuras\n\t\tcpd = cpd + cStrc\n\t\tnewSB.AptDetalleDirectorio = cpd\n\t\t// Inicio BMap Inodo = Inicio DDir + (sizeDDir * #Estructuras)\n\t\tcpd = cpd + (sStrc.sizeDDir * cStrc)\n\t\tnewSB.AptBmapTablaInodo = cpd\n\t\t// Inicio Inodos = Inicio BMap Inodo + (5 * sizeInodo)\n\t\tcpd = cpd + (5 * cStrc)\n\t\tnewSB.AptTablaInodo = cpd\n\t\t// Inicio BMap Bloque = Inicio Inodos + (5 * sizeInodo * #Estructuras)\n\t\tcpd = cpd + (5 * sStrc.sizeInodo * cStrc)\n\t\tnewSB.AptBmapBloques = cpd\n\t\t// Inicio Bloque = Inicio Inodo + (20 * #Estructuras)\n\t\tcpd = cpd + (20 * cStrc)\n\t\tnewSB.AptBloques = cpd\n\t\t// Inicio Bitacora (Log) = Inicio Bloque + (20 * sizeBloque * #Estructuras)\n\t\tcpd = cpd + (20 * sStrc.sizeBD * cStrc)\n\t\tnewSB.AptLog = cpd\n\t\t// Inicio Copia SB = Inicio Bitacora + (sizeLog * #Estructuras)\n\t\tcpd = cpd + (sStrc.sizeLog * cStrc)\n\t\t//--- Se guarda el tamaño de las estructuras ------------------------------------\n\t\tnewSB.TamStrcArbolDirectorio = sStrc.sizeAV\n\t\tnewSB.TamStrcDetalleDirectorio = sStrc.sizeDDir\n\t\tnewSB.TamStrcInodo = sStrc.sizeInodo\n\t\tnewSB.TamStrcBloque = sStrc.sizeBD\n\t\t//--- Se guarda el primer bit vacio del bitmap de cada estructura ---------------\n\t\tnewSB.PrimerBitLibreArbolDir = 2\n\t\tnewSB.PrimerBitLibreDetalleDir = 2\n\t\tnewSB.PrimerBitLibreTablaInodo = 2\n\t\tnewSB.PrimerBitLibreBloques = 3\n\t\t//--- Numero Magico -------------------------------------------------------------\n\t\tnewSB.NumeroMagico = 201503442\n\t\t//--- Escribir SB en Disco ------------------------------------------------------\n\t\tWriteSuperBoot(mpartition.Path, newSB, partition.PartStart)\n\t\t//--- Escritura de la Copia de SB -----------------------------------------------\n\t\tWriteSuperBoot(mpartition.Path, newSB, cpd)\n\t\t//--- (1) Crear un AVD : root \"/\" -----------------------------------------------\n\t\tavdRoot := ArbolVirtualDir{}\n\t\tavdRoot.FechaCreacion = getCurrentTime()\n\t\tcopy(avdRoot.NombreDirectorio[:], \"/\")\n\t\tcopy(avdRoot.AvdPropietario[:], \"root\")\n\t\tcopy(avdRoot.AvdGID[:], \"root\")\n\t\tavdRoot.AvdPermisos = 777\n\t\tavdRoot.AptDetalleDirectorio = 1\n\t\tWriteAVD(mpartition.Path, avdRoot, newSB.AptArbolDirectorio)\n\t\t//--- (2) Crear un Detalle de Directorio ----------------------------------------\n\t\tdetalleDir := DetalleDirectorio{}\n\t\tarchivoInf := InfoArchivo{}\n\t\tarchivoInf.FechaCreacion = getCurrentTime()\n\t\tarchivoInf.FechaModifiacion = getCurrentTime()\n\t\tcopy(archivoInf.FileName[:], \"user.txt\")\n\t\tarchivoInf.ApInodo = 1\n\t\tdetalleDir.InfoFile[0] = archivoInf\n\t\tWriteDetalleDir(mpartition.Path, detalleDir, newSB.AptDetalleDirectorio)\n\t\t//--- (3) Crear una Tabla de Inodo ----------------------------------------------\n\t\tstrAux := \"1,G,root\\n1,U,root,201503442\\n\"\n\t\ttbInodo := TablaInodo{}\n\t\ttbInodo.NumeroInodo = 1 // Primer Inodo creado\n\t\ttbInodo.SizeArchivo = int64(len(strAux))\n\t\ttbInodo.CantBloquesAsignados = 2\n\t\ttbInodo.AptBloques[0] = int64(1)\n\t\ttbInodo.AptBloques[1] = int64(2)\n\t\tcopy(tbInodo.IDPropietario[:], \"root\")\n\t\tcopy(tbInodo.IDUGrupo[:], \"root\")\n\t\ttbInodo.IPermisos = 777\n\t\tWriteTInodo(mpartition.Path, tbInodo, newSB.AptTablaInodo)\n\t\t//--- (4) Creación de los Bloques de datos --------------------------------------\n\t\tbloque1 := BloqueDeDatos{}\n\t\tcopy(bloque1.Data[:], strAux[0:25])\n\t\tWriteBloqueD(mpartition.Path, bloque1, newSB.AptBloques)\n\t\tbloque2 := BloqueDeDatos{}\n\t\tcopy(bloque2.Data[:], strAux[25:len(strAux)])\n\t\tWriteBloqueD(mpartition.Path, bloque2, newSB.AptBloques+newSB.TamStrcBloque)\n\t\t//--- (5) Escribir en BitMap ----------------------------------------------------\n\t\tauxBytes := []byte{1}\n\t\tWriteBitMap(mpartition.Path, auxBytes, newSB.AptBmapArbolDirectorio)\n\t\tWriteBitMap(mpartition.Path, auxBytes, newSB.AptBmapDetalleDirectorio)\n\t\tWriteBitMap(mpartition.Path, auxBytes, newSB.AptBmapTablaInodo)\n\t\tauxBytes = append(auxBytes, 1)\n\t\tWriteBitMap(mpartition.Path, auxBytes, newSB.AptBmapBloques)\n\t} else {\n\t\tfmt.Println(\"[!] La particion\", idp, \" no se encuentra montada...\")\n\t}\n}", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\t// fmt.Printf(\"creating file in dir with inode %d\\n\", d.inodeNum)\n\t// fmt.Println(\"name of file to be created is: \" + req.Name)\n\tdirTable, err := getTable(d.inode)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfileExists := dirTable.Table[req.Name] != 0\n\tvar inode *Inode\n\tvar inodeNum uint64\n\tif !fileExists {\n\t\t// fmt.Println(\"file does not yet exist in Create\")\n\t\tvar isDir int8 = 0\n\t\tinode = createInode(isDir)\n\t\tinodeNum = d.inodeStream.next()\n\t\tinode.init(d.inodeNum, inodeNum)\n\t\td.addFile(req.Name, inodeNum)\n\t} else {\n\t\t// fmt.Println(\"file already exists in Create\")\n\t\tinodeNum = dirTable.Table[req.Name]\n\t\tinode, err = getInode(inodeNum)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tchild := &File{\n\t\tinode: inode,\n\t\tinodeNum: inodeNum,\n\t\tinodeStream: d.inodeStream,\n\t}\n\thandle := &FileHandle{\n\t\tinode: inode,\n\t\tinodeNum: inodeNum,\n\t}\n\t// can any errors happen here?\n\treturn child, handle, nil\n}", "func NewFileSystem(t mockConstructorTestingTNewFileSystem) *FileSystem {\n\tmock := &FileSystem{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (client StorageGatewayClient) connectFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems/{fileSystemName}/actions/connect\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ConnectFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func NewFileSystem(ctrl *gomock.Controller) *FileSystem {\n\tmock := &FileSystem{ctrl: ctrl}\n\tmock.recorder = &FileSystemMockRecorder{mock}\n\treturn mock\n}", "func (a DBFSAPI) Create(path string, overwrite bool, data string) (err error) {\n\tbyteArr, err := base64.StdEncoding.DecodeString(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbyteChunks := split(byteArr, 1e6)\n\thandle, err := a.createHandle(path, overwrite)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\terr = a.closeHandle(handle)\n\t}()\n\tfor _, byteChunk := range byteChunks {\n\t\tb64Data := base64.StdEncoding.EncodeToString(byteChunk)\n\t\terr := a.addBlock(b64Data, handle)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}", "func NewFS(basedir string) (kvs *FS, err error) {\n\treturn newFileSystem(basedir, os.MkdirAll)\n}", "func (d Dir) Create(name string) (*os.File, error) {\n\tif d.env == \"\" {\n\t\treturn nil, errors.New(\"xdgdir: Create on zero Dir\")\n\t}\n\tp := d.Path()\n\tif p == \"\" {\n\t\treturn nil, fmt.Errorf(\"xdgdir: create %s: %s is invalid or not set\", name, d.env)\n\t}\n\tfp := filepath.Join(p, name)\n\tif err := os.MkdirAll(filepath.Dir(fp), 0700); err != nil {\n\t\treturn nil, err\n\t}\n\treturn os.Create(fp)\n}", "func (client StorageGatewayClient) ConnectFileSystem(ctx context.Context, request ConnectFileSystemRequest) (response ConnectFileSystemResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.connectFileSystem, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ConnectFileSystemResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ConnectFileSystemResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ConnectFileSystemResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ConnectFileSystemResponse\")\n\t}\n\treturn\n}", "func setupFilesystem(ctx context.Context, path string, forETL bool) (res fileservice.FileService, readPath string, err error) {\n\treturn setupFileservice(ctx, &pathConfig{\n\t\tisS3: false,\n\t\tforETL: forETL,\n\t\tfilesystemConfig: filesystemConfig{path: path},\n\t})\n}", "func (tfs *TierFS) Create(namespace string) (StoredFile, error) {\n\tif err := validateNamespace(namespace); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid args: %w\", err)\n\t}\n\n\tif err := tfs.createNSWorkspaceDir(namespace); err != nil {\n\t\treturn nil, fmt.Errorf(\"create namespace dir: %w\", err)\n\t}\n\n\ttempPath := tfs.workspaceTempFilePath(namespace)\n\tfh, err := os.Create(tempPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating file: %w\", err)\n\t}\n\n\treturn &WRFile{\n\t\tFile: fh,\n\t\tstore: func(filename string) error {\n\t\t\treturn tfs.store(namespace, tempPath, filename)\n\t\t},\n\t}, nil\n}", "func TestMountCreat(t *testing.T) {\n\tconst concurrency = 2\n\tconst repeat = 2\n\n\tdir := test_helpers.InitFS(t)\n\tmnt := dir + \".mnt\"\n\n\tfor j := 0; j < repeat; j++ {\n\t\ttest_helpers.MountOrFatal(t, dir, mnt, \"-extpass=echo test\")\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(concurrency)\n\t\tfor i := 0; i < concurrency; i++ {\n\t\t\tgo func(i int) {\n\t\t\t\tpath := fmt.Sprintf(\"%s/%d\", mnt, i)\n\t\t\t\tfd, err := syscall.Open(path, syscall.O_CREAT|syscall.O_WRONLY|syscall.O_TRUNC, 0600)\n\t\t\t\tsyscall.Close(fd)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"Creat %q: %v\", path, err)\n\t\t\t\t}\n\t\t\t\twg.Done()\n\t\t\t}(i)\n\t\t}\n\t\twg.Wait()\n\t\ttest_helpers.UnmountPanic(mnt)\n\t}\n}", "func (b *Bundler) Create(name string) (afero.File, error) {\n\terr := b.fs.MkdirAll(filepath.Dir(name), fileMode)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating file: %w\", err)\n\t}\n\n\tfile, err := b.fs.Create(name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating file: %w\", err)\n\t}\n\n\treturn file, nil\n}", "func OpenFileSystem(filename string) FileSystem {\n\treturn nil\n}", "func (c *fileSystemClient) CreateVolumeForRead(ctx context.Context, in *fs.CreateVolumeForReadRequest, opts ...grpc.CallOption) (*fs.CreateVolumeForReadResponse, error) {\n\treturn c.c.CreateVolumeForRead(ctx, in, opts...)\n}", "func (z *ZkPlus) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {\n\tz.forPath(path).Log(logkey.ZkMethod, \"Create\")\n\tp, err := z.blockOnConn().Create(z.realPath(path), data, flags, acl)\n\tif strings.HasPrefix(p, z.pathPrefix) && z.pathPrefix != \"\" {\n\t\tp = p[len(z.pathPrefix)+1:]\n\t}\n\treturn p, errors.Annotatef(err, \"cannot create zk path %s\", path)\n}", "func (d ImagefsDriver) Create(r *volume.CreateRequest) error {\n\tfmt.Printf(\"-> Create %+v\\n\", r)\n\tsource, ok := r.Options[\"source\"]\n\tif !ok {\n\t\treturn fmt.Errorf(\"no source volume specified\")\n\t}\n\n\t// pull the image\n\t/*readCloser, err := d.cli.ImagePull(context.Background(), source, types.ImagePullOptions{\n\t\t// HACK assume the registry ignores the auth header\n\t\tRegistryAuth: \"null\",\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unexpected error: %s\", err)\n\t}\n\tscanner := bufio.NewScanner(readCloser)\n\tfor scanner.Scan() {\n\t}*/\n\n\tcontainerConfig := &container.Config{\n\t\tImage: source,\n\t\tEntrypoint: []string{\"/runtime/loop\"},\n\t\tLabels: map[string]string{\n\t\t\t\"com.docker.imagefs.version\": version,\n\t\t},\n\t\tNetworkDisabled: true,\n\t}\n\n\tif target, ok := r.Options[\"target\"]; ok {\n\t\tcontainerConfig.Labels[\"com.docker.imagefs.target\"] = target\n\t}\n\t// TODO handle error\n\thostConfig := &container.HostConfig{\n\t\tBinds: []string{\"/tmp/runtime:/runtime\"},\n\t\t//AutoRemove: true,\n\t}\n\n\tvar platform *specs.Platform\n\tif platformStr, ok := r.Options[\"platform\"]; ok {\n\t\tif versions.GreaterThanOrEqualTo(d.cli.ClientVersion(), \"1.41\") {\n\t\t\tp, err := platforms.Parse(platformStr)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"error parsing specified platform\")\n\t\t\t}\n\t\t\tplatform = &p\n\t\t}\n\t}\n\n\tnetworkConfig := &network.NetworkingConfig{}\n\tcont, err := d.cli.ContainerCreate(\n\t\tcontext.Background(),\n\t\tcontainerConfig,\n\t\thostConfig,\n\t\tnetworkConfig,\n\t\tplatform,\n\t\t// TODO(rabrams) namespace\n\t\tr.Name,\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unexpected error: %s\", err)\n\t}\n\tfmt.Printf(\"Temp container ID: %s\", cont.ID)\n\td.cli.ContainerStart(\n\t\tcontext.Background(),\n\t\tcont.ID,\n\t\ttypes.ContainerStartOptions{},\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unexpected error: %s\", err)\n\t}\n\treturn nil\n}", "func (tfs *TierFS) Create(namespace string) (*File, error) {\n\tif err := validateNamespace(namespace); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid args: %w\", err)\n\t}\n\n\tif err := tfs.createNSWorkspaceDir(namespace); err != nil {\n\t\treturn nil, fmt.Errorf(\"create namespace dir: %w\", err)\n\t}\n\n\ttempPath := tfs.workspaceTempFilePath(namespace)\n\tfh, err := os.Create(tempPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating file: %w\", err)\n\t}\n\n\treturn &File{\n\t\tfh: fh,\n\t\tstore: func(filename string) error {\n\t\t\treturn tfs.store(namespace, tempPath, filename)\n\t\t},\n\t}, nil\n}", "func getFileSystem(frame *rtda.Frame) {\n\tthread := frame.Thread\n\tunixFsClass := frame.GetClassLoader().LoadClass(\"java/io/UnixFileSystem\")\n\tif unixFsClass.InitializationNotStarted() {\n\t\tframe.NextPC = thread.PC // undo getFileSystem\n\t\tthread.InitClass(unixFsClass)\n\t\treturn\n\t}\n\n\tunixFsObj := unixFsClass.NewObj()\n\tframe.PushRef(unixFsObj)\n\n\t// call <init>\n\tframe.PushRef(unixFsObj) // this\n\tconstructor := unixFsClass.GetDefaultConstructor()\n\tthread.InvokeMethod(constructor)\n}", "func NewFileSystemClient() FileSystemClient {\n\treturn FsClient{}\n}", "func createDir(path string, host string) error {\n\tsshCmd := fmt.Sprintf(\"mkdir -p %s\", path)\n\tframework.Logf(\"Invoking command '%v' on ESX host %v\", sshCmd, host)\n\tresult, err := fssh.SSH(sshCmd, host+\":22\", framework.TestContext.Provider)\n\tif err != nil || result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\treturn fmt.Errorf(\"couldn't execute command: '%s' on ESX host: %v\", sshCmd, err)\n\t}\n\treturn nil\n}", "func createFile( filename string) {\n f, err := os.Create(filename)\n u.ErrNil(err, \"Unable to create file\")\n defer f.Close()\n log.Printf(\"Created %s\\n\", f.Name())\n}", "func (s stage) createFilesystemsFiles(config types.Config) error {\n\tif len(config.Storage.Filesystems) == 0 {\n\t\treturn nil\n\t}\n\ts.Logger.PushPrefix(\"createFilesystemsFiles\")\n\tdefer s.Logger.PopPrefix()\n\n\tfileMap, err := s.mapFilesToFilesystems(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor fs, f := range fileMap {\n\t\tif err := s.createFiles(fs, f); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create files: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}" ]
[ "0.7532974", "0.72078437", "0.71549237", "0.709281", "0.7048207", "0.7030605", "0.70085895", "0.6557903", "0.6551424", "0.6468269", "0.6361563", "0.63513356", "0.62807924", "0.62282985", "0.60684615", "0.6032318", "0.60243344", "0.6024124", "0.5850698", "0.5837949", "0.58215404", "0.5810168", "0.57509744", "0.5714654", "0.57115144", "0.5705758", "0.56912595", "0.5687771", "0.5687322", "0.56753075", "0.56544155", "0.5639041", "0.56385124", "0.56263703", "0.56133443", "0.55980855", "0.5580407", "0.5572527", "0.554794", "0.55458665", "0.55422986", "0.55417556", "0.5535347", "0.5501125", "0.54907024", "0.5486937", "0.5483352", "0.5479818", "0.54775447", "0.54694265", "0.5465236", "0.5435946", "0.5434246", "0.542073", "0.5413105", "0.5404915", "0.5403999", "0.53954613", "0.5391681", "0.5388665", "0.5383335", "0.53696805", "0.53653055", "0.53588873", "0.5355973", "0.5339503", "0.5306384", "0.53048205", "0.53014916", "0.52904594", "0.5267698", "0.5260379", "0.52532434", "0.52514195", "0.52505386", "0.5225272", "0.52097625", "0.51984113", "0.51943094", "0.5193183", "0.51904637", "0.5171209", "0.51609224", "0.5158876", "0.5148563", "0.5142918", "0.5137802", "0.5120682", "0.51134884", "0.51048166", "0.5102921", "0.5102047", "0.5095436", "0.5084666", "0.5081923", "0.5080624", "0.5072222", "0.50719994", "0.50650585", "0.5062041" ]
0.74027896
1
CreateFileSystemWithChan invokes the dfs.CreateFileSystem API asynchronously
func (client *Client) CreateFileSystemWithChan(request *CreateFileSystemRequest) (<-chan *CreateFileSystemResponse, <-chan error) { responseChan := make(chan *CreateFileSystemResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.CreateFileSystem(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client *Client) CreateFileSystemWithCallback(request *CreateFileSystemRequest, callback func(response *CreateFileSystemResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFileSystemResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFileSystem(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (manager *mockFileSystemManager) CreateFileSystem(ctx context.Context, groupName string, filesystemName string, timeout *int32, xMsDate string, datalakeName string) (*autorest.Response, error) {\n\tfs := fileSystemResource{\n\t\tresourceGroupName: groupName,\n\t\tstorageAccountName: datalakeName,\n\t\tfilesystemName: filesystemName,\n\t}\n\n\tmanager.fileSystemResource = append(manager.fileSystemResource, fs)\n\tmockresponse := helpers.GetRestResponse(http.StatusOK)\n\n\treturn &mockresponse, nil\n}", "func (client *Client) CreateFileSystem(request *CreateFileSystemRequest) (response *CreateFileSystemResponse, err error) {\n\tresponse = CreateCreateFileSystemResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (z *zfsctl) CreateFileSystem(ctx context.Context, name string, properties map[string]string) *execute {\n\targs := []string{\"create\", \"-p\"}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (client *Client) ListFileSystemsWithChan(request *ListFileSystemsRequest) (<-chan *ListFileSystemsResponse, <-chan error) {\n\tresponseChan := make(chan *ListFileSystemsResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.ListFileSystems(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (c *MockFileStorageClient) CreateFileSystem(ctx context.Context, details filestorage.CreateFileSystemDetails) (*filestorage.FileSystem, error) {\n\treturn &filestorage.FileSystem{Id: &fileSystemID}, nil\n}", "func FileSystemCreate(f types.Filesystem) error {\n\tvar cmd *exec.Cmd\n\tvar debugCMD string\n\n\tswitch f.Mount.Format {\n\tcase \"swap\":\n\t\tcmd = exec.Command(\"/sbin/mkswap\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkswap\", f.Mount.Device)\n\tcase \"ext4\", \"ext3\", \"ext2\":\n\t\t// Add filesystem flags\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-t\")\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Format)\n\n\t\t// Add force\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-F\")\n\n\t\t// Add Device to formate\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Device)\n\n\t\t// Format disk\n\t\tcmd = exec.Command(\"/sbin/mke2fs\", f.Mount.Create.Options...)\n\t\tfor i := range f.Mount.Create.Options {\n\t\t\tdebugCMD = fmt.Sprintf(\"%s %s\", debugCMD, f.Mount.Create.Options[i])\n\t\t}\n\tcase \"vfat\":\n\t\tcmd = exec.Command(\"/sbin/mkfs.fat\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkfs.fat\", f.Mount.Device)\n\tdefault:\n\t\tlog.Warnf(\"Unknown filesystem type [%s]\", f.Mount.Format)\n\t}\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\n\treturn nil\n}", "func (client StorageGatewayClient) CreateFileSystem(ctx context.Context, request CreateFileSystemRequest) (response CreateFileSystemResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\n\tif !(request.OpcRetryToken != nil && *request.OpcRetryToken != \"\") {\n\t\trequest.OpcRetryToken = common.String(common.RetryToken())\n\t}\n\n\tociResponse, err = common.Retry(ctx, request, client.createFileSystem, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = CreateFileSystemResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = CreateFileSystemResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(CreateFileSystemResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into CreateFileSystemResponse\")\n\t}\n\treturn\n}", "func (client *Client) CreateFileDetectWithChan(request *CreateFileDetectRequest) (<-chan *CreateFileDetectResponse, <-chan error) {\n\tresponseChan := make(chan *CreateFileDetectResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateFileDetect(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client StorageGatewayClient) createFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (s *Service) Create(parent *basefs.File, name string, isDir bool) (*basefs.File, error) {\n\tparentID := \"\"\n\tvar megaParent *mega.Node\n\tif parent == nil {\n\t\tmegaParent = s.megaCli.FS.GetRoot()\n\t} else {\n\t\tparentID = parent.ID\n\t\tmegaParent = parent.Data.(*MegaPath).Node\n\t}\n\n\tnewName := parentID + \"/\" + name\n\tif isDir {\n\t\tnewNode, err := s.megaCli.CreateDir(name, megaParent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\t}\n\n\t// Create tempFile, since mega package does not accept a reader\n\tf, err := ioutil.TempFile(os.TempDir(), \"megafs\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Close() // we don't need the descriptor, only the name\n\n\tprogress := make(chan int, 1)\n\t// Upload empty file\n\tnewNode, err := s.megaCli.UploadFile(f.Name(), megaParent, name, &progress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t<-progress\n\n\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\n}", "func (fsys *FS) Create(filePath string, flags int, mode uint32) (errc int, fh uint64) {\n\tdefer fs.Trace(filePath, \"flags=0x%X, mode=0%o\", flags, mode)(\"errc=%d, fh=0x%X\", &errc, &fh)\n\tleaf, parentDir, errc := fsys.lookupParentDir(filePath)\n\tif errc != 0 {\n\t\treturn errc, fhUnset\n\t}\n\t_, handle, err := parentDir.Create(leaf)\n\tif err != nil {\n\t\treturn translateError(err), fhUnset\n\t}\n\treturn 0, fsys.openFilesWr.Open(handle)\n}", "func MakeFsOnDisk() FileSystem { return filesys.MakeFsOnDisk() }", "func CreateCreateFileSystemRequest() (request *CreateFileSystemRequest) {\n\trequest = &CreateFileSystemRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"CreateFileSystem\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func newFileSystem(basedir string, mkdir osMkdirAll) (*FS, error) {\n\tif err := mkdir(basedir, 0700); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &FS{basedir: basedir}, nil\n}", "func NewFileSystemClient() (FileSystemClient, error) {\n\taddress := os.Getenv(constants.EnvFileSystemAddress)\n\tif address == \"\" {\n\t\treturn nil, fmt.Errorf(\"Environment variable '%s' not set\", constants.EnvFileSystemAddress)\n\t}\n\n\t// Create a connection\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a client\n\tc := fs.NewFileSystemClient(conn)\n\n\treturn &fileSystemClient{c: c, conn: conn}, nil\n}", "func (storage *B2Storage) CreateDirectory(threadIndex int, dir string) (err error) {\n return nil\n}", "func (*FileSystemBase) Create(path string, flags int, mode uint32) (int, uint64) {\n\treturn -ENOSYS, ^uint64(0)\n}", "func CreateFilesystem(e *efs.EFS, n string) (*efs.FileSystemDescription, error) {\n\tcreateParams := &efs.CreateFileSystemInput{\n\t\tCreationToken: aws.String(n),\n\t}\n\tcreateResp, err := e.CreateFileSystem(createParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for the filesystem to become available.\n\tfor {\n\t\tfs, err := DescribeFilesystem(e, n)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(fs.FileSystems) > 0 {\n\t\t\tif *fs.FileSystems[0].LifeCycleState == efsAvail {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n\treturn createResp, nil\n}", "func (client *Client) CreateFileDetectWithCallback(request *CreateFileDetectRequest, callback func(response *CreateFileDetectResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFileDetectResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFileDetect(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) ListFileSystemsWithCallback(request *ListFileSystemsRequest, callback func(response *ListFileSystemsResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ListFileSystemsResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ListFileSystems(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateFileSystemInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateFileSystem\", params, optFns, c.addOperationCreateFileSystemMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateFileSystemOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (fs *FileSystem) Create(name string) (afero.File, error) {\n\tlogger.Println(\"Create\", name)\n\tname = normalizePath(name)\n\tpath := filepath.Dir(name)\n\n\tif err := fs.MkdirAll(path, os.ModeDir); err != nil {\n\t\treturn nil, &os.PathError{Op: \"create\", Path: name, Err: err}\n\t}\n\n\tfs.Lock()\n\tfileData := CreateFile(name)\n\tfs.data[name] = fileData\n\tfs.Unlock()\n\n\treturn NewFileHandle(fs, fileData), nil\n}", "func (fs ReverseHttpFs) Create(n string) (afero.File, error) {\n\treturn nil, syscall.EPERM\n}", "func (fsys *gcsFS) Create(name string) (WriterFile, error) {\n\tf, err := fsys.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.(*GCSFile), nil\n}", "func (client *Client) CreateGatewayFileShareWithChan(request *CreateGatewayFileShareRequest) (<-chan *CreateGatewayFileShareResponse, <-chan error) {\n\tresponseChan := make(chan *CreateGatewayFileShareResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateGatewayFileShare(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func Create(fsys fs.FS, name string) (WriterFile, error) {\n\tcfs, ok := fsys.(CreateFS)\n\tif !ok {\n\t\treturn nil, &fs.PathError{Op: \"create\", Path: name, Err: fmt.Errorf(\"not implemented on type %T\", fsys)}\n\t}\n\treturn cfs.Create(name)\n}", "func NewFileSystem(token string, debug bool) *FileSystem {\n\toauthClient := oauth2.NewClient(\n\t\toauth2.NoContext,\n\t\toauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}),\n\t)\n\tclient := putio.NewClient(oauthClient)\n\tclient.UserAgent = defaultUserAgent\n\n\treturn &FileSystem{\n\t\tputio: client,\n\t\tlogger: NewLogger(\"putiofs: \", debug),\n\t}\n}", "func (fsOnDisk) Create(name string) (File, error) { return os.Create(name) }", "func (realFS) Create(name string) (File, error) { return os.Create(name) }", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\td.fs.logger.Debugf(\"File create request for %v\\n\", d)\n\n\tu, err := d.fs.putio.Files.Upload(ctx, strings.NewReader(\"\"), req.Name, d.ID)\n\tif err != nil {\n\t\td.fs.logger.Printf(\"Upload failed: %v\\n\", err)\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\t// possibly a torrent file is uploaded. torrent files are picked up by the\n\t// Put.io API and pushed into the transfer queue. Original torrent file is\n\t// not keeped.\n\tif u.Transfer != nil {\n\t\treturn nil, nil, fuse.ENOENT\n\t}\n\n\tif u.File == nil {\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\tf := &File{fs: d.fs, File: u.File}\n\n\treturn f, f, nil\n}", "func execNewChan(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := types.NewChan(types.ChanDir(args[0].(int)), args[1].(types.Type))\n\tp.Ret(2, ret)\n}", "func (fs osFS) Create(path string) (io.WriteCloser, error) {\n\tf, err := os.Create(fs.resolve(path))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif fi.IsDir() {\n\t\treturn nil, fmt.Errorf(\"Open: %s is a directory\", path)\n\t}\n\n\treturn f, nil\n}", "func (z *ZfsH) CreateFilesystem(name string, properties map[string]string) (*Dataset, error) {\n\targs := make([]string, 1, 4)\n\targs[0] = \"create\"\n\n\tif properties != nil {\n\t\targs = append(args, propsSlice(properties)...)\n\t}\n\n\targs = append(args, name)\n\t_, err := z.zfs(args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn z.GetDataset(name)\n}", "func (d *Definition) Create() error {\n\terrChan := make(chan error)\n\ttree := d.ResourceTree\n\n\t// Check definition context exists\n\tif _, err := os.Stat(tree.Root().ID()); err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t`Definition Create: Expected context: \"%s\" to exist.`,\n\t\t\ttree.Root().Name(),\n\t\t)\n\t}\n\n\tgo func() {\n\t\tdefer close(errChan)\n\t\ttree.Traverse(func(r Resource) {\n\t\t\terrChan <- r.Create(d.Options)\n\t\t})\n\t}()\n\n\tfor err := range errChan {\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Definition Create: %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\troot = parsePath(root)\n\tclient := fshttp.NewClient(ctx)\n\tf := &Fs{\n\t\tname: name,\n\t\troot: root,\n\t\topt: *opt,\n\t\tsrv: rest.NewClient(client).SetRoot(rootURL),\n\t\tpacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),\n\t\tm: m,\n\t\tauthExpiry: parseExpiry(opt.AuthorizationExpiry),\n\t}\n\tf.features = (&fs.Features{\n\t\tCaseInsensitive: true,\n\t\tCanHaveEmptyDirectories: true,\n\t}).Fill(ctx, f)\n\tf.srv.SetSigner(f.getAuth) // use signing hook to get the auth\n\tf.srv.SetErrorHandler(errorHandler)\n\n\t// Get rootID\n\tif f.opt.RootID == \"\" {\n\t\tuser, err := f.getUser(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.opt.RootID = user.SyncFolders\n\t\tif strings.HasSuffix(f.opt.RootID, \"/contents\") {\n\t\t\tf.opt.RootID = f.opt.RootID[:len(f.opt.RootID)-9]\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"unexpected rootID %q\", f.opt.RootID)\n\t\t}\n\t\t// Cache the results\n\t\tf.m.Set(\"root_id\", f.opt.RootID)\n\t\tf.opt.DeletedID = user.Deleted\n\t\tf.m.Set(\"deleted_id\", f.opt.DeletedID)\n\t}\n\tf.dirCache = dircache.New(root, f.opt.RootID, f)\n\n\t// Find the current root\n\terr = f.dirCache.FindRoot(ctx, false)\n\tif err != nil {\n\t\t// Assume it is a file\n\t\tnewRoot, remote := dircache.SplitPath(root)\n\t\toldDirCache := f.dirCache\n\t\tf.dirCache = dircache.New(newRoot, f.opt.RootID, f)\n\t\tf.root = newRoot\n\t\tresetF := func() {\n\t\t\tf.dirCache = oldDirCache\n\t\t\tf.root = root\n\t\t}\n\t\t// Make new Fs which is the parent\n\t\terr = f.dirCache.FindRoot(ctx, false)\n\t\tif err != nil {\n\t\t\t// No root so return old f\n\t\t\tresetF()\n\t\t\treturn f, nil\n\t\t}\n\t\t_, err := f.newObjectWithInfo(ctx, remote, nil)\n\t\tif err != nil {\n\t\t\tif err == fs.ErrorObjectNotFound {\n\t\t\t\t// File doesn't exist so return old f\n\t\t\t\tresetF()\n\t\t\t\treturn f, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\t// return an error with an fs which points to the parent\n\t\treturn f, fs.ErrorIsFile\n\t}\n\treturn f, nil\n}", "func (self *File_Client) CreateDir(path interface{}, name interface{}) error {\n\n\trqst := &filepb.CreateDirRequest{\n\t\tPath: Utility.ToString(path),\n\t\tName: Utility.ToString(name),\n\t}\n\n\t_, err := self.c.CreateDir(context.Background(), rqst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (client *Client) ListAvailableFileSystemTypesWithChan(request *ListAvailableFileSystemTypesRequest) (<-chan *ListAvailableFileSystemTypesResponse, <-chan error) {\n\tresponseChan := make(chan *ListAvailableFileSystemTypesResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.ListAvailableFileSystemTypes(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func CreateFiles(fS *FileCollection, ts int64, filelock chan int64) {\n\tvar lt time.Time\n\tvar err error\n\n\tselect {\n\tcase <- time.After(5 * time.Second):\n\t\t//If 5 seconds pass without getting the proper lock, abort\n\t\tlog.Printf(\"partdisk.CreateFiles(): timeout waiting for lock\\n\")\n\t\treturn\n\tcase chts := <- filelock:\n\t\tif chts == ts { //Got the lock and it matches the timestamp received\n\t\t\t//Proceed\n\t\t\tfS.flid = ts\n\t\t\tdefer func(){\n\t\t\t\tfilelock <- 0 //Release lock\n\t\t\t}()\n\t\t\tlt = time.Now() //Start counting how long does the parts creation take\n\t\t\tlog.Printf(\"CreateFiles(): lock obtained, timestamps match: %d\\n\",ts)\n\t\t} else {\n\t\t\tlog.Printf(\"CreateFiles(): lock obtained, but timestamps missmatch: %d - %d\\n\", ts,chts)\n\t\t\tfilelock <- chts\n\t\t\treturn\n\t\t}\n\t}\n\t//Lock obtained proper, create/delete the files\n\terr = adrefiles(fS)\n\tif err != nil {\n\t\tlog.Printf(\"CreateFiles(): Error creating file: %s\\n\",err.Error())\n\t\treturn\n\t}\n\tlog.Printf(\"CreateFiles(): Request %d completed in %d seconds\\n\",ts,int64(time.Since(lt).Seconds()))\n}", "func (fb *FileBase) Create(ID string) (io.WriteCloser, error) {\n\treturn fb.fs.Create(filepath.Join(fb.root, ID))\n}", "func (linux *Linux) FileCreate(filePath string) error {\n\tif !linux.FileExists(filePath) {\n\t\tfile, err := os.Create(linux.applyChroot(filePath))\n\t\tdefer file.Close()\n\t\treturn err\n\t}\n\treturn os.ErrExist\n}", "func (dir *HgmDir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\treturn nil, nil, fuse.Errno(syscall.EROFS)\n}", "func createFile(fs fileSystem, fileName string) (file, error) {\n\treturn fs.Create(fileName)\n}", "func NewFS(basedir string) (kvs *FS, err error) {\n\treturn newFileSystem(basedir, os.MkdirAll)\n}", "func (f *FakeFileSystem) Create(file string) (io.WriteCloser, error) {\n\tf.CreateFile = file\n\treturn &f.CreateContent, f.CreateError\n}", "func init() {\n\tioops.CreateDirectory(Root)\n\tchPic = make(chan string, 1)\n}", "func CreateCreateFileSystemResponse() (response *CreateFileSystemResponse) {\n\tresponse = &CreateFileSystemResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (cs *ControllerServer) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) {\n\tname := req.GetName()\n\tif len(name) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"CreateVolume name must be provided\")\n\t}\n\tif err := cs.validateVolumeCapabilities(req.GetVolumeCapabilities()); err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\treqCapacity := req.GetCapacityRange().GetRequiredBytes()\n\tnfsVol, err := cs.newNFSVolume(name, reqCapacity, req.GetParameters())\n\tif err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\tvar volCap *csi.VolumeCapability\n\tif len(req.GetVolumeCapabilities()) > 0 {\n\t\tvolCap = req.GetVolumeCapabilities()[0]\n\t} // 执行挂载 命令\n\t// Mount nfs base share so we can create a subdirectory\n\tif err = cs.internalMount(ctx, nfsVol, volCap); err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to mount nfs server: %v\", err.Error())\n\t}\n\tdefer func() {\n\t\tif err = cs.internalUnmount(ctx, nfsVol); err != nil {\n\t\t\tklog.Warningf(\"failed to unmount nfs server: %v\", err.Error())\n\t\t}\n\t}()\n\n\t// Create subdirectory under base-dir\n\t// TODO: revisit permissions\n\tinternalVolumePath := cs.getInternalVolumePath(nfsVol)\n\tif err = os.Mkdir(internalVolumePath, 0777); err != nil && !os.IsExist(err) {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to make subdirectory: %v\", err.Error())\n\t}\n\t// Remove capacity setting when provisioner 1.4.0 is available with fix for\n\t// https://github.com/kubernetes-csi/external-provisioner/pull/271\n\treturn &csi.CreateVolumeResponse{Volume: cs.nfsVolToCSI(nfsVol, reqCapacity)}, nil\n}", "func (c *Client) Create(path gfs.Path) error {\n\tvar reply gfs.CreateFileReply\n\terr := util.Call(c.master, \"Master.RPCCreateFile\", gfs.CreateFileArg{path}, &reply)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (fs *VolatileFileSystem) CreateFile(name string, data []byte) error {\n\tvar flags C.int = C.SQLITE_OPEN_EXCLUSIVE | C.SQLITE_OPEN_CREATE\n\n\tiFd, rc := fs.vfs.Open(name, flags)\n\tif rc != C.SQLITE_OK {\n\t\treturn Error{\n\t\t\tCode: ErrIoErr,\n\t\t\tExtendedCode: ErrNoExtended(rc),\n\t\t}\n\t}\n\n\tfile, _ := fs.vfs.FileByFD(iFd)\n\tfile.mu.Lock()\n\tfile.data = data\n\tfile.mu.Unlock()\n\n\treturn nil\n}", "func (client *Client) CreateGatewayFileShareWithCallback(request *CreateGatewayFileShareRequest, callback func(response *CreateGatewayFileShareResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateGatewayFileShareResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateGatewayFileShare(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func Create(instructionData reflect.Value, finished chan bool) int {\n\tfmt.Println(\"FIBER INFO: Creating File ...\")\n\n\tpath, err := variable.GetValue(instructionData, \"PathVarName\", \"PathIsVar\", \"Path\")\n\tif err != nil {\n\t\tfinished <- true\n\t\treturn -1\n\t}\n\n\tf, _ := os.Create(path.(string))\n\tf.Close()\n\tfinished <- true\n\treturn -1\n}", "func Create(p []string) (Task, error) {\n\tt := Task{\n\t\tPaths: p,\n\t}\n\tw, err := fsnotify.NewWatcher()\n\tt.FSWatcher = w\n\treturn t, err\n}", "func (z *zfsctl) ReceiveFileSystem(ctx context.Context, name, options string, properties map[string]string, xProperty string, de string) *execute {\n\targs := []string{\"receive\"}\n\tif len(options) > 0 {\n\t\targs = append(args, options)\n\t}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, strings.TrimSuffix(kv, \" \"))\n\t}\n\tif len(xProperty) > 0 {\n\t\targs = append(args, \"-x \"+xProperty)\n\t}\n\tswitch de {\n\tcase \"-d\":\n\t\targs = append(args, \"-d\")\n\tcase \"-e\":\n\t\targs = append(args, \"-e\")\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (fl *FolderList) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (_ fs.Node, _ fs.Handle, err error) {\n\tfl.fs.vlog.CLogf(ctx, libkb.VLog1, \"FL Create\")\n\ttlfName := tlf.CanonicalName(req.Name)\n\tdefer func() { err = fl.processError(ctx, libkbfs.WriteMode, tlfName, err) }()\n\tif strings.HasPrefix(req.Name, \"._\") {\n\t\t// Quietly ignore writes to special macOS files, without\n\t\t// triggering a notification.\n\t\treturn nil, nil, syscall.ENOENT\n\t}\n\treturn nil, nil, libkbfs.NewWriteUnsupportedError(tlfhandle.BuildCanonicalPath(fl.PathType(), string(tlfName)))\n}", "func (daemon *Daemon) openContainerFS(container *container.Container) (_ *containerFSView, err error) {\n\tif err := daemon.Mount(container); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t_ = daemon.Unmount(container)\n\t\t}\n\t}()\n\n\tmounts, err := daemon.setupMounts(container)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t_ = container.UnmountVolumes(daemon.LogVolumeEvent)\n\t\t}\n\t}()\n\n\t// Setup in initial mount namespace complete. We're ready to unshare the\n\t// mount namespace and bind the volume mounts into that private view of\n\t// the container FS.\n\ttodo := make(chan future)\n\tdone := make(chan error)\n\terr = unshare.Go(unix.CLONE_NEWNS,\n\t\tfunc() error {\n\t\t\tif err := mount.MakeRSlave(\"/\"); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, m := range mounts {\n\t\t\t\tdest, err := container.GetResourcePath(m.Destination)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tvar stat os.FileInfo\n\t\t\t\tstat, err = os.Stat(m.Source)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tbindMode := \"rbind\"\n\t\t\t\tif m.NonRecursive {\n\t\t\t\t\tbindMode = \"bind\"\n\t\t\t\t}\n\t\t\t\twriteMode := \"ro\"\n\t\t\t\tif m.Writable {\n\t\t\t\t\twriteMode = \"rw\"\n\t\t\t\t\tif m.ReadOnlyNonRecursive {\n\t\t\t\t\t\treturn errors.New(\"options conflict: Writable && ReadOnlyNonRecursive\")\n\t\t\t\t\t}\n\t\t\t\t\tif m.ReadOnlyForceRecursive {\n\t\t\t\t\t\treturn errors.New(\"options conflict: Writable && ReadOnlyForceRecursive\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif m.ReadOnlyNonRecursive && m.ReadOnlyForceRecursive {\n\t\t\t\t\treturn errors.New(\"options conflict: ReadOnlyNonRecursive && ReadOnlyForceRecursive\")\n\t\t\t\t}\n\n\t\t\t\t// openContainerFS() is called for temporary mounts\n\t\t\t\t// outside the container. Soon these will be unmounted\n\t\t\t\t// with lazy unmount option and given we have mounted\n\t\t\t\t// them rbind, all the submounts will propagate if these\n\t\t\t\t// are shared. If daemon is running in host namespace\n\t\t\t\t// and has / as shared then these unmounts will\n\t\t\t\t// propagate and unmount original mount as well. So make\n\t\t\t\t// all these mounts rprivate. Do not use propagation\n\t\t\t\t// property of volume as that should apply only when\n\t\t\t\t// mounting happens inside the container.\n\t\t\t\topts := strings.Join([]string{bindMode, writeMode, \"rprivate\"}, \",\")\n\t\t\t\tif err := mount.Mount(m.Source, dest, \"\", opts); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif !m.Writable && !m.ReadOnlyNonRecursive {\n\t\t\t\t\tif err := makeMountRRO(dest); err != nil {\n\t\t\t\t\t\tif m.ReadOnlyForceRecursive {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.G(context.TODO()).WithError(err).Debugf(\"Failed to make %q recursively read-only\", dest)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn mounttree.SwitchRoot(container.BaseFS)\n\t\t},\n\t\tfunc() {\n\t\t\tdefer close(done)\n\n\t\t\tfor it := range todo {\n\t\t\t\terr := it.fn()\n\t\t\t\tif it.res != nil {\n\t\t\t\t\tit.res <- err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// The thread will terminate when this goroutine returns, taking the\n\t\t\t// mount namespace and all the volume bind-mounts with it.\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvw := &containerFSView{\n\t\td: daemon,\n\t\tctr: container,\n\t\ttodo: todo,\n\t\tdone: done,\n\t}\n\truntime.SetFinalizer(vw, (*containerFSView).Close)\n\treturn vw, nil\n}", "func mkChannel(path string) (chan uint8, <-chan vm.Msg, error) {\n\tfd, err := os.OpenFile(path, unix.O_RDWR, 0600|os.ModeExclusive)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrapf(err, \"OpenFile %s\", path)\n\t}\n\n\tackChan := make(chan uint8)\n\tmsgChan := make(chan vm.Msg, 1)\n\n\tgo func() {\n\t\tfor {\n\t\t\tvalue := <-ackChan\n\t\t\tif _, err := fd.Write([]byte{value}); err != nil {\n\t\t\t\tlog.Printf(\"Write: %v\", err)\n\t\t\t}\n\t\t\tackChan <- 0\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\t// read header\n\t\t\tbuf := make([]byte, headerSize)\n\t\t\tif _, err := io.ReadFull(fd, buf); err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\n\t\t\tpayloadSize := int(binary.BigEndian.Uint32(buf[:4]))\n\t\t\tmsgType := vm.Msgtype(buf[4])\n\n\t\t\t// read payload\n\t\t\tbuf = make([]byte, payloadSize)\n\t\t\trd := bufio.NewReaderSize(fd, payloadSize)\n\t\t\tif _, err := io.ReadFull(rd, buf); err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\n\t\t\tmsgChan <- vm.Msg{\n\t\t\t\tType: msgType,\n\t\t\t\tData: buf,\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn ackChan, msgChan, nil\n}", "func newFile(fd uintptr, name string, kind newFileKind) *File {\n\tfdi := int(fd)\n\tif fdi < 0 {\n\t\treturn nil\n\t}\n\tf := &File{&file{\n\t\tpfd: poll.FD{\n\t\t\tSysfd: fdi,\n\t\t\tIsStream: true,\n\t\t\tZeroReadIsEOF: true,\n\t\t},\n\t\tname: name,\n\t\tstdoutOrErr: fdi == 1 || fdi == 2,\n\t}}\n\n\tpollable := kind == kindOpenFile || kind == kindPipe || kind == kindNonBlock\n\n\t// If the caller passed a non-blocking filedes (kindNonBlock),\n\t// we assume they know what they are doing so we allow it to be\n\t// used with kqueue.\n\tif kind == kindOpenFile {\n\t\tswitch runtime.GOOS {\n\t\tcase \"darwin\", \"ios\", \"dragonfly\", \"freebsd\", \"netbsd\", \"openbsd\":\n\t\t\tvar st syscall.Stat_t\n\t\t\terr := ignoringEINTR(func() error {\n\t\t\t\treturn syscall.Fstat(fdi, &st)\n\t\t\t})\n\t\t\ttyp := st.Mode & syscall.S_IFMT\n\t\t\t// Don't try to use kqueue with regular files on *BSDs.\n\t\t\t// On FreeBSD a regular file is always\n\t\t\t// reported as ready for writing.\n\t\t\t// On Dragonfly, NetBSD and OpenBSD the fd is signaled\n\t\t\t// only once as ready (both read and write).\n\t\t\t// Issue 19093.\n\t\t\t// Also don't add directories to the netpoller.\n\t\t\tif err == nil && (typ == syscall.S_IFREG || typ == syscall.S_IFDIR) {\n\t\t\t\tpollable = false\n\t\t\t}\n\n\t\t\t// In addition to the behavior described above for regular files,\n\t\t\t// on Darwin, kqueue does not work properly with fifos:\n\t\t\t// closing the last writer does not cause a kqueue event\n\t\t\t// for any readers. See issue #24164.\n\t\t\tif (runtime.GOOS == \"darwin\" || runtime.GOOS == \"ios\") && typ == syscall.S_IFIFO {\n\t\t\t\tpollable = false\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := f.pfd.Init(\"file\", pollable); err != nil {\n\t\t// An error here indicates a failure to register\n\t\t// with the netpoll system. That can happen for\n\t\t// a file descriptor that is not supported by\n\t\t// epoll/kqueue; for example, disk files on\n\t\t// Linux systems. We assume that any real error\n\t\t// will show up in later I/O.\n\t} else if pollable {\n\t\t// We successfully registered with netpoll, so put\n\t\t// the file into nonblocking mode.\n\t\tif err := syscall.SetNonblock(fdi, true); err == nil {\n\t\t\tf.nonblock = true\n\t\t}\n\t}\n\n\truntime.SetFinalizer(f.file, (*file).close)\n\treturn f\n}", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\t// fmt.Printf(\"creating file in dir with inode %d\\n\", d.inodeNum)\n\t// fmt.Println(\"name of file to be created is: \" + req.Name)\n\tdirTable, err := getTable(d.inode)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfileExists := dirTable.Table[req.Name] != 0\n\tvar inode *Inode\n\tvar inodeNum uint64\n\tif !fileExists {\n\t\t// fmt.Println(\"file does not yet exist in Create\")\n\t\tvar isDir int8 = 0\n\t\tinode = createInode(isDir)\n\t\tinodeNum = d.inodeStream.next()\n\t\tinode.init(d.inodeNum, inodeNum)\n\t\td.addFile(req.Name, inodeNum)\n\t} else {\n\t\t// fmt.Println(\"file already exists in Create\")\n\t\tinodeNum = dirTable.Table[req.Name]\n\t\tinode, err = getInode(inodeNum)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tchild := &File{\n\t\tinode: inode,\n\t\tinodeNum: inodeNum,\n\t\tinodeStream: d.inodeStream,\n\t}\n\thandle := &FileHandle{\n\t\tinode: inode,\n\t\tinodeNum: inodeNum,\n\t}\n\t// can any errors happen here?\n\treturn child, handle, nil\n}", "func CrawlFileSystem(workQueue chan *Data, root string, wg *sync.WaitGroup, verbose bool) {\n\tdefer wg.Done()\n\tID := int64(0)\n\t\n\t// Start timing\n\tstart := time.Now()\n\t\n\t// Walk file system\n\terr := filepath.Walk(root, func(path string, f os.FileInfo, err error) error {\n\t\tworkQueue <- &Data{path, ID}\n\t\tID++\n\t\treturn err\n\t})\n\n\tif err != nil && verbose {\n\t\tlog.Printf(\"crawl error: %s\", err)\n\t}\n\n\tlog.Printf(\"Finished crawling %s in %s\", root, time.Since(start))\n\tclose(workQueue)\n}", "func mkdirForFile(path string) error {\n\treturn os.MkdirAll(filepath.Dir(path), DefaultDirectoryPermissions)\n}", "func NewFileSystem() FileSystem {\n\treturn &fs{\n\t\trunner: NewCommandRunner(),\n\t}\n}", "func (fsi *fsIOPool) Create(path string) (wlk *lock.LockedFile, err error) {\n\tif err = checkPathLength(path); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Creates parent if missing.\n\tif err = mkdirAll(pathutil.Dir(path), 0777); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Attempt to create the file.\n\twlk, err = lock.LockedOpenFile(path, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\tswitch {\n\t\tcase os.IsPermission(err):\n\t\t\treturn nil, errFileAccessDenied\n\t\tcase isSysErrIsDir(err):\n\t\t\treturn nil, errIsNotRegular\n\t\tcase isSysErrPathNotFound(err):\n\t\t\treturn nil, errFileAccessDenied\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Success.\n\treturn wlk, nil\n}", "func Factory(token string, channelID string) (func(string) error, error) {\n\ts, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Before using the message endpoint, you must connect to\n\t// and identify with a gateway at least once.\n\terr = s.Open()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = s.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcb := func(src string) error {\n\t\tf, err := os.Open(src)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\n\t\t_, err = s.ChannelFileSend(channelID, filepath.Base(src), f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn cb, nil\n}", "func getFileSystem(frame *rtda.Frame) {\n\tthread := frame.Thread\n\tunixFsClass := frame.GetClassLoader().LoadClass(\"java/io/UnixFileSystem\")\n\tif unixFsClass.InitializationNotStarted() {\n\t\tframe.NextPC = thread.PC // undo getFileSystem\n\t\tthread.InitClass(unixFsClass)\n\t\treturn\n\t}\n\n\tunixFsObj := unixFsClass.NewObj()\n\tframe.PushRef(unixFsObj)\n\n\t// call <init>\n\tframe.PushRef(unixFsObj) // this\n\tconstructor := unixFsClass.GetDefaultConstructor()\n\tthread.InvokeMethod(constructor)\n}", "func createPaths() {\n\tdataDir, err := conf.GetDataLoc()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdirs := []string{\"uploads\", \"sources\", \"sinks\", \"functions\", \"services\", \"services/schemas\", \"connections\"}\n\n\tfor _, v := range dirs {\n\t\t// Create dir if not exist\n\t\trealDir := filepath.Join(dataDir, v)\n\t\tif _, err := os.Stat(realDir); os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(realDir, os.ModePerm); err != nil {\n\t\t\t\tfmt.Printf(\"Failed to create dir %s: %v\", realDir, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tfiles := []string{\"connections/connection.yaml\"}\n\tfor _, v := range files {\n\t\t// Create dir if not exist\n\t\trealFile := filepath.Join(dataDir, v)\n\t\tif _, err := os.Stat(realFile); os.IsNotExist(err) {\n\t\t\tif _, err := os.Create(realFile); err != nil {\n\t\t\t\tfmt.Printf(\"Failed to create file %s: %v\", realFile, err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (fs *FileSystem) CreateFile(fileName string, data string, parentInodeNum int, fileType int) error {\n\n\t// Validation of the arguments\n\t// TODO same name file in the directory.\n\tif err := fs.validateCreationRequest(fileName); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while validating : \", err)\n\t\treturn err\n\t}\n\tdataBlockRequired := int(math.Ceil(float64(len(data) / DataBlockSize)))\n\t// Check resources available or not\n\tif err := resourceAvailable(fs, dataBlockRequired); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while check availabilty of resource : \", err)\n\t\treturn err\n\t}\n\n\tfmt.Println(\"filename\", fileName, \"datablockrequired\", dataBlockRequired)\n\t// Get Parent Inode\n\tparInode, err := getInodeInfo(parentInodeNum)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to get parent inode \", err)\n\t\treturn err\n\t}\n\n\t// check parent inode has space to accomodate new file/ directory inside it.\n\t// here 4 is used because 1 for comma and 3 bytes representing inode number.\n\tif len(parInode) < (InodeBlockSize - 4) {\n\t\treturn fmt.Errorf(\"Parent inode doesn't have space left to accomodate new file in it\")\n\t}\n\n\t// Allocate an inode and intialise\n\tif dataBlockRequired != 0 {\n\t\tdataBlockRequired++\n\t}\n\tinode := inode{fs.nextFreeInode[0], fileType, parentInodeNum, fs.nextFreeDataBlock[:dataBlockRequired]}\n\n\tfmt.Println(\"inode\", inode)\n\t// Update fst with new inode entries.\n\tfs.UpdateFst(inode)\n\n\t// Add entry in FST in memory\n\tfs.fileSystemTable[fileName] = inode.inodeNum\n\n\tparentInode := parseInode(parInode)\n\tparentInode.dataList = append(parentInode.dataList, inode.inodeNum)\n\n\t// Update the dumpFile with the file content.\n\tif err := UpdateDumpFile(inode, data, fileName, parentInode, parentInodeNum); err != nil {\n\t\tfmt.Println(\"unable to update the disk : \", err)\n\t\treturn err\n\t}\n\n\t// TODO : After successfull creation of file, update the directory data block accordingly..\n\n\tfmt.Println(\"successful updation in disk\", inode)\n\n\treturn nil\n}", "func Create(name string) (*os.File, error)", "func createDir(path string, host string) error {\n\tsshCmd := fmt.Sprintf(\"mkdir -p %s\", path)\n\tframework.Logf(\"Invoking command '%v' on ESX host %v\", sshCmd, host)\n\tresult, err := fssh.SSH(sshCmd, host+\":22\", framework.TestContext.Provider)\n\tif err != nil || result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\treturn fmt.Errorf(\"couldn't execute command: '%s' on ESX host: %v\", sshCmd, err)\n\t}\n\treturn nil\n}", "func (s Storage) Create(path string) (io.ReadWriteCloser, error) {\n\tloc, err := s.fullPath(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdir, _ := filepath.Split(loc)\n\t_, err = os.Stat(dir)\n\n\tif err != nil && os.IsNotExist(err) {\n\t\terr = os.MkdirAll(dir, 0766)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn os.OpenFile(loc, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0766)\n}", "func (f *Fs) createFile(ctx context.Context, pathID, leaf, mimeType string) (newID string, err error) {\n\tvar resp *http.Response\n\topts := rest.Opts{\n\t\tMethod: \"POST\",\n\t\tRootURL: pathID,\n\t\tNoResponse: true,\n\t}\n\tmkdir := api.CreateFile{\n\t\tName: f.opt.Enc.FromStandardName(leaf),\n\t\tMediaType: mimeType,\n\t}\n\terr = f.pacer.Call(func() (bool, error) {\n\t\tresp, err = f.srv.CallXML(ctx, &opts, &mkdir, nil)\n\t\treturn shouldRetry(ctx, resp, err)\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp.Header.Get(\"Location\"), nil\n}", "func newFSConn(token, infoPath string) (conn *FSConn, err error) {\n\tvar info slack.Info\n\tconn = new(FSConn)\n\n\tif infoPath != \"\" {\n\t\tbuf, err := ioutil.ReadFile(infoPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ReadFile(%s): %s\", infoPath, err)\n\t\t}\n\t\terr = json.Unmarshal(buf, &info)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unmarshal: %s\", err)\n\t\t}\n\t} else {\n\t\tconn.api = slack.New(token)\n\t\t//conn.api.SetDebug(true)\n\t\tconn.ws, err = conn.api.StartRTM(\"\", \"https://slack.com\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"StartRTM(): %s\\n\", err)\n\t\t}\n\t\tinfo = conn.api.GetInfo()\n\t}\n\n\tconn.in = make(chan slack.SlackEvent)\n\tconn.sinks = make([]EventHandler, 0, 5)\n\tconn.Super = NewSuper()\n\n\tusers := make([]*User, 0, len(info.Users))\n\tfor _, u := range info.Users {\n\t\tusers = append(users, NewUser(u, conn))\n\t}\n\tconn.users, err = NewUserSet(\"users\", conn, NewUserDir, users)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewUserSet: %s\", err)\n\t}\n\n\tconn.self, err = NewSelf(conn, info.User, info.Team)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewSelf: %s\", err)\n\t}\n\n\tchans := make([]Room, 0, len(info.Channels))\n\tfor _, c := range info.Channels {\n\t\tchans = append(chans, NewChannel(c, conn))\n\t}\n\tconn.channels, err = NewRoomSet(\"channels\", conn, NewChannelDir, chans)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewRoomSet: %s\", err)\n\t}\n\n\tgroups := make([]Room, 0, len(info.Groups))\n\tfor _, g := range info.Groups {\n\t\tgroups = append(groups, NewGroup(g, conn))\n\t}\n\tconn.groups, err = NewRoomSet(\"groups\", conn, NewGroupDir, groups)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewRoomSet: %s\", err)\n\t}\n\n\tims := make([]Room, 0, len(info.IMs))\n\tfor _, im := range info.IMs {\n\t\tims = append(ims, NewIM(im, conn))\n\t}\n\tconn.ims, err = NewRoomSet(\"ims\", conn, NewIMDir, ims)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewRoomSet: %s\", err)\n\t}\n\n\t// simplify dispatch code by keeping track of event handlers\n\t// in a slice. We (FSConn) are an event sink too - add\n\t// ourselves to the list first, so that we can separate\n\t// routing logic from connection-level handling logic.\n\tconn.sinks = append(conn.sinks, conn,\n\t\tconn.users, conn.channels, conn.groups, conn.ims)\n\n\t// only spawn goroutines in online mode\n\tif infoPath == \"\" {\n\t\tgo conn.ws.HandleIncomingEvents(conn.in)\n\t\tgo conn.ws.Keepalive(10 * time.Second)\n\t\tgo conn.consumeEvents()\n\t}\n\n\treturn conn, nil\n}", "func (client *Client) CreateClusterWithChan(request *CreateClusterRequest) (<-chan *CreateClusterResponse, <-chan error) {\n\tresponseChan := make(chan *CreateClusterResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateCluster(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func createFormatFS(fsPath string) error {\n\tfsFormatPath := pathJoin(fsPath, minioMetaBucket, formatConfigFile)\n\n\t// Attempt a write lock on formatConfigFile `format.json`\n\t// file stored in minioMetaBucket(.minio.sys) directory.\n\tlk, err := lock.TryLockedOpenFile((fsFormatPath), os.O_RDWR|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn traceError(err)\n\t}\n\t// Close the locked file upon return.\n\tdefer lk.Close()\n\n\t// Load format on disk, checks if we are unformatted\n\t// writes the new format.json\n\tvar format = &formatConfigV1{}\n\terr = format.LoadFormat(lk)\n\tif errorCause(err) == errUnformattedDisk {\n\t\t_, err = newFSFormat().WriteTo(lk)\n\t\treturn err\n\t}\n\treturn err\n}", "func (ks *KopiaSnapshotter) ConnectOrCreateFilesystem(path string) error {\n\treturn nil\n}", "func createNode(parent string, infos []FileInfo) error {\n\tfor _, info := range infos {\n\t\tpath := filepath.Join(parent, info.Name)\n\t\tif info.Type == DirType { // info is a dir\n\t\t\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\t\t\tos.Mkdir(path, 0755)\n\t\t\t}\n\t\t\tif info.Children != nil && len(info.Children) > 0 {\n\t\t\t\tif err := createNode(path, info.Children); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t} else if info.Type == FileType { // info is a file\n\t\t\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\t\t\tif err := ioutil.WriteFile(path, []byte(info.Content), 0755); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"unknown FileInfo type: %v\", info.Type)\n\t\t}\n\t}\n\treturn nil\n}", "func (fs *EmbedFs) Create(path string) (file, error) {\n\treturn nil, ErrNotAvail\n}", "func CreateRecursive(ctx context.Context, conn *ZkConn, zkPath string, value []byte, flags int32, aclv []zk.ACL, maxCreationDepth int) (string, error) {\n\tpathCreated, err := conn.Create(ctx, zkPath, value, flags, aclv)\n\tif err == zk.ErrNoNode {\n\t\tif maxCreationDepth == 0 {\n\t\t\treturn \"\", zk.ErrNoNode\n\t\t}\n\n\t\t// Make sure that nodes are either \"file\" or\n\t\t// \"directory\" to mirror file system semantics.\n\t\tdirAclv := make([]zk.ACL, len(aclv))\n\t\tfor i, acl := range aclv {\n\t\t\tdirAclv[i] = acl\n\t\t\tdirAclv[i].Perms = PermDirectory\n\t\t}\n\t\tparentPath := path.Dir(zkPath)\n\t\t_, err = CreateRecursive(ctx, conn, parentPath, nil, 0, dirAclv, maxCreationDepth-1)\n\t\tif err != nil && err != zk.ErrNodeExists {\n\t\t\treturn \"\", err\n\t\t}\n\t\tpathCreated, err = conn.Create(ctx, zkPath, value, flags, aclv)\n\t}\n\treturn pathCreated, err\n}", "func (m *FileSystem) Create(file string) (io.Writer, error) {\n\tret := m.ctrl.Call(m, \"Create\", file)\n\tret0, _ := ret[0].(io.Writer)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (fs osFsEval) Create(path string) (*os.File, error) {\n\treturn os.Create(path)\n}", "func createRepo(c *config, repo string, ch chan<- bool) error {\n\t// create context\n\tctxt, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tcdp, err := chromedp.New(ctxt, chromedp.WithLog(log.Printf))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// run task list\n\terr = cdp.Run(ctxt, gitHub(c, repo))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// shutdown chrome\n\terr = cdp.Shutdown(ctxt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// wait for chrome to finish\n\terr = cdp.Wait()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tch <- true\n\treturn nil\n}", "func NewCfnFileSystem(scope awscdk.Construct, id *string, props *CfnFileSystemProps) CfnFileSystem {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnFileSystem{}\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_fsx.CfnFileSystem\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func create(rawZipString string) (http.FileSystem, error) {\n\tif zipData == \"\" {\n\t\treturn nil, errors.New(\"statik/fs: no zip data registered\")\n\t}\n\tzipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make(map[string]file, len(zipReader.File))\n\tdirs := make(map[string][]string)\n\tfs := &ginBinFs{files: files, dirs: dirs}\n\tfor _, zipFile := range zipReader.File {\n\t\tfi := zipFile.FileInfo()\n\t\tf := file{FileInfo: fi, fs: fs}\n\t\tf.data, err = unzip(zipFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"statik/fs: error unzipping file %q: %s\", zipFile.Name, err)\n\t\t}\n\t\tfiles[\"/\"+zipFile.Name] = f\n\t}\n\tfor fn := range files {\n\t\t// go up directories recursively in order to care deep directory\n\t\tfor dn := path.Dir(fn); dn != fn; {\n\t\t\tif _, ok := files[dn]; !ok {\n\t\t\t\tfiles[dn] = file{FileInfo: dirInfo{dn}, fs: fs}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfn, dn = dn, path.Dir(dn)\n\t\t}\n\t}\n\tfor fn := range files {\n\t\tdn := path.Dir(fn)\n\t\tif fn != dn {\n\t\t\tfs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))\n\t\t}\n\t}\n\tfor _, s := range fs.dirs {\n\t\tsort.Strings(s)\n\t}\n\treturn fs, nil\n}", "func create(rawZipString string) (http.FileSystem, error) {\n\tif zipData == \"\" {\n\t\treturn nil, errors.New(\"statik/fs: no zip data registered\")\n\t}\n\tzipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make(map[string]file, len(zipReader.File))\n\tdirs := make(map[string][]string)\n\tfs := &ginBinFs{files: files, dirs: dirs}\n\tfor _, zipFile := range zipReader.File {\n\t\tfi := zipFile.FileInfo()\n\t\tf := file{FileInfo: fi, fs: fs}\n\t\tf.data, err = unzip(zipFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"statik/fs: error unzipping file %q: %s\", zipFile.Name, err)\n\t\t}\n\t\tfiles[\"/\"+zipFile.Name] = f\n\t}\n\tfor fn := range files {\n\t\t// go up directories recursively in order to care deep directory\n\t\tfor dn := path.Dir(fn); dn != fn; {\n\t\t\tif _, ok := files[dn]; !ok {\n\t\t\t\tfiles[dn] = file{FileInfo: dirInfo{dn}, fs: fs}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfn, dn = dn, path.Dir(dn)\n\t\t}\n\t}\n\tfor fn := range files {\n\t\tdn := path.Dir(fn)\n\t\tif fn != dn {\n\t\t\tfs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))\n\t\t}\n\t}\n\tfor _, s := range fs.dirs {\n\t\tsort.Strings(s)\n\t}\n\treturn fs, nil\n}", "func create(rawZipString string) (http.FileSystem, error) {\n\tif zipData == \"\" {\n\t\treturn nil, errors.New(\"statik/fs: no zip data registered\")\n\t}\n\tzipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make(map[string]file, len(zipReader.File))\n\tdirs := make(map[string][]string)\n\tfs := &ginBinFs{files: files, dirs: dirs}\n\tfor _, zipFile := range zipReader.File {\n\t\tfi := zipFile.FileInfo()\n\t\tf := file{FileInfo: fi, fs: fs}\n\t\tf.data, err = unzip(zipFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"statik/fs: error unzipping file %q: %s\", zipFile.Name, err)\n\t\t}\n\t\tfiles[\"/\"+zipFile.Name] = f\n\t}\n\tfor fn := range files {\n\t\t// go up directories recursively in order to care deep directory\n\t\tfor dn := path.Dir(fn); dn != fn; {\n\t\t\tif _, ok := files[dn]; !ok {\n\t\t\t\tfiles[dn] = file{FileInfo: dirInfo{dn}, fs: fs}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfn, dn = dn, path.Dir(dn)\n\t\t}\n\t}\n\tfor fn := range files {\n\t\tdn := path.Dir(fn)\n\t\tif fn != dn {\n\t\t\tfs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))\n\t\t}\n\t}\n\tfor _, s := range fs.dirs {\n\t\tsort.Strings(s)\n\t}\n\treturn fs, nil\n}", "func createFile( filename string) {\n f, err := os.Create(filename)\n u.ErrNil(err, \"Unable to create file\")\n defer f.Close()\n log.Printf(\"Created %s\\n\", f.Name())\n}", "func ServeFuseFS(\n\tfilesys *plugin.Registry,\n\tmountpoint string,\n\tanalyticsClient analytics.Client,\n) (chan<- context.Context, <-chan struct{}, error) {\n\tfuse.Debug = func(msg interface{}) {\n\t\tlog.Tracef(\"FUSE: %v\", msg)\n\t}\n\n\tlog.Infof(\"FUSE: Mounting at %v\", mountpoint)\n\tfuseConn, err := fuse.Mount(mountpoint)\n\tif err != nil {\n\t\treturn nil, nil, mountFailedErr(err)\n\t}\n\n\t// Start the FUSE server. We use the serverExitedCh to catch externally triggered unmounts.\n\t// If we're explicitly asked to shutdown the server, we want to wait until both Unmount and\n\t// Serve have exited before signaling completion.\n\tserverExitedCh := make(chan struct{})\n\tgo func() {\n\t\tserverConfig := &fs.Config{\n\t\t\tWithContext: func(ctx context.Context, req fuse.Request) context.Context {\n\t\t\t\tpid := int(req.Hdr().Pid)\n\t\t\t\tnewctx := context.WithValue(ctx, activity.JournalKey, activity.JournalForPID(pid))\n\t\t\t\tnewctx = context.WithValue(newctx, analytics.ClientKey, analyticsClient)\n\t\t\t\treturn newctx\n\t\t\t},\n\t\t}\n\t\tserver := fs.New(fuseConn, serverConfig)\n\t\troot := newRoot(filesys)\n\t\tif err := server.Serve(&root); err != nil {\n\t\t\tlog.Warnf(\"FUSE: fs.Serve errored with: %v\", err)\n\t\t}\n\n\t\t// check if the mount process has an error to report\n\t\t<-fuseConn.Ready\n\t\tif err := fuseConn.MountError; err != nil {\n\t\t\tlog.Warnf(\"FUSE: Mount process errored with: %v\", err)\n\t\t}\n\t\tlog.Infof(\"FUSE: Serve complete\")\n\n\t\t// Signal that Serve exited so the clean-up goroutine can close the stopped channel\n\t\t// if it hasn't already done so.\n\t\tdefer close(serverExitedCh)\n\t}()\n\n\t// Clean-up\n\tstopCh := make(chan context.Context)\n\tstoppedCh := make(chan struct{})\n\tgo func() {\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\t// Handle explicit shutdown\n\t\t\tlog.Infof(\"FUSE: Shutting down the server\")\n\n\t\t\tlog.Infof(\"FUSE: Unmounting %v\", mountpoint)\n\t\t\tif err = fuse.Unmount(mountpoint); err != nil {\n\t\t\t\tlog.Warnf(\"FUSE: Shutdown failed: %v\", err)\n\t\t\t\tlog.Warnf(\"FUSE: Manual cleanup required: umount %v\", mountpoint)\n\n\t\t\t\t// Retry in a loop until no longer blocked buy an open handle.\n\t\t\t\t// All errors are `*os.PathError`, so we just match a known error string.\n\t\t\t\t// Note that casing of the error message differs on macOS and Linux.\n\t\t\t\tfor ; err != nil && strings.HasSuffix(strings.ToLower(err.Error()), \"resource busy\"); err = fuse.Unmount(mountpoint) {\n\t\t\t\t\tlog.Debugf(\"FUSE: Unmount failed: %v\", err)\n\t\t\t\t\ttime.Sleep(3 * time.Second)\n\t\t\t\t}\n\t\t\t\tlog.Debugf(\"FUSE: Unmount: %v\", err)\n\t\t\t}\n\t\t\tlog.Infof(\"FUSE: Unmount complete\")\n\t\tcase <-serverExitedCh:\n\t\t\t// Server exited on its own, fallthrough.\n\t\t}\n\t\t// Check that Serve has exited successfully in case we initiated the Unmount.\n\t\t<-serverExitedCh\n\t\terr := fuseConn.Close()\n\t\tif err != nil {\n\t\t\tlog.Infof(\"FUSE: Error closing the connection: %v\", err)\n\t\t}\n\t\tlog.Infof(\"FUSE: Server shutdown complete\")\n\t\tclose(stoppedCh)\n\t}()\n\n\treturn stopCh, stoppedCh, nil\n}", "func createFile(filePath string) error {\n\tfile, err := os.OpenFile(filePath, os.O_RDONLY|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn file.Close()\n}", "func (s *mockFSServer) Create(ctx context.Context, r *proto.CreateRequest) (*proto.CreateResponse, error) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.filesCreated[r.Path] = false\n\n\treturn new(proto.CreateResponse), nil\n}", "func createTransfer(path, name string, friendNumber uint32, file *os.File, size uint64, callback func(status State)) *transfer {\n\treturn &transfer{\n\t\tpath: path,\n\t\tname: name,\n\t\tfriend: friendNumber,\n\t\tfile: file,\n\t\tsize: size,\n\t\tprogress: 0,\n\t\tdoneCallback: callback,\n\t\tisDone: false}\n}", "func createDirectories() error {\n\n\tvar brickPath = glusterBrickPath + \"/\" + glusterVolumeName\n\tvar mountPath = glusterMountPath + \"/\" + glusterVolumeName\n\tvar volumePath = glusterDockerVolumePath\n\n\tdirPath := []string{brickPath, mountPath, volumePath}\n\n\tfor i := 0; i < len(dirPath); i++ {\n\t\tif helpers.Exists(dirPath[i]) == false {\n\t\t\terr := helpers.CreateDir(dirPath[i])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (f *Fs) mkdir(ctx context.Context, dirPath string) (err error) {\n\t// defer log.Trace(dirPath, \"\")(\"err=%v\", &err)\n\terr = f._mkdir(ctx, dirPath)\n\tif apiErr, ok := err.(*api.Error); ok {\n\t\t// parent does not exist so create it first then try again\n\t\tif apiErr.StatusCode == http.StatusConflict {\n\t\t\terr = f.mkParentDir(ctx, dirPath)\n\t\t\tif err == nil {\n\t\t\t\terr = f._mkdir(ctx, dirPath)\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func BuildFs(fs Filesystem, basepath string, opts *BuildOpts) (ops chan OpData, prog chan string) {\n\n\tops = make(chan OpData)\n\tprog = make(chan string)\n\n\tgo build(fs, basepath, ops, prog, opts)\n\n\treturn\n}", "func (client *Client) CreateVSwitchWithChan(request *CreateVSwitchRequest) (<-chan *CreateVSwitchResponse, <-chan error) {\n\tresponseChan := make(chan *CreateVSwitchResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateVSwitch(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func createDirectoryOrCancelTask(path string, tid int64,\n\tcancel chan bool) bool {\n\tvar ack bool\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\t\tconn.Call(\"WorkerAPI.PublishTaskResult\", remote_worker.Result{\n\t\t\t\tTid: tid,\n\t\t\t\tStdout: \"\",\n\t\t\t\tStderr: \"Cannot create cache directory!\",\n\t\t\t\tExit_status: -1,\n\t\t\t}, &ack)\n\t\t\t<-cancel\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (c *fileSystemClient) CreateFileURI(ctx context.Context, in *fs.CreateFileURIRequest, opts ...grpc.CallOption) (*fs.CreateFileURIResponse, error) {\n\treturn c.c.CreateFileURI(ctx, in, opts...)\n}", "func (b *Broker) createFolders() (err error) {\n\t_oldUMask := syscall.Umask(0)\n\n\tvar _folderRight os.FileMode\n\t_folderRight = 0755 // for writes... (so creation of file need 'X', hence owner should be RWX = 7, others... usually for R+X = 5)\n\n\t// [Path] Data\n\tlog.Tracef(\"[createFolders] *** data: %v log: %v\", b.Path.Data, b.Path.Log)\n\t_exists, _ := util.IsFileExists(b.Path.Data)\n\tif !_exists {\n\t\terr = os.MkdirAll(b.Path.Data, _folderRight)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\t// [Path] Log\n\t_exists, _ = util.IsFileExists(b.Path.Log)\n\tif !_exists {\n\t\terr = os.MkdirAll(b.Path.Log, _folderRight)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\t// TODO: update folder creation if more configs were added\n\tsyscall.Umask(_oldUMask)\n\n\treturn\n}", "func (client StorageGatewayClient) connectFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems/{fileSystemName}/actions/connect\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ConnectFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func NewFileSystem() FileSystem {\r\n\treturn &osFileSystem{}\r\n}", "func (s *storager) Create(ctx context.Context, location string, mode os.FileMode, reader io.Reader, isDir bool, options ...storage.Option) error {\n\troot := s.Root\n\tif isDir {\n\t\t_, err := root.Folder(location, mode)\n\t\treturn err\n\t}\n\treturn s.Upload(ctx, location, mode, reader)\n}" ]
[ "0.7438406", "0.59352165", "0.58698547", "0.58682775", "0.5800312", "0.5783298", "0.5782387", "0.5774499", "0.56610906", "0.56329244", "0.5362752", "0.53274715", "0.52781004", "0.52586395", "0.52302724", "0.5204847", "0.517791", "0.5176203", "0.5168632", "0.50918365", "0.5090746", "0.50887173", "0.5078688", "0.5070004", "0.5014069", "0.4998363", "0.4966987", "0.4965756", "0.49635392", "0.49505255", "0.49483892", "0.49271625", "0.49203116", "0.49142587", "0.49135125", "0.4898408", "0.4898084", "0.4873829", "0.4859631", "0.48377973", "0.48311728", "0.48270527", "0.48255876", "0.48138842", "0.4810215", "0.48006475", "0.4772576", "0.47668034", "0.47651732", "0.47540152", "0.47516978", "0.47491857", "0.47448534", "0.47374976", "0.4735826", "0.47166464", "0.47125658", "0.47108907", "0.4697916", "0.46862173", "0.46815112", "0.46746534", "0.46739498", "0.4664394", "0.46534875", "0.46508607", "0.46426266", "0.46417794", "0.46410203", "0.46394387", "0.46349168", "0.4629937", "0.46276748", "0.4612222", "0.46106598", "0.4597719", "0.4596728", "0.45904416", "0.45886105", "0.4586888", "0.45717865", "0.45525908", "0.45525286", "0.45525286", "0.45525286", "0.45519158", "0.45517004", "0.45457235", "0.4541163", "0.45408356", "0.45401004", "0.45312417", "0.45234653", "0.45216343", "0.45184454", "0.45148808", "0.45132414", "0.45107666", "0.4509462", "0.45084605" ]
0.80296123
0
CreateFileSystemWithCallback invokes the dfs.CreateFileSystem API asynchronously
func (client *Client) CreateFileSystemWithCallback(request *CreateFileSystemRequest, callback func(response *CreateFileSystemResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *CreateFileSystemResponse var err error defer close(result) response, err = client.CreateFileSystem(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (manager *mockFileSystemManager) CreateFileSystem(ctx context.Context, groupName string, filesystemName string, timeout *int32, xMsDate string, datalakeName string) (*autorest.Response, error) {\n\tfs := fileSystemResource{\n\t\tresourceGroupName: groupName,\n\t\tstorageAccountName: datalakeName,\n\t\tfilesystemName: filesystemName,\n\t}\n\n\tmanager.fileSystemResource = append(manager.fileSystemResource, fs)\n\tmockresponse := helpers.GetRestResponse(http.StatusOK)\n\n\treturn &mockresponse, nil\n}", "func (client *Client) CreateFileSystemWithChan(request *CreateFileSystemRequest) (<-chan *CreateFileSystemResponse, <-chan error) {\n\tresponseChan := make(chan *CreateFileSystemResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateFileSystem(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (c *MockFileStorageClient) CreateFileSystem(ctx context.Context, details filestorage.CreateFileSystemDetails) (*filestorage.FileSystem, error) {\n\treturn &filestorage.FileSystem{Id: &fileSystemID}, nil\n}", "func (client *Client) CreateFileSystem(request *CreateFileSystemRequest) (response *CreateFileSystemResponse, err error) {\n\tresponse = CreateCreateFileSystemResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (client StorageGatewayClient) CreateFileSystem(ctx context.Context, request CreateFileSystemRequest) (response CreateFileSystemResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\n\tif !(request.OpcRetryToken != nil && *request.OpcRetryToken != \"\") {\n\t\trequest.OpcRetryToken = common.String(common.RetryToken())\n\t}\n\n\tociResponse, err = common.Retry(ctx, request, client.createFileSystem, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = CreateFileSystemResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = CreateFileSystemResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(CreateFileSystemResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into CreateFileSystemResponse\")\n\t}\n\treturn\n}", "func (z *zfsctl) CreateFileSystem(ctx context.Context, name string, properties map[string]string) *execute {\n\targs := []string{\"create\", \"-p\"}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func FileSystemCreate(f types.Filesystem) error {\n\tvar cmd *exec.Cmd\n\tvar debugCMD string\n\n\tswitch f.Mount.Format {\n\tcase \"swap\":\n\t\tcmd = exec.Command(\"/sbin/mkswap\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkswap\", f.Mount.Device)\n\tcase \"ext4\", \"ext3\", \"ext2\":\n\t\t// Add filesystem flags\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-t\")\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Format)\n\n\t\t// Add force\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-F\")\n\n\t\t// Add Device to formate\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Device)\n\n\t\t// Format disk\n\t\tcmd = exec.Command(\"/sbin/mke2fs\", f.Mount.Create.Options...)\n\t\tfor i := range f.Mount.Create.Options {\n\t\t\tdebugCMD = fmt.Sprintf(\"%s %s\", debugCMD, f.Mount.Create.Options[i])\n\t\t}\n\tcase \"vfat\":\n\t\tcmd = exec.Command(\"/sbin/mkfs.fat\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkfs.fat\", f.Mount.Device)\n\tdefault:\n\t\tlog.Warnf(\"Unknown filesystem type [%s]\", f.Mount.Format)\n\t}\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\n\treturn nil\n}", "func (client *Client) ListFileSystemsWithCallback(request *ListFileSystemsRequest, callback func(response *ListFileSystemsResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ListFileSystemsResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ListFileSystems(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client StorageGatewayClient) createFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func CreateFilesystem(e *efs.EFS, n string) (*efs.FileSystemDescription, error) {\n\tcreateParams := &efs.CreateFileSystemInput{\n\t\tCreationToken: aws.String(n),\n\t}\n\tcreateResp, err := e.CreateFileSystem(createParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for the filesystem to become available.\n\tfor {\n\t\tfs, err := DescribeFilesystem(e, n)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(fs.FileSystems) > 0 {\n\t\t\tif *fs.FileSystems[0].LifeCycleState == efsAvail {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n\treturn createResp, nil\n}", "func CreateCreateFileSystemRequest() (request *CreateFileSystemRequest) {\n\trequest = &CreateFileSystemRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"CreateFileSystem\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func newFileSystem(basedir string, mkdir osMkdirAll) (*FS, error) {\n\tif err := mkdir(basedir, 0700); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &FS{basedir: basedir}, nil\n}", "func (*FileSystemBase) Create(path string, flags int, mode uint32) (int, uint64) {\n\treturn -ENOSYS, ^uint64(0)\n}", "func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateFileSystemInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateFileSystem\", params, optFns, c.addOperationCreateFileSystemMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateFileSystemOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (client *Client) CreateFileDetectWithCallback(request *CreateFileDetectRequest, callback func(response *CreateFileDetectResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFileDetectResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFileDetect(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func CreateCreateFileSystemResponse() (response *CreateFileSystemResponse) {\n\tresponse = &CreateFileSystemResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func NewFileSystem(token string, debug bool) *FileSystem {\n\toauthClient := oauth2.NewClient(\n\t\toauth2.NoContext,\n\t\toauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}),\n\t)\n\tclient := putio.NewClient(oauthClient)\n\tclient.UserAgent = defaultUserAgent\n\n\treturn &FileSystem{\n\t\tputio: client,\n\t\tlogger: NewLogger(\"putiofs: \", debug),\n\t}\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\troot = parsePath(root)\n\tclient := fshttp.NewClient(ctx)\n\tf := &Fs{\n\t\tname: name,\n\t\troot: root,\n\t\topt: *opt,\n\t\tsrv: rest.NewClient(client).SetRoot(rootURL),\n\t\tpacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),\n\t\tm: m,\n\t\tauthExpiry: parseExpiry(opt.AuthorizationExpiry),\n\t}\n\tf.features = (&fs.Features{\n\t\tCaseInsensitive: true,\n\t\tCanHaveEmptyDirectories: true,\n\t}).Fill(ctx, f)\n\tf.srv.SetSigner(f.getAuth) // use signing hook to get the auth\n\tf.srv.SetErrorHandler(errorHandler)\n\n\t// Get rootID\n\tif f.opt.RootID == \"\" {\n\t\tuser, err := f.getUser(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.opt.RootID = user.SyncFolders\n\t\tif strings.HasSuffix(f.opt.RootID, \"/contents\") {\n\t\t\tf.opt.RootID = f.opt.RootID[:len(f.opt.RootID)-9]\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"unexpected rootID %q\", f.opt.RootID)\n\t\t}\n\t\t// Cache the results\n\t\tf.m.Set(\"root_id\", f.opt.RootID)\n\t\tf.opt.DeletedID = user.Deleted\n\t\tf.m.Set(\"deleted_id\", f.opt.DeletedID)\n\t}\n\tf.dirCache = dircache.New(root, f.opt.RootID, f)\n\n\t// Find the current root\n\terr = f.dirCache.FindRoot(ctx, false)\n\tif err != nil {\n\t\t// Assume it is a file\n\t\tnewRoot, remote := dircache.SplitPath(root)\n\t\toldDirCache := f.dirCache\n\t\tf.dirCache = dircache.New(newRoot, f.opt.RootID, f)\n\t\tf.root = newRoot\n\t\tresetF := func() {\n\t\t\tf.dirCache = oldDirCache\n\t\t\tf.root = root\n\t\t}\n\t\t// Make new Fs which is the parent\n\t\terr = f.dirCache.FindRoot(ctx, false)\n\t\tif err != nil {\n\t\t\t// No root so return old f\n\t\t\tresetF()\n\t\t\treturn f, nil\n\t\t}\n\t\t_, err := f.newObjectWithInfo(ctx, remote, nil)\n\t\tif err != nil {\n\t\t\tif err == fs.ErrorObjectNotFound {\n\t\t\t\t// File doesn't exist so return old f\n\t\t\t\tresetF()\n\t\t\t\treturn f, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\t// return an error with an fs which points to the parent\n\t\treturn f, fs.ErrorIsFile\n\t}\n\treturn f, nil\n}", "func MakeFsOnDisk() FileSystem { return filesys.MakeFsOnDisk() }", "func (storage *B2Storage) CreateDirectory(threadIndex int, dir string) (err error) {\n return nil\n}", "func (fs ReverseHttpFs) Create(n string) (afero.File, error) {\n\treturn nil, syscall.EPERM\n}", "func NewFileSystem(fs http.FileSystem, name string) FileSystem {\n\treturn Trace(&fileSystem{fs}, name)\n}", "func (realFS) Create(name string) (File, error) { return os.Create(name) }", "func (s *Service) Create(parent *basefs.File, name string, isDir bool) (*basefs.File, error) {\n\tparentID := \"\"\n\tvar megaParent *mega.Node\n\tif parent == nil {\n\t\tmegaParent = s.megaCli.FS.GetRoot()\n\t} else {\n\t\tparentID = parent.ID\n\t\tmegaParent = parent.Data.(*MegaPath).Node\n\t}\n\n\tnewName := parentID + \"/\" + name\n\tif isDir {\n\t\tnewNode, err := s.megaCli.CreateDir(name, megaParent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\t}\n\n\t// Create tempFile, since mega package does not accept a reader\n\tf, err := ioutil.TempFile(os.TempDir(), \"megafs\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Close() // we don't need the descriptor, only the name\n\n\tprogress := make(chan int, 1)\n\t// Upload empty file\n\tnewNode, err := s.megaCli.UploadFile(f.Name(), megaParent, name, &progress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t<-progress\n\n\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\n}", "func (fsOnDisk) Create(name string) (File, error) { return os.Create(name) }", "func (fsys *FS) Create(filePath string, flags int, mode uint32) (errc int, fh uint64) {\n\tdefer fs.Trace(filePath, \"flags=0x%X, mode=0%o\", flags, mode)(\"errc=%d, fh=0x%X\", &errc, &fh)\n\tleaf, parentDir, errc := fsys.lookupParentDir(filePath)\n\tif errc != 0 {\n\t\treturn errc, fhUnset\n\t}\n\t_, handle, err := parentDir.Create(leaf)\n\tif err != nil {\n\t\treturn translateError(err), fhUnset\n\t}\n\treturn 0, fsys.openFilesWr.Open(handle)\n}", "func (fl *FolderList) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (_ fs.Node, _ fs.Handle, err error) {\n\tfl.fs.vlog.CLogf(ctx, libkb.VLog1, \"FL Create\")\n\ttlfName := tlf.CanonicalName(req.Name)\n\tdefer func() { err = fl.processError(ctx, libkbfs.WriteMode, tlfName, err) }()\n\tif strings.HasPrefix(req.Name, \"._\") {\n\t\t// Quietly ignore writes to special macOS files, without\n\t\t// triggering a notification.\n\t\treturn nil, nil, syscall.ENOENT\n\t}\n\treturn nil, nil, libkbfs.NewWriteUnsupportedError(tlfhandle.BuildCanonicalPath(fl.PathType(), string(tlfName)))\n}", "func NewFileSystemClient() (FileSystemClient, error) {\n\taddress := os.Getenv(constants.EnvFileSystemAddress)\n\tif address == \"\" {\n\t\treturn nil, fmt.Errorf(\"Environment variable '%s' not set\", constants.EnvFileSystemAddress)\n\t}\n\n\t// Create a connection\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a client\n\tc := fs.NewFileSystemClient(conn)\n\n\treturn &fileSystemClient{c: c, conn: conn}, nil\n}", "func (z *ZfsH) CreateFilesystem(name string, properties map[string]string) (*Dataset, error) {\n\targs := make([]string, 1, 4)\n\targs[0] = \"create\"\n\n\tif properties != nil {\n\t\targs = append(args, propsSlice(properties)...)\n\t}\n\n\targs = append(args, name)\n\t_, err := z.zfs(args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn z.GetDataset(name)\n}", "func NewFileSystem() FileSystem {\n\treturn &fs{\n\t\trunner: NewCommandRunner(),\n\t}\n}", "func Create(fsys fs.FS, name string) (WriterFile, error) {\n\tcfs, ok := fsys.(CreateFS)\n\tif !ok {\n\t\treturn nil, &fs.PathError{Op: \"create\", Path: name, Err: fmt.Errorf(\"not implemented on type %T\", fsys)}\n\t}\n\treturn cfs.Create(name)\n}", "func (fs *VolatileFileSystem) CreateFile(name string, data []byte) error {\n\tvar flags C.int = C.SQLITE_OPEN_EXCLUSIVE | C.SQLITE_OPEN_CREATE\n\n\tiFd, rc := fs.vfs.Open(name, flags)\n\tif rc != C.SQLITE_OK {\n\t\treturn Error{\n\t\t\tCode: ErrIoErr,\n\t\t\tExtendedCode: ErrNoExtended(rc),\n\t\t}\n\t}\n\n\tfile, _ := fs.vfs.FileByFD(iFd)\n\tfile.mu.Lock()\n\tfile.data = data\n\tfile.mu.Unlock()\n\n\treturn nil\n}", "func (client *Client) ListAvailableFileSystemTypesWithCallback(request *ListAvailableFileSystemTypesRequest, callback func(response *ListAvailableFileSystemTypesResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ListAvailableFileSystemTypesResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ListAvailableFileSystemTypes(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func NewFS(basedir string) (kvs *FS, err error) {\n\treturn newFileSystem(basedir, os.MkdirAll)\n}", "func (f *Fs) createFile(ctx context.Context, pathID, leaf, mimeType string) (newID string, err error) {\n\tvar resp *http.Response\n\topts := rest.Opts{\n\t\tMethod: \"POST\",\n\t\tRootURL: pathID,\n\t\tNoResponse: true,\n\t}\n\tmkdir := api.CreateFile{\n\t\tName: f.opt.Enc.FromStandardName(leaf),\n\t\tMediaType: mimeType,\n\t}\n\terr = f.pacer.Call(func() (bool, error) {\n\t\tresp, err = f.srv.CallXML(ctx, &opts, &mkdir, nil)\n\t\treturn shouldRetry(ctx, resp, err)\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp.Header.Get(\"Location\"), nil\n}", "func createFile(fs fileSystem, fileName string) (file, error) {\n\treturn fs.Create(fileName)\n}", "func (fsys *gcsFS) Create(name string) (WriterFile, error) {\n\tf, err := fsys.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.(*GCSFile), nil\n}", "func NewCfnFileSystem(scope awscdk.Construct, id *string, props *CfnFileSystemProps) CfnFileSystem {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnFileSystem{}\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_fsx.CfnFileSystem\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func (dir *HgmDir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\treturn nil, nil, fuse.Errno(syscall.EROFS)\n}", "func (d *Definition) Create() error {\n\terrChan := make(chan error)\n\ttree := d.ResourceTree\n\n\t// Check definition context exists\n\tif _, err := os.Stat(tree.Root().ID()); err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t`Definition Create: Expected context: \"%s\" to exist.`,\n\t\t\ttree.Root().Name(),\n\t\t)\n\t}\n\n\tgo func() {\n\t\tdefer close(errChan)\n\t\ttree.Traverse(func(r Resource) {\n\t\t\terrChan <- r.Create(d.Options)\n\t\t})\n\t}()\n\n\tfor err := range errChan {\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Definition Create: %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func CreateRecursive(ctx context.Context, conn *ZkConn, zkPath string, value []byte, flags int32, aclv []zk.ACL, maxCreationDepth int) (string, error) {\n\tpathCreated, err := conn.Create(ctx, zkPath, value, flags, aclv)\n\tif err == zk.ErrNoNode {\n\t\tif maxCreationDepth == 0 {\n\t\t\treturn \"\", zk.ErrNoNode\n\t\t}\n\n\t\t// Make sure that nodes are either \"file\" or\n\t\t// \"directory\" to mirror file system semantics.\n\t\tdirAclv := make([]zk.ACL, len(aclv))\n\t\tfor i, acl := range aclv {\n\t\t\tdirAclv[i] = acl\n\t\t\tdirAclv[i].Perms = PermDirectory\n\t\t}\n\t\tparentPath := path.Dir(zkPath)\n\t\t_, err = CreateRecursive(ctx, conn, parentPath, nil, 0, dirAclv, maxCreationDepth-1)\n\t\tif err != nil && err != zk.ErrNodeExists {\n\t\t\treturn \"\", err\n\t\t}\n\t\tpathCreated, err = conn.Create(ctx, zkPath, value, flags, aclv)\n\t}\n\treturn pathCreated, err\n}", "func (fs *FileSystem) Create(name string) (afero.File, error) {\n\tlogger.Println(\"Create\", name)\n\tname = normalizePath(name)\n\tpath := filepath.Dir(name)\n\n\tif err := fs.MkdirAll(path, os.ModeDir); err != nil {\n\t\treturn nil, &os.PathError{Op: \"create\", Path: name, Err: err}\n\t}\n\n\tfs.Lock()\n\tfileData := CreateFile(name)\n\tfs.data[name] = fileData\n\tfs.Unlock()\n\n\treturn NewFileHandle(fs, fileData), nil\n}", "func (client *Client) CreateGatewayFileShareWithCallback(request *CreateGatewayFileShareRequest, callback func(response *CreateGatewayFileShareResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateGatewayFileShareResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateGatewayFileShare(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\td.fs.logger.Debugf(\"File create request for %v\\n\", d)\n\n\tu, err := d.fs.putio.Files.Upload(ctx, strings.NewReader(\"\"), req.Name, d.ID)\n\tif err != nil {\n\t\td.fs.logger.Printf(\"Upload failed: %v\\n\", err)\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\t// possibly a torrent file is uploaded. torrent files are picked up by the\n\t// Put.io API and pushed into the transfer queue. Original torrent file is\n\t// not keeped.\n\tif u.Transfer != nil {\n\t\treturn nil, nil, fuse.ENOENT\n\t}\n\n\tif u.File == nil {\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\tf := &File{fs: d.fs, File: u.File}\n\n\treturn f, f, nil\n}", "func CreateListFileSystemsRequest() (request *ListFileSystemsRequest) {\n\trequest = &ListFileSystemsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"ListFileSystems\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func NewFileSystemClient() FileSystemClient {\n\treturn FsClient{}\n}", "func (self *File_Client) CreateDir(path interface{}, name interface{}) error {\n\n\trqst := &filepb.CreateDirRequest{\n\t\tPath: Utility.ToString(path),\n\t\tName: Utility.ToString(name),\n\t}\n\n\t_, err := self.c.CreateDir(context.Background(), rqst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (fs *FileSystem) CreateFile(fileName string, data string, parentInodeNum int, fileType int) error {\n\n\t// Validation of the arguments\n\t// TODO same name file in the directory.\n\tif err := fs.validateCreationRequest(fileName); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while validating : \", err)\n\t\treturn err\n\t}\n\tdataBlockRequired := int(math.Ceil(float64(len(data) / DataBlockSize)))\n\t// Check resources available or not\n\tif err := resourceAvailable(fs, dataBlockRequired); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while check availabilty of resource : \", err)\n\t\treturn err\n\t}\n\n\tfmt.Println(\"filename\", fileName, \"datablockrequired\", dataBlockRequired)\n\t// Get Parent Inode\n\tparInode, err := getInodeInfo(parentInodeNum)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to get parent inode \", err)\n\t\treturn err\n\t}\n\n\t// check parent inode has space to accomodate new file/ directory inside it.\n\t// here 4 is used because 1 for comma and 3 bytes representing inode number.\n\tif len(parInode) < (InodeBlockSize - 4) {\n\t\treturn fmt.Errorf(\"Parent inode doesn't have space left to accomodate new file in it\")\n\t}\n\n\t// Allocate an inode and intialise\n\tif dataBlockRequired != 0 {\n\t\tdataBlockRequired++\n\t}\n\tinode := inode{fs.nextFreeInode[0], fileType, parentInodeNum, fs.nextFreeDataBlock[:dataBlockRequired]}\n\n\tfmt.Println(\"inode\", inode)\n\t// Update fst with new inode entries.\n\tfs.UpdateFst(inode)\n\n\t// Add entry in FST in memory\n\tfs.fileSystemTable[fileName] = inode.inodeNum\n\n\tparentInode := parseInode(parInode)\n\tparentInode.dataList = append(parentInode.dataList, inode.inodeNum)\n\n\t// Update the dumpFile with the file content.\n\tif err := UpdateDumpFile(inode, data, fileName, parentInode, parentInodeNum); err != nil {\n\t\tfmt.Println(\"unable to update the disk : \", err)\n\t\treturn err\n\t}\n\n\t// TODO : After successfull creation of file, update the directory data block accordingly..\n\n\tfmt.Println(\"successful updation in disk\", inode)\n\n\treturn nil\n}", "func NewFileSystem(t mockConstructorTestingTNewFileSystem) *FileSystem {\n\tmock := &FileSystem{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (f *FakeFileSystem) Create(file string) (io.WriteCloser, error) {\n\tf.CreateFile = file\n\treturn &f.CreateContent, f.CreateError\n}", "func NewFileSystem() FileSystem {\r\n\treturn &osFileSystem{}\r\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\t// Parse config into Options struct\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = checkUploadChunkSize(opt.ChunkSize)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"dropbox: chunk size: %w\", err)\n\t}\n\n\t// Convert the old token if it exists. The old token was just\n\t// just a string, the new one is a JSON blob\n\toldToken, ok := m.Get(config.ConfigToken)\n\toldToken = strings.TrimSpace(oldToken)\n\tif ok && oldToken != \"\" && oldToken[0] != '{' {\n\t\tfs.Infof(name, \"Converting token to new format\")\n\t\tnewToken := fmt.Sprintf(`{\"access_token\":\"%s\",\"token_type\":\"bearer\",\"expiry\":\"0001-01-01T00:00:00Z\"}`, oldToken)\n\t\terr := config.SetValueAndSave(name, config.ConfigToken, newToken)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"NewFS convert token: %w\", err)\n\t\t}\n\t}\n\n\toAuthClient, _, err := oauthutil.NewClient(ctx, name, m, getOauthConfig(m))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to configure dropbox: %w\", err)\n\t}\n\n\tci := fs.GetConfig(ctx)\n\n\tf := &Fs{\n\t\tname: name,\n\t\topt: *opt,\n\t\tci: ci,\n\t\tpacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(opt.PacerMinSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),\n\t}\n\tf.batcher, err = newBatcher(ctx, f, f.opt.BatchMode, f.opt.BatchSize, time.Duration(f.opt.BatchTimeout))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg := dropbox.Config{\n\t\tLogLevel: dropbox.LogOff, // logging in the SDK: LogOff, LogDebug, LogInfo\n\t\tClient: oAuthClient, // maybe???\n\t\tHeaderGenerator: f.headerGenerator,\n\t}\n\n\t// unauthorized config for endpoints that fail with auth\n\tucfg := dropbox.Config{\n\t\tLogLevel: dropbox.LogOff, // logging in the SDK: LogOff, LogDebug, LogInfo\n\t}\n\n\t// NOTE: needs to be created pre-impersonation so we can look up the impersonated user\n\tf.team = team.New(cfg)\n\n\tif opt.Impersonate != \"\" {\n\t\tuser := team.UserSelectorArg{\n\t\t\tEmail: opt.Impersonate,\n\t\t}\n\t\tuser.Tag = \"email\"\n\n\t\tmembers := []*team.UserSelectorArg{&user}\n\t\targs := team.NewMembersGetInfoArgs(members)\n\n\t\tmemberIds, err := f.team.MembersGetInfo(args)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid dropbox team member: %q: %w\", opt.Impersonate, err)\n\t\t}\n\t\tif len(memberIds) == 0 || memberIds[0].MemberInfo == nil || memberIds[0].MemberInfo.Profile == nil {\n\t\t\treturn nil, fmt.Errorf(\"dropbox team member not found: %q\", opt.Impersonate)\n\t\t}\n\n\t\tcfg.AsMemberID = memberIds[0].MemberInfo.Profile.MemberProfile.TeamMemberId\n\t}\n\n\tf.srv = files.New(cfg)\n\tf.svc = files.New(ucfg)\n\tf.sharing = sharing.New(cfg)\n\tf.users = users.New(cfg)\n\tf.features = (&fs.Features{\n\t\tCaseInsensitive: true,\n\t\tReadMimeType: false,\n\t\tCanHaveEmptyDirectories: true,\n\t})\n\n\t// do not fill features yet\n\tif f.opt.SharedFiles {\n\t\tf.setRoot(root)\n\t\tif f.root == \"\" {\n\t\t\treturn f, nil\n\t\t}\n\t\t_, err := f.findSharedFile(ctx, f.root)\n\t\tf.root = \"\"\n\t\tif err == nil {\n\t\t\treturn f, fs.ErrorIsFile\n\t\t}\n\t\treturn f, nil\n\t}\n\n\tif f.opt.SharedFolders {\n\t\tf.setRoot(root)\n\t\tif f.root == \"\" {\n\t\t\treturn f, nil // our root it empty so we probably want to list shared folders\n\t\t}\n\n\t\tdir := path.Dir(f.root)\n\t\tif dir == \".\" {\n\t\t\tdir = f.root\n\t\t}\n\n\t\t// root is not empty so we have find the right shared folder if it exists\n\t\tid, err := f.findSharedFolder(ctx, dir)\n\t\tif err != nil {\n\t\t\t// if we didn't find the specified shared folder we have to bail out here\n\t\t\treturn nil, err\n\t\t}\n\t\t// we found the specified shared folder so let's mount it\n\t\t// this will add it to the users normal root namespace and allows us\n\t\t// to actually perform operations on it using the normal api endpoints.\n\t\terr = f.mountSharedFolder(ctx, id)\n\t\tif err != nil {\n\t\t\tswitch e := err.(type) {\n\t\t\tcase sharing.MountFolderAPIError:\n\t\t\t\tif e.EndpointError == nil || (e.EndpointError != nil && e.EndpointError.Tag != sharing.MountFolderErrorAlreadyMounted) {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// if the mount failed we have to abort here\n\t\t}\n\t\t// if the mount succeeded it's now a normal folder in the users root namespace\n\t\t// we disable shared folder mode and proceed normally\n\t\tf.opt.SharedFolders = false\n\t}\n\n\tf.features.Fill(ctx, f)\n\n\t// If root starts with / then use the actual root\n\tif strings.HasPrefix(root, \"/\") {\n\t\tvar acc *users.FullAccount\n\t\terr = f.pacer.Call(func() (bool, error) {\n\t\t\tacc, err = f.users.GetCurrentAccount()\n\t\t\treturn shouldRetry(ctx, err)\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"get current account failed: %w\", err)\n\t\t}\n\t\tswitch x := acc.RootInfo.(type) {\n\t\tcase *common.TeamRootInfo:\n\t\t\tf.ns = x.RootNamespaceId\n\t\tcase *common.UserRootInfo:\n\t\t\tf.ns = x.RootNamespaceId\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown RootInfo type %v %T\", acc.RootInfo, acc.RootInfo)\n\t\t}\n\t\tfs.Debugf(f, \"Using root namespace %q\", f.ns)\n\t}\n\tf.setRoot(root)\n\n\t// See if the root is actually an object\n\tif f.root != \"\" {\n\t\t_, err = f.getFileMetadata(ctx, f.slashRoot)\n\t\tif err == nil {\n\t\t\tnewRoot := path.Dir(f.root)\n\t\t\tif newRoot == \".\" {\n\t\t\t\tnewRoot = \"\"\n\t\t\t}\n\t\t\tf.setRoot(newRoot)\n\t\t\t// return an error with an fs which points to the parent\n\t\t\treturn f, fs.ErrorIsFile\n\t\t}\n\t}\n\treturn f, nil\n}", "func (fb *FileBase) Create(ID string) (io.WriteCloser, error) {\n\treturn fb.fs.Create(filepath.Join(fb.root, ID))\n}", "func (a DBFSAPI) Create(path string, overwrite bool, data string) (err error) {\n\tbyteArr, err := base64.StdEncoding.DecodeString(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbyteChunks := split(byteArr, 1e6)\n\thandle, err := a.createHandle(path, overwrite)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\terr = a.closeHandle(handle)\n\t}()\n\tfor _, byteChunk := range byteChunks {\n\t\tb64Data := base64.StdEncoding.EncodeToString(byteChunk)\n\t\terr := a.addBlock(b64Data, handle)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}", "func (ks *KopiaSnapshotter) ConnectOrCreateFilesystem(path string) error {\n\treturn nil\n}", "func getFileSystem(frame *rtda.Frame) {\n\tthread := frame.Thread\n\tunixFsClass := frame.GetClassLoader().LoadClass(\"java/io/UnixFileSystem\")\n\tif unixFsClass.InitializationNotStarted() {\n\t\tframe.NextPC = thread.PC // undo getFileSystem\n\t\tthread.InitClass(unixFsClass)\n\t\treturn\n\t}\n\n\tunixFsObj := unixFsClass.NewObj()\n\tframe.PushRef(unixFsObj)\n\n\t// call <init>\n\tframe.PushRef(unixFsObj) // this\n\tconstructor := unixFsClass.GetDefaultConstructor()\n\tthread.InvokeMethod(constructor)\n}", "func (linux *Linux) FileCreate(filePath string) error {\n\tif !linux.FileExists(filePath) {\n\t\tfile, err := os.Create(linux.applyChroot(filePath))\n\t\tdefer file.Close()\n\t\treturn err\n\t}\n\treturn os.ErrExist\n}", "func NewFileSystemServer(fs FileSystem) fuse.Server {\n\treturn &fileSystemServer{\n\t\tfs: fs,\n\t}\n}", "func createTransfer(path, name string, friendNumber uint32, file *os.File, size uint64, callback func(status State)) *transfer {\n\treturn &transfer{\n\t\tpath: path,\n\t\tname: name,\n\t\tfriend: friendNumber,\n\t\tfile: file,\n\t\tsize: size,\n\t\tprogress: 0,\n\t\tdoneCallback: callback,\n\t\tisDone: false}\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\t// Parse config into Options struct\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(opt.Headers)%2 != 0 {\n\t\treturn nil, errors.New(\"odd number of headers supplied\")\n\t}\n\n\tif !strings.HasSuffix(opt.Endpoint, \"/\") {\n\t\topt.Endpoint += \"/\"\n\t}\n\n\t// Parse the endpoint and stick the root onto it\n\tbase, err := url.Parse(opt.Endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu, err := rest.URLJoin(base, rest.URLPathEscape(root))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := fshttp.NewClient(ctx)\n\n\tendpoint, isFile := getFsEndpoint(ctx, client, u.String(), opt)\n\tfs.Debugf(nil, \"Root: %s\", endpoint)\n\tu, err = url.Parse(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tci := fs.GetConfig(ctx)\n\tf := &Fs{\n\t\tname: name,\n\t\troot: root,\n\t\topt: *opt,\n\t\tci: ci,\n\t\thttpClient: client,\n\t\tendpoint: u,\n\t\tendpointURL: u.String(),\n\t}\n\tf.features = (&fs.Features{\n\t\tCanHaveEmptyDirectories: true,\n\t}).Fill(ctx, f)\n\n\tif isFile {\n\t\t// return an error with an fs which points to the parent\n\t\treturn f, fs.ErrorIsFile\n\t}\n\n\tif !strings.HasSuffix(f.endpointURL, \"/\") {\n\t\treturn nil, errors.New(\"internal error: url doesn't end with /\")\n\t}\n\n\treturn f, nil\n}", "func NewFs(client *api.Client) (*fs, nodefs.Node) {\n\tdefaultfs := pathfs.NewDefaultFileSystem() // Returns ENOSYS by default\n\treadonlyfs := pathfs.NewReadonlyFileSystem(defaultfs) // R/W calls return EPERM\n\n\tkwfs := &fs{readonlyfs, client}\n\tnfs := pathfs.NewPathNodeFs(kwfs, nil)\n\tnfs.SetDebug(true)\n\treturn kwfs, nfs.Root()\n}", "func NewFileSystem(ctrl *gomock.Controller) *FileSystem {\n\tmock := &FileSystem{ctrl: ctrl}\n\tmock.recorder = &FileSystemMockRecorder{mock}\n\treturn mock\n}", "func (fs *EmbedFs) Create(path string) (file, error) {\n\treturn nil, ErrNotAvail\n}", "func (mzk *MockZK) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {\n\tmzk.Args = append(mzk.Args, []interface{}{\n\t\t\"create\",\n\t\tpath,\n\t\tdata,\n\t\tflags,\n\t\tacl,\n\t})\n\treturn mzk.CreateFn(path, data, flags, acl)\n}", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\t// fmt.Printf(\"creating file in dir with inode %d\\n\", d.inodeNum)\n\t// fmt.Println(\"name of file to be created is: \" + req.Name)\n\tdirTable, err := getTable(d.inode)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfileExists := dirTable.Table[req.Name] != 0\n\tvar inode *Inode\n\tvar inodeNum uint64\n\tif !fileExists {\n\t\t// fmt.Println(\"file does not yet exist in Create\")\n\t\tvar isDir int8 = 0\n\t\tinode = createInode(isDir)\n\t\tinodeNum = d.inodeStream.next()\n\t\tinode.init(d.inodeNum, inodeNum)\n\t\td.addFile(req.Name, inodeNum)\n\t} else {\n\t\t// fmt.Println(\"file already exists in Create\")\n\t\tinodeNum = dirTable.Table[req.Name]\n\t\tinode, err = getInode(inodeNum)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tchild := &File{\n\t\tinode: inode,\n\t\tinodeNum: inodeNum,\n\t\tinodeStream: d.inodeStream,\n\t}\n\thandle := &FileHandle{\n\t\tinode: inode,\n\t\tinodeNum: inodeNum,\n\t}\n\t// can any errors happen here?\n\treturn child, handle, nil\n}", "func (f *Fs) mkdir(ctx context.Context, dirPath string) (err error) {\n\t// defer log.Trace(dirPath, \"\")(\"err=%v\", &err)\n\terr = f._mkdir(ctx, dirPath)\n\tif apiErr, ok := err.(*api.Error); ok {\n\t\t// parent does not exist so create it first then try again\n\t\tif apiErr.StatusCode == http.StatusConflict {\n\t\t\terr = f.mkParentDir(ctx, dirPath)\n\t\t\tif err == nil {\n\t\t\t\terr = f._mkdir(ctx, dirPath)\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func (fs *dsFileSys) Create(name string) (fsi.File, error) {\n\n\t// WriteFile & Create\n\tdir, bname := fs.SplitX(name)\n\n\tf := DsFile{}\n\tf.fSys = fs\n\tf.BName = common.Filify(bname)\n\tf.Dir = dir\n\tf.MModTime = time.Now()\n\tf.MMode = 0644\n\n\t// let all the properties by set by fs.saveFileByPath\n\terr := f.Sync()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// return &f, nil\n\tff := fsi.File(&f)\n\treturn ff, err\n\n}", "func Create(name string) (*os.File, error)", "func (fs osFS) Create(path string) (io.WriteCloser, error) {\n\tf, err := os.Create(fs.resolve(path))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif fi.IsDir() {\n\t\treturn nil, fmt.Errorf(\"Open: %s is a directory\", path)\n\t}\n\n\treturn f, nil\n}", "func (fs *bundleFs) Create(name string) (afero.File, error) {\n\treturn nil, ErrReadOnly\n}", "func (c *fileSystemClient) CreateVolumeForWrite(ctx context.Context, in *fs.CreateVolumeForWriteRequest, opts ...grpc.CallOption) (*fs.CreateVolumeForWriteResponse, error) {\n\treturn c.c.CreateVolumeForWrite(ctx, in, opts...)\n}", "func (z *zfsctl) MountFileSystem(ctx context.Context, name, options, opts string, all bool) *execute {\n\targs := []string{\"mount\"}\n\tif len(options) > 0 {\n\t\targs = append(args, options)\n\t}\n\tif len(opts) > 0 {\n\t\targs = append(args, opts)\n\t}\n\tif all {\n\t\targs = append(args, \"-a\")\n\t} else {\n\t\targs = append(args, name)\n\t}\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (s *storager) Create(ctx context.Context, location string, mode os.FileMode, reader io.Reader, isDir bool, options ...storage.Option) error {\n\troot := s.Root\n\tif isDir {\n\t\t_, err := root.Folder(location, mode)\n\t\treturn err\n\t}\n\treturn s.Upload(ctx, location, mode, reader)\n}", "func NewFs(remote string) fs.Fs {\n\tf, err := fs.NewFs(remote)\n\tif err != nil {\n\t\tfs.Stats.Error()\n\t\tlog.Fatalf(\"Failed to create file system for %q: %v\", remote, err)\n\t}\n\treturn f\n}", "func (a *FileStorageApiService) CreateDirectoryExecute(r ApiCreateDirectoryRequest) (SingleNode, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue SingleNode\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.Ctx, \"FileStorageApiService.CreateDirectory\")\n\tif localBasePath == \"/\" {\n\t localBasePath = \"\"\n\t}\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v2/file_storage/buckets/{bucket_id}/create_directory\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"bucket_id\"+\"}\", _neturl.PathEscape(parameterToString(r.P_bucketId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.P_nodeRequest == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"nodeRequest is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.P_nodeRequest\n\treq, err := a.client.prepareRequest(r.Ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (*FileSystemBase) Fsync(path string, datasync bool, fh uint64) int {\n\treturn -ENOSYS\n}", "func CheckFsCreationInProgress(device model.Device) (inProgress bool, err error) {\n\treturn linux.CheckFsCreationInProgress(device)\n}", "func (fsi *fsIOPool) Create(path string) (wlk *lock.LockedFile, err error) {\n\tif err = checkPathLength(path); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Creates parent if missing.\n\tif err = mkdirAll(pathutil.Dir(path), 0777); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Attempt to create the file.\n\twlk, err = lock.LockedOpenFile(path, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\tswitch {\n\t\tcase os.IsPermission(err):\n\t\t\treturn nil, errFileAccessDenied\n\t\tcase isSysErrIsDir(err):\n\t\t\treturn nil, errIsNotRegular\n\t\tcase isSysErrPathNotFound(err):\n\t\t\treturn nil, errFileAccessDenied\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Success.\n\treturn wlk, nil\n}", "func (client *Client) ListFileSystemsWithChan(request *ListFileSystemsRequest) (<-chan *ListFileSystemsResponse, <-chan error) {\n\tresponseChan := make(chan *ListFileSystemsResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.ListFileSystems(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (c *fileSystemClient) CreateFileView(ctx context.Context, in *fs.CreateFileViewRequest, opts ...grpc.CallOption) (*fs.CreateFileViewResponse, error) {\n\treturn c.c.CreateFileView(ctx, in, opts...)\n}", "func NewFS(db *bolt.DB, bucketpath string) (*FileSystem, error) {\n\n\t// create buckets\n\terr := db.Update(func(tx *bolt.Tx) error {\n\t\treturn bucketInit(tx, bucketpath)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// load or initialize\n\trootIno := uint64(1)\n\tfs := &FileSystem{\n\t\tdb: db,\n\t\tbucket: bucketpath,\n\t\trootIno: rootIno,\n\t\tcwd: \"/\",\n\t}\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\tbb, err := openBucket(tx, bucketpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb := newFsBucket(bb)\n\n\t\t// create the `nil` node if it doesn't exist\n\t\terr = b.InodeInit()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// load the\n\t\tdata := make([]byte, 4)\n\t\tbinary.BigEndian.PutUint32(data, uint32(0755))\n\t\t_, err = b.LoadOrSet(\"umask\", data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// load the root Ino if one is available\n\t\tdata, err = b.LoadOrSet(\"rootIno\", i2b(rootIno))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trootIno = b2i(data)\n\n\t\t_, err = b.GetInode(rootIno)\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tif err == os.ErrNotExist {\n\t\t\tnode := newInode(os.ModeDir | 0755)\n\t\t\tnode.countUp()\n\t\t\terr = b.PutInode(rootIno, node)\n\t\t\tif err != nil {\n\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfs.rootIno = rootIno\n\treturn fs, nil\n\n}", "func (client *Client) RenameDbfsWithCallback(request *RenameDbfsRequest, callback func(response *RenameDbfsResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *RenameDbfsResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.RenameDbfs(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func createFormatFS(fsPath string) error {\n\tfsFormatPath := pathJoin(fsPath, minioMetaBucket, formatConfigFile)\n\n\t// Attempt a write lock on formatConfigFile `format.json`\n\t// file stored in minioMetaBucket(.minio.sys) directory.\n\tlk, err := lock.TryLockedOpenFile((fsFormatPath), os.O_RDWR|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn traceError(err)\n\t}\n\t// Close the locked file upon return.\n\tdefer lk.Close()\n\n\t// Load format on disk, checks if we are unformatted\n\t// writes the new format.json\n\tvar format = &formatConfigV1{}\n\terr = format.LoadFormat(lk)\n\tif errorCause(err) == errUnformattedDisk {\n\t\t_, err = newFSFormat().WriteTo(lk)\n\t\treturn err\n\t}\n\treturn err\n}", "func (lm LinksManager) CreateFile(url *url.URL, t resource.Type) (*os.File, resource.Issue) {\n\treturn nil, resource.NewIssue(url.String(), \"NOT_IMPLEMENTED_YET\", \"CreateFile not implemented in graph.LinkLifecyleSettings\", true)\n}", "func NewFS(dataDir string) Interface {\n\treturn &fsLoader{dataDir: dataDir}\n}", "func NewFilesystem(_ context.Context, cfgMap map[string]interface{}) (qfs.Filesystem, error) {\n\treturn NewFS(cfgMap)\n}", "func createTmpConfigInFileSystem(rawJSON string) (func(), error) {\n\tconfigJSONFile, err := os.CreateTemp(os.TempDir(), \"configJSON-\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot create file %v: %v\", configJSONFile.Name(), err)\n\t}\n\t_, err = configJSONFile.Write(json.RawMessage(rawJSON))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot write marshalled JSON: %v\", err)\n\t}\n\toldObservabilityConfigFile := envconfig.ObservabilityConfigFile\n\tenvconfig.ObservabilityConfigFile = configJSONFile.Name()\n\treturn func() {\n\t\tconfigJSONFile.Close()\n\t\tenvconfig.ObservabilityConfigFile = oldObservabilityConfigFile\n\t}, nil\n}", "func CreateFiles(fS *FileCollection, ts int64, filelock chan int64) {\n\tvar lt time.Time\n\tvar err error\n\n\tselect {\n\tcase <- time.After(5 * time.Second):\n\t\t//If 5 seconds pass without getting the proper lock, abort\n\t\tlog.Printf(\"partdisk.CreateFiles(): timeout waiting for lock\\n\")\n\t\treturn\n\tcase chts := <- filelock:\n\t\tif chts == ts { //Got the lock and it matches the timestamp received\n\t\t\t//Proceed\n\t\t\tfS.flid = ts\n\t\t\tdefer func(){\n\t\t\t\tfilelock <- 0 //Release lock\n\t\t\t}()\n\t\t\tlt = time.Now() //Start counting how long does the parts creation take\n\t\t\tlog.Printf(\"CreateFiles(): lock obtained, timestamps match: %d\\n\",ts)\n\t\t} else {\n\t\t\tlog.Printf(\"CreateFiles(): lock obtained, but timestamps missmatch: %d - %d\\n\", ts,chts)\n\t\t\tfilelock <- chts\n\t\t\treturn\n\t\t}\n\t}\n\t//Lock obtained proper, create/delete the files\n\terr = adrefiles(fS)\n\tif err != nil {\n\t\tlog.Printf(\"CreateFiles(): Error creating file: %s\\n\",err.Error())\n\t\treturn\n\t}\n\tlog.Printf(\"CreateFiles(): Request %d completed in %d seconds\\n\",ts,int64(time.Since(lt).Seconds()))\n}", "func (z *ZkPlus) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {\n\tz.forPath(path).Log(logkey.ZkMethod, \"Create\")\n\tp, err := z.blockOnConn().Create(z.realPath(path), data, flags, acl)\n\tif strings.HasPrefix(p, z.pathPrefix) && z.pathPrefix != \"\" {\n\t\tp = p[len(z.pathPrefix)+1:]\n\t}\n\treturn p, errors.Annotatef(err, \"cannot create zk path %s\", path)\n}", "func NewStatsFileSystem(sc *statsclient.StatsClient) (root fs.InodeEmbedder, err error) {\n\treturn &dirNode{client: sc}, nil\n}", "func (s *mockFSServer) Create(ctx context.Context, r *proto.CreateRequest) (*proto.CreateResponse, error) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.filesCreated[r.Path] = false\n\n\treturn new(proto.CreateResponse), nil\n}", "func (dw *DirWatcher) onRootCreated() {\n\tvar (\n\t\tlogp = \"DirWatcher.onRootCreated\"\n\t\terr error\n\t)\n\n\tdw.fs, err = New(&dw.Options)\n\tif err != nil {\n\t\tlog.Printf(\"%s: %s\", logp, err)\n\t\treturn\n\t}\n\n\tdw.root, err = dw.fs.Get(\"/\")\n\tif err != nil {\n\t\tlog.Printf(\"%s: %s\", logp, err)\n\t\treturn\n\t}\n\n\tdw.dirsLocker.Lock()\n\tdw.dirs = make(map[string]*Node)\n\tdw.dirsLocker.Unlock()\n\tdw.mapSubdirs(dw.root)\n\n\tns := NodeState{\n\t\tNode: *dw.root,\n\t\tState: FileStateCreated,\n\t}\n\n\tselect {\n\tcase dw.qchanges <- ns:\n\tdefault:\n\t}\n}", "func NewFileSystemWatch(files []string, ev func(fsnotify.Event), errs func(error)) *FileSystemWatch {\n\treturn &FileSystemWatch{\n\t\tfiles: files,\n\t\tevents: ev,\n\t\terrors: errs,\n\t}\n}", "func (fs *Fs) Create(name string) (*os.File, error) {\n\treturn os.Create(name) // #nosec G304\n}", "func createDirectories() error {\n\n\tvar brickPath = glusterBrickPath + \"/\" + glusterVolumeName\n\tvar mountPath = glusterMountPath + \"/\" + glusterVolumeName\n\tvar volumePath = glusterDockerVolumePath\n\n\tdirPath := []string{brickPath, mountPath, volumePath}\n\n\tfor i := 0; i < len(dirPath); i++ {\n\t\tif helpers.Exists(dirPath[i]) == false {\n\t\t\terr := helpers.CreateDir(dirPath[i])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (d *DriveDB) createRoot() error {\n\tlaunch, _ := time.Unix(1335225600, 0).MarshalText()\n\tfile := &gdrive.File{\n\t\tId: d.rootId,\n\t\tTitle: \"/\",\n\t\tMimeType: driveFolderMimeType,\n\t\tLastViewedByMeDate: string(launch),\n\t\tModifiedDate: string(launch),\n\t\tCreatedDate: string(launch),\n\t}\n\t// Inode allocation special-cases the rootId, so we can let the usual\n\t// code paths do all the work\n\t_, err := d.UpdateFile(nil, file)\n\treturn err\n}", "func (cs *ControllerServer) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) {\n\tname := req.GetName()\n\tif len(name) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"CreateVolume name must be provided\")\n\t}\n\tif err := cs.validateVolumeCapabilities(req.GetVolumeCapabilities()); err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\treqCapacity := req.GetCapacityRange().GetRequiredBytes()\n\tnfsVol, err := cs.newNFSVolume(name, reqCapacity, req.GetParameters())\n\tif err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\tvar volCap *csi.VolumeCapability\n\tif len(req.GetVolumeCapabilities()) > 0 {\n\t\tvolCap = req.GetVolumeCapabilities()[0]\n\t} // 执行挂载 命令\n\t// Mount nfs base share so we can create a subdirectory\n\tif err = cs.internalMount(ctx, nfsVol, volCap); err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to mount nfs server: %v\", err.Error())\n\t}\n\tdefer func() {\n\t\tif err = cs.internalUnmount(ctx, nfsVol); err != nil {\n\t\t\tklog.Warningf(\"failed to unmount nfs server: %v\", err.Error())\n\t\t}\n\t}()\n\n\t// Create subdirectory under base-dir\n\t// TODO: revisit permissions\n\tinternalVolumePath := cs.getInternalVolumePath(nfsVol)\n\tif err = os.Mkdir(internalVolumePath, 0777); err != nil && !os.IsExist(err) {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to make subdirectory: %v\", err.Error())\n\t}\n\t// Remove capacity setting when provisioner 1.4.0 is available with fix for\n\t// https://github.com/kubernetes-csi/external-provisioner/pull/271\n\treturn &csi.CreateVolumeResponse{Volume: cs.nfsVolToCSI(nfsVol, reqCapacity)}, nil\n}", "func create(rawZipString string) (http.FileSystem, error) {\n\tif zipData == \"\" {\n\t\treturn nil, errors.New(\"statik/fs: no zip data registered\")\n\t}\n\tzipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make(map[string]file, len(zipReader.File))\n\tdirs := make(map[string][]string)\n\tfs := &ginBinFs{files: files, dirs: dirs}\n\tfor _, zipFile := range zipReader.File {\n\t\tfi := zipFile.FileInfo()\n\t\tf := file{FileInfo: fi, fs: fs}\n\t\tf.data, err = unzip(zipFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"statik/fs: error unzipping file %q: %s\", zipFile.Name, err)\n\t\t}\n\t\tfiles[\"/\"+zipFile.Name] = f\n\t}\n\tfor fn := range files {\n\t\t// go up directories recursively in order to care deep directory\n\t\tfor dn := path.Dir(fn); dn != fn; {\n\t\t\tif _, ok := files[dn]; !ok {\n\t\t\t\tfiles[dn] = file{FileInfo: dirInfo{dn}, fs: fs}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfn, dn = dn, path.Dir(dn)\n\t\t}\n\t}\n\tfor fn := range files {\n\t\tdn := path.Dir(fn)\n\t\tif fn != dn {\n\t\t\tfs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))\n\t\t}\n\t}\n\tfor _, s := range fs.dirs {\n\t\tsort.Strings(s)\n\t}\n\treturn fs, nil\n}", "func create(rawZipString string) (http.FileSystem, error) {\n\tif zipData == \"\" {\n\t\treturn nil, errors.New(\"statik/fs: no zip data registered\")\n\t}\n\tzipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make(map[string]file, len(zipReader.File))\n\tdirs := make(map[string][]string)\n\tfs := &ginBinFs{files: files, dirs: dirs}\n\tfor _, zipFile := range zipReader.File {\n\t\tfi := zipFile.FileInfo()\n\t\tf := file{FileInfo: fi, fs: fs}\n\t\tf.data, err = unzip(zipFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"statik/fs: error unzipping file %q: %s\", zipFile.Name, err)\n\t\t}\n\t\tfiles[\"/\"+zipFile.Name] = f\n\t}\n\tfor fn := range files {\n\t\t// go up directories recursively in order to care deep directory\n\t\tfor dn := path.Dir(fn); dn != fn; {\n\t\t\tif _, ok := files[dn]; !ok {\n\t\t\t\tfiles[dn] = file{FileInfo: dirInfo{dn}, fs: fs}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfn, dn = dn, path.Dir(dn)\n\t\t}\n\t}\n\tfor fn := range files {\n\t\tdn := path.Dir(fn)\n\t\tif fn != dn {\n\t\t\tfs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))\n\t\t}\n\t}\n\tfor _, s := range fs.dirs {\n\t\tsort.Strings(s)\n\t}\n\treturn fs, nil\n}", "func create(rawZipString string) (http.FileSystem, error) {\n\tif zipData == \"\" {\n\t\treturn nil, errors.New(\"statik/fs: no zip data registered\")\n\t}\n\tzipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make(map[string]file, len(zipReader.File))\n\tdirs := make(map[string][]string)\n\tfs := &ginBinFs{files: files, dirs: dirs}\n\tfor _, zipFile := range zipReader.File {\n\t\tfi := zipFile.FileInfo()\n\t\tf := file{FileInfo: fi, fs: fs}\n\t\tf.data, err = unzip(zipFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"statik/fs: error unzipping file %q: %s\", zipFile.Name, err)\n\t\t}\n\t\tfiles[\"/\"+zipFile.Name] = f\n\t}\n\tfor fn := range files {\n\t\t// go up directories recursively in order to care deep directory\n\t\tfor dn := path.Dir(fn); dn != fn; {\n\t\t\tif _, ok := files[dn]; !ok {\n\t\t\t\tfiles[dn] = file{FileInfo: dirInfo{dn}, fs: fs}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfn, dn = dn, path.Dir(dn)\n\t\t}\n\t}\n\tfor fn := range files {\n\t\tdn := path.Dir(fn)\n\t\tif fn != dn {\n\t\t\tfs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))\n\t\t}\n\t}\n\tfor _, s := range fs.dirs {\n\t\tsort.Strings(s)\n\t}\n\treturn fs, nil\n}" ]
[ "0.66443145", "0.6494744", "0.64063805", "0.6279257", "0.6207732", "0.6184654", "0.61342597", "0.60683924", "0.6045436", "0.56931496", "0.5614541", "0.55832964", "0.5576147", "0.54953367", "0.5450374", "0.5437641", "0.53679824", "0.536721", "0.536561", "0.53433496", "0.5338602", "0.5312654", "0.53121203", "0.52847797", "0.5273296", "0.52483857", "0.5241643", "0.5208248", "0.52045506", "0.51309025", "0.5125862", "0.5084794", "0.50722307", "0.5061616", "0.5048797", "0.5023597", "0.49996778", "0.49942267", "0.49849206", "0.4979911", "0.49797067", "0.49671754", "0.49670565", "0.49569687", "0.4930457", "0.492508", "0.4915943", "0.49115378", "0.49071872", "0.4906612", "0.48995763", "0.48977298", "0.4892283", "0.48877427", "0.48847038", "0.48770732", "0.48481736", "0.48409742", "0.48370454", "0.4830748", "0.48241818", "0.48014215", "0.4798321", "0.47835004", "0.4754567", "0.47537243", "0.4735462", "0.473011", "0.47294652", "0.47267115", "0.47211236", "0.47104704", "0.47069806", "0.4700375", "0.4694624", "0.46938145", "0.4687137", "0.46792284", "0.4675613", "0.46699896", "0.46686015", "0.4668587", "0.46647882", "0.46610698", "0.4659716", "0.46509025", "0.46493894", "0.46449304", "0.4642953", "0.4631977", "0.463056", "0.46190038", "0.46152478", "0.46079794", "0.46075723", "0.46060452", "0.46001044", "0.4598306", "0.4598306", "0.4598306" ]
0.8151044
0
CreateCreateFileSystemRequest creates a request to invoke CreateFileSystem API
func CreateCreateFileSystemRequest() (request *CreateFileSystemRequest) { request = &CreateFileSystemRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("DFS", "2018-06-20", "CreateFileSystem", "alidfs", "openAPI") request.Method = requests.POST return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client *Client) CreateFileSystem(request *CreateFileSystemRequest) (response *CreateFileSystemResponse, err error) {\n\tresponse = CreateCreateFileSystemResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func CreateListFileSystemsRequest() (request *ListFileSystemsRequest) {\n\trequest = &ListFileSystemsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"ListFileSystems\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (z *zfsctl) CreateFileSystem(ctx context.Context, name string, properties map[string]string) *execute {\n\targs := []string{\"create\", \"-p\"}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (manager *mockFileSystemManager) CreateFileSystem(ctx context.Context, groupName string, filesystemName string, timeout *int32, xMsDate string, datalakeName string) (*autorest.Response, error) {\n\tfs := fileSystemResource{\n\t\tresourceGroupName: groupName,\n\t\tstorageAccountName: datalakeName,\n\t\tfilesystemName: filesystemName,\n\t}\n\n\tmanager.fileSystemResource = append(manager.fileSystemResource, fs)\n\tmockresponse := helpers.GetRestResponse(http.StatusOK)\n\n\treturn &mockresponse, nil\n}", "func (client StorageGatewayClient) createFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateFileSystemInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateFileSystem\", params, optFns, c.addOperationCreateFileSystemMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateFileSystemOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (client StorageGatewayClient) CreateFileSystem(ctx context.Context, request CreateFileSystemRequest) (response CreateFileSystemResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\n\tif !(request.OpcRetryToken != nil && *request.OpcRetryToken != \"\") {\n\t\trequest.OpcRetryToken = common.String(common.RetryToken())\n\t}\n\n\tociResponse, err = common.Retry(ctx, request, client.createFileSystem, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = CreateFileSystemResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = CreateFileSystemResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(CreateFileSystemResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into CreateFileSystemResponse\")\n\t}\n\treturn\n}", "func (c *MockFileStorageClient) CreateFileSystem(ctx context.Context, details filestorage.CreateFileSystemDetails) (*filestorage.FileSystem, error) {\n\treturn &filestorage.FileSystem{Id: &fileSystemID}, nil\n}", "func CreateCreateFileDetectRequest() (request *CreateFileDetectRequest) {\n\trequest = &CreateFileDetectRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Sas\", \"2018-12-03\", \"CreateFileDetect\", \"sas\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateListAvailableFileSystemTypesRequest() (request *ListAvailableFileSystemTypesRequest) {\n\trequest = &ListAvailableFileSystemTypesRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"EHPC\", \"2018-04-12\", \"ListAvailableFileSystemTypes\", \"ehs\", \"openAPI\")\n\treturn\n}", "func CreateFile(w http.ResponseWriter, r *http.Request) {\n\tvar body datastructures.CreateBody\n\n\tif reqBody, err := ioutil.ReadAll(r.Body); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"Could not read request body\"))\n\t\treturn\n\t} else if err = json.Unmarshal(reqBody, &body); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"Bad request\"))\n\t\treturn\n\t}\n\n\tlog.Println(\n\t\t\"Create file request for\",\n\t\t\"workspace\", body.Workspace.ToString(),\n\t\t\"path\", filepath.Join(body.File.Path...),\n\t)\n\n\tif err := utils.CreateFile(body.Workspace, body.File); err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func FileSystemCreate(f types.Filesystem) error {\n\tvar cmd *exec.Cmd\n\tvar debugCMD string\n\n\tswitch f.Mount.Format {\n\tcase \"swap\":\n\t\tcmd = exec.Command(\"/sbin/mkswap\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkswap\", f.Mount.Device)\n\tcase \"ext4\", \"ext3\", \"ext2\":\n\t\t// Add filesystem flags\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-t\")\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Format)\n\n\t\t// Add force\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-F\")\n\n\t\t// Add Device to formate\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Device)\n\n\t\t// Format disk\n\t\tcmd = exec.Command(\"/sbin/mke2fs\", f.Mount.Create.Options...)\n\t\tfor i := range f.Mount.Create.Options {\n\t\t\tdebugCMD = fmt.Sprintf(\"%s %s\", debugCMD, f.Mount.Create.Options[i])\n\t\t}\n\tcase \"vfat\":\n\t\tcmd = exec.Command(\"/sbin/mkfs.fat\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkfs.fat\", f.Mount.Device)\n\tdefault:\n\t\tlog.Warnf(\"Unknown filesystem type [%s]\", f.Mount.Format)\n\t}\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\n\treturn nil\n}", "func CreateCreateFileSystemResponse() (response *CreateFileSystemResponse) {\n\tresponse = &CreateFileSystemResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateFaceConfigRequest() (request *CreateFaceConfigRequest) {\n\trequest = &CreateFaceConfigRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Cloudauth\", \"2019-03-07\", \"CreateFaceConfig\", \"cloudauth\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateRenameDbfsRequest() (request *RenameDbfsRequest) {\n\trequest = &RenameDbfsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DBFS\", \"2020-04-18\", \"RenameDbfs\", \"dbfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateClusterRequest() (request *CreateClusterRequest) {\n\trequest = &CreateClusterRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"CS\", \"2015-12-15\", \"CreateCluster\", \"/clusters\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateVSwitchRequest() (request *CreateVSwitchRequest) {\n\trequest = &CreateVSwitchRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Ecs\", \"2014-05-26\", \"CreateVSwitch\", \"ecs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateGetDirectoryOrFilePropertiesRequest() (request *GetDirectoryOrFilePropertiesRequest) {\n\trequest = &GetDirectoryOrFilePropertiesRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"NAS\", \"2017-06-26\", \"GetDirectoryOrFileProperties\", \"nas\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *Client) CreateFileSystemWithCallback(request *CreateFileSystemRequest, callback func(response *CreateFileSystemResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFileSystemResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFileSystem(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func CreateCreateGatewayFileShareRequest() (request *CreateGatewayFileShareRequest) {\n\trequest = &CreateGatewayFileShareRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"sgw\", \"2018-05-11\", \"CreateGatewayFileShare\", \"hcs_sgw\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateRequest(c context.Context, record *models.FileRequest) error {\n\treturn FromContext(c).CreateRequest(record)\n}", "func (client *KeyVaultClient) createKeyCreateRequest(ctx context.Context, vaultBaseURL string, keyName string, parameters KeyCreateParameters, options *KeyVaultClientCreateKeyOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/keys/{key-name}/create\"\n\tif keyName == \"\" {\n\t\treturn nil, errors.New(\"parameter keyName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{key-name}\", url.PathEscape(keyName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, parameters)\n}", "func (client *KeyVaultClient) createKeyCreateRequest(ctx context.Context, vaultBaseURL string, keyName string, parameters KeyCreateParameters, options *KeyVaultClientCreateKeyOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/keys/{key-name}/create\"\n\tif keyName == \"\" {\n\t\treturn nil, errors.New(\"parameter keyName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{key-name}\", url.PathEscape(keyName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.3\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, parameters)\n}", "func CreateCreateScheduleRequest() (request *CreateScheduleRequest) {\n\trequest = &CreateScheduleRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"fnf\", \"2019-03-15\", \"CreateSchedule\", \"fnf\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *Client) CreateFileSystemWithChan(request *CreateFileSystemRequest) (<-chan *CreateFileSystemResponse, <-chan error) {\n\tresponseChan := make(chan *CreateFileSystemResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateFileSystem(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func newCreateRequest(path, name string) (*Request, error) {\n\t// XXX Better to delay reading the file content until it is needed\n\t// inside sendRequests() loop, and skip the overhead from copying data.\n\t// ==> Replace Request.Data by the file descriptor, then use\n\t// splice(2) (or other) for zero-copying (use\n\t// rpc.NewClientWithCodec() instead of rpc.NewClient())\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Request{Type: requestCreate, Path: name, Data: content}, nil\n}", "func CreateFilesystem(e *efs.EFS, n string) (*efs.FileSystemDescription, error) {\n\tcreateParams := &efs.CreateFileSystemInput{\n\t\tCreationToken: aws.String(n),\n\t}\n\tcreateResp, err := e.CreateFileSystem(createParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for the filesystem to become available.\n\tfor {\n\t\tfs, err := DescribeFilesystem(e, n)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(fs.FileSystems) > 0 {\n\t\t\tif *fs.FileSystems[0].LifeCycleState == efsAvail {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n\treturn createResp, nil\n}", "func (z *ZFS) Create(req *acomm.Request) (interface{}, *url.URL, error) {\n\tvar args CreateArgs\n\tif err := req.UnmarshalArgs(&args); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif args.Name == \"\" {\n\t\treturn nil, nil, errors.New(\"missing arg: name\")\n\t}\n\n\tif err := fixPropertyTypesFromJSON(args.Properties); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar ds *gozfs.Dataset\n\tvar err error\n\tswitch args.Type {\n\tcase gozfs.DatasetFilesystem:\n\t\tds, err = gozfs.CreateFilesystem(args.Name, args.Properties)\n\tcase gozfs.DatasetVolume:\n\t\tif args.Volsize <= 0 {\n\t\t\terr = errors.New(\"missing or invalid arg: volsize\")\n\t\t\tbreak\n\t\t}\n\t\tds, err = gozfs.CreateVolume(args.Name, args.Volsize, args.Properties)\n\tdefault:\n\t\terr = errors.New(\"missing or invalid arg: type\")\n\t}\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn &DatasetResult{newDataset(ds)}, nil, nil\n}", "func CreateCreateTopicRequest() (request *CreateTopicRequest) {\n\trequest = &CreateTopicRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"alikafka\", \"2019-09-16\", \"CreateTopic\", \"alikafka\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateFabricChannelRequest() (request *CreateFabricChannelRequest) {\n\trequest = &CreateFabricChannelRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Baas\", \"2018-12-21\", \"CreateFabricChannel\", \"baas\", \"openAPI\")\n\treturn\n}", "func CreateDescribeLogstoreStorageRequest() (request *DescribeLogstoreStorageRequest) {\n\trequest = &DescribeLogstoreStorageRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Sas\", \"2018-12-03\", \"DescribeLogstoreStorage\", \"sas\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (*FileSystemBase) Create(path string, flags int, mode uint32) (int, uint64) {\n\treturn -ENOSYS, ^uint64(0)\n}", "func CreateCreateAgentRequest() (request *CreateAgentRequest) {\n\trequest = &CreateAgentRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"scsp\", \"2020-07-02\", \"CreateAgent\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *FileServicesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *FileServicesListOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices\"\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := azcore.NewRequest(ctx, http.MethodGet, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2019-06-01\")\n\treq.URL.RawQuery = query.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (z *ZfsH) CreateFilesystem(name string, properties map[string]string) (*Dataset, error) {\n\targs := make([]string, 1, 4)\n\targs[0] = \"create\"\n\n\tif properties != nil {\n\t\targs = append(args, propsSlice(properties)...)\n\t}\n\n\targs = append(args, name)\n\t_, err := z.zfs(args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn z.GetDataset(name)\n}", "func (client *ContainerClient) createCreateRequest(ctx context.Context, options *ContainerClientCreateOptions, containerCPKScopeInfo *ContainerCPKScopeInfo) (*policy.Request, error) {\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, client.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"restype\", \"container\")\n\tif options != nil && options.Timeout != nil {\n\t\treqQP.Set(\"timeout\", strconv.FormatInt(int64(*options.Timeout), 10))\n\t}\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\tif options != nil && options.Metadata != nil {\n\t\tfor k, v := range options.Metadata {\n\t\t\tif v != nil {\n\t\t\t\treq.Raw().Header[\"x-ms-meta-\"+k] = []string{*v}\n\t\t\t}\n\t\t}\n\t}\n\tif options != nil && options.Access != nil {\n\t\treq.Raw().Header[\"x-ms-blob-public-access\"] = []string{string(*options.Access)}\n\t}\n\treq.Raw().Header[\"x-ms-version\"] = []string{\"2020-10-02\"}\n\tif options != nil && options.RequestID != nil {\n\t\treq.Raw().Header[\"x-ms-client-request-id\"] = []string{*options.RequestID}\n\t}\n\tif containerCPKScopeInfo != nil && containerCPKScopeInfo.DefaultEncryptionScope != nil {\n\t\treq.Raw().Header[\"x-ms-default-encryption-scope\"] = []string{*containerCPKScopeInfo.DefaultEncryptionScope}\n\t}\n\tif containerCPKScopeInfo != nil && containerCPKScopeInfo.PreventEncryptionScopeOverride != nil {\n\t\treq.Raw().Header[\"x-ms-deny-encryption-scope-override\"] = []string{strconv.FormatBool(*containerCPKScopeInfo.PreventEncryptionScopeOverride)}\n\t}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/xml\"}\n\treturn req, nil\n}", "func (client *FileServicesClient) setServicePropertiesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters FileServiceProperties, options *FileServicesSetServicePropertiesOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/{FileServicesName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\turlPath = strings.ReplaceAll(urlPath, \"{FileServicesName}\", url.PathEscape(\"default\"))\n\treq, err := azcore.NewRequest(ctx, http.MethodPut, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2019-06-01\")\n\treq.URL.RawQuery = query.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, req.MarshalAsJSON(parameters)\n}", "func CreateCreateTagTaskRequest() (request *CreateTagTaskRequest) {\n\trequest = &CreateTagTaskRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"viapi-regen\", \"2021-11-19\", \"CreateTagTask\", \"selflearning\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func Create(fsys fs.FS, name string) (WriterFile, error) {\n\tcfs, ok := fsys.(CreateFS)\n\tif !ok {\n\t\treturn nil, &fs.PathError{Op: \"create\", Path: name, Err: fmt.Errorf(\"not implemented on type %T\", fsys)}\n\t}\n\treturn cfs.Create(name)\n}", "func createFile(fs fileSystem, fileName string) (file, error) {\n\treturn fs.Create(fileName)\n}", "func CreateCreateMeetingRequest() (request *CreateMeetingRequest) {\n\trequest = &CreateMeetingRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"aliyuncvc\", \"2019-10-30\", \"CreateMeeting\", \"aliyuncvc\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateOrUpdateDataSourceRequest() (request *CreateOrUpdateDataSourceRequest) {\n\trequest = &CreateOrUpdateDataSourceRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"aegis\", \"2016-11-11\", \"CreateOrUpdateDataSource\", \"vipaegis\", \"openAPI\")\n\treturn\n}", "func CreateCreateExchangeRequest() (request *CreateExchangeRequest) {\n\trequest = &CreateExchangeRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"amqp-open\", \"2019-12-12\", \"CreateExchange\", \"onsproxy\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateExpressSyncRequest() (request *CreateExpressSyncRequest) {\n\trequest = &CreateExpressSyncRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"sgw\", \"2018-05-11\", \"CreateExpressSync\", \"hcs_sgw\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateStackRequest() (request *CreateStackRequest) {\n\trequest = &CreateStackRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"ROS\", \"2019-09-10\", \"CreateStack\", \"ros\", \"openAPI\")\n\treturn\n}", "func (fs ReverseHttpFs) Create(n string) (afero.File, error) {\n\treturn nil, syscall.EPERM\n}", "func NewTaskCreateRequest(flux string) *TaskCreateRequest {\n\tthis := TaskCreateRequest{}\n\tthis.Flux = flux\n\treturn &this\n}", "func NewQtreeCreateRequest() *QtreeCreateRequest {\n\treturn &QtreeCreateRequest{}\n}", "func (mzk *MockZK) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {\n\tmzk.Args = append(mzk.Args, []interface{}{\n\t\t\"create\",\n\t\tpath,\n\t\tdata,\n\t\tflags,\n\t\tacl,\n\t})\n\treturn mzk.CreateFn(path, data, flags, acl)\n}", "func (fsOnDisk) Create(name string) (File, error) { return os.Create(name) }", "func (client *Client) sapDiskConfigurationsCreateRequest(ctx context.Context, location string, options *ClientSAPDiskConfigurationsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/providers/Microsoft.Workloads/locations/{location}/sapVirtualInstanceMetadata/default/getDiskConfigurations\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif location == \"\" {\n\t\treturn nil, errors.New(\"parameter location cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{location}\", url.PathEscape(location))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-12-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\tif options != nil && options.SAPDiskConfigurations != nil {\n\t\treturn req, runtime.MarshalAsJSON(req, *options.SAPDiskConfigurations)\n\t}\n\treturn req, nil\n}", "func (connection *Connection) CreateStoreRequest(fnr Fnr) (*StoreRequest, error) {\n\treturn NewStoreRequestAdabas(connection.adabasToData, fnr), nil\n}", "func CreateCreateFaceGroupRequest() (request *CreateFaceGroupRequest) {\n\trequest = &CreateFaceGroupRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"multimediaai\", \"2019-08-10\", \"CreateFaceGroup\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func Create(name string) (*os.File, error)", "func CreateCreateApplicationGroupRequest() (request *CreateApplicationGroupRequest) {\n\trequest = &CreateApplicationGroupRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"oos\", \"2019-06-01\", \"CreateApplicationGroup\", \"oos\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateVmAndSaveStockRequest() (request *CreateVmAndSaveStockRequest) {\n\trequest = &CreateVmAndSaveStockRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Ens\", \"2017-11-10\", \"CreateVmAndSaveStock\", \"ens\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func NewCreateanewSystemContactRequest(server string, body CreateanewSystemContactJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewSystemContactRequestWithBody(server, \"application/json\", bodyReader)\n}", "func (client *VirtualMachinesClient) createCreateRequest(ctx context.Context, resourceGroupName string, virtualMachineName string, body VirtualMachine, options *VirtualMachinesClientBeginCreateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/virtualMachines/{virtualMachineName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif virtualMachineName == \"\" {\n\t\treturn nil, errors.New(\"parameter virtualMachineName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{virtualMachineName}\", url.PathEscape(virtualMachineName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-01-10-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, runtime.MarshalAsJSON(req, body)\n}", "func (c *UFSClient) NewCreateUFSVolumeRequest() *CreateUFSVolumeRequest {\n\treq := &CreateUFSVolumeRequest{}\n\n\t// setup request with client config\n\tc.Client.SetupRequest(req)\n\n\t// setup retryable with default retry policy (retry for non-create action and common error)\n\treq.SetRetryable(false)\n\treturn req\n}", "func CreateDescribeParentPlatformRequest() (request *DescribeParentPlatformRequest) {\n\trequest = &DescribeParentPlatformRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"vs\", \"2018-12-12\", \"DescribeParentPlatform\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateModifyDirectoryRequest() (request *ModifyDirectoryRequest) {\n\trequest = &ModifyDirectoryRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"vs\", \"2018-12-12\", \"ModifyDirectory\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateTrafficMirrorFilterRequest() (request *CreateTrafficMirrorFilterRequest) {\n\trequest = &CreateTrafficMirrorFilterRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Vpc\", \"2016-04-28\", \"CreateTrafficMirrorFilter\", \"vpc\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func NewCreateOrderRequest(server string, body CreateOrderJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateOrderRequestWithBody(server, \"application/json\", bodyReader)\n}", "func CreateSegmentSkyRequest() (request *SegmentSkyRequest) {\n\trequest = &SegmentSkyRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"imageseg\", \"2019-12-30\", \"SegmentSky\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateMetastoreCreateTableRequest() (request *MetastoreCreateTableRequest) {\n\trequest = &MetastoreCreateTableRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Emr\", \"2016-04-08\", \"MetastoreCreateTable\", \"emr\", \"openAPI\")\n\treturn\n}", "func createFileUploadRequest(url string, extraParameters map[string]string, parameterName, filePath string, fileContent []byte) *Request {\n\tfile := &RequestFile{\n\t\tParameterName: parameterName,\n\t\tFilePath: filePath,\n\t\tFileContent: fileContent,\n\t}\n\trequest := &Request{\n\t\tURL: url,\n\t\tMethod: \"PUT\",\n\t\tParameters: extraParameters,\n\t\tFiles: []*RequestFile{\n\t\t\tfile,\n\t\t},\n\t}\n\treturn request\n}", "func NewCreateUserRequest(userName string) *CreateUserRequest {\n\tthis := CreateUserRequest{}\n\tthis.UserName = userName\n\treturn &this\n}", "func NewFileSystem(token string, debug bool) *FileSystem {\n\toauthClient := oauth2.NewClient(\n\t\toauth2.NoContext,\n\t\toauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}),\n\t)\n\tclient := putio.NewClient(oauthClient)\n\tclient.UserAgent = defaultUserAgent\n\n\treturn &FileSystem{\n\t\tputio: client,\n\t\tlogger: NewLogger(\"putiofs: \", debug),\n\t}\n}", "func (client *Client) uploadCreateRequest(ctx context.Context, ruleID string, streamName string, logs []byte, options *UploadOptions) (*policy.Request, error) {\n\turlPath := \"/dataCollectionRules/{ruleId}/streams/{stream}\"\n\tif ruleID == \"\" {\n\t\treturn nil, errors.New(\"parameter ruleID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{ruleId}\", url.PathEscape(ruleID))\n\tif streamName == \"\" {\n\t\treturn nil, errors.New(\"parameter streamName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{stream}\", url.PathEscape(streamName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-01-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\tif options != nil && options.ContentEncoding != nil {\n\t\treq.Raw().Header[\"Content-Encoding\"] = []string{*options.ContentEncoding}\n\t}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, req.SetBody(streaming.NopCloser(bytes.NewReader(logs)), \"application/json\")\n}", "func (f *Fs) createFile(ctx context.Context, pathID, leaf, mimeType string) (newID string, err error) {\n\tvar resp *http.Response\n\topts := rest.Opts{\n\t\tMethod: \"POST\",\n\t\tRootURL: pathID,\n\t\tNoResponse: true,\n\t}\n\tmkdir := api.CreateFile{\n\t\tName: f.opt.Enc.FromStandardName(leaf),\n\t\tMediaType: mimeType,\n\t}\n\terr = f.pacer.Call(func() (bool, error) {\n\t\tresp, err = f.srv.CallXML(ctx, &opts, &mkdir, nil)\n\t\treturn shouldRetry(ctx, resp, err)\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp.Header.Get(\"Location\"), nil\n}", "func CreateTestFlowStrategy01Request() (request *TestFlowStrategy01Request) {\n\trequest = &TestFlowStrategy01Request{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Ft\", \"2018-07-13\", \"TestFlowStrategy01\", \"\", \"\")\n\trequest.Method = requests.PUT\n\treturn\n}", "func (service *Service) CreateRequest(parameters map[string]string) (*Request, error) {\n\tvar int1, int2, limit int64\n\tvar err error\n\n\t// Convert string parameters to int64\n\tif int1, err = strconv.ParseInt(parameters[\"int1\"], 10, 64); err != nil {\n\t\treturn nil, err\n\t}\n\tif int2, err = strconv.ParseInt(parameters[\"int2\"], 10, 64); err != nil {\n\t\treturn nil, err\n\t}\n\tif limit, err = strconv.ParseInt(parameters[\"limit\"], 10, 64); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Request{\n\t\tInt1: int1,\n\t\tInt2: int2,\n\t\tLimit: limit,\n\t\tStr1: parameters[\"str1\"],\n\t\tStr2: parameters[\"str2\"],\n\t}, nil\n}", "func CreateActionDiskRmaRequest() (request *ActionDiskRmaRequest) {\n\trequest = &ActionDiskRmaRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"TeslaDam\", \"2018-01-18\", \"ActionDiskRma\", \"tesladam\", \"openAPI\")\n\treturn\n}", "func (realFS) Create(name string) (File, error) { return os.Create(name) }", "func NewFileSystem(fs http.FileSystem, name string) FileSystem {\n\treturn Trace(&fileSystem{fs}, name)\n}", "func (c *Client) NewCreateLabelRequest(ctx context.Context, path string, payload *CreateLabelPayload) (*http.Request, error) {\n\tvar body bytes.Buffer\n\terr := c.Encoder.Encode(payload, &body, \"*/*\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode body: %s\", err)\n\t}\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"POST\", u.String(), &body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\theader.Set(\"Content-Type\", \"application/json\")\n\tif c.JWTSigner != nil {\n\t\tc.JWTSigner.Sign(req)\n\t}\n\treturn req, nil\n}", "func CreateNormalRpcHsfApiRequest() (request *NormalRpcHsfApiRequest) {\n\trequest = &NormalRpcHsfApiRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Ft\", \"2021-01-01\", \"NormalRpcHsfApi\", \"\", \"\")\n\trequest.Method = requests.GET\n\treturn\n}", "func newFileSystem(basedir string, mkdir osMkdirAll) (*FS, error) {\n\tif err := mkdir(basedir, 0700); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &FS{basedir: basedir}, nil\n}", "func (client *SparkJobDefinitionClient) executeSparkJobDefinitionCreateRequest(ctx context.Context, sparkJobDefinitionName string, options *SparkJobDefinitionBeginExecuteSparkJobDefinitionOptions) (*azcore.Request, error) {\n\turlPath := \"/sparkJobDefinitions/{sparkJobDefinitionName}/execute\"\n\tif sparkJobDefinitionName == \"\" {\n\t\treturn nil, errors.New(\"parameter sparkJobDefinitionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{sparkJobDefinitionName}\", url.PathEscape(sparkJobDefinitionName))\n\treq, err := azcore.NewRequest(ctx, http.MethodPost, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\treqQP := req.URL.Query()\n\treqQP.Set(\"api-version\", \"2019-06-01-preview\")\n\treq.URL.RawQuery = reqQP.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (g Graph) CreateDrive(w http.ResponseWriter, r *http.Request) {\n\tus, ok := ctxpkg.ContextGetUser(r.Context())\n\tif !ok {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusUnauthorized, \"invalid user\")\n\t\treturn\n\t}\n\n\t// TODO determine if the user tries to create his own personal space and pass that as a boolean\n\tif !canCreateSpace(r.Context(), false) {\n\t\t// if the permission is not existing for the user in context we can assume we don't have it. Return 401.\n\t\terrorcode.GeneralException.Render(w, r, http.StatusUnauthorized, \"insufficient permissions to create a space.\")\n\t\treturn\n\t}\n\n\tclient := g.GetGatewayClient()\n\tdrive := libregraph.Drive{}\n\tif err := json.NewDecoder(r.Body).Decode(&drive); err != nil {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusBadRequest, \"invalid schema definition\")\n\t\treturn\n\t}\n\tspaceName := *drive.Name\n\tif spaceName == \"\" {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, \"invalid name\")\n\t\treturn\n\t}\n\n\tvar driveType string\n\tif drive.DriveType != nil {\n\t\tdriveType = *drive.DriveType\n\t}\n\tswitch driveType {\n\tcase \"\", \"project\":\n\t\tdriveType = \"project\"\n\tdefault:\n\t\terrorcode.GeneralException.Render(w, r, http.StatusBadRequest, fmt.Sprintf(\"drives of type %s cannot be created via this api\", driveType))\n\t\treturn\n\t}\n\n\tcsr := storageprovider.CreateStorageSpaceRequest{\n\t\tOwner: us,\n\t\tType: driveType,\n\t\tName: spaceName,\n\t\tQuota: getQuota(drive.Quota, g.config.Spaces.DefaultQuota),\n\t}\n\n\tif drive.Description != nil {\n\t\tcsr.Opaque = utils.AppendPlainToOpaque(csr.Opaque, \"description\", *drive.Description)\n\t}\n\n\tif drive.DriveAlias != nil {\n\t\tcsr.Opaque = utils.AppendPlainToOpaque(csr.Opaque, \"spaceAlias\", *drive.DriveAlias)\n\t}\n\n\tresp, err := client.CreateStorageSpace(r.Context(), &csr)\n\tif err != nil {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tif resp.GetStatus().GetCode() != cs3rpc.Code_CODE_OK {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, \"\")\n\t\treturn\n\t}\n\n\twdu, err := url.Parse(g.config.Spaces.WebDavBase + g.config.Spaces.WebDavPath)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error parsing url\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tnewDrive, err := g.cs3StorageSpaceToDrive(r.Context(), wdu, resp.StorageSpace)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error parsing space\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\trender.Status(r, http.StatusCreated)\n\trender.JSON(w, r, newDrive)\n}", "func (c *Client) BuildStorageVolumesCreateRequest(ctx context.Context, v interface{}) (*http.Request, error) {\n\tu := &url.URL{Scheme: c.scheme, Host: c.host, Path: StorageVolumesCreateSpinRegistryPath()}\n\treq, err := http.NewRequest(\"POST\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, goahttp.ErrInvalidURL(\"spin-registry\", \"storage_volumes_create\", u.String(), err)\n\t}\n\tif ctx != nil {\n\t\treq = req.WithContext(ctx)\n\t}\n\n\treturn req, nil\n}", "func (c *Client) NewCreateScansRequest(ctx context.Context, path string, payload *ScanPayload) (*http.Request, error) {\n\tvar body bytes.Buffer\n\terr := c.Encoder.Encode(payload, &body, \"*/*\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode body: %s\", err)\n\t}\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"POST\", u.String(), &body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\theader.Set(\"Content-Type\", \"application/json\")\n\treturn req, nil\n}", "func (client *ContainerClient) ListBlobHierarchySegmentCreateRequest(ctx context.Context, delimiter string, options *ContainerClientListBlobHierarchySegmentOptions) (*policy.Request, error) {\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, client.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"restype\", \"container\")\n\treqQP.Set(\"comp\", \"list\")\n\tif options != nil && options.Prefix != nil {\n\t\treqQP.Set(\"prefix\", *options.Prefix)\n\t}\n\treqQP.Set(\"delimiter\", delimiter)\n\tif options != nil && options.Marker != nil {\n\t\treqQP.Set(\"marker\", *options.Marker)\n\t}\n\tif options != nil && options.Maxresults != nil {\n\t\treqQP.Set(\"maxresults\", strconv.FormatInt(int64(*options.Maxresults), 10))\n\t}\n\tif options != nil && options.Include != nil {\n\t\treqQP.Set(\"include\", strings.Join(strings.Fields(strings.Trim(fmt.Sprint(options.Include), \"[]\")), \",\"))\n\t}\n\tif options != nil && options.Timeout != nil {\n\t\treqQP.Set(\"timeout\", strconv.FormatInt(int64(*options.Timeout), 10))\n\t}\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"x-ms-version\"] = []string{\"2020-10-02\"}\n\tif options != nil && options.RequestID != nil {\n\t\treq.Raw().Header[\"x-ms-client-request-id\"] = []string{*options.RequestID}\n\t}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/xml\"}\n\treturn req, nil\n}", "func NewCreateDNSZoneRequest(server string, body CreateDNSZoneJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateDNSZoneRequestWithBody(server, \"application/json\", bodyReader)\n}", "func CreateUploadIoTDataToBlockchainRequest() (request *UploadIoTDataToBlockchainRequest) {\n\trequest = &UploadIoTDataToBlockchainRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"lto\", \"2021-07-07\", \"UploadIoTDataToBlockchain\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateEvaluateTaskRequest() (request *CreateEvaluateTaskRequest) {\n\trequest = &CreateEvaluateTaskRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Drds\", \"2019-01-23\", \"CreateEvaluateTask\", \"Drds\", \"openAPI\")\n\treturn\n}", "func (c *Client) NewCreateLambdaRequest(ctx context.Context, path string, payload *LambdaPayload, contentType string) (*http.Request, error) {\n\tvar body bytes.Buffer\n\tif contentType == \"\" {\n\t\tcontentType = \"*/*\" // Use default encoder\n\t}\n\terr := c.Encoder.Encode(payload, &body, contentType)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode body: %s\", err)\n\t}\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"POST\", u.String(), &body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\tif contentType == \"*/*\" {\n\t\theader.Set(\"Content-Type\", \"application/json\")\n\t} else {\n\t\theader.Set(\"Content-Type\", contentType)\n\t}\n\treturn req, nil\n}", "func CreateDescribeExplorerRequest() (request *DescribeExplorerRequest) {\n\trequest = &DescribeExplorerRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Baas\", \"2018-07-31\", \"DescribeExplorer\", \"\", \"\")\n\treturn\n}", "func NewFileSystem(ctrl *gomock.Controller) *FileSystem {\n\tmock := &FileSystem{ctrl: ctrl}\n\tmock.recorder = &FileSystemMockRecorder{mock}\n\treturn mock\n}", "func CreateCreateDataAPIServiceRequest() (request *CreateDataAPIServiceRequest) {\n\trequest = &CreateDataAPIServiceRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Iot\", \"2018-01-20\", \"CreateDataAPIService\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (fs *FileSystem) Create(name string) (afero.File, error) {\n\tlogger.Println(\"Create\", name)\n\tname = normalizePath(name)\n\tpath := filepath.Dir(name)\n\n\tif err := fs.MkdirAll(path, os.ModeDir); err != nil {\n\t\treturn nil, &os.PathError{Op: \"create\", Path: name, Err: err}\n\t}\n\n\tfs.Lock()\n\tfileData := CreateFile(name)\n\tfs.data[name] = fileData\n\tfs.Unlock()\n\n\treturn NewFileHandle(fs, fileData), nil\n}", "func NewCreateSksClusterRequest(server string, body CreateSksClusterJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateSksClusterRequestWithBody(server, \"application/json\", bodyReader)\n}", "func (fs *FileSystem) CreateFile(fileName string, data string, parentInodeNum int, fileType int) error {\n\n\t// Validation of the arguments\n\t// TODO same name file in the directory.\n\tif err := fs.validateCreationRequest(fileName); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while validating : \", err)\n\t\treturn err\n\t}\n\tdataBlockRequired := int(math.Ceil(float64(len(data) / DataBlockSize)))\n\t// Check resources available or not\n\tif err := resourceAvailable(fs, dataBlockRequired); err != nil {\n\t\tfmt.Println(\"Error: Creation request fails while check availabilty of resource : \", err)\n\t\treturn err\n\t}\n\n\tfmt.Println(\"filename\", fileName, \"datablockrequired\", dataBlockRequired)\n\t// Get Parent Inode\n\tparInode, err := getInodeInfo(parentInodeNum)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to get parent inode \", err)\n\t\treturn err\n\t}\n\n\t// check parent inode has space to accomodate new file/ directory inside it.\n\t// here 4 is used because 1 for comma and 3 bytes representing inode number.\n\tif len(parInode) < (InodeBlockSize - 4) {\n\t\treturn fmt.Errorf(\"Parent inode doesn't have space left to accomodate new file in it\")\n\t}\n\n\t// Allocate an inode and intialise\n\tif dataBlockRequired != 0 {\n\t\tdataBlockRequired++\n\t}\n\tinode := inode{fs.nextFreeInode[0], fileType, parentInodeNum, fs.nextFreeDataBlock[:dataBlockRequired]}\n\n\tfmt.Println(\"inode\", inode)\n\t// Update fst with new inode entries.\n\tfs.UpdateFst(inode)\n\n\t// Add entry in FST in memory\n\tfs.fileSystemTable[fileName] = inode.inodeNum\n\n\tparentInode := parseInode(parInode)\n\tparentInode.dataList = append(parentInode.dataList, inode.inodeNum)\n\n\t// Update the dumpFile with the file content.\n\tif err := UpdateDumpFile(inode, data, fileName, parentInode, parentInodeNum); err != nil {\n\t\tfmt.Println(\"unable to update the disk : \", err)\n\t\treturn err\n\t}\n\n\t// TODO : After successfull creation of file, update the directory data block accordingly..\n\n\tfmt.Println(\"successful updation in disk\", inode)\n\n\treturn nil\n}", "func newMkdirRequest(name string) *Request {\n\treturn &Request{Type: requestMkdir, Path: name}\n}", "func CreateCreateContainerInstancesRequest() (request *CreateContainerInstancesRequest) {\n\trequest = &CreateContainerInstancesRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Ecs\", \"2014-05-26\", \"CreateContainerInstances\", \"ecs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (c *Client) NewCreateUserRequest(ctx context.Context, path string, payload *CreateUserPayload, contentType string) (*http.Request, error) {\n\tvar body bytes.Buffer\n\tif contentType == \"\" {\n\t\tcontentType = \"*/*\" // Use default encoder\n\t}\n\terr := c.Encoder.Encode(payload, &body, contentType)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode body: %s\", err)\n\t}\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"POST\", u.String(), &body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\tif contentType == \"*/*\" {\n\t\theader.Set(\"Content-Type\", \"application/json\")\n\t} else {\n\t\theader.Set(\"Content-Type\", contentType)\n\t}\n\treturn req, nil\n}", "func CreateDescribeFpgaImagesRequest() (request *DescribeFpgaImagesRequest) {\n\trequest = &DescribeFpgaImagesRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"faas\", \"2020-02-17\", \"DescribeFpgaImages\", \"faas\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *CloudServicesClient) startCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginStartOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/start\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif cloudServiceName == \"\" {\n\t\treturn nil, errors.New(\"parameter cloudServiceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{cloudServiceName}\", url.PathEscape(cloudServiceName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-09-04\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (store *Engine) CreateRequest(request *Request) (string, error) {\n\tvar id struct {\n\t\tID string `json:\"id\"`\n\t}\n\n\t_, err := store.api.\n\t\tURL(\"/workflow-engine/api/v1/requests\").\n\t\tPost(&request, &id)\n\n\treturn id.ID, err\n}", "func NewCreateanewSoundFileRequest(server string, body CreateanewSoundFileJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewSoundFileRequestWithBody(server, \"application/json\", bodyReader)\n}" ]
[ "0.74044955", "0.7277164", "0.7208954", "0.7005334", "0.6775199", "0.67420554", "0.66735137", "0.662397", "0.6544891", "0.63551843", "0.6137757", "0.605717", "0.59149057", "0.5900351", "0.58727604", "0.57616615", "0.57495767", "0.5742306", "0.573904", "0.57332695", "0.5698775", "0.56630176", "0.56537527", "0.5620307", "0.55950856", "0.55882853", "0.55834025", "0.55513746", "0.5546973", "0.55397207", "0.55282634", "0.5514236", "0.5502149", "0.5499126", "0.5494996", "0.5479951", "0.5461243", "0.54531705", "0.5445831", "0.5442856", "0.54374444", "0.5433586", "0.54317313", "0.5426106", "0.54243225", "0.5420428", "0.5418315", "0.5406106", "0.53952247", "0.53826046", "0.5382112", "0.53784746", "0.5375143", "0.53695434", "0.53506595", "0.53495955", "0.5342001", "0.53415763", "0.5341148", "0.5339594", "0.5338037", "0.5320624", "0.5303603", "0.52918744", "0.528945", "0.5286966", "0.52761173", "0.52728903", "0.527197", "0.52678263", "0.5255856", "0.5225574", "0.5224698", "0.52106935", "0.5206156", "0.52008516", "0.51979434", "0.51975197", "0.51938534", "0.518828", "0.5182749", "0.5172974", "0.5171404", "0.5156043", "0.5154647", "0.5154103", "0.5153118", "0.5146945", "0.51424366", "0.5141831", "0.51413965", "0.51412755", "0.5130506", "0.5128824", "0.51250714", "0.5122296", "0.51214105", "0.51170045", "0.511427", "0.51112175" ]
0.8567599
0
CreateCreateFileSystemResponse creates a response to parse from CreateFileSystem response
func CreateCreateFileSystemResponse() (response *CreateFileSystemResponse) { response = &CreateFileSystemResponse{ BaseResponse: &responses.BaseResponse{}, } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (manager *mockFileSystemManager) CreateFileSystem(ctx context.Context, groupName string, filesystemName string, timeout *int32, xMsDate string, datalakeName string) (*autorest.Response, error) {\n\tfs := fileSystemResource{\n\t\tresourceGroupName: groupName,\n\t\tstorageAccountName: datalakeName,\n\t\tfilesystemName: filesystemName,\n\t}\n\n\tmanager.fileSystemResource = append(manager.fileSystemResource, fs)\n\tmockresponse := helpers.GetRestResponse(http.StatusOK)\n\n\treturn &mockresponse, nil\n}", "func CreateListFileSystemsResponse() (response *ListFileSystemsResponse) {\n\tresponse = &ListFileSystemsResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client StorageGatewayClient) createFileSystem(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/fileSystems\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateFileSystemResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (client StorageGatewayClient) CreateFileSystem(ctx context.Context, request CreateFileSystemRequest) (response CreateFileSystemResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\n\tif !(request.OpcRetryToken != nil && *request.OpcRetryToken != \"\") {\n\t\trequest.OpcRetryToken = common.String(common.RetryToken())\n\t}\n\n\tociResponse, err = common.Retry(ctx, request, client.createFileSystem, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = CreateFileSystemResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = CreateFileSystemResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(CreateFileSystemResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into CreateFileSystemResponse\")\n\t}\n\treturn\n}", "func (client *Client) CreateFileSystem(request *CreateFileSystemRequest) (response *CreateFileSystemResponse, err error) {\n\tresponse = CreateCreateFileSystemResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func CreateCreateFileSystemRequest() (request *CreateFileSystemRequest) {\n\trequest = &CreateFileSystemRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"CreateFileSystem\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateFileDetectResponse() (response *CreateFileDetectResponse) {\n\tresponse = &CreateFileDetectResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateRenameDbfsResponse() (response *RenameDbfsResponse) {\n\tresponse = &RenameDbfsResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateListAvailableFileSystemTypesResponse() (response *ListAvailableFileSystemTypesResponse) {\n\tresponse = &ListAvailableFileSystemTypesResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (z *zfsctl) CreateFileSystem(ctx context.Context, name string, properties map[string]string) *execute {\n\targs := []string{\"create\", \"-p\"}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (f *Fs) createFile(ctx context.Context, pathID, leaf, mimeType string) (newID string, err error) {\n\tvar resp *http.Response\n\topts := rest.Opts{\n\t\tMethod: \"POST\",\n\t\tRootURL: pathID,\n\t\tNoResponse: true,\n\t}\n\tmkdir := api.CreateFile{\n\t\tName: f.opt.Enc.FromStandardName(leaf),\n\t\tMediaType: mimeType,\n\t}\n\terr = f.pacer.Call(func() (bool, error) {\n\t\tresp, err = f.srv.CallXML(ctx, &opts, &mkdir, nil)\n\t\treturn shouldRetry(ctx, resp, err)\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp.Header.Get(\"Location\"), nil\n}", "func CreateCreateGatewayFileShareResponse() (response *CreateGatewayFileShareResponse) {\n\tresponse = &CreateGatewayFileShareResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateFile(w http.ResponseWriter, r *http.Request) {\n\tvar body datastructures.CreateBody\n\n\tif reqBody, err := ioutil.ReadAll(r.Body); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"Could not read request body\"))\n\t\treturn\n\t} else if err = json.Unmarshal(reqBody, &body); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"Bad request\"))\n\t\treturn\n\t}\n\n\tlog.Println(\n\t\t\"Create file request for\",\n\t\t\"workspace\", body.Workspace.ToString(),\n\t\t\"path\", filepath.Join(body.File.Path...),\n\t)\n\n\tif err := utils.CreateFile(body.Workspace, body.File); err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (s *mockFSServer) Create(ctx context.Context, r *proto.CreateRequest) (*proto.CreateResponse, error) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.filesCreated[r.Path] = false\n\n\treturn new(proto.CreateResponse), nil\n}", "func (c *MockFileStorageClient) CreateFileSystem(ctx context.Context, details filestorage.CreateFileSystemDetails) (*filestorage.FileSystem, error) {\n\treturn &filestorage.FileSystem{Id: &fileSystemID}, nil\n}", "func (fs ReverseHttpFs) Create(n string) (afero.File, error) {\n\treturn nil, syscall.EPERM\n}", "func FileSystemCreate(f types.Filesystem) error {\n\tvar cmd *exec.Cmd\n\tvar debugCMD string\n\n\tswitch f.Mount.Format {\n\tcase \"swap\":\n\t\tcmd = exec.Command(\"/sbin/mkswap\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkswap\", f.Mount.Device)\n\tcase \"ext4\", \"ext3\", \"ext2\":\n\t\t// Add filesystem flags\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-t\")\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Format)\n\n\t\t// Add force\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, \"-F\")\n\n\t\t// Add Device to formate\n\t\tf.Mount.Create.Options = append(f.Mount.Create.Options, f.Mount.Device)\n\n\t\t// Format disk\n\t\tcmd = exec.Command(\"/sbin/mke2fs\", f.Mount.Create.Options...)\n\t\tfor i := range f.Mount.Create.Options {\n\t\t\tdebugCMD = fmt.Sprintf(\"%s %s\", debugCMD, f.Mount.Create.Options[i])\n\t\t}\n\tcase \"vfat\":\n\t\tcmd = exec.Command(\"/sbin/mkfs.fat\", f.Mount.Device)\n\t\tdebugCMD = fmt.Sprintf(\"%s %s\", \"/sbin/mkfs.fat\", f.Mount.Device)\n\tdefault:\n\t\tlog.Warnf(\"Unknown filesystem type [%s]\", f.Mount.Format)\n\t}\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Command [%s] Filesystem [%v]\", debugCMD, err)\n\t}\n\n\treturn nil\n}", "func CreateGetDirectoryOrFilePropertiesResponse() (response *GetDirectoryOrFilePropertiesResponse) {\n\tresponse = &GetDirectoryOrFilePropertiesResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateFaceConfigResponse() (response *CreateFaceConfigResponse) {\n\tresponse = &CreateFaceConfigResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateModifyDirectoryResponse() (response *ModifyDirectoryResponse) {\n\tresponse = &ModifyDirectoryResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateClusterResponse() (response *CreateClusterResponse) {\n\tresponse = &CreateClusterResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func NewQtreeCreateResponse() *QtreeCreateResponse {\n\treturn &QtreeCreateResponse{}\n}", "func CreateUploadIoTDataToBlockchainResponse() (response *UploadIoTDataToBlockchainResponse) {\n\tresponse = &UploadIoTDataToBlockchainResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (a *FileStorageApiService) CreateDirectoryExecute(r ApiCreateDirectoryRequest) (SingleNode, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue SingleNode\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.Ctx, \"FileStorageApiService.CreateDirectory\")\n\tif localBasePath == \"/\" {\n\t localBasePath = \"\"\n\t}\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v2/file_storage/buckets/{bucket_id}/create_directory\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"bucket_id\"+\"}\", _neturl.PathEscape(parameterToString(r.P_bucketId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.P_nodeRequest == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"nodeRequest is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.P_nodeRequest\n\treq, err := a.client.prepareRequest(r.Ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func CreateListFileSystemsRequest() (request *ListFileSystemsRequest) {\n\trequest = &ListFileSystemsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"DFS\", \"2018-06-20\", \"ListFileSystems\", \"alidfs\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateVSwitchResponse() (response *CreateVSwitchResponse) {\n\tresponse = &CreateVSwitchResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (cfr CreateFilesystemResponse) Response() *http.Response {\n\treturn cfr.rawResponse\n}", "func (f FileURL) Create(ctx context.Context, size int64, h FileHTTPHeaders, metadata Metadata) (*FileCreateResponse, error) {\n\tpermStr, permKey, fileAttr, fileCreateTime, FileLastWriteTime, err := h.selectSMBPropertyValues(false, defaultPermissionString, defaultFileAttributes, defaultCurrentTimeString)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.fileClient.Create(ctx, size, fileAttr, fileCreateTime, FileLastWriteTime, nil,\n\t\t&h.ContentType, &h.ContentEncoding, &h.ContentLanguage, &h.CacheControl,\n\t\th.ContentMD5, &h.ContentDisposition, metadata, permStr, permKey)\n}", "func CreateCreatedResponse(w http.ResponseWriter, data interface{}) {\n\tif data != nil {\n\t\tbytes, err := json.Marshal(data)\n\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(http.StatusCreated)\n\t\tw.Write(bytes)\n\t}\n}", "func CreateActionDiskRmaResponse() (response *ActionDiskRmaResponse) {\n\tresponse = &ActionDiskRmaResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (f *FakeFileSystem) Create(file string) (io.WriteCloser, error) {\n\tf.CreateFile = file\n\treturn &f.CreateContent, f.CreateError\n}", "func CreateDescribeGatewayFileSharesResponse() (response *DescribeGatewayFileSharesResponse) {\n\tresponse = &DescribeGatewayFileSharesResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateNormalRpcHsfApiResponse() (response *NormalRpcHsfApiResponse) {\n\tresponse = &NormalRpcHsfApiResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (realFS) Create(name string) (File, error) { return os.Create(name) }", "func CreateFilesystem(e *efs.EFS, n string) (*efs.FileSystemDescription, error) {\n\tcreateParams := &efs.CreateFileSystemInput{\n\t\tCreationToken: aws.String(n),\n\t}\n\tcreateResp, err := e.CreateFileSystem(createParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for the filesystem to become available.\n\tfor {\n\t\tfs, err := DescribeFilesystem(e, n)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(fs.FileSystems) > 0 {\n\t\t\tif *fs.FileSystems[0].LifeCycleState == efsAvail {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n\treturn createResp, nil\n}", "func (fl *FolderList) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (_ fs.Node, _ fs.Handle, err error) {\n\tfl.fs.vlog.CLogf(ctx, libkb.VLog1, \"FL Create\")\n\ttlfName := tlf.CanonicalName(req.Name)\n\tdefer func() { err = fl.processError(ctx, libkbfs.WriteMode, tlfName, err) }()\n\tif strings.HasPrefix(req.Name, \"._\") {\n\t\t// Quietly ignore writes to special macOS files, without\n\t\t// triggering a notification.\n\t\treturn nil, nil, syscall.ENOENT\n\t}\n\treturn nil, nil, libkbfs.NewWriteUnsupportedError(tlfhandle.BuildCanonicalPath(fl.PathType(), string(tlfName)))\n}", "func CreateCreateStackResponse() (response *CreateStackResponse) {\n\tresponse = &CreateStackResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (z *ZFS) Create(req *acomm.Request) (interface{}, *url.URL, error) {\n\tvar args CreateArgs\n\tif err := req.UnmarshalArgs(&args); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif args.Name == \"\" {\n\t\treturn nil, nil, errors.New(\"missing arg: name\")\n\t}\n\n\tif err := fixPropertyTypesFromJSON(args.Properties); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar ds *gozfs.Dataset\n\tvar err error\n\tswitch args.Type {\n\tcase gozfs.DatasetFilesystem:\n\t\tds, err = gozfs.CreateFilesystem(args.Name, args.Properties)\n\tcase gozfs.DatasetVolume:\n\t\tif args.Volsize <= 0 {\n\t\t\terr = errors.New(\"missing or invalid arg: volsize\")\n\t\t\tbreak\n\t\t}\n\t\tds, err = gozfs.CreateVolume(args.Name, args.Volsize, args.Properties)\n\tdefault:\n\t\terr = errors.New(\"missing or invalid arg: type\")\n\t}\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn &DatasetResult{newDataset(ds)}, nil, nil\n}", "func CreateCreateExpressSyncResponse() (response *CreateExpressSyncResponse) {\n\tresponse = &CreateExpressSyncResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client *Client) CreateFileSystemWithCallback(request *CreateFileSystemRequest, callback func(response *CreateFileSystemResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFileSystemResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFileSystem(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func CreateCreateExchangeResponse() (response *CreateExchangeResponse) {\n\tresponse = &CreateExchangeResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_api_proto_rawDescGZIP(), []int{2}\n}", "func CreateDescribeExplorerResponse() (response *DescribeExplorerResponse) {\n\tresponse = &DescribeExplorerResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateFaceGroupResponse() (response *CreateFaceGroupResponse) {\n\tresponse = &CreateFaceGroupResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client *Client) CreateFileSystemWithChan(request *CreateFileSystemRequest) (<-chan *CreateFileSystemResponse, <-chan error) {\n\tresponseChan := make(chan *CreateFileSystemResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateFileSystem(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (*FileSystemBase) Create(path string, flags int, mode uint32) (int, uint64) {\n\treturn -ENOSYS, ^uint64(0)\n}", "func CreateMetastoreCreateTableResponse() (response *MetastoreCreateTableResponse) {\n\tresponse = &MetastoreCreateTableResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func createFile(fs fileSystem, fileName string) (file, error) {\n\treturn fs.Create(fileName)\n}", "func CreateCreateTagTaskResponse() (response *CreateTagTaskResponse) {\n\tresponse = &CreateTagTaskResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateVmAndSaveStockResponse() (response *CreateVmAndSaveStockResponse) {\n\tresponse = &CreateVmAndSaveStockResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateFabricChannelResponse() (response *CreateFabricChannelResponse) {\n\tresponse = &CreateFabricChannelResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateTrafficMirrorFilterResponse() (response *CreateTrafficMirrorFilterResponse) {\n\tresponse = &CreateTrafficMirrorFilterResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDescribeLogstoreStorageResponse() (response *DescribeLogstoreStorageResponse) {\n\tresponse = &DescribeLogstoreStorageResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateResponse() *application.HTTPResponse {\n\tresponse := &application.HTTPResponse{}\n\tresponse.Headers = make(map[string]*application.HTTPResponse_HTTPHeaderParameter)\n\treturn response\n}", "func CreateCreateFileDetectRequest() (request *CreateFileDetectRequest) {\n\trequest = &CreateFileDetectRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Sas\", \"2018-12-03\", \"CreateFileDetect\", \"sas\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateTopicResponse() (response *CreateTopicResponse) {\n\tresponse = &CreateTopicResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (dir *HgmDir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\treturn nil, nil, fuse.Errno(syscall.EROFS)\n}", "func Create(name string) (*os.File, error)", "func (s *Service) Create(parent *basefs.File, name string, isDir bool) (*basefs.File, error) {\n\tparentID := \"\"\n\tvar megaParent *mega.Node\n\tif parent == nil {\n\t\tmegaParent = s.megaCli.FS.GetRoot()\n\t} else {\n\t\tparentID = parent.ID\n\t\tmegaParent = parent.Data.(*MegaPath).Node\n\t}\n\n\tnewName := parentID + \"/\" + name\n\tif isDir {\n\t\tnewNode, err := s.megaCli.CreateDir(name, megaParent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\t}\n\n\t// Create tempFile, since mega package does not accept a reader\n\tf, err := ioutil.TempFile(os.TempDir(), \"megafs\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Close() // we don't need the descriptor, only the name\n\n\tprogress := make(chan int, 1)\n\t// Upload empty file\n\tnewNode, err := s.megaCli.UploadFile(f.Name(), megaParent, name, &progress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t<-progress\n\n\treturn File(&MegaPath{Path: newName, Node: newNode}), nil\n\n}", "func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {\n\td.fs.logger.Debugf(\"File create request for %v\\n\", d)\n\n\tu, err := d.fs.putio.Files.Upload(ctx, strings.NewReader(\"\"), req.Name, d.ID)\n\tif err != nil {\n\t\td.fs.logger.Printf(\"Upload failed: %v\\n\", err)\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\t// possibly a torrent file is uploaded. torrent files are picked up by the\n\t// Put.io API and pushed into the transfer queue. Original torrent file is\n\t// not keeped.\n\tif u.Transfer != nil {\n\t\treturn nil, nil, fuse.ENOENT\n\t}\n\n\tif u.File == nil {\n\t\treturn nil, nil, fuse.EIO\n\t}\n\n\tf := &File{fs: d.fs, File: u.File}\n\n\treturn f, f, nil\n}", "func CreateDescribeImportOASTaskResponse() (response *DescribeImportOASTaskResponse) {\n\tresponse = &DescribeImportOASTaskResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateResponse(resultCode uint32, internalCommand []byte) ([]byte, error) {\n\t// Response frame:\n\t// - uint32 (size of response)\n\t// - []byte (response)\n\t// - uint32 (code)\n\tvar buf bytes.Buffer\n\n\tif err := binary.Write(&buf, binary.BigEndian, uint32(len(internalCommand))); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err := buf.Write(internalCommand); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := binary.Write(&buf, binary.BigEndian, resultCode); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func CreateResponse(w *gin.Context, payload interface{}) {\n\tw.JSON(200, payload)\n}", "func CreateCreateDataAPIServiceResponse() (response *CreateDataAPIServiceResponse) {\n\tresponse = &CreateDataAPIServiceResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDescribeServiceMeshesResponse() (response *DescribeServiceMeshesResponse) {\n\tresponse = &DescribeServiceMeshesResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*MkDirResponse) Descriptor() ([]byte, []int) {\n\treturn file_IOService_proto_rawDescGZIP(), []int{3}\n}", "func CreateDescribeParentPlatformResponse() (response *DescribeParentPlatformResponse) {\n\tresponse = &DescribeParentPlatformResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (o *CreateFoldersCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(201)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (mzk *MockZK) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {\n\tmzk.Args = append(mzk.Args, []interface{}{\n\t\t\"create\",\n\t\tpath,\n\t\tdata,\n\t\tflags,\n\t\tacl,\n\t})\n\treturn mzk.CreateFn(path, data, flags, acl)\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_task_v1_task_proto_rawDescGZIP(), []int{2}\n}", "func (c *WSCodec) CreateResponse(id interface{}, reply interface{}) interface{} {\n\treturn &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply}\n}", "func (client BaseClient) CreateSystemResponder(resp *http.Response) (result System, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func CreateCreateScheduleResponse() (response *CreateScheduleResponse) {\n\tresponse = &CreateScheduleResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func createResponse(req *http.Request) *http.Response {\n\treturn &http.Response{\n\t\tStatusCode: http.StatusOK,\n\t\tRequest: req,\n\t\tHeader: make(http.Header),\n\t\tBody: ioutil.NopCloser(bytes.NewBuffer([]byte{})),\n\t}\n}", "func (*CreateNodeResponse) Descriptor() ([]byte, []int) {\n\treturn file_service_node_proto_rawDescGZIP(), []int{1}\n}", "func CreateUploadFileByURLResponse() (response *UploadFileByURLResponse) {\n\tresponse = &UploadFileByURLResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (d *VolumeDriver) Create(r volume.Request) volume.Response {\n\tlog.Errorf(\"VolumeDriver Create to be implemented\")\n\treturn volume.Response{Err: \"\"}\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_account_proto_rawDescGZIP(), []int{1}\n}", "func (fs *dsFileSys) Create(name string) (fsi.File, error) {\n\n\t// WriteFile & Create\n\tdir, bname := fs.SplitX(name)\n\n\tf := DsFile{}\n\tf.fSys = fs\n\tf.BName = common.Filify(bname)\n\tf.Dir = dir\n\tf.MModTime = time.Now()\n\tf.MMode = 0644\n\n\t// let all the properties by set by fs.saveFileByPath\n\terr := f.Sync()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// return &f, nil\n\tff := fsi.File(&f)\n\treturn ff, err\n\n}", "func create() (*os.File, error) {\n\tbaseURL, err := url.Parse(*root)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn os.Create(baseURL.Host + \".xml\")\n}", "func (fsOnDisk) Create(name string) (File, error) { return os.Create(name) }", "func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateFileSystemInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateFileSystem\", params, optFns, c.addOperationCreateFileSystemMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateFileSystemOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func CreateFile(buf []byte) (File, error) {\n\tfileFormat, dataType, err := getFileInformation(buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf, err := NewFile(*fileFormat)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif *dataType == JsonData {\n\t\terr = json.Unmarshal(buf, f)\n\t} else {\n\t\terr = f.Parse(string(buf))\n\t}\n\treturn f, err\n}", "func (s *Systemd) Create(req *acomm.Request) (interface{}, *url.URL, error) {\n\tvar args CreateArgs\n\tif err := req.UnmarshalArgs(&args); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif args.Name == \"\" {\n\t\treturn nil, nil, errors.New(\"missing arg: name\")\n\t}\n\n\tunitFilePath, err := s.config.UnitFilePath(args.Name)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif _, err = os.Stat(unitFilePath); err == nil {\n\t\treturn nil, nil, errors.New(\"unit file already exists\")\n\t}\n\n\tunitFileContents, err := ioutil.ReadAll(unit.Serialize(args.UnitOptions))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\t// TODO: Sort out file permissions\n\treturn nil, nil, ioutil.WriteFile(unitFilePath, unitFileContents, os.ModePerm)\n}", "func CreateGetServiceInputMappingResponse() (response *GetServiceInputMappingResponse) {\n\tresponse = &GetServiceInputMappingResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateResponse(result interface{}, err error) *Response {\n\tif err == nil {\n\t\treturn CreateSuccessResponse(result)\n\t}\n\treturn CreateErrorResponse(err)\n}", "func (e *FileExistsError) ConstructResponse() string {\n\tresponse := \"already_\"\n\tif e.state == Published {\n\t\tresponse += \"published\"\n\t} else {\n\t\tresponse += \"uploaded\"\n\t}\n\tif e.userIsOwner {\n\t\tresponse += \"_self\"\n\t}\n\treturn response\n}", "func CreateDeleteServiceTimeConfigResponse() (response *DeleteServiceTimeConfigResponse) {\n\tresponse = &DeleteServiceTimeConfigResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_todo_proto_rawDescGZIP(), []int{2}\n}", "func CreateCreateAgentResponse() (response *CreateAgentResponse) {\n\tresponse = &CreateAgentResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func createJSONFile (outputDir string, fileName string) *os.File {\n\n file, err := os.Create(filepath.Join(outputDir, fileName+jsonExt)) \n check(err) \n\n return file\n}", "func CreateUpdateMediaStorageClassResponse() (response *UpdateMediaStorageClassResponse) {\n\tresponse = &UpdateMediaStorageClassResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateListAvailableFileSystemTypesRequest() (request *ListAvailableFileSystemTypesRequest) {\n\trequest = &ListAvailableFileSystemTypesRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"EHPC\", \"2018-04-12\", \"ListAvailableFileSystemTypes\", \"ehs\", \"openAPI\")\n\treturn\n}", "func MakeCreateEndpoint(s service.FilesCreatorService) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(CreateRequest)\n\t\ts0 := s.Create(ctx, req.FileDescriptor)\n\t\treturn CreateResponse{S0: s0}, nil\n\t}\n}", "func (fsys *FS) Create(filePath string, flags int, mode uint32) (errc int, fh uint64) {\n\tdefer fs.Trace(filePath, \"flags=0x%X, mode=0%o\", flags, mode)(\"errc=%d, fh=0x%X\", &errc, &fh)\n\tleaf, parentDir, errc := fsys.lookupParentDir(filePath)\n\tif errc != 0 {\n\t\treturn errc, fhUnset\n\t}\n\t_, handle, err := parentDir.Create(leaf)\n\tif err != nil {\n\t\treturn translateError(err), fhUnset\n\t}\n\treturn 0, fsys.openFilesWr.Open(handle)\n}", "func CreateCreateETLJobResponse() (response *CreateETLJobResponse) {\n\tresponse = &CreateETLJobResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateMeetingResponse() (response *CreateMeetingResponse) {\n\tresponse = &CreateMeetingResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (dcr DirectoryCreateResponse) Response() *http.Response {\n\treturn PathCreateResponse(dcr).Response()\n}", "func CreateDropPartitionResponse() (response *DropPartitionResponse) {\n\tresponse = &DropPartitionResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateSegmentSkyResponse() (response *SegmentSkyResponse) {\n\tresponse = &SegmentSkyResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}" ]
[ "0.7409187", "0.7196471", "0.7153243", "0.68064606", "0.67132664", "0.66525936", "0.65382826", "0.6406937", "0.6363215", "0.6359061", "0.6322241", "0.6244479", "0.61652124", "0.61642545", "0.61275655", "0.6105425", "0.5946818", "0.5941657", "0.5848543", "0.5826824", "0.577976", "0.57733905", "0.5758492", "0.5747923", "0.5744731", "0.57396835", "0.5689065", "0.5681631", "0.5680091", "0.56444407", "0.563234", "0.56201255", "0.5608951", "0.56014705", "0.5592805", "0.5585474", "0.5582265", "0.5581949", "0.55807084", "0.55626774", "0.5546555", "0.55463594", "0.5546118", "0.5535951", "0.5530715", "0.55220884", "0.551553", "0.55060273", "0.5500247", "0.5495028", "0.54948586", "0.54770744", "0.54632044", "0.54516846", "0.54378635", "0.53995013", "0.53981733", "0.5388875", "0.5382732", "0.5371733", "0.53707623", "0.5369803", "0.5367772", "0.5366723", "0.535142", "0.5351372", "0.5333564", "0.5331378", "0.5327585", "0.53202814", "0.5311656", "0.5311418", "0.53090256", "0.52991235", "0.5297834", "0.52957904", "0.5293028", "0.52919465", "0.52918726", "0.5288642", "0.528266", "0.528248", "0.52755314", "0.5274467", "0.5273221", "0.5272936", "0.5263046", "0.5259504", "0.5258404", "0.52569115", "0.5256101", "0.5248763", "0.5244914", "0.5240597", "0.5235423", "0.5224955", "0.52202874", "0.5220245", "0.52052367", "0.51974773" ]
0.8397854
0
SaveBody creates or overwrites the existing response body file for the url associated with the given Fetcher
func (f Fetcher) SaveBody() { file, err := os.Create(f.url) check(err) defer file.Close() b := f.processBody() _, err = file.Write(b) check(err) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Response) Save(fileName string) error {\r\n\treturn ioutil.WriteFile(fileName, r.Body, 0644)\r\n}", "func (response *S3Response) WriteBody(dst io.Writer) error {\n defer response.Close()\n _, err := io.Copy(dst, response.httpResponse.Body)\n return err\n}", "func saveFile(savedPath string, res *http.Response) {\n\t// create a file of the given name and in the given path\n\tf, err := os.Create(savedPath)\n\terrCheck(err)\n\tio.Copy(f, res.Body)\n}", "func (resp *Response) SaveFile(filename string, perm os.FileMode) (err error) {\n\tvar file *os.File\n\tfile, err = os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)\n\tif err == nil {\n\t\tdefer file.Close()\n\t\terr = drainBody(resp.Body, file)\n\t}\n\treturn\n}", "func (p *Page) save() error {\n filename := p.Title + \".txt\"\n return ioutil.WriteFile(filename, p.Body, 0600)\n}", "func (p *para) saveFile(res *http.Response) error {\n\tvar err error\n\tp.ContentType = res.Header[\"Content-Type\"][0]\n\terr = p.getFilename(res)\n\tif err = p.getFilename(res); err != nil {\n\t\treturn err\n\t}\n\tfile, err := os.Create(filepath.Join(p.WorkDir, p.Filename))\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(file, res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfileInfo, err := file.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"{\\\"Filename\\\": \\\"%s\\\", \\\"Type\\\": \\\"%s\\\", \\\"MimeType\\\": \\\"%s\\\", \\\"FileSize\\\": %d}\\n\", p.Filename, p.Kind, p.ContentType, fileInfo.Size())\n\tdefer func() {\n\t\tfile.Close()\n\t\tres.Body.Close()\n\t}()\n\treturn nil\n}", "func api_save_cert_of_need(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"api_save_cert_of_need\", r.URL.Scheme, \"method=\", r.Method)\n\tfmt.Println(\"URL=\", r.URL)\n\tvar urstr = r.URL.RequestURI()\n\tid := strings.Replace(urstr, \"/api/save-cert-of-need/\", \"\", 1)\n\tfmt.Println(\"id =\", id)\n\tid = strings.SplitN(id, \"?\", 2)[0]\n\tid = strings.Replace(id, \"\\\\\", \"-\", -1)\n\tid = strings.Replace(id, \"/\", \"-\", -1)\n\tid = strings.Replace(id, \" \", \"-\", -1)\n\tid = strings.Replace(id, \":\", \"-\", -1)\n\tfmt.Println(\"id=\", id)\n\tif len(id) < 2 {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, \"id is mandatory as last segment of URI\")\n\t\treturn\n\t}\n\t// Read the body string.\n\tfmt.Println(\"contentLength=\", r.ContentLength)\n\tbodya := make([]byte, r.ContentLength)\n\t_, err := r.Body.Read(bodya)\n\n\toutFiName := \"data/cert-of-need/\" + id + \".JSON\"\n\terr = ioutil.WriteFile(outFiName, bodya, 0644)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"err saving file \", err)\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintf(w, \"{'status' : 'sucess'}\")\n\n\tbodys := string(bodya)\n\tfmt.Println(\"bodys=\", bodys)\n}", "func DownloadFile(filepath string, url string) error {\n\n // Get the data\n resp, err := http.Get(url)\n if err != nil {\n //return err\n fmt.Println(\"Get the data\")\n }\n defer resp.Body.Close()\n\n // Create the file\n out, err := os.Create(filepath)\n if err != nil {\n fmt.Println(\"Create the file\")\n }\n defer out.Close()\n\n // Write the body to file\n _, err = io.Copy(out, resp.Body)\n return err\n}", "func (s *Saver) SaveResponse(resp *http.Response) error {\n\trespName, err := GetResponseFilename(s.reqName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(filepath.Join(s.dir, respName))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer handleClose(&err, f)\n\n\treturn resp.Write(f)\n}", "func (p *Page) save() error {\n\tfilename := \"data/\" + p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}", "func writeBody(fileName, line string) (string, error) {\n\t//make the temp directory if not exist\n\tdir, err := ioutil.TempDir(\"\", APP_SHORT_NAME)\n\tif err != nil {\n\t\treturn fileName, err\n\t}\n\t//write the file inside the HOME/directory\n\ttempGoFile := filepath.Join(dir, fileName) + EXT\n\treturn tempGoFile, ioutil.WriteFile(tempGoFile, []byte(line), 0644)\n}", "func (s *Scraper) storeDownload(u *url.URL, buf *bytes.Buffer, fileExtension string) {\n\tisAPage := false\n\tif fileExtension == \"\" {\n\t\thtml, fixed, err := s.fixURLReferences(u, buf)\n\t\tif err != nil {\n\t\t\ts.logger.Error(\"Fixing file references failed\",\n\t\t\t\tlog.Stringer(\"url\", u),\n\t\t\t\tlog.Err(err))\n\t\t\treturn\n\t\t}\n\n\t\tif fixed {\n\t\t\tbuf = bytes.NewBufferString(html)\n\t\t}\n\t\tisAPage = true\n\t}\n\n\tfilePath := s.GetFilePath(u, isAPage)\n\t// always update html files, content might have changed\n\tif err := s.writeFile(filePath, buf); err != nil {\n\t\ts.logger.Error(\"Writing to file failed\",\n\t\t\tlog.Stringer(\"URL\", u),\n\t\t\tlog.String(\"file\", filePath),\n\t\t\tlog.Err(err))\n\t}\n}", "func SaveFileByFileInfo(fileInfo resource.IResource, resp *http.Response) resource.IResource {\n\tMakeDirAll(fileInfo.GetSaveParentPath())\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tfmt.Println(\"push body read error is \", err)\n\t\treturn nil\n\t}\n\tdataSize := len(body)\n\terr = ioutil.WriteFile(fileInfo.GetSavePath(), body, 0644)\n\tif err != nil {\n\t\tfmt.Println(\"push body write error is \", err)\n\t\treturn nil\n\t}\n\tfileInfo.SetDataSize(dataSize)\n\treturn fileInfo\n}", "func (r *Recipe) Save(fname string) (err error) {\n\tb, err := json.MarshalIndent(r, \"\", \" \")\n\tif err != nil {\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(fname, b, 0644)\n\treturn\n}", "func (p *Page) save() error {\r\n\tfilename := p.Title + \".txt\"\r\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\r\n}", "func (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}", "func fetchWriteCache(url string, body *string) <-chan struct{} {\n\tIOComplete := make(chan struct{})\n\tgo func() {\n\t\tfetchCache.WriteString(\"\", Id(NormalizeURL(url)), body, false)\n\t\tclose(IOComplete)\n\t}()\n\treturn IOComplete\n}", "func DownloadFile(saveto string, extension string, url string, maxMegabytes uint64) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tfilename := saveto + \"/\" + FilenameFromURL(url)\n\t// Create the file\n\tvar out *os.File\n\tif _, err := os.Stat(filename); err == nil {\n\t\tout, err = os.Create(filename + randString(10) + \".\" + extension)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tout, err = os.Create(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t//_, err = io.Copy(out, resp.Body)\n\tmegabytes := int64(maxMegabytes * 1024000)\n\t_, err = io.CopyN(out, resp.Body, megabytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (f *fetcher) Save(data []byte) {\n\t// Implementation can be application dependent\n\t// eg. you may implement connect to a redis server here\n\tfmt.Println(string(data))\n}", "func (f Fetcher) processBody() []byte {\n\tb, err := io.ReadAll(f.resp.Body)\n\tf.resp.Body.Close()\n\tif f.resp.StatusCode >= 300 {\n\t\tlog.Fatalf(\"Response failed with status code: %d\\n and body: %s\\n\", f.resp.StatusCode, b)\n\t}\n\tcheck(err)\n\treturn b\n}", "func saveHandler(w http.ResponseWriter, r *http.Request) {\r\n title := r.URL.Path[len(\"/save/\"):]\r\n body := r.FormValue(\"body\")\r\n p := &Page{Title: title, Body: []byte(body)}\r\n p.save()\r\n http.Redirect(w, r, \"/view/\"+title, http.StatusFound)\r\n}", "func PostHandler(basePath string, w http.ResponseWriter, r *http.Request) {\n\tname := fileKey(r.URL)\n\tf := NewFile(name, r.Header.Get(\"Content-Type\"))\n\n\tFilesLock.Lock()\n\tFiles.Add(name, f)\n\tFilesLock.Unlock()\n\n\t// Start writing to file without holding lock so that GET requests can read from it\n\tio.Copy(f, r.Body)\n\tr.Body.Close()\n\tf.Close()\n\n\terr := f.WriteToDisk(basePath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error saving to disk: %v\", err)\n\t}\n\n\tw.WriteHeader(http.StatusNoContent)\n}", "func (p *Page) save() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\t// 0600 = r-w permissions for current user only\n}", "func (page *Page) save() error {\n\tfilename := page.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, page.Body, 0600)\n}", "func Save(r *http.Request, w http.ResponseWriter) error {\n\n}", "func DownloadToFile(outputFilePath, defaultFileName string, body []byte, extension string, permissions os.FileMode, overwrite bool) string {\n\tmsgPrinter := i18n.GetMessagePrinter()\n\tvar fileName string\n\t// if no fileName and filePath specified, data will be saved in current dir, with name {defaultFileName}\n\tif outputFilePath == \"\" {\n\t\tfileName = defaultFileName\n\t} else {\n\t\t// trim the ending \"/\" if there are more than 1 \"/\"\n\t\tfor strings.HasSuffix(outputFilePath, \"//\") {\n\t\t\toutputFilePath = strings.TrimSuffix(outputFilePath, \"/\")\n\t\t}\n\n\t\tfi, _ := os.Stat(outputFilePath)\n\t\tif fi == nil {\n\t\t\t// outputFilePath is not an existing dir, then consider it as fileName, need to remove \"/\" in the end\n\t\t\tif strings.HasSuffix(outputFilePath, \"/\") {\n\t\t\t\toutputFilePath = strings.TrimSuffix(outputFilePath, \"/\")\n\t\t\t}\n\t\t\tfileName = outputFilePath\n\t\t} else {\n\t\t\tif fi.IsDir() {\n\t\t\t\tif !strings.HasSuffix(outputFilePath, \"/\") {\n\t\t\t\t\toutputFilePath = outputFilePath + \"/\"\n\t\t\t\t}\n\t\t\t\tfileName = fmt.Sprintf(\"%s%s\", outputFilePath, defaultFileName)\n\t\t\t} else {\n\t\t\t\tfileName = outputFilePath\n\t\t\t}\n\t\t}\n\t}\n\tif fileName[len(fileName)-len(extension):] != extension {\n\t\tfileName += extension\n\t}\n\n\tif !overwrite {\n\t\tif _, err := os.Stat(fileName); !os.IsNotExist(err) {\n\t\t\tFatal(CLI_INPUT_ERROR, msgPrinter.Sprintf(\"File %s already exists. Please specify a different file path or file name. To overwrite the existing file, use the '--overwrite' flag.\", fileName))\n\t\t}\n\t}\n\n\t// add newline to end of file\n\tbodyString := string(body)\n\tif bodyString[len(bodyString)-1] != '\\n' {\n\t\tbodyString += \"\\n\"\n\t}\n\tbody = []byte(bodyString)\n\n\tif err := ioutil.WriteFile(fileName, body, permissions); err != nil {\n\t\tFatal(INTERNAL_ERROR, msgPrinter.Sprintf(\"Failed to save data for object '%s' to file %s, err: %v\", defaultFileName, fileName, err))\n\t}\n\n\treturn fileName\n}", "func savePage(url url.URL, body []byte) bool{\n\t// TODO: Take save location as a CMD line flag\n\trootDir := \"/tmp/scraper\"\n\n\tdirPath := rootDir + \"/\" + url.Host + url.Path\n\n\terr := os.MkdirAll(dirPath, 0777)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot create directory %s. \\nError: %s\", dirPath, err)\n\t\treturn false\n\t}\n\n\tfilePath := dirPath + \"/index.html\"\n\n\terr = ioutil.WriteFile(filePath, body, 0777)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot write to file=%s. \\nError: %s\", filePath, err)\n\t\treturn false\n\t}\n\treturn true\n}", "func saveHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle, err := getTitle(w, r)\n\tif err != nil {\n\t\treturn\n\t}\n\tbody := r.FormValue(\"body\")\t// Get the page content. It is of type string - we must convert it to []byte before it will fit into the Page struct.ß\n\tp := &Page{Title: title, Body: []byte(body)}\n\terr = p.save()\t// Write the data to a file\n\t// An error that occurs during p.save() will be reported to the user\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\thttp.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}", "func SaveTo(ctx *log.Context, d []Downloader, dst string, mode os.FileMode) (int64, error) {\n\tf, err := os.OpenFile(dst, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, mode)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"failed to open file for writing\")\n\t}\n\tdefer f.Close()\n\n\tn, err := WithRetries(ctx, f, d, ActualSleep)\n\tif err != nil {\n\t\treturn n, errors.Wrapf(err, \"failed to download response and write to file: %s\", dst)\n\t}\n\n\treturn n, nil\n}", "func (m *CopyToDefaultContentLocationPostRequestBody) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"destinationFileName\", m.GetDestinationFileName())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"sourceFile\", m.GetSourceFile())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func DownloadFile(filepath string, url string)(err error){\n //Get the data \n resp, err := http.Get(url)\n if err != nil {\n logs.Error(\"Error downloading file: \"+err.Error())\n return err\n }\n defer resp.Body.Close()\n // Create the file\n out, err := os.Create(filepath)\n if err != nil {\n logs.Error(\"Error creating file after download: \"+err.Error())\n return err\n }\n defer out.Close()\n\n // Write the body to file\n _, err = io.Copy(out, resp.Body)\n if err != nil {\n logs.Error(\"Error Copying downloaded file: \"+err.Error())\n return err\n }\n return nil\n}", "func (fcb *FileCacheBackend) Save(ob types.OutgoingBatch) error {\n\tfilename := fcb.getFilename(fcb.getCacheFilename(ob))\n\tlog.Printf(\"Saving to %s\", filename)\n\tfile, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to save to %s - %s\", filename, err)\n\t}\n\tdefer file.Close()\n\tfor _, item := range ob.Values {\n\t\tfile.WriteString(item + \"\\n\")\n\t}\n\treturn nil\n}", "func (p *Page) save() error {\r\n\tfilename := p.Title\r\n\t//writes data to a file named by filename, the 0600 indicates that the file should be created with\r\n\t//read and write permissions for the user\r\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\r\n}", "func (p *Post) Download(loc string) error {\n\tres, err := http.Get(p.FileURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tfileName := path.Join(loc, p.GetFileName())\n\n\tfh, err := os.Create(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fh.Close()\n\n\t_, err = io.Copy(fh, res.Body)\n\treturn err\n}", "func (r *Repository) Save(url string, toAddr, ccAddr []string, content string, status int) error {\n\treturn nil\n}", "func DownloadFile(client *http.Client, url, filepath string) (string, error) {\n\n\tlog.Println(\"Downloading\")\n\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\tlog.Printf(\"error: GET, %s\", err)\n\t\treturn \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn \"\", fmt.Errorf(\"Received non 200 response code\")\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"error: READ, %s\", err)\n\t\treturn \"\", err\n\t}\n\n\t// Create blank file\n\t//file, err := os.Create(filepath)\n\t//file, err := os.OpenFile(filepath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\t//if err != nil {\n\t//\treturn \"\", err\n\t//}\n\n\t//buff := make([]byte, 4096)\n\n\t//for {\n\t//\tnread, err := resp.Body.Read(buff)\n\t//\tif nread == 0 {\n\t//\t\tif err == nil {\n\t//\t\t\tcontinue\n\t//\t\t}\n\t//\t\tif _, err := file.Write(buff); err != nil {\n\t//\t\t\tbreak\n\t//\t\t}\n\t//\t\tif err != nil {\n\t//\t\t\tbreak\n\t//\t\t}\n\t//\t}\n\t//}\n\t////size, err := io.Copy(file, resp.Body)\n\t//defer file.Close()\n\n\t////if err != nil {\n\t////\tlog.Printf(\"error: WRITE, %s\", err)\n\t////\treturn \"\", err\n\t////}\n\t//statsFile, err := file.Stat()\n\t//log.Printf(\"Downloaded a file %s with size %d\", filepath, statsFile.Size())\n\n\tif err := ioutil.WriteFile(filepath, body, 0644); err != nil {\n\t\tlog.Printf(\"error: WRITE, %s\", err)\n\t\treturn \"\", err\n\t}\n\n\t//content, err := ioutil.ReadAll(file)\n\t//if err != nil {\n\t//\tlog.Printf(\"error: READ, %s\", err)\n\t//\treturn \"\", err\n\t//}\n\n\tmd5sum := md5.Sum(body)\n\tmd5s := hex.EncodeToString(md5sum[0:])\n\n\treturn md5s, nil\n}", "func createBody(f *os.File, releaseTag, branch, docURL, exampleURL, releaseTars string) error {\n\tvar title string\n\tif *preview {\n\t\ttitle = \"Branch \"\n\t}\n\n\tif releaseTag == \"HEAD\" || releaseTag == branchHead {\n\t\ttitle += branch\n\t} else {\n\t\ttitle += releaseTag\n\t}\n\n\tif *preview {\n\t\tf.WriteString(fmt.Sprintf(\"**Release Note Preview - generated on %s**\\n\", time.Now().Format(\"Mon Jan 2 15:04:05 MST 2006\")))\n\t}\n\n\tf.WriteString(fmt.Sprintf(\"\\n# %s\\n\\n\", title))\n\tf.WriteString(fmt.Sprintf(\"[Documentation](%s) & [Examples](%s)\\n\\n\", docURL, exampleURL))\n\n\tif releaseTars != \"\" {\n\t\tf.WriteString(fmt.Sprintf(\"## Downloads for %s\\n\\n\", title))\n\t\ttables := []struct {\n\t\t\theading string\n\t\t\tfilename []string\n\t\t}{\n\t\t\t{\"\", []string{releaseTars + \"/kubernetes.tar.gz\", releaseTars + \"/kubernetes-src.tar.gz\"}},\n\t\t\t{\"Client Binaries\", []string{releaseTars + \"/kubernetes-client*.tar.gz\"}},\n\t\t\t{\"Server Binaries\", []string{releaseTars + \"/kubernetes-server*.tar.gz\"}},\n\t\t\t{\"Node Binaries\", []string{releaseTars + \"/kubernetes-node*.tar.gz\"}},\n\t\t}\n\n\t\tfor _, table := range tables {\n\t\t\terr := createDownloadsTable(f, releaseTag, table.heading, table.filename...)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to create downloads table: %v\", err)\n\t\t\t}\n\t\t}\n\t\tf.WriteString(\"\\n\")\n\t}\n\treturn nil\n}", "func (api *api) save() {\n\tr := map[string]string{}\n\tfor k, v := range api.Manager.pathes {\n\t\tr[k] = v.content\n\t}\n\tdata, err := json.MarshalIndent(r, \"\", \" \")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(api.ConfigFile, data, 0755)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (p BlogPost) Save() error {\n\ttemp, err := json.Marshal(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(\"www/posts/\"+p.Path+\".json\", temp, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *Page) save() error {\n\tfilename := \"./pages/\" + p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}", "func writeHTTPResponseInWriter(httpRes http.ResponseWriter, httpReq *http.Request, nobelPrizeWinnersResponse []byte, err error) {\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\thttp.Error(httpRes, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlog.Printf(\"Request %s Succesfully Completed\", httpReq.RequestURI)\n\thttpRes.Header().Set(\"Content-Type\", \"application/json\")\n\thttpRes.Write(nobelPrizeWinnersResponse)\n}", "func (r *historyRow) save(dir string) error {\n\trBytes, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thistoryFile := getLatestHistoryFile(dir)\n\n\tf, err := os.OpenFile(historyFile.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\t_, err = f.Write(append(rBytes, []byte(\"\\n\")...))\n\treturn err\n}", "func writeToPath(resp *http.Response, path string) (int, error) {\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode > 299 {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn resp.StatusCode, errors.New(string(msg))\n\t}\n\n\tout, err := os.Create(path)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer out.Close()\n\n\tio.Copy(out, resp.Body)\n\treturn resp.StatusCode, nil\n}", "func (env *Env) Save(res http.ResponseWriter, req *http.Request, title string) {\n\tenv.Log.V(1, \"beginning hanlding of Save.\")\n\ttitle = strings.Replace(strings.Title(title), \" \", \"_\", -1)\n\tbody := []byte(req.FormValue(\"body\"))\n\tpage := &webAppGo.Page{Title: title, Body: body}\n\terr := env.Cache.SaveToCache(page)\n\tif err != nil {\n\t\tenv.Log.V(1, \"notifying client that an internal error occured. Error is associated with Cache.SaveToCache.\")\n\t\thttp.Error(res, err.Error(), 500)\n\t}\n\terr = env.DB.SavePage(page)\n\tif err != nil {\n\t\tenv.Log.V(1, \"notifying client that an internal error occured. Error is associated with Cache.SavePage.\")\n\t\thttp.Error(res, err.Error(), 500)\n\t}\n\tenv.Log.V(1, \"The requested new page was successully saved, redirecting client to /view/PageTitle.\")\n\thttp.Redirect(res, req, \"/view/\"+title, http.StatusFound)\n}", "func SaveFileHandler(w http.ResponseWriter, r *http.Request) {\n\thttpSession, _ := session.HTTPSession.Get(r, session.CookieName)\n\tif httpSession.IsNew {\n\t\thttp.Error(w, \"Forbidden\", http.StatusForbidden)\n\n\t\treturn\n\t}\n\tuid := httpSession.Values[\"uid\"].(string)\n\n\tresult := gulu.Ret.NewResult()\n\tdefer gulu.Ret.RetResult(w, r, result)\n\n\tif conf.Wide.ReadOnly {\n\t\tresult.Code = -1\n\t\tresult.Msg = \"readonly mode\"\n\t\treturn\n\t}\n\n\tvar args map[string]interface{}\n\n\tif err := json.NewDecoder(r.Body).Decode(&args); err != nil {\n\t\tlogger.Error(err)\n\t\tresult.Code = -1\n\n\t\treturn\n\t}\n\n\tfilePath := args[\"file\"].(string)\n\tsid := args[\"sid\"].(string)\n\n\tif gulu.Go.IsAPI(filePath) || !session.CanAccess(uid, filePath) {\n\t\thttp.Error(w, \"Forbidden\", http.StatusForbidden)\n\n\t\treturn\n\t}\n\n\tfout, err := os.Create(filePath)\n\n\tif nil != err {\n\t\tlogger.Error(err)\n\t\tresult.Code = -1\n\n\t\treturn\n\t}\n\n\tcode := args[\"code\"].(string)\n\n\tfout.WriteString(code)\n\n\tif err := fout.Close(); nil != err {\n\t\tlogger.Error(err)\n\t\tresult.Code = -1\n\n\t\twSession := session.WideSessions.Get(sid)\n\t\twSession.EventQueue.Queue <- &event.Event{Code: event.EvtCodeServerInternalError, Sid: sid,\n\t\t\tData: \"can't save file \" + filePath}\n\n\t\treturn\n\t}\n}", "func (b *BodyWriter) Flush() {}", "func handleSave(w http.ResponseWriter, r *http.Request, title string) {\n\tvar (\n\t\tbody = r.FormValue(\"body\")\n\t\tp = &page.Page{Title: title, Body: []byte(body)}\n\t)\n\tif err := p.Save(); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\thttp.Redirect(w, r, pathView+title, http.StatusFound)\n\tlogInfo(p.Title, \"file saved succesfully\")\n}", "func SaveFileByURLPath(urlPath string, resp *http.Response) resource.IResource {\n\tfileInfo := resource.ParseURL(urlPath)\n\tif fileInfo != nil {\n\t\treturn SaveFileByFileInfo(fileInfo, resp)\n\t}\n\treturn nil\n}", "func (b *BaseHandler) SavePostFile(name, to string) error {\n\tb.request.ParseForm()\n\tfile, _, err := b.GetPostFile(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tout, err := os.Create(to)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t_, err = io.Copy(out, file)\n\n\treturn err\n}", "func saveWebPage(cr *Crawler, url, extension string, content []byte) {\n\tname := strings.Replace(strings.Replace(url, \":\", \"*\", -1), \"/\", \"!\", -1)\n\tfilename := cr.destinationPath + \"/\" + name + \".\" + extension\n\texisting := cr.destinationPath + \"/\" + name\n\tif extension == \"done\" {\n\t\texisting += \".saved\"\n\t} else {\n\t\tif extension == \"saved\" {\n\t\t\texisting += \".ready\"\n\t\t}\n\t\tfile, err := os.Create(existing)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfile.Write(content)\n\t\tfile.Close()\n\t}\n\tif err := os.Rename(existing, filename); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (mc *MockClient) AddBody(Method, Url, Body string, StatusCode int, header http.Header) {\n\tmc.AddResponse(Method, Url, http.Response{\n\t\tStatusCode: StatusCode,\n\t\tHeader: header,\n\t\tBody: io.NopCloser(bytes.NewReader([]byte(Body))),\n\t})\n}", "func (p *Entry) Save() (err error) {\n\tfm, err := frontmatter.Marshal(&p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar perm os.FileMode = 0666\n\tif err = ioutil.WriteFile(p.Path, append(fm, p.Body...), perm); err != nil {\n\t\tfmt.Println(\"Dump:\")\n\t\tfmt.Println(string(fm))\n\t\tfmt.Println(string(p.Body))\n\t}\n\treturn err\n}", "func (c *Config) Save(filename string) (err error) {\n\tlog.Println(\"[DEBUG] Save\", filename)\n\n\tbody, err := json.MarshalIndent(c, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.writeFile(filename, body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Write(body *multipart.Writer, item interface{}, files []File) error {\n\t// Encode the JSON body first\n\tw, err := body.CreateFormField(\"payload_json\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create bodypart for JSON\")\n\t}\n\n\tif err := json.EncodeStream(w, item); err != nil {\n\t\treturn errors.Wrap(err, \"failed to encode JSON\")\n\t}\n\n\tfor i, file := range files {\n\t\tnum := strconv.Itoa(i)\n\n\t\tw, err := body.CreateFormFile(\"file\"+num, file.Name)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to create bodypart for \"+num)\n\t\t}\n\n\t\tif _, err := io.Copy(w, file.Reader); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to write for file \"+num)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (a *httpAxel) Download() error {\n\t// if save path exists, return conflicts\n\tif _, err := os.Stat(a.save); err == nil {\n\t\treturn fmt.Errorf(\"conflicts, save path [%s] already exists\", a.save)\n\t}\n\n\t// get the header & size\n\t// prepare for the chunk size\n\tresp, err := a.client.Get(a.remoteURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// return if not http status 200\n\tif code := resp.StatusCode; code != http.StatusOK {\n\t\treturn fmt.Errorf(\"%d - %s\", code, http.StatusText(code))\n\t}\n\n\t// detect total size & partial support\n\t// note: reset conn=1 if total size unknown\n\t// note: reset conn=1 if not supported partial download\n\ta.totalSize = resp.ContentLength\n\ta.supportPart = resp.Header.Get(\"Accept-Ranges\") != \"\"\n\tif a.totalSize <= 1 || !a.supportPart {\n\t\ta.conn = 1\n\t}\n\n\t// directly download and save\n\tif a.conn == 1 {\n\t\treturn a.directSave(resp.Body)\n\t}\n\n\t// partial downloa and save by concurrency\n\ta.chunkSize = a.totalSize / int64(a.conn)\n\ta.chunksDir = path.Join(filepath.Dir(a.save), filepath.Base(a.save)+\".chunks\")\n\tdefer os.RemoveAll(a.chunksDir)\n\n\t// concurrency get each chunks\n\terr = a.getAllChunks()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// join each pieces to the final save path\n\treturn a.join()\n}", "func downloadFile(filepath string, url string) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func downloadBinaryFromResponse(response *http.Response, output *os.File, filePath string) error {\n\tif _, err := io.Copy(output, response.Body); err != nil {\n\t\treturn fmt.Errorf(\"problem saving %s to %s: %w\", response.Request.URL, filePath, err)\n\t}\n\n\t// Download was successful, add the rw bits.\n\tif err := output.Chmod(finishedFileMode); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *HTTPResponse) ToFile(filename string) error {\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tif r.resp.Body == nil {\n\t\treturn nil\n\t}\n\tdefer r.resp.Body.Close()\n\t_, err = io.Copy(f, r.resp.Body)\n\treturn err\n}", "func downloadFile(filepath string, url string) error {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func downloadFile(filepath string, url string) error {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func (g *Generator) Save(w io.Writer) error {\n\tdata, err := json.MarshalIndent(g.spec, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = w.Write(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func saveHandler(w http.ResponseWriter, r *http.Request, title string) {\n\tbody := r.FormValue(\"body\")\n\tp := &Page{Title: title, Body: []byte(body)}\n\terr := p.save()\n\tif err != nil {\n\t\tlog.Println(\"saveHandler() error: \", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\thttp.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}", "func (s *Storage) WriteBody(hash common.Hash, body *types.Body) {\n\ts.write(BODY, hash.Bytes(), body)\n\n\t/*\n\t\tdata, err := rlp.EncodeToBytes(body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn s.set(BODY, hash.Bytes(), data)\n\t*/\n}", "func saveHandler(w http.ResponseWriter, r *http.Request, title string) {\n\tbody := r.FormValue(\"body\")\n\tp := &Page{Title: title, Body: []byte(body)}\n\terr := p.save()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\thttp.Redirect(w, r, \"/view/\"+title, http.StatusFound)\n}", "func RespBody(r *http.Response) []byte {\n\tvar mw io.Writer\n\tvar body bytes.Buffer\n\tmw = io.MultiWriter(&body)\n\tio.Copy(mw, r.Body)\n\treturn body.Bytes()\n}", "func (w *WriterInterceptor) writeBody() (int, error) {\n\tif w.closed {\n\t\treturn 0, nil\n\t}\n\n\tbuf, err := ioutil.ReadAll(w.response.Body)\n\tdefer w.Close()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn w.writer.Write(buf)\n}", "func main() {\n\t// r here is a response, and r.Body is an io.Reader.\n\tr, err := http.Get(os.Args[1])\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t// Create a file to persist the response.\n\tfile, err := os.Create(os.Args[2])\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer file.Close()\n\t//os.Stdout.Write(r.Body)\n\tvar buffer bytes.Buffer\n\tfor {\n\t\tb := make([]byte, 100)\n\t\tn, err := r.Body.Read(b)\n\t\tif n > 0 {\n\t\t\tbuffer.Write(b)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Println(buffer.String())\n\t// Use MultiWriter so we can write to stdout and\n\t// a file on the same write operation.\n\t//dest := io.MultiWriter(os.Stdout, file)\n\n\t// Read the response and write to both destinations.\n\t//io.Copy(dest, r.Body)\n\tif err := r.Body.Close(); err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (c *Controller) Save(name string, f file.Any) error {\n\tb, err := json.Marshal(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\tutil.Log(string(b))\n\n\tr := bytes.NewReader(b)\n\n\tinput := &s3.PutObjectInput{\n\t\tBody: aws.ReadSeekCloser(r),\n\t\tBucket: aws.String(c.bucket),\n\t\tKey: aws.String(name),\n\t\tServerSideEncryption: aws.String(\"AES256\"),\n\t}\n\n\tswitch f.(type) {\n\tcase file.BananasMon:\n\t\tinput.Tagging = aws.String(\"App Name=hit-the-bananas\")\n\tcase file.D2sVendorDays:\n\t\tinput.Tagging = aws.String(\"App Name=drive-2-sku\")\n\t}\n\n\tresult, err := c.c3svc.PutObject(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.verIDs[name] = result.VersionId\n\n\treturn nil\n}", "func downloadHandler(w http.ResponseWriter, r *http.Request) {\n\tsession, err := store.Get(r, sessName)\n\tif err != nil {\n\t\tw.Write([]byte(\"bad cookie\"))\n\t\treturn\n\t}\n\n\t// authenticate user\n\tif session.Values[\"logged_in\"] != \"yes\" || !isAdmin(session.Values[\"andrew\"].(string)) {\n\t\thttp.Redirect(w, r, htmlRoot+\"/\", http.StatusFound)\n\t\treturn\n\t}\n\n\t// get andrew ID from GET\n\tandrew := r.URL.Query().Get(\"user\")\n\tif andrew == \"\" {\n\t\thttp.Redirect(w, r, htmlRoot+\"/admin\", http.StatusFound)\n\t}\n\n\t// find requested file in directory (gotta search b/c ext unknown)\n\tdir, err := ioutil.ReadDir(\"submissions\")\n\trx, _ := regexp.Compile(`[^\\.]+`)\n\tfor _, stat := range dir {\n\t\tmatches := rx.FindStringSubmatch(stat.Name())\n\t\tif matches[0] == andrew {\n\t\t\t// todo: use Content-Disposition or whatever to name file\n\t\t\tfile, err := os.Open(\"submissions/\" + stat.Name())\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tbuffer := make([]byte, stat.Size())\n\t\t\t_, err = file.Read(buffer)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tw.Write(buffer)\n\t\t\treturn\n\t\t}\n\t}\n\thttp.Redirect(w, r, htmlRoot+\"/admin\", http.StatusFound)\n}", "func (handler *ObjectWebHandler) Download(w http.ResponseWriter, r *http.Request) {\n\tparams := context.Get(r, CtxParamsKey).(httprouter.Params)\n\tif !bson.IsObjectIdHex(params.ByName(\"id\")) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid object ID\", nil)\n\t\treturn\n\t}\n\n\tobjID := bson.ObjectIdHex(params.ByName(\"id\"))\n\tfs := handler.Session.DB(os.Getenv(EnvGridFSDatabase)).GridFS(os.Getenv(EnvGridFSPrefix))\n\n\tfile, err := fs.OpenId(objID)\n\tif err == mgo.ErrNotFound {\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\trespondWithError(w, http.StatusNotFound, \"Object does not exist\", err)\n\t\treturn\n\t} else if err != nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\trespondWithError(w, http.StatusInternalServerError, \"Operational error\", err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\tif file.ContentType() != \"\" {\n\t\tw.Header().Set(\"Content-Type\", file.ContentType())\n\t}\n\tif file.Name() != \"\" {\n\t\tw.Header().Set(\"Content-Disposition\", fmt.Sprintf(\"inline; filename=\\\"%v\\\"\", file.Name()))\n\t}\n\n\t_, err = io.Copy(w, file)\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, \"Operational error\", err)\n\t\treturn\n\t}\n}", "func handlerSave(w http.ResponseWriter, r *http.Request, title string) {\r\n\tbody := r.FormValue(\"body\")\r\n\tp := &Page{Title: title, Body: []byte(body)}\r\n\terr := p.save()\r\n\tif err != nil {\r\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\r\n\t\tos.Exit(1)\r\n\t}\r\n\thttp.Redirect(w, r, \"/view/\"+p.Title, http.StatusFound)\r\n}", "func downloadFile(filepath string, url string) error {\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func downloadBookHandler(res http.ResponseWriter, req *http.Request) {\n _, claims, err := jwtauth.FromContext(req.Context())\n if err != nil {\n log.Println(err)\n res.WriteHeader(500)\n return\n }\n \n // Get the book's id from the request\n idQuery := req.URL.Query().Get(\"id\")\n var id primitive.ObjectID\n if _, err := hex.Decode(id[:], []byte(idQuery)); err != nil {\n res.WriteHeader(400)\n log.Println(err)\n return\n }\n\n // Check if the user owns the book\n if !userOwnsBook(claims[\"username\"].(string), id) {\n res.WriteHeader(400)\n log.Println(\"No such book\")\n return\n }\n\n // Load the book data from the database\n stream, err := booksBucket.OpenDownloadStream(id)\n defer stream.Close()\n if err != nil {\n res.WriteHeader(500)\n log.Println(err)\n return\n }\n\n // Send the book data to the user\n if _, err := io.Copy(res, stream); err != nil {\n log.Println(err)\n return\n }\n}", "func (h *Homework) save() (err error) {\n\tbuf, err := json.MarshalIndent(h, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(h.path, buf, 0777)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Download(url string, filepath string) (err error) {\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Writer the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func writeResponseLocation(request *restful.Request, response *restful.Response, identifier string) {\n\tlocation := request.Request.URL.Path\n\tif request.Request.Method == http.MethodPost {\n\t\tlocation = location + \"/\" + identifier\n\t}\n\tresponse.AddHeader(\"Content-Location\", location)\n\tresponse.WriteHeader(201)\n}", "func downloadFile(url, output string) error {\n\tif fsutil.IsExist(output) {\n\t\tos.Remove(output)\n\t}\n\n\tfd, err := os.OpenFile(output, os.O_CREATE|os.O_WRONLY, 0644)\n\n\tif err != nil {\n\t\treturn fmtc.Errorf(\"Can't create file: %v\", err)\n\t}\n\n\tdefer fd.Close()\n\n\tresp, err := req.Request{URL: url}.Get()\n\n\tif err != nil {\n\t\treturn fmtc.Errorf(\"Can't download file: %v\", err)\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn fmtc.Errorf(\"Can't download file: server return status code %d\", resp.StatusCode)\n\t}\n\n\tw := bufio.NewWriter(fd)\n\t_, err = io.Copy(w, resp.Body)\n\n\tw.Flush()\n\n\tif err != nil {\n\t\treturn fmtc.Errorf(\"Can't write file: %v\", err)\n\t}\n\n\treturn nil\n}", "func (dr downloadResponse) Body() io.ReadCloser {\n\treturn dr.rawResponse.Body\n}", "func closeBody(r *http.Response) {\n\tif r.Body != nil {\n\t\t_, _ = io.Copy(io.Discard, r.Body)\n\t\t_ = r.Body.Close()\n\t}\n}", "func downloadFile(filepath string, url string) (err error) {\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Get the data into RAM - TODO stream straight to disk\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Check server response\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"bad status: %s\", resp.Status)\n\t}\n\n\t// write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (w *WebsiteSource) WriteToFile() error {\n\tsum := md5.Sum([]byte(w.URL + w.CSSSelect))\n\tfileName := hex.EncodeToString(sum[:]) //Try to generate a file name of fixed length\n\n\tsourceJSON, err := json.Marshal(*w)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error writing to file: %v\", err)\n\t}\n\n\tif err := os.MkdirAll(\"savedWebsites\", 0644); err != nil {\n\t\treturn fmt.Errorf(\"Error writing to file: %w\", err)\n\t}\n\n\treturn ioutil.WriteFile(\"savedWebsites/\"+fileName+\".json\", sourceJSON, 0644)\n}", "func SaveConfig(w http.ResponseWriter, r *http.Request) {\n\t//Load config-entry array from json\n\tlog.Println(\"Started answering save-request...\")\n\tlog.Println(\"Msg: \" + strconv.FormatInt(r.ContentLength, 10))\n\tjsonData, err := ioutil.ReadFile(configJsonPath)\n\tif err != nil {\n\t\tlog.Println(\"No \" + configJsonPath + \" found: \" + err.Error())\n\t}\n\tvar configEntries []Config\n\terr = json.Unmarshal(jsonData, &configEntries)\n\tif err != nil {\n\t\tlog.Println(\"Unmarshaling failed: \" + err.Error())\n\t}\n\t//Create and init config-entry\n\tvar newConfig Config\n\tmessage, err := readRequestBody(r)\n\tif err != nil {\n\t\treportError(w,400,\"Couldnt read the request-body\",\"could not read the request-body: \" + err.Error())\n\t\treturn\n\t}\n\tConfigInit(&newConfig, uint64(len(configEntries)))\n\t//Add config-entry to config array\n\tconfigEntries = append(configEntries, newConfig)\n\t//write config-entry array to json\n\tnewJson, err := json.MarshalIndent(configEntries, \"\", \" \")\n\tif err != nil {\n\t\treportError(w,500,\"Internal server error\",\"Failed marshaling the new Config-array: \" + err.Error())\n\t\treturn\n\t}\n\t//save config to fileURL\n\tioutil.WriteFile(configJsonPath, newJson, 0644)\n\t//create config file in configSavePath\n\tioutil.WriteFile(newConfig.FileUrl, []byte(message), 0644)\n\t//send back the new pwd\n\tw.Write([]byte(\"ID: \" + strconv.FormatUint(newConfig.ID, 10) + \" Password: \" + newConfig.Password))\n\tlog.Println(\"Answered save-request successfully...\")\n}", "func closeBody(f http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tf(w, r)\n\t\tr.Body.Close()\n\t}\n}", "func saveDocument(key string, c *gin.Context) *ResponseType {\n\tfilePath := dataDir + \"/\" + key\n\tfi, err := os.Stat(filePath)\n\tif err == nil && fi.Size() > 0 {\n\t\treturn newErrorResp(key, \"file exists\", fmt.Errorf(\"file already exists for key %s\", key))\n\t}\n\tf, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file creation error\", fmt.Errorf(\"error creating file for key %s: %s\", key, err.Error()))\n\t}\n\tdefer f.Close()\n\t_, err = io.Copy(f, c.Request.Body)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file write error\", fmt.Errorf(\"error copying body to file for key %s: %s\", key, err.Error()))\n\t}\n\tname := c.Request.FormValue(\"name\")\n\tcontentType := c.Request.Header.Get(\"Content-Type\")\n\textractor := c.Request.FormValue(\"extractor\")\n\ttitle := c.Request.FormValue(\"dc:title\")\n\tcreation := c.Request.FormValue(\"dcterms:created\")\n\tmodification := c.Request.FormValue(\"dcterms:modified\")\n\tmetadata := DocMetadata{\n\t\tTimestamp: time.Now().Unix(),\n\t\tName: name,\n\t\tContentType: contentType,\n\t\tExtractor: extractor,\n\t\tTitle: title,\n\t\tCreationDate: creation,\n\t\tModificationDate: modification,\n\t}\n\terr = saveMetadata(key, &metadata)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file metadata write error\", fmt.Errorf(\"error saving metadata for key %s: %s\", key, err.Error()))\n\t}\n\treturn newSuccessResp(key, \"document saved\")\n}", "func (app *service) Save(genesis Genesis) error {\n\tjs, err := app.adapter.ToJSON(genesis)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn app.fileService.Save(app.fileNameWithExt, js)\n}", "func (e EncodedFile) BodyAfterScanning(bodyByte []byte) string {\n\tencodedFile := base64.StdEncoding.EncodeToString(bodyByte)\n\te.data[\"Base64\"] = encodedFile\n\tj, _ := json.Marshal(e.data)\n\treturn string(j)\n}", "func (a *Asset) DownloadProxy(proxy Proxy) (string, error) {\n\tf, err := ioutil.TempFile(os.TempDir(), \"update-\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"creating temp file\")\n\t}\n\n\tlog.Debugf(\"fetch %q\", a.URL)\n\tres, err := http.Get(a.URL)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"fetching asset\")\n\t}\n\n\tkind := res.Header.Get(\"Content-Type\")\n\tsize, _ := strconv.Atoi(res.Header.Get(\"Content-Length\"))\n\tlog.Debugf(\"response %s – %s (%d KiB)\", res.Status, kind, size/1024)\n\n\tbody := proxy(size, res.Body)\n\n\tif res.StatusCode >= 400 {\n\t\tbody.Close()\n\t\treturn \"\", errors.Wrap(err, res.Status)\n\t}\n\n\tlog.Debugf(\"copy to %q\", f.Name())\n\tif _, err := io.Copy(f, body); err != nil {\n\t\tbody.Close()\n\t\treturn \"\", errors.Wrap(err, \"copying body\")\n\t}\n\n\tif err := body.Close(); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"closing body\")\n\t}\n\n\tif err := f.Close(); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"closing file\")\n\t}\n\n\tlog.Debugf(\"copied\")\n\treturn f.Name(), nil\n}", "func (r *Recipes) Save() error {\n\tb, err := json.Marshal(r.values)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := ioutil.WriteFile(\"recipes.json\", b, 0644); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *CreateBlueprintInWorkspaceInternalParams) SetBody(body *model.BlueprintV4Request) {\n\to.Body = body\n}", "func (s *Saver) SaveRequest() error {\n\treqName, err := nameFromReqFileName(filepath.Base(s.fname))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdst := filepath.Join(s.dir, s.reqName)\n\n\tif !fileExists(dst) {\n\t\treturn copyFile(s.fname, dst)\n\t}\n\n\tok, err := compareFiles(s.fname, dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ok {\n\t\treturn nil\n\t}\n\n\tdst = ReqFileName(reqName, s.dir)\n\ts.reqName = filepath.Base(dst)\n\n\treturn copyFile(s.fname, dst)\n}", "func (r *Reserve) Save(s *Store) error {\n\tdata, _ := json.Marshal(s)\n\tif err := ioutil.WriteFile(r.path, data, 0644); err != nil {\n\t\treturn fmt.Errorf(\"Failed to set %s: %s\", r.name, err)\n\t}\n\treturn nil\n}", "func Save(obj any, file string) error {\n\tfp, err := os.Create(file)\n\tdefer fp.Close()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tbw := bufio.NewWriter(fp)\n\terr = Write(obj, bw)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\terr = bw.Flush()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn err\n}", "func (o *DownloadFlowFileContentParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tif err := r.SetTimeout(o.timeout); err != nil {\n\t\treturn err\n\t}\n\tvar res []error\n\n\tif o.ClientID != nil {\n\n\t\t// query param clientId\n\t\tvar qrClientID string\n\n\t\tif o.ClientID != nil {\n\t\t\tqrClientID = *o.ClientID\n\t\t}\n\t\tqClientID := qrClientID\n\t\tif qClientID != \"\" {\n\n\t\t\tif err := r.SetQueryParam(\"clientId\", qClientID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif o.ClusterNodeID != nil {\n\n\t\t// query param clusterNodeId\n\t\tvar qrClusterNodeID string\n\n\t\tif o.ClusterNodeID != nil {\n\t\t\tqrClusterNodeID = *o.ClusterNodeID\n\t\t}\n\t\tqClusterNodeID := qrClusterNodeID\n\t\tif qClusterNodeID != \"\" {\n\n\t\t\tif err := r.SetQueryParam(\"clusterNodeId\", qClusterNodeID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// path param flowfile-uuid\n\tif err := r.SetPathParam(\"flowfile-uuid\", o.FlowfileUUID); err != nil {\n\t\treturn err\n\t}\n\n\t// path param id\n\tif err := r.SetPathParam(\"id\", o.ID); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (app *service) Save(state State) error {\n\tjs, err := app.adapter.ToJSON(state)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tchainHash := state.Chain()\n\tindex := state.Height()\n\tpath := filePath(chainHash, index)\n\treturn app.fileService.Save(path, js)\n}", "func (bd *blobFSDownloader) GenerateDownloadFunc(jptm IJobPartTransferMgr, srcPipeline pipeline.Pipeline, destWriter common.ChunkedFileWriter, id common.ChunkID, length int64, pacer pacer) chunkFunc {\n\treturn createDownloadChunkFunc(jptm, id, func() {\n\n\t\t// step 1: Downloading the file from range startIndex till (startIndex + adjustedChunkSize)\n\t\tinfo := jptm.Info()\n\t\tu, _ := url.Parse(info.Source)\n\t\tsrcFileURL := azbfs.NewDirectoryURL(*u, srcPipeline).NewFileUrl()\n\t\t// At this point we create an HTTP(S) request for the desired portion of the file, and\n\t\t// wait until we get the headers back... but we have not yet read its whole body.\n\t\t// The Download method encapsulates any retries that may be necessary to get to the point of receiving response headers.\n\t\tjptm.LogChunkStatus(id, common.EWaitReason.HeaderResponse())\n\t\tget, err := srcFileURL.Download(jptm.Context(), id.OffsetInFile(), length)\n\t\tif err != nil {\n\t\t\tjptm.FailActiveDownload(\"Downloading response body\", err) // cancel entire transfer because this chunk has failed\n\t\t\treturn\n\t\t}\n\n\t\t// parse the remote lmt, there shouldn't be any error, unless the service returned a new format\n\t\tremoteLastModified, err := time.Parse(time.RFC1123, get.LastModified())\n\t\tcommon.PanicIfErr(err)\n\t\tremoteLmtLocation := remoteLastModified.Location()\n\n\t\t// Verify that the file has not been changed via a client side LMT check\n\t\tif !remoteLastModified.Equal(jptm.LastModifiedTime().In(remoteLmtLocation)) {\n\t\t\tjptm.FailActiveDownload(\"BFS File modified during transfer\",\n\t\t\t\terrors.New(\"BFS File modified during transfer\"))\n\t\t}\n\n\t\t// step 2: Enqueue the response body to be written out to disk\n\t\t// The retryReader encapsulates any retries that may be necessary while downloading the body\n\t\tjptm.LogChunkStatus(id, common.EWaitReason.Body())\n\t\tretryReader := get.Body(azbfs.RetryReaderOptions{\n\t\t\tMaxRetryRequests: MaxRetryPerDownloadBody,\n\t\t\tNotifyFailedRead: common.NewV1ReadLogFunc(jptm, u),\n\t\t})\n\t\tdefer retryReader.Close()\n\t\terr = destWriter.EnqueueChunk(jptm.Context(), id, length, newPacedResponseBody(jptm.Context(), retryReader, pacer), true)\n\t\tif err != nil {\n\t\t\tjptm.FailActiveDownload(\"Enqueuing chunk\", err)\n\t\t\treturn\n\t\t}\n\t})\n}", "func Fastly_http_body_write(\n\tbody_handle BodyHandle,\n\tbuf *uintptr,\n\tbuf_len *uintptr,\n\tend BodyWriteEnd,\n\tnwritten_out *uintptr, // *mut usize\n) int32", "func (i *buildEntry) ParseBodyWrite(rbody []byte, score int) (key string, err error) {\n\tfhidLogger.Loggo.Info(\"Processing image body request\", \"Body\", string(rbody))\n\terr = json.Unmarshal(rbody, i)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tt := time.Now()\n\ttstring := t.Format(\"2006-01-02 15:04:05\")\n\tkey = getUUID()\n\ti.ImageID = key\n\ti.CreateDate = tstring\n\tsrep, err := json.MarshalIndent(i, \"\", \" \")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = Rset(key, string(srep), score)\n\treturn key, err\n}", "func (h *httpFetcher) Fetch(ctx context.Context, url string, headers map[string]string) (*os.File, error) {\n\tif h.URLGetter == nil {\n\t\th.URLGetter = httpGet\n\t}\n\n\tif h.Limiter != nil {\n\t\tif !h.Limiter.Allow() {\n\t\t\treturn nil, fmt.Errorf(\"can't download asset due to rate limit\")\n\t\t}\n\t}\n\n\tresp, err := h.URLGetter(ctx, url, h.trustedCAFile, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\t// Write response to tmp\n\ttmpFile, err := ioutil.TempFile(os.TempDir(), \"sensu-asset\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't open tmp file for asset: %s\", err)\n\t}\n\n\tcleanup := func() {\n\t\ttmpFile.Close()\n\t\t_ = os.Remove(tmpFile.Name())\n\t}\n\n\tbuffered := bufio.NewWriter(tmpFile)\n\tif _, err = io.Copy(buffered, resp); err != nil {\n\t\tcleanup()\n\t\treturn nil, fmt.Errorf(\"error downloading asset: %s\", err)\n\t}\n\tif err := buffered.Flush(); err != nil {\n\t\tcleanup()\n\t\treturn nil, fmt.Errorf(\"error downloading asset: %s\", err)\n\t}\n\n\tif err := tmpFile.Sync(); err != nil {\n\t\tcleanup()\n\t\treturn nil, err\n\t}\n\n\tif _, err := tmpFile.Seek(0, 0); err != nil {\n\t\tcleanup()\n\t\treturn nil, err\n\t}\n\n\treturn tmpFile, nil\n}", "func (gl GroceryList) Save() error {\n\tgl.mu.Lock()\n\terr := ioutil.WriteFile(\"./resources/grocery-list.txt\", gl.Body, os.ModeDevice)\n\tgl.mu.Unlock()\n\treturn err\n}", "func (w bodyCacheWriter) Write(b []byte) (int, error) {\n\n\texceptionPaths := []string{\"search\"}\n\thasException := funk.Contains(exceptionPaths, w.model.Slug)\n\thasException = funk.Contains(exceptionPaths, w.model.Code)\n\n\tcacheIgnoredPaths := []string{\"search\"}\n\tisIgnored := funk.Contains(cacheIgnoredPaths, w.model.Slug)\n\tisIgnored = funk.Contains(cacheIgnoredPaths, w.model.Code)\n\n\t// Write the response to the cache only if a success code\n\tstatus := w.Status()\n\tif 200 <= status && status <= 299 && !isIgnored {\n\t\tswitch w.store {\n\t\tcase \"redis\":\n\t\t\tgo w.redis.Set(RedisResponsePrefix, w.itemKey, string(b), RedisResponseDefaultKeyExpirationTime)\n\n\t\t\tvar setKey string\n\t\t\tsetKey = w.groupKey\n\t\t\tif w.hasRequestParams && !hasException {\n\t\t\t\tsetKey = fmt.Sprint(w.groupKey, \":with_params\")\n\t\t\t}\n\n\t\t\titemKeyIndex := w.requestURI\n\t\t\tauthRole := *w.authUserRole\n\t\t\tauthUserID := *w.authUserID\n\n\t\t\tif authRole != \"\" && authUserID != 0 {\n\t\t\t\titemKeyIndex = fmt.Sprint(w.requestURI, \":user_role:\", authRole, \":user_id:\", authUserID)\n\n\t\t\t\tif w.model.ID != \"\" || w.model.Code != \"\" || (w.model.Slug != \"\" && !hasException) {\n\t\t\t\t\tgo w.redis.SAdd(RedisResponsePrefix, fmt.Sprint(w.groupKey, \":\", w.requestURI), itemKeyIndex)\n\t\t\t\t} else {\n\t\t\t\t\tif !w.hasRequestParams {\n\t\t\t\t\t\tgo w.redis.SAdd(RedisResponsePrefix, setKey, itemKeyIndex)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tgo w.redis.SAdd(RedisResponsePrefix, setKey, w.requestURI)\n\t\t\tgo w.redis.SAdd(RedisResponsePrefix, fmt.Sprint(w.groupKey, \":all\"), w.requestURI)\n\t\t}\n\n\t}\n\n\t// Then write the response to gin\n\treturn w.ResponseWriter.Write(b)\n}" ]
[ "0.6250908", "0.5745216", "0.54999065", "0.53012586", "0.52373475", "0.5236081", "0.52156407", "0.5190274", "0.5153593", "0.5066596", "0.50165904", "0.5004325", "0.5003726", "0.49831364", "0.49391568", "0.4936893", "0.49297172", "0.4924654", "0.49175733", "0.49039724", "0.48872268", "0.48849592", "0.48724967", "0.48633686", "0.48601738", "0.48408905", "0.4835482", "0.48346964", "0.48284206", "0.48160887", "0.48074564", "0.48025808", "0.47972956", "0.4789378", "0.47720528", "0.476858", "0.4753662", "0.47345617", "0.47309682", "0.47287366", "0.47176924", "0.47112498", "0.47075444", "0.47018388", "0.4699659", "0.46922952", "0.4664548", "0.46567246", "0.46471077", "0.46374145", "0.46371257", "0.46114537", "0.46004766", "0.45830727", "0.45651945", "0.45411554", "0.45346886", "0.45198193", "0.4519364", "0.4519364", "0.45177582", "0.45168605", "0.45115536", "0.45105916", "0.45084625", "0.4502075", "0.44971228", "0.4491625", "0.44734704", "0.4472949", "0.44695708", "0.44690493", "0.44584137", "0.4450451", "0.44466907", "0.4443132", "0.44308832", "0.44156304", "0.44110703", "0.4409355", "0.44050813", "0.44028366", "0.43910962", "0.43857595", "0.43823516", "0.43795165", "0.43750075", "0.43707013", "0.4367824", "0.436467", "0.43581614", "0.43577847", "0.4343641", "0.43372628", "0.43329254", "0.43319362", "0.4327579", "0.4326056", "0.4325922", "0.4311143" ]
0.85055155
0
processBody reads the response body associated for the given Fetcher and reports any errors
func (f Fetcher) processBody() []byte { b, err := io.ReadAll(f.resp.Body) f.resp.Body.Close() if f.resp.StatusCode >= 300 { log.Fatalf("Response failed with status code: %d\n and body: %s\n", f.resp.StatusCode, b) } check(err) return b }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func decodeBody(resp *http.Response, out interface{}) (error) {\n\tswitch resp.ContentLength {\n\tcase 0:\n\t\tif out == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"Got 0 byte response with non-nil decode object\")\n\tdefault:\n\t\tdec := json.NewDecoder(resp.Body)\n\t\treturn dec.Decode(out)\n\t}\n}", "func decodeBody(resp *http.Response, out interface{}) error {\n\tswitch resp.ContentLength {\n\tcase 0:\n\t\tif out == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"Got 0 byte response with non-nil decode object\")\n\tdefault:\n\t\tdec := json.NewDecoder(resp.Body)\n\t\treturn dec.Decode(out)\n\t}\n}", "func (avisess *AviSession) fetchBody(verb, uri string, resp *http.Response) (result []byte, err error) {\n\turl := avisess.prefix + uri\n\terrorResult := AviError{HttpStatusCode: resp.StatusCode, Verb: verb, Url: url}\n\n\tif resp.StatusCode == 204 {\n\t\t// no content in the response\n\t\treturn result, nil\n\t}\n\t// It cannot be assumed that the error will always be from server side in response.\n\t// Error could be from HTTP client side which will not have body in response.\n\t// Need to change our API resp handling design if we want to handle client side errors separately.\n\n\t// Below block will take care for errors without body.\n\tif resp.Body == nil {\n\t\tglog.Errorf(\"Encountered client side error: %+v\", resp)\n\t\terrorResult.Message = &resp.Status\n\t\treturn result, errorResult\n\t}\n\n\tdefer resp.Body.Close()\n\tresult, err = ioutil.ReadAll(resp.Body)\n\tif err == nil {\n\t\tif resp.StatusCode < 200 || resp.StatusCode > 299 || resp.StatusCode == 500 {\n\t\t\tmres, merr := convertAviResponseToMapInterface(result)\n\t\t\tglog.Infof(\"Error code %v parsed resp: %v err %v\",\n\t\t\t\tresp.StatusCode, mres, merr)\n\t\t\temsg := fmt.Sprintf(\"%v\", mres)\n\t\t\terrorResult.Message = &emsg\n\t\t} else {\n\t\t\treturn result, nil\n\t\t}\n\t} else {\n\t\terrmsg := fmt.Sprintf(\"Response body read failed: %v\", err)\n\t\terrorResult.Message = &errmsg\n\t\tglog.Errorf(\"Error in reading uri %v %v\", uri, err)\n\t}\n\treturn result, errorResult\n}", "func decodeJSONBody(w http.ResponseWriter, r *http.Request, dst interface{}) *FailureResponse {\n\t// Check if Header is 'Content-Type: application/json'.\n\tif r.Header.Get(\"Content-Type\") != \"application/json\" {\n\t\treturn NewFailureResponse(http.StatusUnsupportedMediaType, \"The 'Content-Type' header is not 'application/json'!\")\n\t}\n\n\t// Parse body, and set max bytes reader (1KB).\n\t// No defaults because I believe there are no more possible errors. Please tell me if you think otherwise!\n\tr.Body = http.MaxBytesReader(w, r.Body, 1024)\n\tdecoder := json.NewDecoder(r.Body)\n\tdecoder.DisallowUnknownFields()\n\tif err := decoder.Decode(dst); err != nil {\n\t\tvar syntaxError *json.SyntaxError\n\t\tvar unmarshalTypeError *json.UnmarshalTypeError\n\n\t\tswitch {\n\t\t// Handle syntax errors.\n\t\tcase errors.As(err, &syntaxError):\n\t\t\terrorMessage := fmt.Sprintf(\"Request body contains a badly formatted JSON at position %d!\", syntaxError.Offset)\n\t\t\treturn NewFailureResponse(http.StatusBadRequest, errorMessage)\n\n\t\t// Handle unexpected EOFs.\n\t\tcase errors.Is(err, io.ErrUnexpectedEOF):\n\t\t\terrorMessage := \"Request body contains a badly-formed JSON!\"\n\t\t\treturn NewFailureResponse(http.StatusBadRequest, errorMessage)\n\n\t\t// Handle wrong data-type in request body.\n\t\tcase errors.As(err, &unmarshalTypeError):\n\t\t\terrorMessage := fmt.Sprintf(\"Request body contains an invalid value for the %q field at position %d!\", unmarshalTypeError.Field, unmarshalTypeError.Offset)\n\t\t\treturn NewFailureResponse(http.StatusBadRequest, errorMessage)\n\n\t\t// Handle unknown fields.\n\t\tcase strings.HasPrefix(err.Error(), \"json: unknown field \"):\n\t\t\tfieldName := strings.TrimPrefix(err.Error(), \"json: unknown field \")\n\t\t\terrorMessage := fmt.Sprintf(\"Request body contains unknown field '%s'!\", fieldName)\n\t\t\treturn NewFailureResponse(http.StatusBadRequest, errorMessage)\n\n\t\t// Handle empty request body.\n\t\tcase errors.Is(err, io.EOF):\n\t\t\terrorMessage := \"Request body must not be empty!\"\n\t\t\treturn NewFailureResponse(http.StatusBadRequest, errorMessage)\n\n\t\t// Handle too large body.\n\t\tcase err.Error() == \"http: request body too large\":\n\t\t\terrorMessage := \"Request body must not be larger than 1KB!\"\n\t\t\treturn NewFailureResponse(http.StatusRequestEntityTooLarge, errorMessage)\n\n\t\t}\n\t}\n\tdefer r.Body.Close()\n\n\t// Handle if client tries to send more than one JSON object.\n\tif err := decoder.Decode(&struct{}{}); err != io.EOF {\n\t\terrorMessage := \"Request body must only contain a single JSON object!\"\n\t\treturn NewFailureResponse(http.StatusBadRequest, errorMessage)\n\t}\n\n\t// Validate input.\n\tif err := validator.New().Struct(dst); err != nil {\n\t\treturn NewFailureResponse(http.StatusBadRequest, err.Error())\n\t}\n\n\t// If everything goes well, don't return anything.\n\treturn nil\n}", "func decodeBody(resp *http.Response, out interface{}) error {\n\tdec := json.NewDecoder(resp.Body)\n\treturn dec.Decode(out)\n}", "func decodeBody(resp *http.Response, out interface{}) error {\n\tdefer resp.Body.Close()\n\tdec := json.NewDecoder(resp.Body)\n\treturn dec.Decode(out)\n}", "func parseBody(r *http.Request, dest interface{}) (int, error) {\n\t// Read the body of the request.\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\n\t// Were we able to read the request?\n\tif err == nil {\n\t\t// We were able to read it, so let's see if the data was valid.\n\t\terr = json.Unmarshal(body, &dest)\n\n\t\t// Was the data valid?\n\t\tif err == nil {\n\t\t\t// Data was valid.\n\t\t\treturn http.StatusOK, nil\n\t\t} else {\n\t\t\t// Data was invalid, so let the user know.\n\t\t\treturn http.StatusBadRequest, errors.New(\"Malformed request body.\")\n\t\t}\n\t} else {\n\t\t// There was an error. Send our error as the response.\n\t\treturn http.StatusBadRequest,\n\t\t\terrors.New(\"Could not read request. Size of request might be too large.\")\n\t}\n}", "func decodeBody(resp *http.Response, out interface{}) error {\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = json.Unmarshal(body, &out); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ReadBodyJSON(output interface{}, body io.ReadCloser) ([]byte, *PzCustomError) {\n\trBytes, err := ioutil.ReadAll(body)\n\tif err != nil {\n\t\treturn nil, &PzCustomError{LogMsg: \"Could not read HTTP response.\"}\n\t}\n\terr = json.Unmarshal(rBytes, output)\n\tif err != nil {\n\t\treturn nil, &PzCustomError{LogMsg: \"Unmarshal failed: \" + err.Error() + \". Original input: \" + string(rBytes) + \".\", SimpleMsg: \"JSON error when reading HTTP Response. See log.\"}\n\t}\n\treturn rBytes, nil\n}", "func parseBody(r io.Reader, obj interface{}) {\n\tbody, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\tlog.Println(\"Error reading body\", err)\n\t}\n\n\terr = json.Unmarshal(body, obj)\n\tif err != nil {\n\t\tlog.Println(\"Error parsing body\", err)\n\t}\n}", "func readBody(response *http.Response) ([]byte, error) {\n\tdefer response.Body.Close()\n\trtn, readErr := ioutil.ReadAll(response.Body)\n\n\treturn rtn, readErr\n}", "func ReadBody(resp *http.Response) (result []byte, err error) {\n\tdefer fs.CheckClose(resp.Body, &err)\n\treturn ioutil.ReadAll(resp.Body)\n}", "func (c *ClientWithResponses) ProcessEHRMessageWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ProcessEHRMessageResponse, error) {\n\trsp, err := c.ProcessEHRMessageWithBody(ctx, contentType, body, reqEditors...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseProcessEHRMessageResponse(rsp)\n}", "func DecodeBody(ctx context.Context, req *http.Request, m interface{}) error {\n\tif err := json.NewDecoder(req.Body).Decode(m); err != nil {\n\t\treturn errors.New(http.StatusText(http.StatusBadRequest))\n\t}\n\treturn nil\n}", "func processBodyIfNecessary(req *http.Request) io.Reader {\n\tswitch req.Header.Get(\"Content-Encoding\") {\n\tdefault:\n\t\treturn req.Body\n\n\tcase \"gzip\":\n\t\treturn gunzippedBodyIfPossible(req.Body)\n\n\tcase \"deflate\", \"zlib\":\n\t\treturn zlibUncompressedbody(req.Body)\n\t}\n}", "func (m *BaseMethod) ResponseProcess(body io.ReadCloser, h http.Header, s StatusCode, retries uint) (*Response, error) {\n\tb, err := ioutil.ReadAll(body)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(ReadBodyError)\n\t\treturn nil, ReadBodyError\n\t}\n\terr = body.Close()\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(CloseBodyError)\n\t\treturn nil, CloseBodyError\n\t}\n\tvar headers []KVPair\n\tfor k, vs := range h {\n\t\tfor _, v := range vs {\n\t\t\theaders = append(headers, KVPair{k, v})\n\t\t}\n\t}\n\treturn &Response{Bytes: b, StatusCode: s, Headers: headers, CountRetry: retries}, nil\n}", "func decodeJSONBody(w http.ResponseWriter, r *http.Request, dst interface{}) error {\n\tif r.Header.Get(\"Content-Type\") != \"\" {\n\t\tvalue, _ := header.ParseValueAndParams(r.Header, \"Content-Type\")\n\t\tif value != \"application/json\" {\n\t\t\tmsg := \"Content-Type header is not application/json\"\n\t\t\treturn &malformedRequest{status: http.StatusUnsupportedMediaType, msg: msg}\n\t\t}\n\t}\n\n\tr.Body = http.MaxBytesReader(w, r.Body, 1048576)\n\n\tdec := json.NewDecoder(r.Body)\n\tdec.DisallowUnknownFields()\n\n\terr := dec.Decode(&dst)\n\tif err != nil {\n\t\tvar syntaxError *json.SyntaxError\n\t\tvar unmarshalTypeError *json.UnmarshalTypeError\n\n\t\tswitch {\n\t\tcase errors.As(err, &syntaxError):\n\t\t\tmsg := fmt.Sprintf(\"Request body contains badly-formed JSON (at position %d)\", syntaxError.Offset)\n\t\t\treturn &malformedRequest{status: http.StatusBadRequest, msg: msg}\n\n\t\tcase errors.Is(err, io.ErrUnexpectedEOF):\n\t\t\tmsg := fmt.Sprintf(\"Request body contains badly-formed JSON\")\n\t\t\treturn &malformedRequest{status: http.StatusBadRequest, msg: msg}\n\n\t\tcase errors.As(err, &unmarshalTypeError):\n\t\t\tmsg := fmt.Sprintf(\"Request body contains an invalid value for the %q field (at position %d)\", unmarshalTypeError.Field, unmarshalTypeError.Offset)\n\t\t\treturn &malformedRequest{status: http.StatusBadRequest, msg: msg}\n\n\t\tcase strings.HasPrefix(err.Error(), \"json: unknown field \"):\n\t\t\tfieldName := strings.TrimPrefix(err.Error(), \"json: unknown field \")\n\t\t\tmsg := fmt.Sprintf(\"Request body contains unknown field %s\", fieldName)\n\t\t\treturn &malformedRequest{status: http.StatusBadRequest, msg: msg}\n\n\t\tcase errors.Is(err, io.EOF):\n\t\t\tmsg := \"Request body must not be empty\"\n\t\t\treturn &malformedRequest{status: http.StatusBadRequest, msg: msg}\n\n\t\tcase err.Error() == \"http: request body too large\":\n\t\t\tmsg := \"Request body must not be larger than 1MB\"\n\t\t\treturn &malformedRequest{status: http.StatusRequestEntityTooLarge, msg: msg}\n\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif dec.More() {\n\t\tmsg := \"Request body must only contain a single JSON object\"\n\t\treturn &malformedRequest{status: http.StatusBadRequest, msg: msg}\n\t}\n\n\treturn nil\n}", "func decodeJsonBody(target interface{}, r *http.Request) error {\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := r.Body.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := json.Unmarshal(body, target); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) drainBody(body io.ReadCloser) {\n\tdefer body.Close()\n\n\t_, err := io.Copy(ioutil.Discard, io.LimitReader(body, 10))\n\tif err != nil {\n\t\tfmt.Println(\"Error reading response body: %v\", err)\n\t}\n}", "func ParseJsonBody(r io.ReadCloser, data interface{}) porterr.IError {\n\tif r == http.NoBody {\n\t\treturn nil\n\t}\n\tbody, err := io.ReadAll(r)\n\tif err != nil {\n\t\treturn porterr.New(porterr.PortErrorIO, \"I/O error. Request body error: \"+err.Error()).HTTP(http.StatusBadRequest)\n\t}\n\tdefer func() {\n\t\terr := r.Close()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\terr = json.Unmarshal(body, data)\n\tif err != nil {\n\t\treturn porterr.New(porterr.PortErrorDecoder, \"Unmarshal error: \"+err.Error()).HTTP(http.StatusBadRequest)\n\t}\n\treturn nil\n}", "func (c *Client) readBody(resp *http.Response) ([]byte, error) {\n\tvar reader io.Reader = resp.Body\n\tswitch resp.Header.Get(\"Content-Encoding\") {\n\tcase \"\":\n\t\t// Do nothing\n\tcase \"gzip\":\n\t\treader = gzipDecompress(resp.Body)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"bug: comm.Client.JSONCall(): content was send with unsupported content-encoding %s\", resp.Header.Get(\"Content-Encoding\"))\n\t}\n\treturn io.ReadAll(reader)\n}", "func (b *Bulb) responseProcessor() {\n\tvar buff = make([]byte, 512)\n\tvar resp map[string]interface{}\n\n\tfor {\n\t\tn, err := b.conn.Read(buff)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tresponses := bytes.Split(buff[:n], []byte{CR, LF})\n\n\t\tfor _, r := range responses[:len(responses)-1] {\n\t\t\tresp = make(map[string]interface{})\n\n\t\t\terr = json.Unmarshal(r, &resp)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"OKResponse err: %s\\n\", r)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase keysExists(resp, \"id\", \"result\"): // Command success\n\t\t\t\tvar unmarshaled OKResponse\n\t\t\t\terr = json.Unmarshal(r, &unmarshaled)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"second unmarshal error: %s\\n\", r)\n\t\t\t\t}\n\t\t\t\tb.results[unmarshaled.id()] <- &unmarshaled\n\t\t\tcase keysExists(resp, \"id\", \"error\"): // Command failed\n\t\t\t\tvar unmarshaled ERRResponse\n\t\t\t\terr = json.Unmarshal(r, &unmarshaled)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"second unmarshal error: %s\\n\", r)\n\t\t\t\t}\n\t\t\t\tb.results[unmarshaled.id()] <- &unmarshaled\n\t\t\tcase keysExists(resp, \"method\", \"params\"): // Notification\n\t\t\t\t// log.Printf(\"state change%s\\n\", r)\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"unhandled response: %s\\n\", r)\n\t\t\t}\n\t\t}\n\t}\n\tlog.Printf(\"response processor exited\\n\")\n}", "func ReadBody(req *http.Request, p interface{}) error {\n\tbody, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"read body error %v\", err)\n\t}\n\n\terr = json.Unmarshal(body, &p)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing body error %v\", err)\n\t}\n\n\treturn nil\n}", "func readBody(r *http.Request, v interface{}) error {\n\tbody, err := ioutil.ReadAll(r.Body)\n\t_ = r.Body.Close()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"body read: %w\", err)\n\t}\n\n\terr = json.Unmarshal(body, v)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"json decode: %w\", err)\n\t}\n\n\treturn nil\n}", "func Body(resp *http.Response) (string, error) {\n\tdefer resp.Body.Close()\n\tb, e := ioutil.ReadAll(resp.Body)\n\treturn string(b), e\n}", "func (response *S3Response) UnmarshalBody(obj interface{}) error {\n defer response.Close()\n unmarshaller := xml.NewDecoder(response.httpResponse.Body)\n return unmarshaller.Decode(obj)\n}", "func (e *HTTPError) ResponseBody() interface{} {\n\treturn ErrRespopnse{\n\t\tCode: -1,\n\t\tMessage: e.Detail,\n\t}\n}", "func processResponse(resp mesos.Response, t agent.Response_Type) (agent.Response, error) {\n\tvar r agent.Response\n\tdefer func() {\n\t\tif resp != nil {\n\t\t\tresp.Close()\n\t\t}\n\t}()\n\tfor {\n\t\tif err := resp.Decode(&r); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn r, err\n\t\t}\n\t}\n\tif r.GetType() == t {\n\t\treturn r, nil\n\t} else {\n\t\treturn r, fmt.Errorf(\"processResponse expected type %q, got %q\", t, r.GetType())\n\t}\n}", "func decodeJSONBody(r *http.Request, dst interface{}) error {\n\tif r.Header.Get(\"Content-Type\") != \"\" {\n\t\tvalue, _ := header.ParseValueAndParams(r.Header, \"Content-Type\")\n\t\tif value != \"application/json\" {\n\t\t\treturn ContentHeaderError\n\t\t}\n\t}\n\n\tdec := json.NewDecoder(r.Body)\n\tdec.DisallowUnknownFields()\n\n\terr := dec.Decode(&dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dec.More() {\n\t\tmsg := \"Request body must only contain a single JSON object\"\n\t\treturn errors.New(msg)\n\t}\n\n\treturn nil\n}", "func safelyReadBody(r *http.Response) (io.ReadCloser, error) {\n\tbuf, _ := ioutil.ReadAll(r.Body)\n\trdr := ioutil.NopCloser(bytes.NewBuffer(buf))\n\trdr2 := ioutil.NopCloser(bytes.NewBuffer(buf))\n\n\tr.Body = rdr2\n\treturn rdr, nil\n}", "func DecodeResponseBody(body io.Reader, dest interface{}) error {\n\tdecoder := json.NewDecoder(body)\n\terr := decoder.Decode(dest)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to decode response body: %s\", err.Error())\n\t}\n\n\treturn nil\n}", "func ParseProcessEHRMessageResponse(rsp *http.Response) (*ProcessEHRMessageResponse, error) {\n\tbodyBytes, err := io.ReadAll(rsp.Body)\n\tdefer func() { _ = rsp.Body.Close() }()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &ProcessEHRMessageResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\treturn response, nil\n}", "func (f Fetcher) SaveBody() {\n\tfile, err := os.Create(f.url)\n\tcheck(err)\n\tdefer file.Close()\n\n\tb := f.processBody()\n\t_, err = file.Write(b)\n\tcheck(err)\n}", "func (c *Client) consumeResponseBody(r *http.Response) {\n\tif r != nil && r.Body != nil {\n\t\tio.Copy(ioutil.Discard, r.Body)\n\t}\n}", "func readBodyContent(r *ResponseReader, res *Response) (string, error) {\n\t// 1. Any response to a HEAD request and any response with a 1xx\n\t// (Informational), 204 (No Content), or 304 (Not Modified) status\n\t// code always has empty body\n\tif (res.StatusCode/100 == 1) || (res.StatusCode == 204) || (res.StatusCode == 304) ||\n\t\t(res.Request != nil && res.Request.Method == \"HEAD\") {\n\t\tres.Body = \"\"\n\t\treturn \"\", nil\n\t}\n\n\tcontentLen := res.GetContentLength()\n\ttransferEnc := res.GetTransferEncoding()\n\t// fmt.Printf(\"Len: %v, Encoding: %v\", contentLen, transferEnc)\n\n\tbody := \"\"\n\tvar err error\n\tif transferEnc == \"chunked\" || contentLen == -1 {\n\t\tbody, err = readChunkedBodyContent(r, res)\n\t} else {\n\t\tbody, err = readLimitedBodyContent(r, res, contentLen)\n\t}\n\n\tres.Body = body\n\tres.AppendRaw(body, false)\n\treturn body, err\n}", "func CheckResponse(body *[]byte) (err error) {\n\n\tpre := new(PxgRetError)\n\n\tdecErr := json.Unmarshal(*body, &pre)\n\n\tif decErr == io.EOF {\n\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t}\n\tif decErr != nil {\n\t\terr = decErr\n\t}\n\n\tif pre.Error != nil {\n\t\terr = pre.Error\n\t}\n\n\treturn err\n}", "func body(resp *http.Response) ([]byte, error) {\n\tvar buf bytes.Buffer\n\t_, err := buf.ReadFrom(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func ValidateFounderResponseBody(body *FounderResponseBody) (err error) {\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\treturn\n}", "func ParseJSONBody(body io.Reader) (map[string]interface{}, error) {\n\tif body == nil {\n\t\treturn nil, nil\n\t}\n\n\tdecoder := json.NewDecoder(body)\n\n\tparsed := make(map[string]interface{})\n\n\tif err := decoder.Decode(&parsed); err == io.EOF {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn parsed, nil\n}", "func (res *ClientHTTPResponse) ReadAndUnmarshalBody(v interface{}) error {\n\trawBody, err := res.ReadAll()\n\tif err != nil {\n\t\t/* coverage ignore next line */\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(rawBody, v)\n\tif err != nil {\n\t\tres.req.Logger.Warn(\"Could not parse client json\",\n\t\t\tzap.String(\"error\", err.Error()),\n\t\t)\n\t\treturn errors.Wrapf(\n\t\t\terr,\n\t\t\t\"Could not parse client %q json\",\n\t\t\tres.req.ClientID,\n\t\t)\n\t}\n\n\treturn nil\n}", "func errorHandler(resp *http.Response) error {\n\tbody, err := rest.ReadBody(resp)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error when trying to read error from body: %w\", err)\n\t}\n\t// Decode error response\n\terrResponse := new(api.Error)\n\terr = xml.Unmarshal(body, &errResponse)\n\tif err != nil {\n\t\t// set the Message to be the body if can't parse the XML\n\t\terrResponse.Message = strings.TrimSpace(string(body))\n\t}\n\terrResponse.Status = resp.Status\n\terrResponse.StatusCode = resp.StatusCode\n\treturn errResponse\n}", "func ProcessWitResponse(message io.ReadCloser) WitMessage {\n\tintent, _ := ioutil.ReadAll(message)\n\n\tjsonString := string(intent[:])\n\t_ = jsonString\n\n\tvar jsonResponse WitMessage\n\terr := json.Unmarshal(intent, &jsonResponse)\n\tif err != nil {\n\t\tlog.Println(\"error parsing json: \", err)\n\t\tlog.Printf(\"plain text json was %+v\", jsonString)\n\t}\n\n\tvar numbers []WitNumber\n\tvar number WitNumber\n\n\terr = json.Unmarshal(jsonResponse.Outcome.Entities.RawGithub, &numbers)\n\tif err != nil {\n\t\t//log.Println(\"1 error parsing number json: \", err)\n\t\t//log.Println(\"string number object is: \", string(jsonResponse.Outcome.Entities.RawGithub))\n\t\terr = json.Unmarshal(jsonResponse.Outcome.Entities.RawGithub, &number)\n\t\tif err != nil {\n\t\t\t//log.Println(\"2 error parsing number json: \", err)\n\t\t} else {\n\t\t\tjsonResponse.Outcome.Entities.MultipleNumber = []WitNumber{number}\n\t\t}\n\n\t} else {\n\t\tjsonResponse.Outcome.Entities.MultipleNumber = numbers\n\t}\n\n\t//log.Printf(\"a: %+v\\n\\n\\n\", jsonResponse)\n\t//log.Printf(\"b: %+v\\n\\n\\n\", jsonString)\n\n\treturn jsonResponse\n\n}", "func closeBody(resp *http.Response) {\n\terr := resp.Body.Close()\n\tif err != nil {\n\t\tutil.Logger.Printf(\"error closing response body - Called by %s: %s\\n\", util.CallFuncName(), err)\n\t}\n}", "func closeBody(r *http.Response) {\n\tif r.Body != nil {\n\t\t_, _ = io.Copy(io.Discard, r.Body)\n\t\t_ = r.Body.Close()\n\t}\n}", "func decodeResponse(resp *http.Response, respJson interface{}) error {\n\tswitch resp.StatusCode {\n\tcase http.StatusOK, http.StatusCreated:\n\t\treturn json.NewDecoder(resp.Body).Decode(respJson)\n\tcase http.StatusUnauthorized, http.StatusNotFound:\n\t\treturn fmt.Errorf(\"HTTP status: %s\", http.StatusText(resp.StatusCode))\n\tcase 422: // Unprocessable Entity\n\t\tvar v map[string][]string\n\t\tif err := json.NewDecoder(resp.Body).Decode(&v); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, messages := range v {\n\t\t\tfor _, msg := range messages {\n\t\t\t\t// Only return the very first error message\n\t\t\t\treturn errors.New(msg)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\treturn fmt.Errorf(\"invalid HTTP body\")\n\tdefault:\n\t\treturn fmt.Errorf(\"unexpected HTTP status: %d\", resp.StatusCode)\n\t}\n}", "func processApigeeJSON(apigeeResp []byte) apigeeJSONstr {\n\tlog.Debug(\"In processsApigeeJSON\")\n\tvar apigeeJSON apigeeJSONstr\n\tif err := json.Unmarshal(apigeeResp, &apigeeJSON); err != nil {\n\t\tpanic(fmt.Errorf(\"fatal error processing Apigee JSON: %s\", err))\n\t}\n\treturn apigeeJSON\n}", "func readBody(t *testing.T, r io.ReadCloser) *bytes.Buffer {\n\tdefer r.Close()\n\n\tvar b []byte\n\tbuf := bytes.NewBuffer(b)\n\t_, err := buf.ReadFrom(r)\n\tcheck(t, err)\n\n\treturn buf\n}", "func BodyParser(r *http.Request) []byte {\n\tbody, _ := ioutil.ReadAll(r.Body)\n\treturn body\n}", "func (ctx *serverRequestContextImpl) TryReadBody(body interface{}) (bool, error) {\n\tbuf, err := ctx.ReadBodyBytes()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tempty := len(buf) == 0\n\tif !empty {\n\t\terr = json.Unmarshal(buf, body)\n\t\tif err != nil {\n\t\t\treturn true, caerrors.NewHTTPErr(400, caerrors.ErrBadReqBody, \"Invalid request body: %s; body=%s\",\n\t\t\t\terr, string(buf))\n\t\t}\n\t}\n\treturn empty, nil\n}", "func (s *Nap) Body(body io.Reader) *Nap {\n\tif body == nil {\n\t\treturn s\n\t}\n\treturn s.BodyProvider(bodyProvider{body: body})\n}", "func (job *JOB) Process(ctx context.Context, rsp *http.Response) error {\n\tif rsp.StatusCode != http.StatusOK {\n\t\treturn errors.New(rsp.Status)\n\t}\n\tdefer rsp.Body.Close()\n\n\tvar result Result\n\tif err := json.NewDecoder(rsp.Body).Decode(&result); err != nil {\n\t\treturn errors.Annotate(err, \"json decode\")\n\t}\n\tlog.Println(\"Parks count:\", len(result.Items[0].Parks))\n\tfor _, item := range result.Items {\n\t\tfor _, park := range item.Parks {\n\t\t\tif err := job.updateParkStatus(ctx, park); err != nil {\n\t\t\t\tlog.Println(\"WARN: park status refresh failed: \", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (d *data) parseResponse(ctx context.Context, bodyReader io.ReadCloser, cond *conditions) error {\n\tpp := d.Points\n\tdataSplit := dataSplitUnaggregated\n\tif cond.aggregated {\n\t\tdataSplit = dataSplitAggregated\n\t}\n\n\t// Prevent starting parser if context is done\n\tif err := contextIsValid(ctx); err != nil {\n\t\treturn ctx.Err()\n\t}\n\n\t// Then wait if there is an active parser working\n\tselect {\n\tcase d.b <- bodyReader:\n\tcase <-ctx.Done():\n\t\treturn fmt.Errorf(\"parseResponse failed: %w\", ctx.Err())\n\t}\n\n\tvar metricID uint32\n\td.mut.Lock()\n\tdefer func() {\n\t\td.mut.Unlock()\n\t\t<-d.b\n\t}()\n\n\t// Are we still good to go?\n\tif err := contextIsValid(ctx); err != nil {\n\t\treturn fmt.Errorf(\"parseResponse failed: %w\", ctx.Err())\n\t}\n\n\tstart := time.Now()\n\tscanner := bufio.NewScanner(bodyReader)\n\tscanner.Buffer(make([]byte, 1048576), 67108864)\n\tscanner.Split(dataSplit)\n\n\tvar rowStart []byte\n\tfor scanner.Scan() {\n\t\trowStart = scanner.Bytes()\n\n\t\td.length += len(rowStart)\n\n\t\tnameLen, readBytes, err := ReadUvarint(rowStart)\n\t\tif err != nil {\n\t\t\treturn errClickHouseResponse\n\t\t}\n\n\t\trow := rowStart[int(readBytes):]\n\n\t\tname := row[:int(nameLen)]\n\t\trow = row[int(nameLen):]\n\n\t\tif cond.isReverse {\n\t\t\tmetricID = pp.MetricIDBytes(reverse.Bytes(name))\n\t\t} else {\n\t\t\tmetricID = pp.MetricIDBytes(name)\n\t\t}\n\n\t\tarrayLen, readBytes, err := ReadUvarint(row)\n\t\tif err != nil {\n\t\t\treturn errClickHouseResponse\n\t\t}\n\n\t\ttimes := make([]uint32, 0, arrayLen)\n\t\tvalues := make([]float64, 0, arrayLen)\n\n\t\trow = row[int(readBytes):]\n\t\tfor i := uint64(0); i < arrayLen; i++ {\n\t\t\ttimes = append(times, binary.LittleEndian.Uint32(row[:4]))\n\t\t\trow = row[4:]\n\t\t}\n\n\t\trow = row[int(readBytes):]\n\t\tfor i := uint64(0); i < arrayLen; i++ {\n\t\t\tvalues = append(values, math.Float64frombits(binary.LittleEndian.Uint64(row[:8])))\n\t\t\trow = row[8:]\n\t\t}\n\n\t\ttimestamps := times\n\t\tif !cond.aggregated {\n\t\t\ttimestamps = make([]uint32, 0, arrayLen)\n\t\t\trow = row[int(readBytes):]\n\t\t\tfor i := uint64(0); i < arrayLen; i++ {\n\t\t\t\ttimestamps = append(timestamps, binary.LittleEndian.Uint32(row[:4]))\n\t\t\t\trow = row[4:]\n\t\t\t}\n\t\t}\n\n\t\tfor i := range times {\n\t\t\tpp.AppendPoint(metricID, values[i], times[i], timestamps[i])\n\t\t}\n\t}\n\td.spent += time.Since(start)\n\n\terr := scanner.Err()\n\tif err != nil {\n\t\tdataErr, ok := err.(*clickhouse.ErrWithDescr)\n\t\tif ok {\n\t\t\t// format full error string, sometimes parse not failed at start orf error string\n\t\t\tdataErr.PrependDescription(string(rowStart))\n\t\t}\n\t\tbodyReader.Close()\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func responseDecodeJSON(bodyResponse io.Reader, response interface{}) error {\n\tvar body, errBody = ioutil.ReadAll(bodyResponse)\n\tif errBody != nil {\n\t\treturn errBody\n\t}\n\n\terrJSON := json.Unmarshal(body, response)\n\tif errJSON != nil {\n\t\treturn errJSON\n\t}\n\n\treturn nil\n}", "func Process(response string, lc logger.LoggingClient) map[string]interface{} {\n\trsp := make(map[string]interface{})\n\terr := json.Unmarshal([]byte(response), &rsp)\n\tif err != nil {\n\t\tlc.Error(\"error unmarshalling response from JSON: %v\", err.Error())\n\t}\n\treturn rsp\n}", "func decodeBody(resp *http.Response, out interface{}) error {\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//fmt.Println(\"response Body:\", string(body))\n\n\t// Unmarshal the XML.\n\tif err = xml.Unmarshal(body, &out); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func decodeBadRequest(r *http.Response) (err error) {\n\n\ttype badRequestResponse struct {\n\t\tErrors []string `json:\"errors\"`\n\t}\n\n\tif !strings.Contains(r.Header.Get(\"Content-Type\"), \"application/json\") {\n\t\treturn NewBadRequestError(\"bad request\")\n\t}\n\tvar e badRequestResponse\n\tif err = json.NewDecoder(r.Body).Decode(&e); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn NewBadRequestError(\"bad request\")\n\t\t}\n\t\treturn err\n\t}\n\treturn NewBadRequestError(e.Errors...)\n}", "func redactBody(ruleMatch HTTPMatch, r *http.Request) error {\n\tif r.Body == nil {\n\t\treturn nil\n\t}\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tredactedBody := []byte{}\n\tcontentType := getContentType(r)\n\n\tif contentType != \"\" {\n\t\tredactedBody, err = mapBody(ruleMatch, contentType, body)\n\t}\n\n\tcontentLength := len(redactedBody)\n\n\tr.Body = ioutil.NopCloser(bytes.NewReader(redactedBody))\n\tr.Header.Set(\"Content-Length\", strconv.Itoa(contentLength))\n\tr.ContentLength = int64(contentLength)\n\n\treturn err\n}", "func (s *Server) process(ctx context.Context, message json.RawMessage) interface{} {\n\trequests := []Request{}\n\t// parsing batch requests\n\tbatch := IsArray(message)\n\n\t// making not batch request looks like batch to simplify further code\n\tif !batch {\n\t\tmessage = append(append([]byte{'['}, message...), ']')\n\t}\n\n\t// unmarshal request(s)\n\tif err := json.Unmarshal(message, &requests); err != nil {\n\t\treturn NewResponseError(nil, ParseError, \"\", nil)\n\t}\n\n\t// if there no requests to process\n\tif len(requests) == 0 {\n\t\treturn NewResponseError(nil, InvalidRequest, \"\", nil)\n\t} else if len(requests) > s.options.BatchMaxLen {\n\t\treturn NewResponseError(nil, InvalidRequest, \"\", \"max requests length in batch exceeded\")\n\t}\n\n\t// process single request: if request single and not notification - just run it and return result\n\tif !batch && requests[0].ID != nil {\n\t\treturn s.processRequest(ctx, requests[0])\n\t}\n\n\t// process batch requests\n\tif res := s.processBatch(ctx, requests); len(res) > 0 {\n\t\treturn res\n\t}\n\n\treturn nil\n}", "func (s *BasecluListener) ExitBody(ctx *BodyContext) {}", "func (o *EmailUpdatePostReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewEmailUpdatePostNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tresult := NewEmailUpdatePostDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func TestGetDataFromUrlBodyReadError(t *testing.T) {\n\tdefer gock.Off()\n\n\tapiUrl := \"http://example.com\"\n\tapiPath := \"status\"\n\n\tgock.New(apiUrl).\n\t\tGet(apiPath).\n\t\tReply(200).\n\t\tBodyString(\"\")\n\n\t_, err := getDataFromURL(apiUrl+\"/\"+apiPath, func(r io.Reader) ([]byte, error) {\n\t\treturn nil, errors.New(\"IO Reader error occurred\")\n\t})\n\n\tassert.Error(t, err)\n}", "func ReadJSONBody(writer http.ResponseWriter, request *http.Request, obj interface{}) error {\n\tb, err := ioutil.ReadAll(request.Body)\n\tif err != nil {\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn err\n\t}\n\terr = json.Unmarshal(b, obj)\n\tif err != nil {\n\t\thttp.Error(writer, err.Error(), http.StatusBadRequest)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *PostSlashingValidatorsValidatorAddrUnjailReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPostSlashingValidatorsValidatorAddrUnjailOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPostSlashingValidatorsValidatorAddrUnjailBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewPostSlashingValidatorsValidatorAddrUnjailInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func getBody(resp *http.Response) ([]byte, error) {\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn body, err\n}", "func readDiscardBody(req *http.Request, resp *http.Response) int64 {\n\tif req.Method == http.MethodHead {\n\t\treturn 0\n\t}\n\n\tw := ioutil.Discard\n\tbytes, err := io.Copy(w, resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"reading HTTP response body: %v\", err)\n\t}\n\treturn bytes\n}", "func processAsyncResponse(client *GroupMgmtClient, body []byte) (interface{}, error) {\n\terrResp, _ := unwrapError(body)\n\tif client.WaitOnJob { // check sync flag\n\t\tunwrapMessage := &ErrorResponse{}\n\t\terr := json.Unmarshal(body, unwrapMessage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar jobId string\n\t\tfor _, msg := range unwrapMessage.Messages {\n\t\t\tif msg.Code == smAsyncJobId {\n\t\t\t\tjobId = msg.Arguments.JobId\n\t\t\t}\n\t\t}\n\t\tif len(jobId) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"http response error: status (202), but no job ID returned, messages: %v\", errResp)\n\t\t}\n\n\t\tid, err := waitForJobResult(jobId, client)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"http response error: status (202), messages: %v\", err.Error())\n\t\t}\n\t\treturn id, nil\n\t}\n\treturn nil, fmt.Errorf(\"http response error: status (202), messages: %v\", errResp)\n}", "func getBody(resp *http.Response) ([]byte, error) {\n\tbody, err := ioutil.ReadAll(resp.Body)\n\treturn body, err\n}", "func (dr downloadResponse) Body() io.ReadCloser {\n\treturn dr.rawResponse.Body\n}", "func process(response []byte, err error) (Response, error) {\n\tvar (\n\t\tjsonR encode.JResult\n\t\tresult Response\n\t\tstatus int\n\t)\n\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tvar objmap map[string]*json.RawMessage\n\terr = json.Unmarshal(response, &objmap)\n\n\terr = json.Unmarshal(*objmap[\"statusCode\"], &status)\n\n\tif status != 200 {\n\t\tvar r Response\n\t\t_ = json.Unmarshal(*objmap[\"statusCode\"], &r.StatusCode)\n\t\t_ = json.Unmarshal(*objmap[\"statusText\"], &r.StatusText)\n\t\treturn r, err\n\t}\n\n\terr = json.Unmarshal(response, &jsonR)\n\tif err != nil {\n\t\treturn Response{}, err\n\t}\n\n\t//Lots of work to convert {\"0\":{},\"1\":{}} to [{},{}]\n\tresult.StatusCode = jsonR.StatusCode\n\tresult.StatusText = jsonR.StatusText\n\tresult.Data.TestId = jsonR.Data.TestId\n\tresult.Data.Summary = jsonR.Data.Summary\n\tresult.Data.Label = jsonR.Data.Label\n\tresult.Data.Url = jsonR.Data.Url\n\tresult.Data.Location = jsonR.Data.Location\n\tresult.Data.Connectivity = jsonR.Data.Connectivity\n\tresult.Data.From = jsonR.Data.From\n\tresult.Data.BwDown = jsonR.Data.BwDown\n\tresult.Data.BwUp = jsonR.Data.BwUp\n\tresult.Data.Latency = jsonR.Data.Latency\n\n\t//iOS app sends int, but browsers send string\n\tswitch v := jsonR.Data.Plr.(type) {\n\tcase string:\n\t\tinf, _ := strconv.ParseInt(v, 10, 32)\n\t\tresult.Data.Plr = int32(inf)\n\tcase int64:\n\t\tresult.Data.Plr = int32(v)\n\tcase float64:\n\t\tresult.Data.Plr = int32(v)\n\tcase nil:\n\t\tresult.Data.Plr = 1\n\tdefault:\n\t\tlog.Printf(\"Failed to convert: %v\", v)\n\t}\n\tresult.Data.Completed = jsonR.Data.Completed\n\tresult.Data.SuccessfulFVRuns = jsonR.Data.SuccessfulFVRuns\n\n\tr, _ := regexp.Compile(\"^userTime.(.*)\")\n\tfor i, val := range jsonR.Data.Runs {\n\t\t_ = i\n\n\t\tval.FirstView.UserTiming = make(map[string]int)\n\n\t\tfor key, extra := range val.FirstView.Extra {\n\t\t\tif r.MatchString(key) && extra != nil {\n\t\t\t\tmetric := r.FindStringSubmatch(key)[1]\n\t\t\t\tval.FirstView.UserTiming[metric] = int(extra.(float64))\n\t\t\t}\n\t\t}\n\t\tresult.Data.Runs = append(result.Data.Runs, val)\n\t}\n\n\treturn result, err\n}", "func ParseBody(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Header.Get(\"Content-Type\") == \"application/json\" {\n\t\t\tvar jf jsonform\n\t\t\tif err := json.NewDecoder(r.Body).Decode(&jf); err != nil {\n\t\t\t\tpanic(srverror.New(err, 400, \"Unable to decode json object\"))\n\t\t\t}\n\t\t\tr.PostForm = jf.Values()\n\t\t\tif err := r.ParseForm(); err != nil {\n\t\t\t\tpanic(srverror.New(err, 400, \"Unable to parse form values\"))\n\t\t\t}\n\t\t} else if r.Header.Get(\"Content-Type\") == \"multipart/form-data\" {\n\t\t\tif err := r.ParseMultipartForm(32 << 20); err != nil {\n\t\t\t\tpanic(srverror.New(err, 400, \"Unable to parse multipart form values\"))\n\t\t\t}\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (s *TeString) processResponse(data string, body string) int8 {\n\n\tregexMatch := regexTeStringMatch.FindAllStringSubmatch(string(body), -1)\n\tif regexMatch == nil {\n\t\tlog.Printf(\"No regex match in TE string report\")\n\t\treturn WORK_RESPONSE_ERROR\n\t}\n\n\treturn s.setRecord(data, int(util.ConvertStringToInt32(regexMatch[0][1])))\n}", "func readBody(win *acme.Win) ([]byte, error) {\n\tvar body []byte\n\tbuf := make([]byte, 8000)\n\tfor {\n\t\tn, err := win.Read(\"body\", buf)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbody = append(body, buf[0:n]...)\n\t}\n\treturn body, nil\n}", "func (o *ActOnPipelineUsingPOSTReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewActOnPipelineUsingPOSTOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewActOnPipelineUsingPOSTUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewActOnPipelineUsingPOSTForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewActOnPipelineUsingPOSTNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewActOnPipelineUsingPOSTInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (req *ServerHTTPRequest) UnmarshalBody(\n\tbody interface{}, rawBody []byte,\n) bool {\n\terr := req.jsonWrapper.Unmarshal(rawBody, body)\n\tif err != nil {\n\t\treq.contextLogger.WarnZ(req.Context(), \"Could not parse json\", zap.Error(err))\n\t\tif !req.parseFailed {\n\t\t\treq.res.SendError(400, \"Could not parse json: \"+err.Error(), err)\n\t\t\treq.parseFailed = true\n\t\t}\n\t\treturn false\n\t}\n\n\treturn true\n}", "func ProcessResponseError(_ context.Context, err error, w http.ResponseWriter) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tswitch err {\n\tcase cargo.ErrUnknown:\n\t\tw.WriteHeader(http.StatusNotFound)\n\tcase servicecommons.ErrInvalidArgument:\n\t\tw.WriteHeader(http.StatusBadRequest)\n\tdefault:\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n\tjson.NewEncoder(w).Encode(map[string]interface{}{\n\t\t\"error\": err.Error(),\n\t})\n}", "func (output *OutputStruct) fillFromResponse(response *http.Response) error {\n\toutput.responseCode = response.StatusCode\n\toutput.headers = response.Header\n\tif len(output.headers) == 0 {\n\t\toutput.headers = nil\n\t}\n\tvar err error\n\toutput.postBody, err = ioutil.ReadAll(response.Body)\n\tif len(output.postBody) == 0 {\n\t\toutput.postBody = nil\n\t}\n\treturn err\n}", "func ReadBody(request *http.Request, des interface{}, msg string) error {\n\tif kind := reflect.TypeOf(des).Kind(); kind != reflect.Ptr {\n\t\treturn errgo.Errorf(\"des should be a pointer: but got %#v\", kind)\n\t}\n\tif err := json.NewDecoder(request.Body).Decode(des); err != nil {\n\t\treturn errgo.Errorf(\"Failed to decode request body,Error: %s\", err.Error())\n\t}\n\treturn nil\n}", "func getBody(rw http.ResponseWriter, r *http.Request, requestBody *structs.Request) (error, string) {\n\tbuf, _ := ioutil.ReadAll(r.Body)\n\trdr1 := ioutil.NopCloser(bytes.NewBuffer(buf))\n\trdr2 := ioutil.NopCloser(bytes.NewBuffer(buf))\n\n\t//Save the state back into the body for later use (Especially useful for getting the AOD/QOD because if the AOD has not been set a random AOD is set and the function called again)\n\tr.Body = rdr2\n\tif err := json.NewDecoder(rdr1).Decode(&requestBody); err != nil {\n\t\tlog.Printf(\"Got error when decoding: %s\", err)\n\t\terr = errors.New(\"request body is not structured correctly. Please refer to the /docs page for information on how to structure the request body\")\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(rw).Encode(structs.ErrorResponse{Message: err.Error()})\n\t\treturn err, \"\"\n\t}\n\treturn nil, string(buf)\n}", "func (c *Client) parseBody(body interface{}) (io.Reader, error) {\n\tvar bodyData io.Reader\n\tvar err error\n\tvar bdata []byte\n\tif body == nil {\n\t\treturn nil, nil\n\t}\n\tswitch body.(type) {\n\tcase string:\n\t\tbodyStr := body.(string)\n\t\tif len(strings.TrimSpace(bodyStr)) == 0 || bodyStr == \"\" {\n\t\t\tbodyData = nil\n\t\t} else {\n\t\t\tbodyData = strings.NewReader(bodyStr)\n\t\t}\n\t\t//json字符串\n\t\tif gjson.Valid(bodyStr) {\n\t\t\tif c.prettyQsl {\n\t\t\t\tbodyStr = string(pretty.Pretty([]byte(bodyStr)))\n\t\t\t}\n\t\t}\n\t\tlogs.Debug(\"the body data:\\n%s\", bodyStr)\n\tdefault:\n\t\tif c.prettyQsl {\n\t\t\tbdata, err = json.MarshalIndent(body, \"\", \"\\t\")\n\t\t} else {\n\t\t\tbdata, err = json.Marshal(body)\n\t\t}\n\t\tif err != nil {\n\t\t\tlogs.Error(\"the body is decoded error:%s\", err.Error())\n\t\t\treturn nil, err\n\t\t}\n\t\tbodyData = bytes.NewReader(bdata)\n\t\tlogs.Debug(\"the body data:\\n%s\", string(bdata))\n\t}\n\treturn bodyData, nil\n}", "func (c *client) handleResponse(resp *http.Response, method, url string, result interface{}) error {\n\t// Read response body into memory\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn maskAny(errors.Wrapf(err, \"Failed reading response data from %s request to %s: %v\", method, url, err))\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tvar er ErrorResponse\n\t\tif err := json.Unmarshal(body, &er); err == nil {\n\t\t\treturn maskAny(StatusError{\n\t\t\t\tStatusCode: resp.StatusCode,\n\t\t\t\tmessage: er.Error,\n\t\t\t})\n\t\t}\n\t\treturn maskAny(StatusError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t})\n\t}\n\n\t// Got a success status\n\tif result != nil {\n\t\tif err := json.Unmarshal(body, result); err != nil {\n\t\t\treturn maskAny(errors.Wrapf(err, \"Failed decoding response data from %s request to %s: %v\", method, url, err))\n\t\t}\n\t}\n\treturn nil\n}", "func (runner *Runner) Batch(context interface{}, body io.Reader) []*Response {\n\trequests := make([]Request, 0)\n\terr := json.NewDecoder(body).Decode(&requests)\n\tif err != nil {\n\t\treturn []*Response{NewResponseWithError(\"\", Errors.InvalidRequest)}\n\t}\n\n\tresponses := make([]*Response, len(requests))\n\tfor index, request := range requests {\n\t\tif request.JsonRPC != \"2.0\" {\n\t\t\tresponses[index] = NewResponseWithError(request.Id, Errors.InvalidRequest)\n\t\t\tcontinue\n\t\t}\n\n\t\tfn, ok := runner.methods[request.Method]\n\t\tif !ok {\n\t\t\tresponses[index] = NewResponseWithError(request.Id, Errors.NotFound)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult, status := fn(context, request.Params)\n\t\tif status.Code != 0 {\n\t\t\tresponses[index] = NewResponseWithError(request.Id, status)\n\t\t\tcontinue\n\t\t}\n\t\tresponses[index] = NewResponse(request.Id, result)\n\t}\n\treturn responses\n}", "func exitOnResp(resp *http.Response) {\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\texitOnErr(err)\n\t}\n\terr = resp.Body.Close()\n\tif err != nil {\n\t\texitOnErr(err)\n\t}\n\texitOnErr(\n\t\tfmt.Errorf(\"Received %s: %s\", resp.Status, string(b)))\n}", "func (r Response) UnprocessableEntity(code string, payload Payload, header ...ResponseHeader) {\n\tr.Response(code, http.UnprocessableEntity, payload, header...)\n}", "func (c *serverCodec) ReadBody(x interface{}) error {\n\t// If x!=nil and return error e:\n\t// - Write() will be called with e.Error() in r.Error\n\tif x == nil {\n\t\treturn nil\n\t}\n\tif c.req.Params == nil {\n\t\treturn nil\n\t}\n\n\tvar (\n\t\tparams []byte\n\t\terr error\n\t)\n\n\t// 在这里把请求参数json 字符串转换成了相应的struct\n\tparams = []byte(*c.req.Params)\n\t// if c.req.Method == BatchMethod {\n\t// \treturn fmt.Errorf(\"batch request is not allowed\")\n\t// \t/*\n\t// \t\targ := x.(*BatchArg)\n\t// \t\targ.srv = c.srv\n\t// \t\tif err := json.Unmarshal(*c.req.Params, &arg.reqs); err != nil {\n\t// \t\t\treturn NewError(errParams.Code, err.Error())\n\t// \t\t}\n\t// \t\tif len(arg.reqs) == 0 {\n\t// \t\t\treturn errRequest\n\t// \t\t}\n\t// \t*/\n\t// } else\n\tif err = json.Unmarshal(*c.req.Params, x); err != nil {\n\t\t// Note: if c.request.Params is nil it's not an error, it's an optional member.\n\t\t// JSON params structured object. Unmarshal to the args object.\n\n\t\tif 2 < len(params) && params[0] == '[' && params[len(params)-1] == ']' {\n\t\t\t// Clearly JSON params is not a structured object,\n\t\t\t// fallback and attempt an unmarshal with JSON params as\n\t\t\t// array value and RPC params is struct. Unmarshal into\n\t\t\t// array containing the request struct.\n\t\t\tparams := [1]interface{}{x}\n\t\t\tif err = json.Unmarshal(*c.req.Params, &params); err != nil {\n\t\t\t\treturn NewError(errParams.Code, err.Error())\n\t\t\t}\n\t\t} else {\n\t\t\treturn NewError(errParams.Code, err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (dr *RetryableDownloadResponse) Body(o RetryReaderOptions) io.ReadCloser {\n\tif o.MaxRetryRequests == 0 {\n\t\treturn dr.Response().Body\n\t}\n\n\treturn NewRetryReader(\n\t\tdr.ctx,\n\t\tdr.Response(),\n\t\tdr.info,\n\t\to,\n\t\tfunc(ctx context.Context, info HTTPGetterInfo) (*http.Response, error) {\n\t\t\tresp, err := dr.f.Download(ctx, info.Offset, info.Count, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn resp.Response(), err\n\t\t})\n}", "func (file *HgmFile) readBody(count int64, copySink *[]byte) (err error) {\n\n\tfor count != 0 {\n\t\t// Creates a sink which we are going to use as our read buffer\n\t\t// note that this is re-allocated on each loop as we may pass\n\t\t// this reference to lruCache and must avoid overwriting it afterwards\n\t\tbyteSink := make([]byte, lruBlockSize)\n\t\tif int64(len(byteSink)) > count {\n\t\t\t// shrink buffer size if we got less to read than allocated\n\t\t\tbyteSink = byteSink[:count]\n\t\t}\n\n\t\tnr := 0\n\t\tfor nr != len(byteSink) {\n\t\t\trb, re := file.bbody.Read(byteSink[nr:])\n\t\t\tnr += rb\n\n\t\t\tif re != nil {\n\t\t\t\tif rb == 0 && re == io.EOF && nr > 0 {\n\t\t\t\t\t// hide this EOF error, as we did read in previous loops\n\t\t\t\t} else {\n\t\t\t\t\terr = re\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif copySink != nil {\n\t\t\t*copySink = append(*copySink, byteSink[:nr]...)\n\t\t\tif lruCache != nil && ((nr > 0 && err == nil) || (nr == 0 && err == io.EOF)) {\n\t\t\t\t// Cache whatever we got from a lruBlockSize boundary\n\t\t\t\t// this will always be <= lruBlockSize\n\t\t\t\tevicted := lruCache.Add(file.lruKey(file.offset), byteSink[:nr])\n\t\t\t\tif evicted {\n\t\t\t\t\thgmStats.lruEvicted++\n\t\t\t\t}\n\t\t\t\thgmStats.bytesMiss += int64(nr)\n\t\t\t}\n\t\t}\n\n\t\tfile.offset += int64(nr)\n\t\tcount -= int64(nr)\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t}\n\treturn err\n}", "func unpackRequestBody(decoder *hessian.Decoder, reqObj interface{}) error {\n\tif decoder == nil {\n\t\treturn perrors.Errorf(\"@decoder is nil\")\n\t}\n\n\treq, ok := reqObj.([]interface{})\n\tif !ok {\n\t\treturn perrors.Errorf(\"@reqObj is not of type: []interface{}\")\n\t}\n\tif len(req) < 7 {\n\t\treturn perrors.New(\"length of @reqObj should be 7\")\n\t}\n\n\tvar (\n\t\terr error\n\t\tdubboVersion, target, serviceVersion, method, argsTypes interface{}\n\t\targs []interface{}\n\t)\n\n\tdubboVersion, err = decoder.Decode()\n\tif err != nil {\n\t\treturn perrors.WithStack(err)\n\t}\n\treq[0] = dubboVersion\n\n\ttarget, err = decoder.Decode()\n\tif err != nil {\n\t\treturn perrors.WithStack(err)\n\t}\n\treq[1] = target\n\n\tserviceVersion, err = decoder.Decode()\n\tif err != nil {\n\t\treturn perrors.WithStack(err)\n\t}\n\treq[2] = serviceVersion\n\n\tmethod, err = decoder.Decode()\n\tif err != nil {\n\t\treturn perrors.WithStack(err)\n\t}\n\treq[3] = method\n\n\targsTypes, err = decoder.Decode()\n\tif err != nil {\n\t\treturn perrors.WithStack(err)\n\t}\n\treq[4] = argsTypes\n\n\tats := DescRegex.FindAllString(argsTypes.(string), -1)\n\tvar arg interface{}\n\tfor i := 0; i < len(ats); i++ {\n\t\targ, err = decoder.Decode()\n\t\tif err != nil {\n\t\t\treturn perrors.WithStack(err)\n\t\t}\n\t\targs = append(args, arg)\n\t}\n\treq[5] = args\n\n\tattachments, err := decoder.Decode()\n\tif err != nil {\n\t\treturn perrors.WithStack(err)\n\t}\n\tif v, ok := attachments.(map[interface{}]interface{}); ok {\n\t\tv[DUBBO_VERSION_KEY] = dubboVersion\n\t\treq[6] = ToMapStringInterface(v)\n\t\treturn nil\n\t}\n\n\treturn perrors.Errorf(\"get wrong attachments: %+v\", attachments)\n}", "func (resp *Response) ReadBody() []byte {\n\tif resp.Resp != nil && resp.Resp.Body != nil {\n\t\tbody, err := ioutil.ReadAll(resp.Resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn body\n\t}\n\treturn nil\n}", "func (c *Ctx) ReadBody(out interface{}) error {\n\t// Get decoder from pool\n\tschemaDecoder := decoderPool.Get().(*schema.Decoder)\n\tdefer decoderPool.Put(schemaDecoder)\n\n\t// Get content-type\n\tctype := ToLower(BytesToString(c.Request.Header.ContentType()))\n\n\tswitch {\n\tcase strings.HasPrefix(ctype, MIMEApplicationJSON):\n\t\tschemaDecoder.SetAliasTag(\"json\")\n\t\treturn json.Unmarshal(c.Request.Body(), out)\n\tcase strings.HasPrefix(ctype, MIMEApplicationForm):\n\t\tschemaDecoder.SetAliasTag(\"form\")\n\t\tdata := make(map[string][]string)\n\t\tc.PostArgs().VisitAll(func(key []byte, val []byte) {\n\t\t\tdata[BytesToString(key)] = append(data[BytesToString(key)], BytesToString(val))\n\t\t})\n\t\treturn schemaDecoder.Decode(out, data)\n\tcase strings.HasPrefix(ctype, MIMEMultipartForm):\n\t\tschemaDecoder.SetAliasTag(\"form\")\n\t\tdata, err := c.MultipartForm()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn schemaDecoder.Decode(out, data.Value)\n\tcase strings.HasPrefix(ctype, MIMETextXML), strings.HasPrefix(ctype, MIMEApplicationXML):\n\t\tschemaDecoder.SetAliasTag(\"xml\")\n\t\treturn xml.Unmarshal(c.Request.Body(), out)\n\t}\n\t// No suitable content type found\n\treturn ErrUnprocessableEntity\n}", "func ParseBetaTestersBuildsGetToManyRelationshipResponse(rsp *http.Response) (*BetaTestersBuildsGetToManyRelationshipResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer func() { _ = rsp.Body.Close() }()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &BetaTestersBuildsGetToManyRelationshipResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest BetaTesterBuildsLinkagesResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 400:\n\t\tvar dest ErrorResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON400 = &dest\n\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 403:\n\t\tvar dest ErrorResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON403 = &dest\n\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 404:\n\t\tvar dest ErrorResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON404 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func unmarshalApiResponse(apiResponse *RawResponse, dest interface{}) error {\n if apiResponse.StatusCode == fasthttp.StatusOK || apiResponse.StatusCode == fasthttp.StatusAccepted {\n if err := json.Unmarshal(apiResponse.Body, dest); err != nil {\n return err\n }\n return nil\n } else {\n var apiError errors.ApiError\n if err := json.Unmarshal(apiResponse.Body, &apiError); err != nil {\n return err\n }\n return apiError\n }\n}", "func DecodeReqBody(reqBody io.ReadCloser, v interface{}) error {\n\tbody, _ := ioutil.ReadAll(reqBody)\n\terr := json.Unmarshal(body, v)\n\tif err != nil {\n\t\tlog.Printf(\"Error unmarshaling request body: %s\", err)\n\t}\n\n\treqBody.Close()\n\treturn err\n}", "func ValidateFieldNoteAuthorResponseBody(body *FieldNoteAuthorResponseBody) (err error) {\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\tif body.MediaURL == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"mediaUrl\", \"body\"))\n\t}\n\treturn\n}", "func readBody(msg []byte, state *readState) error {\n\tline := msg[0 : len(msg)-2]\n\tvar err error\n\tif line[0] == '$' {\n\t\t// bulk reply\n\t\tstate.bulkLen, err = strconv.ParseInt(string(line[1:]), 10, 64)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"protocol error: \" + string(msg))\n\t\t}\n\t\tif state.bulkLen <= 0 { // null bulk in multi bulks\n\t\t\tstate.args = append(state.args, []byte{})\n\t\t\tstate.bulkLen = 0\n\t\t}\n\t} else {\n\t\tstate.args = append(state.args, line)\n\t}\n\treturn nil\n}", "func (pr httpProber) ProbeForBody(req *http.Request, timeout time.Duration) (probe.Result, string, string, error) {\n\tpr.transport.DisableCompression = true // removes Accept-Encoding header\n\tclient := &http.Client{\n\t\tTimeout: timeout,\n\t\tTransport: pr.transport,\n\t\tCheckRedirect: RedirectChecker(pr.followNonLocalRedirects),\n\t}\n\treturn DoHTTPProbe(req, client)\n}", "func (ctx *serverRequestContextImpl) ReadBody(body interface{}) error {\n\tempty, err := ctx.TryReadBody(body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif empty {\n\t\treturn caerrors.NewHTTPErr(400, caerrors.ErrEmptyReqBody, \"Empty request body\")\n\t}\n\treturn nil\n}", "func (res *ServerHTTPResponse) PeekBody(\n\tkeys ...string,\n) ([]byte, jsonparser.ValueType, error) {\n\tvalue, valueType, _, err := jsonparser.Get(\n\t\tres.pendingBodyBytes, keys...,\n\t)\n\tif err != nil {\n\t\treturn nil, -1, err\n\t}\n\n\treturn value, valueType, nil\n}", "func ReadBody(body io.ReadCloser) (string, error) {\n\tbuf := new(bytes.Buffer)\n\t_, err := buf.ReadFrom(body)\n\treturn buf.String(), err\n}", "func CollectHTTPBody(r *http.Request, g *grids.GridPacket) {\n\tcontent, ok := r.Header[\"Content-Type\"]\n\tmuxcontent := strings.Join(content, \";\")\n\twind := strings.Index(muxcontent, \"application/x-www-form-urlencode\")\n\tmind := strings.Index(muxcontent, \"multipart/form-data\")\n\tjsn := strings.Index(muxcontent, \"application/json\")\n\n\tif ok {\n\n\t\tif jsn != -1 {\n\t\t\tg.Set(\"Type\", \"json\")\n\t\t\tg.Set(\"JSON\", true)\n\t\t\tg.Set(\"Data\", true)\n\t\t}\n\n\t\tif wind != -1 {\n\t\t\tif err := r.ParseForm(); err != nil {\n\t\t\t\tlog.Println(\"Request Read Form Error\", err)\n\t\t\t} else {\n\t\t\t\tform := r.Form\n\t\t\t\tpform := r.PostForm\n\n\t\t\t\tg.Set(\"Data\", true)\n\t\t\t\tg.Set(\"Form\", true)\n\t\t\t\tg.Set(\"Form\", form)\n\t\t\t\tg.Set(\"PostForm\", pform)\n\t\t\t}\n\t\t}\n\n\t\tif mind != -1 {\n\t\t\tif err := r.ParseMultipartForm(32 << 20); err != nil {\n\t\t\t\tlog.Println(\"Request Read MultipartForm Error\", err)\n\t\t\t} else {\n\t\t\t\tg.Set(\"Data\", true)\n\t\t\t\tg.Set(\"Form\", false)\n\t\t\t\tg.Set(\"Value\", r.MultipartForm.Value)\n\t\t\t\tg.Set(\"Body\", r.MultipartForm.File)\n\t\t\t}\n\t\t}\n\n\t\tif mind == -1 && wind == -1 && r.Body != nil {\n\n\t\t\tdata := make([]byte, r.ContentLength)\n\t\t\ttotal, err := r.Body.Read(data)\n\n\t\t\tif err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\tlog.Println(\"Request Read Body Error\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tg.Set(\"Data\", true)\n\t\t\tg.Set(\"Form\", false)\n\t\t\tg.Set(\"Value\", total)\n\t\t\tg.Set(\"Body\", data)\n\n\t\t}\n\t}\n}", "func Body(body, contentType, transferEncoding string, opt Options) (string, error) {\n\t// attempt to do some base64-decoding anyway\n\tif decoded, err := base64.URLEncoding.DecodeString(body); err == nil {\n\t\tbody = string(decoded)\n\t}\n\tif decoded, err := base64.StdEncoding.DecodeString(body); err == nil {\n\t\tbody = string(decoded)\n\t}\n\n\tif strings.ToLower(transferEncoding) == \"quoted-printable\" {\n\t\tb, err := ioutil.ReadAll(quotedprintable.NewReader(strings.NewReader(body)))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tbody = string(b)\n\t}\n\n\tct := strings.ToLower(contentType)\n\tif strings.Contains(ct, \"multipart/\") {\n\t\treturn parseMultipart(body, contentType, opt)\n\t}\n\n\tif !opt.SkipHTML && strings.Contains(ct, \"text/html\") {\n\t\tbody = stripHTML(body, opt)\n\t}\n\n\tbody = stripEmbedded(body, opt)\n\tif opt.LineLimit > 0 || opt.ColLimit > 0 {\n\t\tlines := strings.Split(body, \"\\n\")\n\t\tif len(lines) > opt.LineLimit {\n\t\t\tlines = lines[:opt.LineLimit]\n\t\t}\n\t\tfor kk, l := range lines {\n\t\t\tif len(l) > opt.ColLimit {\n\t\t\t\tlines[kk] = l[:opt.ColLimit]\n\t\t\t}\n\t\t}\n\t\tbody = strings.Join(lines, \"\\n\")\n\t}\n\treturn body, nil\n}" ]
[ "0.5680592", "0.56435114", "0.5631959", "0.5522728", "0.54882276", "0.5482303", "0.54751396", "0.5364349", "0.5358157", "0.53234804", "0.5321872", "0.52747655", "0.5210658", "0.51857114", "0.5130053", "0.5072723", "0.50544876", "0.5036079", "0.5028855", "0.49748597", "0.4963768", "0.4952745", "0.4938989", "0.49363086", "0.4920965", "0.4911645", "0.49109825", "0.48982882", "0.48913342", "0.48871675", "0.48425215", "0.48420122", "0.48388273", "0.48203894", "0.48093832", "0.4808277", "0.47887823", "0.47856432", "0.47812858", "0.4773805", "0.47708338", "0.47615275", "0.4748162", "0.47479904", "0.4747029", "0.47385287", "0.47291046", "0.46974552", "0.4690019", "0.4685364", "0.4672111", "0.46676952", "0.46636498", "0.46458364", "0.46446848", "0.46409777", "0.46365994", "0.4627743", "0.4626552", "0.4623899", "0.46231934", "0.46186945", "0.4613056", "0.46030784", "0.46028998", "0.45993727", "0.4597782", "0.45961374", "0.45931348", "0.45891005", "0.45874673", "0.45867157", "0.45816615", "0.45796645", "0.45739892", "0.45722306", "0.45697692", "0.45652527", "0.45640007", "0.45571062", "0.45519018", "0.454939", "0.4541909", "0.4539101", "0.45375875", "0.4534919", "0.45268714", "0.45241663", "0.4523686", "0.45182332", "0.45164788", "0.45036244", "0.45032585", "0.45026022", "0.44985098", "0.44937098", "0.4484905", "0.44847673", "0.44740582", "0.44721746" ]
0.7787903
0
linker_config generates protobuf file from json file. This protobuf file will be used from linkerconfig while generating ld.config.txt. Format of this file can be found from
func linkerConfigFactory() android.Module { m := &linkerConfig{} m.AddProperties(&m.properties) android.InitAndroidArchModule(m, android.HostAndDeviceSupported, android.MultilibFirst) return m }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GenerateAppLinkJsonFile(packageName string, sha256 string) {\n\tlog.Infof(\"[Cert Resource] Start to generate new app link json file!\")\n\t// mutex to lock\n\tandroidLock.Lock()\n\tdefer androidLock.Unlock()\n\n\tcurDir := getcurdir()\n\tfile, err := ioutil.ReadFile(curDir + \"/../app_site/.well-known/assetlinks_full.json\")\n\tif err != nil {\n\t\tlog.Errorf(\"[Cert Resource] Find file <assetlinks> failed! Err Msg=%s\", err)\n\t\treturn\n\t}\n\n\tvar appLinkJson AppLinkJson\n\tjson.Unmarshal(file, &appLinkJson)\n\tlog.Infof(\"[Cert Resource] AppLinkJson File Content : %v\", appLinkJson)\n\t// add new element\n\n\ttarget := Target{Namespace: \"android_app\", PackageName: packageName, SHA256: []string{sha256}}\n\tapplink := AppLink{Relation: []string{\"delegate_permission/common.handle_all_urls\"}, Target: target}\n\n\tappLinkJson.AppLink = append(appLinkJson.AppLink, applink)\n\n\tnewResult, err := json.Marshal(appLinkJson)\n\tif err != nil {\n\t\tlog.Errorf(\"[Cert Resource] Marshal upsert info failed! Err Msg=%v\", err)\n\t\treturn\n\t}\n\n\terr = ioutil.WriteFile(curDir+\"/../app_site/.well-known/assetlinks_full.json\", newResult, 0666)\n\tif err != nil {\n\t\tlog.Errorf(\"[Cert Resource] Failed to generate new json file, error: %v\\n\", err)\n\t\treturn\n\t}\n\n\t//\n\tnewResult, err = json.Marshal(appLinkJson.AppLink)\n\tif err != nil {\n\t\tlog.Errorf(\"[Cert Resource] Marshal upsert info failed! Err Msg=%v\", err)\n\t\treturn\n\t}\n\n\terr = ioutil.WriteFile(curDir+\"/../app_site/.well-known/assetlinks.json\", newResult, 0666)\n\tif err != nil {\n\t\tlog.Errorf(\"[Cert Resource] Failed to generate new json file, error: %v\\n\", err)\n\t\treturn\n\t}\n}", "func genConfig() ([]byte, error) {\n\t// Using genflags.getConfig() instead of config.New() because\n\t// it will include any defaults we have on the command line such\n\t// as default plugin selection. We didn't want to wire this into\n\t// the `config` package, but it will be a default value the CLI\n\t// users expect.\n\tc := genflags.resolveConfig()\n\tb, err := json.Marshal(c)\n\treturn b, errors.Wrap(err, \"unable to marshal configuration\")\n}", "func MavenDependencyConfigToProtoRuntimeLibrary(dependency bufpluginconfig.MavenDependencyConfig) *registryv1alpha1.MavenConfig_RuntimeLibrary {\n\treturn &registryv1alpha1.MavenConfig_RuntimeLibrary{\n\t\tGroupId: dependency.GroupID,\n\t\tArtifactId: dependency.ArtifactID,\n\t\tVersion: dependency.Version,\n\t\tClassifier: dependency.Classifier,\n\t\tExtension: dependency.Extension,\n\t}\n}", "func (*GrpcJsonTranscoder_DescriptorConfigMap) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_v1_options_grpc_json_grpc_json_proto_rawDescGZIP(), []int{0, 1}\n}", "func protoGoRuntimeLibraryToGoRuntimeDependency(config *registryv1alpha1.GoConfig_RuntimeLibrary) *bufpluginconfig.GoRegistryDependencyConfig {\n\treturn &bufpluginconfig.GoRegistryDependencyConfig{\n\t\tModule: config.Module,\n\t\tVersion: config.Version,\n\t}\n}", "func goRuntimeDependencyToProtoGoRuntimeLibrary(config *bufpluginconfig.GoRegistryDependencyConfig) *registryv1alpha1.GoConfig_RuntimeLibrary {\n\treturn &registryv1alpha1.GoConfig_RuntimeLibrary{\n\t\tModule: config.Module,\n\t\tVersion: config.Version,\n\t}\n}", "func (c *Config) GenerateConfig(path string) {\n\n\tc = &Config{\n\t\tCertificate: \"cert.pem\",\n\t\tCertificateKey: \"cert.key\",\n\t\tWWWHost: \":9000\",\n\t\tWWWRoot: \"www\",\n\t\tTag: \"/chat\",\n\t\tTLS: false,\n\t\tVerbose: true,\n\t\tEscapeData: true,\n\t}\n\n\tb, _ := json.MarshalIndent(c, \"\", \"\\t\")\n\tioutil.WriteFile(*conf, b, 0644)\n\n}", "func (*ConfigFile) Descriptor() ([]byte, []int) {\n\treturn file_google_api_servicemanagement_v1_resources_proto_rawDescGZIP(), []int{4}\n}", "func (f *Flags) Link() {\n\tflag.StringVar(&f.ConfigPath, \"c\", \"clutch-config.yaml\", \"path to YAML configuration\")\n\tflag.BoolVar(&f.Template, \"template\", false, \"executes go templates on the configuration file\")\n\tflag.BoolVar(&f.Validate, \"validate\", false, \"validates the configuration file and exits\")\n}", "func (*ConfigRef) Descriptor() ([]byte, []int) {\n\treturn file_config_v1_resources_proto_rawDescGZIP(), []int{4}\n}", "func (*ConfigRef) Descriptor() ([]byte, []int) {\n\treturn file_google_api_servicemanagement_v1_resources_proto_rawDescGZIP(), []int{5}\n}", "func (*TranslateConfig) Descriptor() ([]byte, []int) {\n\treturn file_sogou_speech_mt_v1_mt_proto_rawDescGZIP(), []int{1}\n}", "func link(pack *godata.GoPackage) bool {\n\tvar argc int\n\tvar argv []string\n\tvar argvFilled int\n\tvar objDir string = \"\" //outputDirPrefix + getObjDir();\n\n\t// build the command line for the linker\n\targc = 4\n\tif *flagIncludePaths != \"\" {\n\t\targc += 2\n\t}\n\tif pack.NeedsLocalSearchPath() {\n\t\targc += 2\n\t}\n\tif pack.Name == \"main\" {\n\t\targc += 2\n\t}\n\n\targv = make([]string, argc*3)\n\n\targv[argvFilled] = linkerBin\n\targvFilled++\n\targv[argvFilled] = \"-o\"\n\targvFilled++\n\targv[argvFilled] = outputDirPrefix + pack.OutputFile\n\targvFilled++\n\tif *flagIncludePaths != \"\" {\n\t\tfor _, v := range strings.Split(*flagIncludePaths, \",\", -1) {\n\t\t\targv[argvFilled] = \"-L\"\n\t\t\targvFilled++\n\t\t\targv[argvFilled] = v\n\t\t\targvFilled++\n\t\t}\n\t}\n\t// \tif pack.NeedsLocalSearchPath() {\n\t// \t\targv[argvFilled] = \"-L\"\n\t// \t\targvFilled++\n\t// \t\tif objDir != \"\" {\n\t// \t\t\targv[argvFilled] = objDir\n\t// \t\t} else {\n\t// \t\t\targv[argvFilled] = \".\"\n\t// \t\t}\n\t// \t\targvFilled++\n\t// \t}\n\tif pack.Name == \"main\" {\n\t\targv[argvFilled] = \"-L\"\n\t\targvFilled++\n\t\targv[argvFilled] = \".\"\n\t\targvFilled++\n\t}\n\targv[argvFilled] = objDir + pack.OutputFile + objExt\n\targvFilled++\n\n\tlogger.Info(\"Linking %s...\\n\", argv[2])\n\tlogger.Info(\" %s\\n\\n\", getCommandline(argv))\n\n\tcmd, err := exec.Run(linkerBin, argv[0:argvFilled], os.Environ(), rootPath,\n\t\texec.DevNull, exec.PassThrough, exec.PassThrough)\n\tif err != nil {\n\t\tlogger.Error(\"%s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\twaitmsg, err := cmd.Wait(0)\n\tif err != nil {\n\t\tlogger.Error(\"Linker execution error (%s), aborting compilation.\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tif waitmsg.ExitStatus() != 0 {\n\t\tlogger.Error(\"Linker returned with errors, aborting.\\n\")\n\t\treturn false\n\t}\n\treturn true\n}", "func (*LightstepConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_trace_v3_lightstep_proto_rawDescGZIP(), []int{0}\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_keepsake_proto_rawDescGZIP(), []int{19}\n}", "func GenerateConfig() (configFile []byte,err error){\n\t// dont crash the whole thing\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = errors.New(\"internal error\")\n\t\t}\n\t}()\n\tkey,err := x25519.NewX25519()\n\tif err != nil{\n\t\treturn\n\t}\n\tjsonBytes , err := Register(base64.StdEncoding.EncodeToString(key.PublicKey),\"\")\n\tif err != nil{\n\t\treturn\n\t}\n\tvar accountResponse map[string]interface{}\n\terr = json.Unmarshal(jsonBytes,&accountResponse)\n\tif err != nil{\n\t\treturn\n\t}\n\tvar data ProfileData\n\tdata.PrivateKey = base64.StdEncoding.EncodeToString(key.SecretKey)\n\tif _,ok:= accountResponse[\"config\"]; !ok{\n\t\treturn\n\t}\n\t{\n\t\tpeer := accountResponse[\"config\"].(map[string]interface{})[\"peers\"].([]interface{})[0].(map[string]interface{})\n\t\tdata.PublicKey = peer[\"public_key\"].(string)\n\t\tdata.Endpoint = peer[\"endpoint\"].(map[string]interface{})[\"host\"].(string)\n\t}\n\t{\n\t\taddresses := accountResponse[\"config\"].(map[string]interface{})[\"interface\"].(map[string]interface{})[\"addresses\"].(map[string]interface{})\n\t\tdata.Address1 = addresses[\"v4\"].(string)\n\t\tdata.Address2 = addresses[\"v6\"].(string)\n\t}\n\tdata.Response = string(jsonBytes)\n\tdata.DeviceID = accountResponse[\"id\"].(string)\n\n\tprofile,err := GenerateProfile(&data)\n\tconfigFile = []byte(profile)\n\treturn\n}", "func generateFile(gen *protogen.Plugin, file *protogen.File) {\n\tfilename := file.GeneratedFilenamePrefix + \"_message.pb.go\"\n\tg := gen.NewGeneratedFile(filename, file.GoImportPath)\n\n\tg.P(\"// Code generated by protoc-gen-message-validator. DO NOT EDIT.\")\n\tg.P()\n\tg.P(\"package \", file.GoPackageName)\n\tg.P()\n\n\tfor _, message := range file.Messages {\n\t\tstructName := string(message.Desc.Name())\n\t\tprefix := strings.ToLower(string(structName[0]))\n\n\t\tfor _, subMessage := range message.Messages {\n\t\t\tif subMessage.Desc.IsMapEntry() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsubStructName := string(subMessage.Desc.Name())\n\t\t\tgenerateMessage(fmt.Sprintf(\"%s_%s\", structName, subStructName), prefix, subMessage, g)\n\t\t}\n\n\t\tgenerateMessage(structName, prefix, message, g)\n\t}\n}", "func (*ConfigurationFile) Descriptor() ([]byte, []int) {\n\treturn file_pkg_kascfg_kascfg_proto_rawDescGZIP(), []int{25}\n}", "func (*PublisherConfig) Descriptor() ([]byte, []int) {\n\treturn file_network_api_proto_rawDescGZIP(), []int{3}\n}", "func (*ExtraConfig) Descriptor() ([]byte, []int) {\n\treturn file_config_v1_resources_proto_rawDescGZIP(), []int{9}\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_config_module_proxy_v1_proxy_proto_rawDescGZIP(), []int{0}\n}", "func (*ExternalConfigurationPayload) Descriptor() ([]byte, []int) {\n\treturn file_external_transforms_proto_rawDescGZIP(), []int{0}\n}", "func (*ConfigSource) Descriptor() ([]byte, []int) {\n\treturn file_google_api_servicemanagement_v1_resources_proto_rawDescGZIP(), []int{3}\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_buildserver_proto_rawDescGZIP(), []int{0}\n}", "func generateSchemaFile(o, wdPath string) error {\n\tsData, err := GenerateSchema()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check if the provided output path is relative\n\tif !path.IsAbs(o) {\n\t\to = path.Join(wdPath, o)\n\t}\n\n\terr = os.WriteFile(path.Join(o, schemaFileName), sData, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tLog.Info(\"generated JSON schema for BlueprintMetadata\", \"path\", path.Join(o, schemaFileName))\n\treturn nil\n}", "func (*Configuration) Descriptor() ([]byte, []int) {\n\treturn file_pkg_pb_protobuf_api_proto_rawDescGZIP(), []int{19}\n}", "func (*CommonExtensionConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_common_tap_v2alpha_common_proto_rawDescGZIP(), []int{0}\n}", "func GenTrafficFromConfig(config *Configuration) {\n\tdnsclient, err := NewDNSClientWithConfig(config)\n\tif err != nil {\n\t\tlog.Panicf(\"%s\", err.Error())\n\t}\n\tlog.Println(\"config the dns loader success\")\n\tlog.Printf(\"current configuration for dns loader is server:%s|port:%d\\n\",\n\t\tdnsclient.Config.Server, dnsclient.Config.Port)\n\t// log.Printf(\"%+v\", config)\n\tparam := GeneratorParam{\n\t\tCaller: dnsclient,\n\t\tTimeout: 1000 * time.Millisecond,\n\t\tQPS: uint32(config.QPS),\n\t\tDuration: time.Second * time.Duration(config.Duration),\n\t}\n\tlog.Printf(\"initialize load %+v\", param)\n\tgen, err := NewDNSLoaderGenerator(param)\n\tif err != nil {\n\t\tlog.Panicf(\"load generator initialization fail :%s\", err)\n\t}\n\tlog.Println(\"start load generator\")\n\tGloablGenerator = gen\n\tgen.Start()\n}", "func (*BindConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_core_v3_address_proto_rawDescGZIP(), []int{3}\n}", "func (*TargetsConfig) Descriptor() ([]byte, []int) {\n\treturn file_pkg_broker_config_targets_proto_rawDescGZIP(), []int{3}\n}", "func (*GlobalOptions) Descriptor() ([]byte, []int) {\n\treturn file_github_com_google_cloudprober_targets_gce_proto_config_proto_rawDescGZIP(), []int{3}\n}", "func Load(dir string) (*Conf, error) {\n\tdata, err := ReadSinkerRc(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconf, err := ParseJsonConfg(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &conf, nil\n}", "func (*LOCConfig) Descriptor() ([]byte, []int) {\n\treturn file_config_devconfig_proto_rawDescGZIP(), []int{0}\n}", "func ProtoMavenRuntimeLibraryToDependencyConfig(proto *registryv1alpha1.MavenConfig_RuntimeLibrary) bufpluginconfig.MavenDependencyConfig {\n\treturn bufpluginconfig.MavenDependencyConfig{\n\t\tGroupID: proto.GetGroupId(),\n\t\tArtifactID: proto.GetArtifactId(),\n\t\tVersion: proto.GetVersion(),\n\t\tClassifier: proto.GetClassifier(),\n\t\tExtension: proto.GetExtension(),\n\t}\n}", "func loadV2JsonPb(data []byte) (*core.Config, error) {\n\tcoreconf := &core.Config{}\n\tjsonpbloader := &protojson.UnmarshalOptions{Resolver: anyresolverv2{serial.GetResolver()}, AllowPartial: true}\n\terr := jsonpbloader.Unmarshal(data, &V2JsonProtobufFollower{coreconf.ProtoReflect()})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coreconf, nil\n}", "func ExampleLinkerClient_ListConfigurations() {\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 := armservicelinker.NewClientFactory(cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewLinkerClient().ListConfigurations(ctx, \"subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Web/sites/test-app\", \"linkName\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.SourceConfigurationResult = armservicelinker.SourceConfigurationResult{\n\t// \tConfigurations: []*armservicelinker.SourceConfiguration{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"ASL_DocumentDb_ConnectionString\"),\n\t// \t\t\tValue: to.Ptr(\"ConnectionString\"),\n\t// \t}},\n\t// }\n}", "func (*ForwardingRules) Descriptor() ([]byte, []int) {\n\treturn file_github_com_google_cloudprober_targets_gce_proto_config_proto_rawDescGZIP(), []int{2}\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_config_module_featureflag_v1_featureflag_proto_rawDescGZIP(), []int{1}\n}", "func (*FileBasedMetadataConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_grpc_credential_v2alpha_file_based_metadata_proto_rawDescGZIP(), []int{0}\n}", "func (c *Config) Binary() []byte {\n\t// TODO: ensure this is sorted?\n\tout, _ := json.MarshalIndent(&Binary{\n\t\tName: c.BinaryName,\n\t\tRepo: c.BuildRepo,\n\t\tBuild: c.BuildCommand,\n\t\tVersion: c.BuildVersion,\n\t}, \"\", \" \")\n\treturn out\n}", "func (*TargetsConf) Descriptor() ([]byte, []int) {\n\treturn file_github_com_google_cloudprober_targets_gce_proto_config_proto_rawDescGZIP(), []int{0}\n}", "func MakeServerConfigFromFile(jsonFile string) (*ServerConfig, error) {\n\tb, err := ioutil.ReadFile(jsonFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn MakeServerConfig(b)\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_config_proto_rawDescGZIP(), []int{4}\n}", "func (*GetConfigurationResponse) Descriptor() ([]byte, []int) {\n\treturn file_runtime_proto_rawDescGZIP(), []int{22}\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{5}\n}", "func (crc *CommandsRunnerClient) GenerateConfig(extensionName string) (string, error) {\n\turl := \"config\"\n\tif extensionName != \"\" {\n\t\turl += \"?extension-name=\" + extensionName\n\t}\n\t//Call the rest API\n\tdata, errCode, err := crc.RestCall(http.MethodPut, global.BaseURL, url, nil, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif errCode != http.StatusOK {\n\t\treturn \"\", errors.New(\"Unable to generate the configuration \" + data + \", please check log for more information\")\n\t}\n\treturn \"\", nil\n}", "func generate(proto string, localArgs []string) error {\n\targs := []string{\n\t\t\"--proto_path=.\",\n\t\t\"--proto_path=\" + filepath.Join(base.KratosMod(), \"api\"),\n\t\t\"--proto_path=\" + filepath.Join(base.KratosMod(), \"third_party\"),\n\t\t\"--proto_path=\" + filepath.Join(os.Getenv(\"GOPATH\"), \"src\"),\n\t\t\"--go_out=paths=source_relative:.\",\n\t\t\"--go-grpc_out=paths=source_relative:.\",\n\t\t\"--go-http_out=paths=source_relative:.\",\n\t\t\"--go-errors_out=paths=source_relative:.\",\n\t}\n\t// ts umi为可选项 只在安装 protoc-gen-ts-umi情况下生成\n\tfmt.Println(localArgs)\n\tfor _, v := range localArgs[1:] {\n\t\tif v == \"vendor\" {\n\t\t\targs = append(args, \"--proto_path=./vendor\")\n\t\t} else {\n\t\t\tif err := look(fmt.Sprintf(\"protoc-gen-%s\", v)); err == nil {\n\t\t\t\targs = append(args, fmt.Sprintf(\"--%s_out=paths=source_relative:.\", v))\n\t\t\t} else {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t}\n\t}\n\targs = append(args, proto)\n\tfd := exec.Command(\"protoc\", args...)\n\tfd.Stdout = os.Stdout\n\tfd.Stderr = os.Stderr\n\t//fd.Dir = path\n\tif err := fd.Run(); err != nil {\n\t\tfmt.Printf(\"comand: protoc %s \\n\", strings.Join(args, \" \"))\n\t\treturn err\n\t}\n\tfmt.Printf(\"proto: %s\\n\", proto)\n\tfmt.Printf(\"comand: protoc %s \\n\", strings.Join(args, \" \"))\n\treturn nil\n}", "func main() {\n\n\tvar (\n\t\tisHelp bool\n\t\tisStdin bool\n\t\tbase64Data string\n\t\tconfName string\n\t\tisForce bool\n\t\tisOffset bool\n\t)\n\n\tflag.BoolVar(&isHelp, \"help\", false, \"show this help.\")\n\tflag.BoolVar(&isStdin, \"stdin\", false, \"read base64 encoded data from standard input.\")\n\tflag.StringVar(&base64Data, \"base64\", \"\", \"base64 encoded data for the configuration file.\")\n\tflag.StringVar(&confName, \"conf\", \"\", \"configuration file name.\")\n\tflag.BoolVar(&isForce, \"force\", false, \"force parsing json-type conf files in a simple and rude manner.\")\n\tflag.BoolVar(&isOffset, \"offset\", false, \"find the conf based on the dir where the exe is located.\")\n\t//如果配置文件里面有配置路径, 还是一个相对路径, 那么这个路径还是根据工作目录走的, 不是根据程序所在的目录走的.\n\tflag.Parse()\n\n\tif isHelp {\n\t\tflag.Usage()\n\t\tfmt.Println()\n\t\tfmt.Println(exampleConfigData())\n\t\tfmt.Println()\n\t\treturn\n\t}\n\n\tcontent, isBase64, baseDir, err := loadConfigContent(isStdin, base64Data, confName, isForce, isOffset)\n\tif err != nil {\n\t\tlog.Fatalln(\"loadConfigContent,\", err)\n\t}\n\n\tif globalConfigData, err = calcConfigData(content, isBase64, baseDir); err != nil {\n\t\tlog.Fatalln(\"calcConfigData,\", err)\n\t}\n\n\tif err := globalConfigData.init(); err != nil {\n\t\tlog.Fatalln(\"init config,\", err)\n\t}\n\n\tif globalConfigData.IsDebugMode {\n\t\tglobalDebugStream = os.Stderr\n\t}\n\n\tvar hostKey ssh.Signer\n\tif hostKey, err = ssh.ParsePrivateKey([]byte(globalConfigData.HostKey)); err != nil {\n\t\tlog.Fatalln(\"ParsePrivateKey\", err)\n\t}\n\n\t// An SSH server is represented by a ServerConfig, which holds\n\t// certificate details and handles authentication of ServerConns.\n\tglobalSSHServerConfig = globalConfigData.sshServerConfig()\n\tglobalSSHServerConfig.PasswordCallback = tmpPasswordCallback\n\tglobalSSHServerConfig.PublicKeyCallback = tmpPublicKeyCallback\n\tglobalSSHServerConfig.AddHostKey(hostKey)\n\n\t// Once a ServerConfig has been configured, connections can be\n\t// accepted.\n\tlistener, err := net.Listen(\"tcp\", globalConfigData.Address)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to listen for connection\", err)\n\t}\n\tlog.Printf(\"Listening on %v\", listener.Addr())\n\n\tfor {\n\t\tnConn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"failed to accept incoming connection\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Println(fmt.Sprintf(\"Accept, LocalAddr=%v, RemoteAddr=%v\", nConn.LocalAddr(), nConn.RemoteAddr()))\n\n\t\t// Before use, a handshake must be performed on the incoming\n\t\t// net.Conn.\n\t\t_, chans, reqs, err := ssh.NewServerConn(nConn, globalSSHServerConfig)\n\t\tif err != nil {\n\t\t\tlog.Println(\"failed to handshake\", err)\n\t\t\tnConn.Close()\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Fprintf(globalDebugStream, \"SSH server established\\n\")\n\n\t\t// The incoming Request channel must be serviced.\n\t\tgo ssh.DiscardRequests(reqs)\n\n\t\tgo handleChannels(chans)\n\t}\n}", "func (*FypConfig) Descriptor() ([]byte, []int) {\n\treturn file_fypConfigService_proto_rawDescGZIP(), []int{0}\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_pkg_config_po_config_proto_rawDescGZIP(), []int{0}\n}", "func (*ChainConfig) Descriptor() ([]byte, []int) {\n\treturn file_pkg_noderpc_proto_feeds_manager_proto_rawDescGZIP(), []int{5}\n}", "func (*BootstrapConfig) Descriptor() ([]byte, []int) {\n\treturn file_config_devconfig_proto_rawDescGZIP(), []int{4}\n}", "func (*Links) Descriptor() ([]byte, []int) {\n\treturn file_dictybase_api_jsonapi_payload_proto_rawDescGZIP(), []int{2}\n}", "func (*CrawlConfig) Descriptor() ([]byte, []int) {\n\treturn file_config_v1_resources_proto_rawDescGZIP(), []int{8}\n}", "func generateGoSchemaFile(schema map[string]interface{}, config Config) {\r\n var obj map[string]interface{}\r\n var schemas = make(map[string]interface{})\r\n var outString = \"package main\\n\\nvar schemas = `\\n\"\r\n\r\n var filename = config.Schemas.GoSchemaFilename\r\n var apiFunctions = config.Schemas.API\r\n var elementNames = config.Schemas.GoSchemaElements\r\n \r\n var functionKey = \"API\"\r\n var objectModelKey = \"objectModelSchemas\"\r\n \r\n schemas[functionKey] = interface{}(make(map[string]interface{}))\r\n schemas[objectModelKey] = interface{}(make(map[string]interface{}))\r\n\r\n fmt.Printf(\"Generate Go SCHEMA file %s for: \\n %s and: \\n %s\\n\", filename, apiFunctions, elementNames)\r\n\r\n // grab the event API functions for input\r\n for i := range apiFunctions {\r\n functionSchemaName := \"#/definitions/API/\" + apiFunctions[i]\r\n functionName := apiFunctions[i]\r\n obj = getObject(schema, functionSchemaName)\r\n if obj == nil {\r\n fmt.Printf(\"** WARN ** %s returned nil from getObject\\n\", functionSchemaName)\r\n return\r\n }\r\n schemas[functionKey].(map[string]interface{})[functionName] = obj \r\n } \r\n\r\n // grab the elements requested (these are useful separately even though\r\n // they obviously appear already as part of the event API functions)\r\n for i := range elementNames {\r\n elementName := elementNames[i]\r\n obj = getObject(schema, elementName)\r\n if obj == nil {\r\n fmt.Printf(\"** ERR ** %s returned nil from getObject\\n\", elementName)\r\n return\r\n }\r\n schemas[objectModelKey].(map[string]interface{})[elementName] = obj \r\n }\r\n \r\n // marshal for output to file \r\n schemaOut, err := json.MarshalIndent(&schemas, \"\", \" \")\r\n if err != nil {\r\n fmt.Printf(\"** ERR ** cannot marshal schema file output for writing\\n\")\r\n return\r\n }\r\n outString += string(schemaOut) + \"`\"\r\n ioutil.WriteFile(filename, []byte(outString), 0644)\r\n}", "func (*ConfigObject) Descriptor() ([]byte, []int) {\n\treturn file_config_v1_resources_proto_rawDescGZIP(), []int{0}\n}", "func (*CodeGeneratorResponse_File) Descriptor() ([]byte, []int) {\n\treturn file_google_protobuf_compiler_plugin_proto_rawDescGZIP(), []int{2, 0}\n}", "func (*ConfigResponse) Descriptor() ([]byte, []int) {\n\treturn file_config_devconfig_proto_rawDescGZIP(), []int{3}\n}", "func (*OutputConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_asset_v1_asset_service_proto_rawDescGZIP(), []int{13}\n}", "func main() {\r\n\r\n var configFileName = \"generate.json\"\r\n\r\n var api string\r\n var line = 1\r\n var lineOut = 1\r\n var offsets [5000]int\r\n \r\n // read the configuration from the json file\r\n filename, _ := filepath.Abs(\"./scripts/\" + configFileName)\r\n fmt.Printf(\"JSON CONFIG FILEPATH:\\n %s\\n\", filename)\r\n jsonFile, err := ioutil.ReadFile(filename)\r\n if err != nil {\r\n fmt.Println(\"error reading json file\")\r\n panic(err)\r\n }\r\n var config Config\r\n err = json.Unmarshal(jsonFile, &config)\r\n if err != nil {\r\n fmt.Println(\"error unmarshaling json config\")\r\n panic(err)\r\n }\r\n\r\n // read the schema file, stripping comments and blank lines, calculate offsets for error output\r\n file, err := os.Open(config.Schemas.SchemaFilename)\r\n if err != nil {\r\n fmt.Printf(\"** ERR ** [%s] opening schema file at %s\\n\", err, config.Schemas.SchemaFilename)\r\n return\r\n }\r\n defer file.Close()\r\n reader := bufio.NewReader(file)\r\n scanner := bufio.NewScanner(reader)\r\n scanner.Split(bufio.ScanLines)\r\n for scanner.Scan() {\r\n ts := strings.TrimSpace(scanner.Text()) \r\n if strings.HasPrefix(ts, \"#\") {\r\n fmt.Println(\"Line: \", line, \" is a comment\")\r\n } else if ts == \"\" {\r\n fmt.Println(\"Line: \", line, \" is blank\")\r\n } else {\r\n api += ts + \"\\n\"\r\n lineOut++\r\n }\r\n offsets[lineOut] = line\r\n line++\r\n }\r\n \r\n // verify the JSON format by unmarshaling it into a map\r\n\r\n var schema map[string]interface{}\r\n err = json.Unmarshal([]byte(api), &schema)\r\n if err != nil {\r\n fmt.Println(\"*********** UNMARSHAL ERR **************\\n\", err)\r\n printSyntaxError(api, &offsets, err)\r\n return\r\n }\r\n \r\n // Looks tricky, but simply creates an output with references resolved \r\n // from the schema, and another object and passes it back. I used to \r\n // call it for each object, but much simpler to call it once for the \r\n // whole schema and simply pick off the objects we want for subschemas\r\n // and samples.\r\n schema = replaceReferences(schema, schema).(map[string]interface{})\r\n \r\n // generate the Go files that the contract needs -- for now, complete schema and \r\n // event schema and sample object \r\n \r\n generateGoSchemaFile(schema, config)\r\n generateGoSampleFile(schema, config)\r\n \r\n // experimental\r\n //generateGoObjectModel(schema, config)\r\n \r\n // TODO generate js object model?? Java??\r\n \r\n}", "func TestGenerateConfigGoResource(t *testing.T) {\n\tconst (\n\t\toutFileName = \"configtemplate.go\"\n\t\tsourceFileName = \"testdata/config.yaml\"\n\t)\n\n\tif _, err := os.Stat(outFileName); !os.IsNotExist(err) {\n\t\tif b, _ := strconv.ParseBool(os.Getenv(\"GENERATE_CONFIG_TEMPLATE\")); !b {\n\t\t\tt.Skip(\"GENERATE_CONFIG_TEMPLATE is not set. Skipping template generation.\")\n\t\t\treturn\n\t\t}\n\t}\n\n\toutFile, err := os.Create(outFileName)\n\tassert.NoError(t, err)\n\n\tinFileData, err := ioutil.ReadFile(sourceFileName)\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write([]byte(\"package main\\n\"))\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write([]byte(\"// Generated content\\n\"))\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write([]byte(\"var templateConfigData = []byte(`\\n\"))\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write(inFileData)\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write([]byte(\"`)\\n\"))\n\tassert.NoError(t, err)\n}", "func (*OpenCensusConfig) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{0}\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_recordwants_proto_rawDescGZIP(), []int{0}\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_baseproto_proto_rawDescGZIP(), []int{0}\n}", "func (*MigrillianConfig) Descriptor() ([]byte, []int) {\n\treturn file_trillian_migrillian_configpb_config_proto_rawDescGZIP(), []int{2}\n}", "func loadConfig(file string) error {\n\tf, err := os.Open(file) // Open file\n\n\t// Error checking, returns error\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close() // Defer file closing to end of function\n\n\tdecoder := json.NewDecoder(f) // Create json decoder\n\terr = decoder.Decode(&cfg) // Decode the json into the config struct\n\n\t// Error checking\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func GenerateConfig(f string) error {\n\texists, err := pathExists(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif exists {\n\t\treturn errors.New(\"output config file already exists: \" + f)\n\t}\n\text := filepath.Ext(f)\n\n\tif len(ext) > 1 {\n\t\text = ext[1:]\n\t}\n\n\tsupportedExts := []string{\"json\", \"toml\", \"yaml\", \"yml\"}\n\n\tif !stringInSlice(ext, supportedExts) {\n\t\treturn errors.New(\"output config file must have one of supported extensions: \" + strings.Join(supportedExts, \", \"))\n\t}\n\n\tvar t *template.Template\n\n\tswitch ext {\n\tcase \"json\":\n\t\tt, err = template.New(\"config\").Parse(jsonConfigTemplate)\n\tcase \"toml\":\n\t\tt, err = template.New(\"config\").Parse(tomlConfigTemplate)\n\tcase \"yaml\", \"yml\":\n\t\tt, err = template.New(\"config\").Parse(yamlConfigTemplate)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar output bytes.Buffer\n\t_ = t.Execute(&output, struct {\n\t\tTokenSecret string\n\t\tAdminPassword string\n\t\tAdminSecret string\n\t\tAPIKey string\n\t}{\n\t\tuuid.New().String(),\n\t\tuuid.New().String(),\n\t\tuuid.New().String(),\n\t\tuuid.New().String(),\n\t})\n\n\treturn ioutil.WriteFile(f, output.Bytes(), 0644)\n}", "func (*ControllerConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_genomics_v1alpha2_pipelines_proto_rawDescGZIP(), []int{11}\n}", "func LoadConfig(client *ClientContext, filename string) {\n var config otgclient.SetConfigJSONRequestBody\n\n data, err := ioutil.ReadFile(filename)\n if (err != nil) {\n log.Fatal(\"failed reading data from %s: %s\\n\", filename, err)\n client.Error = err\n\treturn\n }\n\n myClient := client.Client\n ctx := client.Ctx\n\n _ = json.Unmarshal([]byte(data), &config)\n response, err := myClient.SetConfigWithResponse(ctx, config)\n\n client.Response = response\n client.Error = err\n return\n}", "func (*CommonExtensionConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_extensions_common_tap_v3_common_proto_rawDescGZIP(), []int{0}\n}", "func recupStructWithConfigFile(file string, debugFile string, debugLog bool) (config Config) {\n\n\t// check if file exists\n\te, err := os.Stat(file)\n\tif err != nil {\n\t\tfmt.Println(\"config file not found\")\n\t\tutils.StopApp()\n\t}\n\tDebugPrint(debugFile, debugLog, \"DEBUG: \", \"File opened : \"+e.Name())\n\n\t// open the file\n\tf, _ := os.Open(file)\n\tdefer f.Close()\n\n\t// read the file contents\n\tbyteValue, _ := ioutil.ReadAll(f)\n\n\t// unmarshal the file's content and save to config variable\n\tjson.Unmarshal(byteValue, &config)\n\n\treturn\n}", "func (*PullRequestConfig) Descriptor() ([]byte, []int) {\n\treturn file_config_proto_rawDescGZIP(), []int{2}\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_config_proto_rawDescGZIP(), []int{0}\n}", "func (*PolitenessConfig) Descriptor() ([]byte, []int) {\n\treturn file_config_v1_resources_proto_rawDescGZIP(), []int{13}\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_fleetspeak_src_client_daemonservice_proto_fleetspeak_daemonservice_config_proto_rawDescGZIP(), []int{0}\n}", "func (*SinkConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_extensions_stat_sinks_open_telemetry_v3_open_telemetry_proto_rawDescGZIP(), []int{0}\n}", "func protoNPMRuntimeLibraryToNPMRuntimeDependency(config *registryv1alpha1.NPMConfig_RuntimeLibrary) *bufpluginconfig.NPMRegistryDependencyConfig {\n\treturn &bufpluginconfig.NPMRegistryDependencyConfig{\n\t\tPackage: config.Package,\n\t\tVersion: config.Version,\n\t}\n}", "func getConfigFromFile(fileName string) (config *BotConfig, err error) {\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn config, err\n}", "func (*OIDCConfig) Descriptor() ([]byte, []int) {\n\treturn file_management_proto_rawDescGZIP(), []int{100}\n}", "func (*UdpProxyConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_filter_udp_udp_proxy_v2alpha_udp_proxy_proto_rawDescGZIP(), []int{0}\n}", "func (*Validator) Descriptor() ([]byte, []int) {\n\treturn file_github_com_google_cloudprober_validators_http_proto_config_proto_rawDescGZIP(), []int{0}\n}", "func TestSnapshotWithCcStaticNocrtBinary(t *testing.T) {\n\tresult := testSdkWithCc(t, `\n\t\tmodule_exports {\n\t\t\tname: \"mymodule_exports\",\n\t\t\thost_supported: true,\n\t\t\tdevice_supported: false,\n\t\t\tnative_binaries: [\"linker\"],\n\t\t}\n\n\t\tcc_binary {\n\t\t\tname: \"linker\",\n\t\t\thost_supported: true,\n\t\t\tstatic_executable: true,\n\t\t\tnocrt: true,\n\t\t\tstl: \"none\",\n\t\t\tsrcs: [\n\t\t\t\t\"Test.cpp\",\n\t\t\t],\n\t\t\tcompile_multilib: \"both\",\n\t\t}\n\t`)\n\n\tCheckSnapshot(t, result, \"mymodule_exports\", \"\",\n\t\tcheckUnversionedAndroidBpContents(`\n// This is auto-generated. DO NOT EDIT.\n\ncc_prebuilt_binary {\n name: \"linker\",\n prefer: false,\n visibility: [\"//visibility:public\"],\n apex_available: [\"//apex_available:platform\"],\n device_supported: false,\n host_supported: true,\n stl: \"none\",\n compile_multilib: \"both\",\n static_executable: true,\n nocrt: true,\n target: {\n host: {\n enabled: false,\n },\n linux_glibc_x86_64: {\n enabled: true,\n srcs: [\"x86_64/bin/linker\"],\n },\n linux_glibc_x86: {\n enabled: true,\n srcs: [\"x86/bin/linker\"],\n },\n },\n}\n`),\n\t\tcheckVersionedAndroidBpContents(`\n// This is auto-generated. DO NOT EDIT.\n\ncc_prebuilt_binary {\n name: \"mymodule_exports_linker@current\",\n sdk_member_name: \"linker\",\n visibility: [\"//visibility:public\"],\n apex_available: [\"//apex_available:platform\"],\n device_supported: false,\n host_supported: true,\n installable: false,\n stl: \"none\",\n compile_multilib: \"both\",\n static_executable: true,\n nocrt: true,\n target: {\n host: {\n enabled: false,\n },\n linux_glibc_x86_64: {\n enabled: true,\n srcs: [\"x86_64/bin/linker\"],\n },\n linux_glibc_x86: {\n enabled: true,\n srcs: [\"x86/bin/linker\"],\n },\n },\n}\n\nmodule_exports_snapshot {\n name: \"mymodule_exports@current\",\n visibility: [\"//visibility:public\"],\n device_supported: false,\n host_supported: true,\n native_binaries: [\"mymodule_exports_linker@current\"],\n target: {\n host: {\n enabled: false,\n },\n linux_glibc_x86_64: {\n enabled: true,\n },\n linux_glibc_x86: {\n enabled: true,\n },\n },\n}\n`),\n\t\tcheckAllCopyRules(`\n.intermediates/linker/linux_glibc_x86_64/linker -> x86_64/bin/linker\n.intermediates/linker/linux_glibc_x86/linker -> x86/bin/linker\n`),\n\t)\n}", "func (*TLSConfig) Descriptor() ([]byte, []int) {\n\treturn file_github_com_cloudprober_cloudprober_common_tlsconfig_proto_config_proto_rawDescGZIP(), []int{0}\n}", "func readConfig(configfile string) (map[string]*json.RawMessage, error) {\n\n\tvar (\n\t\tfile []byte\n\t\tobjmap map[string]*json.RawMessage\n\t\terr error\n\t)\n\n\tfile, err = ioutil.ReadFile(configfile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlines := strings.Split(string(file), \"\\n\")\n\tvar jdata []byte\n\tfor _, line := range lines {\n\t\tif !strings.HasPrefix(strings.TrimSpace(line), \"//\") {\n\t\t\tjdata = append(jdata, []byte(line+\"\\n\")...)\n\t\t}\n\t}\n\n\terr = json.Unmarshal(jdata, &objmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn objmap, nil\n}", "func (*CommonExtensionConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_extensions_common_tap_v4alpha_common_proto_rawDescGZIP(), []int{0}\n}", "func (*ClientOAuthConfiguration) Descriptor() ([]byte, []int) {\n\treturn file_pkg_proto_configuration_grpc_grpc_proto_rawDescGZIP(), []int{2}\n}", "func (*EmbeddedFilePayload) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{43}\n}", "func (*Label) Descriptor() ([]byte, []int) {\n\treturn file_config_v1_resources_proto_rawDescGZIP(), []int{2}\n}", "func MavenRuntimeConfigToProtoRuntimeConfig(runtime bufpluginconfig.MavenRuntimeConfig) *registryv1alpha1.MavenConfig_RuntimeConfig {\n\tvar libraries []*registryv1alpha1.MavenConfig_RuntimeLibrary\n\tfor _, dependency := range runtime.Deps {\n\t\tlibraries = append(libraries, MavenDependencyConfigToProtoRuntimeLibrary(dependency))\n\t}\n\treturn &registryv1alpha1.MavenConfig_RuntimeConfig{\n\t\tName: runtime.Name,\n\t\tRuntimeLibraries: libraries,\n\t\tOptions: runtime.Options,\n\t}\n}", "func (*RaftConfigurationProto) Descriptor() ([]byte, []int) {\n\treturn file_raft_proto_rawDescGZIP(), []int{4}\n}", "func (*RaftConfigPB) Descriptor() ([]byte, []int) {\n\treturn file_yb_common_consensus_metadata_proto_rawDescGZIP(), []int{1}\n}", "func protoLoader() interpreter.Loader {\n\tmapping := make(map[string]string, len(publicProtos))\n\tfor path, proto := range publicProtos {\n\t\tmapping[path] = proto.goPath\n\t}\n\treturn interpreter.ProtoLoader(mapping)\n}", "func loadConfig(configFile string) *utils.Config {\n\tconf := &utils.Config{}\n\tif _, err := toml.DecodeFile(configFile, &conf); err != nil {\n\t\tfmt.Println(err)\n\t}\n\treturn conf\n}", "func LoadConfig(conf interface{}, filename string) (err error) {\n\tvar decoder *json.Decoder\n\tfile := OpenFile(conf, filename)\n\tdefer file.Close()\n\tdecoder = json.NewDecoder(file)\n\tif err = decoder.Decode(conf); err != nil {\n\t\treturn\n\t}\n\tjson.Marshal(&conf)\n\treturn\n}", "func (*DatadogConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_trace_v3_datadog_proto_rawDescGZIP(), []int{0}\n}", "func main() {\n\tdata, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\tlog.Fatalln(err, \"reading input\")\n\t}\n\n\tvar request plugin.CodeGeneratorRequest\n\tif err := proto.Unmarshal(data, &request); err != nil {\n\t\tlog.Fatalln(err, \"parsing input proto\")\n\t}\n\n\tif len(request.FileToGenerate) == 0 {\n\t\tlog.Fatalln(\"no files to generate\")\n\t}\n\n\trequestJSON, err := json.MarshalIndent(request, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tvar response plugin.CodeGeneratorResponse\n\tresponse.File = append(response.File, &plugin.CodeGeneratorResponse_File{\n\t\tName: proto.String(\"raw.json\"),\n\t\tContent: proto.String(string(requestJSON)),\n\t})\n\n\tdata, err = proto.Marshal(&response)\n\tif err != nil {\n\t\tlog.Fatalln(err, \"failed to marshal output proto\")\n\t}\n\n\t_, err = os.Stdout.Write(data)\n\tif err != nil {\n\t\tlog.Fatalln(err, \"failed to write output proto\")\n\t}\n}", "func (*PeriodicJobConfig) Descriptor() ([]byte, []int) {\n\treturn file_external_applications_applications_proto_rawDescGZIP(), []int{10}\n}", "func (*AgentConfiguration) Descriptor() ([]byte, []int) {\n\treturn file_pkg_pb_protobuf_api_proto_rawDescGZIP(), []int{27}\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_app_log_config_proto_rawDescGZIP(), []int{1}\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_githubcard_proto_rawDescGZIP(), []int{2}\n}" ]
[ "0.52065396", "0.52007353", "0.51941204", "0.51577306", "0.5107777", "0.5025856", "0.49242315", "0.48540878", "0.48468336", "0.47196868", "0.47193876", "0.4700907", "0.46915385", "0.46912202", "0.4678856", "0.46544382", "0.46082795", "0.45997837", "0.45863217", "0.4579745", "0.4576471", "0.4576258", "0.45617834", "0.45576525", "0.45402718", "0.45344943", "0.4520351", "0.45036113", "0.45018938", "0.4500345", "0.44968498", "0.4475281", "0.4472735", "0.447148", "0.44713545", "0.4457274", "0.44569662", "0.4447007", "0.44467515", "0.44379863", "0.4436904", "0.44325334", "0.44180185", "0.4417036", "0.44074365", "0.44065973", "0.44020838", "0.44004807", "0.43970248", "0.43945122", "0.43930104", "0.43847814", "0.4384222", "0.43838587", "0.4380552", "0.43744045", "0.43703777", "0.43695602", "0.43687463", "0.43655995", "0.43650764", "0.43640578", "0.43603978", "0.43575937", "0.4357013", "0.435537", "0.4353331", "0.43529", "0.43526354", "0.43368378", "0.4334114", "0.43340343", "0.43319446", "0.43283895", "0.432578", "0.43188164", "0.43181866", "0.4314372", "0.43132532", "0.43122783", "0.43120098", "0.43076563", "0.43034375", "0.43028268", "0.43027967", "0.43023977", "0.4302069", "0.4295221", "0.42924264", "0.429208", "0.4287083", "0.42859265", "0.42857105", "0.42855707", "0.4284058", "0.42834878", "0.428336", "0.42824516", "0.42822155", "0.42813185" ]
0.48850825
7
NewTree creates a new Tree.
func NewTree(options *Options) *Tree { if options == nil { options = new(Options) } setDefaultOptions(options) idx := &Tree{ newBlocks: make(chan int), done: make(chan bool), blockMap: make(map[int]int), manager: newEpochManager(options.NumAllocators), } idx.allocators = make([]*Allocator, options.NumAllocators) idx.allocatorQueue = newSlots(len(idx.allocators)) for i := range idx.allocators { idx.allocators[i] = newAllocator(idx, i, blockSize, idx.newBlocks) } go idx.blockAllocator() return idx }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewTree() *Tree {\n\treturn &Tree{Symbol{NIL, \"NewTree holder\"}, make([]*Tree, 0, maxChildren), nil}\n}", "func NewTree() *Tree {\n\treturn new(Tree)\n}", "func NewTree() *Tree {\n\treturn &Tree{&bytes.Buffer{}}\n}", "func New() *Tree {\n\treturn &Tree{}\n}", "func New(name string) *Tree {\n\treturn &Tree{\n\t\tName: name,\n\t}\n}", "func NewTree(c *Config) *Tree {\n\treturn &Tree{c: c}\n}", "func NewTree() *Tree {\n\treturn &Tree{\n\t\trnd: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n}", "func NewTree() *Tree {\n\treturn &Tree{\n\t\tBlock: *NewBlock(),\n\t\tTextStyle: Theme.Tree.Text,\n\t\tSelectedRowStyle: Theme.Tree.Text,\n\t\tWrapText: true,\n\t}\n}", "func New(name string) *Tree {\n\ttr := new(Tree)\n\ttr.Name = name\n\treturn tr\n}", "func New() *Tree {\n\treturn &Tree{\n\t\tDelimiter: DefaultDelimiter,\n\t\tFormatter: SimpleFormatter,\n\t\tErrors: make(map[string]error),\n\t}\n}", "func New() *Tree {\n\treturn &Tree{root: &node{}}\n}", "func New(name string) *Tree {\n\treturn &Tree{name: name, root: &Node{}, mtx: &sync.RWMutex{}}\n}", "func NewTree(n *node) (*Tree, error) {\n\treturn &Tree{\n\t\troot: n,\n\t\tvalues: map[string]*node{n.value: n},\n\t}, nil\n}", "func NewTree(pattern string, handlers []baa.HandlerFunc) *Tree {\n\tif pattern == \"\" {\n\t\tpanic(\"tree.new: pattern can be empty\")\n\t}\n\treturn &Tree{\n\t\tstatic: true,\n\t\talpha: pattern[0],\n\t\tpattern: pattern,\n\t\tformat: []byte(pattern),\n\t\thandlers: handlers,\n\t}\n}", "func NewTree(width int, company string) *Tree {\n\theight := width / 2\n\n\tleaves := make([][]string, height)\n\n\tfor i := 0; i < height; i++ {\n\t\tleaves[i] = newLevelLeaves(width, \" \")\n\t\tif i == 0 {\n\t\t\tleaves[i][width/2] = \"★\"\n\t\t\tcontinue\n\t\t}\n\n\t\tleaves[i][height-i] = \"/\"\n\t\tleaves[i][height+i] = \"\\\\\"\n\t\tfor j := (height - i + 1); j < height+i; j++ {\n\t\t\tleaves[i][j] = leafContent()\n\t\t}\n\t}\n\n\tleaves = append(leaves, bottomLeaves(width, \"^\"), bottomLeaves(width, \" \"))\n\n\treturn &Tree{\n\t\tleaves: leaves,\n\t\tcompany: company,\n\t}\n}", "func NewTree(repo *Repository, id SHA1) *Tree {\n\treturn &Tree{\n\t\tID: id,\n\t\trepo: repo,\n\t}\n}", "func New(opts ...TreeOption) *Tree {\n\tt := &Tree{}\n\tfor _, opt := range opts {\n\t\topt(t)\n\t}\n\tt.init()\n\treturn t\n}", "func NewTree(path string, withFiles bool) Tree {\n\tfiles, err := ioutil.ReadDir(path)\n\tif err != nil {\n\t\treturn nil\n\t}\n\troot := newNode(path, true, buildTree(path, files, withFiles))\n\treturn &tree{\n\t\troot: root,\n\t}\n}", "func New() Tree {\n\treturn &Node{Value: \".\"}\n}", "func NewTree(childs Childs) *Quadtree {\n\tqt, ok := nodeMap[childs]\n\tif ok {\n\t\tcacheHit++\n\t\treturn qt\n\t}\n\tcacheMiss++\n\tqt = &Quadtree{childs.NE.Level + 1, childs, childs.population(), nil}\n\tif qt.Population == 0 || qt.Level <= 16 {\n\t\tnodeMap[childs] = qt\n\t}\n\treturn qt\n}", "func NewTree() InfluenceTree {\n\treturn InfluenceTree{ID: RootTree.ID}\n}", "func NewTree(depth int) *Tree {\n\tif depth > 0 {\n\t\treturn &Tree{Left: NewTree(depth - 1), Right: NewTree(depth - 1)}\n\t} else {\n\t\treturn &Tree{}\n\t}\n}", "func (t *Tree) NewTreeNode(parent *TreeNode, step Step, pass bool, side Value, first bool) *TreeNode {\n\te := &TreeNode{\n\t\tt: t,\n\t\tside: side,\n\t\tstep: step,\n\t\tpass: pass,\n\t\tparent: parent,\n\t\tpolicy: policyPool.Get().([]float32),\n\t\tfirst: first,\n\t}\n\treturn e\n}", "func NewTree(db *badger.Storage, root []byte) *Tree {\n\tt := &Tree{\n\t\tdb: newTreeDb(db),\n\t}\n\tt.cache = lru.NewCache(2048)\n\tvar zero [32]byte\n\tif root != nil && len(root) == int(32) && bytes.Compare(root, zero[:]) > common.Zero {\n\t\tt.root = t.mustLoadNode(root)\n\t}\n\n\tif err := FileExist(); err == nil {\n\t\tt.BackCommit()\n\t}\n\n\treturn t\n}", "func NewTree(prefix, delimiter string) *Node {\n\treturn &Node{\n\t\tname: prefix,\n\t\tdelimiter: delimiter,\n\t\tnodes: make(map[string]*Node),\n\t}\n}", "func NewTree(depth int) ITree {\n\tt := &Tree{\n\t\tdepth: depth,\n\t\trootNode: &node{},\n\t}\n\n\treturn t\n}", "func NewTree() *BPTree {\n\treturn &BPTree{LastAddress: 0, keyPosMap: make(map[string]int64), enabledKeyPosMap: false}\n}", "func NewTree(cs []Content) (*MerkleTree, error) {\n\troot, leafs, err := buildWithContent(cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &MerkleTree{\n\t\tRoot: root,\n\t\tmerkleRoot: root.Hash,\n\t\tLeafs: leafs,\n\t}\n\treturn t, nil\n}", "func NewTree(index uint8) *RBTree {\n\tvar rbTree = &RBTree{\n\t\troot: nil,\n\t\tmLeft: nil,\n\t\tmRight: nil,\n\t\tSize: 0,\n\t\tIndex: index,\n\t}\n\treturn rbTree\n}", "func (f *Forest) New(d *crypto.Digest, l uint32) *Tree {\n\tt := &Tree{\n\t\tleaves: l,\n\t\tdig: d,\n\t\tf: f,\n\t\tlastBlockLen: BlockSize,\n\t\tleavesComplete: make([]bool, l),\n\t}\n\tf.writeTree(t)\n\treturn t\n}", "func NewTree(cs []Content) (*MerkleTree, error) {\n\tvar defaultHashStrategy = \"sha256\"\n\tt := &MerkleTree{\n\t\tHashStrategy: defaultHashStrategy,\n\t}\n\troot, leafs, err := buildWithContent(cs, t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt.Root = root\n\tt.Leafs = leafs\n\tt.MerkleRoot = root.Hash\n\treturn t, nil\n}", "func New(options ...TreeOpt) (*Tree, error) {\n\ttmp := tree{obj: Tree{\n\t\talgorithm: hash.Default,\n\t\tmaxLevel: defaultMaxLevel,\n\t}}\n\n\tfor _, setter := range options {\n\t\tif err := tmp.setOption(setter); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &tmp.obj, nil\n}", "func NewTreeNode(name string, sum float64) *TreeNode {\n\treturn &TreeNode{\n\t\tName: name,\n\t\tTotal: sum,\n\t\tChildren: make(map[string]*TreeNode),\n\t}\n}", "func NewTree(fs []SymbolFreq) Tree {\n\t// Sort frequencies\n\tsort.Sort(byFreq(fs))\n\n\twrkList := []node{}\n\tfor _, f := range fs {\n\t\twrkList = append(wrkList, f)\n\t}\n\n\tfor {\n\t\tif len(wrkList) < 2 {\n\t\t\tbreak\n\t\t}\n\n\t\tnewNode := makeNewNode(wrkList[0], wrkList[1])\n\n\t\twrkList = insertItem(wrkList[2:], newNode)\n\t}\n\n\treturn Tree{wrkList[0]}\n}", "func New() *binaryTree {\n\treturn CreateDefaultTree()\n}", "func newTreeNode(parent *treeNode, move Move, state GameState, ucbC float64) *treeNode {\n\t// Construct the new node.\n\tnode := treeNode{\n\t\tparent: parent,\n\t\tmove: move,\n\t\tstate: state,\n\t\ttotalOutcome: 0.0, // No outcome yet.\n\t\tvisits: 0, // No visits yet.\n\t\tuntriedMoves: state.AvailableMoves(), // Initially the node starts with every node unexplored.\n\t\tchildren: nil, // No children yet.\n\t\tucbC: ucbC, // Whole tree uses same constant.\n\t\tselectionScore: 0.0, // No value yet.\n\t\tplayer: state.PlayerJustMoved(),\n\t}\n\n\t// We're working with pointers.\n\treturn &node\n}", "func (treeNode *TreeNode) New(node Item) (*TreeNode, error) {\n\tif treeNode != nil {\n\t\treturn nil, errors.New(\"treeNode must be nil\")\n\t}\n\ttreeNode = &TreeNode{\n\t\tLeft: nil,\n\t\tRight: nil,\n\t\tValue: node,\n\t}\n\treturn treeNode, nil\n}", "func NewTree(n int) *Tree {\n\treturn &Tree{\n\t\tn: n,\n\t\tbit: make([]int, n+1),\n\t}\n}", "func NewTree(r RuleHandle) (*Tree, error) {\n\tif r.Detection == nil {\n\t\treturn nil, ErrMissingDetection{}\n\t}\n\texpr, ok := r.Detection[\"condition\"].(string)\n\tif !ok {\n\t\treturn nil, ErrMissingCondition{}\n\t}\n\n\tp := &parser{\n\t\tlex: lex(expr),\n\t\tcondition: expr,\n\t\tsigma: r.Detection,\n\t\tnoCollapseWS: r.NoCollapseWS,\n\t}\n\tif err := p.run(); err != nil {\n\t\treturn nil, err\n\t}\n\tt := &Tree{\n\t\tRoot: p.result,\n\t\tRule: &r,\n\t}\n\treturn t, nil\n}", "func NewTreeNode(d int) *TreeNode {\n\treturn &TreeNode{\n\t\tdata: d,\n\t\tsize: 1,\n\t}\n}", "func NewNode(name string) TreeNode {\n\treturn TreeNode{\n\t\tname: name,\n\t\tsize: 0,\n\t\tfiles: make(map[string]Entry),\n\t}\n}", "func New() *VersionTree {\n\treturn &VersionTree{}\n}", "func NewTree(rootName string, builder caching.TreeBuilder, updater caching.TreeUpdater,\n\tlocker caching.Locker) (*Tree, error) {\n\troot := &caching.Node{\n\t\tName: rootName,\n\t\tLeaf: false,\n\t\tSize: int64(0),\n\t\tChildren: []*caching.Node{},\n\t}\n\n\tnodes := map[string]*caching.Node{rootName: root}\n\ttree := &Tree{\n\t\tRootName: rootName,\n\t\tnodes: nodes,\n\t\tbuilder: builder,\n\t\tupdater: updater,\n\t\tlocker: locker,\n\t\tBulkUpdates: 100,\n\t\tUpdateRoutines: 10,\n\t}\n\terr := tree.AddNode(rootName, root)\n\treturn tree, err\n}", "func NewObjectTree(flags byte) *ObjectTree { return new(ObjectTree).Init(flags) }", "func newDemoTree() TreeRoot {\n\tn1 := newNode(1)\n\n\tn2 := newNode(2)\n\tn1.Left = n2\n\n\tn3 := newNode(3)\n\tn1.Right = n3\n\n\tn4 := newNode(4)\n\tn2.Left = n4\n\n\tn5 := newNode(5)\n\tn2.Right = n5\n\n\tn6 := newNode(6)\n\tn3.Left = n6\n\n\tn7 := newNode(7)\n\tn3.Right = n7\n\n\tn8 := newNode(8)\n\tn4.Left = n8\n\n\tn9 := newNode(9)\n\tn4.Right = n9\n\n\tn10 := newNode(10)\n\tn5.Left = n10\n\n\tn11 := newNode(11)\n\tn5.Right = n11\n\n\tn12 := newNode(12)\n\tn6.Left = n12\n\n\tn13 := newNode(13)\n\tn6.Right = n13\n\n\tn14 := newNode(14)\n\tn7.Left = n14\n\n\tn15 := newNode(15)\n\tn7.Right = n15\n\n\tn16 := newNode(16)\n\tn14.Left = n16\n\n\tn17 := newNode(17)\n\tn14.Right = n17\n\n\treturn n1\n}", "func NewBinaryTree() *BinaryTree {\n\treturn &BinaryTree{}\n}", "func New(ctx context.Context, client *http.Client, projectName string) (*tree.FS, error) {\n\tp, err := newGithubProject(ctx, client, projectName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstart := time.Now()\n\tt, err := p.getTree(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"Loaded project with %d files in %.1fs\", len(t), time.Now().Sub(start).Seconds())\n\treturn tree.NewFS(t), nil\n}", "func NewTree(id string, cache storage.Cache, leaves storage.Store, hasher hashing.Hasher) *Tree {\n\n\tcacheLevels := int(math.Max(0.0, math.Floor(math.Log(float64(cache.Size()))/math.Log(2.0))))\n\tdigestLength := len(hasher([]byte(\"a test event\"))) * 8\n\n\ttree := &Tree{\n\t\t[]byte(id),\n\t\tleafHasherF(hasher),\n\t\tinteriorHasherF(hasher),\n\t\tmake([][]byte, digestLength),\n\t\tcache,\n\t\tleaves,\n\t\tnew(stats),\n\t\tnewArea(digestLength-cacheLevels, digestLength),\n\t\tdigestLength,\n\t\tnil,\n\t}\n\n\t// init default hashes cache\n\ttree.defaultHashes[0] = hasher(tree.id, Empty)\n\tfor i := 1; i < int(digestLength); i++ {\n\t\ttree.defaultHashes[i] = hasher(tree.defaultHashes[i-1], tree.defaultHashes[i-1])\n\t}\n\ttree.ops = tree.operations()\n\n\treturn tree\n}", "func NewTree(from []int) *Tree {\n\ttreeSize := calcTreeSize(len(from))\n\tnodes := make([]int, treeSize)\n\n\tt := &Tree{nodes, len(from)}\n\tt.build(from, 0, 0, len(from)-1)\n\n\treturn t\n}", "func NewTreeNode(role Role) *TreeNode {\n\treturn &TreeNode{\n\t\tRole: role,\n\t\tUsers: make(map[int]*User),\n\t\tSubordinates: []*TreeNode{},\n\t}\n}", "func newTree(segmentSize, maxsize, depth int, hashfunc func() hash.Hash) *tree {\n\tn := newNode(0, nil, hashfunc())\n\tprevlevel := []*node{n}\n\t// iterate over levels and creates 2^(depth-level) nodes\n\t// the 0 level is on double segment sections so we start at depth - 2\n\tcount := 2\n\tfor level := depth - 2; level >= 0; level-- {\n\t\tnodes := make([]*node, count)\n\t\tfor i := 0; i < count; i++ {\n\t\t\tparent := prevlevel[i/2]\n\t\t\tnodes[i] = newNode(i, parent, hashfunc())\n\t\t}\n\t\tprevlevel = nodes\n\t\tcount *= 2\n\t}\n\t// the datanode level is the nodes on the last level\n\treturn &tree{\n\t\tleaves: prevlevel,\n\t\tbuffer: make([]byte, maxsize),\n\t}\n}", "func New() Tree {\n\treturn &binarySearchTree{}\n}", "func NewBSTree() *BSTree {\n\tb := &BSTree{\n\t\tleft: &BSTree{},\n\t\tright: &BSTree{},\n\t}\n\treturn b\n}", "func New(boundary *AABB, depth int, parent *QuadTree) *QuadTree {\n\treturn &QuadTree{\n\t\tboundary: boundary,\n\t\tdepth: depth,\n\t\tparent: parent,\n\t}\n}", "func New(r io.Reader) (*Tree, error) {\n\tn, err := html.Parse(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif n == nil {\n\t\treturn nil, fmt.Errorf(\"Error parsing html from reader\")\n\t}\n\treturn &Tree{n}, nil\n}", "func TreeStoreNew(types ...glib.Type) *TreeStore {\n\tgtypes := C.alloc_types(C.int(len(types)))\n\tfor n, val := range types {\n\t\tC.set_type(gtypes, C.int(n), C.GType(val))\n\t}\n\tdefer C.g_free(C.gpointer(gtypes))\n\tc := C.gtk_tree_store_newv(C.gint(len(types)), gtypes)\n\treturn wrapTreeStore(unsafe.Pointer(c))\n}", "func New(dgree int, ctx interface{}) *BTree {\n\treturn NewWithFreeList(degree, NewFreeList(DefaultFreeListSize), ctx)\n}", "func New(k int) *Tree {\n\tvar t *Tree\n\tfor _, v := range []int{6, 4, 5, 2, 9, 8, 7, 3, 1} {\n\t\tt = insert(t, v)\n\t}\n\treturn t\n}", "func NewWith(comparator utils.Comparator) *Tree {\n\treturn &Tree{Comparator: comparator}\n}", "func New() *RBTree {\n\treturn &RBTree{\n\t\tlock: sync.RWMutex{},\n\t\tNode: nil,\n\t\tstack: newStack(nil),\n\t}\n}", "func NewNode(tleft *BTree, tright *BTree, val int) BTree {\n\treturn &treeNode{\n\t\tval: val,\n\t\tleft: tleft,\n\t\tright: tright,\n\t}\n}", "func New() *RedBlackTree {\n\treturn &RedBlackTree{root: nil, size:0}\n}", "func NewBinaryTree(vals ...interface{}) (res *BinaryTreeNode, err error) {\n\tif len(vals) == 0 {\n\t\treturn nil, ErrEmptyInput\n\t}\n\tif res, err = createNode(vals[0]); err != nil {\n\t\treturn\n\t}\n\terr = buildTree([]*BinaryTreeNode{res}, 1, vals)\n\treturn\n}", "func New() *Tree23 {\n\treturn NewCapacity(1)\n}", "func New(hashFunc func(i interface{}) int64) *rbTree {\n\treturn &rbTree{hashFunc: hashFunc}\n}", "func NewBinaryTree() *BinaryTree {\n\tvar t BinaryTree\n\treturn &t\n}", "func (collection *Collection) NewGameTree() (*GameTree, *Node) {\n\tgameTree := &GameTree{}\n\tcollection.AddGameTree(gameTree)\n\tnode := gameTree.NewNode()\n\treturn gameTree, node\n}", "func NewBinaryTree(vals []Comparable) *BinaryTree {\n\treturn new(BinaryTree).Init(vals)\n}", "func New() *TreeMap { return new(TreeMap) }", "func (gameTree *GameTree) NewGameTree() (*GameTree, *Node) {\n\tnewGameTree := &GameTree{}\n\tgameTree.AddGameTree(newGameTree)\n\tnode := newGameTree.NewNode()\n\treturn newGameTree, node\n}", "func NewBST() *BSTree {\n\treturn &BSTree{nil}\n}", "func BTreeCreate(t int) *BTree {\n\t// create null node to use as place filler\n\tnullNode := &BTreeNode{}\n\tfor i := 0; i < 2*t; i++ {\n\t\tnullNode.children = append(nullNode.children, nullNode)\n\t}\n\n\t// create the tree\n\ttree := BTree{\n\t\tt: t,\n\t\tnullNode: nullNode,\n\t}\n\n\t// create root node\n\tx := tree.AllocateNode()\n\tx.leaf = true\n\ttree.root = x\n\n\t// create null node used to auto-populate children of newly allocated nodes\n\ttree.nullNode = tree.AllocateNode()\n\n\t// *Here is where we'd write the new node to disk\n\treturn &tree\n}", "func NewBTree(\n\tctx context.Context,\n\tobjStore *objstore.ObjectStore,\n\tencConf pbobject.EncryptionConfig,\n) (*BTree, error) {\n\trootNode := &Node{}\n\trootNode.Leaf = true\n\trootRef, _, err := objStore.StoreObject(ctx, rootNode, encConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbt := &BTree{\n\t\tobjStore: objStore,\n\t\tencConf: encConf,\n\t\tfreeList: sync.Pool{New: func() interface{} { return &Node{} }},\n\t}\n\n\trootMemNod := bt.newNode()\n\trootMemNod.node = rootNode\n\tbt.root = rootMemNod\n\n\trootNod := &Root{\n\t\tRootNodeRef: rootRef,\n\t}\n\trootNodRef, _, err := objStore.StoreObject(ctx, rootNod, encConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbt.rootNod = rootNod\n\tbt.rootNodRef = rootNodRef\n\n\treturn bt, nil\n}", "func NewString() *Tree {\n\ttree := &Tree{\n\t\tdatatype: containers.StringContainer(\"A\"),\n\t}\n\t// The below handling is required to achieve method overriding.\n\t// Refer: https://stackoverflow.com/questions/38123911/golang-method-override\n\ttree.TreeOperations = interface{}(tree).(binarytrees.TreeOperations)\n\treturn tree\n}", "func newAlohaTree(t *testing.T, db dbm.DB) (*iavl.MutableTree, types.CommitID) {\n\tt.Helper()\n\ttree := iavl.NewMutableTree(db, cacheSize, false, log.NewNopLogger())\n\n\tfor k, v := range treeData {\n\t\t_, err := tree.Set([]byte(k), []byte(v))\n\t\trequire.NoError(t, err)\n\t}\n\n\tfor i := 0; i < nMoreData; i++ {\n\t\tkey := randBytes(12)\n\t\tvalue := randBytes(50)\n\t\t_, err := tree.Set(key, value)\n\t\trequire.NoError(t, err)\n\t}\n\n\thash, ver, err := tree.SaveVersion()\n\trequire.Nil(t, err)\n\n\treturn tree, types.CommitID{Version: ver, Hash: hash}\n}", "func NewQuadTree(leftX, rightX, topY, bottomY float64, leafAllocation int64) T {\n\tvar newView = NewViewP(leftX, rightX, topY, bottomY)\n\treturn newRoot(newView, leafAllocation)\n}", "func (up *Uploader) NewTreeUpload(dir string) *TreeUpload {\n\treturn &TreeUpload{\n\t\tbase: dir,\n\t\tup: up,\n\t\tdonec: make(chan bool, 1),\n\t\terrc: make(chan error, 1),\n\t\tstattedc: make(chan *node, buffered),\n\t}\n}", "func CreateTree(parties []int, B int, lambda int) []Node {\n\tnodes := make([]Node, (2*B)-1) //create length based on B\n\tfor i := 0; i < len(nodes); i++ {\n\t\tpath, nonces := CreatePath(parties, int(math.Pow(math.Log2(float64(lambda)), 2))) //use path for each node\n\t\tnodes[i].Path = path\n\t\tnodes[i].Nonces = nonces\n\t\t//assigns nodes\n\t}\n\tfactor := 0 //this makes the right parent index\n\tpivotNode := CalculatePivotNode(B)\n\tfor i := 0; i < pivotNode; i++ {\n\t\tnodes[i].Parent = &nodes[B+factor] //so the parent is the right node, and last is null\n\t\tif i%2 == 1 {\n\t\t\tfactor += 1\n\t\t}\n\t}\n\treturn nodes\n\n}", "func NewTreeCommand() cli.Command {\n\treturn cli.Command{\n\t\tName: \"tree\",\n\t\tUsage: \"List directory as a tree\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.BoolFlag{Name: \"sort\", Usage: \"returns result in sorted order\"},\n\t\t},\n\t\tAction: func(c *cli.Context) error {\n\t\t\ttreeCommandFunc(c)\n\t\t\treturn nil\n\t\t},\n\t}\n}", "func CreateTreeNode(e DataType) *TreeNode {\n\tnewTreeNode := TreeNode{\n\t\tdata: e,\n\t\tleftChild: nil,\n\t\trightChild: nil,\n\t}\n\treturn &newTreeNode\n}", "func NewFromString(s string) (*Tree, error) {\n\treturn New(strings.NewReader(s))\n}", "func NewDNFTree(nbvar int) *DNFTree {\n\treturn &DNFTree{Content: nil, Nbvar: nbvar}\n}", "func New(db Databaser) *TreeURLs {\n\tvar t *TreeURLs\n\trouter := mux.NewRouter()\n\tt = &TreeURLs{\n\t\tdb: db,\n\t\trouter: router,\n\t}\n\trouter.HandleFunc(\"/\", t.Greeting).Methods(\"GET\")\n\trouter.HandleFunc(\"/{sha1}\", t.Get).Methods(\"GET\")\n\trouter.HandleFunc(\"/{sha1}\", t.Post).Methods(\"PUT\")\n\trouter.HandleFunc(\"/{sha1}\", t.Post).Methods(\"POST\")\n\trouter.HandleFunc(\"/{sha1}\", t.Delete).Methods(\"DELETE\")\n\trouter.Handle(\"/debug/vars\", http.DefaultServeMux)\n\treturn t\n}", "func New(a []int) *PTree {\n\tn := len(a)\n\tb := make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\tb[i] = i\n\t}\n\tsort.Sort(&arrayPerm{a, b})\n\tt := &PTree{}\n\tt.a = a\n\tt.n = len(a)\n\tt.root = make([]*node, n+1)\n\tt.root[n] = t.build(b)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tt.root[i] = t.del(t.root[i+1], i)\n\t}\n\treturn t\n}", "func NewTreeStructure() *TreeStructure {\n\treturn &TreeStructure{\n\t\tRoot: &Node{\n\t\t\tTagType: \"root\",\n\t\t\tChildren: make(map[string]*Node),\n\t\t\tContent: []string{\"root\"},\n\t\t},\n\t}\n}", "func NewMerkleTree() (*MerkleTree, error) {\n\troot := newInteriorNode(nil, 0, []bool{})\n\tnonce, err := crypto.MakeRand()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm := &MerkleTree{\n\t\tnonce: nonce,\n\t\troot: root,\n\t}\n\treturn m, nil\n}", "func NewEmptyTree(tt *TranspositionTable) *Tree {\n\tt := &Tree{\n\t\ttt: tt,\n\t}\n\treturn t\n}", "func New() *Node {\n\treturn &Node{\n\t\tparent: nil,\n\t\tchildren: map[option]*Node{},\n\t}\n}", "func New(text string, children ...*ASCIITree) *ASCIITree {\n\ttree := &ASCIITree{Text: text}\n\ttree.Add(children...)\n\treturn tree\n}", "func CreateTree(data []Tree) *Tree {\n\ttemp := make(map[int]*Tree)\n\tvar root *Tree\n\tfor i := range data {\n\t\tleaf := &data[i]\n\t\ttemp[leaf.ID] = leaf\n\t\tif leaf.ParentID == 0 {\n\t\t\troot = leaf\n\t\t}\n\t}\n\n\tfor _, v := range temp {\n\t\tif v.ParentID != 0 {\n\t\t\ttemp[v.ParentID].AddNode(v)\n\t\t}\n\t}\n\n\treturn root\n}", "func NewSerial() Tree {\n\tt := new(serial)\n\tt.Clear()\n\treturn t\n}", "func CreateTree(pairs []string) (root Node) {\n\troot = Node{Name: \"COM\", Parent: nil, Children: nil}\n\trecursiveInsertToTree(&root, pairs)\n\treturn\n}", "func MakeTree(baseDirectory string, actions []Action, dump io.Writer) error {\n\tvar ran []LogEntry\n\n\tlogRan := func(baseDirectory string, action Action) {\n\t\tran = append(ran, LogEntry{baseDirectory, action})\n\t}\n\n\tif err := doTree(baseDirectory, actions, dump, logRan); err != nil {\n\t\trollbackTree(baseDirectory, ran, dump)\n\t\treturn errors.New(\"error on making a tree: \" + err.Error())\n\t} else {\n\t\treturn nil\n\t}\n}", "func NewRBTree(less, more, equal func(a, b interface{}) bool) *RBTree {\n\trb := new(RBTree)\n\trb.root = nil\n\trb.size = 0\n\trb.less = less\n\trb.more = more\n\trb.equal = equal\n\treturn rb\n}", "func (d *decoder) createTree() *node {\n\tif val, _ := readBit(d.r); val {\n\t\treturn &node{readByte(d.r), -1, false, nil, nil}\n\t} else if d.numChars != d.numCharsDecoded {\n\t\tleft := d.createTree()\n\t\tright := d.createTree()\n\t\treturn &node{0, -1, true, left, right}\n\t}\n\n\treturn nil\n}", "func (t *BPTree) newLeaf() *Node {\n\tleaf := t.newNode()\n\tleaf.isLeaf = true\n\treturn leaf\n}", "func New(typ NodeType, ns, name string, attrs []Attribute, children ...*Node) *Node {\n\tvar norm []Attribute\n\tvar key string\n\tfor _, v := range attrs {\n\t\tif v.Key == \"key\" {\n\t\t\tkey = expr.Eval(v.Val)\n\t\t} else {\n\t\t\tnorm = append(norm, v)\n\t\t}\n\t}\n\tif len(children) > 0 {\n\t\tnorm = append(norm, Attribute{\n\t\t\tKey: \"children\",\n\t\t\tVal: children,\n\t\t})\n\t}\n\tn := &Node{\n\t\tType: typ,\n\t\tNamespace: ns,\n\t\tKey: key,\n\t\tData: name,\n\t\tAttr: norm,\n\t}\n\treturn n\n}", "func (dTreeOp DirTreeOp) New() DirTreeOp {\n newDTreeOp := DirTreeOp{}\n newDTreeOp.ErrReturns = make([]error, 0, 100)\n return newDTreeOp\n}", "func NewNode(left, right *TreeNode, val int) *TreeNode {\n\treturn &TreeNode{\n\t\tLeft: left,\n\t\tRight: right,\n\t\tVal: val,\n\t}\n}", "func NewTreeTopology(fanout, nTasks uint64) *TreeTopology {\n\tm := &TreeTopology{\n\t\tfanout: fanout,\n\t\tnumOfTasks: nTasks,\n\t}\n\treturn m\n}" ]
[ "0.82855225", "0.8141068", "0.8019526", "0.7978955", "0.78814346", "0.784047", "0.7823877", "0.78038585", "0.77911633", "0.77679545", "0.7755644", "0.7601492", "0.74408257", "0.7408058", "0.7302533", "0.73020464", "0.7254405", "0.7205861", "0.7181317", "0.71228427", "0.7115974", "0.7087297", "0.7015526", "0.7001558", "0.6992556", "0.6984323", "0.69695604", "0.69567823", "0.69122", "0.68874055", "0.68721455", "0.6858355", "0.6794174", "0.6793598", "0.6788928", "0.6711628", "0.6705107", "0.6699159", "0.6698107", "0.6691924", "0.66811657", "0.667705", "0.6676579", "0.66215396", "0.6565204", "0.6559617", "0.6556233", "0.65397686", "0.6512007", "0.6500773", "0.64927584", "0.6474871", "0.64366627", "0.64333713", "0.6391795", "0.63672423", "0.6345246", "0.6288401", "0.6282916", "0.6274563", "0.62498885", "0.624748", "0.6239631", "0.62347406", "0.6198229", "0.61949676", "0.6155374", "0.6132591", "0.6128452", "0.6120203", "0.61188996", "0.611356", "0.6098085", "0.6087339", "0.6086587", "0.60850847", "0.6073627", "0.60625666", "0.6049474", "0.6040118", "0.60395473", "0.60102093", "0.6009103", "0.597107", "0.59672266", "0.5951173", "0.59497863", "0.5946307", "0.59439695", "0.5894062", "0.58929783", "0.5889008", "0.5868465", "0.58455956", "0.58437335", "0.58387613", "0.58348966", "0.58334076", "0.5817384", "0.58149344" ]
0.6822363
32
NewTreeFromState initiates a Tree from state data previously written by
func NewTreeFromState(data io.Reader) (*Tree, error) { idx := &Tree{ newBlocks: make(chan int), done: make(chan bool), blockMap: make(map[int]int), } if err := idx.loadState(data); err != nil { return nil, fmt.Errorf("Failed loading index state : %v", err) } go idx.blockAllocator() return idx, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (db *DB) InitStateTree(depth int) error {\n\trootNode := core.NewStateRoot(depth)\n\treturn db.Instance.Create(&rootNode).Error\n}", "func newTreeNode(parent *treeNode, move Move, state GameState, ucbC float64) *treeNode {\n\t// Construct the new node.\n\tnode := treeNode{\n\t\tparent: parent,\n\t\tmove: move,\n\t\tstate: state,\n\t\ttotalOutcome: 0.0, // No outcome yet.\n\t\tvisits: 0, // No visits yet.\n\t\tuntriedMoves: state.AvailableMoves(), // Initially the node starts with every node unexplored.\n\t\tchildren: nil, // No children yet.\n\t\tucbC: ucbC, // Whole tree uses same constant.\n\t\tselectionScore: 0.0, // No value yet.\n\t\tplayer: state.PlayerJustMoved(),\n\t}\n\n\t// We're working with pointers.\n\treturn &node\n}", "func (n *Node) createState() bytes.Buffer {\n\tstate := &struct {\n\t\tNext string\n\t\tID string\n\t\tPrev string\n\t}{\n\t\tn.fingers[0].node.IP,\n\t\tn.IP,\n\t\tn.prev.IP,\n\t}\n\tb := new(bytes.Buffer)\n\terr := json.NewEncoder(b).Encode(state)\n\tif err != nil {\n\t\tn.log.Err.Println(err)\n\t}\n\treturn *b\n}", "func NewTree(c *Config) *Tree {\n\treturn &Tree{c: c}\n}", "func NewTree() *Tree {\n\treturn &Tree{&bytes.Buffer{}}\n}", "func NewTree() *BPTree {\n\treturn &BPTree{LastAddress: 0, keyPosMap: make(map[string]int64), enabledKeyPosMap: false}\n}", "func newTree(segmentSize, maxsize, depth int, hashfunc func() hash.Hash) *tree {\n\tn := newNode(0, nil, hashfunc())\n\tprevlevel := []*node{n}\n\t// iterate over levels and creates 2^(depth-level) nodes\n\t// the 0 level is on double segment sections so we start at depth - 2\n\tcount := 2\n\tfor level := depth - 2; level >= 0; level-- {\n\t\tnodes := make([]*node, count)\n\t\tfor i := 0; i < count; i++ {\n\t\t\tparent := prevlevel[i/2]\n\t\t\tnodes[i] = newNode(i, parent, hashfunc())\n\t\t}\n\t\tprevlevel = nodes\n\t\tcount *= 2\n\t}\n\t// the datanode level is the nodes on the last level\n\treturn &tree{\n\t\tleaves: prevlevel,\n\t\tbuffer: make([]byte, maxsize),\n\t}\n}", "func NewTree() *Tree {\n\treturn &Tree{\n\t\trnd: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n}", "func (t *BPTree) startNewTree(key []byte, pointer *Record) error {\n\tt.root = t.newLeaf()\n\tt.root.Keys[0] = key\n\tt.root.pointers[0] = pointer\n\tt.root.KeysNum = 1\n\n\treturn nil\n}", "func NewObjectTree(flags byte) *ObjectTree { return new(ObjectTree).Init(flags) }", "func (d *decoder) createTree() *node {\n\tif val, _ := readBit(d.r); val {\n\t\treturn &node{readByte(d.r), -1, false, nil, nil}\n\t} else if d.numChars != d.numCharsDecoded {\n\t\tleft := d.createTree()\n\t\tright := d.createTree()\n\t\treturn &node{0, -1, true, left, right}\n\t}\n\n\treturn nil\n}", "func NewStateNode(path, hash string, nodeType uint64) *UserState {\n\tnewUserState := &UserState{\n\t\tAccountID: ZERO,\n\t\tPath: path,\n\t\tType: nodeType,\n\t}\n\tnewUserState.UpdatePath(newUserState.Path)\n\tnewUserState.Hash = hash\n\treturn newUserState\n}", "func NewTree(repo *Repository, id SHA1) *Tree {\n\treturn &Tree{\n\t\tID: id,\n\t\trepo: repo,\n\t}\n}", "func NewTree(path string, withFiles bool) Tree {\n\tfiles, err := ioutil.ReadDir(path)\n\tif err != nil {\n\t\treturn nil\n\t}\n\troot := newNode(path, true, buildTree(path, files, withFiles))\n\treturn &tree{\n\t\troot: root,\n\t}\n}", "func NewTree(db *badger.Storage, root []byte) *Tree {\n\tt := &Tree{\n\t\tdb: newTreeDb(db),\n\t}\n\tt.cache = lru.NewCache(2048)\n\tvar zero [32]byte\n\tif root != nil && len(root) == int(32) && bytes.Compare(root, zero[:]) > common.Zero {\n\t\tt.root = t.mustLoadNode(root)\n\t}\n\n\tif err := FileExist(); err == nil {\n\t\tt.BackCommit()\n\t}\n\n\treturn t\n}", "func NewTree(pattern string, handlers []baa.HandlerFunc) *Tree {\n\tif pattern == \"\" {\n\t\tpanic(\"tree.new: pattern can be empty\")\n\t}\n\treturn &Tree{\n\t\tstatic: true,\n\t\talpha: pattern[0],\n\t\tpattern: pattern,\n\t\tformat: []byte(pattern),\n\t\thandlers: handlers,\n\t}\n}", "func (f *Forest) New(d *crypto.Digest, l uint32) *Tree {\n\tt := &Tree{\n\t\tleaves: l,\n\t\tdig: d,\n\t\tf: f,\n\t\tlastBlockLen: BlockSize,\n\t\tleavesComplete: make([]bool, l),\n\t}\n\tf.writeTree(t)\n\treturn t\n}", "func NewTree(n *node) (*Tree, error) {\n\treturn &Tree{\n\t\troot: n,\n\t\tvalues: map[string]*node{n.value: n},\n\t}, nil\n}", "func New(name string) *Tree {\n\treturn &Tree{name: name, root: &Node{}, mtx: &sync.RWMutex{}}\n}", "func NewTree(id string, cache storage.Cache, leaves storage.Store, hasher hashing.Hasher) *Tree {\n\n\tcacheLevels := int(math.Max(0.0, math.Floor(math.Log(float64(cache.Size()))/math.Log(2.0))))\n\tdigestLength := len(hasher([]byte(\"a test event\"))) * 8\n\n\ttree := &Tree{\n\t\t[]byte(id),\n\t\tleafHasherF(hasher),\n\t\tinteriorHasherF(hasher),\n\t\tmake([][]byte, digestLength),\n\t\tcache,\n\t\tleaves,\n\t\tnew(stats),\n\t\tnewArea(digestLength-cacheLevels, digestLength),\n\t\tdigestLength,\n\t\tnil,\n\t}\n\n\t// init default hashes cache\n\ttree.defaultHashes[0] = hasher(tree.id, Empty)\n\tfor i := 1; i < int(digestLength); i++ {\n\t\ttree.defaultHashes[i] = hasher(tree.defaultHashes[i-1], tree.defaultHashes[i-1])\n\t}\n\ttree.ops = tree.operations()\n\n\treturn tree\n}", "func New(name string) *Tree {\n\treturn &Tree{\n\t\tName: name,\n\t}\n}", "func NewFromString(s string) (*Tree, error) {\n\treturn New(strings.NewReader(s))\n}", "func NewTree() *Tree {\n\treturn &Tree{Symbol{NIL, \"NewTree holder\"}, make([]*Tree, 0, maxChildren), nil}\n}", "func NewTree(index uint8) *RBTree {\n\tvar rbTree = &RBTree{\n\t\troot: nil,\n\t\tmLeft: nil,\n\t\tmRight: nil,\n\t\tSize: 0,\n\t\tIndex: index,\n\t}\n\treturn rbTree\n}", "func NewState(e *etcd.Client, ttl time.Duration, path ...string) State {\n\trealttl := 1 * time.Second\n\tif ttl.Seconds() > realttl.Seconds() {\n\t\trealttl = ttl\n\t}\n\treturn &state{\n\t\te: e,\n\t\tkey: strings.Join(path, \"/\"),\n\t\tttl: uint64(realttl.Seconds()),\n\t}\n}", "func (l *hierLayer) updateState(cmap map[*replicationElement]string) {\n\t//go through the map and build the tree\n\tl.root = &DfsTreeElement{name: \"/\", fileType: \"dir\", path: \"\", content: \"\",parent:nil,}\n\tstack := lls.New()\n\n\n\t//policy used here is skip\n\n\tstack.Push(l.root)\n\t// untill stack empty\n\tfor !stack.Empty() {\n\t\t// \tpop stack call el\n\t\tra, _ := stack.Pop()\n\t\tel := ra.(*DfsTreeElement)\n\n\t\tif el.fileType == \"dir\" {\n\t\t\tfor _, i := range getChildren(el, cmap) {\n\t\t\t\tii := i\n\t\t\t\tstack.Push(&ii)\n\t\t\t\tel.children = append(el.children, &ii)\n\t\t\t}\n\t\t\t// fmt.Println(el.getPath(), el.children)\n\n\t\t}\n\n\t}\n\n\t//last step is to send the interface layer with update state\n\tl.updateInterface()\n\n}", "func newPageState(title string) *PageState {\n\treturn &PageState{\n\t\tTitle: title,\n\t\tTimezones: []*page.Component{},\n\t}\n}", "func New(rootHash, utxoRootHash *corecrypto.HashType, db storage.Table) (*StateDB, error) {\n\n\ttr, err := trie.New(rootHash, db)\n\tif err != nil {\n\t\tlogger.Warn(err)\n\t\treturn nil, err\n\t}\n\tutr, err := trie.New(utxoRootHash, db)\n\tif err != nil {\n\t\tlogger.Warn(err)\n\t\treturn nil, err\n\t}\n\treturn &StateDB{\n\t\tdb: db,\n\t\ttrie: tr,\n\t\tutxoTrie: utr,\n\t\tstateObjects: make(map[types.AddressHash]*stateObject),\n\t\tstateObjectsDirty: make(map[types.AddressHash]struct{}),\n\t\tlogs: make(map[corecrypto.HashType][]*types.Log),\n\t\tpreimages: make(map[corecrypto.HashType][]byte),\n\t\tjournal: newJournal(),\n\t}, nil\n}", "func New() *Tree {\n\treturn &Tree{}\n}", "func NewTree() *Tree {\n\treturn new(Tree)\n}", "func New() *Tree {\n\treturn &Tree{\n\t\tDelimiter: DefaultDelimiter,\n\t\tFormatter: SimpleFormatter,\n\t\tErrors: make(map[string]error),\n\t}\n}", "func NewTree(from []int) *Tree {\n\ttreeSize := calcTreeSize(len(from))\n\tnodes := make([]int, treeSize)\n\n\tt := &Tree{nodes, len(from)}\n\tt.build(from, 0, 0, len(from)-1)\n\n\treturn t\n}", "func createStartingState(path string, finfo os.FileInfo) (*walkerContext, *Directory) {\n\tdir := newDirectory(path, finfo)\n\tcontext := &walkerContext{\n\t\tcurrent: dir,\n\t\tbaseDir: path,\n\t\tall: make(map[string]*Directory),\n\t}\n\tcontext.all[path] = dir\n\treturn context, dir\n}", "func NewStateFromDisk() (*State, error) {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgen, err := loadgen(filepath.Join(cwd, \"database\", \"gen.json\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar balances State\n\tbalances.Balances = gen.Balances\n\n\tf, err := os.OpenFile(filepath.Join(cwd, \"database\", \"block.db\"), os.O_APPEND|os.O_RDWR, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscanner := bufio.NewScanner(f)\n\n\tstate := &State{\n\t\tBalances: balances.Balances,\n\t\ttxMempool: []Tx{},\n\t\tlatestBlockHash: Hash{},\n\t\tdbFile: f,\n\t}\n\n\tfor scanner.Scan() {\n\t\tif err := scanner.Err(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar blockFs BlockFS\n\t\tblockFsJson := scanner.Bytes()\n\t\terr = json.Unmarshal(blockFsJson, &blockFs)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := state.applyBlock(blockFs.Value); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstate.latestBlockHash = blockFs.Key\n\t}\n\n\treturn state, nil\n}", "func NewTreeFromBS(bs *bitstream.BitStream) Tree {\n\troot := newTreeFromBS(bs)\n\treturn Tree{root: root}\n}", "func NewStateSync(root common.Hash, database trie.DatabaseReader) *trie.TrieSync {\n\tvar syncer *trie.TrieSync\n\tcallback := func(leaf []byte, parent common.Hash) error {\n\t\tvar obj Account\n\t\tif err := rlp.Decode(bytes.NewReader(leaf), &obj); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsyncer.AddSubTrie(obj.Root, 64, parent, nil)\n\t\tsyncer.AddRawEntry(common.BytesToHash(obj.CodeHash), 64, parent)\n\t\treturn nil\n\t}\n\tsyncer = trie.NewTrieSync(root, database, callback)\n\treturn syncer\n}", "func NewTree(n int) *Tree {\n\treturn &Tree{\n\t\tn: n,\n\t\tbit: make([]int, n+1),\n\t}\n}", "func NewTree() *Tree {\n\treturn &Tree{\n\t\tBlock: *NewBlock(),\n\t\tTextStyle: Theme.Tree.Text,\n\t\tSelectedRowStyle: Theme.Tree.Text,\n\t\tWrapText: true,\n\t}\n}", "func NewTree(childs Childs) *Quadtree {\n\tqt, ok := nodeMap[childs]\n\tif ok {\n\t\tcacheHit++\n\t\treturn qt\n\t}\n\tcacheMiss++\n\tqt = &Quadtree{childs.NE.Level + 1, childs, childs.population(), nil}\n\tif qt.Population == 0 || qt.Level <= 16 {\n\t\tnodeMap[childs] = qt\n\t}\n\treturn qt\n}", "func New(opts ...TreeOption) *Tree {\n\tt := &Tree{}\n\tfor _, opt := range opts {\n\t\topt(t)\n\t}\n\tt.init()\n\treturn t\n}", "func New() *Tree {\n\treturn &Tree{root: &node{}}\n}", "func New(name string) *Tree {\n\ttr := new(Tree)\n\ttr.Name = name\n\treturn tr\n}", "func CreateNodeState(nodeId int32, money int64) string {\n\treturn fmt.Sprintf(\"node %d = %d\\n\", nodeId, money)\n}", "func MakeTree(baseDirectory string, actions []Action, dump io.Writer) error {\n\tvar ran []LogEntry\n\n\tlogRan := func(baseDirectory string, action Action) {\n\t\tran = append(ran, LogEntry{baseDirectory, action})\n\t}\n\n\tif err := doTree(baseDirectory, actions, dump, logRan); err != nil {\n\t\trollbackTree(baseDirectory, ran, dump)\n\t\treturn errors.New(\"error on making a tree: \" + err.Error())\n\t} else {\n\t\treturn nil\n\t}\n}", "func NewBuildState(config *Configuration) *BuildState {\n\tgraph := NewGraph()\n\tstate := &BuildState{\n\t\tGraph: graph,\n\t\tpendingParses: make(chan ParseTask, 10000),\n\t\tpendingActions: make(chan Task, 1000),\n\t\thashers: map[string]*fs.PathHasher{\n\t\t\t// For compatibility reasons the sha1 hasher has no suffix.\n\t\t\t\"sha1\": fs.NewPathHasher(RepoRoot, config.Build.Xattrs, sha1.New, \"sha1\"),\n\t\t\t\"sha256\": fs.NewPathHasher(RepoRoot, config.Build.Xattrs, sha256.New, \"sha256\"),\n\t\t\t\"crc32\": fs.NewPathHasher(RepoRoot, config.Build.Xattrs, newCRC32, \"crc32\"),\n\t\t\t\"crc64\": fs.NewPathHasher(RepoRoot, config.Build.Xattrs, newCRC64, \"crc64\"),\n\t\t\t\"blake3\": fs.NewPathHasher(RepoRoot, config.Build.Xattrs, newBlake3, \"blake3\"),\n\t\t\t\"xxhash\": fs.NewPathHasher(RepoRoot, config.Build.Xattrs, newXXHash, \"xxhash\"),\n\t\t},\n\t\tProcessExecutor: executorFromConfig(config),\n\t\tStartTime: startTime,\n\t\tConfig: config,\n\t\tRepoConfig: config,\n\t\tVerifyHashes: true,\n\t\tNeedBuild: true,\n\t\tXattrsSupported: config.Build.Xattrs,\n\t\tCoverage: TestCoverage{Files: map[string][]LineCoverage{}},\n\t\tTargetArch: config.Build.Arch,\n\t\tArch: cli.HostArch(),\n\t\tstats: &lockedStats{},\n\t\tprogress: &stateProgress{\n\t\t\tnumActive: 1, // One for the initial target adding on the main thread.\n\t\t\tnumPending: 1,\n\t\t\tpendingTargets: cmap.New[BuildLabel, chan struct{}](cmap.DefaultShardCount, hashBuildLabel),\n\t\t\tpendingPackages: cmap.New[packageKey, chan struct{}](cmap.DefaultShardCount, hashPackageKey),\n\t\t\tpackageWaits: cmap.New[packageKey, chan struct{}](cmap.DefaultShardCount, hashPackageKey),\n\t\t\tinternalResults: make(chan *BuildResult, 1000),\n\t\t\tcycleDetector: cycleDetector{graph: graph},\n\t\t},\n\t\tinitOnce: new(sync.Once),\n\t\tpreloadDownloadOnce: new(sync.Once),\n\t}\n\n\tstate.PathHasher = state.Hasher(config.Build.HashFunction)\n\tstate.progress.allStates = []*BuildState{state}\n\tstate.Hashes.Config = config.Hash()\n\tfor _, exp := range config.Parse.ExperimentalDir {\n\t\tstate.experimentalLabels = append(state.experimentalLabels, BuildLabel{PackageName: exp, Name: \"...\"})\n\t}\n\tgo state.forwardResults()\n\treturn state\n}", "func newTapestry(tap *tapestry.Node, zkAddr string) (*Tapestry, error) {\n\t//TODO: Setup a zookeeper connection and return a Tapestry struct\n\tconn, err := connectZk(zkAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\texists, _, err := conn.Exists(\"/tapestry\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error: zookeeper fail to find target, reason is %v\", err)\n\t}\n\tif !exists {\n\t\t_, err = conn.Create(\"/tapestry\", nil, 0, zk.WorldACL(zk.PermAll))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t// Tapestry register them in ZooKeeper\n\t// we will simply use file paths as unique IDs for files and directories.\n\terr = createEphSeq(conn, filepath.Join(\"/tapestry\", tap.Addr()), []byte(tap.Addr()))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Tapestry{\n\t\ttap: tap,\n\t\tzk: conn,\n\t}, nil\n}", "func GitTreeState() string { return gitTreeState }", "func newObject(db *StateDB, address common.Address, data model.StateAccount) *stateObject {\n\tif data.Balance == nil {\n\t\tdata.Balance = new(big.Int)\n\t}\n\tif data.CodeHash == nil {\n\t\tdata.CodeHash = emptyCodeHash\n\t}\n\tif data.Root == (common.Hash{}) {\n\t\tdata.Root = emptyRoot\n\t}\n\treturn &stateObject{\n\t\tdb: db,\n\t\taddress: address,\n\t\taddrHash: crypto.Keccak256Hash(address[:]),\n\t\tdata: data,\n\t\toriginStorage: make(Storage),\n\t\tpendingStorage: make(Storage),\n\t\tdirtyStorage: make(Storage),\n\t}\n}", "func New() *binaryTree {\n\treturn CreateDefaultTree()\n}", "func newObject(db *StateDB, key math.Hash, data meta.Account) *StateObject {\n\treturn &StateObject{\n\t\tdb: db,\n\t\tkey: key,\n\t\tdata: data,\n\t\toriginStorage: make(Storage),\n\t\tdirtyStorage: make(Storage),\n\t}\n}", "func CreateTree(parties []int, B int, lambda int) []Node {\n\tnodes := make([]Node, (2*B)-1) //create length based on B\n\tfor i := 0; i < len(nodes); i++ {\n\t\tpath, nonces := CreatePath(parties, int(math.Pow(math.Log2(float64(lambda)), 2))) //use path for each node\n\t\tnodes[i].Path = path\n\t\tnodes[i].Nonces = nonces\n\t\t//assigns nodes\n\t}\n\tfactor := 0 //this makes the right parent index\n\tpivotNode := CalculatePivotNode(B)\n\tfor i := 0; i < pivotNode; i++ {\n\t\tnodes[i].Parent = &nodes[B+factor] //so the parent is the right node, and last is null\n\t\tif i%2 == 1 {\n\t\t\tfactor += 1\n\t\t}\n\t}\n\treturn nodes\n\n}", "func NewState() *State {\n\treturn &State{\n\t\tProblem: make(Problem),\n\t\tSolution: make(Solution),\n\t\tDependees: make(StringGraph),\n\t}\n}", "func (m *MockLogic) StateTree() tree.Tree {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StateTree\")\n\tret0, _ := ret[0].(tree.Tree)\n\treturn ret0\n}", "func New(options ...TreeOpt) (*Tree, error) {\n\ttmp := tree{obj: Tree{\n\t\talgorithm: hash.Default,\n\t\tmaxLevel: defaultMaxLevel,\n\t}}\n\n\tfor _, setter := range options {\n\t\tif err := tmp.setOption(setter); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &tmp.obj, nil\n}", "func (m *MockAtomicLogic) StateTree() tree.Tree {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StateTree\")\n\tret0, _ := ret[0].(tree.Tree)\n\treturn ret0\n}", "func ConstructState(store adt.Store, rootKeyAddress addr.Address) (*State, error) {\n\temptyMapCid, err := adt.StoreEmptyMap(store, builtin.DefaultHamtBitwidth)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"failed to create empty map: %w\", err)\n\t}\n\n\treturn &State{\n\t\tRootKey: rootKeyAddress,\n\t\tVerifiers: emptyMapCid,\n\t\tVerifiedClients: emptyMapCid,\n\t\tRemoveDataCapProposalIDs: emptyMapCid,\n\t}, nil\n}", "func NewTree(options *Options) *Tree {\n\tif options == nil {\n\t\toptions = new(Options)\n\t}\n\tsetDefaultOptions(options)\n\n\tidx := &Tree{\n\t\tnewBlocks: make(chan int),\n\t\tdone: make(chan bool),\n\t\tblockMap: make(map[int]int),\n\t\tmanager: newEpochManager(options.NumAllocators),\n\t}\n\n\tidx.allocators = make([]*Allocator, options.NumAllocators)\n\tidx.allocatorQueue = newSlots(len(idx.allocators))\n\tfor i := range idx.allocators {\n\t\tidx.allocators[i] = newAllocator(idx, i, blockSize, idx.newBlocks)\n\t}\n\tgo idx.blockAllocator()\n\treturn idx\n}", "func CreateState() *State {\n\treturn &State{\n\t\tVars: make(map[string]string),\n\t}\n}", "func NewOrderTree(orderDB *BatchDatabase, key []byte, orderBook *Orderbook) *OrderTree {\n\t// create priceTree from db for order list\n\t// orderListDBPath := path.Join(datadir, \"pricetree\")\n\t// orderDBPath := path.Join(datadir, \"order\")\n\tpriceTree := NewRedBlackTreeExtended(orderDB)\n\t// priceTree.Debug = orderDB.Debug\n\n\t// itemCache, _ := lru.New(defaultCacheLimit)\n\t// orderDB, _ := ethdb.NewLDBDatabase(orderDBPath, 0, 0)\n\n\titem := &OrderTreeItem{\n\t\tVolume: Zero(),\n\t\tNumOrders: 0,\n\t\t// Depth: 0,\n\t\tPriceTreeSize: 0,\n\t}\n\n\tslot := new(big.Int).SetBytes(key)\n\n\t// we will need a lru for cache hit, and internal cache for orderbook db to do the batch update\n\torderTree := &OrderTree{\n\t\torderDB: orderDB,\n\t\tPriceTree: priceTree,\n\t\tKey: key,\n\t\tslot: slot,\n\t\tItem: item,\n\t\torderBook: orderBook,\n\t\t// orderListCache: itemCache,\n\t}\n\n\t// must restore from db first to make sure we get corrent information\n\t// orderTree.Restore()\n\t// then update PriceTree after restore the order tree\n\n\t// update price tree\n\t// orderTree.PriceTree = priceTree\n\t// orderTree.Key = GetKeyFromBig(orderTree.slot)\n\treturn orderTree\n}", "func (bpt *BplusTree) treeNodeInit(isLeaf bool, next common.Key, prev common.Key,\n\tinitLen int) *treeNode {\n\n\tnode := defaultAlloc()\n\tnode.Children = make([]treeNodeElem, initLen, bpt.context.maxDegree)\n\tnode.IsLeaf = isLeaf\n\tnode.NextKey = next\n\tnode.PrevKey = prev\n\t// Generate a new key for the node being added.\n\tnode.NodeKey = common.Generate(bpt.context.keyType, bpt.context.pfx)\n\treturn node\n}", "func constructTreeNode(requestPathParts []string, nodePathIndex int) (*TreeNode, error) {\n\tnewNodeUUID, uuidErr := genUUID()\n\tif uuidErr != nil {\n\t\treturn nil, uuidErr\n\t}\n\ttreeNode := TreeNode{level: nodePathIndex, uuid: newNodeUUID, value: requestPathParts[nodePathIndex], parent: nil}\n\n\tif len(requestPathParts) > nodePathIndex+1 {\n\t\tchildNode, childErr := constructTreeNode(requestPathParts, nodePathIndex+1)\n\t\tif childErr != nil {\n\t\t\treturn nil, childErr\n\t\t}\n\n\t\ttreeNode.addChild(nil, childNode)\n\t}\n\n\treturn &treeNode, nil\n}", "func NewStateSync(root common.Hash, database trie.DatabaseReader) *trie.Sync {\n\tvar syncer *trie.Sync\n\tcallback := func(leaf []byte, parent common.Hash) error {\n\t\treturn nil\n\t}\n\tsyncer = trie.NewSync(root, database, callback)\n\treturn syncer\n}", "func BTreeCreate(t int) *BTree {\n\t// create null node to use as place filler\n\tnullNode := &BTreeNode{}\n\tfor i := 0; i < 2*t; i++ {\n\t\tnullNode.children = append(nullNode.children, nullNode)\n\t}\n\n\t// create the tree\n\ttree := BTree{\n\t\tt: t,\n\t\tnullNode: nullNode,\n\t}\n\n\t// create root node\n\tx := tree.AllocateNode()\n\tx.leaf = true\n\ttree.root = x\n\n\t// create null node used to auto-populate children of newly allocated nodes\n\ttree.nullNode = tree.AllocateNode()\n\n\t// *Here is where we'd write the new node to disk\n\treturn &tree\n}", "func NewTree(cs []Content) (*MerkleTree, error) {\n\troot, leafs, err := buildWithContent(cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &MerkleTree{\n\t\tRoot: root,\n\t\tmerkleRoot: root.Hash,\n\t\tLeafs: leafs,\n\t}\n\treturn t, nil\n}", "func NewTree(rootName string, builder caching.TreeBuilder, updater caching.TreeUpdater,\n\tlocker caching.Locker) (*Tree, error) {\n\troot := &caching.Node{\n\t\tName: rootName,\n\t\tLeaf: false,\n\t\tSize: int64(0),\n\t\tChildren: []*caching.Node{},\n\t}\n\n\tnodes := map[string]*caching.Node{rootName: root}\n\ttree := &Tree{\n\t\tRootName: rootName,\n\t\tnodes: nodes,\n\t\tbuilder: builder,\n\t\tupdater: updater,\n\t\tlocker: locker,\n\t\tBulkUpdates: 100,\n\t\tUpdateRoutines: 10,\n\t}\n\terr := tree.AddNode(rootName, root)\n\treturn tree, err\n}", "func InitTree(symbol Symbol) (*Tree, error) {\n\thandler, err := getHandler(symbol)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Tree{symbol, make([]*Tree, 0, maxChildren), handler}, nil\n}", "func newGenState() *genState {\n\treturn &genState{\n\t\t// Mark the name that is used for the binary type as a reserved name\n\t\t// within the output structs.\n\t\tdefinedGlobals: map[string]bool{\n\t\t\tygot.BinaryTypeName: true,\n\t\t\tygot.EmptyTypeName: true,\n\t\t},\n\t\tuniqueDirectoryNames: make(map[string]string),\n\t\tuniqueEnumeratedTypedefNames: make(map[string]string),\n\t\tuniqueIdentityNames: make(map[string]string),\n\t\tuniqueEnumeratedLeafNames: make(map[string]string),\n\t\tuniqueProtoMsgNames: make(map[string]map[string]bool),\n\t\tuniqueProtoPackages: make(map[string]string),\n\t\tgeneratedUnions: make(map[string]bool),\n\t}\n}", "func New() *VersionTree {\n\treturn &VersionTree{}\n}", "func (t *Tree) NewTreeNode(parent *TreeNode, step Step, pass bool, side Value, first bool) *TreeNode {\n\te := &TreeNode{\n\t\tt: t,\n\t\tside: side,\n\t\tstep: step,\n\t\tpass: pass,\n\t\tparent: parent,\n\t\tpolicy: policyPool.Get().([]float32),\n\t\tfirst: first,\n\t}\n\treturn e\n}", "func (tree *Tree23) initializeTree(capacity int) {\n\n\ttree.root = 0\n\n\ttree.oneElemTreeList = []TreeNodeIndex{-1}\n\ttree.twoElemTreeList = []TreeNodeIndex{-1, -1}\n\ttree.threeElemTreeList = []TreeNodeIndex{-1, -1, -1}\n\ttree.nineElemTreeList = []TreeNodeIndex{-1, -1, -1, -1, -1, -1, -1, -1, -1}\n\n\ttree.treeNodes = make([]treeNode, capacity, capacity)\n\tfor i := 0; i < len(tree.treeNodes); i++ {\n\t\tvar a [3]treeLink\n\t\ttree.treeNodes[i] = treeNode{a, 0, nil, -1, -1}\n\t}\n\ttree.treeNodesFirstFreePos = 1\n\ttree.treeNodesFreePositions = make(stack, 0, 0)\n}", "func newAlohaTree(t *testing.T, db dbm.DB) (*iavl.MutableTree, types.CommitID) {\n\tt.Helper()\n\ttree := iavl.NewMutableTree(db, cacheSize, false, log.NewNopLogger())\n\n\tfor k, v := range treeData {\n\t\t_, err := tree.Set([]byte(k), []byte(v))\n\t\trequire.NoError(t, err)\n\t}\n\n\tfor i := 0; i < nMoreData; i++ {\n\t\tkey := randBytes(12)\n\t\tvalue := randBytes(50)\n\t\t_, err := tree.Set(key, value)\n\t\trequire.NoError(t, err)\n\t}\n\n\thash, ver, err := tree.SaveVersion()\n\trequire.Nil(t, err)\n\n\treturn tree, types.CommitID{Version: ver, Hash: hash}\n}", "func TreeStoreNew(types ...glib.Type) *TreeStore {\n\tgtypes := C.alloc_types(C.int(len(types)))\n\tfor n, val := range types {\n\t\tC.set_type(gtypes, C.int(n), C.GType(val))\n\t}\n\tdefer C.g_free(C.gpointer(gtypes))\n\tc := C.gtk_tree_store_newv(C.gint(len(types)), gtypes)\n\treturn wrapTreeStore(unsafe.Pointer(c))\n}", "func NewTree(width int, company string) *Tree {\n\theight := width / 2\n\n\tleaves := make([][]string, height)\n\n\tfor i := 0; i < height; i++ {\n\t\tleaves[i] = newLevelLeaves(width, \" \")\n\t\tif i == 0 {\n\t\t\tleaves[i][width/2] = \"★\"\n\t\t\tcontinue\n\t\t}\n\n\t\tleaves[i][height-i] = \"/\"\n\t\tleaves[i][height+i] = \"\\\\\"\n\t\tfor j := (height - i + 1); j < height+i; j++ {\n\t\t\tleaves[i][j] = leafContent()\n\t\t}\n\t}\n\n\tleaves = append(leaves, bottomLeaves(width, \"^\"), bottomLeaves(width, \" \"))\n\n\treturn &Tree{\n\t\tleaves: leaves,\n\t\tcompany: company,\n\t}\n}", "func NewState(username string) *State {\n\treturn &State{\n\t\tUsername: username,\n\t\tURL: fmt.Sprintf(\"https://aggr.md/@%s.json\", username),\n\t}\n}", "func createNewState(state int, at map[int]map[uint8]int) {\n at[state] = make(map[uint8]int)\n if debugMode==true {\n fmt.Printf(\"\\ncreated state %d\", state)\n }\n}", "func newState(digest string, blob remote.Blob) *state {\n\treturn &state{\n\t\tNode: nodefs.NewDefaultNode(),\n\t\tstatFile: &statFile{\n\t\t\tNode: nodefs.NewDefaultNode(),\n\t\t\tname: digest + \".json\",\n\t\t\tstatJSON: statJSON{\n\t\t\t\tDigest: digest,\n\t\t\t\tSize: blob.Size(),\n\t\t\t},\n\t\t\tblob: blob,\n\t\t},\n\t}\n}", "func (tp *Trie) NewState() *State {\n\ts := &State{\n\t\tID: tp.StatesCount,\n\t\tSuccess: map[rune]*State{},\n\t}\n\ttp.StatesCount++\n\treturn s\n}", "func New() Tree {\n\treturn &Node{Value: \".\"}\n}", "func (treeNode *TreeNode) New(node Item) (*TreeNode, error) {\n\tif treeNode != nil {\n\t\treturn nil, errors.New(\"treeNode must be nil\")\n\t}\n\ttreeNode = &TreeNode{\n\t\tLeft: nil,\n\t\tRight: nil,\n\t\tValue: node,\n\t}\n\treturn treeNode, nil\n}", "func NewString() *Tree {\n\ttree := &Tree{\n\t\tdatatype: containers.StringContainer(\"A\"),\n\t}\n\t// The below handling is required to achieve method overriding.\n\t// Refer: https://stackoverflow.com/questions/38123911/golang-method-override\n\ttree.TreeOperations = interface{}(tree).(binarytrees.TreeOperations)\n\treturn tree\n}", "func (dTreeOp DirTreeOp) New() DirTreeOp {\n newDTreeOp := DirTreeOp{}\n newDTreeOp.ErrReturns = make([]error, 0, 100)\n return newDTreeOp\n}", "func NewTree(cs []Content) (*MerkleTree, error) {\n\tvar defaultHashStrategy = \"sha256\"\n\tt := &MerkleTree{\n\t\tHashStrategy: defaultHashStrategy,\n\t}\n\troot, leafs, err := buildWithContent(cs, t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt.Root = root\n\tt.Leafs = leafs\n\tt.MerkleRoot = root.Hash\n\treturn t, nil\n}", "func New(hashFunc func(i interface{}) int64) *rbTree {\n\treturn &rbTree{hashFunc: hashFunc}\n}", "func NewBST() *BSTree {\n\treturn &BSTree{nil}\n}", "func newDemoTree() TreeRoot {\n\tn1 := newNode(1)\n\n\tn2 := newNode(2)\n\tn1.Left = n2\n\n\tn3 := newNode(3)\n\tn1.Right = n3\n\n\tn4 := newNode(4)\n\tn2.Left = n4\n\n\tn5 := newNode(5)\n\tn2.Right = n5\n\n\tn6 := newNode(6)\n\tn3.Left = n6\n\n\tn7 := newNode(7)\n\tn3.Right = n7\n\n\tn8 := newNode(8)\n\tn4.Left = n8\n\n\tn9 := newNode(9)\n\tn4.Right = n9\n\n\tn10 := newNode(10)\n\tn5.Left = n10\n\n\tn11 := newNode(11)\n\tn5.Right = n11\n\n\tn12 := newNode(12)\n\tn6.Left = n12\n\n\tn13 := newNode(13)\n\tn6.Right = n13\n\n\tn14 := newNode(14)\n\tn7.Left = n14\n\n\tn15 := newNode(15)\n\tn7.Right = n15\n\n\tn16 := newNode(16)\n\tn14.Left = n16\n\n\tn17 := newNode(17)\n\tn14.Right = n17\n\n\treturn n1\n}", "func New(ctx context.Context, client *http.Client, projectName string) (*tree.FS, error) {\n\tp, err := newGithubProject(ctx, client, projectName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstart := time.Now()\n\tt, err := p.getTree(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"Loaded project with %d files in %.1fs\", len(t), time.Now().Sub(start).Seconds())\n\treturn tree.NewFS(t), nil\n}", "func MigrateStateTree(ctx context.Context, store cbor.IpldStore, stateRootIn cid.Cid) (cid.Cid, error) {\n\t// Setup input and output state tree helpers\n\tadtStore := adt.WrapStore(ctx, store)\n\tactorsIn, err := states0.LoadTree(adtStore, stateRootIn)\n\tif err != nil {\n\t\treturn cid.Undef, err\n\t}\n\tstateRootOut, err := adt.MakeEmptyMap(adtStore).Root()\n\tif err != nil {\n\t\treturn cid.Undef, err\n\t}\n\tactorsOut, err := states.LoadTree(adtStore, stateRootOut)\n\tif err != nil {\n\t\treturn cid.Undef, err\n\t}\n\n\t// Extra setup\n\t// miner\n\tvar p phoenix\n\tif err := p.load(ctx, actorsIn); err != nil {\n\t\treturn cid.Undef, err\n\t}\n\t// power\n\tpm := migrations[builtin0.StoragePowerActorCodeID].StateMigration.(*powerMigrator)\n\tpm.actorsIn = actorsIn\n\n\t// Iterate all actors in old state root\n\t// Set new state root actors as we go\n\tif err = actorsIn.ForEach(func(addr address.Address, actorIn *states.Actor) error {\n\t\tmigration := migrations[actorIn.Code]\n\n\t\t// This will be migrated at the end\n\t\tif actorIn.Code == builtin0.VerifiedRegistryActorCodeID {\n\t\t\treturn nil\n\t\t}\n\t\theadOut, transfer, err := migration.StateMigration.MigrateState(ctx, store, actorIn.Head, actorIn.Balance)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"state migration error on %s actor at addr %s: %w\", builtin.ActorNameByCode(migration.OutCodeCID), addr, err)\n\t\t}\n\n\t\t// set up new state root with the migrated state\n\t\tactorOut := states.Actor{\n\t\t\tCode: migration.OutCodeCID,\n\t\t\tHead: headOut,\n\t\t\tCallSeqNum: actorIn.CallSeqNum,\n\t\t\tBalance: big.Add(actorIn.Balance, transfer),\n\t\t}\n\t\tif err = p.transfer(transfer); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn actorsOut.SetActor(addr, &actorOut)\n\t}); err != nil {\n\t\treturn cid.Undef, err\n\t}\n\n\t// // Migrate verified registry\n\tvm := migrations[builtin0.VerifiedRegistryActorCodeID].StateMigration.(*verifregMigrator)\n\tvm.actorsOut = actorsOut\n\tverifRegActorIn, found, err := actorsIn.GetActor(builtin0.VerifiedRegistryActorAddr)\n\tif err != nil {\n\t\treturn cid.Undef, err\n\t}\n\tif !found {\n\t\treturn cid.Undef, xerrors.Errorf(\"could not find verifreg actor in state\")\n\t}\n\tverifRegHeadOut, transfer, err := vm.MigrateState(ctx, store, verifRegActorIn.Head, verifRegActorIn.Balance)\n\tif err != nil {\n\t\treturn cid.Undef, err\n\t}\n\tverifRegActorOut := states.Actor{\n\t\tCode: builtin.VerifiedRegistryActorCodeID,\n\t\tHead: verifRegHeadOut,\n\t\tCallSeqNum: verifRegActorIn.CallSeqNum,\n\t\tBalance: big.Add(verifRegActorIn.Balance, transfer),\n\t}\n\tif err = p.transfer(transfer); err != nil {\n\t\treturn cid.Undef, err\n\t}\n\tif err := actorsOut.SetActor(builtin.VerifiedRegistryActorAddr, &verifRegActorOut); err != nil {\n\t\treturn cid.Undef, err\n\t}\n\n\t// Track deductions to burntFunds actor's balance\n\tif err := p.flush(ctx, actorsOut); err != nil {\n\t\treturn cid.Undef, err\n\t}\n\n\treturn actorsOut.Flush()\n}", "func NewTree(depth int) *Tree {\n\tif depth > 0 {\n\t\treturn &Tree{Left: NewTree(depth - 1), Right: NewTree(depth - 1)}\n\t} else {\n\t\treturn &Tree{}\n\t}\n}", "func createBinaryTree(rootAddress **BinaryTreeNode) {\n\troot := newBinaryTreeNode(4)\n\troot.Left = newBinaryTreeNode(2)\n\troot.Left.Left = newBinaryTreeNode(1)\n\troot.Left.Right = newBinaryTreeNode(3)\n\troot.Right = newBinaryTreeNode(6)\n\troot.Right.Left = newBinaryTreeNode(5)\n\troot.Right.Right = newBinaryTreeNode(8)\n\troot.Left.Left.Left = newBinaryTreeNode(0)\n\troot.Right.Right.Left = newBinaryTreeNode(7)\n\n\t*rootAddress = root\n}", "func NewTree(fs []SymbolFreq) Tree {\n\t// Sort frequencies\n\tsort.Sort(byFreq(fs))\n\n\twrkList := []node{}\n\tfor _, f := range fs {\n\t\twrkList = append(wrkList, f)\n\t}\n\n\tfor {\n\t\tif len(wrkList) < 2 {\n\t\t\tbreak\n\t\t}\n\n\t\tnewNode := makeNewNode(wrkList[0], wrkList[1])\n\n\t\twrkList = insertItem(wrkList[2:], newNode)\n\t}\n\n\treturn Tree{wrkList[0]}\n}", "func NewTree(r RuleHandle) (*Tree, error) {\n\tif r.Detection == nil {\n\t\treturn nil, ErrMissingDetection{}\n\t}\n\texpr, ok := r.Detection[\"condition\"].(string)\n\tif !ok {\n\t\treturn nil, ErrMissingCondition{}\n\t}\n\n\tp := &parser{\n\t\tlex: lex(expr),\n\t\tcondition: expr,\n\t\tsigma: r.Detection,\n\t\tnoCollapseWS: r.NoCollapseWS,\n\t}\n\tif err := p.run(); err != nil {\n\t\treturn nil, err\n\t}\n\tt := &Tree{\n\t\tRoot: p.result,\n\t\tRule: &r,\n\t}\n\treturn t, nil\n}", "func newStudentState(content *Content) *studentState {\n\tstate := &studentState{content: content}\n\tstate.reset()\n\treturn state\n}", "func (p *Contentity) st2b_BuildIntoTree() *Contentity {\n\tif p.HasError() {\n\t\treturn p\n\t}\n\tvar e error\n\tp.GTree, e = gtree.NewGTreeFromGTags(p.GTags)\n\tif e != nil {\n\t\tprintln(\"==> mcfl.st2b: Error!:\", e.Error())\n\t\tp.WrapError(\"NewGTreeFromGTags\", e)\n\t\treturn p\n\t}\n\tif p.GTree == nil {\n\t\tprintln(\"==> mcfl.st2b: got nil Gtree: %s\", e.Error())\n\t\tp.WrapError(\"nil tree from NewGTreeFromGTags\", e)\n\t}\n\tif p.GTree != nil && p.GTreeWriter != nil &&\n\t\tp.GTreeWriter != io.Discard {\n\t\tgtoken.DumpTo(p.GTokens, p.GTreeWriter)\n\t} else {\n\t\tgtoken.DumpTo(p.GTokens, os.Stdout)\n\t}\n\treturn p\n}", "func New(dgree int, ctx interface{}) *BTree {\n\treturn NewWithFreeList(degree, NewFreeList(DefaultFreeListSize), ctx)\n}", "func newt(terms []string) Tree {\n\tkvs := make([]kv, 0, len(terms))\n\tfor i, k := range terms {\n\t\tkvs = append(kvs, kv{[]byte(k), i})\n\t}\n\tsort.Slice(kvs, func(i, j int) bool {\n\t\ta, b := kvs[i].k, kvs[j].k\n\t\tfor i := 0; i < len(a) && i < len(b); i++ {\n\t\t\tif a[i] == b[i] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn a[i] < b[i]\n\t\t}\n\t\treturn len(a) < len(b)\n\t})\n\n\tt := Tree{node{next: 1}}\n\n\tt = t.construct(kvs, 0, 0)\n\treturn t\n}", "func New() Tree {\n\treturn &binarySearchTree{}\n}", "func buildTree(preorder []int, inorder []int) *TreeNode {\n\t// 先判断长度,返回空的情况\n\tif len(preorder) == 0 || len(inorder) == 0 {\n\t\treturn nil\n\t}\n\t// 从preorder里面找到根节点的坐标,然后做拆分\n\tidx := getIdx(inorder, preorder[0])\n\n\t// 递归构造树\n\troot := &TreeNode{\n\t\tVal: preorder[0],\n\t\tLeft: buildTree(preorder[1:idx+1], inorder[:idx]),\n\t\tRight: buildTree(preorder[idx+1:], inorder[idx+1:]),\n\t}\n\treturn root\n}", "func NewTreeNode(d int) *TreeNode {\n\treturn &TreeNode{\n\t\tdata: d,\n\t\tsize: 1,\n\t}\n}", "func NewBSTree() *BSTree {\n\tb := &BSTree{\n\t\tleft: &BSTree{},\n\t\tright: &BSTree{},\n\t}\n\treturn b\n}", "func (pm *PathMap) _createTree(path []string) *PathMap {\n\ttree := pm\n\tfor _, component := range path {\n\t\tsubtree, ok := tree.dirs[component]\n\t\tif ok {\n\t\t\t// The component already exists. Unshare it so that\n\t\t\t// it can be modified without messing with other PathMaps\n\t\t\tsubtree = subtree._unshare()\n\t\t} else {\n\t\t\t// Create the component as a directory\n\t\t\tsubtree = newPathMap()\n\t\t}\n\t\t// Put the new or snapshot tree in place, and go down a level\n\t\ttree.dirs[component] = subtree\n\t\ttree = subtree\n\t}\n\treturn tree\n}" ]
[ "0.6912023", "0.6191913", "0.6073148", "0.60606235", "0.6037155", "0.59091216", "0.58979636", "0.58852684", "0.5877665", "0.5856578", "0.583802", "0.5774494", "0.5756803", "0.57559043", "0.5738696", "0.5727683", "0.5727124", "0.5712563", "0.5702321", "0.56940013", "0.5655744", "0.56385726", "0.56345934", "0.56321985", "0.5622304", "0.56064886", "0.56003165", "0.5597568", "0.5590963", "0.5575393", "0.5561368", "0.5539236", "0.5537224", "0.5513302", "0.54868394", "0.5485376", "0.5480623", "0.54600066", "0.5451722", "0.5449684", "0.54488575", "0.5421222", "0.54113716", "0.54060936", "0.5401457", "0.5393409", "0.53910464", "0.5380275", "0.5362926", "0.53515744", "0.53482693", "0.5323391", "0.5316233", "0.53147906", "0.52998525", "0.5297487", "0.52868015", "0.52810615", "0.5279192", "0.52777797", "0.5265121", "0.52641", "0.5260487", "0.52574235", "0.52524614", "0.5248247", "0.5245588", "0.5229439", "0.52266645", "0.5224337", "0.5210951", "0.51858914", "0.5185389", "0.5179666", "0.5179659", "0.51763254", "0.5174438", "0.51735127", "0.51676667", "0.5164829", "0.51591676", "0.51559013", "0.5141789", "0.51385206", "0.5137637", "0.5136117", "0.51336616", "0.5129997", "0.5123709", "0.5117777", "0.51100326", "0.51096815", "0.5109246", "0.5088807", "0.50872225", "0.50785553", "0.5072015", "0.50713056", "0.5065567", "0.5056995" ]
0.8084078
0
Len returns the current number of items in the tree It needs to query all allocators for their counters, so it will block if an allocator is constantly reserved...
func (idx *Tree) Len() (count int) { idx.Stop() count = int(idx.liveObjects) for _, a := range idx.allocators { count += int(a.itemCounter) } idx.Start() return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *Tree) Len() int { return t.Count }", "func (s *Pool) Len() int { return int(atomic.LoadUint32(&s.avail)) }", "func (t *BinaryTree) Size() int { return t.count }", "func (t *Tree) Len() int {\n\treturn t.Count\n}", "func (h ReqHeap) Len() int { return len(h) }", "func (p NodePools) Len() int { return len(p) }", "func (r *Root) Len() uint64 {\n\treturn r.count\n}", "func (this *Manager) GetNodesLen() int {\n\treturn len(this.nodes)\n}", "func (s *orderedSynchronizer) Len() int {\n\treturn len(s.heap)\n}", "func (h PerformanceHeap) Len() int { return len(h.items) }", "func (h *Heap) Len() int { return len(h.slice) }", "func (n Nodes) Len() int", "func (buf *queueBuffer) Len() uint64 {\n\treturn buf.depth\n}", "func (r *RlogcHeap) Len() int { return r.queue.Len() }", "func (o *OrderedSynchronizer) Len() int {\n\treturn len(o.heap)\n}", "func (tree *BTree) Length() int {\n\tif tree.isset {\n\t\tif tree.length == 0 {\n\t\t\ttree.length = tree.uncachedLength()\n\t\t}\n\t\treturn tree.length\n\t}\n\treturn 0\n}", "func (b *BTree) Len() int {\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\treturn int(b.rootNod.GetLength())\n}", "func (t *Trie) Len() uint32 {\n\tif t.root == nil {\n\t\treturn 0\n\t}\n\treturn t.root.count\n}", "func (t *Tree) Size() uint {\n\tif t.Safe {\n\t\tdefer t.mtx.RUnlock()\n\t\tt.mtx.RLock()\n\t}\n\n\treturn t.size + 1\n}", "func (v ResourceNodes) Len() int {\n\treturn len(v)\n}", "func (em *eventManager) Len() int {\n\treturn len(em.heap)\n}", "func (bt *Tree) Length() int {\n\treturn bt.length\n}", "func (ri *rawItemList) len() int { return len(ri.cumSize) }", "func (bh blockHeap) Len() int {\n\treturn bh.impl.Len()\n}", "func (tree *RedBlack[K, V]) Len() int {\n\treturn tree.size\n}", "func (l *LRU) Len() int {\n\tl.lazyInit()\n\tvar len int\n\tfor i := 0; i < l.nshards; i++ {\n\t\tlen += l.shards[i].Len()\n\t}\n\treturn len\n}", "func (n *TreeBuilderNode) Size() uint64 { return n.size }", "func (c *Cache) Len() int {\n\tif c == nil {\n\t\treturn 0\n\t}\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.lru.Len() + c.mfa.Len()\n}", "func (h tHeap) Len() int { return len(h) }", "func (t *RbTree[K, V]) Size() int {\n\treturn t.size\n}", "func (n nodes) Len() int { return len(n) }", "func (qi *Items) Len() int {\n\tqi.RLock()\n\tc := qi.Length\n\tlog.Printf(\"queue length: %d\\n\", c)\n\tqi.RUnlock()\n\treturn c\n}", "func (rb *RingBuffer[T]) Len() int {\n\tif rb == nil {\n\t\treturn 0\n\t}\n\trb.mu.Lock()\n\tdefer rb.mu.Unlock()\n\treturn len(rb.buf)\n}", "func (pool GenePool) Len() int {\n return len(pool)\n}", "func (tr *Tree) Len() int {\n\treturn tr.len\n}", "func (t *TrieNode) Len() int {\n\tt.mx.RLock()\n\tdefer t.mx.RUnlock()\n\treturn t.LenHelper()\n}", "func (fib *Fib) Len() int {\n\treturn fib.tree.CountEntries()\n}", "func (seq *Sequence) Len() int { return len(seq.Nodes) }", "func (q *Queue) Len() int {\n\tlength := 0\n\n\tfor _, current := range q.Items {\n\t\tif !current.IsReserved() {\n\t\t\tlength++\n\t\t}\n\t}\n\n\treturn length\n}", "func (ms *memoryStore) Len() int {\n\treturn len(ms.namespaces)\n}", "func (ac *AuthContext) Len() int {\n\tl := 1\n\tif ac.Parent != nil {\n\t\tl += ac.Parent.Len()\n\t}\n\treturn l\n}", "func (m *SplitNode_Children) Len() int {\n\tif m.Dense != nil {\n\t\tn := 0\n\t\tm.ForEach(func(_ int, _ int64) bool { n++; return true })\n\t\treturn n\n\t}\n\treturn len(m.Sparse)\n}", "func (l *semaphoreList) length() int {\n\tl.RLock()\n\tdefer l.RUnlock()\n\tlength := len(l.list)\n\treturn length\n}", "func (this *List) Len() int {\n this.lock.RLock()\n this.lock.RUnlock()\n\n return len(this.counters)\n}", "func (t Tree) Size() int {\n\tif t.Symbol.Kind == NIL {\n\t\treturn 0\n\t}\n\n\tcount := 1\n\tfor _, child := range t.Children {\n\t\tif child != nil {\n\t\t\tcount += child.Size()\n\t\t}\n\t}\n\n\treturn count\n}", "func (c *Cache) len() int {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\treturn c.evictList.Len()\n}", "func (r *KeyRing) Len() int {\n\treturn len(r.entities)\n}", "func (h minHeap) Len() int { return len(h) }", "func (c *LRU) Len() int {\n\treturn c.evictList.Len()\n}", "func (d *Dtrie) Size() (size int) {\n\tfor _ = range iterate(d.root, nil) {\n\t\tsize++\n\t}\n\treturn size\n}", "func (c *LruCache) Len() int {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\treturn c.evictList.Len()\n}", "func (lc *LruCache) Len() uint {\n\treturn lc.LruStore.Len()\n}", "func (s *Store) Len(ctx context.Context) (int64, error) {\n\tvar nb int64\n\tif err := s.List(ctx, \"\", func(string) error {\n\t\tnb++\n\t\treturn nil\n\t}); err != nil {\n\t\treturn 0, err\n\t}\n\treturn nb, nil\n}", "func AllocatorSize() (size uint32) {\n\t// size of freeBuddiesList\n\tsize += MaxOrder * uint32(unsafe.Sizeof(freeBuddiesList{}))\n\n\t// size of bigPagesBitmap\n\tsize += nMaps(_nBigPages) * 4\n\n\t// size of individual freeBuddiesList\n\tfor i := 0; i < MaxOrder; i++ {\n\t\t// maxOrder - 1 pages of order i, further divide by 2 since we use 1 bit\n\t\t// for buddy pair.\n\t\tvar nBuddies uint32 = _nBigPages * (1 << uint32(MaxOrder-i-1))\n\t\tsize += nMaps(nBuddies) * 4\n\t}\n\n\t// size of node pool\n\tsize += nodePoolSize()\n\n\treturn\n}", "func (h MaxHeap) Len() int { return len(h) }", "func (queue PriorityQueue) Len() int {\n\treturn queue.heap.Len()\n}", "func (r *RingT[T]) Len() int {\n\treturn int((r.head - r.tail) & r.mask)\n}", "func (p *Pool) AllocCount() int {\n\tp.RLock()\n\tdefer p.RUnlock()\n\treturn len(p.allocated)\n}", "func (t *AATree) Size() int {\n\tif t.root == nil {\n\t\treturn 0\n\t}\n\t// return t.root\n\treturn 0\n}", "func (c *LRU) Len() int {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.ll.Len()\n}", "func (tree *UTree) Size() int {\r\n\treturn tree.size\r\n}", "func (blt Bolt) Length() int {\n\tvar len int\n\tblt.db.View(func(tx *b.Tx) error { //nolint:errcheck\n\t\tlen = tx.Bucket(blt.Bucket).Stats().KeyN\n\t\treturn nil\n\t})\n\treturn len\n}", "func (lm *LevelMetadata) Len() int {\n\treturn lm.tree.Count()\n}", "func (lru *KeyLRU) Len() int {\n\treturn len(lru.m)\n}", "func (p Pool) Len() int { return len(p) }", "func (m *Manager) Len() int {\n\treturn m.hub.len()\n}", "func (ne nodeEntries) Len() int { return len(ne) }", "func (c *LRU) Len() int {\n\tc.RLock()\n\tresult := c.evictList.Len()\n\tc.RUnlock()\n\treturn result\n}", "func (nc *NvmeController) Capacity() (tb uint64) {\n\tif nc == nil {\n\t\treturn 0\n\t}\n\tfor _, n := range nc.Namespaces {\n\t\ttb += n.Size\n\t}\n\treturn\n}", "func (c *RingBuffer) Len() int {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\treturn c.len\n}", "func (s *scope) len() int {\n\tl := 0\n\tfor _, level := range s.levels {\n\t\tl += len(level.named) + len(level.init)\n\t}\n\treturn l\n}", "func (candidates *LookupCandidates) Len() int {\n\treturn len(candidates.Nodelist)\n}", "func (candidates *LookupCandidates) Len() int {\n\treturn len(candidates.Nodelist)\n}", "func (a nodesInRequestOrder) Len() int { return len(a) }", "func alloc() uint64 {\n\tvar stats runtime.MemStats\n\truntime.GC()\n\truntime.ReadMemStats(&stats)\n\t// return stats.Alloc - uint64(unsafe.Sizeof(hs[0]))*uint64(cap(hs))\n\treturn stats.Alloc\n}", "func (sm safeMap) Len() int {\n\treply := make(chan interface{})\n\tsm <- commandData{action: COUNT, result: reply}\n\treturn (<-reply).(int)\n}", "func (c *Cache) Len() int {\n\tvar len int\n\tfor _, shard := range c.shards {\n\t\tlen += shard.policy.Len()\n\t}\n\n\treturn len\n}", "func (rb *RingBuffer) Len() int {\n\trb.lock.RLock()\n\tdefer rb.lock.RUnlock()\n\tif n := len(rb.data); rb.seq < uint64(n) {\n\t\treturn int(rb.seq)\n\t} else {\n\t\treturn n\n\t}\n}", "func (q *Stack) Len() int {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\treturn q.count\n}", "func (s *Stack) Len() int {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn s.count\n}", "func (ms *multiSorter) Len() int {\n\treturn len(ms.Nodes)\n}", "func (sr *Stackers) Length() int {\n\tvar l int\n\tsr.ro.Lock()\n\t{\n\t\tl = len(sr.stacks)\n\t\tsr.ro.Unlock()\n\t}\n\treturn l\n}", "func (h MinHeap) Len() int { return len(h) }", "func (sc *Scavenger) Len() int {\n\tsc.mu.Lock()\n\tn := len(sc.entries)\n\tsc.mu.Unlock()\n\treturn n\n}", "func (db *MemoryCache) Len() int {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\treturn len(db.db)\n}", "func (s *nodeSorter) Len() int {\n\treturn len(s.nodes)\n}", "func (s *stackImpl) Len() int {\n\treturn len(s.items)\n}", "func (t *BinarySearchTree) Size() int {\n\treturn 0\n}", "func (c *UnlimitedCache) Len() int {\n\treturn len(c.m)\n}", "func (q *wantConnQueue) len() int {\n\treturn len(q.head) - q.headPos + len(q.tail)\n}", "func (storage *Storage) Len() (n int) {\n\tstorage.mutex.Lock()\n\tn = storage.lruList.Len()\n\tstorage.mutex.Unlock()\n\treturn\n}", "func (node *Node) Len() int {\n\treturn node.buf.Len()\n}", "func (md MinQueue) Len() int { return len(md) }", "func (h *Heap) Len() int {\n\treturn len(h.data.queue)\n}", "func (t *TrieNode) LenHelper() int {\n\tentryCount := len(t.values)\n\tfor child := range t.children {\n\t\tentryCount += t.children[child].LenHelper()\n\t}\n\treturn entryCount\n}", "func (n *NodeSorter) Len() int {\n\treturn len(n.nodes)\n}", "func (h *hashRing) Size() int {\n\treturn len(h.nodes)\n}", "func (c Containers) Length() int {\n\treturn len(c)\n}", "func (q *queue) Len() int {\n\tq.lock.RLock()\n\tdefer q.lock.RUnlock()\n\tc := q.tail - q.head\n\tif c < 0 {\n\t\tc = 0\n\t}\n\n\treturn c\n}", "func (t *MCTS) alloc() Naughty {\n\tt.Lock()\n\tdefer t.Unlock()\n\tl := len(t.freelist)\n\tif l == 0 {\n\t\tN := Node{\n\t\t\tlock: sync.Mutex{},\n\t\t\ttree: ptrFromTree(t),\n\t\t\tid: Naughty(len(t.nodes)),\n\t\t\thasChildren: false,\n\t\t}\n\t\tt.nodes = append(t.nodes, N)\n\t\tt.children = append(t.children, make([]Naughty, 0, t.current.ActionSpace()))\n\t\tn := Naughty(len(t.nodes) - 1)\n\t\treturn n\n\t}\n\n\ti := t.freelist[l-1]\n\tt.freelist = t.freelist[:l-1]\n\treturn i\n}" ]
[ "0.6939439", "0.6840272", "0.6690427", "0.6655519", "0.6647418", "0.66106826", "0.64596206", "0.6438696", "0.64009213", "0.6397146", "0.6384905", "0.6336007", "0.6332157", "0.6309753", "0.6295182", "0.62948596", "0.62872094", "0.6268528", "0.6266187", "0.62337065", "0.6231077", "0.62103856", "0.620677", "0.61662656", "0.61635333", "0.6145804", "0.61448765", "0.6140936", "0.6130743", "0.6129027", "0.61256754", "0.6116637", "0.61157215", "0.6114252", "0.60936993", "0.60863984", "0.6082177", "0.6051007", "0.6035896", "0.60289747", "0.60203236", "0.60142094", "0.6006133", "0.6003219", "0.59928966", "0.59878474", "0.59788406", "0.59749025", "0.59655935", "0.5957082", "0.59501815", "0.5949283", "0.59476954", "0.59433067", "0.59377", "0.5921969", "0.5916688", "0.5915226", "0.59064347", "0.59056205", "0.59021556", "0.5897286", "0.5883292", "0.5881635", "0.5879257", "0.58736646", "0.58731294", "0.5866175", "0.58581936", "0.5858064", "0.5857676", "0.58573294", "0.58573294", "0.5855873", "0.5855465", "0.58548427", "0.58541745", "0.5852701", "0.5848677", "0.58457965", "0.5840112", "0.5838294", "0.5836919", "0.58256626", "0.58233106", "0.5822644", "0.5813346", "0.5812319", "0.5811154", "0.5810775", "0.5810448", "0.58101815", "0.58079267", "0.57980293", "0.5794227", "0.57879823", "0.57846475", "0.5784435", "0.5782686", "0.57822335" ]
0.8014996
0
Stop withdraws all allocators to prevent any more write or reads. It will blocks until it gets all allocators. If already stopped, it returns silently.
func (idx *Tree) Stop() { if !atomic.CompareAndSwapInt32(&idx.stopped, 0, 1) { return } for i := 0; i < len(idx.allocators); i++ { _ = idx.allocatorQueue.get() } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (fetchers Fetchers) Stop() {\n\tfor _, fetcher := range fetchers {\n\t\tfetcher.Stop()\n\t}\n}", "func (r *reducer) stop() {\n\tfor _, m := range r.mappers {\n\t\tm.stop()\n\t}\n\tsyncClose(r.done)\n}", "func exitAllocRunner(runners ...AllocRunner) {\n\tfor _, ar := range runners {\n\t\tterminalAlloc := ar.Alloc().Copy()\n\t\tterminalAlloc.DesiredStatus = structs.AllocDesiredStatusStop\n\t\tar.Update(terminalAlloc)\n\t}\n}", "func (it *messageIterator) stop() {\n\tit.cancel()\n\tit.mu.Lock()\n\tit.checkDrained()\n\tit.mu.Unlock()\n\tit.wg.Wait()\n}", "func (c *ResourceSemaphore) stop() {\n\tcount := 0\n\n\tfor {\n\t\tselect {\n\t\tcase d := <-c.received: // wait for all resource released\n\t\t\tc.storage <- d\n\t\tcase <-c.storage:\n\t\t\tcount += 1\n\t\t\tif count == c.size {\n\t\t\t\tclose(c.endChan) // all resource released\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *Pacer) Stop() {\n\tclose(p.gate)\n}", "func (c *Context) watchStop(walker *ContextGraphWalker) (chan struct{}, <-chan struct{}) {\n\tstop := make(chan struct{})\n\twait := make(chan struct{})\n\n\t// get the runContext cancellation channel now, because releaseRun will\n\t// write to the runContext field.\n\tdone := c.runContext.Done()\n\n\tgo func() {\n\t\tdefer close(wait)\n\t\t// Wait for a stop or completion\n\t\tselect {\n\t\tcase <-done:\n\t\t\t// done means the context was canceled, so we need to try and stop\n\t\t\t// providers.\n\t\tcase <-stop:\n\t\t\t// our own stop channel was closed.\n\t\t\treturn\n\t\t}\n\n\t\t// If we're here, we're stopped, trigger the call.\n\n\t\t{\n\t\t\t// Copy the providers so that a misbehaved blocking Stop doesn't\n\t\t\t// completely hang Terraform.\n\t\t\twalker.providerLock.Lock()\n\t\t\tps := make([]ResourceProvider, 0, len(walker.providerCache))\n\t\t\tfor _, p := range walker.providerCache {\n\t\t\t\tps = append(ps, p)\n\t\t\t}\n\t\t\tdefer walker.providerLock.Unlock()\n\n\t\t\tfor _, p := range ps {\n\t\t\t\t// We ignore the error for now since there isn't any reasonable\n\t\t\t\t// action to take if there is an error here, since the stop is still\n\t\t\t\t// advisory: Terraform will exit once the graph node completes.\n\t\t\t\tp.Stop()\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\t// Call stop on all the provisioners\n\t\t\twalker.provisionerLock.Lock()\n\t\t\tps := make([]ResourceProvisioner, 0, len(walker.provisionerCache))\n\t\t\tfor _, p := range walker.provisionerCache {\n\t\t\t\tps = append(ps, p)\n\t\t\t}\n\t\t\tdefer walker.provisionerLock.Unlock()\n\n\t\t\tfor _, p := range ps {\n\t\t\t\t// We ignore the error for now since there isn't any reasonable\n\t\t\t\t// action to take if there is an error here, since the stop is still\n\t\t\t\t// advisory: Terraform will exit once the graph node completes.\n\t\t\t\tp.Stop()\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn stop, wait\n}", "func (m *mapper) stop() { syncClose(m.done) }", "func (p *hardwareProfiler) Stop() error {\n\tvar err error\n\tfor _, profiler := range p.profilers {\n\t\terr = multierr.Append(err, profiler.Stop())\n\t}\n\treturn err\n}", "func Stop() {\n\tclose(configReloaderStopCh)\n\tconfigReloaderWG.Wait()\n\n\tfor _, rwctx := range rwctxsDefault {\n\t\trwctx.MustStop()\n\t}\n\trwctxsDefault = nil\n\n\t// There is no need in locking rwctxsMapLock here, since nobody should call Push during the Stop call.\n\tfor _, rwctxs := range rwctxsMap {\n\t\tfor _, rwctx := range rwctxs {\n\t\t\trwctx.MustStop()\n\t\t}\n\t}\n\trwctxsMap = nil\n\n\tif sl := hourlySeriesLimiter; sl != nil {\n\t\tsl.MustStop()\n\t}\n\tif sl := dailySeriesLimiter; sl != nil {\n\t\tsl.MustStop()\n\t}\n}", "func (collection *Collection) Stop() {\n\tfor _, c := range collection.collectors {\n\t\tc.Stop()\n\t\tcollection.wg.Done()\n\t}\n}", "func (ps *rateLimiter) Stop() { close(ps.exit) }", "func (csrl *CoalescingSerializingRateLimiter) Stop() {\n\tcsrl.lock.Lock()\n\tcsrl.stopped = true\n\tcsrl.lock.Unlock()\n\n\tfor csrl.isHandlerRunning() {\n\t\ttime.Sleep(50 * time.Millisecond)\n\t}\n}", "func (it *Iterator) Stop() {\n\tit.mu.Lock()\n\tdefer it.mu.Unlock()\n\n\tselect {\n\tcase <-it.closed:\n\t\t// Cleanup has already been performed.\n\t\treturn\n\tdefault:\n\t}\n\n\t// We close this channel before calling it.puller.Stop to ensure that we\n\t// reliably return Done from Next.\n\tclose(it.closed)\n\n\t// Stop the puller. Once this completes, no more messages will be added\n\t// to it.ka.\n\tit.puller.Stop()\n\n\t// Start acking messages as they arrive, ignoring ackTicker. This will\n\t// result in it.ka.Stop, below, returning as soon as possible.\n\tit.acker.FastMode()\n\n\t// This will block until\n\t// (a) it.ka.Ctx is done, or\n\t// (b) all messages have been removed from keepAlive.\n\t// (b) will happen once all outstanding messages have been either ACKed or NACKed.\n\tit.ka.Stop()\n\n\t// There are no more live messages, so kill off the acker.\n\tit.acker.Stop()\n\n\tit.kaTicker.Stop()\n\tit.ackTicker.Stop()\n}", "func (cm *CertMan) Stop() {\n\tcm.watching <- false\n}", "func (l *Launcher) Stop() {\n\tl.stop <- struct{}{}\n\tstopper := startstop.NewParallelStopper()\n\tfor identifier, tailer := range l.tailers {\n\t\tstopper.Add(tailer)\n\t\tdelete(l.tailers, identifier)\n\t}\n\tstopper.Stop()\n}", "func (b *Blinker) Stop() {\n\tclose(b.stop)\n}", "func (p *literalProcessor) stop() { syncClose(p.done) }", "func (r *reaper) stop() {\n\tr.stopCh <- struct{}{}\n}", "func (m *Manager) Stop() {\n\tclose(m.stop)\n\t<-m.stopDone\n}", "func (a *Acceptor) Stop() {\n\t//TODO(student): Task 3 - distributed implementation\n\ta.stop <- 0\n\n}", "func (b *blocksProviderImpl) Stop() {\n\tatomic.StoreInt32(&b.done, 1)\n\tb.client.CloseSend()\n}", "func (tCertPool *tCertPoolSingleThreadImpl) Stop() (err error) {\n\n\ttCertPool.m.Lock()\n\tdefer tCertPool.m.Unlock()\n\n\tfor k := range tCertPool.tcblMap {\n\t\tcertList := tCertPool.tcblMap[k]\n\t\ttCertPool.client.ks.storeUnusedTCerts(certList.GetUnusedTCertBlocks())\n\t}\n\n\ttCertPool.client.Debug(\"Store unused TCerts...done!\")\n\n\treturn\n}", "func (sp *scrapePool) stop() {\n\tsp.mtx.Lock()\n\tdefer sp.mtx.Unlock()\n\tsp.cancel()\n\tsp.targetMtx.Lock()\n\tvar wg sync.WaitGroup\n\twg.Add(len(sp.loops))\n\tfor fp, l := range sp.loops {\n\t\tgo func(l *scrapeLoop) {\n\t\t\tl.stop()\n\t\t\twg.Done()\n\t\t}(l)\n\t\tdelete(sp.loops, fp)\n\t\tdelete(sp.activeTargets, fp)\n\t}\n\tsp.targetMtx.Unlock()\n\twg.Wait()\n\tsp.client.CloseIdleConnections()\n}", "func (m *Manager) Stop() {\n\tfor _, bot := range m.bots {\n\t\tbot.Close()\n\t}\n\n\tm.running = false\n}", "func (p *Pool) Stop() {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\tp.cancel()\n\tfor _, routine := range p.routines {\n\t\troutine.stop <- true\n\t}\n\tp.waitGroup.Wait()\n\tfor _, routine := range p.routines {\n\t\tclose(routine.stop)\n\t}\n}", "func (s *stateManager) Stop() {\n\tfor _, c := range s.stopChan {\n\t\tc <- true\n\t}\n\ts.cli.Close()\n}", "func (s *BufferedWriteSyncer) Stop() (err error) {\n\tvar stopped bool\n\n\t// Critical section.\n\tfunc() {\n\t\ts.mu.Lock()\n\t\tdefer s.mu.Unlock()\n\n\t\tif !s.initialized {\n\t\t\treturn\n\t\t}\n\n\t\tstopped = s.stopped\n\t\tif stopped {\n\t\t\treturn\n\t\t}\n\t\ts.stopped = true\n\n\t\ts.ticker.Stop()\n\t\tclose(s.stop) // tell flushLoop to stop\n\t\t// close(s.flush) // close flush chan\n\t\t<-s.done // and wait until it has\n\t}()\n\n\t// Don't call Sync on consecutive Stops.\n\tif !stopped {\n\t\terr = s.Sync()\n\t}\n\n\treturn err\n}", "func (dt *discoveryTool) stop() {\n\tclose(dt.done)\n\n\t//Shutdown timer\n\ttimer := time.NewTimer(time.Second * 3)\n\tdefer timer.Stop()\nL:\n\tfor { //Unblock go routine by reading from dt.dataChan\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\tbreak L\n\t\tcase <-dt.dataChan:\n\t\t}\n\t}\n\n\tdt.wg.Wait()\n}", "func (rp *ResolverPool) Stop() error {\n\trp.hasBeenStopped = true\n\n\tfor _, r := range rp.Resolvers {\n\t\tr.Stop()\n\t}\n\n\trp.Resolvers = []Resolver{}\n\treturn nil\n}", "func (margelet *Margelet) Stop() {\n\tmargelet.running = false\n}", "func (w *StatsWriter) Stop() {\n\tw.stop <- struct{}{}\n\t<-w.stop\n\tstopSenders(w.senders)\n}", "func (d *Dispatcher) Stop(){\n\tfor _, w := range d.Workers {\n\t\tw.Stop()\n\t}\n}", "func (v *vtStopCrawler) stop() {\n\tfor _, worker := range v.workers {\n\t\tworker.stop()\n\t}\n\tclose(v.done)\n}", "func (wp *WorkerPool[T]) Stop() {\n\twp.mutex.Lock()\n\tif !wp.started {\n\t\twp.mutex.Unlock()\n\t\treturn\n\t}\n\n\tif !wp.stopped {\n\n\t\tfor i := 0; i < wp.numShards; i++ {\n\t\t\tshard := wp.shards[i]\n\t\t\tshard.mutex.Lock()\n\t\t\tshard.stopped = true\n\t\t\tfor j := 0; j < len(shard.idleWorkerList); j++ {\n\t\t\t\tif !shard.idleWorkerList[j].isDeleted {\n\t\t\t\t\tshard.idleWorkerList[j].isDeleted = true\n\t\t\t\t\tclose(shard.idleWorkerList[j].taskChan)\n\t\t\t\t}\n\t\t\t}\n\t\t\tshard.mutex.Unlock()\n\t\t}\n\t}\n\twp.stopped = true\n\twp.mutex.Unlock()\n}", "func (p *GoroutinePool) Stop() {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tif !p.running {\n\t\treturn\n\t}\n\tfor _, w := range p.allWorkers {\n\t\tw.stop <- struct{}{}\n\t}\n\n\tp.Wait()\n\n\tclose(p.workers)\n\tp.running = false\n}", "func (p *Pool) Stop() {\n\tfor _, worker := range p.Workers {\n\t\tworker.Stop()\n\t}\n\tp.RunningBackground <-true\n}", "func (a *appsec) stop() {\n\ta.unregisterWAF()\n\ta.limiter.Stop()\n}", "func (m *ProbeManager) Stop() {\n\tclose(m.done)\n}", "func (l *Learner) Stop() {\n\t// TODO(student): distributed implementation\n\tl.stop <- struct{}{}\n}", "func (s *Bgmchain) Stop() error {\n\tif s.stopDbUpgrade != nil {\n\t\ts.stopDbUpgrade()\n\t}\n\ts.bloomIndexer.Close()\n\ts.blockchain.Stop()\n\ts.protocolManager.Stop()\n\tif s.lesServer != nil {\n\t\ts.lesServer.Stop()\n\t}\n\ts.txPool.Stop()\n\ts.miner.Stop()\n\ts.eventMux.Stop()\n\n\ts.chainDbPtr.Close()\n\tclose(s.shutdownChan)\n\n\treturn nil\n}", "func (c *ZKCluster) Stop() {\n\tif c.checkerdone != nil {\n\t\tclose(c.checkerdone)\n\t\tclose(c.updates)\n\t\tc.checkerdone = nil\n\t}\n}", "func (c *Cache) Stop() {\n\tclose(c.promotables)\n\t<-c.donec\n}", "func (phStats *passwordHasherStats) stopAccumulating() {\n\tclose(phStats.queue)\n}", "func (c *Concentrator) Stop() {\n\tclose(c.exit)\n\tc.exitWG.Wait()\n}", "func (ab *Buffer) Stop() error {\n\tif !ab.Latch.CanStop() {\n\t\treturn ex.New(async.ErrCannotStop)\n\t}\n\t// stop the interval worker\n\tab.intervalWorker.WaitStopped()\n\n\t// stop the running dispatch loop\n\tab.Latch.WaitStopped()\n\n\ttimeoutContext, cancel := context.WithTimeout(ab.Background(), ab.ShutdownGracePeriod)\n\tdefer cancel()\n\n\tab.contentsMu.Lock()\n\tdefer ab.contentsMu.Unlock()\n\tif ab.contents.Len() > 0 {\n\t\tab.flushes <- Flush{\n\t\t\tContext: timeoutContext,\n\t\t\tContents: ab.contents.Drain(),\n\t\t}\n\t}\n\n\tif remainingFlushes := len(ab.flushes); remainingFlushes > 0 {\n\t\tlogger.MaybeDebugf(ab.Log, \"%d flushes remaining\", remainingFlushes)\n\t\tvar flushWorker *async.Worker\n\t\tvar flush Flush\n\t\tfor x := 0; x < remainingFlushes; x++ {\n\t\t\tselect {\n\t\t\tcase <-timeoutContext.Done():\n\t\t\t\tlogger.MaybeDebugf(ab.Log, \"stop timed out\")\n\t\t\t\treturn nil\n\t\t\tcase flush = <-ab.flushes:\n\t\t\t\tselect {\n\t\t\t\tcase <-timeoutContext.Done():\n\t\t\t\t\tlogger.MaybeDebugf(ab.Log, \"stop timed out\")\n\t\t\t\t\treturn nil\n\t\t\t\tcase flushWorker = <-ab.flushWorkersReady:\n\t\t\t\t\tflushWorker.Work <- flush\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tworkersStopped := make(chan struct{})\n\tgo func() {\n\t\tdefer close(workersStopped)\n\t\twg := sync.WaitGroup{}\n\t\twg.Add(len(ab.flushWorkers))\n\t\tfor index, worker := range ab.flushWorkers {\n\t\t\tgo func(i int, w *async.Worker) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tlogger.MaybeDebugf(ab.Log, \"draining worker %d\", i)\n\t\t\t\tw.StopContext(timeoutContext)\n\t\t\t}(index, worker)\n\t\t}\n\t\twg.Wait()\n\t}()\n\n\tselect {\n\tcase <-timeoutContext.Done():\n\t\tlogger.MaybeDebugf(ab.Log, \"stop timed out\")\n\t\treturn nil\n\tcase <-workersStopped:\n\t\treturn nil\n\t}\n}", "func (s *Spooler) Stop() {\n\tlogp.Info(\"Stopping spooler\")\n\n\t// Signal to the run method that it should stop.\n\tclose(s.exit)\n\n\t// Stop accepting writes. Any events in the channel will be flushed.\n\tclose(s.Channel)\n\n\t// Wait for the flush to complete.\n\ts.wg.Wait()\n\tdebugf(\"Spooler has stopped\")\n}", "func stopWatchHeapOps() {\n\tquitChan <- true\n}", "func (l *Learner) Stop() {\n\tl.stop <- true\n}", "func (a *Appender) Stop() {\n\tif !a.started {\n\t\treturn\n\t}\n\ta.started = false\n\tclose(a.finish)\n\ta.wg.Wait()\n\t// all channels can be closed now, but then users can not start this\n\t// appender again.\n}", "func (g *GRPC) Stop() {\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\n\tif g == nil {\n\t\treturn\n\t}\n\n\tfor _, cancel := range g.cancelFuncs {\n\t\tcancel()\n\t}\n\n\tg.serv.GracefulStop()\n\n\tg.lis = nil\n}", "func (c *collector) Stop() {\n\tclose(c.stop)\n}", "func (g *Group) Stop() {\n\tif g.Total > len(g.threads) {\n\t\tdefer close(g.chanStop)\n\t\tg.chanStop <- true\n\t}\n\n\tfor _, ok := range g.threads {\n\t\tok.Stop()\n\t}\n}", "func (s *samplerBackendRateCounter) Stop() {\n\tclose(s.exit)\n\t<-s.stopped\n}", "func (w *Watch) stop() {\n\tw.done <- struct{}{}\n}", "func (l *Learner) Stop() {\n\t//TODO(student): Task 3 - distributed implementation\n}", "func (a *Acceptor) Stop() {\n\t//TODO(student): Task 3 - distributed implementation\n\ta.stopChan <- 0\n}", "func (d *Dispatcher) Stop() {\n\td.rwMutex.Lock()\n\tdefer d.rwMutex.Unlock()\n\td.asyncWG.Wait()\n}", "func (rp *ResolverPool) Stop() error {\n\tif rp.hasBeenStopped {\n\t\treturn nil\n\t}\n\trp.hasBeenStopped = true\n\tclose(rp.Done)\n\n\tfor _, r := range rp.Resolvers {\n\t\tr.Stop()\n\t}\n\n\trp.Resolvers = []Resolver{}\n\treturn nil\n}", "func (f *flushDaemon) stop() {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\tif f.stopC == nil { // daemon not running\n\t\treturn\n\t}\n\n\tf.stopC <- struct{}{}\n\t<-f.stopDone\n\n\tf.stopC = nil\n\tf.stopDone = nil\n}", "func (s *Scanner) Stop() {\n\ts.stop <- struct{}{}\n}", "func (is *idleSweep) Stop() {\n\tif !is.started {\n\t\treturn\n\t}\n\n\tis.started = false\n\tis.ch.log.Info(\"Stopping idle connections poller.\")\n\tclose(is.stopCh)\n}", "func (c *NsqConsumer) Stop() {\n\tfor _, h := range c.handlers {\n\t\th.Stop()\n\t}\n\tif c.C != nil {\n\t\tclose(c.C)\n\t}\n}", "func (b *breachArbiter) Stop() error {\n\tif !atomic.CompareAndSwapUint32(&b.stopped, 0, 1) {\n\t\treturn nil\n\t}\n\n\tbrarLog.Infof(\"Breach arbiter shutting down\")\n\n\tclose(b.quit)\n\tb.wg.Wait()\n\n\treturn nil\n}", "func (e *binaryExprEvaluator) stop() {\n\te.lhs.stop()\n\te.rhs.stop()\n\tsyncClose(e.done)\n}", "func (d *Dispatcher) Stop() error {\n\tfor _, w := range d.Workers {\n\t\tw.Stop()\n\t}\n\treturn nil\n}", "func StopAll() {\n\tfor {\n\t\tglobal.Lock()\n\t\tfor _, pool := range global.pools {\n\t\t\tgo pool.Stop()\n\t\t}\n\t\tglobal.Unlock()\n\t}\n}", "func (recBuf *recBuf) lockedStopLinger() {\n\tif recBuf.lingering != nil {\n\t\trecBuf.lingering.Stop()\n\t\trecBuf.lingering = nil\n\t}\n}", "func (b *Bootstrapper) Stop() {\n\tif b.cancel != nil {\n\t\tb.cancel()\n\t}\n}", "func (c *KeyCertBundleRotator) Stop() {\n\tc.stoppedMutex.Lock()\n\tif !c.stopped {\n\t\tc.stopped = true\n\t\tc.stopCh <- true\n\t}\n\tc.stoppedMutex.Unlock()\n}", "func (s *Stopper) Stop(ctx context.Context) {\n\ts.mu.Lock()\n\tstopCalled := s.mu.stopping\n\ts.mu.stopping = true\n\ts.mu.Unlock()\n\n\tif stopCalled {\n\t\t// Wait for the concurrent Stop() to complete.\n\t\t<-s.stopped\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\ts.Recover(ctx)\n\t\tunregister(s)\n\t\tclose(s.stopped)\n\t}()\n\n\t// Don't bother doing stuff cleanly if we're panicking, that would likely\n\t// block. Instead, best effort only. This cleans up the stack traces,\n\t// avoids stalls and helps some tests in `./cli` finish cleanly (where\n\t// panics happen on purpose).\n\tif r := recover(); r != nil {\n\t\tgo s.Quiesce(ctx)\n\t\ts.mu.Lock()\n\t\tfor _, c := range s.mu.closers {\n\t\t\tgo c.Close()\n\t\t}\n\t\ts.mu.Unlock()\n\t\tpanic(r)\n\t}\n\n\ts.Quiesce(ctx)\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfor _, c := range s.mu.closers {\n\t\tc.Close()\n\t}\n}", "func (p *Provider) Stop() {\n\tclose(p.stop)\n\t<-p.stopDone\n}", "func (er *BufferedExchangeReporter) Stop() {\n\n}", "func (_m *MockCompactionPlanContext) stop() {\n\t_m.Called()\n}", "func (gc *GC) Stop() {\n\tgc.mu.Lock()\n\tdefer gc.mu.Unlock()\n\tif gc.ticker == nil {\n\t\treturn // not started\n\t}\n\tgc.ticker.Stop()\n\tgc.ticker = nil\n}", "func (ab *AutoflushBuffer) Stop() error {\n\tif !ab.Latch.CanStop() {\n\t\treturn ex.New(ErrCannotStop)\n\t}\n\tab.Latch.Stopping()\n\t<-ab.Latch.NotifyStopped()\n\treturn nil\n}", "func stop() error {\n\tif spammerInstance == nil {\n\t\treturn ErrSpammerDisabled\n\t}\n\n\tspammerLock.Lock()\n\tdefer spammerLock.Unlock()\n\n\tstopWithoutLocking()\n\n\tisRunning = false\n\n\treturn nil\n}", "func (_m *Manager) WaitStop() {\n\t_m.Called()\n}", "func (sl *ReceiverLoop) stop() {\n\tsl.cancel()\n\t<-sl.stopped\n}", "func (b *Bootstrapper) Stop() error {\n\treturn nil\n}", "func (b *Bootstrapper) Stop() error {\n\treturn nil\n}", "func (br *Broker) Stop() error {\n\tif br.metaWatcher != nil {\n\t\tbr.metaWatcher.Stop()\n\t\tbr.metaWatcher = nil\n\t}\n\n\t// cancel routine context\n\tbr.ctxCancelFunc()\n\n\t// close the rpc clients\n\tfor idx, rc := range br.rpcClients {\n\t\trc.Close()\n\t\tdelete(br.rpcClients, idx)\n\t}\n\n\treturn nil\n}", "func Stop() {\n\tfor _, d := range daemons {\n\t\td.Close()\n\t}\n\tpeers = nil\n\tdaemons = nil\n}", "func (collector *Collector) Stop() {\n\t// Stop the underlying Prospector (this should block until all workers shutdown)\n\tcollector.prospector.Stop()\n\n\t// Signal our internal processing to stop as well. It's probably safer to do this\n\t// after we've stopped the prospector just to make sure we handle as much data as possible\n\tclose(collector.Done)\n\t// Wait for our collector to tell us its finished shutting down.\n\t<-collector.Stopped\n\n\tif collector.ticker != nil {\n\t\tcollector.ticker.Stop()\n\t}\n}", "func (p *Proposer) Stop() {\n\tp.stop <- struct{}{}\n}", "func (it *OracleMgrUnpauseIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func Stop() {\n\tstopRunning <- true\n\n}", "func (d *drainer) Stop() {\n\tif !d.lifecycle.Stop() {\n\t\tlog.Warn(\"drainer is already stopped, no\" +\n\t\t\t\" action will be performed\")\n\t\treturn\n\t}\n\t// Wait for drainer to be stopped\n\td.lifecycle.Wait()\n\tlog.Info(\"drainer stopped\")\n}", "func (m *MemoryStorer) StopCleaner() {\n\tclose(m.quit)\n\tm.wg.Wait()\n}", "func (s *Stopper) Stop(ctx context.Context) {\n\tdefer s.Recover(ctx)\n\tdefer unregister(s)\n\n\tif log.V(1) {\n\t\tfile, line, _ := caller.Lookup(1)\n\t\tlog.Infof(ctx,\n\t\t\t\"stop has been called from %s:%d, stopping or quiescing all running tasks\", file, line)\n\t}\n\t// Don't bother doing stuff cleanly if we're panicking, that would likely\n\t// block. Instead, best effort only. This cleans up the stack traces,\n\t// avoids stalls and helps some tests in `./cli` finish cleanly (where\n\t// panics happen on purpose).\n\tif r := recover(); r != nil {\n\t\tgo s.Quiesce(ctx)\n\t\tclose(s.stopper)\n\t\tclose(s.stopped)\n\t\ts.mu.Lock()\n\t\tfor _, c := range s.mu.closers {\n\t\t\tgo c.Close()\n\t\t}\n\t\ts.mu.Unlock()\n\t\tpanic(r)\n\t}\n\n\ts.Quiesce(ctx)\n\ts.mu.Lock()\n\tfor _, cancel := range s.mu.sCancels {\n\t\tcancel()\n\t}\n\tclose(s.stopper)\n\ts.mu.Unlock()\n\n\ts.stop.Wait()\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfor _, c := range s.mu.closers {\n\t\tc.Close()\n\t}\n\tclose(s.stopped)\n}", "func (dw *DirWatcher) Stop() {\n\tdw.qrun <- false\n}", "func (se *StateEngine) Stop() {\n\tse.mgrLock.Lock()\n\tdefer se.mgrLock.Unlock()\n\tif se.stopped {\n\t\treturn\n\t}\n\tfor _, m := range se.managers {\n\t\tif stopper, ok := m.(StateStopper); ok {\n\t\t\tstopper.Stop()\n\t\t}\n\t}\n\tse.stopped = true\n}", "func (a *Agent) Stop() {\n\tclose(a.stopping)\n\ta.wg.Wait()\n}", "func (t *traverser) Stop() error {\n\t// Don't do anything if the traverser has already been stopped or suspended.\n\tt.stopMux.Lock()\n\tdefer t.stopMux.Unlock()\n\tif t.stopped {\n\t\treturn nil\n\t} else if t.suspended {\n\t\treturn ErrShuttingDown\n\t}\n\tclose(t.stopChan)\n\tt.stopped = true\n\tt.logger.Infof(\"stopping traverser and all jobs\")\n\n\t// Stop the runningReaper and start the stoppedReaper which saves jobs' states\n\t// but doesn't enqueue any more jobs to run. It sends the chain's final state\n\t// to the RM when all jobs have stopped running.\n\tt.reaper.Stop() // blocks until runningReaper stops\n\tstoppedReaperChan := make(chan struct{})\n\tt.reaper = t.reaperFactory.MakeStopped() // t.reaper = stoppedReaper\n\tgo func() {\n\t\tdefer close(stoppedReaperChan)\n\t\tt.reaper.Run()\n\t}()\n\n\t// Stop all job runners in the runner repo. Do this after switching to the\n\t// stopped reaper so that when the jobs finish and are sent on doneJobChan,\n\t// they are reaped correctly.\n\ttimeout := time.After(t.stopTimeout)\n\terr := t.stopRunningJobs(timeout)\n\tif err != nil {\n\t\t// Don't return the error yet - we still want to wait for the stop\n\t\t// reaper to be done.\n\t\terr = fmt.Errorf(\"traverser was stopped, but encountered an error in the process: %s\", err)\n\t}\n\n\t// Wait for the stopped reaper to finish. If it takes too long, some jobs\n\t// haven't respond quickly to being stopped. Stop waiting for these jobs by\n\t// stopping the stopped reaper.\n\tselect {\n\tcase <-stoppedReaperChan:\n\tcase <-timeout:\n\t\tt.logger.Warnf(\"timed out waiting for jobs to stop - stopping reaper\")\n\t\tt.reaper.Stop()\n\t}\n\tclose(t.doneChan)\n\treturn err\n}", "func (cMap *MyStruct) Stop(){\n\tcMap.stop <- true\n}", "func (s *TXPoolServer) Stop() {\n\tfor _, v := range s.actors {\n\t\tv.Stop()\n\t}\n\t//Stop worker\n\tfor i := 0; i < len(s.workers); i++ {\n\t\ts.workers[i].stop()\n\t}\n\ts.wg.Wait()\n\n\tif s.slots != nil {\n\t\tclose(s.slots)\n\t}\n}", "func (t *gRPCTransport) stop() {\n\t// Stop Communicate RPC and sendLoop\n\tt.grpcServer.Stop()\n\tfor i := 1; i <= 2; i++ {\n\t\tt.stopChan <- struct{}{}\n\t}\n\t// Close connections to peers.\n\tfor _, p := range t.peers {\n\t\tp.stop()\n\t}\n}", "func (rcw *RemoteClusterConfigWatcher) Stop() {\n\trcw.Lock()\n\tdefer rcw.Unlock()\n\tfor _, watcher := range rcw.clusterWatchers {\n\t\twatcher.Stop(false)\n\t}\n}", "func (p *Pipe) Stop() {\n\tif !p.stoppable {\n\t\treturn\n\t}\n\tPipeRegistry().Delete(p.registryID)\n\tclose(p.terminate)\n\tgo func() {\n\t\tp.listenerMU.RLock()\n\t\tif p.listener != nil {\n\t\t\tp.listener.Close()\n\t\t}\n\t\tp.listenerMU.RUnlock()\n\n\t\t// close all clients connections\n\t\tp.clientsMapMU.Lock()\n\t\tfor k, v := range p.clientsMap {\n\t\t\tv.Close()\n\t\t\tdelete(p.clientsMap, k)\n\t\t}\n\t\tp.clientsMapMU.Unlock()\n\t}()\n}", "func (s *Builder) Stop() {\n\tif s.stop {\n\t\treturn\n\t}\n\ts.stop = true\n}" ]
[ "0.6062398", "0.6048799", "0.59177333", "0.58795786", "0.5779963", "0.5743292", "0.5741704", "0.5685443", "0.56540674", "0.5640358", "0.56347626", "0.56151617", "0.5592923", "0.5573741", "0.55554795", "0.5539427", "0.55270153", "0.5490114", "0.5471471", "0.5466442", "0.5453796", "0.5442172", "0.5435045", "0.5409717", "0.53787017", "0.53772897", "0.53502905", "0.5347786", "0.53369284", "0.53311336", "0.5330833", "0.5329055", "0.5328833", "0.5319902", "0.53190815", "0.53187096", "0.5309235", "0.5305718", "0.5304798", "0.53012556", "0.52936524", "0.52819264", "0.52668977", "0.52593005", "0.5256755", "0.5244483", "0.524171", "0.523256", "0.52293205", "0.5213084", "0.52021533", "0.5199965", "0.51961327", "0.51912165", "0.5189871", "0.5185161", "0.5177055", "0.5176868", "0.5173233", "0.51705223", "0.5166221", "0.5162779", "0.5159641", "0.5144035", "0.5142461", "0.5139246", "0.5138475", "0.51360756", "0.51318973", "0.51298213", "0.5128819", "0.5127992", "0.51251066", "0.5112824", "0.5111493", "0.5109696", "0.5109526", "0.5108793", "0.5097686", "0.5076717", "0.5076717", "0.5074939", "0.50725025", "0.50673157", "0.5066114", "0.5064622", "0.50584006", "0.50557536", "0.50511837", "0.5044308", "0.50381655", "0.5037935", "0.50328046", "0.5030212", "0.5028484", "0.5026554", "0.5026159", "0.5013047", "0.5012364", "0.5010185" ]
0.7085047
0
Start releases all allocators withdrawn through a previous call to Stop. In case the indexed is not stopped in returns silently.
func (idx *Tree) Start() { if !atomic.CompareAndSwapInt32(&idx.stopped, 1, 0) { return } for i := 0; i < len(idx.allocators); i++ { idx.allocatorQueue.put(i) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (idx *Tree) Stop() {\n\tif !atomic.CompareAndSwapInt32(&idx.stopped, 0, 1) {\n\t\treturn\n\t}\n\tfor i := 0; i < len(idx.allocators); i++ {\n\t\t_ = idx.allocatorQueue.get()\n\t}\n}", "func (mi *MinerIndex) start() {\n\tdefer func() { mi.finished <- struct{}{} }()\n\n\tif err := mi.updateOnChainIndex(); err != nil {\n\t\tlog.Errorf(\"error on initial updating miner index: %s\", err)\n\t}\n\tmi.chMeta <- struct{}{}\n\tfor {\n\t\tselect {\n\t\tcase <-mi.ctx.Done():\n\t\t\tlog.Info(\"graceful shutdown of background miner index\")\n\t\t\treturn\n\t\tcase <-time.After(metadataRefreshInterval):\n\t\t\tselect {\n\t\t\tcase mi.chMeta <- struct{}{}:\n\t\t\tdefault:\n\t\t\t\tlog.Info(\"skipping meta index update since it's busy\")\n\t\t\t}\n\t\tcase <-time.After(util.AvgBlockTime):\n\t\t\tif err := mi.updateOnChainIndex(); err != nil {\n\t\t\t\tlog.Errorf(\"error when updating miner index: %s\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}", "func exitAllocRunner(runners ...AllocRunner) {\n\tfor _, ar := range runners {\n\t\tterminalAlloc := ar.Alloc().Copy()\n\t\tterminalAlloc.DesiredStatus = structs.AllocDesiredStatusStop\n\t\tar.Update(terminalAlloc)\n\t}\n}", "func (gc *GC) Start() *GC {\n\tgc.mu.Lock()\n\tdefer gc.mu.Unlock()\n\tif gc.ticker != nil {\n\t\treturn gc // already started\n\t}\n\tgc.ticker = time.NewTicker(gc.interval)\n\tgo func() {\n\t\tfor _ = range gc.ticker.C {\n\t\t\tgc.Collect() // ignore error\n\t\t}\n\t}()\n\treturn gc\n}", "func stopWatchHeapOps() {\n\tquitChan <- true\n}", "func (ta *CachedAllocator) Start() error {\n\tta.TChan.Init()\n\tta.wg.Add(1)\n\tgo ta.mainLoop()\n\treturn nil\n}", "func Start() (err error) {\n\tlock_.Lock()\n\tready := ready_\n\tready_ = nil\n\tlock_.Unlock()\n\n\tfor _, g := range ready {\n\t\tg.StopOld()\n\t}\n\tfor _, g := range ready {\n\t\terr = g.Start()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Printf(\"G: Start complete\")\n\treturn\n}", "func (i *Index) Freeze() {\n\ti.frozen = true\n}", "func (m *Nitro) Close() {\n\t// Wait until all snapshot iterators have finished\n\tfor s := m.snapshots.GetStats(); int(s.NodeCount) != 0; s = m.snapshots.GetStats() {\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\n\tm.Lock()\n\tm.hasShutdown = true\n\tm.Unlock()\n\n\t// Acquire gc chan ownership\n\t// This will make sure that no other goroutine will write to gcchan\n\tfor !atomic.CompareAndSwapInt32(&m.isGCRunning, 0, 1) {\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\tclose(m.gcchan)\n\n\tbuf := dbInstances.MakeBuf()\n\tdefer dbInstances.FreeBuf(buf)\n\tdbInstances.Delete(unsafe.Pointer(m), CompareNitro, buf, &dbInstances.Stats)\n\n\tif m.useMemoryMgmt {\n\t\tbuf := m.snapshots.MakeBuf()\n\t\tdefer m.snapshots.FreeBuf(buf)\n\n\t\tm.shutdownWg1.Wait()\n\t\tclose(m.freechan)\n\t\tm.shutdownWg2.Wait()\n\n\t\t// Manually free up all nodes\n\t\titer := m.store.NewIterator(m.iterCmp, buf)\n\t\tdefer iter.Close()\n\t\tvar lastNode *skiplist.Node\n\n\t\titer.SeekFirst()\n\t\tif iter.Valid() {\n\t\t\tlastNode = iter.GetNode()\n\t\t\titer.Next()\n\t\t}\n\n\t\tfor lastNode != nil {\n\t\t\tm.freeItem((*Item)(lastNode.Item()))\n\t\t\tm.store.FreeNode(lastNode, &m.store.Stats)\n\t\t\tlastNode = nil\n\n\t\t\tif iter.Valid() {\n\t\t\t\tlastNode = iter.GetNode()\n\t\t\t\titer.Next()\n\t\t\t}\n\t\t}\n\n\t\tm.store.FreeNode(m.store.HeadNode(), &m.store.Stats)\n\t\tm.store.FreeNode(m.store.TailNode(), &m.store.Stats)\n\t}\n}", "func (s *Index) start() {\n\tdefer close(s.finished)\n\tif err := s.updateIndex(); err != nil {\n\t\tlog.Errorf(\"error on first updating slashing history: %s\", err)\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\tlog.Info(\"graceful shutdown of background slashing updater\")\n\t\t\treturn\n\t\tcase <-time.After(util.AvgBlockTime):\n\t\t\tif err := s.updateIndex(); err != nil {\n\t\t\t\tlog.Errorf(\"error when updating slashing history: %s\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *MIDs) Free(i uint16) {\n\tm.Lock()\n\tm.index[i] = nil\n\tm.Unlock()\n}", "func (it *Dprdpr1intspareMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (ns *EsIndexer) Stop() {\n\n}", "func (it *Dppdpp1intspareMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Dprdpr0intspareMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Mcmc1intmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Dppdpp0intspareMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (ls *Libstore) GarbageCollector() {\n\tfor {\n\t\ttime.Sleep(12*time.Second)\n\t\tnow := time.Now().UnixNano()\n\t\t<- ls.leaseM\n\t\tleases := ls.leaseMap //don't want to be accessing leaseMap in a loop while blocking other processes\n\t\tls.leaseM <- 1\n\t\tfor key, lease := range leases {\n\t\t\tif now >= lease.RequestLeaseTime || \n\t\t\t(lease.LeaseTimeout > 0 && now >= lease.LeaseTimeout) || \n\t\t\tlease.Queries < 3 {\t\n\t\t\t\tls.ClearCaches(key) \n\t\t\t}\n\t\t}\n\t}\n}", "func startCrawling(start string) {\n\tcheckIndexPresence()\n\n\tvar wg sync.WaitGroup\n\tnoOfWorkers := 10\n\n\t// Send first url to the channel\n\tgo func(s string) {\n\t\tqueue <- s\n\t}(start)\n\n\t// Create worker pool with noOfWorkers workers\n\twg.Add(noOfWorkers)\n\tfor i := 1; i <= noOfWorkers; i++ {\n\t\tgo worker(&wg, i)\n\t}\n\twg.Wait()\n}", "func (cbi *CandidatesBucketsIndexer) Stop(ctx context.Context) error {\n\treturn cbi.kvStore.Stop(ctx)\n}", "func (la *Allocator) Clear() {\n\tfor lc, role := range la.allocated {\n\t\tif role != \"\" {\n\t\t\tla.Free(eal.LCoreFromID(lc))\n\t\t}\n\t}\n}", "func (b *B) ReportAllocs() {}", "func (it *Mxmx1intmacMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (mi *MinerIndex) Close() error {\n\tlog.Info(\"Closing\")\n\tmi.clsLock.Lock()\n\tdefer mi.clsLock.Unlock()\n\tif mi.closed {\n\t\treturn nil\n\t}\n\tmi.cancel()\n\tfor i := 0; i < goroutinesCount; i++ {\n\t\t<-mi.finished\n\t}\n\tclose(mi.finished)\n\tmi.signaler.Close()\n\n\tmi.closed = true\n\treturn nil\n}", "func (it *Mxmx1inteccMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (e *quotaEvaluator) start() {\n\tdefer utilruntime.HandleCrash()\n\n\tfor i := 0; i < e.workers; i++ {\n\t\tgo wait.Until(e.doWork, time.Second, e.stopCh)\n\t}\n}", "func (it *Mcmc4intmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Mxmx0intmacMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (a *allocator) Recycle() {\n\ta.base.Recycle()\n}", "func (b *B) ReportAllocs()", "func (gc *GC) Stop() {\n\tgc.mu.Lock()\n\tdefer gc.mu.Unlock()\n\tif gc.ticker == nil {\n\t\treturn // not started\n\t}\n\tgc.ticker.Stop()\n\tgc.ticker = nil\n}", "func (it *Dprdpr1intsramseccMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Mcmc0intmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func StartGaugeVector() {\n\tMetricVecs = map[string]prometheus.GaugeVec{}\n\tlogger = logrus.WithFields(logrus.Fields{\"custom_metrics\": \"StartGaugeVector\"})\n\n\tgo func() {\n\t\tfor {\n\t\t\tlogger.Info(\"calling reset on all prometheus gauge vectors\")\n\t\t\tfor _, val := range MetricVecs {\n\t\t\t\tval.Reset()\n\t\t\t}\n\t\t\ttime.Sleep(time.Duration(sleepytime) * time.Second)\n\t\t}\n\t}()\n}", "func (it *Mcmc2intmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Dppdpp1intsramseccMetricsIterator) Free() {\n\tit.iter.Free()\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 (it *Mxmx0inteccMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Mcmc1mchintmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (f *IndexFile) Retain() { f.wg.Add(1) }", "func (fetchers Fetchers) Stop() {\n\tfor _, fetcher := range fetchers {\n\t\tfetcher.Stop()\n\t}\n}", "func (m *MemoryStorer) StartCleaner() {\n\tif m.maxAge == 0 || m.cleanInterval == 0 {\n\t\tpanic(\"both max age and clean interval must be set to non-zero\")\n\t}\n\n\t// init quit chan\n\tm.quit = make(chan struct{})\n\n\tm.wg.Add(1)\n\n\t// Start the cleaner infinite loop go routine.\n\t// StopCleaner() can be used to kill this go routine.\n\tgo m.cleanerLoop()\n}", "func (la *Allocator) Free(lc eal.LCore) {\n\tif la.allocated[lc.ID()] == \"\" {\n\t\tpanic(\"lcore double free\")\n\t}\n\tlogger.Info(\"lcore freed\",\n\t\tlc.ZapField(\"lc\"),\n\t\tzap.String(\"role\", la.allocated[lc.ID()]),\n\t\tla.provider.NumaSocketOf(lc).ZapField(\"socket\"),\n\t)\n\tla.allocated[lc.ID()] = \"\"\n}", "func (it *Dppdpp0intreg1MetricsIterator) Free() {\n\tit.iter.Free()\n}", "func StartStopScan(pool string, t ScanType) error {\n\tcmd := &Cmd{\n\t\tCookie: uint64(t),\n\t}\n\treturn NvlistIoctl(zfsHandle.Fd(), ZFS_IOC_POOL_SCAN, pool, cmd, nil, nil, nil)\n}", "func (it *Dppdpp0intsramseccMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (r *reducer) stop() {\n\tfor _, m := range r.mappers {\n\t\tm.stop()\n\t}\n\tsyncClose(r.done)\n}", "func (cbi *CandidatesBucketsIndexer) Start(ctx context.Context) error {\n\tif err := cbi.kvStore.Start(ctx); err != nil {\n\t\treturn err\n\t}\n\tret, err := cbi.kvStore.Get(StakingCandidatesNamespace, []byte(indexerHeightKey))\n\tswitch errors.Cause(err) {\n\tcase nil:\n\t\tcbi.latestCandidatesHeight = byteutil.BytesToUint64BigEndian(ret)\n\tcase db.ErrNotExist:\n\t\tcbi.latestCandidatesHeight = 0\n\tdefault:\n\t\treturn err\n\t}\n\n\tret, err = cbi.kvStore.Get(StakingBucketsNamespace, []byte(indexerHeightKey))\n\tswitch errors.Cause(err) {\n\tcase nil:\n\t\tcbi.latestBucketsHeight = byteutil.BytesToUint64BigEndian(ret)\n\tcase db.ErrNotExist:\n\t\tcbi.latestBucketsHeight = 0\n\tdefault:\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a *AddressBook) Start() {\n\terrch := make(chan error, 10)\n\ta.warmAddressBookCache(errch)\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 (it *Mcmc0mchintmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (mm *BytesMonitor) Start(ctx context.Context, pool *BytesMonitor, reserved BoundAccount) {\n\tif mm.mu.curAllocated != 0 {\n\t\tpanic(fmt.Sprintf(\"%s: started with %d bytes left over\", mm.name, mm.mu.curAllocated))\n\t}\n\tif mm.mu.curBudget.mon != nil {\n\t\tpanic(fmt.Sprintf(\"%s: already started with pool %s\", mm.name, mm.mu.curBudget.mon.name))\n\t}\n\tmm.mu.curAllocated = 0\n\tmm.mu.maxAllocated = 0\n\tmm.mu.curBudget = pool.MakeBoundAccount()\n\tmm.reserved = reserved\n\tif log.V(2) {\n\t\tpoolname := \"(none)\"\n\t\tif pool != nil {\n\t\t\tpoolname = pool.name\n\t\t}\n\t\tlog.InfofDepth(ctx, 1, \"%s: starting monitor, reserved %s, pool %s\",\n\t\t\tmm.name,\n\t\t\thumanizeutil.IBytes(mm.reserved.used),\n\t\t\tpoolname)\n\t}\n}", "func (it *Msmsintprp1MetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Mcmc4mchintmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (r *ReconcileNodes) Start(stop context.Context) error {\n\tr.cache.WaitForCacheSync(stop)\n\n\tchDels, err := r.watchDeletions(stop.Done())\n\tif err != nil {\n\t\t// I've seen watchDeletions() fail because the Cache Informers weren't ready. WaitForCacheSync()\n\t\t// should block until they are, however, but I believe I saw this not being true once.\n\t\t//\n\t\t// Start() failing would exit the Operator process. Since this is a minor feature, let's disable\n\t\t// for now until further investigation is done.\n\t\tr.logger.Info(\"failed to initialize watcher for deleted nodes - disabled\", \"error\", err)\n\t\tchDels = make(chan string)\n\t}\n\tchUpdates, err := r.watchUpdates()\n\tif err != nil {\n\t\tr.logger.Info(\"failed to initialize watcher for updating nodes - disabled\", \"error\", err)\n\t\tchUpdates = make(chan string)\n\t}\n\n\tchAll := watchTicks(stop.Done(), 5*time.Minute)\n\n\tfor {\n\t\tselect {\n\t\tcase <-stop.Done():\n\t\t\tr.logger.Info(\"stopping nodes controller\")\n\t\t\treturn nil\n\t\tcase node := <-chDels:\n\t\t\tif err := r.onDeletion(node); err != nil {\n\t\t\t\tr.logger.Error(err, \"failed to reconcile deletion\", \"node\", node)\n\t\t\t}\n\t\tcase node := <-chUpdates:\n\t\t\tif err := r.onUpdate(node); err != nil {\n\t\t\t\tr.logger.Error(err, \"failed to reconcile updates\", \"node\", node)\n\t\t\t}\n\t\tcase <-chAll:\n\t\t\tif err := r.reconcileAll(); err != nil {\n\t\t\t\tr.logger.Error(err, \"failed to reconcile nodes\")\n\t\t\t}\n\t\t}\n\t}\n}", "func (it *Mcmc2mchintmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Dprdpr0intflopfifo1MetricsIterator) Free() {\n\tit.iter.Free()\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 (ncs NvmeControllers) Free() (tb uint64) {\n\tfor _, c := range ncs {\n\t\ttb += (*NvmeController)(c).Free()\n\t}\n\treturn\n}", "func (s *stateManager) MaintainIndices() {\n\n\tupdateIndex := func(a *Allocation) {\n\t\t// Update IP->Allocation.ID lookup table\n\t\tif a.Lease != nil {\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), s.requestTimeout)\n\t\t\tdefer cancel()\n\t\t\tkey := fmt.Sprintf(\"%s/lookup/%s\", etcdPrefix, a.Lease.FixedAddress)\n\t\t\t_, err := s.kv.Put(ctx, key, a.ID.String())\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"State: error updating IP<->ID lookup table [%s]\", err.Error())\n\t\t\t}\n\t\t}\n\t}\n\n\tdeleteIndex := func(a *Allocation) {\n\t\t// Update IP->Allocation.ID lookup table\n\t\tif a.Lease != nil {\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), s.requestTimeout)\n\t\t\tdefer cancel()\n\t\t\tkey := fmt.Sprintf(\"%s/lookup/%s\", etcdPrefix, a.Lease.FixedAddress)\n\t\t\t_, err := s.kv.Delete(ctx, key)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"State: error deleteing IP<->ID mapping [%s]\", err.Error())\n\t\t\t}\n\t\t}\n\t}\n\n\t// Ensure consistency of the IP<->ID lookup\n\twatcher := AllocationWatcher{\n\t\tOnModify: updateIndex,\n\t\tOnCreate: updateIndex,\n\t\tOnDelete: deleteIndex,\n\t}\n\ts.Watch(&watcher)\n\n}", "func (mci *XMCacheIterator) Release() {\n\tif mci.dir == dirReleased {\n\t\treturn\n\t}\n\tmci.dir = dirReleased\n\tif mci.mIter != nil {\n\t\tmci.mIter.Release()\n\t}\n\tfor _, it := range mci.iters {\n\t\tit.Release()\n\t}\n\tmci.keys = nil\n\tmci.iters = nil\n}", "func (s *samplerBackendRateCounter) Start() {\n\tgo func() {\n\t\tdefer watchdog.LogOnPanic()\n\t\tdecayTicker := time.NewTicker(s.backend.decayPeriod)\n\t\tdefer decayTicker.Stop()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-decayTicker.C:\n\t\t\t\ts.backend.decayScore()\n\t\t\tcase <-s.exit:\n\t\t\t\tclose(s.stopped)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func (w *IndexPoller) Start() {\n\tw.channel <- w.run()\n\tticker := time.NewTicker(w.pollRate)\n\tfor {\n\t\tselect {\n\t\tcase <-w.controlChannel:\n\t\t\tdefer close(w.channel)\n\t\t\tticker.Stop()\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tw.channel <- w.run()\n\t\t}\n\t}\n}", "func (s *LDBStore) startGC(c int) {\n\n\ts.gc.count = 0\n\t// calculate the target number of deletions\n\tif c >= s.gc.maxRound {\n\t\ts.gc.target = s.gc.maxRound\n\t} else {\n\t\ts.gc.target = c / s.gc.ratio\n\t}\n\ts.gc.batch = newBatch()\n\tlog.Debug(\"startgc\", \"requested\", c, \"target\", s.gc.target)\n}", "func (q *Query) release() {\n\tq.sets.reset()\n\tq.sort = nil\n\tq.offset = 0\n\tq.around = 0\n\tq.limit = 50\n\tq.desc = false\n\tq.db.queries <- q\n}", "func (it *Msmsintprp4MetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Dprdpr1intreg1MetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (c *Cache) StartGC() {\n\tgo c.GC()\n}", "func (c *MultiClusterController) Start(stop <-chan struct{}) error {\n\tklog.Infof(\"start mc-controller %q\", c.name)\n\n\tdefer c.Queue.ShutDown()\n\n\tfor i := 0; i < c.MaxConcurrentReconciles; i++ {\n\t\tgo wait.Until(c.worker, c.JitterPeriod, stop)\n\t}\n\n\tselect {\n\tcase <-stop:\n\t\treturn nil\n\t}\n}", "func (it *Dprdpr1intreg2MetricsIterator) Free() {\n\tit.iter.Free()\n}", "func GC()", "func (ow *realOOMWatcher) Start(ref *api.ObjectReference) error {\n\trequest := events.Request{\n\t\tEventType: map[cadvisorapi.EventType]bool{\n\t\t\tcadvisorapi.EventOom: true,\n\t\t},\n\t\tContainerName: \"/\",\n\t\tIncludeSubcontainers: false,\n\t}\n\teventChannel, err := ow.cadvisor.WatchEvents(&request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tdefer runtime.HandleCrash()\n\n\t\tfor event := range eventChannel.GetChannel() {\n\t\t\tglog.V(2).Infof(\"Got sys oom event from cadvisor: %v\", event)\n\t\t\tow.recorder.PastEventf(ref, unversioned.Time{Time: event.Timestamp}, api.EventTypeWarning, systemOOMEvent, \"System OOM encountered\")\n\t\t}\n\t\tglog.Errorf(\"Unexpectedly stopped receiving OOM notifications from cAdvisor\")\n\t}()\n\treturn nil\n}", "func (mon Monitor) Start(ip string, port int, cloudFunctionsPattern string, chanAnalyzer chan []CloudService) {\n\n\tmon.cloudFunctionsPattern = cloudFunctionsPattern\n\n\tfor {\n\t\t//mon.lookup = *dist.NewLookupProxy(ip, port)\n\n\t\tmon.refreshCloudServices(ip, port)\n\n\t\t//err := mon.lookup.Close()\n\t\t//if err != nil {\n\t\t//\tlib.PrintlnError(\"Error at closing lookup. Error:\", err)\n\t\t//}\n\n\t\tfor i := range mon.cloudServices {\n\t\t\tmon.cloudServices[i].RefreshPrice()\n\t\t\tmon.cloudServices[i].RefreshStatus()\n\t\t}\n\n\t\tif len(mon.cloudServices) > 0 {\n\t\t\tchanAnalyzer <- mon.cloudServices\n\t\t}\n\n\t\ttime.Sleep(5 * time.Second)\n\t}\n}", "func (tCertPool *tCertPoolSingleThreadImpl) Stop() (err error) {\n\n\ttCertPool.m.Lock()\n\tdefer tCertPool.m.Unlock()\n\n\tfor k := range tCertPool.tcblMap {\n\t\tcertList := tCertPool.tcblMap[k]\n\t\ttCertPool.client.ks.storeUnusedTCerts(certList.GetUnusedTCertBlocks())\n\t}\n\n\ttCertPool.client.Debug(\"Store unused TCerts...done!\")\n\n\treturn\n}", "func (it *Dprdpr1intcreditMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (i *Iterator) Dispose() {\n\titMutex.Lock()\n\tdefer itMutex.Unlock()\n\n\tif i.iterPtr != 0 {\n\t\tC.IteratorFree(i.iterPtr)\n\t\ti.iterPtr = 0\n\t}\n\ti.finished = true\n\ti.root = nil\n}", "func (it *Dppdpp1intreg1MetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (p *PgStore) startCleanup(d time.Duration) {\n\tp.stopChan = make(chan struct{})\n\tt := time.NewTicker(d)\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tif err := p.deleteExpired(); err != nil {\n\t\t\t\tp.errChan <- err\n\t\t\t}\n\t\tcase <-p.stopChan:\n\t\t\tt.Stop()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (t *ttl) start() {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-t.shutdown:\n\t\t\t\tt.tick.Stop()\n\t\t\t\treturn\n\n\t\t\tcase <-t.tick.C:\n\t\t\t\t// iterate over all the buckets and remove the expired keys\n\t\t\t\t// can be optimized using priority queue with increased code complexity\n\t\t\t\tvar keys []string\n\t\t\t\tfor _, bucket := range t.cache.buckets {\n\t\t\t\t\tbucket.RLock()\n\t\t\t\t\tfor k, v := range bucket.items {\n\t\t\t\t\t\tif v.isExpired() {\n\t\t\t\t\t\t\tkeys = append(keys, k)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbucket.RUnlock()\n\t\t\t\t}\n\t\t\t\tt.cache.deleteKeys(keys...)\n\t\t\t}\n\t\t}\n\t}()\n}", "func (s *BasevhdlListener) ExitAllocator(ctx *AllocatorContext) {}", "func (e *Engine) Start() {\n e.cmdStack = &Queue{onReceiveEmptyChan: make(chan bool)}\n e.onFinishChan = make(chan bool)\n go func() {\n for {\n cmd := e.cmdStack.Pull(&e.stopRequest)\n if cmd == nil {\n break\n }\n cmd.Execute(e)\n }\n e.onFinishChan <- true\n }()\n}", "func (ia *idAllocator) Allocate() (int64, error) {\n\tfor {\n\t\tid := <-ia.ids\n\t\tif id == allocationTrigger {\n\t\t\tif !ia.stopper.StartTask() {\n\t\t\t\tif atomic.CompareAndSwapInt32(&ia.closed, 0, 1) {\n\t\t\t\t\tclose(ia.ids)\n\t\t\t\t}\n\t\t\t\treturn 0, util.Errorf(\"could not allocate ID; system is draining\")\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tia.allocateBlock(ia.blockSize)\n\t\t\t\tia.stopper.FinishTask()\n\t\t\t}()\n\t\t} else {\n\t\t\treturn id, nil\n\t\t}\n\t}\n}", "func (nc NvmeController) Free() (tb uint64) {\n\tfor _, d := range nc.SmdDevices {\n\t\ttb += d.AvailBytes\n\t}\n\treturn\n}", "func (*inMemoryAllocator) End() int64 {\n\t// It doesn't matter.\n\treturn 0\n}", "func (it *Mcmc5intmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (_m *MockCompactionPlanContext) start() {\n\t_m.Called()\n}", "func (bfx *bloomfilterIndexer) Stop(ctx context.Context) error {\n\treturn bfx.flusher.KVStoreWithBuffer().Stop(ctx)\n}", "func (it *Dppdpp1intcreditMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Mcmc6intmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (rp *RequestManager) StartGC(gcPeriod time.Duration) {\n\tctx, stop := context.WithCancel(context.Background())\n\trp.stopGC = stop\n\ttick := time.Tick(gcPeriod)\n\trp.wg.Add(1)\n\tgo func() {\n\t\tlogrus.Info(\"starting cleanup go routine\")\n\t\tdefer logrus.Info(\"exiting cleanup go routine\")\n\t\tdefer rp.wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-tick:\n\t\t\t\trp.cleanup(rp.now())\n\t\t\t}\n\t\t}\n\n\t}()\n}", "func (iter *FlatIterator) Release() {\n\titer.db.iterating = false\n}", "func (it *Dprdpr1intflopfifo1MetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Dprdpr0intcreditMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (f *IndexFile) Release() { f.wg.Done() }", "func (it *Dppdpp0intcreditMetricsIterator) Free() {\n\tit.iter.Free()\n}", "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 destroy(ar *allocRunner) {\n\tar.Destroy()\n\t<-ar.DestroyCh()\n}", "func (bs *BoltStore) startCleanup(cleanupInterval time.Duration) {\n\tbs.stopCleanup = make(chan bool)\n\tticker := time.NewTicker(cleanupInterval)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\terr := bs.deleteExpired()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\tcase <-bs.stopCleanup:\n\t\t\tticker.Stop()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *Store) Start() {\n\ts.sigs = make(chan os.Signal, 1)\n\tsignal.Notify(s.sigs, syscall.SIGINT, syscall.SIGTERM)\n\tgo func() {\n\t\t<-s.sigs\n\t\ts.Close()\n\t\ts.Exiter(1)\n\t}()\n}", "func (sa *SuffixArray) Freeze() error { return sa.ba.Freeze() }" ]
[ "0.6604761", "0.54873544", "0.5444315", "0.5245357", "0.50982845", "0.49836162", "0.49654576", "0.4962564", "0.4926634", "0.49095482", "0.4865416", "0.4863822", "0.48342353", "0.48192653", "0.48100424", "0.47962928", "0.4782292", "0.47776186", "0.47687042", "0.47663927", "0.47584805", "0.47550577", "0.47499615", "0.47269952", "0.4724175", "0.47132063", "0.471256", "0.47124755", "0.47070995", "0.4703771", "0.46967033", "0.4696645", "0.46860278", "0.46762753", "0.4671433", "0.46686643", "0.4653767", "0.4647844", "0.4639334", "0.4623625", "0.46203572", "0.46164605", "0.4614597", "0.46039987", "0.45946407", "0.4591134", "0.45910975", "0.45902765", "0.45902652", "0.4587976", "0.45859465", "0.45849818", "0.45837024", "0.45794702", "0.45626423", "0.45604047", "0.45510727", "0.4547234", "0.45468915", "0.4546215", "0.45451057", "0.454334", "0.4538786", "0.45375082", "0.45358625", "0.45347103", "0.45328125", "0.4532335", "0.45213825", "0.45156202", "0.45131394", "0.45128915", "0.45113716", "0.45092815", "0.45051992", "0.45042536", "0.45025906", "0.4502061", "0.44966862", "0.4489798", "0.4489354", "0.44885927", "0.4487335", "0.4486537", "0.44865108", "0.448632", "0.4483438", "0.44705963", "0.44665897", "0.44648772", "0.44449705", "0.44441462", "0.44349578", "0.44345564", "0.44342387", "0.44280493", "0.44249347", "0.44239694", "0.44210783", "0.4413763" ]
0.686857
0
Close stops the index, and then terminates the memory allocation goroutine, which will otherwise leak.
func (idx *Tree) Close() { idx.Stop() close(idx.done) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i *queueIndex) close() error {\n\treturn i.indexArena.Unmap()\n}", "func (s ConsoleIndexStore) Close() error { return nil }", "func (f *IndexFile) Close() error {\n\t// Wait until all references are released.\n\tf.wg.Wait()\n\n\tf.sblk = SeriesBlock{}\n\tf.tblks = nil\n\tf.mblk = MeasurementBlock{}\n\tf.seriesN = 0\n\treturn mmap.Unmap(f.data)\n}", "func (i *Index) Close() error {\n\tif err := i.mmap.Sync(gommap.MS_SYNC); err != nil {\n\t\treturn lib.Wrap(err, \"Unable to sync mmap\")\n\t}\n\n\tif err := i.file.Sync(); err != nil {\n\t\treturn lib.Wrap(err, \"Unable to sync file\")\n\t}\n\n\tif err := i.file.Truncate(int64(i.size)); err != nil {\n\t\treturn lib.Wrap(err, \"Unable to truncate file\")\n\t}\n\n\treturn i.file.Close()\n}", "func (m memVec) Close() {\n}", "func (mi *MinerIndex) Close() error {\n\tlog.Info(\"Closing\")\n\tmi.clsLock.Lock()\n\tdefer mi.clsLock.Unlock()\n\tif mi.closed {\n\t\treturn nil\n\t}\n\tmi.cancel()\n\tfor i := 0; i < goroutinesCount; i++ {\n\t\t<-mi.finished\n\t}\n\tclose(mi.finished)\n\tmi.signaler.Close()\n\n\tmi.closed = true\n\treturn nil\n}", "func (b *index) Close() error {\n\tif closer, ok := b.readerAt.(io.Closer); ok {\n\t\treturn closer.Close()\n\t}\n\n\treturn nil\n}", "func (s *Index) Close() error {\n\tlog.Info(\"Closing\")\n\ts.clsLock.Lock()\n\tdefer s.clsLock.Unlock()\n\tif s.closed {\n\t\treturn nil\n\t}\n\ts.cancel()\n\t<-s.finished\n\ts.closed = true\n\treturn nil\n}", "func (c *indexIter) Close() {\n\tif c.it != nil {\n\t\tc.it.Close()\n\t\tc.it = nil\n\t}\n}", "func (f *IndexFile) Release() { f.wg.Done() }", "func (i *Index) Close() error {\n\ti.mu.Lock()\n\tdefer i.mu.Unlock()\n\n\t// Close the attribute store.\n\ti.columnAttrs.Close()\n\n\t// Close all fields.\n\tfor _, f := range i.fields {\n\t\tif err := f.Close(); err != nil {\n\t\t\treturn errors.Wrap(err, \"closing field\")\n\t\t}\n\t}\n\ti.fields = make(map[string]*Field)\n\n\treturn nil\n}", "func (e *IndexLookUpExecutor) Close() error {\n\t// TODO: It's better to notify fetchHandles to close instead of fetching all index handle.\n\t// Consume the task channel in case channel is full.\n\tfor range e.taskChan {\n\t}\n\te.taskChan = nil\n\terr := e.result.Close()\n\te.result = nil\n\treturn errors.Trace(err)\n}", "func (t *Table) Close() error {\n\tif t.fd != nil {\n\t\tt.fd.Close()\n\t}\n\tif t.indexFd != nil {\n\t\tif len(t.indexData) != 0 {\n\t\t\ty.Munmap(t.indexData)\n\t\t}\n\t\tt.indexFd.Close()\n\t}\n\treturn nil\n}", "func (di *dataIndexer) Close() error {\n\treturn di.dispatcher.Close()\n}", "func (i *Index) Close() error {\n\treturn i.db.Close()\n}", "func (o IndexOptimizer) Close() error {\n\treturn o.conn.Close()\n}", "func (ms *memoryStorer) Close() error {\n\treturn nil\n}", "func (vec Vector) Close() error {\n\tif len(vec) > 0 {\n\t\tC.rte_pktmbuf_free_bulk(vec.ptr(), C.uint(len(vec)))\n\t}\n\treturn nil\n}", "func (m *MIDs) Free(i uint16) {\n\tm.Lock()\n\tm.index[i] = nil\n\tm.Unlock()\n}", "func (fw *Writer) Close() {\n\tfb := fw.buf\n\tif fb.numRecords > 0 {\n\t\tlog.Debug.Printf(\"%v: Start flush (close)\", fb.label)\n\t\tfw.FlushBuf()\n\t} else {\n\t\tfw.bufFreePool.pool.Put(fb)\n\t\tfw.buf = nil\n\t}\n\tif fw.out != nil {\n\t\tfw.rio.Wait()\n\t\tindex := biopb.PAMFieldIndex{\n\t\t\tMagic: FieldIndexMagic,\n\t\t\tVersion: pamutil.DefaultVersion,\n\t\t\tBlocks: fw.blockIndexes,\n\t\t}\n\t\tlog.Debug.Printf(\"creating index with %d blocks\", len(index.Blocks))\n\t\tdata, err := index.Marshal()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfw.rio.SetTrailer(data)\n\t\tif err := fw.rio.Finish(); err != nil {\n\t\t\tfw.err.Set(err)\n\t\t}\n\t\tif err := fw.out.Close(vcontext.Background()); err != nil {\n\t\t\tfw.err.Set(errors.E(err, fmt.Sprintf(\"fieldio close %s\", fw.out.Name())))\n\t\t}\n\t}\n}", "func (c *Counter) Close() {}", "func (iter *radixIterator) Close() {\n\titer.miTxn.Abort()\n}", "func (p padVec) Close() {\n}", "func (m *Memory) Close(ctx context.Context) error {\n\tm.opened = false\n\tclose(m.exit)\n\treturn nil\n}", "func (x *Indexer) Close() error {\n\tdefer x.lock.Close()\n\tfor i := 0; i < x.config.NumShatters; i++ {\n\t\tx.shatter <- &shatterReq{shutdown: true}\n\t\t// no more shatters running, each waits\n\t\t// for all shards to complete before\n\t\t// returning => shards are no longer busy.\n\t}\n\tfor i := 0; i < x.config.NumShards; i++ {\n\t\tclose(x.shards[i].PostChan())\n\t}\n\tif err := x.config.Write(); err != nil {\n\t\treturn err\n\t}\n\tif err := x.writeFiles(); err != nil {\n\t\treturn err\n\t}\n\tif err := x.dmds.Close(); err != nil {\n\t\treturn err\n\t}\n\terrs := make(chan error, len(x.shards))\n\tfor i := range x.shards {\n\t\tb := &x.shards[i]\n\t\tgo func(b *shard.Indexer) {\n\t\t\terrs <- b.Close()\n\t\t}(b)\n\t}\n\tvar err error\n\tfor i := range x.shards {\n\t\tierr := <-errs\n\t\tif err != nil && ierr != nil {\n\t\t\tlog.Printf(\"dupy.Index.Close: dropping error %s from bucket %d\", ierr, i)\n\t\t} else if ierr != nil {\n\t\t\terr = ierr\n\t\t}\n\t}\n\treturn err\n}", "func (it *AccessIndexorDbgAddressIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (e *IndexReaderExecutor) Close() error {\n\terr := closeAll(e.result, e.partialResult)\n\te.result = nil\n\te.partialResult = nil\n\treturn errors.Trace(err)\n}", "func (b *Buffer) Close() {\n\tb.length = 0\n\tb.pool.buffers <- b\n}", "func (c *AdapterMemory) Close(ctx context.Context) error {\n\tif c.cap > 0 {\n\t\tc.lru.Close()\n\t}\n\tc.closed.Set(true)\n\treturn nil\n}", "func (i *Iterator) Close() {}", "func (m *Nitro) Close() {\n\t// Wait until all snapshot iterators have finished\n\tfor s := m.snapshots.GetStats(); int(s.NodeCount) != 0; s = m.snapshots.GetStats() {\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\n\tm.Lock()\n\tm.hasShutdown = true\n\tm.Unlock()\n\n\t// Acquire gc chan ownership\n\t// This will make sure that no other goroutine will write to gcchan\n\tfor !atomic.CompareAndSwapInt32(&m.isGCRunning, 0, 1) {\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\tclose(m.gcchan)\n\n\tbuf := dbInstances.MakeBuf()\n\tdefer dbInstances.FreeBuf(buf)\n\tdbInstances.Delete(unsafe.Pointer(m), CompareNitro, buf, &dbInstances.Stats)\n\n\tif m.useMemoryMgmt {\n\t\tbuf := m.snapshots.MakeBuf()\n\t\tdefer m.snapshots.FreeBuf(buf)\n\n\t\tm.shutdownWg1.Wait()\n\t\tclose(m.freechan)\n\t\tm.shutdownWg2.Wait()\n\n\t\t// Manually free up all nodes\n\t\titer := m.store.NewIterator(m.iterCmp, buf)\n\t\tdefer iter.Close()\n\t\tvar lastNode *skiplist.Node\n\n\t\titer.SeekFirst()\n\t\tif iter.Valid() {\n\t\t\tlastNode = iter.GetNode()\n\t\t\titer.Next()\n\t\t}\n\n\t\tfor lastNode != nil {\n\t\t\tm.freeItem((*Item)(lastNode.Item()))\n\t\t\tm.store.FreeNode(lastNode, &m.store.Stats)\n\t\t\tlastNode = nil\n\n\t\t\tif iter.Valid() {\n\t\t\t\tlastNode = iter.GetNode()\n\t\t\t\titer.Next()\n\t\t\t}\n\t\t}\n\n\t\tm.store.FreeNode(m.store.HeadNode(), &m.store.Stats)\n\t\tm.store.FreeNode(m.store.TailNode(), &m.store.Stats)\n\t}\n}", "func (i *Indexio) Close() error {\n\treturn i.db.Close()\n}", "func (s *testSuite) TestIndexDoubleReadClose(c *C) {\n\tif _, ok := s.store.GetClient().(*tikv.CopClient); !ok {\n\t\t// Make sure the store is tikv store.\n\t\treturn\n\t}\n\toriginSize := executor.LookupTableTaskChannelSize\n\texecutor.LookupTableTaskChannelSize = 1\n\ttk := testkit.NewTestKit(c, s.store)\n\ttk.MustExec(\"use test\")\n\ttk.MustExec(\"create table dist (id int primary key, c_idx int, c_col int, index (c_idx))\")\n\n\t// Insert 100 rows.\n\tvar values []string\n\tfor i := 0; i < 100; i++ {\n\t\tvalues = append(values, fmt.Sprintf(\"(%d, %d, %d)\", i, i, i))\n\t}\n\ttk.MustExec(\"insert dist values \" + strings.Join(values, \",\"))\n\n\trss, err := tk.Se.Execute(\"select * from dist where c_idx between 0 and 100\")\n\tc.Assert(err, IsNil)\n\trs := rss[0]\n\t_, err = rs.Next()\n\tc.Assert(err, IsNil)\n\tc.Check(taskGoroutineExists(), IsTrue)\n\trs.Close()\n\ttime.Sleep(time.Millisecond * 50)\n\tc.Check(taskGoroutineExists(), IsFalse)\n\texecutor.LookupTableTaskChannelSize = originSize\n}", "func (mcs *MemoryCellStore) Close() error {\n\treturn nil\n}", "func (sa *SuffixArray) Close() error { return sa.ba.Close() }", "func (fdb *fdbSlice) Close() error {\n\n\tcommon.Infof(\"ForestDBSlice::Close \\n\\tClosing Slice Id %v, IndexInstId %v, \"+\n\t\t\"IndexDefnId %v\", fdb.idxInstId, fdb.idxDefnId, fdb.id)\n\n\t//signal shutdown for command handler routines\n\tfor i := 0; i < NUM_WRITER_THREADS_PER_SLICE; i++ {\n\t\tfdb.stopCh <- true\n\t\t<-fdb.stopCh\n\t}\n\n\t//close the main index\n\tif fdb.main[0] != nil {\n\t\tfdb.main[0].Close()\n\t}\n\t//close the back index\n\tif fdb.back[0] != nil {\n\t\tfdb.back[0].Close()\n\t}\n\treturn nil\n}", "func (s *MemStore) Close() error {\n\treturn nil\n}", "func (e *IndexLookUpJoin) Close() error {\n\tif e.stats != nil {\n\t\tdefer e.Ctx().GetSessionVars().StmtCtx.RuntimeStatsColl.RegisterStats(e.ID(), e.stats)\n\t}\n\tif e.cancelFunc != nil {\n\t\te.cancelFunc()\n\t}\n\te.workerWg.Wait()\n\te.memTracker = nil\n\te.task = nil\n\te.finished.Store(false)\n\te.prepared = false\n\treturn e.BaseExecutor.Close()\n}", "func (s *BaseCymbolListener) ExitIndex(ctx *IndexContext) {}", "func (k *Khaiii) Close() {\n\tif k.firstWord != nil {\n\t\tk.FreeAnalyzeResult()\n\t}\n\tC.khaiii_close(k.handle)\n}", "func (s *Store) Close() error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\ts.recs = []*record{}\n\ts.index = map[uint64]*record{}\n\n\treturn s.backend.Close()\n}", "func (s *MemorySink) Close() error { return nil }", "func (dr *Resolver) Close() error {\n\treturn fmt.Errorf(\"couldn't cleanup eRPC memory segment: %w\", unix.Munmap(dr.erpcSegment))\n}", "func (b *Builder) Close() {\n\tb.opts.AllocPool.Return(b.alloc)\n}", "func (m *MemBook) Close(_ context.Context) (err error) {\n\n\t// Lock the Book data for async safe use.\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\n\t// Delete all Book data.\n\tm.deleteAll()\n\n\treturn nil\n}", "func (sr *shardResult) Close() {\n\tfor _, series := range sr.blocks {\n\t\tseries.Blocks.Close()\n\t}\n}", "func (i *blockIter) Close() error {\n\ti.handle.Release()\n\ti.handle = bufferHandle{}\n\ti.val = nil\n\ti.lazyValue = base.LazyValue{}\n\ti.lazyValueHandling.vbr = nil\n\treturn nil\n}", "func (mt *MemoryTopo) Close() {\n}", "func TestEngineClose_RemoveIndex(t *testing.T) {\n\tengine := NewDefaultEngine()\n\tdefer engine.Close()\n\tengine.MustOpen()\n\n\tpt := models.MustNewPoint(\n\t\t\"cpu\",\n\t\tmodels.Tags{\n\t\t\t{Key: models.MeasurementTagKeyBytes, Value: []byte(\"cpu\")},\n\t\t\t{Key: []byte(\"host\"), Value: []byte(\"server\")},\n\t\t\t{Key: models.FieldKeyTagKeyBytes, Value: []byte(\"value\")},\n\t\t},\n\t\tmap[string]interface{}{\"value\": 1.0},\n\t\ttime.Unix(1, 2),\n\t)\n\n\terr := engine.Engine.WritePoints(context.TODO(), []models.Point{pt})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif got, exp := engine.SeriesCardinality(), int64(1); got != exp {\n\t\tt.Fatalf(\"got %d series, exp %d series in index\", got, exp)\n\t}\n\n\t// ensure the index gets loaded after closing and opening the shard\n\tengine.Engine.Close() // Don't destroy temporary data.\n\tengine.Open(context.Background())\n\n\tif got, exp := engine.SeriesCardinality(), int64(1); got != exp {\n\t\tt.Fatalf(\"got %d series, exp %d series in index\", got, exp)\n\t}\n}", "func (b *Buffer) Close() {\n\tatomic.StoreInt32(&b.stop, stop)\n}", "func (w *InMemoryWorld) Close() {\n\tif w.structEditing {\n\t\tw.saveStruct()\n\t}\n\n\tfor _, chunk := range w.chunks {\n\t\tif chunk.dirty {\n\t\t\tw.chunksToWrite <- chunk\n\t\t}\n\t}\n\tclose(w.chunksToWrite)\n\tlog.Println(\"Closed in memory world world\")\n}", "func (r *MMapRef) Close() error { return r.DecRef() }", "func (i *Iterator) Close() error {\n\ti.r.SetChunk(nil)\n\treturn i.Error()\n}", "func (pool *Pool) Close() {\n\tpool.mutex.Lock()\n\tpool.freelist = nil\n\tpool.mutex.Unlock()\n}", "func (nt *NodeTable) Close() {\n\tnt.fastHTCount = 0\n\tnt.slowHTCount = 0\n\tnt.conflicts = 0\n\tnt.fastHT = make(map[uint32]uint64)\n\tnt.slowHT = make(map[uint32][]uint64)\n\n\tbuf := dbInstances.MakeBuf()\n\tdefer dbInstances.FreeBuf(buf)\n\tdbInstances.Delete(unsafe.Pointer(nt), CompareNodeTable, buf, &dbInstances.Stats)\n}", "func (si *ScanIterator) Close() {\n\t// Cleanup\n}", "func (it *TokenVestingReleasedIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (p *MessagePartition) releaseIndexfile(fileId uint64, file *os.File) {\n\tfile.Close()\n}", "func (b *Batch) Close() {\n}", "func (npw *Writer) Close() error {\n\tif npw.closed {\n\t\treturn nil\n\t}\n\n\tnpw.closed = true\n\n\tblockBufOffset := npw.offset % BigBlockSize\n\n\tif blockBufOffset > 0 {\n\t\tblockIndex := npw.offset / BigBlockSize\n\t\terr := npw.Pool.Downstream.Store(BlockLocation{FileIndex: npw.FileIndex, BlockIndex: blockIndex}, npw.blockBuf[:blockBufOffset])\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (i *Index) Freeze() {\n\ti.frozen = true\n}", "func (e *IndexLookUpMergeJoin) Close() error {\n\tif e.RuntimeStats() != nil {\n\t\tdefer e.Ctx().GetSessionVars().StmtCtx.RuntimeStatsColl.RegisterStats(e.ID(), e.RuntimeStats())\n\t}\n\tif e.cancelFunc != nil {\n\t\te.cancelFunc()\n\t\te.cancelFunc = nil\n\t}\n\tif e.resultCh != nil {\n\t\tchannel.Clear(e.resultCh)\n\t\te.resultCh = nil\n\t}\n\te.joinChkResourceCh = nil\n\t// joinChkResourceCh is to recycle result chunks, used by inner worker.\n\t// resultCh is the main thread get the results, used by main thread and inner worker.\n\t// cancelFunc control the outer worker and outer worker close the task channel.\n\te.workerWg.Wait()\n\te.memTracker = nil\n\te.prepared = false\n\treturn e.BaseExecutor.Close()\n}", "func (it *BaseContentSpaceCreateSpaceIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *BaseContentSpaceVersionDeleteIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *BaseContentSpaceCreateLibraryIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (f MemFile) Close() error {\n\treturn nil\n}", "func (b *Backend) Close() error { return nil }", "func (it *ContractsNewPositionIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *ZKOnacciTransferIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *Univ2MintIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (d *Document) Close() {\n\tdefaultPool.Put(d)\n}", "func (o *Objects) Close() error {\n\to.gcExit <- 1\n\to.Flush()\n\treturn nil\n}", "func (it *BaseContentDbgAccessIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *AccessIndexorRightsChangedIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *EthdkgDisputeIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (r *reader) Close() error {\n\tr.sb.lock.Lock()\n\tdefer r.sb.lock.Unlock()\n\n\t// SharedBuffer can now forget about tracking this reader\n\theap.Remove(&r.sb.readers, r.idx)\n\n\tr.at = 0\n\tr.idx = -1\n\tr.sb = nil\n\n\treturn nil\n}", "func (p *bytesViewer) Close() error { return nil }", "func (it *BaseContentSpaceAddKMSLocatorIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *TTFT20MintIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (n *NoOP) Close() {}", "func (it *RandomBeaconDkgSeedTimedOutIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *RandomBeaconDkgTimedOutIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *BaseContentSpaceAddNodeIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (w *SimpleMapReduce) Close() {\n close(w.workQueue)\n for _, f := range w.mappersFinished {\n <-f\n }\n\n close(w.reduceQueue)\n <-w.reducedFinished\n}", "func (it *BaseContentSpaceCreateContentIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *BaseContentSpaceRemoveKMSLocatorIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (mp *Mempool) Close() error {\n\tC.rte_mempool_free(mp.ptr())\n\treturn nil\n}", "func (mio *Mio) Close() error {\n if mio.obj == nil {\n return errors.New(\"object is not opened\")\n }\n C.m0_obj_fini(mio.obj)\n C.free(unsafe.Pointer(mio.obj))\n mio.obj = nil\n\n return nil\n}", "func (it *CrTokenReservesReducedIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (cluster *mongoCluster) Release() {\n\tcluster.Lock()\n\tif cluster.references == 0 {\n\t\tpanic(\"cluster.Release() with references == 0\")\n\t}\n\tcluster.references--\n\tif cluster.references == 0 {\n\t\tfor _, server := range cluster.servers.Slice() {\n\t\t\tserver.Close()\n\t\t}\n\t}\n\tcluster.Unlock()\n}", "func (it *FibonacciTestEventIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *EventExampleDataStoredIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (e *Enumerator) Close() {\n\t*e = ze\n\tbtEPool.Put(e)\n}", "func (ram *Ram) Close() error {\n\tram.tables = nil\n\n\treturn nil\n}", "func (it *BaseLibraryVersionDeleteIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (o *LargeObject) Close() error {\n\t_, err := o.tx.Exec(o.ctx, \"select lo_close($1)\", o.fd)\n\treturn err\n}", "func (p *Proposal) Close(idx int) {\n\tif !p.checkIndex(idx) {\n\t\treturn\n\t}\n\tp.nullifiers[idx].voteState.finished = true\n}", "func (it *BondedECDSAKeepERC20RewardDistributedIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (p *InMemoryExchangeBuffer) Close() int {\n\treturn 0\n}", "func (b *Bcache) Close() error {\n\tb.logger.Printf(\"mesh router stopping\")\n\treturn b.router.Stop()\n}" ]
[ "0.7114902", "0.7012508", "0.698615", "0.6954264", "0.6819634", "0.67804974", "0.66179514", "0.6605064", "0.6602648", "0.65786433", "0.64706266", "0.6317055", "0.63160914", "0.62167317", "0.61983234", "0.61652386", "0.61438406", "0.6076535", "0.6058903", "0.6026794", "0.60068387", "0.60020965", "0.5987533", "0.5971988", "0.5968409", "0.59376585", "0.5934937", "0.59332436", "0.5930128", "0.592206", "0.59123695", "0.590166", "0.58983934", "0.5892223", "0.586335", "0.58593065", "0.58586305", "0.5856666", "0.58556116", "0.5828585", "0.5792371", "0.5787406", "0.57555467", "0.5749399", "0.57444316", "0.57341987", "0.57286674", "0.5714522", "0.5682797", "0.56798536", "0.56764066", "0.5675436", "0.5673072", "0.5641931", "0.5641174", "0.56226474", "0.56069136", "0.56015974", "0.557964", "0.55719244", "0.55634844", "0.5563349", "0.5549744", "0.55369234", "0.55317044", "0.5530961", "0.55184835", "0.5512273", "0.5511817", "0.55090934", "0.55035514", "0.55007255", "0.55001974", "0.5497861", "0.5495478", "0.54942775", "0.54901725", "0.54877037", "0.54835474", "0.54820484", "0.5475141", "0.5472791", "0.5464365", "0.54436874", "0.54408926", "0.54384094", "0.54355294", "0.54343766", "0.54342633", "0.5431427", "0.54312474", "0.5424389", "0.54243267", "0.54207575", "0.54097867", "0.54096735", "0.5407647", "0.54068136", "0.54040325", "0.540029" ]
0.60702044
18
WriteState writes the state of a stopped index to the given writer. If the indexed is not stopped the result is undefined.
func (idx *Tree) WriteState(out io.Writer) (n int, err error) { return idx.writeState(out) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *EtcdStateDriver) WriteState(key string, value core.State,\n\tmarshal func(interface{}) ([]byte, error)) error {\n\tencodedState, err := marshal(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn d.Write(key, encodedState)\n}", "func (p *Platform) WriteState(w io.Writer) (*Platform, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\tsf := statefile.New(p.State, \"\", 0)\n\treturn p, statefile.Write(sf, w)\n}", "func (s LocalBackend) WriteState(st *State) error {\n\tlog.Debugf(\"Writing state to %s\\n\", s.Path)\n\tdata, err := json.MarshalIndent(st, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to Load State for Writing\")\n\t}\n\terr = ioutil.WriteFile(s.Path, data, 0644)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to write state to file\")\n\t}\n\treturn nil\n}", "func (r *templateRouter) writeState() error {\n\tdat, err := json.MarshalIndent(r.state, \"\", \" \")\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to marshal route table: %v\", err)\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(routeFile, dat, 0644)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to write route table: %v\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (w *Writer) writeIndex() (int64, error) {\n\tw.written = true\n\n\tbuf := new(bytes.Buffer)\n\tst := sst.NewWriter(buf)\n\n\tw.spaceIds.Sort()\n\n\t// For each defined space, we index the space's\n\t// byte offset in the file and the length in bytes\n\t// of all data in the space.\n\tfor _, spaceId := range w.spaceIds {\n\t\tb := new(bytes.Buffer)\n\n\t\tbinary.WriteInt64(b, w.spaceOffsets[spaceId])\n\t\tbinary.WriteInt64(b, w.spaceLengths[spaceId])\n\n\t\tif err := st.Set([]byte(spaceId), b.Bytes()); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tif err := st.Close(); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn buf.WriteTo(w.file)\n}", "func (s *Store) WriteState(id ipn.StateKey, bs []byte) error {\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tsecret, err := s.client.GetSecret(ctx, s.secretName)\n\tif err != nil {\n\t\tif st, ok := err.(*kube.Status); ok && st.Code == 404 {\n\t\t\treturn s.client.CreateSecret(ctx, &kube.Secret{\n\t\t\t\tTypeMeta: kube.TypeMeta{\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\tKind: \"Secret\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: kube.ObjectMeta{\n\t\t\t\t\tName: s.secretName,\n\t\t\t\t},\n\t\t\t\tData: map[string][]byte{\n\t\t\t\t\tsanitizeKey(id): bs,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\treturn err\n\t}\n\tif s.canPatch {\n\t\tm := []kube.JSONPatch{\n\t\t\t{\n\t\t\t\tOp: \"add\",\n\t\t\t\tPath: \"/data/\" + sanitizeKey(id),\n\t\t\t\tValue: bs,\n\t\t\t},\n\t\t}\n\t\tif err := s.client.JSONPatchSecret(ctx, s.secretName, m); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tsecret.Data[sanitizeKey(id)] = bs\n\tif err := s.client.UpdateSecret(ctx, secret); err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (x *Index) Write(w io.Writer) error", "func (losm LogOnlyStateManager) WriteState(state *sous.State, _ sous.User) error {\n\treportWriting(losm.log, time.Now(), state, nil)\n\treturn nil\n}", "func (t *WindowedThroughput) SaveState() ([]byte, error) {\n\treturn nil, nil\n}", "func (q *T) updateWriterState(w *writer, overrideBusy bool, isActive bool, consumed int) {\n\tq.mutex.Lock()\n\tif isActive {\n\t\tif w.isActive == idle || w.isActive == busy && overrideBusy {\n\t\t\tq.active[w.priority] = append(q.active[w.priority], w)\n\t\t\tw.isActive = active\n\t\t\tw.deficit -= consumed\n\t\t\tif w.deficit < 0 {\n\t\t\t\tpanic(\"deficit is negative\")\n\t\t\t}\n\t\t\tq.cond.Signal()\n\t\t}\n\t} else {\n\t\tif w.isActive == active {\n\t\t\tpanic(\"Writer is active when it should not be\")\n\t\t}\n\t\tif overrideBusy {\n\t\t\tw.isActive = idle\n\t\t}\n\t\tw.deficit = 0\n\t}\n\tq.mutex.Unlock()\n}", "func (x *Index) Write(w io.Writer) error {}", "func (c *Conn) WriteServiceResState(v bool) error {\n\tb := byte(0)\n\tif v {\n\t\tb = 1\n\t}\n\n\t_, err := c.writeBuf.Write([]byte{b})\n\t// do not flush, since WriteServiceResState() is always called before a WriteMessage()\n\treturn err\n}", "func (item *queueItem) setIndexState(state indexState) {\n\tif state == item.indexState {\n\t\treturn\n\t}\n\tif item.indexState != \"\" {\n\t\tmetricIndexState.WithLabelValues(string(item.indexState)).Dec()\n\t}\n\titem.indexState = state\n\tif item.indexState != \"\" {\n\t\tmetricIndexState.WithLabelValues(string(item.indexState)).Inc()\n\t}\n}", "func (c *Action) SaveState(k, v string) {\n\tfmt.Fprintf(c.w, saveStateFmt, k, escapeData(v))\n}", "func Write(s *File, w io.Writer) error {\n\tdiags := writeStateV4(s, w)\n\treturn diags.Err()\n}", "func writer(ch <-chan Word, index *sync.Map, wg *sync.WaitGroup) {\n\tfor {\n\t\tif word, more := <-ch; more {\n\t\t\t// fmt.Printf(\"Writing: %s\\n\", word)\n\t\t\tseen, loaded := index.LoadOrStore(word.word, []int{word.index})\n\t\t\tif loaded && !contains(seen.([]int), word.index) {\n\t\t\t\tseen = append(seen.([]int), word.index)\n\t\t\t\tindex.Store(word.word, seen)\n\t\t\t}\n\t\t} else {\n\t\t\twg.Done()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (state *State) SetStopped() error {\n\treturn state.SetState(false)\n}", "func (o ExportOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Export) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (w *StatusWorker) SetState(state StatusWorkerState) {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\n\tw.state = state\n\tstatsState.Set(string(state))\n}", "func IndexWrite(x *suffixarray.Index, w io.Writer) error", "func (p *PhidgetDigitalOutput) SetState(state bool) error {\n\treturn p.phidgetError(C.PhidgetDigitalOutput_setState(p.handle, boolToCInt(state)))\n}", "func (ips *IPAMState) Write() error {\n\tvar err error\n\n\tips.IPAMPolicy.Lock()\n\tdefer ips.IPAMPolicy.Unlock()\n\n\tprop := &ips.IPAMPolicy.Status.PropagationStatus\n\tpropStatus := ips.getPropStatus()\n\tnewProp := &security.PropagationStatus{\n\t\tGenerationID: propStatus.generationID,\n\t\tMinVersion: propStatus.minVersion,\n\t\tPending: propStatus.pending,\n\t\tPendingNaples: propStatus.pendingDSCs,\n\t\tUpdated: propStatus.updated,\n\t\tStatus: propStatus.status,\n\t}\n\n\t//Do write only if changed\n\tif ips.stateMgr.propgatationStatusDifferent(prop, newProp) {\n\t\tips.IPAMPolicy.Status.PropagationStatus = *newProp\n\t\terr = ips.IPAMPolicy.Write()\n\t\tif err != nil {\n\t\t\tips.IPAMPolicy.Status.PropagationStatus = *prop\n\t\t}\n\t}\n\treturn err\n}", "func (fp *FileProducer) WriteTFState() error {\n\tbase := make(map[string]interface{})\n\t// NOTE(muvaf): Since we try to produce the current state, observation\n\t// takes precedence over parameters.\n\tfor k, v := range fp.parameters {\n\t\tbase[k] = v\n\t}\n\tfor k, v := range fp.observation {\n\t\tbase[k] = v\n\t}\n\tbase[\"id\"] = meta.GetExternalName(fp.Resource)\n\tattr, err := json.JSParser.Marshal(base)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot marshal produced state attributes\")\n\t}\n\tvar privateRaw []byte\n\tif pr, ok := fp.Resource.GetAnnotations()[AnnotationKeyPrivateRawAttribute]; ok {\n\t\tprivateRaw = []byte(pr)\n\t}\n\ts := json.NewStateV4()\n\ts.TerraformVersion = fp.Setup.Version\n\ts.Lineage = string(fp.Resource.GetUID())\n\ts.Resources = []json.ResourceStateV4{\n\t\t{\n\t\t\tMode: \"managed\",\n\t\t\tType: fp.Resource.GetTerraformResourceType(),\n\t\t\tName: fp.Resource.GetName(),\n\t\t\t// TODO(muvaf): we should get the full URL from Dockerfile since\n\t\t\t// providers don't have to be hosted in registry.terraform.io\n\t\t\tProviderConfig: fmt.Sprintf(`provider[\"registry.terraform.io/%s\"]`, fp.Setup.Requirement.Source),\n\t\t\tInstances: []json.InstanceObjectStateV4{\n\t\t\t\t{\n\t\t\t\t\tSchemaVersion: uint64(fp.Resource.GetTerraformSchemaVersion()),\n\t\t\t\t\tPrivateRaw: privateRaw,\n\t\t\t\t\tAttributesRaw: attr,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\trawState, err := json.JSParser.Marshal(s)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot marshal state object\")\n\t}\n\treturn errors.Wrap(fp.fs.WriteFile(filepath.Join(fp.Dir, \"terraform.tfstate\"), rawState, os.ModePerm), \"cannot write tfstate file\")\n}", "func (c *Cursor) WriteState(timestamp time.Time, state StateData, config *RateConfig) (writeError error) {\n\tc.computeMutex.Lock()\n\tvar savedEntry *StreamEntry\n\tdefer func() {\n\t\tif writeError == nil && savedEntry != nil {\n\t\t\tc.computedTimestamp = savedEntry.Timestamp\n\t\t\tfor _, ch := range c.entrySubscriptions {\n\t\t\t\tch <- savedEntry\n\t\t\t}\n\t\t}\n\t}()\n\tdefer c.computeMutex.Unlock()\n\n\tif c.lastState != nil && reflect.DeepEqual(c.lastState.StateData, state) {\n\t\treturn nil\n\t}\n\n\tif err := c.canHandleNewEntry(timestamp); err != nil {\n\t\treturn err\n\t}\n\n\tinputState := CloneStateData(state)\n\n\tvar lastChange time.Time\n\tif c.lastMutation == nil {\n\t\tif c.lastSnapshot != nil {\n\t\t\tlastChange = c.lastSnapshot.Timestamp\n\t\t}\n\t} else {\n\t\tlastChange = c.lastMutation.Timestamp\n\t}\n\tif c.lastState != nil && timestamp.Before(lastChange) {\n\t\treturn errors.New(\"Cannot write entry before last change.\")\n\t}\n\n\t// If the last thing that changed was a mutation and it's too soon to make a new mutation\n\tif c.lastMutation != nil && timestamp.Sub(c.lastMutation.Timestamp) < (time.Duration(config.ChangeFrequency)*time.Millisecond) {\n\t\tamendedMutation := &StreamEntry{\n\t\t\tType: StreamEntryMutation,\n\t\t\tTimestamp: c.lastMutation.Timestamp,\n\t\t}\n\n\t\t// Calculate a mutation from lastMutation to the new state.\n\t\tif c.lastState != nil && len(c.entrySubscriptions) > 0 {\n\t\t\tsavedEntry = &StreamEntry{\n\t\t\t\tType: StreamEntryMutation,\n\t\t\t\tTimestamp: timestamp,\n\t\t\t}\n\t\t\tdupedLastState, err := c.lastState.Clone()\n\t\t\tif err == nil {\n\t\t\t\tsavedEntry.Data = mutate.BuildMutation(dupedLastState.StateData, inputState.StateData)\n\t\t\t}\n\t\t}\n\n\t\t// Calculate the new mutation\n\t\tamendedMutation.Data = mutate.BuildMutation(c.lastState.StateData, inputState.StateData)\n\t\tif err := c.storage.AmendEntry(amendedMutation, c.lastMutation.Timestamp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Apply the new state\n\t\tc.computedState = inputState\n\t\tc.computedTimestamp = timestamp\n\t\tc.lastMutation = amendedMutation\n\t\treturn nil\n\t}\n\n\t// Check if we should make a new snapshot\n\tif c.lastState == nil || timestamp.Sub(c.lastSnapshot.Timestamp) >= (time.Duration(config.KeyframeFrequency)*time.Millisecond) {\n\t\t// Make a new snapshot\n\t\tsnapshot := &StreamEntry{\n\t\t\tType: StreamEntrySnapshot,\n\t\t\tData: inputState.StateData,\n\t\t\tTimestamp: timestamp,\n\t\t}\n\n\t\tsavedEntry = snapshot\n\t\tif err := c.storage.SaveEntry(snapshot); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.lastSnapshot = snapshot\n\t\tc.lastMutation = nil\n\t\tif err := c.copySnapshotState(); err != nil {\n\t\t\tc.ready = false\n\t\t\tc.computedState = nil\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Make a new mutation\n\toldState, err := c.computedState.Clone()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewMutationEntry := &StreamEntry{\n\t\tType: StreamEntryMutation,\n\t\tTimestamp: timestamp,\n\t\tData: mutate.BuildMutation(c.lastState.StateData, inputState.StateData),\n\t}\n\n\tsavedEntry = newMutationEntry\n\tif err := c.storage.SaveEntry(newMutationEntry); err != nil {\n\t\treturn err\n\t}\n\n\tc.lastMutation = newMutationEntry\n\tc.lastState = oldState\n\tc.computedState = inputState\n\tc.computedTimestamp = timestamp\n\treturn nil\n}", "func (f *Ferry) ReportState() {\n\tcallback := f.Config.StateCallback\n\tstate, err := f.SerializeStateToJSON()\n\tif err != nil {\n\t\tf.logger.WithError(err).Error(\"failed to serialize state to JSON\")\n\t\treturn\n\t}\n\n\tcallback.Payload = string(state)\n\terr = callback.Post(&http.Client{})\n\tif err != nil {\n\t\tf.logger.WithError(err).Errorf(\"failed to post state to callback %s\", callback.URI)\n\t}\n}", "func (m *VppToken) SetState(value *VppTokenState)() {\n m.state = value\n}", "func (p *Platform) WriteStateToFile(filename string) (*Platform, error) {\n\tvar state bytes.Buffer\n\tif _, err := p.WriteState(&state); err != nil {\n\t\treturn p, err\n\t}\n\treturn p, ioutil.WriteFile(filename, state.Bytes(), 0644)\n}", "func (w *Writer) Stop() {\n\tw.Flush()\n\tw.tdone <- true\n\t<-w.tdone\n}", "func (a *AliasAddAction) IsWriteIndex(flag bool) *AliasAddAction {\n\ta.isWriteIndex = &flag\n\treturn a\n}", "func (w *Watcher) SetState(key string, value any) {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tw.stateCache[key] = value\n}", "func (m *MacOSSoftwareUpdateStateSummary) SetState(value *MacOSSoftwareUpdateState)() {\n err := m.GetBackingStore().Set(\"state\", value)\n if err != nil {\n panic(err)\n }\n}", "func (l *LED) SetState(s State) error {\n\tvar v int\n\tv, ok := l.states[s]\n\tif !ok {\n\t\treturn fmt.Errorf(\"unrecognized %s LED state %q [%d]\", l.spi.Name(), s, s)\n\t}\n\n\treturn l.spi.Write(v)\n}", "func (w *Writer) BitIndex() int64", "func (sgp *SgpolicyState) Write() error {\n\tvar err error\n\n\tsgp.NetworkSecurityPolicy.Lock()\n\tdefer sgp.NetworkSecurityPolicy.Unlock()\n\n\tprop := &sgp.NetworkSecurityPolicy.Status.PropagationStatus\n\tpropStatus := sgp.getPropStatus()\n\tnewProp := &security.PropagationStatus{\n\t\tGenerationID: propStatus.generationID,\n\t\tMinVersion: propStatus.minVersion,\n\t\tPending: propStatus.pending,\n\t\tPendingNaples: propStatus.pendingDSCs,\n\t\tUpdated: propStatus.updated,\n\t\tStatus: propStatus.status,\n\t}\n\t//Do write only if changed\n\tif sgp.stateMgr.propgatationStatusDifferent(prop, newProp) {\n\t\tsgp.NetworkSecurityPolicy.Status.RuleStatus = make([]security.SGRuleStatus, len(sgp.ruleStats))\n\t\tfor i, ruleStat := range sgp.ruleStats {\n\t\t\tsgp.NetworkSecurityPolicy.Status.RuleStatus[i] = ruleStat\n\t\t}\n\t\tsgp.NetworkSecurityPolicy.Status.PropagationStatus = *newProp\n\t\terr = sgp.NetworkSecurityPolicy.Write()\n\t\tif err != nil {\n\t\t\tsgp.NetworkSecurityPolicy.Status.PropagationStatus = *prop\n\t\t}\n\t}\n\n\treturn err\n}", "func (index *ind) writeIndexFile() {\n\tif _, err := os.Stat(index.name); os.IsNotExist(err) {\n\t\tindexFile, err := os.Create(index.name)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tindexFile.Close()\n\t}\n\n\tb := new(bytes.Buffer)\n\te := gob.NewEncoder(b)\n\n\terr := e.Encode(index)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tioutil.WriteFile(index.name, b.Bytes(), 7777)\n}", "func (o JobStatusOutput) State() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.State }).(pulumi.StringPtrOutput)\n}", "func (b *BTSVShardWriter) Close(ctx context.Context) {\n\tb.rio.Flush()\n\tb.rio.Wait()\n\tb.colSorter.Sort()\n\tidx := gqlpb.BinaryTSVIndex{\n\t\tDescription: []string{\n\t\t\tfmt.Sprintf(\"cmdline: %s\", strings.Join(os.Args, \"\\t\")),\n\t\t},\n\t\tName: b.attrs.Name,\n\t\tPath: b.attrs.Path,\n\t\tMarshaledContext: b.marshalCtx.marshal(),\n\t}\n\tif b.attrs.Description != \"\" {\n\t\tidx.Description = append(idx.Description, b.attrs.Description)\n\t}\n\tfor _, colName := range b.colSorter.Columns() {\n\t\tcolID, ok := b.colIDMap[colName]\n\t\tif !ok {\n\t\t\tlog.Panicf(\"col %v not registered\", colName)\n\t\t}\n\t\tcol := *b.cols[colID]\n\n\t\t// Copy the description from the attrs given by the caller.\n\t\tfor _, c := range b.attrs.Columns {\n\t\t\tif c.Name == col.Name {\n\t\t\t\tcol.Description = c.Description\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tidx.Column = append(idx.Column, col)\n\t}\n\tidx.Rows = int64(b.nrows)\n\tidx.TimeLocation = b.locs\n\tidxData, err := idx.Marshal()\n\tif err != nil {\n\t\tlog.Panicf(\"btsv index marshal: %v\", err)\n\t}\n\tb.rio.SetTrailer(idxData)\n\tif err := b.rio.Finish(); err != nil {\n\t\tlog.Panicf(\"writebtsv %v: close: %v\", b.out.Name(), err)\n\t}\n\tif err := b.out.Close(ctx); err != nil {\n\t\tlog.Panicf(\"writebtsv %v: close: %v\", b.out.Name(), err)\n\t}\n\tlog.Debug.Printf(\"btsvwriter: close %s\", b.out.Name())\n}", "func (t *BenchmarkerChaincode) WriteRandom(stub shim.ChaincodeStubInterface, seed, nKeys, keySizeLo, keySizeHi, valSizeLo, valSizeHi int, indexName, indexValues string) pb.Response {\n\tvar (\n\t\tkm NoopKeyMapper\n\t\tval RandomStringValue\n\t\tindexValueSpace = t.getIndexValueSpace(indexValues)\n\t)\n\n\tval.Init(seed)\n\tkeys := km.GetKeys(seed, nKeys, keySizeLo, keySizeHi)\n\n\tfor _, key := range keys {\n\t\tval.Generate(key, valSizeLo, valSizeHi)\n\t\tfmt.Printf(\"WriteRandom: Putting '%s':'%s'\\n\", key, val.SerializeForState())\n\n\t\terr := stub.PutState(key, []byte(val.SerializeForState()))\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\t\tt.updateIndex(stub, key, indexName, indexValueSpace)\n\t}\n\n\treturn shim.Success([]byte(\"OK\"))\n}", "func (w *Writer) WriteBool(b bool) {\n\tif b {\n\t\tw.cache |= 1 << (w.available - 1)\n\t}\n\n\tw.available--\n\n\tif w.available == 0 {\n\t\t// WriteByte never returns error\n\t\t_ = w.out.WriteByte(w.cache)\n\t\tw.cache = 0\n\t\tw.available = 8\n\t}\n}", "func (m *SecurityActionState) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"appId\", m.GetAppId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n if m.GetStatus() != nil {\n cast := (*m.GetStatus()).String()\n err := writer.WriteStringValue(\"status\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteTimeValue(\"updatedDateTime\", m.GetUpdatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"user\", m.GetUser())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (w *heightStopWAL) Write(m walm.WALMessage) error {\n\tif w.stopped {\n\t\tpanic(\"WAL already stopped. Not writing meta message\")\n\t}\n\n\tw.logger.Debug(\"WAL Write Message\", \"msg\", m)\n\terr := w.enc.Write(walm.TimedWALMessage{fixedTime, m})\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to encode the msg %v\", m))\n\t}\n\n\treturn nil\n}", "func (o LookupIndexResultOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupIndexResult) string { return v.State }).(pulumi.StringOutput)\n}", "func (r *Registry) SaveUnitState(jobName string, unitState *unit.UnitState) {\n\tkey := path.Join(r.keyPrefix, statePrefix, jobName)\n\t//TODO: Handle the error generated by marshal\n\tjson, _ := marshal(unitState)\n\tr.etcd.Set(key, json, 0)\n}", "func (m *PrintJobStatus) SetState(value *PrintJobProcessingState)() {\n m.state = value\n}", "func (t *nonStopWriter) Write(p []byte) (int, error) {\n\tfor _, w := range t.writers {\n\t\tw.Write(p)\n\t}\n\treturn len(p), nil\n}", "func (this *Tidy) WriteBack(val bool) (bool, error) {\n\treturn this.optSetBool(C.TidyWriteBack, cBool(val))\n}", "func (i *Int64) WriterStore(v int64) {\n\taba := i.aba\n\taba++\n\ti.val[aba&1] = v\n\tfence.W_SMP() // store(i.val[aba&1]) must be observed before store(i.aba).\n\tatomic.StoreUintptr(&i.aba, aba)\n}", "func Write_SymbolDirectorySymbolStatus(stream Streams.IMitchWriter, value SymbolDirectorySymbolStatus) (int, error) {\n\treturn stream.Write_byte(byte(value))\n}", "func (s *State) Export(writer io.WriteSeeker, evictedSlot slot.Index) (err error) {\n\treturn stream.WriteCollection(writer, func() (elementsCount uint64, err error) {\n\t\tfor currentSlot := s.delayedBlockEvictionThreshold(evictedSlot) + 1; currentSlot <= evictedSlot; currentSlot++ {\n\t\t\tif err = s.storage.RootBlocks.Stream(currentSlot, func(rootBlockID models.BlockID, commitmentID commitment.ID) (err error) {\n\t\t\t\tif err = stream.WriteSerializable(writer, rootBlockID, models.BlockIDLength); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"failed to write root block ID %s\", rootBlockID)\n\t\t\t\t}\n\n\t\t\t\tif err = stream.WriteSerializable(writer, commitmentID, commitmentID.Length()); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"failed to write root block's %s commitment %s\", rootBlockID, commitmentID)\n\t\t\t\t}\n\n\t\t\t\telementsCount++\n\n\t\t\t\treturn\n\t\t\t}); err != nil {\n\t\t\t\treturn 0, errors.Wrap(err, \"failed to stream root blocks\")\n\t\t\t}\n\t\t}\n\n\t\treturn elementsCount, nil\n\t})\n}", "func (lw *LogWriter) Status() error {\n\treturn lw.state\n}", "func (w *writer) updateStateLocked(overrideBusy bool, consumed int) {\n\tw.free.IncN(uint(consumed))\n\n\t// The w.isActive state does not depend on the deficit.\n\tisActive := (w.size == 0 && w.isClosed) ||\n\t\t(w.size != 0 && (w.released < 0 || w.contents.Front().(*iobuf.Slice).Size() <= w.released))\n\tw.q.updateWriterState(w, overrideBusy, isActive, consumed)\n}", "func (g *Gossiper) SaveState() {\n\tobj, e := json.MarshalIndent(g, \"\", \"\\t\")\n\tutils.HandleError(e)\n\t_ = os.Mkdir(utils.STATE_FOLDER, os.ModePerm)\n\tcwd, _ := os.Getwd()\n\te = ioutil.WriteFile(filepath.Join(cwd, utils.STATE_FOLDER, fmt.Sprint(g.Name, \".json\")), obj, 0644)\n\tutils.HandleError(e)\n}", "func (m *DeviceEnrollmentWindowsHelloForBusinessConfiguration) SetState(value *Enablement)() {\n err := m.GetBackingStore().Set(\"state\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o MetadataExportResponseOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MetadataExportResponse) string { return v.State }).(pulumi.StringOutput)\n}", "func (o DeprecationStatusResponseOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DeprecationStatusResponse) string { return v.State }).(pulumi.StringOutput)\n}", "func writableIndexStore(location string, cmdOpt cmdStoreOptions) (desync.IndexWriteStore, string, error) {\n\ts, indexName, err := indexStoreFromLocation(location, cmdOpt)\n\tif err != nil {\n\t\treturn nil, indexName, err\n\t}\n\tstore, ok := s.(desync.IndexWriteStore)\n\tif !ok {\n\t\treturn nil, indexName, fmt.Errorf(\"index store '%s' does not support writing\", location)\n\t}\n\treturn store, indexName, nil\n}", "func (c *CycleState) Write(key StateKey, val StateData) {\n\tc.storage[key] = val\n}", "func (n *alterIndexNode) ReadingOwnWrites() {}", "func (w *StatusWorker) State() StatusWorkerState {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\n\treturn w.state\n}", "func (q *Queue) SetIndexed(repoName string, opts IndexOptions, state indexState) {\n\tq.mu.Lock()\n\titem := q.get(repoName)\n\titem.setIndexState(state)\n\tif state != indexStateFail {\n\t\titem.indexed = reflect.DeepEqual(opts, item.opts)\n\t}\n\tif item.heapIdx >= 0 {\n\t\t// We only update the position in the queue, never add it.\n\t\theap.Fix(&q.pq, item.heapIdx)\n\t}\n\tq.mu.Unlock()\n}", "func (o CustomPagesOutput) State() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *CustomPages) pulumi.StringPtrOutput { return v.State }).(pulumi.StringPtrOutput)\n}", "func SetState(newState map[string]interface{}) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tfor key, value := range newState {\n\t\tstate[key] = value\n\t}\n}", "func SetState(state bool, macAdd string) {\n\tvar statebit string\n\tif state == true {\n\t\tstatebit = \"01\"\n\t} else {\n\t\tstatebit = \"00\"\n\t}\n\tsendMessage(\"686400176463\"+macAdd+twenties+\"00000000\"+statebit, sockets[macAdd].IP)\n\tgo func() { Events <- EventStruct{\"stateset\", *sockets[macAdd]} }()\n}", "func (w *TimedWriter) Stop() {\n\tw.ticker.Stop()\n\tclose(w.done)\n}", "func (s *State) Write(p []byte) (nn int, err error) {\n\tl := len(p)\n\ts.clen += l\n\ts.tail = append(s.tail, p...)\n\treturn l, nil\n}", "func (ns *EsIndexer) Stop() {\n\n}", "func (s *StateMgr) SetState(n State) {\n\ts.current = n\n}", "func (o TestMatrixOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *TestMatrix) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (stub *MockStub) PutState(key string, value []byte) error {\n\tif stub.TxID == \"\" {\n\t\terr := errors.New(\"cannot PutState without a transactions - call stub.MockTransactionStart()?\")\n\t\treturn err\n\t}\n\n\t// If the value is nil or empty, delete the key\n\tif len(value) == 0 {\n\t\treturn stub.DelState(key)\n\t}\n\tstub.State[key] = value\n\n\t// insert key into ordered list of keys\n\tfor elem := stub.Keys.Front(); elem != nil; elem = elem.Next() {\n\t\telemValue := elem.Value.(string)\n\t\tcomp := strings.Compare(key, elemValue)\n\t\tif comp < 0 {\n\t\t\t// key < elem, insert it before elem\n\t\t\tstub.Keys.InsertBefore(key, elem)\n\t\t\tbreak\n\t\t} else if comp == 0 {\n\t\t\t// keys exists, no need to change\n\t\t\tbreak\n\t\t} else { // comp > 0\n\t\t\t// key > elem, keep looking unless this is the end of the list\n\t\t\tif elem.Next() == nil {\n\t\t\t\tstub.Keys.PushBack(key)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// special case for empty Keys list\n\tif stub.Keys.Len() == 0 {\n\t\tstub.Keys.PushFront(key)\n\t}\n\n\treturn nil\n}", "func (b *BlubberBlockDirectory) dumpState() {\n\tvar now time.Time = time.Now()\n\tvar newpath string = b.journalPrefix + now.Format(\"2006-01-02.150405\")\n\tvar oldJournalFile *os.File = b.journalFile\n\tvar newJournalFile *os.File\n\tvar newStateDumpFile *os.File\n\tvar stateDumpWriter *serialdata.SerialDataWriter\n\tvar stateDumpHeader *blubberstore.BlockDirectoryHeader\n\tvar blockId string\n\tvar serverMap map[string]*blubberstore.ServerBlockStatus\n\tvar err error\n\n\tos.Remove(b.blockMapPrefix + \".new\")\n\tnewStateDumpFile, err = os.Create(b.blockMapPrefix + \".new\")\n\tif err != nil {\n\t\tlog.Print(\"Unable to open new journal file \", newpath, \": \", err)\n\t\tlog.Print(\"Skipping state dump\")\n\t\treturn\n\t}\n\n\tnewJournalFile, err = os.Create(newpath)\n\tif err != nil {\n\t\tlog.Print(\"Unable to open new journal file \", newpath, \": \", err)\n\t\tlog.Print(\"Skipping state dump\")\n\t\treturn\n\t}\n\n\t// Start a new journal to track future differences. We'll assume they're\n\t// idempotent so we can just replay them on top of an already-modified\n\t// tree.\n\tb.currentJournal = serialdata.NewSerialDataWriter(newJournalFile)\n\tb.journalFile = newJournalFile\n\n\tstateDumpWriter = serialdata.NewSerialDataWriter(newStateDumpFile)\n\n\tb.blockMapMtx.RLock()\n\tdefer b.blockMapMtx.RUnlock()\n\tstateDumpHeader = new(blubberstore.BlockDirectoryHeader)\n\tstateDumpHeader.Revision = proto.Uint64(b.blockMapVersion)\n\tstateDumpWriter.WriteMessage(stateDumpHeader)\n\tstateDumpHeader = nil\n\n\tfor blockId, serverMap = range b.blockMap {\n\t\tvar bs blubberstore.BlockStatus\n\t\tvar host string\n\t\tvar srv *blubberstore.ServerBlockStatus\n\n\t\tbs.BlockId = make([]byte, len([]byte(blockId)))\n\t\tcopy(bs.BlockId, []byte(blockId))\n\n\t\t// TODO(caoimhe): make this something user specified.\n\t\tbs.ReplicationFactor = proto.Uint32(3)\n\n\t\tfor host, srv = range serverMap {\n\t\t\tif srv.GetHostPort() != host {\n\t\t\t\tlog.Print(\"host:port mismatch for block \", []byte(blockId),\n\t\t\t\t\t\": \", srv.GetHostPort(), \" vs. \", host)\n\t\t\t\tsrv.HostPort = proto.String(host)\n\t\t\t}\n\n\t\t\tbs.Servers = append(bs.Servers, srv)\n\t\t}\n\n\t\terr = stateDumpWriter.WriteMessage(&bs)\n\t\tif err != nil {\n\t\t\tlog.Print(\"Error writing record to state dump file: \", err)\n\t\t\tnewStateDumpFile.Close()\n\t\t\tos.Remove(b.blockMapPrefix + \".new\")\n\t\t}\n\t}\n\n\terr = newStateDumpFile.Close()\n\tif err != nil {\n\t\tlog.Print(\"Error writing state dump: \", err)\n\t\tos.Remove(b.blockMapPrefix + \".new\")\n\t\treturn\n\t}\n\n\t// Try moving the old state dump out of the way.\n\terr = os.Rename(b.blockMapPrefix+\".blockmap\", b.blockMapPrefix+\".old\")\n\tif err != nil && !os.IsNotExist(err) {\n\t\tlog.Print(\"Error moving away old state dump: \", err)\n\t}\n\n\t// Move the new state dump into the place where the old one used to be.\n\terr = os.Rename(b.blockMapPrefix+\".new\", b.blockMapPrefix+\".blockmap\")\n\tif err != nil {\n\t\tlog.Print(\"Error moving new state dump into place: \", err)\n\t\tos.Remove(b.blockMapPrefix + \".new\")\n\t\treturn\n\t}\n\n\terr = os.Remove(b.blockMapPrefix + \".old\")\n\tif err != nil && !os.IsNotExist(err) {\n\t\tlog.Print(\"Error deleting old state dump: \", err)\n\t}\n\n\terr = os.Remove(oldJournalFile.Name())\n\tif err != nil {\n\t\tlog.Print(\"Error deleting old journal file \", oldJournalFile.Name(),\n\t\t\t\": \", err)\n\t}\n}", "func (m *MacOSSoftwareUpdateStateSummary) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastUpdatedDateTime\", m.GetLastUpdatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"productKey\", m.GetProductKey())\n if err != nil {\n return err\n }\n }\n if m.GetState() != nil {\n cast := (*m.GetState()).String()\n err = writer.WriteStringValue(\"state\", &cast)\n if err != nil {\n return err\n }\n }\n if m.GetUpdateCategory() != nil {\n cast := (*m.GetUpdateCategory()).String()\n err = writer.WriteStringValue(\"updateCategory\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"updateVersion\", m.GetUpdateVersion())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (d *EtcdStateDriver) Write(key string, value []byte) error {\n\tctx, cancel := context.WithTimeout(context.Background(), ctxTimeout)\n\tdefer cancel()\n\n\tvar err error\n\n\tfor i := 0; i < maxEtcdRetries; i++ {\n\t\t_, err = d.Client.KV.Put(ctx, key, string(value[:]))\n\t\tif err != nil && err.Error() == client.ErrNoAvailableEndpoints.Error() {\n\t\t\t// Retry after a delay\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\t// when err == nil or anything other than connection refused\n\t\treturn err\n\t}\n\n\treturn err\n}", "func IndexState_Values() []string {\n\treturn []string{\n\t\tIndexStateCreating,\n\t\tIndexStateActive,\n\t\tIndexStateDeleting,\n\t\tIndexStateDeleted,\n\t\tIndexStateUpdating,\n\t}\n}", "func (this *DtNavMesh) StoreTileState(tile *DtMeshTile, data []byte, maxDataSize int) DtStatus {\n\t// Make sure there is enough space to store the state.\n\tsizeReq := this.GetTileStateSize(tile)\n\tif maxDataSize < sizeReq {\n\t\treturn DT_FAILURE | DT_BUFFER_TOO_SMALL\n\t}\n\n\ttileState := (*dtTileState)(unsafe.Pointer(&(data[0])))\n\tvar polyStates []dtPolyState\n\tsliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&polyStates)))\n\tsliceHeader.Cap = int(tile.Header.PolyCount)\n\tsliceHeader.Len = int(tile.Header.PolyCount)\n\tsliceHeader.Data = uintptr(unsafe.Pointer(&(data[DtAlign4(int(unsafe.Sizeof(dtTileState{})))])))\n\n\t// Store tile state.\n\ttileState.magic = DT_NAVMESH_STATE_MAGIC\n\ttileState.version = DT_NAVMESH_STATE_VERSION\n\ttileState.ref = this.GetTileRef(tile)\n\n\t// Store per poly state.\n\tfor i := 0; i < int(tile.Header.PolyCount); i++ {\n\t\tp := &tile.Polys[i]\n\t\ts := &polyStates[i]\n\t\ts.flags = p.Flags\n\t\ts.area = p.GetArea()\n\t}\n\n\treturn DT_SUCCESS\n}", "func (m *DeviceManagementIntentDeviceState) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"deviceDisplayName\", m.GetDeviceDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"deviceId\", m.GetDeviceId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastReportedDateTime\", m.GetLastReportedDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetState() != nil {\n cast := (*m.GetState()).String()\n err = writer.WriteStringValue(\"state\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userName\", m.GetUserName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userPrincipalName\", m.GetUserPrincipalName())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (c *Controller) Write(value byte) {\n\tc.strobe = value&1 == 1\n\tif c.strobe {\n\t\tc.index = 0\n\t}\n}", "func (vt *perfSchemaTable) WritableIndices() []table.Index {\n\treturn nil\n}", "func (o FunctionOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Function) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (i *index) Write(off uint32, pos uint64) error {\n\tif uint64(len(i.mmap)) < i.size+entWidth {\n\t\treturn io.EOF\n\t}\n\n\tenc.PutUint32(i.mmap[i.size:i.size+offWidth], off)\n\tenc.PutUint64(i.mmap[i.size+offWidth:i.size+entWidth], pos)\n\ti.size += uint64(entWidth)\n\treturn nil\n}", "func saveIndex(repoIndex *index.Index, dir string) {\n\tindexPath := path.Join(dir, INDEX_NAME)\n\n\tfmtc.Printf(\"Saving index… \")\n\n\terr := jsonutil.Write(indexPath, repoIndex)\n\n\tif err != nil {\n\t\tfmtc.Println(\"{r}ERROR{!}\")\n\t\tprintErrorAndExit(\"Can't save index as %s: %v\", indexPath, err)\n\t}\n\n\tfmtc.Println(\"{g}DONE{!}\")\n}", "func (s *TrainingJobStatusCounters) SetStopped(v int64) *TrainingJobStatusCounters {\n\ts.Stopped = &v\n\treturn s\n}", "func (o WorkerPoolOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *WorkerPool) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (o WorkflowOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Workflow) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (suh *StatusUpdateHandler) Writer() StatusUpdater {\n\treturn &StatusUpdateWriter{\n\t\tenabled: suh.sendUpdates,\n\t\tupdateChannel: suh.updateChannel,\n\t}\n}", "func setWriteFlag(tx *bolt.Tx) {\n}", "func StateToOutput(state StateT, dirToWatch string) OutputT {\n\tvar jsonMsg []byte\n\tvar encErr error\n\tif state.NewChanges || state.IgnorantMaster {\n\t\tjsonMsg, encErr = createPostMsg(\n\t\t\tstate.IgnorantMaster,\n\t\t\tstate.LatestGuid,\n\t\t\tstate.NewestChange,\n\t\t\tstate.Folder,\n\t\t\tstate.PreviousGuid,\n\t\t\tdirToWatch)\n\t} else {\n\t\tjsonMsg = []byte{}\n\t\tencErr = nil\n\t}\n\terrs := combineErrors([]error{state.FatalError, state.NonFatalError, encErr})\n\tvar msgToPrint string\n\tif errs == nil {\n\t\tmsgToPrint = \"\"\n\t} else {\n\t\tmsgToPrint = errs.Error()\n\t}\n\treturn OutputT{\n\t\tJsonToSend: jsonMsg,\n\t\tMsgToPrint: msgToPrint,\n\t}\n}", "func (d *Deck) SaveState() {\n\td.saveStateToBucket(phrasesBucket)\n}", "func SetStateDb() {\n\tgenCode(flagSetStateDb)\n}", "func (o EnvironmentOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Environment) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (p *Stream) WriteBool(v bool) {\n\tswitch v {\n\tcase true:\n\t\tp.writeFrame[p.writeIndex] = 2\n\tcase false:\n\t\tp.writeFrame[p.writeIndex] = 3\n\t}\n\tp.writeIndex++\n\tif p.writeIndex == streamBlockSize {\n\t\tp.gotoNextWriteFrame()\n\t}\n}", "func (s *Stopper) SetStopped() {\n\tif s != nil {\n\t\ts.wg.Done()\n\t}\n}", "func (ws *workingSet) PutState(s interface{}, opts ...protocol.StateOption) (uint64, error) {\n\t_stateDBMtc.WithLabelValues(\"put\").Inc()\n\tcfg, err := processOptions(opts...)\n\tif err != nil {\n\t\treturn ws.height, err\n\t}\n\tss, err := state.Serialize(s)\n\tif err != nil {\n\t\treturn ws.height, errors.Wrapf(err, \"failed to convert account %v to bytes\", s)\n\t}\n\treturn ws.height, ws.store.Put(cfg.Namespace, cfg.Key, ss)\n}", "func (o LookupWorkstationResultOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupWorkstationResult) string { return v.State }).(pulumi.StringOutput)\n}", "func (ws *workingSet) PutState(pkHash hash.PKHash, s interface{}) error {\n\tss, err := state.Serialize(s)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to convert account %v to bytes\", s)\n\t}\n\treturn ws.accountTrie.Upsert(pkHash[:], ss)\n}", "func (b *bar) writer() {\n\tb.update()\n\tfor {\n\t\tselect {\n\t\tcase <-b.finishChan:\n\t\t\treturn\n\t\tcase <-time.After(b.opts.RefreshRate):\n\t\t\tb.update()\n\t\t}\n\t}\n}", "func (m *WorkbookRangeBorder) SetSideIndex(value *string)() {\n err := m.GetBackingStore().Set(\"sideIndex\", value)\n if err != nil {\n panic(err)\n }\n}", "func (t *tableCommon) WritableIndices() []table.Index {\n\ttrace_util_0.Count(_tables_00000, 36)\n\tif len(t.writableIndices) > 0 {\n\t\ttrace_util_0.Count(_tables_00000, 39)\n\t\treturn t.writableIndices\n\t}\n\ttrace_util_0.Count(_tables_00000, 37)\n\twritable := make([]table.Index, 0, len(t.indices))\n\tfor _, index := range t.indices {\n\t\ttrace_util_0.Count(_tables_00000, 40)\n\t\ts := index.Meta().State\n\t\tif s != model.StateDeleteOnly && s != model.StateDeleteReorganization {\n\t\t\ttrace_util_0.Count(_tables_00000, 41)\n\t\t\twritable = append(writable, index)\n\t\t}\n\t}\n\ttrace_util_0.Count(_tables_00000, 38)\n\treturn writable\n}", "func (m *DeviceManagementIntentDeviceState) SetState(value *ComplianceStatus)() {\n err := m.GetBackingStore().Set(\"state\", value)\n if err != nil {\n panic(err)\n }\n}", "func SaveLastRunState(lastRunState LastRunDownServers) {\n\t// write new last run state\n\tb, err := json.MarshalIndent(lastRunState, \"\", \" \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = ioutil.WriteFile(\"status.json\", b, 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func WriteTransitionStatus(db database.KeyValueWriter, data []byte) {\n\tif err := db.Put(transitionStatusKey, data, \"transitionStatus\"); err != nil {\n\t\tlog.Critical(\"Failed to store the entropy2 transition status\", \"err\", err)\n\t}\n}" ]
[ "0.5682337", "0.5468304", "0.535246", "0.5290441", "0.5290366", "0.51643854", "0.5085427", "0.50634223", "0.49989465", "0.49612185", "0.4951277", "0.4912789", "0.48487547", "0.47717863", "0.47549745", "0.46995154", "0.46872133", "0.4659843", "0.46535382", "0.46109673", "0.4590497", "0.45428738", "0.45198643", "0.4485708", "0.44738805", "0.44610378", "0.44441885", "0.44398794", "0.44252488", "0.44223306", "0.44065732", "0.44034633", "0.43868756", "0.43799925", "0.4375914", "0.43664423", "0.43662417", "0.43570018", "0.43557367", "0.43470213", "0.434353", "0.43076164", "0.42826858", "0.42825404", "0.42668325", "0.42656386", "0.42337576", "0.42259625", "0.42201728", "0.4208787", "0.42039198", "0.4199142", "0.41988212", "0.41835713", "0.41782707", "0.4178092", "0.4169382", "0.41602513", "0.41473103", "0.4139683", "0.41243264", "0.41167018", "0.41138053", "0.4112633", "0.41071132", "0.41002902", "0.40952528", "0.40912786", "0.40754077", "0.40674734", "0.40638977", "0.40626052", "0.40618655", "0.40581614", "0.40575042", "0.40568763", "0.40565133", "0.4056272", "0.40535212", "0.4038709", "0.40362325", "0.40270564", "0.4018023", "0.4014998", "0.401341", "0.40127096", "0.40102753", "0.40075657", "0.40072334", "0.40036887", "0.40000227", "0.39955613", "0.39893377", "0.39873046", "0.3983913", "0.3976705", "0.39765504", "0.39757174", "0.39746287", "0.39725727" ]
0.62815976
0
allocateNode returns the new node and its data block, position at start
func (idx *Tree) allocateNode(a *Allocator, count int, prefixLen int) (n uint64, data []uint64) { prefixSlots := (prefixLen + 7) >> 3 if prefixLen >= 255 { prefixSlots++ } count += prefixSlots n = a.newNode(count) block := int(n >> blockSlotsShift) offset := int(n & blockSlotsOffsetMask) data = idx.blocks[block].data[offset:] return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *BTree) AllocateNode() *BTreeNode {\n\tx := BTreeNode{}\n\tfor i := 0; i < 2*t.t; i++ {\n\t\tx.children = append(x.children, t.nullNode)\n\t}\n\tfor i := 0; i < 2*t.t-1; i++ {\n\t\tx.keys = append(x.keys, -1)\n\t}\n\treturn &x\n}", "func (idx *Tree) allocateNodeWithPrefix(a *Allocator, count int, prefix []byte) (n uint64, data []uint64) {\n\tprefixLen := len(prefix)\n\tprefixSlots := (prefixLen + 7) >> 3\n\tif prefixLen >= 255 {\n\t\tprefixSlots++\n\t}\n\tcount += prefixSlots\n\tn = a.newNode(count)\n\tblock := int(n >> blockSlotsShift)\n\toffset := int(n & blockSlotsOffsetMask)\n\tdata = idx.blocks[block].data[offset:]\n\tif prefixLen > 0 {\n\t\tstorePrefix(data, prefix)\n\t\tdata = data[prefixSlots:]\n\t}\n\treturn\n}", "func (allc *Allocator) makeNode(truncatedSize uint32) uint32 {\n\t// Calculate the amount of actual memory required for this node.\n\t// Depending on the height of the node, size might be truncated.\n\tsize := defaultNodeSize - truncatedSize\n\t/*padding := size % cacheLineSize\n\tif padding < paddingLimit {\n\t\tsize += padding\n\t}*/\n\treturn allc.new(size)\n}", "func (b *nodeBuilder) createNode(rng Range, kind AstNodeKind, scope ScopePosition) NodePosition {\n\t// maybe we should handle here the capacity of the node arrays ?\n\tl := NodePosition(len(b.nodes))\n\tb.nodes = append(b.nodes, AstNode{Kind: kind, Range: rng, Scope: scope})\n\treturn l\n}", "func (t *BPTree) newNode() *Node {\n\tnode := &Node{\n\t\tKeys: make([][]byte, order-1),\n\t\tpointers: make([]interface{}, order),\n\t\tisLeaf: false,\n\t\tparent: nil,\n\t\tKeysNum: 0,\n\t\tAddress: t.LastAddress,\n\t}\n\tsize := getBinaryNodeSize()\n\tt.LastAddress += size\n\n\treturn node\n}", "func (t *Btree) newNode() *Node {\n\t*t.NodeCount++\n\tid := t.genrateID()\n\tnode := &Node{\n\t\tNodeRecordMetaData: NodeRecordMetaData{\n\t\t\tId: proto.Int64(id),\n\t\t\tIsDirt: proto.Int32(0),\n\t\t},\n\t}\n\tt.nodes[id] = node\n\treturn node\n}", "func NewNode(host string, size int) Node {\n\treturn node{host: host, size: size}\n}", "func (t *MCTS) alloc() naughty {\n\tt.Lock()\n\tl := len(t.freelist)\n\tif l == 0 {\n\t\tN := Node{\n\t\t\ttree: ptrFromTree(t),\n\t\t\tid: naughty(len(t.nodes)),\n\n\t\t\tminPSARatioChildren: defaultMinPsaRatio,\n\t\t}\n\t\tt.nodes = append(t.nodes, N)\n\t\tt.children = append(t.children, make([]naughty, 0, t.M*t.N+1))\n\t\tt.childLock = append(t.childLock, sync.Mutex{})\n\t\tn := naughty(len(t.nodes) - 1)\n\t\tt.Unlock()\n\t\treturn n\n\t}\n\n\ti := t.freelist[l-1]\n\tt.freelist = t.freelist[:l-1]\n\tt.Unlock()\n\treturn naughty(i)\n}", "func createNewEmptyNode() Node {\n\tnextNewId--\n\treturn Node{\n\t\tId: nextNewId,\n\t\tVisible: true,\n\t\tTimestamp: time.Now().Format(\"2006-01-02T15:04:05Z\"),\n\t\tVersion: \"1\",\n\t}\n}", "func newNode(parent *node, entry *nodeEntry) *node {\n\treturn &node{\n\t\tparent: parent,\n\t\toccupied: true,\n\t\tevalTotal: entry.eval,\n\t\tcount: 1,\n\t\tentry: entry,\n\t}\n}", "func (b *BTree) newNode() *memNode {\n\tfget := b.freeList.Get()\n\tvar n *Node\n\tif fget != nil {\n\t\tn = fget.(*Node)\n\t\tn.Reset()\n\t} else {\n\t\tn = &Node{}\n\t}\n\n\t// var parentIdx int\n\tvar depth int // parent == nil -> depth=0 root\n\n\tmn := &memNode{\n\t\tid: b.opCtx.GetNextID(),\n\t\tdepth: depth,\n\t\tnode: n,\n\t}\n\tb.opCtx.PushDirtyNode(mn)\n\treturn mn\n}", "func newNode(cluster *Cluster, nv *nodeValidator) *Node {\n\treturn &Node{\n\t\tcluster: cluster,\n\t\tname: nv.name,\n\t\taliases: nv.aliases,\n\t\taddress: nv.address,\n\t\tuseNewInfo: nv.useNewInfo,\n\n\t\t// Assign host to first IP alias because the server identifies nodes\n\t\t// by IP address (not hostname).\n\t\thost: nv.aliases[0],\n\t\tconnections: NewAtomicQueue(cluster.clientPolicy.ConnectionQueueSize),\n\t\tconnectionCount: NewAtomicInt(0),\n\t\thealth: NewAtomicInt(_FULL_HEALTH),\n\t\tpartitionGeneration: NewAtomicInt(-1),\n\t\treferenceCount: NewAtomicInt(0),\n\t\trefreshCount: NewAtomicInt(0),\n\t\tresponded: NewAtomicBool(false),\n\t\tactive: NewAtomicBool(true),\n\n\t\tsupportsFloat: NewAtomicBool(nv.supportsFloat),\n\t\tsupportsBatchIndex: NewAtomicBool(nv.supportsBatchIndex),\n\t\tsupportsReplicasAll: NewAtomicBool(nv.supportsReplicasAll),\n\t\tsupportsGeo: NewAtomicBool(nv.supportsGeo),\n\t}\n}", "func createNewNode(ctx context.Context, nodeName string, virtual bool, clientset kubernetes.Interface) (*corev1.Node, error) {\n\tresources := corev1.ResourceList{}\n\tresources[corev1.ResourceCPU] = *resource.NewScaledQuantity(5000, resource.Milli)\n\tresources[corev1.ResourceMemory] = *resource.NewScaledQuantity(5, resource.Mega)\n\tnode := &corev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: nodeName,\n\t\t},\n\t}\n\tif virtual {\n\t\tnode.Labels = map[string]string{\n\t\t\tconsts.TypeLabel: consts.TypeNode,\n\t\t}\n\t}\n\tnode.Status = corev1.NodeStatus{\n\t\tCapacity: resources,\n\t\tAllocatable: resources,\n\t\tConditions: []corev1.NodeCondition{\n\t\t\t0: {\n\t\t\t\tType: corev1.NodeReady,\n\t\t\t\tStatus: corev1.ConditionTrue,\n\t\t\t},\n\t\t},\n\t}\n\tnode, err := clientset.CoreV1().Nodes().Create(ctx, node, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn node, nil\n}", "func (t *MCTS) alloc() Naughty {\n\tt.Lock()\n\tdefer t.Unlock()\n\tl := len(t.freelist)\n\tif l == 0 {\n\t\tN := Node{\n\t\t\tlock: sync.Mutex{},\n\t\t\ttree: ptrFromTree(t),\n\t\t\tid: Naughty(len(t.nodes)),\n\t\t\thasChildren: false,\n\t\t}\n\t\tt.nodes = append(t.nodes, N)\n\t\tt.children = append(t.children, make([]Naughty, 0, t.current.ActionSpace()))\n\t\tn := Naughty(len(t.nodes) - 1)\n\t\treturn n\n\t}\n\n\ti := t.freelist[l-1]\n\tt.freelist = t.freelist[:l-1]\n\treturn i\n}", "func NewNode(data int) *Node {\n\treturn &Node{\n\t\tNext: nil,\n\t\tData: data,\n\t}\n}", "func NewNode(data int) *Node {\n\treturn &Node{\n\t\tData: data,\n\t\tNext: nil,\n\t}\n}", "func (bpt *BplusTree) treeNodeInit(isLeaf bool, next common.Key, prev common.Key,\n\tinitLen int) *treeNode {\n\n\tnode := defaultAlloc()\n\tnode.Children = make([]treeNodeElem, initLen, bpt.context.maxDegree)\n\tnode.IsLeaf = isLeaf\n\tnode.NextKey = next\n\tnode.PrevKey = prev\n\t// Generate a new key for the node being added.\n\tnode.NodeKey = common.Generate(bpt.context.keyType, bpt.context.pfx)\n\treturn node\n}", "func newNode() *node {\n\treturn &node{}\n}", "func NewNode(p string) *MyNode {\n\taddr := getLocalAddress()\n\n\treturn &MyNode{\n\t\tAddr: addr,\n\t\tPort: p,\n\t\tID: HashString(fmt.Sprintf(\"%v:%v\", addr, p)),\n\t\tData: make(map[string]string),\n\t\tbuf: new(bytes.Buffer),\n\t}\n}", "func Regalloc(n *Node, t *Type, o *Node)", "func (_BaseFactory *BaseFactoryTransactor) CreateNode(opts *bind.TransactOpts, _owner common.Address) (*types.Transaction, error) {\n\treturn _BaseFactory.contract.Transact(opts, \"createNode\", _owner)\n}", "func newNode(nodePath string) Node {\n\treturn &nodeImpl{nodePath: nodePath}\n}", "func newNode() *node {\n\treturn &node{\n\t\tvalue: nil,\n\t\tchildren: map[string]*node{},\n\t}\n}", "func NewNode(cnf *Config, joinNode *api.Node) (*Node, error) {\n\tvar nodeID string\n\n\tnode := &Node{\n\t\tNode: new(api.Node),\n\t\tshutdownCh: make(chan struct{}),\n\t\tcnf: cnf,\n\t\tstorage: NewMapStore(cnf.Hash),\n\t}\n\tif cnf.Id != \"\" {\n\t\tnodeID = cnf.Id\n\t} else {\n\t\tnodeID = cnf.Addr\n\t}\n\n\tid, err := node.hashKey(nodeID)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taInt := (&big.Int{}).SetBytes(id) // treating id as bytes of a big-endian unsigned integer, return the integer it represents\n\tlog.Printf(aurora.Sprintf(aurora.Yellow(\"New Node ID = %d, \\n\"), aInt))\n\tnode.Node.Id = id\n\tnode.Node.Addr = cnf.Addr\n\t// Populate finger table (by anotating itself to be in charge of all possible hashes at the moment)\n\tnode.fingerTable = newFingerTable(node.Node, cnf.HashSize)\n\n\t// Start RPC server (start listening function, )\n\t// transport is a struct that contains grpc server and supplementary attributes (like timeout etc)\n\ttransport, err := NewGrpcTransport(cnf)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnode.transport = transport\n\n\tapi.RegisterChordServer(transport.server, node)\n\tnode.transport.Start()\n\n\t// find the closest node clockwise from the id of this node (i.e. successor node)\n\t// adds successor to the 'successor' attribute of the node\n\tnodeJoinErr := node.join(joinNode)\n\n\tif nodeJoinErr != nil {\n\t\tlog.Printf(\"Error joining node\")\n\t\treturn nil, err\n\t}\n\n\t// run routines\n\t// Fix fingers every 500 ms\n\tgo node.fixFingerRoutine(500)\n\n\t// Stablize every 1000ms\n\tgo node.stabilizeRoutine(1000)\n\t// Check predecessor fail every 5000 ms\n\tgo node.checkPredecessorRoutine(2000)\n\n\treturn node, nil\n}", "func NewNode(id uint64) *Node { return &Node{Id: id} }", "func createLocalNode() {\n\t// Initialize the internal table\n\tinternalTable = NewTable(config.maxKey)\n\n\t// Set the variables of this node.\n\tvar err error\n\tcaller, err = NewNodeCaller(config.callerPort)\n\tif err != nil {\n\t\tpanic(\"rpcCaller failed to initialize\")\n\t}\n\terr = initNodeCallee(config.calleePort)\n\tif err != nil {\n\t\tpanic(\"rpcCallee failed to initialize\")\n\t}\n\n\tmy.address = fmt.Sprintf(\"%s:%d\", config.addr, config.calleePort)\n\n\tmy.key = Hash(my.address, config.maxKey)\n\tlog.Printf(\"[NODE %d] Keyspace position %d was derived from address %s\\n\", my.key, my.key, my.address)\n\n\tpredecessor = nil\n\tsuccessor = &RemoteNode{\n\t\tAddress: my.address,\n\t\tKey: my.key,\n\t}\n\t// Initialize the finger table for the solo ring configuration\n\tfingers = make([]*RemoteNode, config.numFingers)\n\tlog.Printf(\"[NODE %d] Finger table size %d was derived from the keyspace size\\n\", my.key, config.numFingers)\n\tfor i := uint64(0); i < config.numFingers; i++ {\n\t\tfingers[i] = successor\n\t}\n}", "func newNode(index int, parent *node, hasher hash.Hash) *node {\n\treturn &node{\n\t\tparent: parent,\n\t\tisLeft: index%2 == 0,\n\t\thasher: hasher,\n\t}\n}", "func newNode() *Node {\n\tn := &Node{}\n\treturn n\n}", "func newNode(val int) *node {\n\treturn &node{val, nil, nil}\n}", "func (tree *Tree23) newNode() TreeNodeIndex {\n\n\t// Recycle a deleted node.\n\tif tree.treeNodesFreePositions.len() > 0 {\n\t\tnode := TreeNodeIndex(tree.treeNodesFreePositions.pop())\n\t\treturn node\n\t}\n\n\t// Resize the cache and get more memory.\n\t// Resize our cache by 2x or 1.25x of the previous length. This is in accordance to slice append resizing.\n\tl := len(tree.treeNodes)\n\tif tree.treeNodesFirstFreePos >= l {\n\t\tappendSize := int(float64(l) * 1.25)\n\t\tif l < 1000 {\n\t\t\tappendSize = l * 2\n\t\t}\n\t\ttree.treeNodes = append(tree.treeNodes, make([]treeNode, appendSize)...)\n\t}\n\n\t// Get node from cached memory.\n\ttree.treeNodesFirstFreePos++\n\treturn TreeNodeIndex(tree.treeNodesFirstFreePos - 1)\n}", "func (nh *NodeHost) RequestAddNode(clusterID uint64,\n\tnodeID uint64, address string, configChangeIndex uint64,\n\ttimeout time.Duration) (*RequestState, error) {\n\tv, ok := nh.getCluster(clusterID)\n\tif !ok {\n\t\treturn nil, ErrClusterNotFound\n\t}\n\treq, err := v.requestAddNodeWithOrderID(nodeID,\n\t\taddress, configChangeIndex, timeout)\n\tnh.execEngine.setNodeReady(clusterID)\n\treturn req, err\n}", "func createNodeRoute(w http.ResponseWriter, r *http.Request) {\n\troute := \"CreateNode\"\n\n\tquery := r.URL.Query()\n\tnodeID, initAmount := query.Get(\"nodeID\"), query.Get(\"initAmount\")\n\n\thandleRoute(route, nodeID, initAmount)\n}", "func NewNode(cache *Cache, path string, parent *Node) *Node {\n\tdepth := 0\n\tif parent != nil {\n\t\tdepth = parent.depth + 1\n\t}\n\treturn &Node{\n\t\tcache: cache,\n\t\tstate: NodeStatePending,\n\t\tparent: parent,\n\t\tpath: path,\n\t\tchildren: make(map[string]*Node),\n\t\tdepth: depth,\n\t}\n}", "func StartNewNode(\n\tconfig *Config,\n\tinitialNetworkState *pb.NetworkState,\n\tinitialCheckpointValue []byte,\n) (*Node, error) {\n\treturn RestartNode(\n\t\tconfig,\n\t\t&dummyWAL{\n\t\t\tinitialNetworkState: initialNetworkState,\n\t\t\tinitialCheckpointValue: initialCheckpointValue,\n\t\t},\n\t)\n}", "func NewNode(data int) *Node {\n\treturn &Node{\n\t\tData: data,\n\t\tLeft: nil,\n\t\tRight: nil,\n\t}\n}", "func (t *BPTree) startNewTree(key []byte, pointer *Record) error {\n\tt.root = t.newLeaf()\n\tt.root.Keys[0] = key\n\tt.root.pointers[0] = pointer\n\tt.root.KeysNum = 1\n\n\treturn nil\n}", "func newCbsNode(region string, volumeAttachLimit int64) (*cbsNode, error) {\n\tsecretID, secretKey, token, _ := util.GetSercet()\n\tcred := &common.Credential{\n\t\tSecretId: secretID,\n\t\tSecretKey: secretKey,\n\t\tToken: token,\n\t}\n\n\tclient, err := cbs.NewClient(cred, region, profile.NewClientProfile())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnode := cbsNode{\n\t\tmetadataClient: metadata.NewMetaData(http.DefaultClient),\n\t\tcbsClient: client,\n\t\tmounter: mount.SafeFormatAndMount{\n\t\t\tInterface: mount.New(\"\"),\n\t\t\tExec: exec.New(),\n\t\t},\n\t\tidempotent: util.NewIdempotent(),\n\t\tvolumeAttachLimit: volumeAttachLimit,\n\t}\n\treturn &node, nil\n}", "func (allc *Allocator) getNode(offset uint32) *node {\n\tif offset == nilAllocatorOffset {\n\t\treturn nil\n\t}\n\treturn (*node)(unsafe.Pointer(&allc.mem[offset]))\n}", "func NewSampleNodeAllocate() NodeAllocate {\n\treturn NodeAllocate{\n\t\tKubeReservedCPU: \"1\",\n\t\tSysReservedCPU: \"1\",\n\t\tKubeMemory: \"500Mi\",\n\t\tSysMemory: \"500Mi\",\n\t\tKubeStorage: \"10Gi\",\n\t\tSysStorage: \"10Gi\",\n\t\tEvictionMemory: \"500Mi\",\n\t\tEvictionNodefs: \"10%\",\n\t}\n}", "func nodeCreator(inputValue int64) *Node {\n\n\t// instantiate the node pointer\n\tnode := new(Node)\n\n\t// add the value\n\tnode.value = inputValue\n\n\t// return a pointer to a node\n\treturn node\n}", "func newNode(allc *Allocator, valAllc *Allocator, height uint8, key []byte, val []byte) (*node, uint32) {\n\ttruncatedSize := (DefaultMaxHeight - int(height)) * LayerSize\n\tkeyOffset := allc.putBytes(key)\n\tnodeOffset := allc.makeNode(uint32(truncatedSize))\n\tvalOffset := valAllc.putBytes(val)\n\tnode := allc.getNode(nodeOffset)\n\tnode.height = height\n\tnode.keyOffset = keyOffset\n\t// TODO key length should not exceed uint16 size, assert.\n\tnode.keySize = uint16(len(key))\n\tnode.encodeValue(valOffset, uint32(len(val)))\n\treturn node, nodeOffset\n}", "func (a API) AddNode(cmd *btcjson.AddNodeCmd) (e error) {\n\tRPCHandlers[\"addnode\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func NewNode(name string, tcpAddr string, job JobType) Node {\n\t// resolve ip\n\tn := util.NewNodeFromTCPAddr(tcpAddr, session.NodeTypeReplica /*dummy field*/)\n\treturn Node{\n\t\tJob: job,\n\t\tName: name,\n\t\tIPPort: n.TCPAddr(),\n\t\tHostname: n.Hostname,\n\t\tAttrs: map[string]interface{}{},\n\t}\n}", "func (bfs *BlockFilesystem) allocate(ctx context.Context) (uint64, error) {\n\tstate, err := bfs.store.State(ctx)\n\tif err != nil {\n\t\treturn nilPtr, err\n\t} else if state.TrashPtr == nilPtr {\n\t\tnext := state.NextPtr\n\t\tstate.NextPtr += 1\n\t\treturn next, nil\n\t}\n\n\tb := &block{parent: bfs}\n\tif bfs.splitPtrs {\n\t\trawPtrs, err := bfs.store.Get(ctx, p(state.TrashPtr))\n\t\tif err != nil {\n\t\t\treturn nilPtr, err\n\t\t} else if err := b.UnmarshalPtrs(rawPtrs); err != nil {\n\t\t\treturn nilPtr, fmt.Errorf(\"blockfs: failed to parse block %x: %v\", state.TrashPtr, err)\n\t\t}\n\t} else {\n\t\traw, err := bfs.store.Get(ctx, state.TrashPtr)\n\t\tif err != nil {\n\t\t\treturn nilPtr, err\n\t\t} else if err := b.Unmarshal(raw); err != nil {\n\t\t\treturn nilPtr, fmt.Errorf(\"blockfs: failed to parse block %x: %v\", state.TrashPtr, err)\n\t\t}\n\t}\n\n\ttrash := state.TrashPtr\n\tstate.TrashPtr = b.ptrs[0]\n\treturn trash, nil\n}", "func (_BaseContentSpace *BaseContentSpaceTransactor) AddNode(opts *bind.TransactOpts, _nodeAddr common.Address, _locator []byte) (*types.Transaction, error) {\n\treturn _BaseContentSpace.contract.Transact(opts, \"addNode\", _nodeAddr, _locator)\n}", "func NewNode(port int) dhtNode {\n\t// Todo: create a node and then return it.\n\treturn dht.NewSurface(port)\n}", "func NewNode(key int) *Node {\n\tp := int(rand.Int31n(math.MaxInt32))\n\treturn &Node{key: key, p: p, size: 1}\n}", "func createNode(cfg *meta.ClusterConfig, nodeUUID, nodeURL string) (*meta.Watcher, *meta.Node, *rpckit.RPCServer, error) {\n\t// create watcher\n\tw, err := meta.NewWatcher(nodeUUID, cfg)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// Start a rpc server\n\trpcSrv, err := rpckit.NewRPCServer(fmt.Sprintf(\"datanode-%s\", nodeUUID), nodeURL, rpckit.WithLoggerEnabled(false))\n\tif err != nil {\n\t\tlog.Errorf(\"failed to listen to %s: Err %v\", nodeURL, err)\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// register RPC handlers\n\ttproto.RegisterDataNodeServer(rpcSrv.GrpcServer, &fakeDataNode{nodeUUID: nodeUUID})\n\trpcSrv.Start()\n\ttime.Sleep(time.Millisecond * 50)\n\n\t// create node\n\tnd, err := meta.NewNode(cfg, nodeUUID, nodeURL)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\treturn w, nd, rpcSrv, nil\n}", "func NewNode(name string) TreeNode {\n\treturn TreeNode{\n\t\tname: name,\n\t\tsize: 0,\n\t\tfiles: make(map[string]Entry),\n\t}\n}", "func createNode(addr string, nodeStmts map[string]ast.Stmt) *ast.Node {\n\tnID := \"n\" + strings.Replace(addr, \".\", \"\", -1)\n\tnID = strings.Replace(nID, \":\", \"\", -1)\n\tn := &ast.Node{ID: nID}\n\tnodeStmts[n.ID] = &ast.NodeStmt{\n\t\tNode: n,\n\t\tAttrs: []*ast.Attr{\n\t\t\t{\n\t\t\t\tKey: \"label\",\n\t\t\t\tVal: fmt.Sprintf(`\"%s\"`, addr),\n\t\t\t},\n\t\t},\n\t}\n\treturn n\n}", "func (l *Libvirt) NodeAllocPages(PageSizes []uint32, PageCounts []uint64, StartCell int32, CellCount uint32, Flags NodeAllocPagesFlags) (rRet int32, err error) {\n\tvar buf []byte\n\n\targs := NodeAllocPagesArgs {\n\t\tPageSizes: PageSizes,\n\t\tPageCounts: PageCounts,\n\t\tStartCell: StartCell,\n\t\tCellCount: CellCount,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(347, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Ret: int32\n\t_, err = dec.Decode(&rRet)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func NewNode(tcpAddr *net.TCPAddr) *Node {\n\tn := new(Node)\n\tn.TcpAddr = tcpAddr\n\tn.btcNet = wire.MainNet\n\tn.doneC = make(chan struct{}, 1)\n\n\treturn n\n}", "func (r *root) newNode(view *View) (n *node) {\n\tif r.freeNode == nil {\n\t\tn = &node{view: *view, disposable: true}\n\t} else {\n\t\tn = r.freeNode\n\t\tr.freeNode = n.nextFree\n\t\tn.view = *view\n\t}\n\tr.newLeaves(view, &n.children)\n\treturn\n}", "func alloc(size uintptr, layout unsafe.Pointer) unsafe.Pointer", "func (p *pool) AllocateBlock(ctx context.Context, nodeName, requestUID string) (*coilv2.AddressBlock, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\tnextIndex, ok := p.allocated.NextClear(0)\n\tif !ok {\n\t\tnextIndex = p.allocated.Len()\n\t}\n\n\tap := &coilv2.AddressPool{}\n\terr := p.client.Get(ctx, client.ObjectKey{Name: p.name}, ap)\n\tif err != nil {\n\t\tp.log.Error(err, \"failed to get AddressPool\")\n\t\treturn nil, err\n\t}\n\tif ap.DeletionTimestamp != nil {\n\t\tp.log.Info(\"unable to curve out a block because pool is under deletion\")\n\t\treturn nil, ErrNoBlock\n\t}\n\n\tvar currentIndex uint\n\tfor _, ss := range ap.Spec.Subnets {\n\t\tvar ones, bits int\n\t\tif ss.IPv4 != nil {\n\t\t\t_, n, _ := net.ParseCIDR(*ss.IPv4) // ss was validated\n\t\t\tones, bits = n.Mask.Size()\n\t\t} else {\n\t\t\t_, n, _ := net.ParseCIDR(*ss.IPv6) // ss was validated\n\t\t\tones, bits = n.Mask.Size()\n\t\t}\n\t\tsize := uint(1) << (bits - ones - int(ap.Spec.BlockSizeBits))\n\t\tif nextIndex >= (currentIndex + size) {\n\t\t\tcurrentIndex += size\n\t\t\tcontinue\n\t\t}\n\n\t\tipv4, ipv6 := ss.GetBlock(nextIndex-currentIndex, int(ap.Spec.BlockSizeBits))\n\n\t\tr := &coilv2.AddressBlock{}\n\t\tr.Name = fmt.Sprintf(\"%s-%d\", p.name, nextIndex)\n\t\tif err := controllerutil.SetControllerReference(ap, r, p.scheme); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr.Labels = map[string]string{\n\t\t\tconstants.LabelPool: p.name,\n\t\t\tconstants.LabelNode: nodeName,\n\t\t\tconstants.LabelRequest: requestUID,\n\t\t}\n\t\tcontrollerutil.AddFinalizer(r, constants.FinCoil)\n\t\tr.Index = int32(nextIndex)\n\t\tif ipv4 != nil {\n\t\t\ts := ipv4.String()\n\t\t\tr.IPv4 = &s\n\t\t}\n\t\tif ipv6 != nil {\n\t\t\ts := ipv6.String()\n\t\t\tr.IPv6 = &s\n\t\t}\n\t\tif err := p.client.Create(ctx, r); err != nil {\n\t\t\tp.log.Error(err, \"failed to create AddressBlock\", \"index\", nextIndex, \"node\", nodeName)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tp.log.Info(\"created AddressBlock\", \"index\", nextIndex, \"node\", nodeName)\n\t\tp.allocated.Set(nextIndex)\n\t\tp.allocatedBlocks.Inc()\n\t\treturn r, nil\n\t}\n\n\tp.log.Error(ErrNoBlock, \"no available blocks\")\n\treturn nil, ErrNoBlock\n}", "func (g *Graph) AppendNode(content []byte, predecessors ...ObjectID) (*Object, error) {\n\tvar buf = make([]byte, 0)\n\n\tfor _, predecessor := range predecessors {\n\t\tbuf = append(buf, predecessor[:]...)\n\t}\n\tbuf = append(buf, content...)\n\n\th := ObjectID{}\n\t// Compute a 64-byte hash of buf and put it in h.\n\tsha3.ShakeSum128(h[:], buf)\n\tvar obj = Object{}\n\tobj.ID = h\n\tobj.Content = content\n\tobj.PredecessorIDs = append([]ObjectID{}, predecessors...)\n\n\tg.ObjectAdapter.WriteObject(obj)\n\n\treturn &obj, nil\n}", "func createList(numNodes int) (*Node) {\n var startNode, curNode *Node\n\n // create last linked\n lastNode := Node{nil, numNodes}\n\n // handle edge cases.\n if numNodes < 0 {\n return nil \n } else if numNodes == 1 {\n return &lastNode\n }\n\n // create n-1 other node.\n for i := 0 ; i<numNodes ; i++ {\n //fmt.Println(\"i\", i)\n // handle init case.\n if i == 0 {\n curNode = &lastNode\n }\n\n // setup new node.\n newNode := Node{nil, numNodes-(i+1)}\n\n // link node.\n curNode = addLink(&newNode, curNode)\n\n // update start node\n startNode = curNode\n }\n\n return startNode\n}", "func NewNode(node ast.Node) Node {\n\treturn creator(baseNode{node: node})\n}", "func NewNode(cnf *Config, joinNode *models.Node) (*Node, error) {\n\tif err := cnf.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tnode := &Node{\n\t\tNode: new(models.Node),\n\t\tshutdownCh: make(chan struct{}),\n\t\tcnf: cnf,\n\t\tstorage: NewMapStore(cnf.Hash),\n\t}\n\n\tvar nID string\n\tif cnf.Id != \"\" {\n\t\tnID = cnf.Id\n\t} else {\n\t\tnID = cnf.Addr\n\t}\n\tid, err := node.hashKey(nID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taInt := (&big.Int{}).SetBytes(id)\n\n\tfmt.Printf(\"new node id %d, \\n\", aInt)\n\n\tnode.Node.Id = id\n\tnode.Node.Addr = cnf.Addr\n\n\t// Populate finger table\n\tnode.fingerTable = newFingerTable(node.Node, cnf.HashSize)\n\n\t// Start RPC server\n\ttransport, err := NewGrpcTransport(cnf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnode.transport = transport\n\n\tmodels.RegisterChordServer(transport.server, node)\n\n\tnode.transport.Start()\n\n\tif err := node.join(joinNode); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Peridoically stabilize the node.\n\tgo func() {\n\t\tticker := time.NewTicker(1 * time.Second)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tnode.stabilize()\n\t\t\tcase <-node.shutdownCh:\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Peridoically fix finger tables.\n\tgo func() {\n\t\tnext := 0\n\t\tticker := time.NewTicker(100 * time.Millisecond)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tnext = node.fixFinger(next)\n\t\t\tcase <-node.shutdownCh:\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Peridoically checkes whether predecessor has failed.\n\n\tgo func() {\n\t\tticker := time.NewTicker(10 * time.Second)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tnode.checkPredecessor()\n\t\t\tcase <-node.shutdownCh:\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn node, nil\n}", "func NewNode(val int) *Node {\n\tn := &Node{}\n\tn.val = val\n\tn.next = nil\n\tn.prev = nil\n\treturn n\n}", "func Node(i Index, r Layer) (p Pos) {\n\tp.i = i\n\tp.r = r\n\tp.assertValid()\n\treturn\n}", "func NewNode(key, value interface{}) *Node {\n\tvar node Node\n\tnode.value = value\n\tnode.key = key\n\tnode.next = nil\n\treturn &node\n}", "func defaultAlloc() *treeNode {\n\treturn &treeNode{}\n}", "func (_PermInterface *PermInterfaceTransactor) AddNode(opts *bind.TransactOpts, _orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"addNode\", _orgId, _enodeId, _ip, _port, _raftport)\n}", "func (c *CAPI) AddNode(req *btcjson.AddNodeCmd, resp None) (e error) {\n\tnrh := RPCHandlers\n\tres := nrh[\"addnode\"].Result()\n\tres.Params = req\n\tnrh[\"addnode\"].Call <- res\n\tselect {\n\tcase resp = <-res.Ch.(chan None):\n\tcase <-time.After(c.Timeout):\n\tcase <-c.quit.Wait():\n\t} \n\treturn \n}", "func (c *Client) CreateDataNode(httpAddr, tcpAddr string) (*NodeInfo, error) {\n\tcmd := &internal.CreateDataNodeCommand{\n\t\tHTTPAddr: proto.String(httpAddr),\n\t\tTCPAddr: proto.String(tcpAddr),\n\t}\n\n\tif err := c.retryUntilExec(internal.Command_CreateDataNodeCommand, internal.E_CreateDataNodeCommand_Command, cmd); err != nil {\n\t\treturn nil, err\n\t}\n\n\tn, err := c.DataNodeByTCPHost(tcpAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.nodeID = n.ID\n\n\treturn n, nil\n}", "func (s *DHT) addNode(node *Node) *Node {\n\t// the bucket index for the node\n\tindex := s.ht.bucketIndex(s.ht.self.ID, node.ID)\n\n\t// 1. if the node is existed, refresh the node to the end of bucket\n\tif s.ht.hasBucketNode(index, node.ID) {\n\t\ts.ht.refreshNode(node.ID)\n\t\treturn nil\n\t}\n\n\ts.ht.mutex.Lock()\n\tdefer s.ht.mutex.Unlock()\n\n\t// 2. if the bucket is full, ping the first node\n\tbucket := s.ht.routeTable[index]\n\tif len(bucket) == K {\n\t\tfirst := bucket[0]\n\n\t\t// new a ping request message\n\t\trequest := s.newMessage(Ping, first, nil)\n\t\t// new a context with timeout\n\t\tctx, cancel := context.WithTimeout(context.Background(), defaultPingTime)\n\t\tdefer cancel()\n\n\t\t// invoke the request and handle the response\n\t\tresponse, err := s.network.Call(ctx, request)\n\t\tif err != nil {\n\t\t\t// the node is down, remove the node from bucket\n\t\t\tbucket = append(bucket, node)\n\t\t\tbucket = bucket[1:]\n\n\t\t\t// need to reset the route table with the bucket\n\t\t\ts.ht.routeTable[index] = bucket\n\n\t\t\tlog.WithContext(ctx).Debugf(\"bucket: %d, network call: %v: %v\", index, request, err)\n\t\t\treturn first\n\t\t}\n\t\tlog.WithContext(ctx).Debugf(\"ping response: %v\", response.String())\n\n\t\t// refresh the node to the end of bucket\n\t\tbucket = bucket[1:]\n\t\tbucket = append(bucket, node)\n\t} else {\n\t\t// 3. append the node to the end of the bucket\n\t\tbucket = append(bucket, node)\n\t}\n\n\t// need to update the route table with the bucket\n\ts.ht.routeTable[index] = bucket\n\n\treturn nil\n}", "func NodeAllocatableRoot(cgroupRoot string, cgroupsPerQOS bool, cgroupDriver string) string {\n\treturn \"\"\n}", "func (root *DSSRoot) newNode(state int, sym lr.Symbol) *DSSNode {\n\tvar node *DSSNode\n\tn, ok := root.reservoir.Get(0)\n\tif ok {\n\t\troot.reservoir.Remove(0)\n\t\tnode = n.(*DSSNode)\n\t\tnode.State = state\n\t\tnode.Sym = sym\n\t} else {\n\t\tnode = newDSSNode(state, sym)\n\t}\n\treturn node\n}", "func (s *Arena) putNode(height int) uint32 {\n\t// Compute the amount of the tower that will never be used, since the height\n\t// is less than maxHeight.\n\tunusedSize := (maxHeight - height) * offsetSize\n\n\t// Pad the allocation with enough bytes to ensure pointer alignment.\n\tl := uint32(MaxNodeSize - unusedSize + nodeAlign)\n\tn := s.allocate(l)\n\n\t// Return the aligned offset.\n\tm := (n - l + uint32(nodeAlign)) & ^uint32(nodeAlign)\n\treturn m\n}", "func NewNode(key int, value string) *Node {\n\treturn &Node{1, nil, nil, key, value}\n}", "func NewNode() *Node {\n\treturn &Node{}\n}", "func NewNode(data string) *Node {\n\tnode := &Node{}\n\tnode.data = data\n\treturn node\n}", "func nextNode(X [][]float64, indicies []int, d int) *Node {\n\txCols := len(X[0])\n\n\tvar c float64\n\tif len(indicies) > 1 {\n\t\tc = computeC(float64(len(indicies)))\n\t}\n\n\tif len(indicies) <= 1 || d >= MaxDepth {\n\t\treturn &Node{External: true, Size: len(indicies), C: c}\n\t}\n\n\tatt := findAttribute(xCols)\n\tsplit := findSplit(X, indicies, att)\n\n\tnewNode := &Node{Attribute: att, Split: split, External: false, Size: len(indicies), C: c}\n\n\tindiciesSmaller, indiciesBigger := splitMatrix(X, split, att, indicies)\n\tnewNode.Left = nextNode(X, indiciesSmaller, d+1)\n\n\tnewNode.Right = nextNode(X, indiciesBigger, d+1)\n\n\treturn newNode\n\n}", "func newNode() *node {\n\tvar leafs [8]octant\n\tfor i := 0; i < 8; i++ {\n\t\tleafs[i] = newLeaf(nil)\n\t}\n\treturn &node{\n\t\tleafs: &leafs,\n\t}\n}", "func newnode(id byte, name string, value string) *xmlx.Node {\n\tnode := xmlx.NewNode(id)\n\tif name != \"\" {\n\t\tnode.Name = xml.Name{\n\t\t\tLocal: name,\n\t\t}\n\t}\n\tif value != \"\" {\n\t\tnode.Value = value\n\t}\n\treturn node\n}", "func (fs *fsMutable) createNode(lk []byte, parentINode fuseops.InodeID, childName string,\n\tentry *fuseops.ChildInodeEntry, nodeType fuseutil.DirentType, isRoot bool) error {\n\n\t// Create lookup key if not already created.\n\tif lk == nil {\n\t\tlk = formLookupKey(parentINode, childName)\n\t}\n\n\tvar iNodeID fuseops.InodeID\n\tif !isRoot {\n\t\tiNodeID = fs.iNodeGenerator.allocINode()\n\t} else {\n\t\tiNodeID = parentINode\n\t}\n\n\t// lookup\n\tfs.lookupTree, _, _ = fs.lookupTree.Insert(lk, lookupEntry{iNode: iNodeID})\n\n\t// Default to common case of create file\n\tvar linkCount = fileLinkCount\n\tvar defaultMode os.FileMode = fileDefaultMode\n\tvar defaultSize uint64\n\n\tif nodeType == fuseutil.DT_Directory {\n\t\tlinkCount = dirLinkCount\n\t\tdefaultMode = dirDefaultMode\n\t\tdefaultSize = dirInitialSize\n\t\tfs.readDirMap[iNodeID] = make(map[fuseops.InodeID]*fuseutil.Dirent)\n\t} else {\n\t\t// dont return error as open file will retry this.\n\t\tfile, err := fs.localCache.Create(fmt.Sprint(iNodeID))\n\t\tif err == nil {\n\t\t\tfs.backingFiles[iNodeID] = &file\n\t\t} else {\n\t\t\tfs.l.Warn(\"failed to create backing file: open file will retry this\",\n\t\t\t\tzap.Error(err),\n\t\t\t\tzap.String(\"child\", childName),\n\t\t\t\tzap.String(\"localfs\", fs.localCache.Name()),\n\t\t\t\tzap.Uint64(\"parent\", uint64(parentINode)))\n\t\t}\n\t}\n\n\td := &fuseutil.Dirent{\n\t\tInode: iNodeID,\n\t\tName: childName,\n\t\tType: nodeType,\n\t}\n\tif !isRoot {\n\t\tfs.insertReadDirEntry(parentINode, d)\n\t}\n\n\tts := time.Now()\n\tattr := fuseops.InodeAttributes{\n\t\tSize: defaultSize,\n\t\tNlink: linkCount,\n\t\tMode: defaultMode,\n\t\tAtime: ts,\n\t\tMtime: ts,\n\t\tCtime: ts,\n\t\tCrtime: ts,\n\t\tUid: defaultGID,\n\t\tGid: defaultUID,\n\t}\n\n\t// iNode Store\n\tfs.iNodeStore, _, _ = fs.iNodeStore.Insert(formKey(iNodeID), &nodeEntry{\n\t\tlock: sync.Mutex{},\n\t\trefCount: 1, // As per spec CreateFileOp\n\t\tpathToBackingFile: getPathToBackingFile(iNodeID),\n\t\tattr: attr,\n\t})\n\n\tif nodeType == fuseutil.DT_Directory {\n\t\t// Increment parent ref count.\n\t\tp, _ := fs.iNodeStore.Get(formKey(parentINode))\n\t\tparentNodeEntry := p.(*nodeEntry)\n\t\tparentNodeEntry.attr.Nlink++\n\t}\n\n\t// If return is expected\n\tif entry != nil {\n\t\tentry.Attributes = attr\n\t\tentry.EntryExpiration = time.Now().Add(cacheYearLong)\n\t\tentry.AttributesExpiration = time.Now().Add(cacheYearLong)\n\t\tentry.Child = iNodeID\n\t}\n\treturn nil\n}", "func checkNodeAllocatableTest(f *framework.Framework) {\n\n\tnodeMem := getNodeMemory(f)\n\tframework.Logf(\"nodeMem says: %+v\", nodeMem)\n\n\t// calculate the allocatable mem based on capacity - reserved amounts\n\tcalculatedNodeAlloc := nodeMem.capacity.Copy()\n\tcalculatedNodeAlloc.Sub(nodeMem.systemReserve)\n\tcalculatedNodeAlloc.Sub(nodeMem.kubeReserve)\n\tcalculatedNodeAlloc.Sub(nodeMem.softEviction)\n\tcalculatedNodeAlloc.Sub(nodeMem.hardEviction)\n\n\tginkgo.By(fmt.Sprintf(\"Checking stated allocatable memory %v against calculated allocatable memory %v\", &nodeMem.allocatable, calculatedNodeAlloc))\n\n\t// sanity check against stated allocatable\n\tgomega.Expect(calculatedNodeAlloc.Cmp(nodeMem.allocatable)).To(gomega.Equal(0))\n}", "func newNode(k collection.Comparer, v interface{}, h int) *node {\n\tn := &node{K: k, V: v, H: h, C: make([]*node, 2)}\n\treturn n\n}", "func InitNode(ipfsAPIendpoint string) (*Node, error) {\n\n\t// use the API endpoint at the specified port\n\tnewNode := &Node{\n\t\tsh: ipfs.NewShell(ipfsAPIendpoint),\n\t\tallowNetwork: true,\n\t\tidentity: \"\",\n\t}\n\n\t// check it's online\n\tif !newNode.IsOnline() {\n\t\treturn nil, ErrOffline\n\t}\n\n\treturn newNode, nil\n}", "func (_NodeSpace *NodeSpaceTransactor) AddNode(opts *bind.TransactOpts, _nodeAddr common.Address, _locator []byte) (*types.Transaction, error) {\n\treturn _NodeSpace.contract.Transact(opts, \"addNode\", _nodeAddr, _locator)\n}", "func newNode(hash string) Node {\n\treturn Node{hash: hash, parent: nil}\n}", "func (p *Pacemaker) AddNode(rid uint64, cli TiKVClient) {\n\tlg.Debug(\"add tikv client to txn\", zap.Uint64(\"txnid\", p.txnid))\n\tp.Lock()\n\tif _, ok := p.kvnodes[rid]; !ok {\n\t\tp.kvnodes[rid] = cli\n\t}\n\tp.Unlock()\n}", "func NewNode(name string, w Worker) *Node {\n\tid := getID()\n\tn := &Node{id: id, w: w, name: name}\n\tn.chained = make(map[string]struct{})\n\tn.close = make(chan struct{})\n\treturn n\n}", "func (c *Client) CreateNode(config *peer.NodeConfig) (string, error) {\n\tnode := \"\"\n\treturn node, c.Post(\"/nodes\", config, node)\n}", "func (cc *ContrailCommand) CreateNode(host vcenter.ESXIHost) error {\n\tlog.Debug(\"Create Node:\", cc.AuthToken)\n\tnodeResource := contrailCommandNodeSync{\n\t\tResources: []*nodeResources{\n\t\t\t{\n\t\t\t\tKind: \"node\",\n\t\t\t\tData: &nodeData{\n\t\t\t\t\tNodeType: \"esxi\",\n\t\t\t\t\tUUID: host.UUID,\n\t\t\t\t\tHostname: host.Hostname,\n\t\t\t\t\tFqName: []string{\"default-global-system-config\", host.Hostname},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tjsonData, err := json.Marshal(nodeResource)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Sending Request\")\n\tresp, _, err := cc.sendRequest(\"/sync\", string(jsonData), \"POST\") //nolint: bodyclose\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Got status : \", resp.StatusCode)\n\tswitch resp.StatusCode {\n\tdefault:\n\t\treturn fmt.Errorf(\"resource creation failed, %d\", resp.StatusCode)\n\tcase 200, 201:\n\t}\n\treturn nil\n}", "func CreateNewRootNode(table *Table, rightNodePageNum uint32) {\n\t// Handle splitting the root.\n\t// Old root copied to new page, becomes left child.\n\t// Address of right child passed in.\n\t// Re-initialize root page to contain the new root node.\n\t// New root node points to two children.\n\tvar rootPage *Page = GetPage(table.Pager, table.RootPageNum)\n\tvar rightPage *Page = GetPage(table.Pager, rightNodePageNum)\n\tvar leftNodePageNum uint32 = GetUnallocatedPageNum(table.Pager)\n\tvar leftPage *Page = GetPage(table.Pager, leftNodePageNum)\n\n\t// The old root page is copied to the left node so we can reuse the root page\n\t// Left child has data copied from old root\n\tif copy(leftPage.Mem[:], rootPage.Mem[:]) != PageSize {\n\t\tos.Exit(util.ExitFailure)\n\t}\n\tSetRootNode(leftPage.Mem[:], false)\n\n\t// Finally we initialize the root page as a new internal node with two children.\n\t// Root node is a new internal node with one key and two children\n\tInitializeInternalNode(rootPage.Mem[:])\n\tSetRootNode(rootPage.Mem[:], true)\n\t*InternalNodeNumKeys(rootPage.Mem[:]) = 1\n\t*InternalNodeChild(rootPage.Mem[:], 0) = leftNodePageNum\n\tvar leftChildMaxKey uint32 = GetNodeMaxKeys(leftPage.Mem[:])\n\t*InternalNodeKey(rootPage.Mem[:], 0) = leftChildMaxKey\n\t*internalNodeRightChildPtr(rootPage.Mem[:]) = rightNodePageNum\n\n\t// Update Parent node to root node page\n\t*ParentNode(leftPage.Mem[:]) = table.RootPageNum\n\t*ParentNode(rightPage.Mem[:]) = table.RootPageNum\n}", "func AddNode(namespace string, clusterName string, req *app.NodeReq) (*model.NodeList, error) {\n\n\t// validate namespace\n\tif err := verifyNamespace(namespace); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get a cluster-entity\n\tcluster := model.NewCluster(namespace, clusterName)\n\tif exists, err := cluster.Select(); err != nil {\n\t\treturn nil, err\n\t} else if exists == false {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Could not be found a cluster '%s'. (namespace=%s)\", clusterName, namespace))\n\t} else if cluster.Status.Phase != model.ClusterPhaseProvisioned {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Unable to add a node. status is '%s'.\", cluster.Status.Phase))\n\t}\n\n\t// get a MCIS\n\tmcis := tumblebug.NewMCIS(namespace, cluster.MCIS)\n\tif exists, err := mcis.GET(); err != nil {\n\t\treturn nil, err\n\t} else if !exists {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Can't be found a MCIS '%s'.\", cluster.MCIS))\n\t}\n\tlogger.Infof(\"[%s.%s] The inquiry has been completed..\", namespace, clusterName)\n\n\tmcisName := cluster.MCIS\n\n\tif cluster.ServiceType == app.ST_SINGLE {\n\t\tif len(mcis.VMs) > 0 {\n\t\t\tconnection := mcis.VMs[0].Config\n\t\t\tfor _, worker := range req.Worker {\n\t\t\t\tif worker.Connection != connection {\n\t\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"The new node must be the same connection config. (connection=%s)\", worker.Connection))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"There is no VMs. (cluster=%s)\", clusterName))\n\t\t}\n\t}\n\n\t// get a provisioner\n\tprovisioner := provision.NewProvisioner(cluster)\n\n\t/*\n\t\tif err := provisioner.BuildAllMachines(); err != nil {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to build provisioner's map: %v\", err))\n\t\t}\n\t*/\n\n\t// get join command\n\tworkerJoinCmd, err := provisioner.NewWorkerJoinCommand()\n\tif err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to get join-command (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Worker join-command inquiry has been completed. (command=%s)\", namespace, clusterName, workerJoinCmd)\n\n\tvar workerCSP app.CSP\n\n\t// create a MCIR & MCIS-vm\n\tidx := cluster.NextNodeIndex(app.WORKER)\n\tvar vmgroupid []string\n\tfor _, worker := range req.Worker {\n\t\tmcir := NewMCIR(namespace, app.WORKER, *worker)\n\t\treason, msg := mcir.CreateIfNotExist()\n\t\tif reason != \"\" {\n\t\t\treturn nil, errors.New(msg)\n\t\t} else {\n\t\t\tfor i := 0; i < mcir.vmCount; i++ {\n\t\t\t\tname := lang.GenerateNewNodeName(string(app.WORKER), idx)\n\t\t\t\tif i == 0 {\n\t\t\t\t\tworkerCSP = mcir.csp\n\t\t\t\t}\n\t\t\t\tvm := mcir.NewVM(namespace, name, mcisName, \"\", worker.RootDisk.Type, worker.RootDisk.Size)\n\t\t\t\tif err := vm.POST(); err != nil {\n\t\t\t\t\tcleanUpNodes(*provisioner)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tvmgroupid = append(vmgroupid, name)\n\t\t\t\tprovisioner.AppendWorkerNodeMachine(name+\"-1\", mcir.csp, mcir.region, mcir.zone, mcir.credential)\n\t\t\t\tidx = idx + 1\n\t\t\t}\n\t\t}\n\t}\n\t// Pull out the added VMlist\n\tif _, err := mcis.GET(); err != nil {\n\t\treturn nil, err\n\t}\n\tvms := []tumblebug.VM{}\n\tfor _, mcisvm := range mcis.VMs {\n\t\tfor _, grupid := range vmgroupid {\n\t\t\tif mcisvm.VmGroupId == grupid {\n\t\t\t\tmcisvm.Namespace = namespace\n\t\t\t\tmcisvm.McisName = mcisName\n\t\t\t\tvms = append(vms, mcisvm)\n\t\t\t}\n\t\t}\n\t}\n\tlogger.Infof(\"[%s.%s] MCIS(vm) creation has been completed. (len=%d)\", namespace, clusterName, len(vms))\n\n\t// save nodes metadata\n\tif nodes, err := provisioner.BindVM(vms); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tcluster.Nodes = append(cluster.Nodes, nodes...)\n\t\tif err := cluster.PutStore(); err != nil {\n\t\t\tcleanUpNodes(*provisioner)\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity. (cause='%v')\", err))\n\t\t}\n\t}\n\n\t// kubernetes provisioning : bootstrap\n\ttime.Sleep(2 * time.Second)\n\tif err := provisioner.Bootstrap(); err != nil {\n\t\tcleanUpNodes(*provisioner)\n\t\treturn nil, errors.New(fmt.Sprintf(\"Bootstrap failed. (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Bootstrap has been completed.\", namespace, clusterName)\n\n\t// kubernetes provisioning : worker node join\n\tfor _, machine := range provisioner.WorkerNodeMachines {\n\t\tif err := machine.JoinWorker(&workerJoinCmd); err != nil {\n\t\t\tcleanUpNodes(*provisioner)\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Fail to worker-node join. (node=%s)\", machine.Name))\n\t\t}\n\t}\n\tlogger.Infof(\"[%s.%s] Woker-nodes join has been completed.\", namespace, clusterName)\n\n\t/* FIXME: after joining, check the worker is ready */\n\n\t// assign node labels (topology.cloud-barista.github.io/csp , topology.kubernetes.io/region, topology.kubernetes.io/zone)\n\tif err = provisioner.AssignNodeLabelAnnotation(); err != nil {\n\t\tlogger.Warnf(\"[%s.%s] Failed to assign node labels (cause='%v')\", namespace, clusterName, err)\n\t} else {\n\t\tlogger.Infof(\"[%s.%s] Node label assignment has been completed.\", namespace, clusterName)\n\t}\n\n\t// kubernetes provisioning : add some actions for cloud-controller-manager\n\tif provisioner.Cluster.ServiceType == app.ST_SINGLE {\n\t\tif workerCSP == app.CSP_AWS {\n\t\t\t// check whether AWS IAM roles exists and are same\n\t\t\tvar bFail bool = false\n\t\t\tvar bEmptyOrDiff bool = false\n\t\t\tvar msgError string\n\t\t\tvar awsWorkerRole string\n\n\t\t\tawsWorkerRole = req.Worker[0].Role\n\t\t\tif awsWorkerRole == \"\" {\n\t\t\t\tbEmptyOrDiff = true\n\t\t\t}\n\n\t\t\tif bEmptyOrDiff == false {\n\t\t\t\tfor _, worker := range req.Worker {\n\t\t\t\t\tif awsWorkerRole != worker.Role {\n\t\t\t\t\t\tbEmptyOrDiff = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif bEmptyOrDiff == true {\n\t\t\t\tbFail = true\n\t\t\t\tmsgError = \"Role should be assigned\"\n\t\t\t} else {\n\t\t\t\tif err := awsPrepareCCM(req.Worker[0].Connection, clusterName, vms, provisioner, \"\", awsWorkerRole); err != nil {\n\t\t\t\t\tbFail = true\n\t\t\t\t\tmsgError = \"Failed to prepare cloud-controller-manager\"\n\t\t\t\t} else {\n\t\t\t\t\t// Success\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif bFail == true {\n\t\t\t\tcleanUpNodes(*provisioner)\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity: %v)\", msgError))\n\t\t\t} else {\n\t\t\t\t// Success\n\t\t\t\tlogger.Infof(\"[%s.%s] CCM ready has been completed.\", namespace, clusterName)\n\t\t\t}\n\t\t}\n\t}\n\n\t// save nodes metadata & update status\n\tfor _, node := range cluster.Nodes {\n\t\tnode.CreatedTime = lang.GetNowUTC()\n\t}\n\tif err := cluster.PutStore(); err != nil {\n\t\tcleanUpNodes(*provisioner)\n\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity. (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Nodes creation has been completed.\", namespace, clusterName)\n\n\tnodes := model.NewNodeList(namespace, clusterName)\n\tnodes.Items = cluster.Nodes\n\treturn nodes, nil\n}", "func NewNode(n *pb.Node) *Node {\n\treturn &Node{\n\t\tX: int(n.X),\n\t\tY: int(n.Y),\n\t\tPlayer: int(n.Player),\n\t}\n}", "func (gortn *goroutine) AddNode(node sesstype.Node) {\n\tif gortn.leaf == nil {\n\t\tpanic(\"AddNode: leaf cannot be nil\")\n\t}\n\n\tnewLeaf := (*gortn.leaf).Append(node)\n\tgortn.leaf = &newLeaf\n}", "func NewNode(weightInitializer WeightInitializer, activationFunction ActivationFunction, derivativeActivation DerivativeActivation, nodeIndex int, learningRate FloatXX, layerIndex int, derivativeError DerivativeError, nodeType NodeType) *Node {\n\treturn &Node{\n\t\tinputNodes: nil,\n\t\toutputNodes: nil,\n\t\tweightInitializer: weightInitializer,\n\t\tactivation: activationFunction,\n\t\tderivativeActivation: derivativeActivation,\n\t\tmyIndex: nodeIndex,\n\t\tlearningRate: learningRate,\n\t\tlayerIndex: layerIndex,\n\t\tderivativeError: derivativeError,\n\t\tweights: []FloatXX{},\n\t\tmyType: nodeType,\n\t\tinputValue: FloatXX(0.0),\n\t\tlabel: FloatXX(0.0),\n\t\tmyErr: FloatXX(0.0),\n\t\tdEdW: []FloatXX{},\n\t\tmyoutCached: false,\n\t\tmyout: FloatXX(0.0),\n\t\tbackCached: false,\n\t\tinputs: []FloatXX{},\n\t\tdEdOut: FloatXX(0.0),\n\t\tdOutdIn: FloatXX(0.0),\n\t\tdIndW: []FloatXX{},\n\t}\n}", "func CreateNode(value int) *Node {\n\treturn &Node{Value: value}\n}", "func (s *Arena) getNode(offset uint32) *node {\n\tif offset == 0 {\n\t\treturn nil\n\t}\n\treturn (*node)(unsafe.Pointer(&s.data[offset]))\n}", "func (vns *VirtualNetworkService) Allocate(ctx context.Context, vnBlueprint blueprint.Interface,\n\tcluster resources.Cluster) (*resources.VirtualNetwork, error) {\n\tclusterID, err := cluster.ID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblueprintText, err := vnBlueprint.Render()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresArr, err := vns.call(ctx, \"one.vn.allocate\", blueprintText, clusterID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vns.RetrieveInfo(ctx, int(resArr[resultIndex].ResultInt()))\n}", "func (m *InstancesManager) CreateNode(obj *v2.CiliumNode, n *ipam.Node) ipam.NodeOperations {\n\treturn &Node{manager: m, node: n}\n}", "func (c *HashRing) AddNode(ip string, weight int) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tif weight <= 0 {\n\t\tweight = 1\n\t}\n\tfor i := 0; i < c.numberOfCubes*weight; i++ {\n\t\tc.ring[c.generateHash(c.generateKey(ip, i))] = ip\n\t}\n\tc.members[ip] = true\n\tc.weights[ip] = weight\n\n\tc.updateSortedRing()\n}", "func NewNode(tr Transaction, id string) *Node {\n\tif tr == nil {\n\t\tpanic(\"transaction may not be nil\")\n\t}\n\tif id == \"\" {\n\t\tid = uuid.NewV4().String()\n\t}\n\n\tn := &Node{\n\t\tTransaction: tr,\n\t\tId: id,\n\t}\n\n\tn.Reset()\n\treturn n\n\n\t/*\n\t\tpos := strings.Index(id, \"-\")\n\t\tif pos == -1 {\n\t\t\tn.Shard = id\n\t\t\tn.UUID = uuid.NewV4().String()\n\t\t} else {\n\t\t\tn.UUID = id[pos+1:]\n\t\t\tn.Shard = id[:pos]\n\t\t}\n\t*/\n\t// return n\n}", "func (rg *ResourceGroup) assignNode(id int64, deltaCapacity int) error {\n\tif rg.containsNode(id) {\n\t\treturn ErrNodeAlreadyAssign\n\t}\n\n\trg.nodes.Insert(id)\n\trg.capacity += deltaCapacity\n\n\treturn nil\n}", "func (np *NodePool) Node(id PolyRef, state uint8) *Node {\n\tbucket := hashRef(id) & uint32(np.hashSize-1)\n\n\tvar i NodeIndex\n\ti = np.first[bucket]\n\tvar node *Node\n\tfor i != nullIdx {\n\t\tif np.nodes[i].ID == id && np.nodes[i].State == state {\n\t\t\treturn &np.nodes[i]\n\t\t}\n\t\ti = np.next[i]\n\t}\n\n\tif np.nodeCount >= np.maxNodes {\n\t\treturn nil\n\t}\n\n\ti = NodeIndex(np.nodeCount)\n\tnp.nodeCount++\n\n\t// Init node\n\tnode = &np.nodes[i]\n\tnode.PIdx = 0\n\tnode.Cost = 0\n\tnode.Total = 0\n\tnode.ID = id\n\tnode.State = state\n\tnode.Flags = 0\n\n\tnp.next[i] = np.first[bucket]\n\tnp.first[bucket] = i\n\n\treturn node\n}", "func (sc *PintaCache) addNode(node *v1.Node) error {\n\tif sc.Nodes[node.Name] != nil {\n\t\tsc.Nodes[node.Name].SetNode(node)\n\t} else {\n\t\tsc.Nodes[node.Name] = info.NewNodeInfo(node)\n\t}\n\treturn nil\n}" ]
[ "0.67350614", "0.66224706", "0.6255893", "0.62361896", "0.58610564", "0.5856234", "0.573066", "0.57271", "0.5717261", "0.5710908", "0.5661831", "0.5650009", "0.56370544", "0.56184864", "0.55880314", "0.55836654", "0.5574136", "0.55566436", "0.5539488", "0.5515493", "0.5494545", "0.5443041", "0.5438003", "0.54197145", "0.54180825", "0.54082316", "0.5400205", "0.5396748", "0.53891194", "0.5387387", "0.5375944", "0.53731114", "0.53660923", "0.5357034", "0.53536665", "0.53452986", "0.5331645", "0.53309566", "0.5315522", "0.53130025", "0.53126055", "0.5306062", "0.52965873", "0.5279149", "0.5265667", "0.52564824", "0.5254148", "0.52520114", "0.5247065", "0.52242184", "0.522266", "0.5211909", "0.52113104", "0.519732", "0.51722234", "0.5168419", "0.5149499", "0.5149497", "0.5146446", "0.51349646", "0.51304334", "0.5124903", "0.51245993", "0.51087844", "0.510837", "0.51032794", "0.5099727", "0.5093389", "0.5092464", "0.5087179", "0.50827783", "0.50814945", "0.50690055", "0.506779", "0.5064144", "0.5060852", "0.5053305", "0.5052487", "0.50520873", "0.50489783", "0.5048548", "0.5046828", "0.5042017", "0.5039781", "0.50397503", "0.50346947", "0.50313133", "0.5028596", "0.502488", "0.5011302", "0.5007563", "0.49956995", "0.49949658", "0.49920753", "0.49918693", "0.4991561", "0.49888897", "0.49859947", "0.49856767", "0.49785948" ]
0.7961014
0
allocateNodeWithPrefix returns the new node and its data block, positioned after the prefix
func (idx *Tree) allocateNodeWithPrefix(a *Allocator, count int, prefix []byte) (n uint64, data []uint64) { prefixLen := len(prefix) prefixSlots := (prefixLen + 7) >> 3 if prefixLen >= 255 { prefixSlots++ } count += prefixSlots n = a.newNode(count) block := int(n >> blockSlotsShift) offset := int(n & blockSlotsOffsetMask) data = idx.blocks[block].data[offset:] if prefixLen > 0 { storePrefix(data, prefix) data = data[prefixSlots:] } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (idx *Tree) allocateNode(a *Allocator, count int, prefixLen int) (n uint64, data []uint64) {\n\tprefixSlots := (prefixLen + 7) >> 3\n\tif prefixLen >= 255 {\n\t\tprefixSlots++\n\t}\n\tcount += prefixSlots\n\tn = a.newNode(count)\n\tblock := int(n >> blockSlotsShift)\n\toffset := int(n & blockSlotsOffsetMask)\n\tdata = idx.blocks[block].data[offset:]\n\treturn\n}", "func (n *nodeHeader) setPrefix(p []byte) {\n\tpLen, pBytes := n.prefixFields()\n\n\t// Write to the byte array and set the length field to the num bytes copied\n\t*pLen = uint16(copy(pBytes, p))\n}", "func (n *nodeHeader) prefix() []byte {\n\tpLen, pBytes := n.prefixFields()\n\n\tif *pLen <= maxPrefixLen {\n\t\t// We have the whole prefix from the node\n\t\treturn pBytes[0:*pLen]\n\t}\n\n\t// Prefix is too long for node, we have to go find it from the leaf\n\tminLeaf := n.minChild().leafNode()\n\treturn minLeaf.key[0:*pLen]\n}", "func (t *Trie) getNodeAtPrefix(prefix string) (*Node, error) {\n\trunner := t.Root\n\n\tfor _, currChar := range prefix {\n\t\tif _, ok := runner.Children[currChar]; !ok {\n\t\t\treturn nil, errors.New(\"prefix not found\")\n\t\t}\n\t\trunner = runner.Children[currChar]\n\t}\n\n\treturn runner, nil\n}", "func (n Node) generatePrefix() string {\n\tindicator := \"├── \"\n\tif n.isLastElement() {\n\t\tindicator = \"└── \"\n\t}\n\n\treturn n.getPrefixes() + indicator\n}", "func (f *MemKv) newPrefixWatcher(ctx context.Context, prefix string, fromVersion string) (*watcher, error) {\n\tif !strings.HasSuffix(prefix, \"/\") {\n\t\tprefix += \"/\"\n\t}\n\treturn f.watch(ctx, prefix, fromVersion, true)\n}", "func generateKeyPrefixData(prefix []byte) []byte {\n\treturn append(prefix, []byte(\":data\")...)\n}", "func resourceNetboxIpamPrefixCreate(d *schema.ResourceData, meta interface{}) error {\n\tnetboxClient := meta.(*ProviderNetboxClient).client\n\n\tprefix := d.Get(\"prefix\").(string)\n\tdescription := d.Get(\"description\").(string)\n\tvrfID := int64(d.Get(\"vrf_id\").(int))\n\tisPool := d.Get(\"is_pool\").(bool)\n\t//status := d.Get(\"status\").(string)\n\ttenantID := int64(d.Get(\"tenant_id\").(int))\n\n\tvar parm = ipam.NewIPAMPrefixesCreateParams().WithData(\n\t\t&models.PrefixCreateUpdate{\n\t\t\tPrefix: &prefix,\n\t\t\tDescription: description,\n\t\t\tIsPool: isPool,\n\t\t\tTags: []string{},\n\t\t\tVrf: vrfID,\n\t\t\tTenant: tenantID,\n\t\t},\n\t)\n\n\tlog.Debugf(\"Executing IPAMPrefixesCreate against Netbox: %v\", parm)\n\n\tout, err := netboxClient.IPAM.IPAMPrefixesCreate(parm, nil)\n\n\tif err != nil {\n\t\tlog.Debugf(\"Failed to execute IPAMPrefixesCreate: %v\", err)\n\n\t\treturn err\n\t}\n\n\t// TODO Probably a better way to parse this ID\n\td.SetId(fmt.Sprintf(\"ipam/prefix/%d\", out.Payload.ID))\n\td.Set(\"prefix_id\", out.Payload.ID)\n\n\tlog.Debugf(\"Done Executing IPAMPrefixesCreate: %v\", out)\n\n\treturn nil\n}", "func newPrefix(targetPrefix []string) (prefixes []models.Prefix, err error) {\n\tprefixes = make([]models.Prefix, len(targetPrefix))\n\tfor i, cidr := range targetPrefix {\n\t\tprefix, err := models.NewPrefix(cidr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tprefixes[i] = prefix\n\t}\n\treturn\n}", "func (list *List) PrependToBeginning(data int) {\n // 1. Create a new node\n newNode := &Node{data: data, next: nil}\n\n // 2. Point the new node's next to current head\n newNode.next = list.Head()\n\n // 3. Update the list's head as the new node\n list.head = newNode\n\n // 4. Increment the list size\n list.size++\n}", "func (db *MemoryCache) NewIteratorWithPrefix(prefix []byte) Iterator {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\tvar (\n\t\tpr = string(prefix)\n\t\tkeys = make([]string, 0, len(db.db))\n\t\tvalues = make([][]byte, 0, len(db.db))\n\t)\n\t// Collect the keys from the memory database corresponding to the given prefix\n\tfor key := range db.db {\n\t\tif strings.HasPrefix(key, pr) {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t}\n\t// Sort the items and retrieve the associated values\n\tsort.Strings(keys)\n\tfor _, key := range keys {\n\t\tvalues = append(values, db.db[key])\n\t}\n\treturn &iterator{\n\t\tkeys: keys,\n\t\tvalues: values,\n\t}\n}", "func NewPrefix(addrString string) (p Prefix, err error) {\n\t_, ipNet, err := net.ParseCIDR(addrString)\n\tif err != nil {\n\t\treturn\n\t}\n\tsz, _ := ipNet.Mask.Size()\n\tp = Prefix{ipNet, ipNet.IP.String(), sz}\n\n\treturn\n}", "func (addr DevAddr) WithPrefix(prefix DevAddrPrefix) (prefixed DevAddr) {\n\tk := uint(prefix.Length)\n\tfor i := 0; i < 4; i++ {\n\t\tif k >= 8 {\n\t\t\tprefixed[i] = prefix.DevAddr[i] & 0xff\n\t\t\tk -= 8\n\t\t\tcontinue\n\t\t}\n\t\tprefixed[i] = (prefix.DevAddr[i] & ^byte(0xff>>k)) | (addr[i] & byte(0xff>>k))\n\t\tk = 0\n\t}\n\treturn\n}", "func (defintion *IndexDefinition) AddPrefix(prefix string) (outDef *IndexDefinition) {\n\toutDef = defintion\n\toutDef.Prefix = append(outDef.Prefix, prefix)\n\treturn\n}", "func (creator *metricCreatorBase) AddOrGetPrefix(prefix string, labelNames []string, labelValues []string) MetricCreator {\n\tfullPrefix, allLabelNames, allLabelValues := creator.concatNameAndLabels(prefix, labelNames, labelValues)\n\n\tcreator.root.mapLock.Lock()\n\tdefer creator.root.mapLock.Unlock()\n\n\treturn &metricCreatorBase{\n\t\tfullPrefix: fullPrefix,\n\t\tfixedLabelNames: allLabelNames,\n\t\tfixedLabelValues: allLabelValues,\n\t\tlogger: creator.logger.WithFields(logger.Fields{\n\t\t\t\"prefix\": fullPrefix,\n\t\t\t\"labelNames\": labelNames,\n\t\t\t\"labelValues\": labelValues,\n\t\t}),\n\t\troot: creator.root,\n\t}\n}", "func NewPrefix(p string) *Prefix {\n\tif len(p) > 0 && p[0] == '_' {\n\t\tp = p[1:]\n\t}\n\tpp := Prefix(p)\n\treturn &pp\n}", "func (rad *Radix) Prefix(prefix string) *list.List {\n\trad.lock.Lock()\n\tdefer rad.lock.Unlock()\n\tl := list.New()\n\tn, _ := rad.root.lookup([]rune(prefix))\n\tif n == nil {\n\t\treturn l\n\t}\n\tn.addToList(l)\n\treturn l\n}", "func add_section_name(\npar int32,/* parent of new node */\nc int,/* right or left? */\nname[]rune,/* section name */\nispref bool/* are we adding a prefix or a full name? */)int32{\np:=int32(len(name_dir))/* new node */\nname_dir= append(name_dir,name_info{})\nname_dir[p].llink= -1\ninit_node(p)\nif ispref{\nname_dir= append(name_dir,name_info{})\nname_dir[p+1].llink= -1\ninit_node(p+1)\n}\nname_dir[p].ispref= ispref\nname_dir[p].name= append(name_dir[p].name,int32(len(name)))/* length of section name */\nname_dir[p].name= append(name_dir[p].name,name...)\nname_dir[p].llink= -1\nname_dir[p].rlink= -1\ninit_node(p)\nif par==-1{\nname_root= p\n}else{\nif c==less{\nname_dir[par].llink= p\n}else{\nname_dir[par].rlink= p\n}\n}\nreturn p\n}", "func (p *Periph) StorePREFIX(n int, prefix uint32) {\n\tp.prefix[n].Store(prefix)\n}", "func NewPrefix(v string) Value {\n\treturn prefixValue(v)\n}", "func (c Node) NamePrefix() string {\n\treturn fmt.Sprintf(\"bpm-%s-\", c.ID)\n}", "func (n *Node) HasPrefix(prefix string) (*Node, error) {\n\tletters := []rune(prefix)\n\tcurrent := n\n\tfor i := 0; current != nil && i < len(letters); i++ {\n\t\tcurrent = current.GetChild(letters[i])\n\t}\n\tif current == nil {\n\t\terr := fmt.Errorf(\"%s not found\", prefix)\n\t\treturn nil, err\n\t}\n\treturn current, nil\n}", "func (tbl RecordTable) WithPrefix(pfx string) RecordTable {\n\ttbl.name.Prefix = pfx\n\treturn tbl\n}", "func (tx *remoteTx) ForPrefix(bucket string, prefix []byte, walker func(k, v []byte) error) error {\n\tc, err := tx.Cursor(bucket)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Close()\n\n\tfor k, v, err := c.Seek(prefix); k != nil; k, v, err = c.Next() {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !bytes.HasPrefix(k, prefix) {\n\t\t\tbreak\n\t\t}\n\t\tif err := walker(k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (db *Database) NewIteratorWithPrefix(prefix []byte) database.Iterator {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\tswitch {\n\tcase db.db == nil:\n\t\treturn &nodb.Iterator{Err: database.ErrClosed}\n\tcase db.corrupted():\n\t\treturn &nodb.Iterator{Err: database.ErrAvoidCorruption}\n\t}\n\n\tit := db.db.NewIterator(db.iteratorOptions)\n\tif it == nil {\n\t\treturn &nodb.Iterator{Err: errFailedToCreateIterator}\n\t}\n\tit.Seek(prefix)\n\treturn &iterator{\n\t\tit: it,\n\t\tdb: db,\n\t\tprefix: prefix,\n\t}\n}", "func (ms *memoryStore) Add(prefix, base string) (*NameSpace, error) {\n\tns, err := ms.GetWithPrefix(prefix)\n\tif err != nil {\n\t\tif err != ErrNameSpaceNotFound {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif ns != nil {\n\t\terr = ns.AddBase(base)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn ns, nil\n\t}\n\n\tns, err = ms.GetWithBase(base)\n\tif err != nil {\n\t\tif err != ErrNameSpaceNotFound {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif ns != nil {\n\t\terr = ns.AddPrefix(prefix)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn ns, nil\n\n\t}\n\n\tns = &NameSpace{\n\t\tPrefix: prefix,\n\t\tBase: base,\n\t}\n\terr = ms.Set(ns)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ns, nil\n}", "func SpawnPrefix(props *Props, prefix string) *PID {\n\treturn EmptyRootContext.SpawnPrefix(props, prefix)\n}", "func (this *Trie) StartsWith(prefix string) bool {\n node := this.searchPrefix(prefix)\n \n return node != nil\n}", "func prefixIndex(addr uint8, prefixLen int) int {\n\t// the prefixIndex of addr/prefixLen is the prefixLen most significant bits\n\t// of addr, with a 1 tacked onto the left-hand side. For example:\n\t//\n\t// - 0/0 is 1: 0 bits of the addr, with a 1 tacked on\n\t// - 42/8 is 1_00101010 (298): all bits of 42, with a 1 tacked on\n\t// - 48/4 is 1_0011 (19): 4 most-significant bits of 48, with a 1 tacked on\n\treturn (int(addr) >> (8 - prefixLen)) + (1 << prefixLen)\n}", "func buildPrefixTree(byteFrequencies *dictionary.Dictionary) *huffmanTreeNode {\n\ttree := new(priorityqueue.PriorityQueue)\n\tkeys := byteFrequencies.Keys()\n\n\tfor i := 0; i < keys.Size(); i++ {\n\t\tbyt := keys.MustGet(i)\n\t\tfrequency, _ := byteFrequencies.Get(byt)\n\n\t\ttree.Enqueue(frequency.(int), &huffmanTreeNode{frequency: frequency.(int), value: byt.(byte)})\n\t}\n\n\tfor tree.Size() > 1 {\n\t\taPrio, a := tree.Dequeue()\n\t\tbPrio, b := tree.Dequeue()\n\n\t\tnewPrio := aPrio + bPrio\n\n\t\tnode := &huffmanTreeNode{frequency: newPrio, left: a.(*huffmanTreeNode), right: b.(*huffmanTreeNode)}\n\n\t\ttree.Enqueue(newPrio, node)\n\t}\n\n\t_, root := tree.Dequeue()\n\n\treturn root.(*huffmanTreeNode)\n}", "func (allc *Allocator) makeNode(truncatedSize uint32) uint32 {\n\t// Calculate the amount of actual memory required for this node.\n\t// Depending on the height of the node, size might be truncated.\n\tsize := defaultNodeSize - truncatedSize\n\t/*padding := size % cacheLineSize\n\tif padding < paddingLimit {\n\t\tsize += padding\n\t}*/\n\treturn allc.new(size)\n}", "func NewWithPrefix(pool *redis.Pool, prefix string) *RedisStore {\n\treturn &RedisStore{\n\t\tpool: pool,\n\t\tprefix: prefix,\n\t}\n}", "func (o InventoryDestinationBucketPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InventoryDestinationBucket) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func NewTree(prefix, delimiter string) *Node {\n\treturn &Node{\n\t\tname: prefix,\n\t\tdelimiter: delimiter,\n\t\tnodes: make(map[string]*Node),\n\t}\n}", "func ReserveHasPrefix(v string) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldReserve), v))\n\t})\n}", "func (ms *memoryStore) GetWithPrefix(prefix string) (*NameSpace, error) {\n\tms.RLock()\n\tdefer ms.RUnlock()\n\tns, ok := ms.prefix2base[prefix]\n\tif !ok {\n\t\treturn nil, ErrNameSpaceNotFound\n\t}\n\treturn ns, nil\n}", "func (tbl DbCompoundTable) WithPrefix(pfx string) DbCompoundTable {\n\ttbl.name.Prefix = pfx\n\treturn tbl\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tbytes := []byte(prefix)\n\tif len(bytes) <= 0 {\n\t\treturn true\n\t}\n\tfor _, value := range bytes {\n\t\t//如果数据存在\n\t\tif _, ok := this.nexts[value]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tthis = this.nexts[value]\n\t}\n\treturn true\n}", "func NewPrefixWriter(prefix string, writer types.ArchiveWriter) types.ArchiveWriter {\n\treturn &prefixWriter{\n\t\tprefix: prefix,\n\t\twriter: writer,\n\t}\n}", "func WithPrefix(value string) *Entry {\n\treturn NewDefaultEntry().WithField(\"prefix\", value)\n}", "func (pq *PrefixQueue) Enqueue(prefix, value []byte) (*Item, error) {\n\tpq.Lock()\n\tdefer pq.Unlock()\n\n\t// Check if queue is closed.\n\tif !pq.isOpen {\n\t\treturn nil, ErrDBClosed\n\t}\n\n\t// Get the queue for this prefix.\n\tq, err := pq.getOrCreateQueue(prefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create new Item.\n\titem := &Item{\n\t\tID: q.Tail + 1,\n\t\tKey: generateKeyPrefixID(prefix, q.Tail+1),\n\t\tValue: value,\n\t}\n\n\t// Add it to the queue.\n\tif err := pq.db.Put(item.Key, item.Value, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Increment tail position and prefix queue size.\n\tq.Tail++\n\tpq.size++\n\n\t// Save the queue.\n\tif err := pq.saveQueue(prefix, q); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Save main prefix queue data.\n\tif err := pq.save(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn item, nil\n}", "func newFileWithPrefix(t *testing.T, prefix, text string) (*os.File, error) {\n\ttmpFile, err := ioutil.TempFile(os.TempDir(), prefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt.Cleanup(func() {\n\t\tos.Remove(tmpFile.Name())\n\t})\n\n\tb := []byte(text)\n\t_, err = tmpFile.Write(b)\n\n\treturn tmpFile, err\n}", "func NewTokenHasPrefix(v string) predicate.User {\n\treturn predicate.User(sql.FieldHasPrefix(FieldNewToken, v))\n}", "func GenerateWithPrefix(size int, prefix string) string {\n\tsize = size - 1 - len(prefix)\n\n\trandom := prefix + randomString(size)\n\tcontrolDigit := strconv.Itoa(generateControlDigit(random))\n\n\treturn random + controlDigit\n}", "func generatePrefixed(prefix string, count *int64, found chan<- result, stop <-chan struct{}) {\n\tnotBefore := time.Now()\n\tnotAfter := time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC)\n\n\ttemplate := x509.Certificate{\n\t\tSerialNumber: new(big.Int).SetInt64(mr.Int63()),\n\t\tSubject: pkix.Name{\n\t\t\tCommonName: \"syncthing\",\n\t\t},\n\t\tNotBefore: notBefore,\n\t\tNotAfter: notAfter,\n\n\t\tKeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,\n\t\tExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},\n\t\tBasicConstraintsValid: true,\n\t}\n\n\tpriv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tderBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tid := protocol.NewDeviceID(derBytes)\n\t\tatomic.AddInt64(count, 1)\n\n\t\tif strings.HasPrefix(id.String(), prefix) {\n\t\t\tselect {\n\t\t\tcase found <- result{id, priv, derBytes}:\n\t\t\tcase <-stop:\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (p *Parser) registerPrefix(tokenType token.TokenType, fn prefixParseFn) {\n\tp.prefixParseFns[tokenType] = fn\n}", "func leading(length int) *xmlx.Node {\n\treturn newnode(xmlx.NT_TEXT, \"\", \"\\n\"+strings.Repeat(\"\\t\", length))\n}", "func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) {\n\tsearch := prefix\n\tfor {\n\t\t// Check for key exhaution\n\t\tif len(search) == 0 {\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t}\n\n\t\t// Look for an edge\n\t\t_, n = n.getEdge(search[0])\n\t\tif n == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Consume the search prefix\n\t\tif bytes.HasPrefix(search, n.prefix) {\n\t\t\tsearch = search[len(n.prefix):]\n\n\t\t} else if bytes.HasPrefix(n.prefix, search) {\n\t\t\t// Child may be under our search prefix\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (o InventoryDestinationBucketOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InventoryDestinationBucket) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (p *Parser) registerPrefix(tokenType token.TokenType, fn PrefixParseFn) {\n\tp.prefixParseFns[tokenType] = fn\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\n\tnode := this.searchPrefix(prefix)\n\tif node == nil {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func NewBranchWithPrefix(parent *Logger, prefix string) *Logger {\n\treturn &Logger{parent: parent, prefix: prefix}\n}", "func NewPrefixBucket(\n\tprefix string,\n\twrapped gcs.Bucket) (b gcs.Bucket, err error) {\n\tif !utf8.ValidString(prefix) {\n\t\terr = errors.New(\"prefix is not valid UTF-8\")\n\t\treturn\n\t}\n\n\tb = &prefixBucket{\n\t\tprefix: prefix,\n\t\twrapped: wrapped,\n\t}\n\n\treturn\n}", "func newPrefixDefinedWriter(writer prefixWriteCloser, prefixLen int) *prefixDefinedWriter {\n\tif prefixLen < 0 {\n\t\tpanic(fmt.Errorf(\"newPrefixDefinedWriter: invalid prefixLen %v\", prefixLen))\n\t}\n\tif writer == nil {\n\t\tpanic(fmt.Errorf(\"newPrefixDefinedWriter: nil writer\"))\n\t}\n\treturn &prefixDefinedWriter{\n\t\tprefixLen: prefixLen,\n\t\tprefix: make([]byte, 0, prefixLen),\n\t\tw: writer}\n}", "func (t *BPTree) startNewTree(key []byte, pointer *Record) error {\n\tt.root = t.newLeaf()\n\tt.root.Keys[0] = key\n\tt.root.pointers[0] = pointer\n\tt.root.KeysNum = 1\n\n\treturn nil\n}", "func (c *FileSystemCache) Prefix(p ...string) Cache {\n\tc.prefix = p\n\treturn c\n}", "func (t *Trie) FindWithPrefix(p string) (counts map[string]int) {\n\tcounts = make(map[string]int)\n\tcharIdx := p[0] - 'a'\n\tt.children[charIdx].findWithPrefix(p, &counts)\n\treturn\n}", "func (fps *FetcherProcessStream) SetPrefix(prefix string) *FetcherProcessStream {\n\tfps.prefix = prefix + \" \"\n\treturn fps\n}", "func (t *Trie) StartWith(prefix string) bool {\n\tcurr := t.Root\n\tfor _, char := range prefix {\n\t\tif _, ok := curr.Children[char]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tcurr = curr.Children[char]\n\t}\n\treturn true\n}", "func (p *Parser) registerPrefix(tokenType token.Type, fn prefixParseFn) {\n\tp.prefixParseFns[tokenType] = fn\n}", "func SetPrefix(p string) {\n\tprefix = p\n}", "func GraphPrefix() []byte {\n\treturn graphPrefix\n}", "func (t *BPTree) PrefixScan(prefix []byte, offsetNum int, limitNum int) (records Records, off int, err error) {\n\tvar (\n\t\tn *Node\n\t\tscanFlag bool\n\t\tkeys [][]byte\n\t\tpointers []interface{}\n\t\ti, j, numFound int\n\t)\n\n\tn = t.FindLeaf(prefix)\n\n\tif n == nil {\n\t\treturn nil, off, ErrPrefixScansNoResult\n\t}\n\n\tfor j = 0; j < n.KeysNum && compare(n.Keys[j], prefix) < 0; {\n\t\tj++\n\t}\n\n\tscanFlag = true\n\tnumFound = 0\n\n\tcoff := 0\n\n\tfor n != nil && scanFlag {\n\t\tfor i = j; i < n.KeysNum; i++ {\n\n\t\t\tif !bytes.HasPrefix(n.Keys[i], prefix) {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif coff < offsetNum {\n\t\t\t\tcoff++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, n.Keys[i])\n\t\t\tpointers = append(pointers, n.pointers[i])\n\t\t\tnumFound++\n\n\t\t\tif limitNum > 0 && numFound == limitNum {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tn, _ = n.pointers[order-1].(*Node)\n\t\tj = 0\n\t}\n\n\toff = coff\n\n\tesr, err := getRecordWrapper(numFound, keys, pointers)\n\treturn esr, off, err\n}", "func ParsePrefix(line string) *Prefix {\n\t// Start by creating an Prefix with nothing but the host\n\tid := &Prefix{\n\t\tName: line,\n\t}\n\n\tuh := strings.SplitN(id.Name, \"@\", 2)\n\tif len(uh) == 2 {\n\t\tid.Name, id.Host = uh[0], uh[1]\n\t}\n\n\tnu := strings.SplitN(id.Name, \"!\", 2)\n\tif len(nu) == 2 {\n\t\tid.Name, id.User = nu[0], nu[1]\n\t}\n\n\treturn id\n}", "func StartNewNode(\n\tconfig *Config,\n\tinitialNetworkState *pb.NetworkState,\n\tinitialCheckpointValue []byte,\n) (*Node, error) {\n\treturn RestartNode(\n\t\tconfig,\n\t\t&dummyWAL{\n\t\t\tinitialNetworkState: initialNetworkState,\n\t\t\tinitialCheckpointValue: initialCheckpointValue,\n\t\t},\n\t)\n}", "func (db *Database) NewIteratorWithPrefix(prefix []byte) database.Iterator {\n\treturn &iter{\n\t\tdb: db,\n\t\tIterator: db.DB.NewIterator(util.BytesPrefix(prefix), nil),\n\t}\n}", "func (s *IPSet) AddPrefix(p IPPrefix) { s.AddRange(p.Range()) }", "func (s *IPSet) AddPrefix(p IPPrefix) { s.AddRange(p.Range()) }", "func prefix(k string) *goraptor.Uri {\n\tvar pref string\n\trest := k\n\tif i := strings.Index(k, \":\"); i >= 0 {\n\t\tpref = k[:i+1]\n\t\trest = k[i+1:]\n\t}\n\tif long, ok := rdfPrefixes[pref]; ok {\n\t\tpref = long\n\t}\n\turi := goraptor.Uri(pref + rest)\n\treturn &uri\n}", "func (pars *Parser) parsePrefixExpression() tree.Expression {\n\texpression := &tree.PrefixExpression{\n\t\tToken: pars.thisToken,\n\t\tOperator: pars.thisToken.Val,\n\t}\n\n\tpars.nextToken()\n\n\texpression.Right = pars.parseExpression(PREFIX)\n\treturn expression\n}", "func (this *Trie) StartsWith(prefix string) bool {\n node := this.root\n for _, r := range prefix {\n child, existed := node.children[r]\n if !existed {\n return false\n }\n node = child\n }\n return true\n}", "func createNode(addr string, nodeStmts map[string]ast.Stmt) *ast.Node {\n\tnID := \"n\" + strings.Replace(addr, \".\", \"\", -1)\n\tnID = strings.Replace(nID, \":\", \"\", -1)\n\tn := &ast.Node{ID: nID}\n\tnodeStmts[n.ID] = &ast.NodeStmt{\n\t\tNode: n,\n\t\tAttrs: []*ast.Attr{\n\t\t\t{\n\t\t\t\tKey: \"label\",\n\t\t\t\tVal: fmt.Sprintf(`\"%s\"`, addr),\n\t\t\t},\n\t\t},\n\t}\n\treturn n\n}", "func (db *Database) NewIteratorWithStartAndPrefix(start, prefix []byte) database.Iterator {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\tswitch {\n\tcase db.db == nil:\n\t\treturn &nodb.Iterator{Err: database.ErrClosed}\n\tcase db.corrupted():\n\t\treturn &nodb.Iterator{Err: database.ErrAvoidCorruption}\n\t}\n\n\tit := db.db.NewIterator(db.iteratorOptions)\n\tif it == nil {\n\t\treturn &nodb.Iterator{Err: errFailedToCreateIterator}\n\t}\n\tif bytes.Compare(start, prefix) == 1 {\n\t\tit.Seek(start)\n\t} else {\n\t\tit.Seek(prefix)\n\t}\n\treturn &iterator{\n\t\tit: it,\n\t\tdb: db,\n\t\tprefix: prefix,\n\t}\n}", "func ParsePrefix(cursor *bufio.Reader) string {\n\tvar buffer string\n\tfor {\n\t\tnextc, _, err := cursor.ReadRune()\n\t\tif strings.ContainsRune(\" \", nextc) {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog.Fatal(\"Error parsing prefix \", err)\n\t\t}\n\t\tbuffer += string(nextc)\n\t}\n\t//fmt.Printf(\"Prefix:\\t\\t%s \\n\", buffer)\n\treturn buffer\n}", "func Prefix(p string) Option {\n\treturn func(s *storage) {\n\t\ts.prefix = p\n\t}\n}", "func (g *Group) WithPrefix(prefix string) *Group {\n\tg.prefix = prefix\n\treturn g\n}", "func (p *Parser) registerPrefix(typ token.Type, fn parsePrefixFn) {\n\tp.prefixParsers[typ] = fn\n}", "func prefixLoad(db *gorocksdb.DB, prefix string) ([]string, []string, error) {\n\tif db == nil {\n\t\treturn nil, nil, errors.New(\"Rocksdb instance is nil when do prefixLoad\")\n\t}\n\treadOpts := gorocksdb.NewDefaultReadOptions()\n\tdefer readOpts.Destroy()\n\treadOpts.SetPrefixSameAsStart(true)\n\titer := db.NewIterator(readOpts)\n\tdefer iter.Close()\n\tkeys := make([]string, 0)\n\tvalues := make([]string, 0)\n\titer.Seek([]byte(prefix))\n\tfor ; iter.Valid(); iter.Next() {\n\t\tkey := iter.Key()\n\t\tvalue := iter.Value()\n\t\tkeys = append(keys, string(key.Data()))\n\t\tkey.Free()\n\t\tvalues = append(values, string(value.Data()))\n\t\tvalue.Free()\n\t}\n\treturn keys, values, nil\n}", "func SetPrefix(pre string) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tprefix = pre\n}", "func (o BucketV2ReplicationConfigurationRuleOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketV2ReplicationConfigurationRule) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tif prefix == \"\" {\n\t\treturn false\n\t}\n\thead := this\n\tfor e := range prefix {\n\t\tif head.data[prefix[e]-'a'] == nil {\n\t\t\treturn false\n\t\t}\n\t\thead = head.data[prefix[e]-'a']\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tnode := this\n\tn := len(prefix)\n\tfor i := 0; i < n; i++ {\n\t\tidx := prefix[i] - 'a'\n\t\tif node.sons[idx] == nil {\n\t\t\treturn false\n\t\t}\n\t\tnode = node.sons[idx]\n\t}\n\treturn true\n}", "func (o BucketReplicationConfigurationRuleOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigurationRule) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (p Printer) WithPrefix(prefix string) *Printer {\n\tnewPrefix := prefix\n\tif len(p.c) > 0 {\n\t\tnewPrefix = color.New(p.c...).Sprintf(newPrefix)\n\t}\n\tp.prefix = p.prefix + newPrefix\n\treturn &p\n}", "func (gobgp *GoBGP) LookupPrefix(\n\tctx context.Context,\n\tprefix string,\n) (*api.RoutesLookupResponse, error) {\n\treturn nil, fmt.Errorf(\"not implemented: LookupPrefix\")\n}", "func (this *Trie) StartsWith(prefix string) bool {\r\n\tstrbyte := []byte(prefix)\r\n\tcurroot := this\r\n\tfor _, char := range strbyte {\r\n\t\tcurroot = curroot.childs[char-'a']\r\n\t\tif curroot == nil {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}", "func compactPrefix() []byte { return []byte{0, 3, 0, 0} }", "func CreateDenomAddressPrefix(denom string) []byte {\n\t// we add a \"zero\" byte at the end - null byte terminator, to allow prefix denom prefix\n\t// scan. Setting it is not needed (key[last] = 0) - because this is the default.\n\tkey := make([]byte, len(DenomAddressPrefix)+len(denom)+1)\n\tcopy(key, DenomAddressPrefix)\n\tcopy(key[len(DenomAddressPrefix):], denom)\n\treturn key\n}", "func (t *Trie) StartsWith(prefix string) bool {\n\tp := t.root\n\twordArr := []rune(prefix)\n\n\tfor i := 0; i < len(wordArr); i++ {\n\t\tif p.edges[wordArr[i]-'a'] == nil {\n\t\t\treturn false\n\t\t} else {\n\t\t\tp = p.edges[wordArr[i]-'a']\n\t\t}\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tif len(prefix) == 0 {\n\t\treturn true\n\t}\n\tfor _, e := range this.edges {\n\t\tif e.char == prefix[0] {\n\t\t\treturn e.next.StartsWith(prefix[1:])\n\t\t}\n\t}\n\treturn false\n}", "func resourceNetboxIpamPrefixRead(d *schema.ResourceData, meta interface{}) error {\n\tnetboxClient := meta.(*ProviderNetboxClient).client\n\n\tid := int64(d.Get(\"prefix_id\").(int))\n\n\tvar readParams = ipam.NewIPAMPrefixesReadParams().WithID(id)\n\n\treadResult, err := netboxClient.IPAM.IPAMPrefixesRead(readParams, nil)\n\n\tif err != nil {\n\t\tlog.Debugf(\"Error fetching Prefix ID # %d from Netbox = %v\", id, err)\n\t\treturn err\n\t}\n\n\tvar vrfID int64\n\tif readResult.Payload.Vrf != nil {\n\t\tvrfID = readResult.Payload.Vrf.ID\n\t}\n\n\td.Set(\"prefix\", readResult.Payload.Prefix)\n\td.Set(\"description\", readResult.Payload.Description)\n\td.Set(\"vrf_id\", vrfID)\n\td.Set(\"is_pool\", readResult.Payload.IsPool)\n\n\tvar tenantID int64\n\tif readResult.Payload.Tenant != nil {\n\t\ttenantID = readResult.Payload.Tenant.ID\n\t}\n\td.Set(\"tenant_id\", tenantID)\n\n\treturn nil\n}", "func (o BucketReplicationConfigRuleFilterAndPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketReplicationConfigRuleFilterAnd) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func (p *Parser) parsePrefixExpression() ast.Expression {\n\texpression := &ast.PrefixExpression{\n\t\tToken: p.curToken,\n\t\tOperator: p.curToken.Literal}\n\tp.nextToken()\n\texpression.Right = p.parseExpression(PREFIX)\n\treturn expression\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tif prefix == \"\" {\n\t\treturn true\n\t}\n\tif this == nil {\n\t\treturn false\n\t}\n\tindex := ([]byte(prefix[0:1]))[0] - byte('a')\n\tif this.child[index] == nil {\n\t\treturn false\n\t}\n\tif prefix[1:] == \"\" {\n\t\treturn true\n\t}\n\treturn this.child[index].StartsWith(prefix[1:])\n\n}", "func NewPrefixWriter(out io.Writer) PrefixWriter {\n\treturn &prefixWriter{out: out}\n}", "func SetPrefix(prefix string) { std.SetPrefix(prefix) }", "func resourceNetboxIpamPrefixUpdate(d *schema.ResourceData, meta interface{}) error {\n\tnetboxClient := meta.(*ProviderNetboxClient).client\n\n\tid := int64(d.Get(\"prefix_id\").(int))\n\n\tprefix := d.Get(\"prefix\").(string)\n\tdescription := d.Get(\"description\").(string)\n\tvrfID := int64(d.Get(\"vrf_id\").(int))\n\tisPool := d.Get(\"is_pool\").(bool)\n\t//status := d.Get(\"status\").(string)\n\ttenantID := int64(d.Get(\"tenant_id\").(int))\n\n\tvar parm = ipam.NewIPAMPrefixesUpdateParams().\n\t\tWithID(id).\n\t\tWithData(\n\t\t\t&models.PrefixCreateUpdate{\n\t\t\t\tPrefix: &prefix,\n\t\t\t\tDescription: description,\n\t\t\t\tIsPool: isPool,\n\t\t\t\tTags: []string{},\n\t\t\t\tVrf: vrfID,\n\t\t\t\tTenant: tenantID,\n\t\t\t},\n\t\t)\n\n\tlog.Debugf(\"Executing IPAMPrefixesUpdate against Netbox: %v\", parm)\n\n\tout, err := netboxClient.IPAM.IPAMPrefixesUpdate(parm, nil)\n\n\tif err != nil {\n\t\tlog.Debugf(\"Failed to execute IPAMPrefixesUpdate: %v\", err)\n\n\t\treturn err\n\t}\n\n\tlog.Debugf(\"Done Executing IPAMPrefixesUpdate: %v\", out)\n\n\treturn nil\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tnode := this\n\tfor _, v := range prefix {\n\t\tif node = node.next[v-'a']; node == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (o *SignalPersonName) SetPrefix(v string) {\n\to.Prefix.Set(&v)\n}", "func (g *Graph) AppendNode(content []byte, predecessors ...ObjectID) (*Object, error) {\n\tvar buf = make([]byte, 0)\n\n\tfor _, predecessor := range predecessors {\n\t\tbuf = append(buf, predecessor[:]...)\n\t}\n\tbuf = append(buf, content...)\n\n\th := ObjectID{}\n\t// Compute a 64-byte hash of buf and put it in h.\n\tsha3.ShakeSum128(h[:], buf)\n\tvar obj = Object{}\n\tobj.ID = h\n\tobj.Content = content\n\tobj.PredecessorIDs = append([]ObjectID{}, predecessors...)\n\n\tg.ObjectAdapter.WriteObject(obj)\n\n\treturn &obj, nil\n}" ]
[ "0.6869773", "0.59520763", "0.56966764", "0.56332743", "0.5543914", "0.5521665", "0.5477629", "0.54177904", "0.5407354", "0.5355928", "0.5346138", "0.5242986", "0.5131678", "0.51244336", "0.51227385", "0.5112621", "0.51077956", "0.50852245", "0.50659835", "0.5065695", "0.50561976", "0.5044929", "0.50395495", "0.5038937", "0.50284374", "0.5024761", "0.50207394", "0.49970347", "0.49963707", "0.49641263", "0.49630398", "0.49630398", "0.49595848", "0.49590218", "0.4952112", "0.49404186", "0.49254477", "0.49226916", "0.4922675", "0.49076456", "0.4906556", "0.49034226", "0.48987782", "0.4893849", "0.48707917", "0.48660982", "0.48647225", "0.48596814", "0.48573878", "0.4855522", "0.4847873", "0.4846317", "0.4837128", "0.48242348", "0.48202607", "0.4814333", "0.4808552", "0.48058063", "0.48041812", "0.47996294", "0.4793638", "0.4790428", "0.47881734", "0.47862297", "0.47855252", "0.47833958", "0.4781115", "0.4781115", "0.47772905", "0.47757426", "0.47718817", "0.4756971", "0.47507554", "0.47496453", "0.47477597", "0.47443882", "0.4739656", "0.47381493", "0.47372523", "0.47217092", "0.46964663", "0.46946496", "0.4692682", "0.46781087", "0.4674948", "0.46693975", "0.46678934", "0.46676993", "0.46626127", "0.46602848", "0.46595386", "0.46595246", "0.46590912", "0.465567", "0.46548498", "0.46543857", "0.46517915", "0.4651649", "0.46494395", "0.46392244" ]
0.8430526
0
GetAllocator reserves an allocator used for bulk Lookup/Update/Delete operations.
func (idx *Tree) GetAllocator() *Allocator { return idx.allocators[idx.allocatorQueue.get()] }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetRuntimePortAllocator() (*RuntimePortAllocator, error) {\n\tif rpa.pa == nil {\n\t\tif err := rpa.createAndRestorePortAllocator(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn rpa, nil\n}", "func NewAllocator(provider lCoreProvider) *Allocator {\n\treturn &Allocator{\n\t\tConfig: make(AllocConfig),\n\t\tprovider: provider,\n\t}\n}", "func NewAllocator(\n\tctx context.Context, acc *mon.BoundAccount, factory coldata.ColumnFactory,\n) *Allocator {\n\treturn &Allocator{\n\t\tctx: ctx,\n\t\tacc: acc,\n\t\tfactory: factory,\n\t}\n}", "func NewAllocator(round uint64) Allocator {\n\ta := &allocator{round: round}\n\treturn a\n}", "func NewAllocator() *Allocator {\n\tvar allocator Allocator\n\tallocator.A = C.zj_NewAllocator()\n\treturn &allocator\n}", "func (a *ResourceAllocator) allocator() memory.Allocator {\n\tif a.Allocator == nil {\n\t\treturn DefaultAllocator\n\t}\n\treturn a.Allocator\n}", "func Allocator() pageframe.Allocator {\n\treturn &_buddyAllocator\n}", "func (t *tableCommon) Allocator(ctx sessionctx.Context) autoid.Allocator {\n\ttrace_util_0.Count(_tables_00000, 322)\n\tif ctx != nil {\n\t\ttrace_util_0.Count(_tables_00000, 324)\n\t\tsessAlloc := ctx.GetSessionVars().IDAllocator\n\t\tif sessAlloc != nil {\n\t\t\ttrace_util_0.Count(_tables_00000, 325)\n\t\t\treturn sessAlloc\n\t\t}\n\t}\n\ttrace_util_0.Count(_tables_00000, 323)\n\treturn t.alloc\n}", "func newAllocator() *allocator {\n\ta := new(allocator)\n\ta.base.Init()\n\treturn a\n}", "func (alloc *inMemoryAllocator) GetType() AllocatorType {\n\treturn alloc.allocType\n}", "func (p *ResourcePool) Alloc(ctx context.Context, id string) (Alloc, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif alloc, ok := p.allocs[id]; ok {\n\t\treturn alloc, nil\n\t}\n\treturn nil, errors.E(\"alloc\", id, errors.NotExist)\n}", "func (idx *Tree) ReleaseAllocator(a *Allocator) {\n\tidx.allocatorQueue.put(a.id)\n}", "func NewPodAllocator(netInfo util.NetInfo, podLister listers.PodLister, kube kube.Interface) *PodAllocator {\n\tpodAnnotationAllocator := pod.NewPodAnnotationAllocator(\n\t\tnetInfo,\n\t\tpodLister,\n\t\tkube,\n\t)\n\n\tpodAllocator := &PodAllocator{\n\t\tnetInfo: netInfo,\n\t\treleasedPods: map[string]sets.Set[string]{},\n\t\treleasedPodsMutex: sync.Mutex{},\n\t\tpodAnnotationAllocator: podAnnotationAllocator,\n\t}\n\n\t// this network might not have IPAM, we will just allocate MAC addresses\n\tif util.DoesNetworkRequireIPAM(netInfo) {\n\t\tpodAllocator.ipAllocator = subnet.NewAllocator()\n\t}\n\n\treturn podAllocator\n}", "func (m *Manager) GetAllocation(fiveTuple *FiveTuple) *Allocation {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn m.allocations[fiveTuple.Fingerprint()]\n}", "func (allocator *Allocator) ReleaseAllocator() {\n\tC.zj_AllocatorRelease(allocator.A)\n}", "func NewUsegAllocator() (Inf, error) {\n\tallocator := &Allocator{\n\t\thostMgrs: make(map[string]usegvlanmgr.Inf),\n\t}\n\terr := allocator.newPGVlanAllocator()\n\treturn allocator, err\n}", "func NewDeviceAllocator() DeviceAllocator {\n\tpossibleDevices := make(map[mountDevice]int)\n\tfor _, firstChar := range []rune{'b', 'c'} {\n\t\tfor i := 'a'; i <= 'z'; i++ {\n\t\t\tdev := mountDevice([]rune{firstChar, i})\n\t\t\tpossibleDevices[dev] = 0\n\t\t}\n\t}\n\treturn &deviceAllocator{\n\t\tpossibleDevices: possibleDevices,\n\t\tcounter: 0,\n\t}\n}", "func (m *Manager) GetAllocation(fiveTuple *FiveTuple) *Allocation {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tfor _, a := range m.allocations {\n\t\tif a.fiveTuple.Equal(fiveTuple) {\n\t\t\treturn a\n\t\t}\n\t}\n\treturn nil\n}", "func (vt *perfSchemaTable) Allocator(ctx sessionctx.Context) autoid.Allocator {\n\treturn nil\n}", "func (sc *schedulerCache) addQuotaAllocator(quotaAllocator *arbv1.QuotaAllocator) error {\n\tif _, ok := sc.quotaAllocators[quotaAllocator.Name]; ok {\n\t\treturn fmt.Errorf(\"quotaAllocator %v exist\", quotaAllocator.Name)\n\t}\n\n\tinfo := &QuotaAllocatorInfo{\n\t\tname: quotaAllocator.Name,\n\t\tquotaAllocator: quotaAllocator.DeepCopy(),\n\t\tPods: make([]*v1.Pod, 0),\n\t}\n\n\t// init Request if it is nil\n\tif info.QuotaAllocator().Spec.Request.Resources == nil {\n\t\tinfo.QuotaAllocator().Spec.Request.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\n\t// init Deserved/Allocated/Used/Preemping if it is nil\n\tif info.QuotaAllocator().Status.Deserved.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Deserved.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Allocated.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Allocated.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Used.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Used.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Preempting.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Preempting.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tsc.quotaAllocators[quotaAllocator.Name] = info\n\treturn nil\n}", "func newAllocator(size uint32) *Allocator {\n\t// Set initial offset as 1 since 0 is used for nil pointers.\n\treturn &Allocator{make([]byte, size), initialAllocatorOffset}\n}", "func NewGlobalTSOAllocator(\n\tam *AllocatorManager,\n\tleadership *election.Leadership,\n) Allocator {\n\tgta := &GlobalTSOAllocator{\n\t\tallocatorManager: am,\n\t\tleadership: leadership,\n\t\ttimestampOracle: &timestampOracle{\n\t\t\tclient: leadership.GetClient(),\n\t\t\trootPath: am.rootPath,\n\t\t\tsaveInterval: am.saveInterval,\n\t\t\tupdatePhysicalInterval: am.updatePhysicalInterval,\n\t\t\tmaxResetTSGap: am.maxResetTSGap,\n\t\t\tdcLocation: GlobalDCLocation,\n\t\t\ttsoMux: &tsoObject{},\n\t\t},\n\t}\n\treturn gta\n}", "func (d *Distro) GetResolvedHostAllocatorSettings(s *evergreen.Settings) (HostAllocatorSettings, error) {\n\tconfig := s.Scheduler\n\thas := d.HostAllocatorSettings\n\tresolved := HostAllocatorSettings{\n\t\tVersion: has.Version,\n\t\tMinimumHosts: has.MinimumHosts,\n\t\tMaximumHosts: has.MaximumHosts,\n\t\tAcceptableHostIdleTime: has.AcceptableHostIdleTime,\n\t}\n\n\tcatcher := grip.NewBasicCatcher()\n\tcatcher.Add(config.ValidateAndDefault())\n\n\tif resolved.Version == \"\" {\n\t\tresolved.Version = config.HostAllocator\n\t}\n\tif !util.StringSliceContains(evergreen.ValidHostAllocators, resolved.Version) {\n\t\tcatcher.Errorf(\"'%s' is not a valid HostAllocationSettings.Version\", resolved.Version)\n\t}\n\tif resolved.AcceptableHostIdleTime == 0 {\n\t\tresolved.AcceptableHostIdleTime = time.Duration(config.AcceptableHostIdleTimeSeconds) * time.Second\n\t}\n\tif catcher.HasErrors() {\n\t\treturn HostAllocatorSettings{}, errors.Wrapf(catcher.Resolve(), \"cannot resolve HostAllocatorSettings for distro '%s'\", d.Id)\n\t}\n\n\td.HostAllocatorSettings = resolved\n\treturn resolved, nil\n}", "func (la *Allocator) Alloc(role string, socket eal.NumaSocket) (lc eal.LCore) {\n\tlist := la.Request(AllocRequest{Role: role, Socket: socket})\n\tif len(list) == 0 {\n\t\treturn eal.LCore{}\n\t}\n\treturn list[0]\n}", "func (r *Registry) Alloc(name string, addr ...string) (uint16, error) {\n\n\tr.Lock()\n\tdefer r.Unlock()\n\n\t_, name_taken := r.byname[name]\n\n\tif name_taken {\n\t\treturn 0, fmt.Errorf(\"Name %q is already taken\", name)\n\t}\n\n\tport, err := r.portFind()\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tr.createSvc(port, name, addr...)\n\n\treturn port, nil\n}", "func GetAllocation(f *agonesv1.Fleet) *allocationv1.GameServerAllocation {\n\t// get an allocation\n\treturn &allocationv1.GameServerAllocation{\n\t\tSpec: allocationv1.GameServerAllocationSpec{\n\t\t\tSelectors: []allocationv1.GameServerSelector{\n\t\t\t\t{LabelSelector: metav1.LabelSelector{MatchLabels: map[string]string{agonesv1.FleetNameLabel: f.ObjectMeta.Name}}},\n\t\t\t},\n\t\t}}\n}", "func (sc *schedulerCache) updateQuotaAllocator(oldQuotaAllocator, newQuotaAllocator *arbv1.QuotaAllocator) error {\n\tif err := sc.deleteQuotaAllocator(oldQuotaAllocator); err != nil {\n\t\treturn err\n\t}\n\tsc.addQuotaAllocator(newQuotaAllocator)\n\treturn nil\n}", "func Search(params SearchParams) (*models.AllocatorOverview, error) {\n\tif err := params.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := params.API.V1API.PlatformInfrastructure.SearchAllocators(\n\t\tplatform_infrastructure.NewSearchAllocatorsParams().\n\t\t\tWithContext(api.WithRegion(context.Background(), params.Region)).\n\t\t\tWithBody(&params.Request),\n\t\tparams.AuthWriter,\n\t)\n\tif err != nil {\n\t\treturn nil, apierror.Wrap(err)\n\t}\n\treturn res.Payload, nil\n}", "func GetMgrPlacement(p PlacementSpec) Placement {\n\treturn p.All().Merge(p[KeyMgr])\n}", "func NewGlobalTSOAllocator(leadership *election.Leadership, rootPath string, saveInterval time.Duration, maxResetTSGap func() time.Duration) Allocator {\n\treturn &GlobalTSOAllocator{\n\t\tleadership: leadership,\n\t\ttimestampOracle: &timestampOracle{\n\t\t\tclient: leadership.GetClient(),\n\t\t\trootPath: rootPath,\n\t\t\tsaveInterval: saveInterval,\n\t\t\tmaxResetTSGap: maxResetTSGap,\n\t\t},\n\t}\n}", "func (rs *resourceServer) GetPreferredAllocation(ctx context.Context,\n\trequest *pluginapi.PreferredAllocationRequest) (*pluginapi.PreferredAllocationResponse, error) {\n\treturn &pluginapi.PreferredAllocationResponse{}, nil\n}", "func GetGangAllocation(gang *resmgrsvc.Gang) *Allocation {\n\tgangAllocation := initializeZeroAlloc()\n\n\tfor _, t := range gang.GetTasks() {\n\t\tgangAllocation = gangAllocation.Add(GetTaskAllocation(t))\n\t}\n\treturn gangAllocation\n}", "func (s *stateManager) Get(id uuid.UUID) (*Allocation, error) {\n\n\tctx, cancel := context.WithTimeout(context.Background(), s.requestTimeout)\n\tdefer cancel()\n\n\tgr, err := s.kv.Get(ctx, fmt.Sprintf(\"%s/allocations/%s\", etcdPrefix, id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif gr.Count == 0 {\n\t\treturn nil, fmt.Errorf(\"No allocation for D %s\", id.String())\n\t}\n\treturn decode(gr.Kvs[0].Value)\n}", "func NewIPAMPoolAllocator(\n\tname string,\n\tstartRange uint32,\n\tendRange uint32,\n\tnetworkStr string) *PoolAllocatorType {\n\n\tvar nextInRange uint32\n\n\tip, n, err := net.ParseCIDR(networkStr)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tnumBitsInMask, _ := n.Mask.Size()\n\n\t// example: /24 is 8 bits so need 2**8 for the bitmap\n\tif startRange == 0 {\n\t\tstartRange = 1 // start at 1 not zero\n\t\tnextInRange = 1\n\t} else {\n\t\tnextInRange = startRange\n\n\t}\n\tif endRange == 0 {\n\t\tendRange = (1 << uint32(32-numBitsInMask)) - 2 // example: 8 bits: 256 - 1 - 1 = 254\n\t}\n\n\ttotalInRange := endRange - startRange + 1\n\n\tif len(ip.To4()) == net.IPv4len {\n\n\t\tpoolAllocator := &PoolAllocatorType{\n\t\t\tName: name,\n\t\t\tStartRange: startRange,\n\t\t\tEndRange: endRange,\n\t\t\tNextInRange: nextInRange,\n\t\t\tTotalInRange: totalInRange,\n\t\t\tNetwork: networkStr,\n\t\t\tipNetworku32: uint32(n.IP[0])<<24 | uint32(n.IP[1])<<16 | uint32(n.IP[2])<<8 | uint32(n.IP[3]),\n\t\t\tipMasku32: uint32(n.Mask[0])<<24 | uint32(n.Mask[1])<<16 | uint32(n.Mask[2])<<8 | uint32(n.Mask[3]),\n\t\t\tnumBitsInMask: numBitsInMask,\n\t\t\tipNetwork: n,\n\t\t\tAllocated: make(map[uint32]struct{}),\n\t\t}\n\t\tfmt.Printf(\"NewIPAMPoolAllocator: %v\\n\", poolAllocator)\n\n\t\treturn poolAllocator\n\t}\n\n\treturn nil\n}", "func NewAllocator(f File) (*Allocator, error) {\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ta := &Allocator{\n\t\tbufp: buffer.CGet(int(szFile - oFileSkip)),\n\t\tf: f,\n\t\tfsize: fi.Size(),\n\t}\n\ta.buf = *a.bufp\n\tfor i := range a.cap {\n\t\ta.cap[i] = int(pageAvail) / (1 << uint(i+4))\n\t}\n\n\tswitch {\n\tcase a.fsize <= oFileSkip:\n\t\tif _, err := f.WriteAt(a.buf, oFileSkip); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\tif n, err := f.ReadAt(a.buf, oFileSkip); n != len(a.buf) {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmax := a.fsize - szPage\n\t\tfor i := range a.pages {\n\t\t\tif a.pages[i], err = a.check(read(a.buf[int(oFilePages-oFileSkip)+8*i:]), 0, max); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tfor i := range a.slots {\n\t\t\tif a.slots[i], err = a.check(read(a.buf[int(oFileSlots-oFileSkip)+8*i:]), 0, max); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn a, nil\n}", "func NewIDAllocator(name string, maxIds int) (Allocator, error) {\n\tidBitmap := bitmapallocator.NewRoundRobinAllocationMap(maxIds, name)\n\n\treturn &idAllocator{\n\t\tnameIdMap: sync.Map{},\n\t\tidBitmap: idBitmap,\n\t}, nil\n}", "func (alloc *RuntimePortAllocator) createAndRestorePortAllocator() (err error) {\n\talloc.pa, err = portallocator.NewPortAllocatorCustom(*alloc.pr, func(max int, rangeSpec string) (allocator.Interface, error) {\n\t\treturn allocator.NewAllocationMap(max, rangeSpec), nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tports, err := alloc.getReservedPorts(alloc.client)\n\tif err != nil {\n\t\treturn err\n\t}\n\talloc.log.Info(\"Found reserved ports\", \"ports\", ports)\n\n\tfor _, port := range ports {\n\t\tif err = alloc.pa.Allocate(port); err != nil {\n\t\t\talloc.log.Error(err, \"can't allocate reserved ports\", \"port\", port)\n\t\t}\n\t}\n\n\treturn nil\n}", "func InitAllocator(addr uint32) {\n\t// Warning: Lot of unsafe pointer usage and manipulation ahead.\n\t// This function basically initializes memory at given address, so that\n\t// _buddyAllocator, and it's members, point to this address.\n\n\t// create freeBuddiesList\n\tvar _freeBuddiesList *[MaxOrder + 1]freeBuddiesList\n\t_freeBuddiesList = (*[MaxOrder + 1]freeBuddiesList)(pointer.Get(addr))\n\taddr += (MaxOrder + 1) * uint32(unsafe.Sizeof(freeBuddiesList{}))\n\n\t// set freeBuddiesList in buddyAllocator\n\t_buddyAllocator.buddies = (*_freeBuddiesList)[:MaxOrder+1]\n\n\t// create bigPagesBitmap\n\t// _nBigPages size for array is way more than needed. this is done since\n\t// array sizes need to be constant.\n\tvar _bigPagesBitmap *[_nBigPages]uint32\n\t_bigPagesBitmap = (*[_nBigPages]uint32)(pointer.Get(addr))\n\taddr += nMaps(_nBigPages) * 4\n\n\t// set bigPagesBitmap in buddyAllocator\n\t_buddyAllocator.buddies[MaxOrder].freeMap.maps = (*_bigPagesBitmap)[:nMaps(_nBigPages)]\n\n\t// mark all big pages as free\n\tfor i := uint32(0); i < nMaps(_nBigPages); i++ {\n\t\t_buddyAllocator.buddies[MaxOrder].freeMap.maps[i] = _allSet\n\t}\n\n\t// create the individual freeBuddiesList\n\tfor i := 0; i < MaxOrder; i++ {\n\t\t// maxOrder - 1 pages of order i, further divide by 2 since we use 1 bit\n\t\t// for buddy pair.\n\t\tvar nBuddies uint32 = _nBigPages * (1 << uint32(MaxOrder-i-1))\n\t\tnMaps := nMaps(nBuddies)\n\n\t\t// set address for this freeBuddiesList\n\t\t// we are addressing way more memory than needed, because array sizes need\n\t\t// to be constant. this will be more than enough for largest freeBuddiesList\n\t\tvar maps *[_nBigPages * _nBigPages]uint32\n\t\tmaps = (*[_nBigPages * _nBigPages]uint32)(pointer.Get(addr))\n\t\taddr += nMaps * 4\n\n\t\t// set the freeBuddiesList\n\t\t_buddyAllocator.buddies[i].freeMap.maps = (*maps)[:nMaps]\n\n\t\t// zero out the freeBuddiesList\n\t\tfor j := uint32(0); j < nMaps; j++ {\n\t\t\t_buddyAllocator.buddies[i].freeMap.maps[j] = 0\n\t\t}\n\t}\n\n\tinitNodePool(addr)\n}", "func (c *Config) TargetAllocatorImage() string {\n\treturn c.targetAllocatorImage\n}", "func NewMemifAllocator() *MemifAllocatorType {\n\n\tMemifAllocator := &MemifAllocatorType{\n\t\tMemifID: 0,\n\t}\n\n\treturn MemifAllocator\n}", "func (p *ResourcePool) Allocs(ctx context.Context) ([]Alloc, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tallocs := make([]Alloc, len(p.allocs))\n\ti := 0\n\tfor _, a := range p.allocs {\n\t\tallocs[i] = a\n\t\ti++\n\t}\n\treturn allocs, nil\n}", "func (p *staticPolicy) GetAllocatableCPUs(s state.State) cpuset.CPUSet {\n\treturn p.topology.CPUDetails.CPUs().Difference(p.reservedCPUs)\n}", "func GetTaskAllocation(rmTask *resmgr.Task) *Allocation {\n\talloc := initializeZeroAlloc()\n\n\ttaskResource := ConvertToResmgrResource(rmTask.Resource)\n\n\t// check if the task is non-preemptible\n\tif rmTask.GetPreemptible() {\n\t\talloc.Value[PreemptibleAllocation] = taskResource\n\t} else {\n\t\talloc.Value[NonPreemptibleAllocation] = taskResource\n\t}\n\n\t// check if its a controller task\n\tif rmTask.GetController() {\n\t\talloc.Value[ControllerAllocation] = taskResource\n\t}\n\n\tif rmTask.GetRevocable() {\n\t\talloc.Value[SlackAllocation] = taskResource\n\t} else {\n\t\talloc.Value[NonSlackAllocation] = taskResource\n\t}\n\n\t// every task account for total allocation\n\talloc.Value[TotalAllocation] = taskResource\n\n\treturn alloc\n}", "func Allocs(nomad *NomadServer) []Alloc {\n\tallocs := make([]Alloc, 0)\n\tdecodeJSON(url(nomad)+\"/v1/allocations\", &allocs)\n\treturn allocs\n}", "func (c *AgonesDiscoverAllocator) Allocate(ctx context.Context, req *pb.AssignTicketsRequest) error {\n\tlogger := runtime.Logger().WithField(\"component\", \"allocator\")\n\n\tfor _, assignmentGroup := range req.Assignments {\n\t\tif err := IsAssignmentGroupValidForAllocation(assignmentGroup); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfilter, err := extensions.ExtractFilterFromExtensions(assignmentGroup.Assignment.Extensions)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"the assignment does not have a valid filter extension\")\n\t\t}\n\n\t\tgameservers, err := c.ListGameServers(ctx, filter)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\tif len(gameservers) == 0 {\n\t\t\tlogger.Debugf(\"gameservers not found for request with filter %v\", filter.Map())\n\t\t\tcontinue\n\t\t}\n\n\t\t// NiceToHave: Filter GameServers by Capacity and Count\n\t\t// Remove not assigned tickets based on playersCapacity - Count\n\t\t// strategy: allTogether, CapacityBased FallBack\n\t\tfor _, gs := range gameservers {\n\t\t\tif HasCapacity(assignmentGroup, gs) {\n\t\t\t\tassignmentGroup.Assignment.Connection = gs.Status.Address\n\t\t\t\t//logger.Debugf(\"extension %v\", assignmentGroup.Assignment.Extensions)\n\t\t\t\tlogger.Infof(\"gameserver %s connection %s assigned to request, total tickets: %d\", gs.Name, assignmentGroup.Assignment.Connection, len(assignmentGroup.TicketIds))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m NoAllocs) GetAllocAccount() (v string, err quickfix.MessageRejectError) {\n\tvar f field.AllocAccountField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func SpaceMapAllocate() (* SpaceMap) {\n return &SpaceMap{}\n}", "func NewAlloc(startChunkSize int, slabSize int, growthFactor float64, malloc func(size int) []byte) *Alloc {\n\tc := new(Alloc)\n\tc.m = make(locker,1)\n\tc.arena = slab.NewArena(startChunkSize,slabSize,growthFactor,malloc)\n\tc.recycle = make(chan []byte,128)\n\treturn c\n}", "func (n *NoOpAllocator) Allocate(poolID types.PoolID, ip net.IP) error {\n\treturn errNotSupported\n}", "func (r *PortAllocator) AllocateNext() (int, error) {\n\toffset, ok, err := r.alloc.AllocateNext()\n\tif err != nil {\n\t\tr.metrics.incrementAllocationErrors(\"dynamic\")\n\t\treturn 0, err\n\t}\n\tif !ok {\n\t\tr.metrics.incrementAllocationErrors(\"dynamic\")\n\t\treturn 0, ErrFull\n\t}\n\n\t// update metrics\n\tr.metrics.incrementAllocations(\"dynamic\")\n\tr.metrics.setAllocated(r.Used())\n\tr.metrics.setAvailable(r.Free())\n\n\treturn r.portRange.Base + offset, nil\n}", "func New(pr net.PortRange, allocatorFactory allocator.AllocatorWithOffsetFactory) (*PortAllocator, error) {\n\tmax := pr.Size\n\trangeSpec := pr.String()\n\n\ta := &PortAllocator{\n\t\tportRange: pr,\n\t\tmetrics: &emptyMetricsRecorder{},\n\t}\n\n\tvar offset = 0\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ServiceNodePortStaticSubrange) {\n\t\toffset = calculateRangeOffset(pr)\n\t}\n\n\tvar err error\n\ta.alloc, err = allocatorFactory(max, rangeSpec, offset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn a, err\n}", "func (m *RdmaDevPlugin) Allocate(ctx context.Context, r *pluginapi.AllocateRequest) (*pluginapi.AllocateResponse, error) {\n\tlog.Println(\"allocate request:\", r)\n\n\tress := make([]*pluginapi.ContainerAllocateResponse, len(r.GetContainerRequests()))\n\n\tfor i := range r.GetContainerRequests() {\n\t\tress[i] = &pluginapi.ContainerAllocateResponse{\n\t\t\tDevices: m.deviceSpec,\n\t\t}\n\t}\n\n\tresponse := pluginapi.AllocateResponse{\n\t\tContainerResponses: ress,\n\t}\n\n\tlog.Println(\"allocate response: \", response)\n\treturn &response, nil\n}", "func (m *MemifAllocatorType) Allocate() uint32 {\n\n\tm.MemifID++\n\n\treturn m.MemifID\n}", "func (alloc *MockIDAllocator) Alloc() (uint64, error) {\n\treturn atomic.AddUint64(&alloc.base, 1), nil\n}", "func (a *ResourceAllocator) Allocate(size int) []byte {\n\tif a == nil {\n\t\treturn DefaultAllocator.Allocate(size)\n\t}\n\n\tif size < 0 {\n\t\tpanic(errors.New(codes.Internal, \"cannot allocate negative memory\"))\n\t} else if size == 0 {\n\t\treturn nil\n\t}\n\n\t// Account for the size requested.\n\tif err := a.count(size); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Allocate the amount of memory.\n\t// TODO(jsternberg): It's technically possible for this to allocate\n\t// more memory than we requested. How do we deal with that since we\n\t// likely want to use that feature?\n\talloc := a.allocator()\n\n\tbs := alloc.Allocate(size)\n\treturn bs\n}", "func (d Device) Alloc(extern External, size int64) (tensor.Memory, error) {\n\tif d == CPU {\n\t\tcudaLogf(\"device is CPU\")\n\t\treturn nil, nil // well there should be an error because this wouldn't be called\n\t}\n\n\tmachine := extern.(CUDAMachine)\n\tctxes := machine.Contexts()\n\tif len(ctxes) == 0 {\n\t\tcudaLogf(\"allocate nothing\")\n\t\treturn nil, nil\n\t}\n\tctx := ctxes[int(d)]\n\n\tcudaLogf(\"calling ctx.MemAlloc(%d)\", size)\n\treturn ctx.MemAlloc(size)\n}", "func (s *Flaky) Alloc() (kv.Entity, error) {\n\tif s.fail() {\n\t\treturn 0, s.err\n\t}\n\treturn s.Txn.Alloc()\n}", "func newIDAllocator(idKey proto.Key, db *client.DB, minID int64, blockSize int64,\n\tstopper *util.Stopper) (*idAllocator, error) {\n\tif minID <= allocationTrigger {\n\t\treturn nil, util.Errorf(\"minID must be > %d\", allocationTrigger)\n\t}\n\tif blockSize < 1 {\n\t\treturn nil, util.Errorf(\"blockSize must be a positive integer: %d\", blockSize)\n\t}\n\tia := &idAllocator{\n\t\tdb: db,\n\t\tminID: minID,\n\t\tblockSize: blockSize,\n\t\tids: make(chan int64, blockSize+blockSize/2+1),\n\t\tstopper: stopper,\n\t}\n\tia.idKey.Store(idKey)\n\tia.ids <- allocationTrigger\n\treturn ia, nil\n}", "func NewAllocation() *Allocation {\n\treturn initializeZeroAlloc()\n}", "func GetManager() *Manager {\n\treturn &mgr\n}", "func (q *Queue) GetResourceManager(systemname string) (ResourceManager, bool) {\n\tmanager, ok := q.managers.Get(systemname)\n\tif ok == true {\n\t\tmgrtype := manager.(ResourceManager)\n\t\treturn mgrtype, ok\n\t} else {\n\t\treturn nil, ok\n\t}\n}", "func (a *Allocation) GetByType(allocationType AllocationType) *Resources {\n\treturn a.Value[allocationType]\n}", "func NewIPAllocator(pendingIPRanges map[string]bool) *IPAllocator {\n\t// Make a copy of the pending IP ranges and set it in the IPAllocator so that the caller cannot mutate this map outside the library\n\tpendingIPRangesCopy := make(map[string]bool)\n\tfor pendingIPRange := range pendingIPRanges {\n\t\tpendingIPRangesCopy[pendingIPRange] = true\n\t}\n\treturn &IPAllocator{\n\t\tpendingIPRanges: pendingIPRangesCopy,\n\t}\n}", "func NewIPAllocator(pendingIPRanges map[string]bool) *IPAllocator {\n\t// Make a copy of the pending IP ranges and set it in the IPAllocator so that the caller cannot mutate this map outside the library\n\tpendingIPRangesCopy := make(map[string]bool)\n\tfor pendingIPRange := range pendingIPRanges {\n\t\tpendingIPRangesCopy[pendingIPRange] = true\n\t}\n\treturn &IPAllocator{\n\t\tpendingIPRanges: pendingIPRangesCopy,\n\t}\n}", "func (o *AllocationRequest) GetAllocation() AllocationAllocation {\n\tif o == nil || o.Allocation == nil {\n\t\tvar ret AllocationAllocation\n\t\treturn ret\n\t}\n\treturn *o.Allocation\n}", "func (c *Client) AllocID(ctx context.Context, req *pdpb.AllocIDReq) (*pdpb.AllocIDRsp, error) {\n\trsp, err := c.proxyRPC(ctx,\n\t\treq,\n\t\tfunc() {\n\t\t\treq.From = c.name\n\t\t\treq.ID = c.seq\n\t\t},\n\t\tfunc(cc context.Context) (interface{}, error) {\n\t\t\treturn c.pd.AllocID(cc, req, grpc.FailFast(true))\n\t\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rsp.(*pdpb.AllocIDRsp), nil\n}", "func FindAlloc(nomad *NomadServer, job *Job, host *Host) (*Alloc, error) {\n\tallocs := Allocs(nomad)\n\tfor _, alloc := range allocs {\n\t\tif alloc.NodeID == host.ID && strings.Contains(alloc.Name, job.Name) {\n\t\t\t// We may be looking at a stale allocation and a newer one exists\n\t\t\tif alloc.DesiredStatus == \"stop\" && len(allocs) > 1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn &alloc, nil\n\t\t}\n\t}\n\treturn &Alloc{}, &AllocNotFound{Hostname: host.Name, Jobname: job.Name}\n}", "func (na *cnmNetworkAllocator) Allocate(n *api.Network) error {\n\tif _, ok := na.networks[n.ID]; ok {\n\t\treturn fmt.Errorf(\"network %s already allocated\", n.ID)\n\t}\n\n\td, err := na.resolveDriver(n)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnw := &network{\n\t\tnw: n,\n\t\tendpoints: make(map[string]string),\n\t\tisNodeLocal: d.capability.DataScope == scope.Local,\n\t}\n\n\t// No swarm-level allocation can be provided by the network driver for\n\t// node-local networks. Only thing needed is populating the driver's name\n\t// in the driver's state.\n\tif nw.isNodeLocal {\n\t\tn.DriverState = &api.Driver{\n\t\t\tName: d.name,\n\t\t}\n\t\t// In order to support backward compatibility with older daemon\n\t\t// versions which assumes the network attachment to contains\n\t\t// non nil IPAM attribute, passing an empty object\n\t\tn.IPAM = &api.IPAMOptions{Driver: &api.Driver{}}\n\t} else {\n\t\tnw.pools, err = na.allocatePools(n)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed allocating pools and gateway IP for network %s\", n.ID)\n\t\t}\n\n\t\tif err := na.allocateDriverState(n); err != nil {\n\t\t\tna.freePools(n, nw.pools)\n\t\t\treturn errors.Wrapf(err, \"failed while allocating driver state for network %s\", n.ID)\n\t\t}\n\t}\n\n\tna.networks[n.ID] = nw\n\n\treturn nil\n}", "func GetManager() *Manager {\n\tif manager == nil {\n\t\tmanager = &Manager{\n\t\t\tProcesses: make(map[int64]*Process),\n\t\t}\n\t}\n\treturn manager\n}", "func (p *mockPolicy) GetAllocatableMemory(s state.State) []state.Block {\n\treturn []state.Block{}\n}", "func GetMgr() *Mgr {\n\treturn mgr\n}", "func GetManager() *Manager {\n\tmanagerMu.Lock()\n\tdefer managerMu.Unlock()\n\n\tif managerInstance == nil {\n\t\tmanagerInstance = NewManager(config.GetConfig().Sub(\"katago\"))\n\t}\n\treturn managerInstance\n}", "func (m *Manager) GetCompiler() *ast.Compiler {\n\tm.compilerMux.RLock()\n\tdefer m.compilerMux.RUnlock()\n\treturn m.compiler\n}", "func TestClientEndpoint_GetClientAllocs_WithoutMigrateTokens(t *testing.T) {\n\tt.Parallel()\n\tassert := assert.New(t)\n\n\ts1 := TestServer(t, nil)\n\tdefer s1.Shutdown()\n\tcodec := rpcClient(t, s1)\n\ttestutil.WaitForLeader(t, s1.RPC)\n\n\t// Create the register request\n\tnode := mock.Node()\n\treg := &structs.NodeRegisterRequest{\n\t\tNode: node,\n\t\tWriteRequest: structs.WriteRequest{Region: \"global\"},\n\t}\n\n\t// Fetch the response\n\tvar resp structs.GenericResponse\n\tif err := msgpackrpc.CallWithCodec(codec, \"Node.Register\", reg, &resp); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tnode.CreateIndex = resp.Index\n\tnode.ModifyIndex = resp.Index\n\n\t// Inject fake evaluations\n\tprevAlloc := mock.Alloc()\n\tprevAlloc.NodeID = node.ID\n\talloc := mock.Alloc()\n\talloc.NodeID = node.ID\n\talloc.PreviousAllocation = prevAlloc.ID\n\talloc.DesiredStatus = structs.AllocClientStatusComplete\n\tstate := s1.fsm.State()\n\tstate.UpsertJobSummary(99, mock.JobSummary(alloc.JobID))\n\terr := state.UpsertAllocs(100, []*structs.Allocation{prevAlloc, alloc})\n\tassert.Nil(err)\n\n\t// Lookup the allocs\n\tget := &structs.NodeSpecificRequest{\n\t\tNodeID: node.ID,\n\t\tSecretID: node.SecretID,\n\t\tQueryOptions: structs.QueryOptions{Region: \"global\"},\n\t}\n\tvar resp2 structs.NodeClientAllocsResponse\n\n\terr = msgpackrpc.CallWithCodec(codec, \"Node.GetClientAllocs\", get, &resp2)\n\tassert.Nil(err)\n\n\tassert.Equal(uint64(100), resp2.Index)\n\tassert.Equal(2, len(resp2.Allocs))\n\tassert.Equal(uint64(100), resp2.Allocs[alloc.ID])\n\tassert.Equal(0, len(resp2.MigrateTokens))\n}", "func (_Erc1820Registry *Erc1820RegistryCaller) GetManager(opts *bind.CallOpts, _addr common.Address) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Erc1820Registry.contract.Call(opts, &out, \"getManager\", _addr)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (s *Store) AllocatorDryRun(ctx context.Context, repl *Replica) (tracing.Recording, error) {\n\tctx, collect, cancel := tracing.ContextWithRecordingSpan(ctx, s.ClusterSettings().Tracer, \"allocator dry run\")\n\tdefer cancel()\n\tcanTransferLease := func(ctx context.Context, repl *Replica) bool { return true }\n\t_, err := s.replicateQueue.processOneChange(\n\t\tctx, repl, canTransferLease, true /* dryRun */)\n\tif err != nil {\n\t\tlog.Eventf(ctx, \"error simulating allocator on replica %s: %s\", repl, err)\n\t}\n\treturn collect(), nil\n}", "func (manager *Manager) GetGenerationManager() generation.Manager {\n\treturn manager.generatorManager\n}", "func (a *ResourceAllocator) Allocated() int64 {\n\treturn atomic.LoadInt64(&a.bytesAllocated)\n}", "func (c *Config) TargetAllocatorConfigMapEntry() string {\n\treturn c.targetAllocatorConfigMapEntry\n}", "func (vns *VirtualNetworkService) Allocate(ctx context.Context, vnBlueprint blueprint.Interface,\n\tcluster resources.Cluster) (*resources.VirtualNetwork, error) {\n\tclusterID, err := cluster.ID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblueprintText, err := vnBlueprint.Render()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresArr, err := vns.call(ctx, \"one.vn.allocate\", blueprintText, clusterID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vns.RetrieveInfo(ctx, int(resArr[resultIndex].ResultInt()))\n}", "func Alloc(addr, size uint64, allocType, protect int) *Memory {\n\tpanic(\"not implemented\")\n}", "func (sc *schedulerCache) deleteQuotaAllocator(quotaAllocator *arbv1.QuotaAllocator) error {\n\tif _, ok := sc.quotaAllocators[quotaAllocator.Name]; !ok {\n\t\treturn fmt.Errorf(\"quotaAllocator %v doesn't exist\", quotaAllocator.Name)\n\t}\n\tdelete(sc.quotaAllocators, quotaAllocator.Name)\n\treturn nil\n}", "func SetupRuntimePortAllocator(client client.Client, pr *net.PortRange, getReservedPorts func(client client.Client) (ports []int, err error)) {\n\trpa = &RuntimePortAllocator{client: client, pr: pr, getReservedPorts: getReservedPorts}\n\trpa.log = ctrl.Log.WithName(\"RuntimePortAllocator\")\n}", "func (c *Context) GetManager() (*Manager) {\n\tmutableMutex.Lock()\n mutableMutex.Unlock()\n\treturn c.Manager\n}", "func (p *spanSetBlockAlloc) alloc() *spanSetBlock {\n\tif s := (*spanSetBlock)(p.stack.pop()); s != nil {\n\t\treturn s\n\t}\n\treturn (*spanSetBlock)(persistentalloc(unsafe.Sizeof(spanSetBlock{}), cpu.CacheLineSize, &memstats.gcMiscSys))\n}", "func (c *FakeGameServerAllocations) Get(name string, options v1.GetOptions) (result *v1alpha1.GameServerAllocation, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewGetAction(gameserverallocationsResource, c.ns, name), &v1alpha1.GameServerAllocation{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1alpha1.GameServerAllocation), err\n}", "func (ia *idAllocator) Allocate() (int64, error) {\n\tfor {\n\t\tid := <-ia.ids\n\t\tif id == allocationTrigger {\n\t\t\tif !ia.stopper.StartTask() {\n\t\t\t\tif atomic.CompareAndSwapInt32(&ia.closed, 0, 1) {\n\t\t\t\t\tclose(ia.ids)\n\t\t\t\t}\n\t\t\t\treturn 0, util.Errorf(\"could not allocate ID; system is draining\")\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tia.allocateBlock(ia.blockSize)\n\t\t\t\tia.stopper.FinishTask()\n\t\t\t}()\n\t\t} else {\n\t\t\treturn id, nil\n\t\t}\n\t}\n}", "func (m *arenaManager) getArena(aid int) (*mmap.File, error) {\n\trelAid := aid - m.baseAid\n\tif relAid == len(m.arenas) {\n\t\tm.arenas = append(m.arenas, nil)\n\t}\n\taa := m.arenas[relAid]\n\tif aa != nil {\n\t\treturn aa, nil\n\t}\n\n\t// before we get a new arena into memory, we need to ensure that after fetching\n\t// a new arena into memory, we do not cross the provided memory limit.\n\tif err := m.ensureEnoughMem(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// now, get arena into memory\n\tif err := m.loadArena(aid); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn m.arenas[aid], nil\n}", "func (s *Store) AllocateRangeID(ctx context.Context) (roachpb.RangeID, error) {\n\tid, err := s.rangeIDAlloc.Allocate(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn roachpb.RangeID(id), nil\n}", "func (r *PortAllocator) Allocate(port int) error {\n\tok, offset := r.contains(port)\n\tif !ok {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(\"static\")\n\n\t\t// include valid port range in error\n\t\tvalidPorts := r.portRange.String()\n\t\treturn &ErrNotInRange{validPorts}\n\t}\n\n\tallocated, err := r.alloc.Allocate(offset)\n\tif err != nil {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(\"static\")\n\t\treturn err\n\t}\n\tif !allocated {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(\"static\")\n\t\treturn ErrAllocated\n\t}\n\n\t// update metrics\n\tr.metrics.incrementAllocations(\"static\")\n\tr.metrics.setAllocated(r.Used())\n\tr.metrics.setAvailable(r.Free())\n\n\treturn nil\n}", "func New() *AllocGrp {\n\tvar m AllocGrp\n\treturn &m\n}", "func (f *FS) AllocSector(typ DataType, miner address.Address, ssize abi.SectorSize, cache bool, num abi.SectorNumber) (SectorPath, error) {\n\t{\n\t\tspath, err := f.FindSector(typ, miner, num)\n\t\tif err == nil {\n\t\t\treturn spath, xerrors.Errorf(\"allocating sector %s: %m\", spath, ErrExists)\n\t\t}\n\t\tif err != ErrNotFound {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tneed := overheadMul[typ] * uint64(ssize)\n\n\tp, err := f.findBestPath(need, cache, false)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsp := p.Sector(typ, miner, num)\n\n\treturn sp, f.reserve(typ, sp.storage(), need)\n}", "func GetManager() *AppManager {\n\treturn &appMgr\n}", "func (cp *connPool) Allocate(\n\tcfg *config.SQL,\n\tresolver resolver.ServiceResolver,\n\tcreate func(cfg *config.SQL, resolver resolver.ServiceResolver) (*sqlx.DB, error),\n) (db *sqlx.DB, err error) {\n\tcp.mu.Lock()\n\tdefer cp.mu.Unlock()\n\n\tdsn, err := buildDSN(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif entry, ok := cp.pool[dsn]; ok {\n\t\tentry.refCount++\n\t\treturn entry.db, nil\n\t}\n\n\tdb, err = create(cfg, resolver)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcp.pool[dsn] = entry{db: db, refCount: 1}\n\n\treturn db, nil\n}", "func GetManager(ctx context.Context, env evergreen.Environment, mgrOpts ManagerOpts) (Manager, error) {\n\tvar provider Manager\n\n\tswitch mgrOpts.Provider {\n\tcase evergreen.ProviderNameEc2OnDemand:\n\t\tprovider = &ec2Manager{\n\t\t\tenv: env,\n\t\t\tEC2ManagerOptions: &EC2ManagerOptions{\n\t\t\t\tclient: &awsClientImpl{},\n\t\t\t\tregion: mgrOpts.Region,\n\t\t\t\tproviderKey: mgrOpts.ProviderKey,\n\t\t\t\tproviderSecret: mgrOpts.ProviderSecret,\n\t\t\t},\n\t\t}\n\tcase evergreen.ProviderNameEc2Fleet:\n\t\tprovider = &ec2FleetManager{\n\t\t\tenv: env,\n\t\t\tEC2FleetManagerOptions: &EC2FleetManagerOptions{\n\t\t\t\tclient: &awsClientImpl{},\n\t\t\t\tregion: mgrOpts.Region,\n\t\t\t\tproviderKey: mgrOpts.ProviderKey,\n\t\t\t\tproviderSecret: mgrOpts.ProviderSecret,\n\t\t\t},\n\t\t}\n\tcase evergreen.ProviderNameStatic:\n\t\tprovider = &staticManager{}\n\tcase evergreen.ProviderNameMock:\n\t\tprovider = makeMockManager()\n\tcase evergreen.ProviderNameDocker:\n\t\tprovider = &dockerManager{env: env}\n\tcase evergreen.ProviderNameDockerMock:\n\t\tprovider = &dockerManager{env: env, client: &dockerClientMock{}}\n\tcase evergreen.ProviderNameOpenstack:\n\t\tprovider = &openStackManager{}\n\tcase evergreen.ProviderNameGce:\n\t\tprovider = &gceManager{}\n\tcase evergreen.ProviderNameVsphere:\n\t\tprovider = &vsphereManager{}\n\tdefault:\n\t\treturn nil, errors.Errorf(\"no known provider '%s'\", mgrOpts.Provider)\n\t}\n\n\tif err := provider.Configure(ctx, env.Settings()); err != nil {\n\t\treturn nil, errors.Wrap(err, \"configuring cloud provider\")\n\t}\n\n\treturn provider, nil\n}", "func Convert_config_SecurityAllocator_To_v1_SecurityAllocator(in *config.SecurityAllocator, out *v1.SecurityAllocator, s conversion.Scope) error {\n\treturn autoConvert_config_SecurityAllocator_To_v1_SecurityAllocator(in, out, s)\n}", "func GetMgrResources(p rook.ResourceSpec) v1.ResourceRequirements {\n\treturn p[ResourcesKeyMgr]\n}", "func Alloc(size uintptr) Pointer {\n\treturn Pointer(allocator.Alloc(size))\n}", "func (o *V0037Node) GetAllocMemory() int64 {\n\tif o == nil || o.AllocMemory == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.AllocMemory\n}", "func GetTaskManager(provider string) (TaskManager, error) {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\tmgr, ok := taskMgrs[provider]\n\tif !ok {\n\t\treturn nil, ErrCloudNoProvider\n\t}\n\treturn mgr, nil\n}" ]
[ "0.68342525", "0.6720525", "0.67027986", "0.6658546", "0.66041344", "0.65315723", "0.6260463", "0.6200884", "0.613557", "0.60628927", "0.595554", "0.588803", "0.5842821", "0.5842404", "0.5824318", "0.57718134", "0.5739044", "0.56429476", "0.559904", "0.5523092", "0.537339", "0.5353337", "0.5258639", "0.51769775", "0.5175778", "0.5163283", "0.5158048", "0.5124906", "0.51056814", "0.5083702", "0.5079356", "0.50778127", "0.5058568", "0.5036097", "0.5032813", "0.5029127", "0.49826175", "0.49767303", "0.49698672", "0.49435058", "0.49346673", "0.49323758", "0.4929502", "0.49186382", "0.49039596", "0.4832469", "0.4824459", "0.4806311", "0.48019302", "0.47948796", "0.47792956", "0.47559065", "0.47557467", "0.4747922", "0.47392437", "0.47127235", "0.47043908", "0.46996912", "0.46955013", "0.4695302", "0.46925154", "0.46874115", "0.46799907", "0.46799907", "0.4677543", "0.46692127", "0.46494237", "0.46301797", "0.46232623", "0.4611734", "0.4581553", "0.45813552", "0.45747536", "0.45721257", "0.45487478", "0.45174846", "0.45070684", "0.45035124", "0.44924206", "0.44836444", "0.4475445", "0.447118", "0.44616953", "0.44609138", "0.44278392", "0.44207782", "0.44201404", "0.44137236", "0.4411491", "0.44061965", "0.44004583", "0.44001287", "0.43975213", "0.43822205", "0.4382004", "0.43814838", "0.43790603", "0.43733928", "0.43697068", "0.43677026" ]
0.7612451
0
ReleaseAllocator returns an allocator previously reserved using GetAllocator
func (idx *Tree) ReleaseAllocator(a *Allocator) { idx.allocatorQueue.put(a.id) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (allocator *Allocator) ReleaseAllocator() {\n\tC.zj_AllocatorRelease(allocator.A)\n}", "func (a *ResourceAllocator) Free(b []byte) {\n\tif a == nil {\n\t\tDefaultAllocator.Free(b)\n\t\treturn\n\t}\n\n\tsize := len(b)\n\n\t// Release the memory to the allocator first.\n\talloc := a.allocator()\n\talloc.Free(b)\n\n\t// Release the memory in our accounting.\n\tatomic.AddInt64(&a.bytesAllocated, int64(-size))\n}", "func (stack *StackAllocator) release() {\n\tstack.alloc = 0\n}", "func NewAllocator(round uint64) Allocator {\n\ta := &allocator{round: round}\n\treturn a\n}", "func NewAllocator() *Allocator {\n\tvar allocator Allocator\n\tallocator.A = C.zj_NewAllocator()\n\treturn &allocator\n}", "func (c *crdBackend) Release(ctx context.Context, id idpool.ID, key allocator.AllocatorKey) (err error) {\n\t// For CiliumIdentity-based allocation, the reference counting is\n\t// handled via CiliumEndpoint. Any CiliumEndpoint referring to a\n\t// CiliumIdentity will keep the CiliumIdentity alive. No action is\n\t// needed to release the reference here.\n\treturn nil\n}", "func (mm *MMapRWManager) Release() (err error) {\n\tmm.fdm.reduceUsing(mm.path)\n\treturn mm.m.Unmap()\n}", "func newAllocator() *allocator {\n\ta := new(allocator)\n\ta.base.Init()\n\treturn a\n}", "func (p *ResourcePool) Free(a Alloc) error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\treturn p.doFree(a)\n}", "func (idx *Tree) GetAllocator() *Allocator {\n\treturn idx.allocators[idx.allocatorQueue.get()]\n}", "func (s *ControllerPool) Release(controllerName string, controller interface{}) {\n\ts.mu.RLock()\n\tpool, ok := s.poolMap[controllerName]\n\ts.mu.RUnlock()\n\tif !ok {\n\t\tpanic(\"unknown controller name\")\n\t}\n\tDiFree(controller)\n\tpool.Put(controller)\n\n}", "func NewAllocator(provider lCoreProvider) *Allocator {\n\treturn &Allocator{\n\t\tConfig: make(AllocConfig),\n\t\tprovider: provider,\n\t}\n}", "func GetRuntimePortAllocator() (*RuntimePortAllocator, error) {\n\tif rpa.pa == nil {\n\t\tif err := rpa.createAndRestorePortAllocator(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn rpa, nil\n}", "func (r *PortAllocator) Destroy() {\n\tr.alloc.Destroy()\n}", "func (r *PortAllocator) Release(port int) error {\n\tok, offset := r.contains(port)\n\tif !ok {\n\t\tklog.Warningf(\"port is not in the range when release it. port: %v\", port)\n\t\treturn nil\n\t}\n\n\terr := r.alloc.Release(offset)\n\tif err == nil {\n\t\t// update metrics\n\t\tr.metrics.setAllocated(r.Used())\n\t\tr.metrics.setAvailable(r.Free())\n\t}\n\treturn err\n}", "func (am *AccountManager) Release() {\n\tam.bsem <- struct{}{}\n}", "func (s *BasevhdlListener) ExitAllocator(ctx *AllocatorContext) {}", "func (jbobject *UnsafeMemoryMemoryAllocator) Free(a UnsafeMemoryMemoryBlockInterface) {\n\tconv_a := javabind.NewGoToJavaCallable()\n\tif err := conv_a.Convert(a); err != nil {\n\t\tpanic(err)\n\t}\n\t_, err := jbobject.CallMethod(javabind.GetEnv(), \"free\", javabind.Void, conv_a.Value().Cast(\"org/apache/spark/unsafe/memory/MemoryBlock\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconv_a.CleanUp()\n\n}", "func Allocator() pageframe.Allocator {\n\treturn &_buddyAllocator\n}", "func (a *Allocator) ReleaseMemory(size int64) {\n\tif size < 0 {\n\t\tcolexecerror.InternalError(errors.AssertionFailedf(\"unexpectedly negative size in ReleaseMemory: %d\", size))\n\t}\n\tif size > a.acc.Used() {\n\t\tsize = a.acc.Used()\n\t}\n\ta.acc.Shrink(a.ctx, size)\n}", "func (a *ResourceAllocator) allocator() memory.Allocator {\n\tif a.Allocator == nil {\n\t\treturn DefaultAllocator\n\t}\n\treturn a.Allocator\n}", "func (y *Yaraus) Release() error {\n\ty.mu.Lock()\n\tdefer y.mu.Unlock()\n\treturn y.release()\n}", "func (ba *buddyAllocator) Release(addr, order uint32) {\n\tindex, first := ba.getIndex(addr, order)\n\n\tif order >= MaxOrder {\n\t\t// we need to free order / _maxOrder pages\n\t\tn := order / MaxOrder\n\t\t// Mark n pages from index as free\n\t\tfor i := uint32(0); i < n; i++ {\n\t\t\tba.buddies[MaxOrder].freeMap.Set(index + i)\n\t\t}\n\t\treturn\n\t}\n\n\t// go up until we get a buddy with one page allocated\n\tfor order <= MaxOrder {\n\t\t// check if other buddy is still allocated\n\t\tif !ba.buddies[order].freeMap.IsSet(index) {\n\t\t\t// mark buddy as free\n\t\t\tba.buddies[order].freeMap.Toggle(index)\n\t\t\t// add this page to free list\n\t\t\tba.buddies[order].freeList.Append(addr)\n\t\t\t// no need to go further\n\t\t\tbreak\n\t\t}\n\t\t// buddy is also free, combine buddies\n\t\tbuddyAddress := ba.getBuddyAddress(index, order, first)\n\t\tba.buddies[order].freeList.Delete(buddyAddress)\n\t\t// now, mark both pages are free\n\t\tba.buddies[order].freeMap.Toggle(index)\n\t\t// go to next order\n\t\torder++\n\t\tif buddyAddress < addr {\n\t\t\taddr = buddyAddress\n\t\t}\n\t\tindex, first = ba.getIndex(addr, order)\n\t}\n\treturn\n}", "func NewAllocator(\n\tctx context.Context, acc *mon.BoundAccount, factory coldata.ColumnFactory,\n) *Allocator {\n\treturn &Allocator{\n\t\tctx: ctx,\n\t\tacc: acc,\n\t\tfactory: factory,\n\t}\n}", "func (tr *tableReader) Release() {\n\ttr.ProcessorBase.Reset()\n\ttr.fetcher.Reset()\n\t*tr = tableReader{\n\t\tProcessorBase: tr.ProcessorBase,\n\t\tfetcher: tr.fetcher,\n\t\tspans: tr.spans[:0],\n\t\trowsRead: 0,\n\t}\n\ttrPool.Put(tr)\n}", "func (t *IDAllocator) Release(id int) {\n\tif id >= t.nextId {\n\t\tlog.Error(\"id[%v] is invalid to release\", id)\n\t\treturn\n\t}\n\tt.reuseIds = append(t.reuseIds, id)\n\tutils.DescFastSort(t.reuseIds)\n}", "func (na *cnmNetworkAllocator) Deallocate(n *api.Network) error {\n\tlocalNet := na.getNetwork(n.ID)\n\tif localNet == nil {\n\t\treturn fmt.Errorf(\"could not get networker state for network %s\", n.ID)\n\t}\n\n\t// No swarm-level resource deallocation needed for node-local networks\n\tif localNet.isNodeLocal {\n\t\tdelete(na.networks, n.ID)\n\t\treturn nil\n\t}\n\n\tif err := na.freeDriverState(n); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to free driver state for network %s\", n.ID)\n\t}\n\n\tdelete(na.networks, n.ID)\n\n\treturn na.freePools(n, localNet.pools)\n}", "func (ng *NameGenerator) Release(name string) {\n\tng.mu.Lock()\n\tdefer ng.mu.Unlock()\n\n\tif _, ok := ng.use[name]; ok {\n\t\tdelete(ng.use, name)\n\t}\n}", "func newAllocator(size uint32) *Allocator {\n\t// Set initial offset as 1 since 0 is used for nil pointers.\n\treturn &Allocator{make([]byte, size), initialAllocatorOffset}\n}", "func (alloc *RuntimePortAllocator) createAndRestorePortAllocator() (err error) {\n\talloc.pa, err = portallocator.NewPortAllocatorCustom(*alloc.pr, func(max int, rangeSpec string) (allocator.Interface, error) {\n\t\treturn allocator.NewAllocationMap(max, rangeSpec), nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tports, err := alloc.getReservedPorts(alloc.client)\n\tif err != nil {\n\t\treturn err\n\t}\n\talloc.log.Info(\"Found reserved ports\", \"ports\", ports)\n\n\tfor _, port := range ports {\n\t\tif err = alloc.pa.Allocate(port); err != nil {\n\t\t\talloc.log.Error(err, \"can't allocate reserved ports\", \"port\", port)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *PortAllocator) Free() int {\n\treturn r.alloc.Free()\n}", "func (la *Allocator) Free(lc eal.LCore) {\n\tif la.allocated[lc.ID()] == \"\" {\n\t\tpanic(\"lcore double free\")\n\t}\n\tlogger.Info(\"lcore freed\",\n\t\tlc.ZapField(\"lc\"),\n\t\tzap.String(\"role\", la.allocated[lc.ID()]),\n\t\tla.provider.NumaSocketOf(lc).ZapField(\"socket\"),\n\t)\n\tla.allocated[lc.ID()] = \"\"\n}", "func (p *request) Release() {\n\tp.ctx = nil\n\tp.Entry = nil\n\tp.read = false\n\trequestPool.Put(p)\n}", "func (client *VirtualMachineScaleSetsClient) deallocate(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsBeginDeallocateOptions) (*http.Response, error) {\n\treq, err := client.deallocateCreateRequest(ctx, resourceGroupName, vmScaleSetName, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := client.pl.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) {\n\t\treturn nil, client.deallocateHandleError(resp)\n\t}\n\treturn resp, nil\n}", "func (r *Reaper) Release() (Destructor, error) {\n\tif r == nil {\n\t\treturn Noop, nil\n\t}\n\tif r.released {\n\t\treturn nil, kerror.New(kerror.EIllegal,\n\t\t\t\"reaper was already released from responsibility for calling destructors\")\n\t}\n\tif r.finalized {\n\t\treturn nil, kerror.New(kerror.EIllegal, \"reaper has already called destructors\")\n\t}\n\tr.released = true\n\tdestructors := r.destructors\n\treturn DestructorFunc(func() error {\n\t\treturn reap(destructors...)\n\t}), nil\n}", "func (_TokenVesting *TokenVestingTransactorSession) Release(_token common.Address) (*types.Transaction, error) {\n\treturn _TokenVesting.Contract.Release(&_TokenVesting.TransactOpts, _token)\n}", "func (idAllocator *idAllocator) ReleaseID(name string) {\n\tv, ok := idAllocator.nameIdMap.Load(name)\n\tif ok {\n\t\tidAllocator.idBitmap.Release(v.(int))\n\t\tidAllocator.nameIdMap.Delete(name)\n\t}\n}", "func (ta *CachedAllocator) Close() {\n\tta.CancelFunc()\n\tta.wg.Wait()\n\tta.TChan.Close()\n\terrMsg := fmt.Sprintf(\"%s is closing\", ta.Role)\n\tta.revokeRequest(errors.New(errMsg))\n}", "func ReleaseDecoder(dec *Decoder) {\n\tif dec.buf.Len() != 0 {\n\t\tpanic(\"marshal.Decoder: found trailing junk\")\n\t}\n\tdecoderPool.Put(dec)\n}", "func NewUsegAllocator() (Inf, error) {\n\tallocator := &Allocator{\n\t\thostMgrs: make(map[string]usegvlanmgr.Inf),\n\t}\n\terr := allocator.newPGVlanAllocator()\n\treturn allocator, err\n}", "func (_TokenVesting *TokenVestingTransactor) Release(opts *bind.TransactOpts, _token common.Address) (*types.Transaction, error) {\n\treturn _TokenVesting.contract.Transact(opts, \"release\", _token)\n}", "func (p *PreemptiveLocker) Release(ctx context.Context) (err error) {\n\tspan, ctx := p.startSpanFromContext(ctx, \"release\")\n\tp.w.Stop()\n\tdefer func() {\n\t\terr = p.l.Unlock() // always unlock\n\t\tspan.Finish(tracer.WithError(err))\n\t}()\n\tvar kp *consul.KVPair\n\tkp, _, _ = p.kv.Get(p.pendingKey, &consul.QueryOptions{AllowStale: false, WaitIndex: uint64(0), WaitTime: p.opts.LockWait})\n\tif p.id == string(kp.Value[:]) {\n\t\tp.kv.DeleteCAS(&consul.KVPair{Key: p.pendingKey, Value: nil}, nil)\n\t}\n\treturn nil\n}", "func (s *MockManagedThread) Release() {}", "func (sc *schedulerCache) deleteQuotaAllocator(quotaAllocator *arbv1.QuotaAllocator) error {\n\tif _, ok := sc.quotaAllocators[quotaAllocator.Name]; !ok {\n\t\treturn fmt.Errorf(\"quotaAllocator %v doesn't exist\", quotaAllocator.Name)\n\t}\n\tdelete(sc.quotaAllocators, quotaAllocator.Name)\n\treturn nil\n}", "func (tracer *Instance) Release() {\n\ttracer.collections.Del(tracer.key())\n}", "func (m *Manager) Release() {\n\tm.con.Close()\n\tm.stdCimV2Con.Close()\n}", "func (sm *SharedManager) release(ctx context.Context) error {\n\tremaining := atomic.AddInt32(&sm.refCount, -1)\n\tif remaining != 0 {\n\t\tlog(ctx).Debugf(\"not closing shared manager, remaining = %v\", remaining)\n\t\treturn nil\n\t}\n\n\tatomic.StoreInt32(&sm.closed, 1)\n\n\tlog(ctx).Debugf(\"closing shared manager\")\n\n\tif err := sm.committedContents.close(); err != nil {\n\t\treturn errors.Wrap(err, \"error closed committed content index\")\n\t}\n\n\tsm.contentCache.close(ctx)\n\tsm.metadataCache.close(ctx)\n\tsm.encryptionBufferPool.Close()\n\n\treturn sm.st.Close(ctx)\n}", "func (r *ResponsePool) Release(resp *Response) {\n\tresp.Reset()\n\tr.pool.Put(resp)\n}", "func (sc *schedulerCache) updateQuotaAllocator(oldQuotaAllocator, newQuotaAllocator *arbv1.QuotaAllocator) error {\n\tif err := sc.deleteQuotaAllocator(oldQuotaAllocator); err != nil {\n\t\treturn err\n\t}\n\tsc.addQuotaAllocator(newQuotaAllocator)\n\treturn nil\n}", "func Release(b *Buffer) {\n\tb.B = b.B[:0]\n\tpool.Put(b)\n}", "func (r *RequestPool) Release(req *Request) {\n\treq.Reset()\n\tr.pool.Put(req)\n}", "func (b *defaultByteBuffer) Release(e error) (err error) {\n\tb.zero()\n\tbytebufPool.Put(b)\n\treturn\n}", "func Release() {\n\tdefaultRoutinePool.Release()\n}", "func (p *Buffer) release() []byte {\n\tbytes := p.buf\n\tp.buf = nil\n\tp.index = 0\n\tp.Immutable = false\n\tp.err = nil\n\tp.array_indexes = nil\n\tbuffer_pool.Put(p)\n\treturn bytes\n}", "func (a *Allocator) Close() error {\n\tif err := a.flush(); err != nil {\n\t\treturn err\n\t}\n\n\tbuffer.Put(a.bufp)\n\treturn a.f.Close()\n}", "func ReleaseRequest(req *Request) {\n\treq.Reset()\n\trequestPool.Put(req)\n}", "func (c *Compiler) Release() {\n\tC.shaderc_compiler_release(c.compiler)\n}", "func (c DevSession) Release() {\n\tcapnp.Client(c).Release()\n}", "func (_ *MemStore) Release() error {\n\treturn nil\n}", "func (sc *schedulerCache) addQuotaAllocator(quotaAllocator *arbv1.QuotaAllocator) error {\n\tif _, ok := sc.quotaAllocators[quotaAllocator.Name]; ok {\n\t\treturn fmt.Errorf(\"quotaAllocator %v exist\", quotaAllocator.Name)\n\t}\n\n\tinfo := &QuotaAllocatorInfo{\n\t\tname: quotaAllocator.Name,\n\t\tquotaAllocator: quotaAllocator.DeepCopy(),\n\t\tPods: make([]*v1.Pod, 0),\n\t}\n\n\t// init Request if it is nil\n\tif info.QuotaAllocator().Spec.Request.Resources == nil {\n\t\tinfo.QuotaAllocator().Spec.Request.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\n\t// init Deserved/Allocated/Used/Preemping if it is nil\n\tif info.QuotaAllocator().Status.Deserved.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Deserved.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Allocated.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Allocated.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Used.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Used.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Preempting.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Preempting.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tsc.quotaAllocators[quotaAllocator.Name] = info\n\treturn nil\n}", "func (b *Buffer) Release() {\n\tif b.mem != nil || b.parent != nil {\n\t\tdebug.Assert(atomic.LoadInt64(&b.refCount) > 0, \"too many releases\")\n\n\t\tif atomic.AddInt64(&b.refCount, -1) == 0 {\n\t\t\tif b.mem != nil {\n\t\t\t\tb.mem.Free(b.buf)\n\t\t\t} else {\n\t\t\t\tb.parent.Release()\n\t\t\t\tb.parent = nil\n\t\t\t}\n\t\t\tb.buf, b.length = nil, 0\n\t\t}\n\t}\n}", "func (_TokenVesting *TokenVestingSession) Release(_token common.Address) (*types.Transaction, error) {\n\treturn _TokenVesting.Contract.Release(&_TokenVesting.TransactOpts, _token)\n}", "func (sm *SourceMgr) Release() {\n\tos.Remove(path.Join(sm.cachedir, \"sm.lock\"))\n}", "func (lr *libraryCache) Release() {\n\tlr.mtx.Lock()\n\tdefer lr.mtx.Unlock()\n\n\tif lr.refCount == 0 {\n\t\treturn\n\t}\n\n\tlr.refCount--\n\tif lr.refCount == 0 {\n\t\tos.RemoveAll(lr.path)\n\t\tlr.path = \"\"\n\t}\n}", "func (_m *TimeoutSemaphoreInterface) Release(ctx context.Context) {\n\t_m.Called(ctx)\n}", "func (cr *ChunkIterator) Release() {\n\tdebug.Assert(atomic.LoadInt64(&cr.refCount) > 0, \"too many releases\")\n\tref := atomic.AddInt64(&cr.refCount, -1)\n\tif ref == 0 {\n\t\tcr.col.Release()\n\t\tfor i := range cr.chunks {\n\t\t\tcr.chunks[i].Release()\n\t\t}\n\t\tif cr.currentChunk != nil {\n\t\t\tcr.currentChunk.Release()\n\t\t\tcr.currentChunk = nil\n\t\t}\n\t\tcr.col = nil\n\t\tcr.chunks = nil\n\t\tcr.dtype = nil\n\t}\n}", "func (p *provider) release() error {\n\tp.m.Lock()\n\tdefer p.m.Unlock()\n\n\tp.refs--\n\n\tif p.refs > 0 {\n\t\treturn nil\n\t}\n\n\tdb := p.db\n\tp.db = nil\n\n\treturn p.close(db)\n}", "func release(k *gostwriter.K) {\n\terr := k.Release()\n\tguard(err)\n}", "func ReleaseEncoder(enc *Encoder) []byte {\n\tdata := enc.Bytes()\n\tenc.Reset(nil)\n\tencoderPool.Put(enc)\n\treturn data\n}", "func InitAllocator(addr uint32) {\n\t// Warning: Lot of unsafe pointer usage and manipulation ahead.\n\t// This function basically initializes memory at given address, so that\n\t// _buddyAllocator, and it's members, point to this address.\n\n\t// create freeBuddiesList\n\tvar _freeBuddiesList *[MaxOrder + 1]freeBuddiesList\n\t_freeBuddiesList = (*[MaxOrder + 1]freeBuddiesList)(pointer.Get(addr))\n\taddr += (MaxOrder + 1) * uint32(unsafe.Sizeof(freeBuddiesList{}))\n\n\t// set freeBuddiesList in buddyAllocator\n\t_buddyAllocator.buddies = (*_freeBuddiesList)[:MaxOrder+1]\n\n\t// create bigPagesBitmap\n\t// _nBigPages size for array is way more than needed. this is done since\n\t// array sizes need to be constant.\n\tvar _bigPagesBitmap *[_nBigPages]uint32\n\t_bigPagesBitmap = (*[_nBigPages]uint32)(pointer.Get(addr))\n\taddr += nMaps(_nBigPages) * 4\n\n\t// set bigPagesBitmap in buddyAllocator\n\t_buddyAllocator.buddies[MaxOrder].freeMap.maps = (*_bigPagesBitmap)[:nMaps(_nBigPages)]\n\n\t// mark all big pages as free\n\tfor i := uint32(0); i < nMaps(_nBigPages); i++ {\n\t\t_buddyAllocator.buddies[MaxOrder].freeMap.maps[i] = _allSet\n\t}\n\n\t// create the individual freeBuddiesList\n\tfor i := 0; i < MaxOrder; i++ {\n\t\t// maxOrder - 1 pages of order i, further divide by 2 since we use 1 bit\n\t\t// for buddy pair.\n\t\tvar nBuddies uint32 = _nBigPages * (1 << uint32(MaxOrder-i-1))\n\t\tnMaps := nMaps(nBuddies)\n\n\t\t// set address for this freeBuddiesList\n\t\t// we are addressing way more memory than needed, because array sizes need\n\t\t// to be constant. this will be more than enough for largest freeBuddiesList\n\t\tvar maps *[_nBigPages * _nBigPages]uint32\n\t\tmaps = (*[_nBigPages * _nBigPages]uint32)(pointer.Get(addr))\n\t\taddr += nMaps * 4\n\n\t\t// set the freeBuddiesList\n\t\t_buddyAllocator.buddies[i].freeMap.maps = (*maps)[:nMaps]\n\n\t\t// zero out the freeBuddiesList\n\t\tfor j := uint32(0); j < nMaps; j++ {\n\t\t\t_buddyAllocator.buddies[i].freeMap.maps[j] = 0\n\t\t}\n\t}\n\n\tinitNodePool(addr)\n}", "func (s *Sampler) Release() {\n\treleaseSampler(s)\n}", "func (d *DeviceInfoCache) Release(deviceInfo DeviceInfo) error {\n\n\t//this information record might be used by more than one SSM\n\tif deviceInfo._refCount == 0 {\n\t\treturn errors.New(\"reference count\")\n\t}\n\n\t// decrement the reference count\n\tdeviceInfo._refCount--\n\td.cache[deviceInfo._cacheKey.HashKey()] = deviceInfo\n\treturn nil\n}", "func (p *tubePool) allocAndReleaseGate(session int64, done chan tube, releaseGate bool, opt RequestOptions) {\n\ttube, err := p.alloc(session, opt)\n\tif releaseGate {\n\t\tp.gate.exit()\n\t}\n\tif err == nil {\n\t\tselect {\n\t\tcase done <- tube:\n\t\tdefault:\n\t\t\tp.put(tube)\n\t\t}\n\t} else {\n\t\tp.mutex.Lock()\n\t\tif !p.closed {\n\t\t\tselect {\n\t\t\tcase p.errCh <- err:\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t\tp.mutex.Unlock()\n\t}\n\tif done != nil {\n\t\tclose(done)\n\t}\n}", "func (alloc *inMemoryAllocator) GetType() AllocatorType {\n\treturn alloc.allocType\n}", "func ReleaseResponse(resp *Response) {\n\tresp.Reset()\n\tresponsePool.Put(resp)\n}", "func NewDeviceAllocator() DeviceAllocator {\n\tpossibleDevices := make(map[mountDevice]int)\n\tfor _, firstChar := range []rune{'b', 'c'} {\n\t\tfor i := 'a'; i <= 'z'; i++ {\n\t\t\tdev := mountDevice([]rune{firstChar, i})\n\t\t\tpossibleDevices[dev] = 0\n\t\t}\n\t}\n\treturn &deviceAllocator{\n\t\tpossibleDevices: possibleDevices,\n\t\tcounter: 0,\n\t}\n}", "func (t *tableCommon) Allocator(ctx sessionctx.Context) autoid.Allocator {\n\ttrace_util_0.Count(_tables_00000, 322)\n\tif ctx != nil {\n\t\ttrace_util_0.Count(_tables_00000, 324)\n\t\tsessAlloc := ctx.GetSessionVars().IDAllocator\n\t\tif sessAlloc != nil {\n\t\t\ttrace_util_0.Count(_tables_00000, 325)\n\t\t\treturn sessAlloc\n\t\t}\n\t}\n\ttrace_util_0.Count(_tables_00000, 323)\n\treturn t.alloc\n}", "func (elm *etcdLeaseManager) Release(key string) {\n\telm.mu.Lock()\n\tdefer elm.mu.Unlock()\n\n\telm.releaseUnlocked(key)\n}", "func (kvclient *MockResKVClient) ReleaseReservation(ctx context.Context, key string) error {\n\treturn nil\n}", "func (rh *ReservationHelper) ReleaseReservation(\n\tctx context.Context, volume *genV1.Volume, ac, acReplacement *accrd.AvailableCapacity) error {\n\tlogger := util.AddCommonFields(ctx, rh.logger, \"ReservationHelper.ReleaseReservation\")\n\tif err := rh.updateIfRequired(ctx); err != nil {\n\t\treturn err\n\t}\n\t// we should select ACR to remove from ACRs which have same size and SC as volume\n\tfilteredACRMap, filteredACNameToACR := buildACRMaps(\n\t\tFilterACRList(rh.acrList, func(acr acrcrd.AvailableCapacityReservation) bool {\n\t\t\treturn acr.Spec.StorageClass == volume.StorageClass && acr.Spec.Size == volume.Size\n\t\t}))\n\t_, acrToRemove := choseACFromOldestACR(ACMap{ac.Name: ac}, filteredACRMap, filteredACNameToACR)\n\tif acrToRemove == nil {\n\t\tlogger.Infof(\"ACR holding AC %s not found. Skip deletion.\", ac.Name)\n\t\treturn nil\n\t}\n\tif err := rh.removeACR(ctx, acrToRemove); err != nil {\n\t\treturn err\n\t}\n\tif ac == acReplacement {\n\t\treturn nil\n\t}\n\tif err := rh.removeACFromACRs(ctx, acrToRemove.Name, ac); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *pollerAutoScaler) Release(resource autoscaler.ResourceUnit) {\n\tp.sem.Release(int(resource))\n}", "func (b *Bucket) Release() {\n\tif b == nil || b.tokens == nil {\n\t\treturn\n\t}\n\tselect {\n\tcase <-b.tokens:\n\tdefault:\n\t}\n}", "func (ctx *Context) Release() {\n\treleaseContext(ctx)\n}", "func ReleaseBuffer(buffer Buffer) {\n\tpool.put(buffer)\n}", "func NewPodAllocator(netInfo util.NetInfo, podLister listers.PodLister, kube kube.Interface) *PodAllocator {\n\tpodAnnotationAllocator := pod.NewPodAnnotationAllocator(\n\t\tnetInfo,\n\t\tpodLister,\n\t\tkube,\n\t)\n\n\tpodAllocator := &PodAllocator{\n\t\tnetInfo: netInfo,\n\t\treleasedPods: map[string]sets.Set[string]{},\n\t\treleasedPodsMutex: sync.Mutex{},\n\t\tpodAnnotationAllocator: podAnnotationAllocator,\n\t}\n\n\t// this network might not have IPAM, we will just allocate MAC addresses\n\tif util.DoesNetworkRequireIPAM(netInfo) {\n\t\tpodAllocator.ipAllocator = subnet.NewAllocator()\n\t}\n\n\treturn podAllocator\n}", "func (a *allocator) Recycle() {\n\ta.base.Recycle()\n}", "func (mci *XMCacheIterator) Release() {\n\tif mci.dir == dirReleased {\n\t\treturn\n\t}\n\tmci.dir = dirReleased\n\tif mci.mIter != nil {\n\t\tmci.mIter.Release()\n\t}\n\tfor _, it := range mci.iters {\n\t\tit.Release()\n\t}\n\tmci.keys = nil\n\tmci.iters = nil\n}", "func Release(p PTR) {\n\tC.release(C.PTR(p))\n}", "func (sm *SourceMgr) Release() {\n\tsm.lf.Close()\n\tos.Remove(filepath.Join(sm.cachedir, \"sm.lock\"))\n}", "func (it *iterator) Release() {\n\tclose(it.next)\n}", "func (c Controller) Release() {\n\tcapnp.Client(c).Release()\n}", "func NewGlobalTSOAllocator(\n\tam *AllocatorManager,\n\tleadership *election.Leadership,\n) Allocator {\n\tgta := &GlobalTSOAllocator{\n\t\tallocatorManager: am,\n\t\tleadership: leadership,\n\t\ttimestampOracle: &timestampOracle{\n\t\t\tclient: leadership.GetClient(),\n\t\t\trootPath: am.rootPath,\n\t\t\tsaveInterval: am.saveInterval,\n\t\t\tupdatePhysicalInterval: am.updatePhysicalInterval,\n\t\t\tmaxResetTSGap: am.maxResetTSGap,\n\t\t\tdcLocation: GlobalDCLocation,\n\t\t\ttsoMux: &tsoObject{},\n\t\t},\n\t}\n\treturn gta\n}", "func Free(p Pointer) {\n\tallocator.Free(uintptr(p))\n}", "func (p *ResourcePool) doFree(a Alloc) error {\n\tid := a.ID()\n\tif p.allocs[id] != a {\n\t\treturn nil\n\t}\n\tdelete(p.allocs, id)\n\treturn p.manager.Kill(a)\n}", "func (rebase *Rebase) Free() {\n\truntime.SetFinalizer(rebase, nil)\n\tC.git_rebase_free(rebase.ptr)\n}", "func (c PersistentIdentity) Release() {\n\tcapnp.Client(c).Release()\n}", "func (sem *Semaphore) Release() {\n\tsem.slots <- struct{}{}\n}", "func (c *QueueController) Release() {\n\tclose(c.reqCh)\n}", "func (iter *ldbCacheIter) Release() {\n}", "func (r *Reaper) MustRelease() Destructor {\n\tdtor, err := r.Release()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn dtor\n}" ]
[ "0.81131625", "0.64977455", "0.64955264", "0.6233524", "0.6059499", "0.604095", "0.59881294", "0.59217936", "0.59119517", "0.5881009", "0.585588", "0.5847171", "0.5824737", "0.5790185", "0.56845546", "0.5651543", "0.5623506", "0.5620355", "0.56128675", "0.5577229", "0.55664533", "0.5508566", "0.55084443", "0.5491774", "0.54756415", "0.5455362", "0.544748", "0.5394747", "0.5374111", "0.5362999", "0.5346324", "0.5340482", "0.5316079", "0.53064674", "0.5286615", "0.52764666", "0.52754813", "0.5274515", "0.52672213", "0.52663815", "0.52619797", "0.5258916", "0.5247062", "0.5225845", "0.5198869", "0.51913166", "0.5179808", "0.51791257", "0.51721156", "0.5170974", "0.51684546", "0.5163162", "0.5162442", "0.51529056", "0.51376283", "0.5136907", "0.51215285", "0.5119683", "0.51142555", "0.50805825", "0.5076433", "0.507555", "0.50657576", "0.506125", "0.50532794", "0.5042628", "0.5034848", "0.5034837", "0.50252086", "0.5019844", "0.501028", "0.50065976", "0.50052875", "0.500476", "0.5001767", "0.50008124", "0.500073", "0.49967572", "0.49932927", "0.4951296", "0.49511155", "0.49504763", "0.49459922", "0.4945317", "0.49437845", "0.4942172", "0.49391234", "0.49376106", "0.49280185", "0.49274075", "0.49187866", "0.49038902", "0.48980716", "0.48964584", "0.48805925", "0.4874965", "0.48743984", "0.48722187", "0.48547292", "0.4852783" ]
0.7707561
1
Lookup searches the tree for a key and if a candidate leaf is found returns the value stored with it. The caller needs to verify if the candidate is equal to the lookup key, since if the key didn't exist, the candidate will be another key sharing a prefix with the lookup key.
func (idx *Tree) Lookup(key []byte) (value uint64, found bool) { id := idx.allocatorQueue.get() value, found = idx.allocators[id].Lookup(key) idx.allocatorQueue.put(id) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (rad *Radix) Lookup(key string) interface{} {\n\trad.lock.Lock()\n\tdefer rad.lock.Unlock()\n\tif x, ok := rad.root.lookup([]rune(key)); ok {\n\t\treturn x.value\n\t}\n\treturn nil\n}", "func (r *HashRing) Lookup(key string) (string, bool) {\n\tstrs := r.LookupN(key, 1)\n\tif len(strs) == 0 {\n\t\treturn \"\", false\n\t}\n\treturn strs[0], true\n}", "func Lookup(node *Node, key int) bool {\n\tif node == nil {\n\t\treturn false\n\t} else {\n\t\tif node.Key == key {\n\t\t\treturn true\n\t\t} else {\n\t\t\tif node.Key > key {\n\t\t\t\treturn Lookup(node.Left, key)\n\t\t\t} else {\n\t\t\t\treturn Lookup(node.Right, key)\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *hashtable) Lookup(key LRUItem) *CacheItem {\n\tkeyHash := key.Hash()\n\tbucketIndex := int(keyHash) % h.bucketcount\n\tfor node := h.buckets[bucketIndex]; node != nil; node = node.chain {\n\t\tif node.hash == keyHash {\n\t\t\tif node.data.Equals(key) {\n\t\t\t\treturn node\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (t *Tree) Lookup(low, high int64) *Node {\n\tn := t.root\n\tfor n != nil && (low > n.high || n.low > high) { // should search in childs\n\t\tif n.left != nil && low <= n.left.m {\n\t\t\tn = n.left // path choice on m.\n\t\t} else {\n\t\t\tn = n.right\n\t\t}\n\t}\n\n\treturn n\n}", "func (m Map) Lookup(d digest.Digest, key T) T {\n\tif _, ok := m.tab[d]; !ok {\n\t\treturn nil\n\t}\n\tentry := *m.tab[d]\n\tfor entry != nil && Less(entry.Key, key) {\n\t\tentry = entry.Next\n\t}\n\tif entry == nil || !Equal(entry.Key, key) {\n\t\treturn nil\n\t}\n\treturn entry.Value\n}", "func (t *DiskTree) Lookup(n *Node, search string, i int) (*Node, int) {\n\n\tif n == nil {\n\t\treturn nil, i\n\t}\n\tdn := t.dnodeFromNode(n)\n\tdebugf(\"Lookup(%+v, \\\"%s\\\", %d)\\n\", dn, search, i)\n\tmatch := matchprefix(n.Edgename, search[i:])\n\ti += len(match)\n\tif i < len(search) && len(n.Edgename) == len(match) {\n\t\tchild := t.fetchChild(n, string(search[i]))\n\t\tc, i := t.Lookup(child, search, i)\n\t\tif c != nil {\n\t\t\treturn c, i\n\t\t}\n\t}\n\treturn n, i\n}", "func (t MemTree) Lookup(n *Node, s string) (nres *Node, part, match string) {\n\tdebugf(\"Lookup: NODE<%+v> for '%s'\\n\", *n, s)\n\tif s == \"\" {\n\t\treturn n, \"\", \"\"\n\t}\n\tfor _, c := range n.Children {\n\t\tdebugf(\"\\tchild %s\", c.Edgename)\n\t\tmatch = matchprefix(c.Edgename, s)\n\t\tif match == \"\" {\n\t\t\tdebug(\" does not match\")\n\t\t\tcontinue\n\t\t} else {\n\t\t\tdebug(\" matches\", len(match), \"characters ->\", match)\n\t\t\tif len(match) < len(c.Edgename) {\n\t\t\t\treturn c, \"\", match\n\t\t\t}\n\t\t\tvar m string\n\t\t\tnres, part, m = t.Lookup(c, s[len(match):])\n\t\t\tmatch += m\n\t\t\tif part == \"\" {\n\t\t\t\tpart = m\n\t\t\t}\n\t\t\t// for a partial match\n\t\t\tif nres == nil {\n\t\t\t\treturn c, part, match\n\t\t\t}\n\t\t\treturn nres, part, match\n\t\t}\n\t}\n\treturn nil, \"\", \"\"\n}", "func (rp *Ringpop) Lookup(key string) string {\n\tstartTime := time.Now()\n\n\tdest, ok := rp.ring.Lookup(key)\n\n\trp.emit(LookupEvent{key, time.Now().Sub(startTime)})\n\n\tif !ok {\n\t\trp.log.WithField(\"key\", key).Warn(\"could not find destination for key\")\n\t\treturn rp.WhoAmI()\n\t}\n\n\treturn dest\n}", "func (c *Config) Lookup(key string) (any, error) {\n\t// check thet key is valid, meaning it starts with one of\n\t// the fields of the config struct\n\tif !c.isValidKey(key) {\n\t\treturn nil, nil\n\t}\n\tval, err := lookupByType(key, reflect.ValueOf(c))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"lookup: error on key '%s'\", key)\n\t}\n\treturn val, nil\n}", "func lookup(p fuseops.InodeID, c string, lookupTree *iradix.Tree) (le lookupEntry, found bool, lk []byte) {\n\tlk = formLookupKey(p, c)\n\tval, found := lookupTree.Get(lk)\n\tif found {\n\t\tle = val.(lookupEntry)\n\t\treturn le, found, lk\n\t}\n\treturn lookupEntry{}, found, lk\n}", "func lookup(p fuseops.InodeID, c string, lookupTree *iradix.Tree) (le lookupEntry, found bool, lk []byte) {\n\tlk = formLookupKey(p, c)\n\tval, found := lookupTree.Get(lk)\n\tif found {\n\t\tle = val.(lookupEntry)\n\t\treturn le, found, lk\n\t}\n\treturn lookupEntry{}, found, lk\n}", "func (local *Node) Lookup(key string) (nodes []RemoteNode, err error) {\n\t// TODO: students should implement this\n\treturn\n}", "func (r *Ring) Lookup(n int, key []byte) ([]*Vnode, error) {\n\t// Ensure that n is sane\n\tif n > r.config.NumSuccessors {\n\t\treturn nil, fmt.Errorf(\"Cannot ask for more successors than NumSuccessors!\")\n\t}\n\n\t// Hash the key\n\th := r.config.HashFunc()\n\th.Write(key)\n\tkey_hash := h.Sum(nil)\n\n\t// Find the nearest local vnode\n\tnearest := r.nearestVnode(key_hash)\n\n\t// Use the nearest node for the lookup\n\tsuccessors, err := nearest.FindSuccessors(n, key_hash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Trim the nil successors\n\tfor successors[len(successors)-1] == nil {\n\t\tsuccessors = successors[:len(successors)-1]\n\t}\n\treturn successors, nil\n}", "func (tree *Tree) Get(key interface{}) (value interface{}, found bool) {\n\tnode := tree.lookup(key)\n\tif node != nil {\n\t\treturn node.Value, true\n\t}\n\treturn nil, false\n}", "func (t *middNode) Lookup(searchKey string) HandlerFuncs {\r\n\tsearchKey = strings.Split(searchKey, \" \")[0]\r\n\tif searchKey[len(searchKey) - 1] == '*' {\r\n\t\tsearchKey = searchKey[:len(searchKey) - 1]\r\n\t}\r\n\treturn t.recursiveLoopup(searchKey)\r\n}", "func (manager *KeysManager) Lookup(keyID string) (*jose.JSONWebKey, error) {\n\tvar jwk *jose.JSONWebKey\n\tjwk, exists := manager.KeyMap[keyID]\n\t// If no key is found, refresh the stored key set.\n\tif !exists {\n\t\tif err := manager.Refresh(); err != nil {\n\t\t\treturn jwk, err\n\t\t}\n\t\tjwk, exists = manager.KeyMap[keyID]\n\t\t// If still no key is found, return an error.\n\t\tif !exists {\n\t\t\treturn nil, missingKey(keyID)\n\t\t}\n\t}\n\treturn jwk, nil\n}", "func (d *gossipDiscoveryImpl) Lookup(PKIID common.PKIidType) *NetworkMember {\n\tif bytes.Equal(PKIID, d.self.PKIid) {\n\t\treturn &d.self\n\t}\n\td.lock.RLock()\n\tdefer d.lock.RUnlock()\n\treturn copyNetworkMember(d.id2Member[string(PKIID)])\n}", "func (kp *KeyPool) Lookup(keyid [signkeys.KeyIDSize]byte) (*signkeys.PublicKey, error) {\n\tkp.mapMutex.RLock()\n\tdefer kp.mapMutex.RUnlock()\n\tkey, err := kp.lookup(keyid)\n\tif err == ErrNotFound && kp.FetchKeyCallBack != nil {\n\t\t// Use fetchkey callback\n\t\tfetchedKeyMarshalled, err := kp.FetchKeyCallBack(keyid[:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfetchedKey, err := new(signkeys.PublicKey).Unmarshal(fetchedKeyMarshalled)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkeyidFetch, err := kp.loadKey(fetchedKey)\n\t\tif err != nil && err != ErrExists {\n\t\t\treturn nil, ErrNotFound\n\t\t}\n\t\tif *keyidFetch == keyid {\n\t\t\treturn fetchedKey, nil\n\t\t}\n\t}\n\treturn key, err\n}", "func (t *Trie) Get(key []byte) (interface{}, bool) {\n\tif t.root == nil {\n\t\treturn nil, false\n\t}\n\n\tn := t.root.findBestLeaf(key)\n\tif bytes.Equal(key, n.key) {\n\t\treturn n.value, true\n\t}\n\treturn nil, false\n}", "func (fs *fsMutable) lookup(p fuseops.InodeID, c string) (le lookupEntry, found bool, lk []byte) {\n\treturn lookup(p, c, fs.lookupTree)\n}", "func (fs *fsMutable) lookup(p fuseops.InodeID, c string) (le lookupEntry, found bool, lk []byte) {\n\treturn lookup(p, c, fs.lookupTree)\n}", "func (n *node) Lookup(ctx context.Context, name string) (fspkg.Node, error) {\n\te, ok := n.te.LookupChild(name)\n\tif !ok {\n\t\treturn nil, syscall.ENOENT\n\t}\n\treturn &node{n.fs, e}, nil\n}", "func (self *BTrie) Get(key []byte) (value interface{}) {\n\tif res, isMatch := self.drillDown(key, nil, nil); isMatch {\n\t\treturn res.leaf.value\n\t}\n\treturn nil\n}", "func (a Address) Lookup(k string) (any, error) {\n\tswitch k {\n\tcase \"port\":\n\t\tt, err := net.ResolveTCPAddr(\"tcp\", a.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn t.Port, nil\n\tcase \"ip\":\n\t\tt, err := net.ResolveTCPAddr(\"tcp\", a.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn t.IP.String(), nil\n\t}\n\treturn nil, ErrKeyNotFound{Key: k}\n}", "func (c *Cache) Lookup(buildid int64) (string, error) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tif hash, ok := c.hashes[buildid]; !ok {\n\t\treturn \"\", fmt.Errorf(\"BuildId not found in cache: %d\", buildid)\n\t} else {\n\t\treturn hash, nil\n\t}\n}", "func (a *addrBook) Lookup(addr p2pcrypto.PublicKey) (*node.Info, error) {\n\ta.mtx.Lock()\n\td := a.lookup(addr)\n\ta.mtx.Unlock()\n\tif d == nil {\n\t\t// Todo: just return empty without error ?\n\t\treturn nil, ErrLookupFailed\n\t}\n\treturn d.na, nil\n}", "func (n *node) Lookup(ctx context.Context, req *fuse.LookupRequest, resp *fuse.LookupResponse) (fs.Node, error) {\n\tvar requested string = req.Name\n\tp, nm := n.Path(), n.Name()\n\tfp, _ := filepath.Abs(filepath.Join(p, \"/\", nm))\n\ttail := n.Tail()\n\tif len(tail) > 0 {\n\t\tfor _, nn := range tail {\n\t\t\tif nn.Aliased() {\n\t\t\t\tif exists, ad := nn.Find(requested, n, nn); exists {\n\t\t\t\t\tswitch ad.Is() {\n\t\t\t\t\tcase Directory:\n\t\t\t\t\t\tad.SetPath(fp)\n\t\t\t\t\t\treturn ad, nil\n\t\t\t\t\tcase File, Fileio:\n\t\t\t\t\t\taf := NewNodeFile(ad)\n\t\t\t\t\t\taf.InitializeFile(fp, n)\n\t\t\t\t\t\treturn af, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif nn.Name() == requested {\n\t\t\t\tswitch nn.Is() {\n\t\t\t\tcase Directory:\n\t\t\t\t\tnn.InitializeDir(fp, n)\n\t\t\t\t\treturn nn, nil\n\t\t\t\tcase File, Fileio, Socket:\n\t\t\t\t\tf := NewNodeFile(nn)\n\t\t\t\t\tf.InitializeFile(fp, n)\n\t\t\t\t\treturn f, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, fuse.ENOENT\n}", "func (kvStore *KVStore) Lookup(hash KademliaID) (output []byte, err error) {\n kvStore.mutex.Lock()\n if val, ok := kvStore.mapping[hash]; ok {\n output = val.data\n } else {\n err = NotFoundError\n }\n kvStore.mutex.Unlock()\n return\n}", "func (w *WindowedMap) Lookup(uid UID) (interface{}, bool) {\n\tw.ExpireOldEntries()\n\titem, ok := w.uidMap[uid]\n\tif !ok {\n\t\treturn nil, false\n\t}\n\tw.Put(uid, item.value)\n\treturn item.value, true\n}", "func (t *Trie) Get(key string) interface{} {\n\ts := commonPrefix(t.suffix, key)\n\n\tif s < len(t.suffix) {\n\t\treturn nil\n\t}\n\n\tif s == len(key) {\n\t\treturn t.value\n\t}\n\n\tif key[s] < t.base || int(key[s]) >= int(t.base)+len(t.children) {\n\t\treturn nil\n\t}\n\n\treturn t.children[key[s]-t.base].Get(key[s+1:])\n}", "func (t *chaining) Search(key string) interface{} {\n\thash := t.hash(key)\n\tlist := t.values[hash]\n\tif list == nil || list.Len == 0 {\n\t\treturn nil\n\t}\n\thead := list.Start().Prev\n\tfor head != list.End() {\n\t\thead = head.Next\n\t\tpair := head.Value.(*pair)\n\t\tif pair.key == key {\n\t\t\treturn pair.value\n\t\t}\n\t}\n\treturn nil\n}", "func (t *Table) Lookup(s string) (n uint32, ok bool) {\n\ti0 := int(murmurSeed(0).hash(s)) & t.level0Mask\n\tseed := t.level0[i0]\n\ti1 := int(murmurSeed(seed).hash(s)) & t.level1Mask\n\tn = t.level1[i1]\n\treturn n, s == t.keys[int(n)]\n}", "func (registry *Registry) Lookup(handle string) *task.Task {\n\t// TODO: Refactor the interface here to explicitly add an `ok`\n\t// return value (in the style of reading a map[...]...)\n\t// to differentiate a present nil value return vs. a\n\t// not-present-at-all value.\n\tregistry.lock.RLock()\n\tdefer registry.lock.RUnlock()\n\n\tif t, exists := registry.db[handle]; exists {\n\t\treturn t\n\t}\n\n\treturn nil\n}", "func (n *NoOP) Lookup(key []byte) []byte {\n\treturn make([]byte, 1)\n}", "func (chain *DataTypeChain) Lookup(lookup map[string]DataType) *DataTypeChain {\n\tif chain.strval != nil {\n\t\tkey := *chain.strval\n\t\tvar val *DataType\n\t\tif v, ok := lookup[key]; ok {\n\t\t\tval = &v\n\t\t} else if v, ok := lookup[strings.ToLower(key)]; ok {\n\t\t\tval = &v\n\t\t}\n\t\tif val != nil {\n\t\t\tchain.value = val\n\t\t\tchain.afterSetValue()\n\t\t}\n\t}\n\treturn chain\n}", "func (sm *ConcurrentStateMachine) Lookup(query []byte) ([]byte, error) {\n\treturn sm.sm.Lookup(query)\n}", "func (n *Node) Lookup(ctx context.Context, name string) (fs.Node, error) {\n\tlog.Println(\"Lookup\", name)\n\tnode, ok := n.fs.Nodes[name]\n\tif ok {\n\t\treturn node, nil\n\t}\n\treturn nil, fuse.ENOENT\n}", "func (r *ring) Lookup(\n\tkey string,\n) (HostInfo, error) {\n\taddr, found := r.ring().Lookup(key)\n\tif !found {\n\t\tselect {\n\t\tcase r.refreshChan <- &ChangedEvent{}:\n\t\tdefault:\n\t\t}\n\t\treturn HostInfo{}, ErrInsufficientHosts\n\t}\n\tr.members.RLock()\n\tdefer r.members.RUnlock()\n\thost, ok := r.members.keys[addr]\n\tif !ok {\n\t\treturn HostInfo{}, fmt.Errorf(\"host not found in member keys, host: %q\", addr)\n\t}\n\treturn host, nil\n}", "func (n *Node) locate(key string) (*models.Node, error) {\n\tid, err := n.hashKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsucc, err := n.findSuccessor(id)\n\treturn succ, err\n}", "func (l *RandomAccessGroupLookup) Lookup(key flux.GroupKey) (interface{}, bool) {\n\tid := l.idForKey(key)\n\te, ok := l.index[string(id)]\n\tif !ok || e.Deleted {\n\t\treturn nil, false\n\t}\n\treturn e.Value, true\n}", "func (s *ConcurrentStateMachine) Lookup(query interface{}) (interface{}, error) {\n\treturn s.sm.Lookup(query)\n}", "func (tree *Trie) Find(key string) (value interface{}, found bool) {\n\tnode, found := tree.findNodeByMask(key)\n\n\tif found && node.terminal {\n\t\treturn node.data, true\n\t}\n\n\treturn nil, false\n}", "func (l *GroupLookup) Lookup(key flux.GroupKey) (interface{}, bool) {\n\tif key == nil || len(l.groups) == 0 {\n\t\treturn nil, false\n\t}\n\n\tgroup := l.lookupGroup(key)\n\tif group == -1 {\n\t\treturn nil, false\n\t}\n\n\ti := l.groups[group].Index(key)\n\tif i != -1 {\n\t\treturn l.groups[group].At(i), true\n\t}\n\treturn nil, false\n}", "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 *Map) Find(key interface{}) (value interface{}, found bool) {\n\troot := m.root\n\tfor root != nil {\n\t\tif m.less(key, root.key) {\n\t\t\troot = root.left\n\t\t} else if m.less(root.key, key) {\n\t\t\troot = root.right\n\t\t} else {\n\t\t\treturn root.value, true\n\t\t}\n\t}\n\treturn nil, false\n}", "func (m *DHTModule) Lookup(key string) string {\n\n\tif m.IsAttached() {\n\t\tval, err := m.Client.DHT().Lookup(key)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn base64.StdEncoding.EncodeToString([]byte(val))\n\t}\n\n\tctx, cn := context.WithTimeout(context.Background(), 60*time.Second)\n\tdefer cn()\n\tbz, err := m.dht.Lookup(ctx, dht2.MakeKey(key))\n\tif err != nil {\n\t\tpanic(errors.ReqErr(500, StatusCodeServerErr, \"key\", err.Error()))\n\t}\n\treturn base64.StdEncoding.EncodeToString(bz)\n}", "func (da *DoubleArray) Lookup(key string) (int, bool) {\n\tnpos := 0\n\tdepth := 0\n\n\tfor ; depth < len(key); depth++ {\n\t\tif da.array[npos].base < 0 {\n\t\t\tbreak\n\t\t}\n\t\tcpos := da.array[npos].base ^ int(key[depth])\n\t\tif da.array[cpos].check != npos {\n\t\t\treturn 0, false\n\t\t}\n\t\tnpos = cpos\n\t}\n\n\tif da.array[npos].base >= 0 {\n\t\tcpos := da.array[npos].base // ^ int(terminator)\n\t\tif da.array[cpos].check != npos {\n\t\t\treturn 0, false\n\t\t}\n\t\treturn da.array[cpos].base, true\n\t}\n\n\ttpos := -da.array[npos].base\n\tfor ; depth < len(key); depth++ {\n\t\tif da.tail[tpos] != key[depth] {\n\t\t\treturn 0, false\n\t\t}\n\t\ttpos++\n\t}\n\n\tif da.tail[tpos] != terminator {\n\t\treturn 0, false\n\t}\n\treturn da.getValue(tpos + 1), true\n}", "func (t *Tree) Get(key string) interface{} {\n tree := t.find(key)\n if tree == nil {\n return nil\n }\n return tree.value\n}", "func (rbTree *RBTree)Get(key MapKey) *MapData {\n\t// curr view tree node\n\tcurr := rbTree.root\n\t// find position\n\tfor curr != nil {\n\t\t// update prev\n\t\tif key == curr.Key {\n\t\t\t// find\n\t\t\treturn curr.Value\n\t\t} else if key < curr.Key {\n\t\t\t// goto left\n\t\t\tcurr = curr.left\n\t\t} else {\n\t\t\t// goto right\n\t\t\tcurr = curr.right\n\t\t}\n\t}\n\treturn nil\n}", "func (t *trieNode) Lookup(path string) HandlerFuncs {\n\tfor _, i := range t.childs {\n\t\tif strings.HasPrefix(path, i.path) {\n\t\t\treturn HandlerFuncsCombine(t.vals, i.Lookup(path[len(i.path):]))\n\t\t}\n\t}\n\treturn t.vals\n}", "func (s *devNull) Lookup(key string) (interface{}, bool) {\n\treturn nil, false\n}", "func (this *Map) Get(key interface{}) interface{} {\n\tnode := this.tree.FindNode(key)\n\tif node != nil {\n\t\treturn node.Value()\n\t}\n\treturn nil\n}", "func (t *RedBlackTree) Get(key interface{}) (value interface{}, found bool) {\n\tif node := t.Node(key); node != nil {\n\t\tvalue = node.value\n\t\tfound = true\n\t\treturn\n\t}\n\n\treturn\n}", "func (this *MultiMap) Get(key interface{}) interface{} {\n\tnode := this.tree.FindNode(key)\n\tif node != nil {\n\t\treturn node.Value()\n\t}\n\treturn nil\n}", "func (sm *RegularStateMachine) Lookup(query []byte) ([]byte, error) {\n\treturn sm.sm.Lookup(query), nil\n}", "func (t *Tree) Get(k []byte) ([]byte, bool) {\n\tif t.root == nil {\n\t\treturn nil, false\n\t}\n\treturn t.root.lookup(t, k)\n}", "func (st *SlimTrie) Search(key string) (lVal, eqVal, rVal interface{}) {\n\n\tlID, eqID, rID := st.searchID(key)\n\n\tif lID != -1 {\n\t\tlVal, _ = st.Leaves.Get(lID)\n\t}\n\tif eqID != -1 {\n\t\teqVal, _ = st.Leaves.Get(eqID)\n\t}\n\tif rID != -1 {\n\t\trVal, _ = st.Leaves.Get(rID)\n\t}\n\n\treturn\n}", "func (s *subtasks) Lookup(ctx context.Context, dir *fs.Inode, p string) (*fs.Dirent, error) {\n\ttid, err := strconv.ParseUint(p, 10, 32)\n\tif err != nil {\n\t\treturn nil, syserror.ENOENT\n\t}\n\n\ttask := s.pidns.TaskWithID(kernel.ThreadID(tid))\n\tif task == nil {\n\t\treturn nil, syserror.ENOENT\n\t}\n\tif task.ThreadGroup() != s.t.ThreadGroup() {\n\t\treturn nil, syserror.ENOENT\n\t}\n\n\ttd := newTaskDir(task, dir.MountSource, s.pidns, false)\n\treturn fs.NewDirent(td, p), nil\n}", "func (s *RegularStateMachine) Lookup(query interface{}) (interface{}, error) {\n\treturn s.sm.Lookup(query)\n}", "func (client *ClientWrapper) Lookup(key string, pointer interface{}) (interface{}, os.Error) {\n\terr := client.Client.Call(\"Registry.Lookup\", key, &pointer)\n\treturn pointer, err\n}", "func (inst *hiddenInstance) Lookup(path ...string) Value {\n\treturn inst.value().Lookup(path...)\n}", "func (c *Cache) lookupResult(\n\tpodName, nodeName, predicateKey string,\n\tequivalenceHash uint64,\n) (value predicateResult, ok bool) {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\tglog.V(5).Infof(\"Cache lookup: node=%s,predicate=%s,pod=%s\", nodeName, predicateKey, podName)\n\tvalue, ok = c.cache[nodeName][predicateKey][equivalenceHash]\n\treturn value, ok\n}", "func (d *Dir) Lookup(ctx context.Context, name string) (fs.Node, error) {\n\t// fmt.Printf(\"doing lookup of dir at inode %d\\n\", d.inodeNum)\n\tvar offset uint64 = 0\n\ttableData, err := d.inode.readFromData(offset, d.inode.Size)\n\tif err != nil {\n\t\tfmt.Println(\"VERY BAD error doing readFromData from offset 0 in Lookup \" + err.Error())\n\t}\n\ttable := new(InodeTable)\n\ttable.UnmarshalBinary(tableData)\n\tinodeNum := table.Table[name]\n\tif inodeNum == 0 {\n\t\treturn nil, fuse.ENOENT\n\t} else {\n\t\tinode, err := getInode(inodeNum)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"VERY BAD error doing getInode on existing entry in Lookup: \" + err.Error())\n\t\t}\n\t\tvar child fs.Node\n\t\tif inode.IsDir == 1 {\n\t\t\tchild = &Dir{\n\t\t\t\tinode: inode,\n\t\t\t\tinodeNum: inodeNum,\n\t\t\t\tinodeStream: d.inodeStream,\n\t\t\t}\n\t\t} else {\n\t\t\tchild = &File{\n\t\t\t\tinode: inode,\n\t\t\t\tinodeNum: inodeNum,\n\t\t\t\tinodeStream: d.inodeStream,\n\t\t\t}\n\t\t}\n\t\treturn child, nil\n\t}\n}", "func (m *hashRing) Get(key string) *destination {\n\tif m.IsEmpty() {\n\t\treturn nil\n\t}\n\n\thash := int(m.hash([]byte(key)))\n\n\t// Binary search for appropriate replica.\n\tidx := sort.Search(len(m.keys), func(i int) bool { return m.keys[i] >= hash })\n\n\t// Means we have cycled back to the first replica.\n\tif idx == len(m.keys) {\n\t\tidx = 0\n\t}\n\n\treturn m.hashMap[m.keys[idx]]\n}", "func (t *Tree) search(k Key) Value {\n\tx := t.root\n\tfor x != nil {\n\t\tcmp := x.key.Compare(k)\n\t\tif cmp == 0 {\n\t\t\treturn x.value\n\t\t}\n\t\tif cmp < 0 {\n\t\t\tx = x.left\n\t\t}\n\t\tif cmp > 0 {\n\t\t\tx = x.right\n\t\t}\n\t}\n\treturn nil\n}", "func (t *RbTree[K, V]) Find(key K) (V, error) {\n\tn := t.findFirstNode(key)\n\tif n != nil {\n\t\treturn n.value, nil\n\t}\n\treturn *new(V), ErrorNotFound\n}", "func (d *Dir) Lookup(ctx context.Context, name string) (fs.Node, error) {\n\tlog.Println(\"dir.Lookup\")\n\tinfo, err := d.core.Stat(ctx, name)\n\tif err != nil {\n\t\treturn &notExistFile{\n\t\t\tcore: d.core,\n\t\t\tkey: name,\n\t\t}, nil\n\t}\n\treturn &existingFile{info: info}, nil\n}", "func (n *Node) Lookup(ctx context.Context, name string) (fs.Node, error) {\n\tn.log.Lookup(ctx, name)\n\tlink, _, err := uio.ResolveUnixfsOnce(ctx, n.Ipfs.DAG, n.Nd, []string{name})\n\tswitch err {\n\tcase os.ErrNotExist, mdag.ErrLinkNotFound:\n\t\t// todo: make this error more versatile.\n\t\treturn nil, fuse.ENOENT\n\tdefault:\n\t\tn.log.Errorf(\"fuse lookup %q: %s\", name, err)\n\t\treturn nil, fuse.EIO\n\tcase nil:\n\t\t// noop\n\t}\n\n\tnd, err := n.Ipfs.DAG.Get(ctx, link.Cid)\n\tswitch err {\n\tcase ipld.ErrNotFound:\n\tdefault:\n\t\tn.log.Errorf(\"fuse lookup %q: %s\", name, err)\n\t\treturn nil, err\n\tcase nil:\n\t\t// noop\n\t}\n\n\treturn &Node{Ipfs: n.Ipfs, Nd: nd, log: n.log}, nil\n}", "func (t *BPTree) Find(key []byte) (*Record, error) {\n\tvar (\n\t\tleaf *Node\n\t\ti int\n\t)\n\n\t// Find leaf by key.\n\tleaf = t.FindLeaf(key)\n\n\tif leaf == nil {\n\t\treturn nil, ErrKeyNotFound\n\t}\n\n\tfor i = 0; i < leaf.KeysNum; i++ {\n\t\tif compare(key, leaf.Keys[i]) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif i == leaf.KeysNum {\n\t\treturn nil, ErrKeyNotFound\n\t}\n\n\treturn leaf.pointers[i].(*Record), nil\n}", "func (c *Cache) Lookup(key string, factory func() interface{}) chan interface{} {\n\tc.lock.Lock()\n\trchan := make(chan interface{}, 1) // Return results.\n\t// Check if we know the key.\n\tif e, ok := c.cache[key]; ok {\n\t\te.lock.Lock() // Switch lock to element mutex\n\t\tdefer e.lock.Unlock()\n\t\tc.lock.Unlock()\n\n\t\tif e.result != nil { // We have a result.\n\t\t\trchan <- e.result\n\t\t\tclose(rchan)\n\t\t} else {\n\t\t\te.futures = append(e.futures, rchan)\n\t\t}\n\t} else {\n\t\tt := &cacheObject{\n\t\t\tfutures: []chan interface{}{rchan},\n\t\t\tlock: new(sync.Mutex),\n\t\t}\n\t\tc.cache[key] = t\n\t\tc.lock.Unlock()\n\t\t// Call factory\n\t\tgo func() {\n\t\t\tvalue := factory()\n\t\t\tc.register(key, value)\n\t\t}()\n\t}\n\treturn rchan\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 (t *ArtTree) Search(key []byte) interface{} {\n\tkey = ensureNullTerminatedKey(key)\n\tfoundNode := t.searchHelper(t.root, key, 0)\n\tif foundNode != nil && foundNode.IsMatch(key) {\n\t\treturn foundNode.value\n\t}\n\treturn nil\n}", "func (r *RadixTrie) Find(key string) (interface{}, bool) {\n\tif len(key) == 0 {\n\t\treturn r.val, r.ok\n\t}\n\tif r.nodes == nil {\n\t\treturn nil, false\n\t}\n\tns := r.nodes\nsearch:\n\tfor {\n\t\tfor i := 0; i < len(ns); i++ {\n\t\t\tif key[0] == ns[i].str[0] {\n\t\t\t\tif len(key) < len(ns[i].str) {\n\t\t\t\t\treturn nil, false\n\t\t\t\t}\n\t\t\t\tfor j := 1; j < len(ns[i].str); j++ {\n\t\t\t\t\tif key[j] != ns[i].str[j] {\n\t\t\t\t\t\treturn nil, false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(key) == len(ns[i].str) {\n\t\t\t\t\treturn ns[i].val, ns[i].ok\n\t\t\t\t}\n\t\t\t\tkey = key[len(ns[i].str):]\n\t\t\t\tns = ns[i].nodes\n\t\t\t\tcontinue search\n\t\t\t}\n\t\t}\n\t\treturn nil, false\n\t}\n}", "func (m *TMap) Find(key interface{}) (value interface{}, exists bool) {\n\tv, ok := m.root.Find(entry{key: key})\n\tif !ok {\n\t\treturn nil, ok\n\t}\n\tent := v.(entry)\n\treturn ent.value, ok\n}", "func Lookup() {\n\tTEXT(\"Lookup\", NOSPLIT, \"func(keyset []byte, key []byte) int\")\n\tDoc(\"Lookup searches for a key in a set of keys, returning its index if \",\n\t\t\"found. If the key cannot be found, the number of keys is returned.\")\n\n\t// Load inputs.\n\tkeyset := Load(Param(\"keyset\").Base(), GP64())\n\tcount := Load(Param(\"keyset\").Len(), GP64())\n\tSHRQ(Imm(4), count)\n\tkeyPtr := Load(Param(\"key\").Base(), GP64())\n\tkeyLen := Load(Param(\"key\").Len(), GP64())\n\tkeyCap := Load(Param(\"key\").Cap(), GP64())\n\n\t// None of the keys are larger than maxLength.\n\tCMPQ(keyLen, Imm(maxLength))\n\tJA(LabelRef(\"not_found\"))\n\n\t// We're going to be unconditionally loading 16 bytes from the input key\n\t// so first check if it's safe to do so (cap >= 16). If not, defer to\n\t// safe_load for additional checks.\n\tCMPQ(keyCap, Imm(maxLength))\n\tJB(LabelRef(\"safe_load\"))\n\n\t// Load the input key and pad with zeroes to 16 bytes.\n\tLabel(\"load\")\n\tkey := XMM()\n\tVMOVUPS(Mem{Base: keyPtr}, key)\n\tLabel(\"prepare\")\n\tzeroes := XMM()\n\tVPXOR(zeroes, zeroes, zeroes)\n\tones := XMM()\n\tVPCMPEQB(ones, ones, ones)\n\tvar blendBytes [maxLength * 2]byte\n\tfor j := 0; j < maxLength; j++ {\n\t\tblendBytes[j] = 0xFF\n\t}\n\tblendMasks := ConstBytes(\"blend_masks\", blendBytes[:])\n\tblendMasksPtr := GP64()\n\tLEAQ(blendMasks.Offset(maxLength), blendMasksPtr)\n\tSUBQ(keyLen, blendMasksPtr)\n\tblend := XMM()\n\tVMOVUPS(Mem{Base: blendMasksPtr}, blend)\n\tVPBLENDVB(blend, key, zeroes, key)\n\n\t// Zero out i so we can use it as the loop increment.\n\ti := GP64()\n\tXORQ(i, i)\n\n\t// Round the key count down to the nearest multiple of unroll to determine\n\t// how many iterations of the big loop we'll need.\n\ttruncatedCount := GP64()\n\tMOVQ(count, truncatedCount)\n\tshift := uint64(math.Log2(float64(unroll)))\n\tSHRQ(Imm(shift), truncatedCount)\n\tSHLQ(Imm(shift), truncatedCount)\n\n\t// Loop over multiple keys in the big loop.\n\tLabel(\"bigloop\")\n\tCMPQ(i, truncatedCount)\n\tJE(LabelRef(\"loop\"))\n\n\tx := []VecPhysical{X8, X9, X10, X11, X12, X13, X14, X15}\n\tfor n := 0; n < unroll; n++ {\n\t\tVPCMPEQB(Mem{Base: keyset, Disp: maxLength * n}, key, x[n])\n\t\tVPTEST(ones, x[n])\n\t\tvar target string\n\t\tif n == 0 {\n\t\t\ttarget = \"done\"\n\t\t} else {\n\t\t\ttarget = fmt.Sprintf(\"found%d\", n)\n\t\t}\n\t\tJCS(LabelRef(target))\n\t}\n\n\t// Advance and loop again.\n\tADDQ(Imm(unroll), i)\n\tADDQ(Imm(unroll*maxLength), keyset)\n\tJMP(LabelRef(\"bigloop\"))\n\n\t// Loop over the remaining keys.\n\tLabel(\"loop\")\n\tCMPQ(i, count)\n\tJE(LabelRef(\"done\"))\n\n\t// Try to match against the input key.\n\tmatch := XMM()\n\tVPCMPEQB(Mem{Base: keyset}, key, match)\n\tVPTEST(ones, match)\n\tJCS(LabelRef(\"done\"))\n\n\t// Advance and loop again.\n\tLabel(\"next\")\n\tINCQ(i)\n\tADDQ(Imm(maxLength), keyset)\n\tJMP(LabelRef(\"loop\"))\n\tJMP(LabelRef(\"done\"))\n\n\t// Return the loop increment, or the count if the key wasn't found. If we're\n\t// here from a jump within the big loop, the loop increment needs\n\t// correcting first.\n\tfor j := unroll - 1; j > 0; j-- {\n\t\tLabel(fmt.Sprintf(\"found%d\", j))\n\t\tINCQ(i)\n\t}\n\tLabel(\"done\")\n\tStore(i, ReturnIndex(0))\n\tRET()\n\tLabel(\"not_found\")\n\tStore(count, ReturnIndex(0))\n\tRET()\n\n\t// If the input key is near a page boundary, we must change the way we load\n\t// it to avoid a fault. We instead want to load the 16 bytes up to and\n\t// including the key, then shuffle the key forward in the register. E.g. for\n\t// key \"foo\" we would load the 13 bytes prior to the key along with \"foo\"\n\t// and then move the last 3 bytes forward so the first 3 bytes are equal\n\t// to \"foo\".\n\tLabel(\"safe_load\")\n\tpageOffset := GP64()\n\tMOVQ(keyPtr, pageOffset)\n\tANDQ(U32(pageSize-1), pageOffset)\n\tCMPQ(pageOffset, U32(pageSize-maxLength))\n\tJBE(LabelRef(\"load\")) // Not near a page boundary.\n\toffset := GP64()\n\tMOVQ(^U64(0)-maxLength+1, offset)\n\tADDQ(keyLen, offset)\n\tVMOVUPS(Mem{Base: keyPtr, Index: offset, Scale: 1}, key)\n\tvar shuffleBytes [maxLength * 2]byte\n\tfor j := 0; j < maxLength; j++ {\n\t\tshuffleBytes[j] = byte(j)\n\t\tshuffleBytes[j+maxLength] = byte(j)\n\t}\n\tshuffleMasks := ConstBytes(\"shuffle_masks\", shuffleBytes[:])\n\tshuffleMasksPtr := GP64()\n\tLEAQ(shuffleMasks.Offset(maxLength), shuffleMasksPtr)\n\tSUBQ(keyLen, shuffleMasksPtr)\n\tshuffle := XMM()\n\tVMOVUPS(Mem{Base: shuffleMasksPtr}, shuffle)\n\tVPSHUFB(shuffle, key, key)\n\tJMP(LabelRef(\"prepare\"))\n}", "func Lookup(key string) RunnerFunc {\n\tv, ok := runners.Load(key)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn v.(RunnerFunc)\n}", "func Lookup(v interface{}) (string, error) {\n\tvar mac net.HardwareAddr\n\tswitch v.(type) {\n\tcase string:\n\t\tvar err error\n\t\tmac, err = net.ParseMAC(v.(string))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\tcase net.HardwareAddr:\n\t\tmac = v.(net.HardwareAddr)\n\tdefault:\n\t\treturn \"\", errCannotResolveType\n\t}\n\n\tprefix := mac[:3].String()\n\tif val, ok := mapping[strings.ToLower(prefix)]; ok {\n\t\treturn val, nil\n\t}\n\n\treturn \"\", nil\n}", "func (r *Ring) Get(key string) (interface{}, error) {\n\thashed := hash(key)\n\ta := r.bst.findNextGreater(hashed)\n\n\tif a == nil {\n\t\ta = r.bst.findPrevSmaller(hashed)\n\t\tif a == nil {\n\t\t\treturn nil, errorsNoNodeAssigned\n\t\t}\n\t}\n\treturn a.val, nil\n}", "func (r *Router) Lookup(method, path string) (Handle, Params, bool) {\n\tif root := r.trees[method]; root != nil {\n\t\treturn root.getValue(path)\n\t}\n\treturn nil, nil, false\n}", "func Lookup(opts []map[string]interface{}, key string) (interface{}, bool) {\n\tif len(opts) == 0 {\n\t\treturn nil, false\n\t}\n\tv, ok := opts[0][key]\n\treturn v, ok\n}", "func (dc *DigestCache) Lookup(hash []byte) []byte {\n\tif r, ok := dc.Records[string(hash)]; ok {\n\t\treturn r\n\t}\n\treturn nil\n}", "func (c *rPathCacheContainer) lookup(cPath string) ([]byte, string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tif cPath == c.cPath {\n\t\t// hit\n\t\treturn c.dirIV, c.pPath\n\t}\n\t// miss\n\treturn nil, \"\"\n}", "func (c *K8sConfig) Lookup() (string, error) {\n\treturn \"\", nil\n}", "func (s STags) Lookup(tag string, fields ...string) (value string, ok bool) {\n\tvalue, ok = s.get(tag, fields...)\n\treturn\n}", "func (ds *RegularStateMachineWrapper) Lookup(query interface{}) (interface{}, error) {\n\tds.mu.RLock()\n\tif ds.Destroyed() {\n\t\tds.mu.RUnlock()\n\t\treturn nil, rsm.ErrClusterClosed\n\t}\n\tds.ensureNotDestroyed()\n\tvar dp *C.uchar\n\tdata := query.([]byte)\n\tif len(data) > 0 {\n\t\tdp = (*C.uchar)(unsafe.Pointer(&data[0]))\n\t}\n\tr := C.LookupDBRegularStateMachine(ds.dataStore, dp, C.size_t(len(data)))\n\tresult := C.GoBytes(unsafe.Pointer(r.result), C.int(r.size))\n\tC.FreeLookupResultDBRegularStateMachine(ds.dataStore, r)\n\tds.mu.RUnlock()\n\treturn result, nil\n}", "func (me *TrieNode) match(searchKey *TrieKey, prematchedBits uint) *TrieNode {\n\tif me == nil {\n\t\treturn nil\n\t}\n\n\tnodeKey := &me.TrieKey\n\tif searchKey.Length < nodeKey.Length {\n\t\treturn nil\n\t}\n\n\tmatches, exact, _, child := contains(nodeKey, searchKey, prematchedBits)\n\tif !matches {\n\t\treturn nil\n\t}\n\n\tif !exact {\n\t\tif better := me.children[child].match(searchKey, me.TrieKey.Length); better != nil {\n\t\t\treturn better\n\t\t}\n\t}\n\n\tif !me.isActive {\n\t\treturn nil\n\t}\n\n\treturn me\n}", "func (cp Pack) Lookup(accountID string) (bool, Account) {\n\tfor _, c := range cp {\n\t\tfound, account := c.Lookup(accountID)\n\t\tif found {\n\t\t\treturn true, account\n\t\t}\n\t}\n\treturn false, Account{}\n}", "func (hn *HeadNode) Get(key interface{}) Node {\n\tcur := hn.head\n\ti := hn.level\n\tfor ; i >= 0; i-- {\n\t\tfor cur.index[i] != nil {\n\t\t\tres := cur.index[i].Node.Compare(key)\n\t\t\tif res == 0 {\n\t\t\t\treturn cur.index[i].Node\n\t\t\t}\n\t\t\tif res > 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcur = cur.index[i]\n\t\t}\n\t}\n\n\treturn nil\n}", "func (dir HgmDir) Lookup(ctx context.Context, name string) (fs.Node, error) {\n\tlocalDirent := dir.localDir + name // dirs are ending with a slash -> just append the name\n\ta := fuse.Attr{}\n\td := HgmDir{hgmFs: dir.hgmFs, localDir: localDirent}\n\terr := d.Attr(ctx, &a)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif (a.Mode & os.ModeType) == os.ModeDir {\n\t\treturn HgmDir{hgmFs: dir.hgmFs, localDir: localDirent + \"/\"}, nil\n\t}\n\n\treturn &HgmFile{hgmFs: dir.hgmFs, localFile: localDirent, fileSize: a.Size}, nil\n}", "func (k *Kubernetes) Lookup(ctx context.Context, state request.Request, name string, typ uint16) (*dns.Msg, error) {\n\treturn k.Upstream.Lookup(ctx, state, name, typ)\n}", "func (n *Node) search(key interface{}) interface{} {\n\tif n.key == key {\n\t\treturn n.value\n\t}\n\tif n.parent != nil {\n\t\treturn n.parent.search(key)\n\t}\n\treturn nil\n}", "func (a *addrBook) Lookup(addr peer.ID) *addrInfo {\n\ta.mu.Lock()\n\td := a.lookup(addr)\n\ta.mu.Unlock()\n\tif d == nil {\n\t\treturn nil\n\t}\n\treturn d.Addr\n}", "func (t *BPTree) FindLeaf(key []byte) *Node {\n\tvar (\n\t\ti int\n\t\tcurr *Node\n\t)\n\n\tif curr = t.root; curr == nil {\n\t\treturn nil\n\t}\n\n\tfor !curr.isLeaf {\n\t\ti = 0\n\t\tfor i < curr.KeysNum {\n\t\t\tif compare(key, curr.Keys[i]) >= 0 {\n\t\t\t\ti++\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tcurr = curr.pointers[i].(*Node)\n\t}\n\n\treturn curr\n}", "func (me *TrieNode) Match(searchKey *TrieKey) *TrieNode {\n\tif searchKey == nil {\n\t\treturn nil\n\t}\n\n\treturn me.match(searchKey, 0)\n}", "func (s *OnDiskStateMachine) Lookup(query interface{}) (interface{}, error) {\n\tif !s.opened {\n\t\tpanic(\"Lookup called when not opened\")\n\t}\n\treturn s.sm.Lookup(query)\n}", "func (m *Map) Get(key string) string {\n\tif m.IsEmpty() {\n\t\treturn \"\"\n\t}\n\n\thash := int(m.hash([]byte(key)))\n\n\t// Binary search for appropriate replica.\n\tidx := sort.Search(len(m.keys), func(i int) bool { return m.keys[i] >= hash })\n\n\t// Means we have cycled back to the first replica.\n\tif idx == len(m.keys) {\n\t\tidx = 0\n\t}\n\n\treturn m.hashMap[m.keys[idx]]\n}", "func (n *Node) Find(key string) (*models.Node, error) {\n\treturn n.locate(key)\n}", "func (idx *Autoincrement) Lookup(v string) ([]string, error) {\n\tsearchPath := path.Join(idx.indexRootDir, v)\n\toldname, err := idx.resolveSymlink(searchPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\terr = &idxerrs.NotFoundErr{TypeName: idx.typeName, Key: idx.indexBy, Value: v}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn []string{oldname}, nil\n}", "func (st *SlimTrie) Get(key string) (eqVal interface{}, found bool) {\n\n\tvar word byte\n\tfound = false\n\teqID := int32(0)\n\n\t// string to 4-bit words\n\tlenWords := 2 * len(key)\n\n\tfor idx := -1; ; {\n\n\t\tbm, rank, hasInner := st.Children.GetWithRank(eqID)\n\t\tif !hasInner {\n\t\t\t// maybe a leaf\n\t\t\tbreak\n\t\t}\n\n\t\tstep, foundstep := st.Steps.Get(eqID)\n\t\tif foundstep {\n\t\t\tidx += int(step)\n\t\t} else {\n\t\t\tidx++\n\t\t}\n\n\t\tif lenWords < idx {\n\t\t\teqID = -1\n\t\t\tbreak\n\t\t}\n\n\t\tif lenWords == idx {\n\t\t\tbreak\n\t\t}\n\n\t\t// Get a 4-bit word from 8-bit words.\n\t\t// Use arithmetic to avoid branch missing.\n\t\tshift := 4 - (idx&1)*4\n\t\tword = ((key[idx>>1] >> uint(shift)) & 0x0f)\n\n\t\tbb := uint64(1) << word\n\t\tif bm&bb != 0 {\n\t\t\tchNum := bits.OnesCount64(bm & (bb - 1))\n\t\t\teqID = rank + 1 + int32(chNum)\n\t\t} else {\n\t\t\teqID = -1\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif eqID != -1 {\n\t\teqVal, found = st.Leaves.Get(eqID)\n\t}\n\n\treturn\n}" ]
[ "0.7312577", "0.6867788", "0.67531496", "0.66930187", "0.6563972", "0.65171254", "0.6340757", "0.6298961", "0.6256727", "0.62558097", "0.62538916", "0.62538916", "0.620855", "0.6186282", "0.6181887", "0.6181399", "0.6107317", "0.604099", "0.6003605", "0.59408414", "0.5936815", "0.5936815", "0.59334886", "0.590152", "0.5883462", "0.5864607", "0.5850694", "0.5848856", "0.58375883", "0.582397", "0.5816233", "0.5808625", "0.5805167", "0.57813513", "0.57684875", "0.5767798", "0.57656485", "0.5759458", "0.5754472", "0.5753552", "0.57394576", "0.57230276", "0.5718752", "0.5716651", "0.57038283", "0.57013804", "0.5690619", "0.56743187", "0.5643223", "0.563531", "0.56294787", "0.55806464", "0.5579579", "0.5572696", "0.5570859", "0.5567992", "0.5560135", "0.555318", "0.5491949", "0.5490443", "0.5482548", "0.5480296", "0.5459823", "0.5457323", "0.54440534", "0.5440358", "0.5439992", "0.5428018", "0.5426149", "0.5411596", "0.54109645", "0.53948814", "0.53927493", "0.53755534", "0.5358964", "0.5351192", "0.53495073", "0.5347141", "0.5343852", "0.5341529", "0.5336694", "0.5333052", "0.5332568", "0.53266543", "0.53209925", "0.5317021", "0.5312736", "0.5307742", "0.5279498", "0.5273901", "0.52713335", "0.5270792", "0.5269433", "0.5267101", "0.5261817", "0.5258235", "0.52561265", "0.52535915", "0.5252206", "0.5251905" ]
0.6672378
4
PrepareUpdate reserves an allocator and uses it to prepare an update operation. See Allocator.PrepareUpdate for details
func (idx *Tree) PrepareUpdate(key []byte) (found bool, op *UpdateOperation) { id := idx.allocatorQueue.get() op = newUpdateOperation(idx, idx.allocators[id], true) return op.prepareUpdate(key), op }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *Table) PrepareUpdate(tu fibdef.Update) (*UpdateCommand, error) {\n\tu := &UpdateCommand{}\n\tu.real.RealUpdate = tu.Real()\n\tu.virt.VirtUpdate = tu.Virt()\n\n\tu.allocSplit = u.real.prepare(t)\n\tu.allocated = make([]*Entry, u.allocSplit+u.virt.prepare(t))\n\tif e := t.allocBulk(u.allocated); e != nil {\n\t\treturn nil, e\n\t}\n\n\treturn u, nil\n}", "func AllocateUpdate() int {\n\tupdateIdGen++\n\treturn updateIdGen\n}", "func (m *MockAllocStateUpdater) Update(alloc *structs.Allocation) {\n\tm.mu.Lock()\n\tm.Allocs = append(m.Allocs, alloc)\n\tm.mu.Unlock()\n}", "func (s DirectorBindStatusStrategy) PrepareForUpdate(ctx request.Context, obj, old runtime.Object) {\n\ts.DefaultStatusStorageStrategy.PrepareForUpdate(ctx, obj, old)\n\tdNew := obj.(*bind.DirectorBind)\n\tlabels := dNew.GetObjectMeta().GetLabels()\n\tif labels == nil {\n\t\tlabels = make(map[string]string)\n\t\tdNew.GetObjectMeta().SetLabels(labels)\n\t}\n\tlabels[\"state\"] = dNew.Status.State\n}", "func (detailsStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewBuild := obj.(*buildapi.Build)\n\toldBuild := old.(*buildapi.Build)\n\n\t// ignore phase updates unless the caller is updating the build to\n\t// a completed phase.\n\tphase := oldBuild.Status.Phase\n\tstages := newBuild.Status.Stages\n\tif buildinternalhelpers.IsBuildComplete(newBuild) {\n\t\tphase = newBuild.Status.Phase\n\t}\n\trevision := newBuild.Spec.Revision\n\tmessage := newBuild.Status.Message\n\treason := newBuild.Status.Reason\n\toutputTo := newBuild.Status.Output.To\n\t*newBuild = *oldBuild\n\tnewBuild.Status.Phase = phase\n\tnewBuild.Status.Stages = stages\n\tnewBuild.Spec.Revision = revision\n\tnewBuild.Status.Reason = reason\n\tnewBuild.Status.Message = message\n\tnewBuild.Status.Output.To = outputTo\n}", "func (b *AllocUpdateBatcher) CreateUpdate(allocs map[string]*structs.DesiredTransition, eval *structs.Evaluation) *BatchFuture {\n\twrapper := &updateWrapper{\n\t\tallocs: allocs,\n\t\te: eval,\n\t\tf: make(chan *BatchFuture, 1),\n\t}\n\n\tb.workCh <- wrapper\n\treturn <-wrapper.f\n}", "func (s *ReleaseServer) prepareUpdate(req *services.UpdateReleaseRequest) (*release.Release, *release.Release, error) {\n\tif req.Chart == nil {\n\t\treturn nil, nil, errMissingChart\n\t}\n\n\t// finds the deployed release with the given name\n\tcurrentRelease, err := s.env.Releases.Deployed(req.Name)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// determine if values will be reused\n\tif err := s.reuseValues(req, currentRelease); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// finds the non-deleted release with the given name\n\tlastRelease, err := s.env.Releases.Last(req.Name)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Increment revision count. This is passed to templates, and also stored on\n\t// the release object.\n\trevision := lastRelease.Version + 1\n\n\tts := timeconv.Now()\n\toptions := chartutil.ReleaseOptions{\n\t\tName: req.Name,\n\t\tTime: ts,\n\t\tNamespace: currentRelease.Namespace,\n\t\tIsUpgrade: true,\n\t\tRevision: int(revision),\n\t}\n\n\tcaps, err := capabilities(s.clientset.Discovery())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tvaluesToRender, err := chartutil.ToRenderValuesCaps(req.Chart, req.Values, options, caps)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\thooks, manifestDoc, notesTxt, err := s.renderResources(req.Chart, valuesToRender, caps.APIVersions)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Store an updated release.\n\tupdatedRelease := &release.Release{\n\t\tName: req.Name,\n\t\tNamespace: currentRelease.Namespace,\n\t\tChart: req.Chart,\n\t\tConfig: req.Values,\n\t\tInfo: &release.Info{\n\t\t\tFirstDeployed: currentRelease.Info.FirstDeployed,\n\t\t\tLastDeployed: ts,\n\t\t\tStatus: &release.Status{Code: release.Status_PENDING_UPGRADE},\n\t\t\tDescription: \"Preparing upgrade\", // This should be overwritten later.\n\t\t},\n\t\tVersion: revision,\n\t\tManifest: manifestDoc.String(),\n\t\tHooks: hooks,\n\t}\n\n\tif len(notesTxt) > 0 {\n\t\tupdatedRelease.Info.Status.Notes = notesTxt\n\t}\n\terr = validateManifest(s.env.KubeClient, currentRelease.Namespace, manifestDoc.Bytes())\n\treturn currentRelease, updatedRelease, err\n}", "func (podPresetStrategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) {\n\tnewPodPreset := obj.(*settings.PodPreset)\n\toldPodPreset := old.(*settings.PodPreset)\n\n\t// Update is not allowed\n\tnewPodPreset.Spec = oldPodPreset.Spec\n}", "func (endpointSliceStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewEPS := obj.(*discovery.EndpointSlice)\n\toldEPS := old.(*discovery.EndpointSlice)\n\n\t// Increment generation if anything other than meta changed\n\t// This needs to be changed if a status attribute is added to EndpointSlice\n\togNewMeta := newEPS.ObjectMeta\n\togOldMeta := oldEPS.ObjectMeta\n\tnewEPS.ObjectMeta = v1.ObjectMeta{}\n\toldEPS.ObjectMeta = v1.ObjectMeta{}\n\n\tif !apiequality.Semantic.DeepEqual(newEPS, oldEPS) {\n\t\togNewMeta.Generation = ogOldMeta.Generation + 1\n\t}\n\n\tnewEPS.ObjectMeta = ogNewMeta\n\toldEPS.ObjectMeta = ogOldMeta\n\n\tdropDisabledConditionsOnUpdate(oldEPS, newEPS)\n}", "func (sc *schedulerCache) updateQuotaAllocator(oldQuotaAllocator, newQuotaAllocator *arbv1.QuotaAllocator) error {\n\tif err := sc.deleteQuotaAllocator(oldQuotaAllocator); err != nil {\n\t\treturn err\n\t}\n\tsc.addQuotaAllocator(newQuotaAllocator)\n\treturn nil\n}", "func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewBuild := obj.(*buildapi.Build)\n\toldBuild := old.(*buildapi.Build)\n\t// If the build is already in a failed state, do not allow an update\n\t// of the reason and message. This is to prevent the build controller from\n\t// overwriting the reason and message that was set by the builder pod\n\t// when it updated the build's details.\n\t// Only allow OOMKilled override because various processes in a container\n\t// can get OOMKilled and this confuses builder to prematurely populate\n\t// failure reason\n\tif oldBuild.Status.Phase == buildapi.BuildPhaseFailed &&\n\t\tnewBuild.Status.Reason != buildapi.StatusReasonOutOfMemoryKilled {\n\t\tnewBuild.Status.Reason = oldBuild.Status.Reason\n\t\tnewBuild.Status.Message = oldBuild.Status.Message\n\t}\n}", "func (rh *ReservationHelper) Update(ctx context.Context) error {\n\tlogger := util.AddCommonFields(ctx, rh.logger, \"ReservationHelper.update\")\n\tvar err error\n\trh.acList, err = rh.capReader.ReadCapacity(ctx)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to read AC list: %s\", err.Error())\n\t\treturn err\n\t}\n\trh.acrList, err = rh.resReader.ReadReservations(ctx)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to read ACR list: %s\", err.Error())\n\t\treturn err\n\t}\n\trh.acMap = buildACMap(rh.acList)\n\trh.acrMap, rh.acNameToACR = buildACRMaps(rh.acrList)\n\n\trh.updated = true\n\n\treturn nil\n}", "func (accountStrategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) {\n}", "func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\t_ = obj.(*authorizationapi.RoleBindingRestriction)\n\t_ = old.(*authorizationapi.RoleBindingRestriction)\n}", "func (client *CapacityReservationsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservationUpdate, options *CapacityReservationsBeginUpdateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif capacityReservationGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter capacityReservationGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{capacityReservationGroupName}\", url.PathEscape(capacityReservationGroupName))\n\tif capacityReservationName == \"\" {\n\t\treturn nil, errors.New(\"parameter capacityReservationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{capacityReservationName}\", url.PathEscape(capacityReservationName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, parameters)\n}", "func (idx *Tree) PrepareDelete(key []byte) (found bool, op *DeleteOperation) {\n\tid := idx.allocatorQueue.get()\n\top = newDeleteOperation(idx, idx.allocators[id], true)\n\tif op.prepare(key) {\n\t\treturn true, op\n\t}\n\top.Abort()\n\treturn false, nil\n}", "func NewAllocUpdateBatcher(ctx context.Context, batchDuration time.Duration, raft DeploymentRaftEndpoints) *AllocUpdateBatcher {\n\tb := &AllocUpdateBatcher{\n\t\tbatch: batchDuration,\n\t\traft: raft,\n\t\tctx: ctx,\n\t\tworkCh: make(chan *updateWrapper, 10),\n\t}\n\n\tgo b.batcher()\n\treturn b\n}", "func (client *CapacitiesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, dedicatedCapacityName string, capacityUpdateParameters DedicatedCapacityUpdateParameters, options *CapacitiesClientBeginUpdateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif dedicatedCapacityName == \"\" {\n\t\treturn nil, errors.New(\"parameter dedicatedCapacityName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{dedicatedCapacityName}\", url.PathEscape(dedicatedCapacityName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-01-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, runtime.MarshalAsJSON(req, capacityUpdateParameters)\n}", "func (client QuotaRequestClient) UpdatePreparer(ctx context.Context, subscriptionID string, providerID string, location string, resourceName string, createQuotaRequest CurrentQuotaLimitBase, ifMatch string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"location\": autorest.Encode(\"path\", location),\n\t\t\"providerId\": autorest.Encode(\"path\", providerID),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", subscriptionID),\n\t}\n\n\tconst APIVersion = \"2019-07-19-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}\", pathParameters),\n\t\tautorest.WithJSON(createQuotaRequest),\n\t\tautorest.WithQueryParameters(queryParameters),\n\t\tautorest.WithHeader(\"If-Match\", autorest.String(ifMatch)))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (b *CompactableBuffer) Update(address *EntryAddress, data []byte) error {\n\taddress.LockForWrite()\n\tdefer address.UnlockWrite()\n\theader, err := b.ReadHeader(address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbeforeUpdataDataSize := header.dataSize\n\tafterUpdateDataSize := len(data) + VarIntSize(len(data))\n\tdataSizeDelta := afterUpdateDataSize - int(beforeUpdataDataSize)\n\n\tremainingSpace := int(header.entrySize) - reservedSize - afterUpdateDataSize\n\theader.dataSize = int64(afterUpdateDataSize)\n\tif remainingSpace <= 0 {\n\t\tatomic.AddInt64(&b.dataSize, int64(-beforeUpdataDataSize))\n\t\tatomic.AddInt64(&b.entrySize, int64(-header.entrySize))\n\t\treturn b.expand(address, data)\n\t}\n\n\tatomic.AddInt64(&b.dataSize, int64(dataSizeDelta))\n\tvar target = make([]byte, 0)\n\tAppendToBytes(data, &target)\n\tif len(target) > int(header.dataSize) {\n\t\treturn io.EOF\n\t}\n\twritableBuffer := b.writableBuffer()\n\t_, err = writableBuffer.Write(address.Position()+reservedSize, target...)\n\treturn err\n}", "func NewUpdate(zone string, class uint16) *Msg {\n\tu := new(Msg)\n\tu.MsgHdr.Response = false\n\tu.MsgHdr.Opcode = OpcodeUpdate\n\tu.Compress = false // Seems BIND9 at least cannot handle compressed update pkgs\n\tu.Question = make([]Question, 1)\n\tu.Question[0] = Question{zone, TypeSOA, class}\n\treturn u\n}", "func (vc *VehicleContainer) Prepare(apiEntries []*APIVehicleEntry) error {\n\ttimezone, err := time.LoadLocation(\"Europe/Warsaw\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvc.Vehicles = make(map[string]*Vehicle, len(apiEntries))\n\n\tfor _, ae := range apiEntries {\n\t\tv, err := NewVehicle(ae, timezone)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvc.Vehicles[v.ID] = v\n\t}\n\n\treturn nil\n}", "func (sb *spdkBackend) Prepare(req storage.BdevPrepareRequest) (*storage.BdevPrepareResponse, error) {\n\tsb.log.Debugf(\"spdk backend prepare (script call): %+v\", req)\n\treturn sb.prepare(req, DetectVMD, cleanHugepages)\n}", "func (t *Table) DiscardUpdate(u *UpdateCommand) {\n\tif u.allocated != nil {\n\t\tmempool.Free(t.mp, u.allocated)\n\t}\n\tu.clear()\n}", "func (e *UpdateExec) prepare(row []types.Datum) (err error) {\n\tif e.updatedRowKeys == nil {\n\t\te.updatedRowKeys = make(map[int]*kv.MemAwareHandleMap[bool])\n\t}\n\te.handles = e.handles[:0]\n\te.tableUpdatable = e.tableUpdatable[:0]\n\te.changed = e.changed[:0]\n\te.matches = e.matches[:0]\n\tfor _, content := range e.tblColPosInfos {\n\t\tif e.updatedRowKeys[content.Start] == nil {\n\t\t\te.updatedRowKeys[content.Start] = kv.NewMemAwareHandleMap[bool]()\n\t\t}\n\t\thandle, err := content.HandleCols.BuildHandleByDatums(row)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\te.handles = append(e.handles, handle)\n\n\t\tupdatable := false\n\t\tflags := e.assignFlag[content.Start:content.End]\n\t\tfor _, flag := range flags {\n\t\t\tif flag >= 0 {\n\t\t\t\tupdatable = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif unmatchedOuterRow(content, row) {\n\t\t\tupdatable = false\n\t\t}\n\t\te.tableUpdatable = append(e.tableUpdatable, updatable)\n\n\t\tchanged, ok := e.updatedRowKeys[content.Start].Get(handle)\n\t\tif ok {\n\t\t\te.changed = append(e.changed, changed)\n\t\t\te.matches = append(e.matches, false)\n\t\t} else {\n\t\t\te.changed = append(e.changed, false)\n\t\t\te.matches = append(e.matches, true)\n\t\t}\n\t}\n\treturn nil\n}", "func (client AccountClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, body AccountResourcePatchDescription) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPatch(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}\",pathParameters),\nautorest.WithJSON(body),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (n *NodeBlockMaker) doPrepareNewBlock() error {\n\t// firstly, check count of transactions to know if there are enough\n\tcount, err := n.getTransactionsManager().GetUnapprovedCount()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tmin, max, err := n.getTransactionNumbersLimits(nil)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn.Logger.Trace.Printf(\"Minting: Found %d transaction from minimum %d\\n\", count, min)\n\n\tif count >= min {\n\t\t// number of transactions is fine\n\t\tif count > max {\n\t\t\tcount = max\n\t\t}\n\t\t// get unapproved transactions\n\t\ttxs, err := n.getTransactionsManager().GetUnapprovedTransactionsForNewBlock(count)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(txs) < min {\n\t\t\treturn errors.New(\"No enought valid transactions! Waiting for new ones...\")\n\t\t}\n\n\t\tn.Logger.Trace.Printf(\"Minting: All good. New block assigned to address %s\\n\", n.MinterAddress)\n\n\t\tnewBlock, err := n.makeNewBlockFromTransactions(txs)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tn.Logger.Trace.Printf(\"Minting: New block Prepared. Not yet complete\\n\")\n\n\t\tn.PreparedBlock = newBlock\n\n\t}\n\n\treturn nil\n}", "func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewRole := obj.(*rbac.Role)\n\toldRole := old.(*rbac.Role)\n\n\t_, _ = newRole, oldRole\n}", "func (_RandomBeacon *RandomBeaconTransactor) UpdateAuthorizationParameters(opts *bind.TransactOpts, _minimumAuthorization *big.Int, _authorizationDecreaseDelay uint64, _authorizationDecreaseChangePeriod uint64) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"updateAuthorizationParameters\", _minimumAuthorization, _authorizationDecreaseDelay, _authorizationDecreaseChangePeriod)\n}", "func (c *HardwareConfig) Prepare() []error {\n\tvar errs []error\n\n\tif c.RAMReservation > 0 && c.RAMReserveAll != false {\n\t\terrs = append(errs, fmt.Errorf(\"'RAM_reservation' and 'RAM_reserve_all' cannot be used together\"))\n\t}\n\n\treturn errs\n}", "func PrepareDBSweep() error {\n\tif !isDBInit {\n\t\tisDBInit = true\n\t\tdbInit <- 1\n\t}\n\treturn nil\n}", "func (c *Command) Prepare() {}", "func (client VersionsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, templateSpecName string, templateSpecVersion string, templateSpecVersionUpdateModel *VersionUpdateModel) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t\t\"templateSpecName\": autorest.Encode(\"path\", templateSpecName),\n\t\t\"templateSpecVersion\": autorest.Encode(\"path\", templateSpecVersion),\n\t}\n\n\tconst APIVersion = \"2019-06-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Resources/templateSpecs/{templateSpecName}/versions/{templateSpecVersion}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\tif templateSpecVersionUpdateModel != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(templateSpecVersionUpdateModel))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (cr *cmdRunner) prep(req storage.ScmPrepareRequest, scanRes *storage.ScmScanResponse) (resp *storage.ScmPrepareResponse, err error) {\n\tstate := scanRes.State\n\tresp = &storage.ScmPrepareResponse{State: state}\n\n\tcr.log.Debugf(\"scm backend prep: state %q\", state)\n\n\tif err = cr.deleteGoals(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Handle unspecified NrNamespacesPerSocket in request.\n\tif req.NrNamespacesPerSocket == 0 {\n\t\treq.NrNamespacesPerSocket = minNrNssPerSocket\n\t}\n\n\tswitch state {\n\tcase storage.ScmStateNotInterleaved:\n\t\t// Non-interleaved AppDirect memory mode is unsupported.\n\t\terr = storage.FaultScmNotInterleaved\n\tcase storage.ScmStateNoRegions:\n\t\t// No regions exist, create interleaved AppDirect PMem regions.\n\t\tif err = cr.createRegions(); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tresp.RebootRequired = true\n\tcase storage.ScmStateFreeCapacity:\n\t\t// Regions exist but no namespaces, create block devices on PMem regions.\n\t\tresp.Namespaces, err = cr.createNamespaces(req.NrNamespacesPerSocket)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tresp.State = storage.ScmStateNoFreeCapacity\n\tcase storage.ScmStateNoFreeCapacity:\n\t\t// Regions and namespaces exist so sanity check number of namespaces matches the\n\t\t// number requested before returning details.\n\t\tvar regionFreeBytes []uint64\n\t\tregionFreeBytes, err = cr.getRegionFreeSpace()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tnrRegions := uint(len(regionFreeBytes))\n\t\tnrNamespaces := uint(len(scanRes.Namespaces))\n\n\t\t// Assume 1:1 mapping between region and NUMA node.\n\t\tif (nrRegions * req.NrNamespacesPerSocket) != nrNamespaces {\n\t\t\terr = storage.FaultScmNamespacesNrMismatch(req.NrNamespacesPerSocket,\n\t\t\t\tnrRegions, nrNamespaces)\n\t\t\tbreak\n\t\t}\n\t\tresp.Namespaces = scanRes.Namespaces\n\tdefault:\n\t\terr = errors.Errorf(\"unhandled scm state %q\", state)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n\tif mb.resourceCapacity < rm.Resource().Attributes().Len() {\n\t\tmb.resourceCapacity = rm.Resource().Attributes().Len()\n\t}\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n\tif mb.resourceCapacity < rm.Resource().Attributes().Len() {\n\t\tmb.resourceCapacity = rm.Resource().Attributes().Len()\n\t}\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n\tif mb.resourceCapacity < rm.Resource().Attributes().Len() {\n\t\tmb.resourceCapacity = rm.Resource().Attributes().Len()\n\t}\n}", "func (sb *spdkBackend) prepare(req storage.BdevPrepareRequest, vmdDetect vmdDetectFn, hpClean hpCleanFn) (*storage.BdevPrepareResponse, error) {\n\tresp := &storage.BdevPrepareResponse{}\n\n\tif req.CleanHugepagesOnly {\n\t\t// Remove hugepages that were created by a no-longer-active SPDK process. Note that\n\t\t// when running prepare, it's unlikely that any SPDK processes are active as this\n\t\t// is performed prior to starting engines.\n\t\tnrRemoved, err := hpClean(sb.log, hugepageDir)\n\t\tif err != nil {\n\t\t\treturn resp, errors.Wrapf(err, \"clean spdk hugepages\")\n\t\t}\n\t\tresp.NrHugepagesRemoved = nrRemoved\n\n\t\tlogNUMAStats(sb.log)\n\n\t\treturn resp, nil\n\t}\n\n\t// Update request if VMD has been explicitly enabled and there are VMD endpoints configured.\n\tif err := updatePrepareRequest(sb.log, &req, vmdDetect); err != nil {\n\t\treturn resp, errors.Wrapf(err, \"update prepare request\")\n\t}\n\tresp.VMDPrepared = req.EnableVMD\n\n\t// Before preparing, reset device bindings.\n\tif req.EnableVMD {\n\t\t// Unbind devices to speed up VMD re-binding as per\n\t\t// https://github.com/spdk/spdk/commit/b0aba3fcd5aceceea530a702922153bc75664978.\n\t\t//\n\t\t// Applies block (not allow) list if VMD is configured so specific NVMe devices can\n\t\t// be reserved for other use (bdev_exclude).\n\t\tif err := sb.script.Unbind(&req); err != nil {\n\t\t\treturn resp, errors.Wrap(err, \"un-binding devices\")\n\t\t}\n\t} else {\n\t\tif err := sb.script.Reset(&req); err != nil {\n\t\t\treturn resp, errors.Wrap(err, \"resetting device bindings\")\n\t\t}\n\t}\n\n\treturn resp, errors.Wrap(sb.script.Prepare(&req), \"binding devices to userspace drivers\")\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupTransactor) UpdateRequest(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BaseAccessControlGroup.contract.Transact(opts, \"updateRequest\")\n}", "func (p *Preparer) Prepare(fullInfo chan resource.Resource, done chan bool, mapWg *sync.WaitGroup) {\n\tmapWg.Wait()\n\n\tvar wg sync.WaitGroup\n\n\tidentifierSend := false\n\n\tfor data := range fullInfo {\n\t\tif !identifierSend {\n\t\t\terr := p.prep.SendIdentifier()\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(log.Fields{\"error\": err}).Fatal(\"error send identifier\")\n\t\t\t}\n\t\t\tidentifierSend = true\n\t\t}\n\t\twg.Add(1)\n\t\tgo p.prep.Preparation(data, &wg)\n\t}\n\n\twg.Wait()\n\n\t// If the identifier was not sent, there is no resource to prepare and send,\n\t// a gRPC connection was not open and no finishing and closing of a connection are needed.\n\tif identifierSend {\n\t\tp.prep.Finish()\n\t}\n\n\tdone <- true\n}", "func (c *AgonesDiscoverAllocator) Allocate(ctx context.Context, req *pb.AssignTicketsRequest) error {\n\tlogger := runtime.Logger().WithField(\"component\", \"allocator\")\n\n\tfor _, assignmentGroup := range req.Assignments {\n\t\tif err := IsAssignmentGroupValidForAllocation(assignmentGroup); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfilter, err := extensions.ExtractFilterFromExtensions(assignmentGroup.Assignment.Extensions)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"the assignment does not have a valid filter extension\")\n\t\t}\n\n\t\tgameservers, err := c.ListGameServers(ctx, filter)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\tif len(gameservers) == 0 {\n\t\t\tlogger.Debugf(\"gameservers not found for request with filter %v\", filter.Map())\n\t\t\tcontinue\n\t\t}\n\n\t\t// NiceToHave: Filter GameServers by Capacity and Count\n\t\t// Remove not assigned tickets based on playersCapacity - Count\n\t\t// strategy: allTogether, CapacityBased FallBack\n\t\tfor _, gs := range gameservers {\n\t\t\tif HasCapacity(assignmentGroup, gs) {\n\t\t\t\tassignmentGroup.Assignment.Connection = gs.Status.Address\n\t\t\t\t//logger.Debugf(\"extension %v\", assignmentGroup.Assignment.Extensions)\n\t\t\t\tlogger.Infof(\"gameserver %s connection %s assigned to request, total tickets: %d\", gs.Name, assignmentGroup.Assignment.Connection, len(assignmentGroup.TicketIds))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (client DeploymentsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, deploymentResource DeploymentResource) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}\", pathParameters),\n\t\tautorest.WithJSON(deploymentResource),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func InitAllocator(addr uint32) {\n\t// Warning: Lot of unsafe pointer usage and manipulation ahead.\n\t// This function basically initializes memory at given address, so that\n\t// _buddyAllocator, and it's members, point to this address.\n\n\t// create freeBuddiesList\n\tvar _freeBuddiesList *[MaxOrder + 1]freeBuddiesList\n\t_freeBuddiesList = (*[MaxOrder + 1]freeBuddiesList)(pointer.Get(addr))\n\taddr += (MaxOrder + 1) * uint32(unsafe.Sizeof(freeBuddiesList{}))\n\n\t// set freeBuddiesList in buddyAllocator\n\t_buddyAllocator.buddies = (*_freeBuddiesList)[:MaxOrder+1]\n\n\t// create bigPagesBitmap\n\t// _nBigPages size for array is way more than needed. this is done since\n\t// array sizes need to be constant.\n\tvar _bigPagesBitmap *[_nBigPages]uint32\n\t_bigPagesBitmap = (*[_nBigPages]uint32)(pointer.Get(addr))\n\taddr += nMaps(_nBigPages) * 4\n\n\t// set bigPagesBitmap in buddyAllocator\n\t_buddyAllocator.buddies[MaxOrder].freeMap.maps = (*_bigPagesBitmap)[:nMaps(_nBigPages)]\n\n\t// mark all big pages as free\n\tfor i := uint32(0); i < nMaps(_nBigPages); i++ {\n\t\t_buddyAllocator.buddies[MaxOrder].freeMap.maps[i] = _allSet\n\t}\n\n\t// create the individual freeBuddiesList\n\tfor i := 0; i < MaxOrder; i++ {\n\t\t// maxOrder - 1 pages of order i, further divide by 2 since we use 1 bit\n\t\t// for buddy pair.\n\t\tvar nBuddies uint32 = _nBigPages * (1 << uint32(MaxOrder-i-1))\n\t\tnMaps := nMaps(nBuddies)\n\n\t\t// set address for this freeBuddiesList\n\t\t// we are addressing way more memory than needed, because array sizes need\n\t\t// to be constant. this will be more than enough for largest freeBuddiesList\n\t\tvar maps *[_nBigPages * _nBigPages]uint32\n\t\tmaps = (*[_nBigPages * _nBigPages]uint32)(pointer.Get(addr))\n\t\taddr += nMaps * 4\n\n\t\t// set the freeBuddiesList\n\t\t_buddyAllocator.buddies[i].freeMap.maps = (*maps)[:nMaps]\n\n\t\t// zero out the freeBuddiesList\n\t\tfor j := uint32(0); j < nMaps; j++ {\n\t\t\t_buddyAllocator.buddies[i].freeMap.maps[j] = 0\n\t\t}\n\t}\n\n\tinitNodePool(addr)\n}", "func (s *BasevhdlListener) EnterAllocator(ctx *AllocatorContext) {}", "func (client AccountQuotaPolicyClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, policyName string, body AccountQuotaPolicyResourcePatchDescription) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"policyName\": policyName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPatch(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/accountQuotaPolicies/{policyName}\",pathParameters),\nautorest.WithJSON(body),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (_RandomBeacon *RandomBeaconTransactorSession) UpdateAuthorizationParameters(_minimumAuthorization *big.Int, _authorizationDecreaseDelay uint64, _authorizationDecreaseChangePeriod uint64) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.UpdateAuthorizationParameters(&_RandomBeacon.TransactOpts, _minimumAuthorization, _authorizationDecreaseDelay, _authorizationDecreaseChangePeriod)\n}", "func Enqueue(update *update.UpdateEntry) {\n\tif update.SeqId==0 {\n\t\tupdate.SeqId=AllocateUpdate()\n\t}\n\tcurrentQueue[update.SeqId]=update\n}", "func (_Container *ContainerTransactor) UpdateRequest(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Container.contract.Transact(opts, \"updateRequest\")\n}", "func (d *DataBuckets) Prepare() {\n}", "func (a *Agent) PreUpdate(s gorp.SqlExecutor) error {\n\ta.Updated = time.Now()\n\treturn nil\n}", "func (txmgr *LockBasedTxMgr) ValidateAndPrepare(blockAndPvtdata *ledger.BlockAndPvtData, doMVCCValidation bool) (\n\t[]*validation.AppInitiatedPurgeUpdate, []*validation.TxStatInfo, []byte, error,\n) {\n\t// Among ValidateAndPrepare(), PrepareForExpiringKeys(), and\n\t// RemoveStaleAndCommitPvtDataOfOldBlocks(), we can allow only one\n\t// function to execute at a time. The reason is that each function calls\n\t// LoadCommittedVersions() which would clear the existing entries in the\n\t// transient buffer and load new entries (such a transient buffer is not\n\t// applicable for the golevelDB). As a result, these three functions can\n\t// interleave and nullify the optimization provided by the bulk read API.\n\t// Once the ledger cache (FAB-103) is introduced and existing\n\t// LoadCommittedVersions() is refactored to return a map, we can allow\n\t// these three functions to execute parallelly.\n\tlogger.Debugf(\"Waiting for purge mgr to finish the background job of computing expirying keys for the block\")\n\ttxmgr.pvtdataPurgeMgr.WaitForPrepareToFinish()\n\ttxmgr.oldBlockCommit.Lock()\n\tdefer txmgr.oldBlockCommit.Unlock()\n\tlogger.Debug(\"lock acquired on oldBlockCommit for validating read set version against the committed version\")\n\n\tblock := blockAndPvtdata.Block\n\tlogger.Debugf(\"Validating new block with num trans = [%d]\", len(block.Data.Data))\n\tbatch, appPurgeUpdates, txstatsInfo, err := txmgr.commitBatchPreparer.ValidateAndPrepareBatch(blockAndPvtdata, doMVCCValidation)\n\tif err != nil {\n\t\ttxmgr.reset()\n\t\treturn nil, nil, nil, err\n\t}\n\ttxmgr.currentUpdates = &currentUpdates{block: block, batch: batch}\n\tif err := txmgr.invokeNamespaceListeners(); err != nil {\n\t\ttxmgr.reset()\n\t\treturn nil, nil, nil, err\n\t}\n\n\tupdateBytes, err := deterministicBytesForPubAndHashUpdates(batch)\n\treturn appPurgeUpdates, txstatsInfo, updateBytes, err\n}", "func (l *blocksLRU) prepareForAdd() {\n\tswitch {\n\tcase l.ll.Len() > l.capacity:\n\t\tpanic(\"impossible\")\n\tcase l.ll.Len() == l.capacity:\n\t\toldest := l.ll.Remove(l.ll.Back()).(block)\n\t\tdelete(l.blocks, oldest.offset)\n\t\tl.evicted(oldest)\n\t}\n}", "func assembleAssetUpdate(curr, update *BaseAsset) {\n\tfor currK, currV := range curr.Data {\n\t\t// Do not update field in `update` asset from `curr` asset\n\t\tif _, ok := update.Data[currK]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tupdate.Data[currK] = currV\n\t}\n}", "func (action *ActionLocationNetworkCreate) Prepare() *ActionLocationNetworkCreateInvocation {\n\treturn &ActionLocationNetworkCreateInvocation{\n\t\tAction: action,\n\t\tPath: \"/v6.0/location_networks\",\n\t}\n}", "func TestAllocRunner_TerminalUpdate_Destroy(t *testing.T) {\n\tci.Parallel(t)\n\talloc := mock.BatchAlloc()\n\ttr := alloc.AllocatedResources.Tasks[alloc.Job.TaskGroups[0].Tasks[0].Name]\n\talloc.Job.TaskGroups[0].RestartPolicy.Attempts = 0\n\talloc.Job.TaskGroups[0].Tasks[0].RestartPolicy.Attempts = 0\n\t// Ensure task takes some time\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Driver = \"mock_driver\"\n\ttask.Config[\"run_for\"] = \"10s\"\n\talloc.AllocatedResources.Tasks[task.Name] = tr\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tdefer destroy(ar)\n\tgo ar.Run()\n\tupd := conf.StateUpdater.(*MockStateUpdater)\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\t\tif last.ClientStatus != structs.AllocClientStatusRunning {\n\t\t\treturn false, fmt.Errorf(\"got status %v; want %v\", last.ClientStatus, structs.AllocClientStatusRunning)\n\t\t}\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n\n\t// Update the alloc to be terminal which should cause the alloc runner to\n\t// stop the tasks and wait for a destroy.\n\tupdate := ar.alloc.Copy()\n\tupdate.DesiredStatus = structs.AllocDesiredStatusStop\n\tar.Update(update)\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\n\t\t// Check the status has changed.\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got client status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\t// Check the alloc directory still exists\n\t\tif _, err := os.Stat(ar.allocDir.AllocDir); err != nil {\n\t\t\treturn false, fmt.Errorf(\"alloc dir destroyed: %v\", ar.allocDir.AllocDir)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n\n\t// Send the destroy signal and ensure the AllocRunner cleans up.\n\tar.Destroy()\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\n\t\t// Check the status has changed.\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got client status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\t// Check the alloc directory was cleaned\n\t\tif _, err := os.Stat(ar.allocDir.AllocDir); err == nil {\n\t\t\treturn false, fmt.Errorf(\"alloc dir still exists: %v\", ar.allocDir.AllocDir)\n\t\t} else if !os.IsNotExist(err) {\n\t\t\treturn false, fmt.Errorf(\"stat err: %v\", err)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n}", "func (cr *cmdRunner) prepReset(scanRes *storage.ScmScanResponse) (*storage.ScmPrepareResponse, error) {\n\tstate := scanRes.State\n\tresp := &storage.ScmPrepareResponse{State: state}\n\n\tcr.log.Debugf(\"scm backend prep reset: state %q\", state)\n\n\tif err := cr.deleteGoals(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch state {\n\tcase storage.ScmStateNoRegions:\n\t\treturn resp, nil\n\tcase storage.ScmStateFreeCapacity, storage.ScmStateNoFreeCapacity, storage.ScmStateNotInterleaved:\n\t\t// Continue to remove namespaces and regions.\n\t\tresp.RebootRequired = true\n\tdefault:\n\t\treturn nil, errors.Errorf(\"unhandled scm state %q\", state)\n\t}\n\n\tfor _, dev := range scanRes.Namespaces {\n\t\tif err := cr.removeNamespace(dev.Name); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcr.log.Infof(\"Resetting PMem memory allocations.\")\n\n\tif err := cr.removeRegions(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (h *HTTPTester) Prepare(stmt string, bSz int, tx bool) error {\n\ts := make([]string, bSz)\n\tfor i := 0; i < len(s); i++ {\n\t\ts[i] = stmt\n\t}\n\n\tb, err := json.Marshal(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\th.br = bytes.NewReader(b)\n\n\tif tx {\n\t\th.url = h.url + \"?transaction\"\n\t}\n\n\treturn nil\n}", "func (p *PetsEquipmentsetEntries) Prepare() {\n}", "func (_Mcapscontroller *McapscontrollerTransactor) UpdateMinimumBalance(opts *bind.TransactOpts, pool common.Address, tokenAddress common.Address) (*types.Transaction, error) {\n\treturn _Mcapscontroller.contract.Transact(opts, \"updateMinimumBalance\", pool, tokenAddress)\n}", "func execPrepareStmt(prepStmt string) {\n\tif db == nil {\n\t\tdb = getDB()\n\t}\n\n\tstmt, err := db.Prepare(prepStmt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t_, err = stmt.Exec()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (client ReferenceDataSetsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, environmentName string, referenceDataSetName string, referenceDataSetUpdateParameters ReferenceDataSetUpdateParameters) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"environmentName\": autorest.Encode(\"path\", environmentName),\n\t\t\"referenceDataSetName\": autorest.Encode(\"path\", referenceDataSetName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-05-15\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TimeSeriesInsights/environments/{environmentName}/referenceDataSets/{referenceDataSetName}\", pathParameters),\n\t\tautorest.WithJSON(referenceDataSetUpdateParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client WorkloadNetworksClient) UpdateSegmentsPreparer(ctx context.Context, resourceGroupName string, privateCloudName string, segmentID string, workloadNetworkSegment WorkloadNetworkSegment) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"privateCloudName\": autorest.Encode(\"path\", privateCloudName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"segmentId\": autorest.Encode(\"path\", segmentID),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-07-17-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/workloadNetworks/default/segments/{segmentId}\", pathParameters),\n\t\tautorest.WithJSON(workloadNetworkSegment),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}", "func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}", "func (p *pod) preparePodUpdateMessage(msgText string) string {\n\t// Handle simple message replacements.\n\treplacements := map[string]string{\n\t\t\"pod triggered scale-up\": \"Job requires additional resources, scaling up cluster.\",\n\t\t\"Successfully assigned\": \"Pod resources allocated.\",\n\t\t\"skip schedule deleting pod\": \"Deleting unscheduled pod.\",\n\t}\n\n\tsimpleReplacement := false\n\n\tfor k, v := range replacements {\n\t\tmatched, err := regexp.MatchString(k, msgText)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t} else if matched {\n\t\t\tmsgText = v\n\t\t\tsimpleReplacement = true\n\t\t}\n\t}\n\n\t// Otherwise, try special treatment for slots availability message.\n\tif !simpleReplacement {\n\t\tmatched, err := regexp.MatchString(\"nodes are available\", msgText)\n\t\tif err == nil && matched {\n\t\t\tavailable := string(msgText[0])\n\t\t\trequired := strconv.Itoa(p.slots)\n\t\t\tvar resourceName string\n\t\t\tswitch p.slotType {\n\t\t\tcase device.CPU:\n\t\t\t\tresourceName = \"CPU slots\"\n\t\t\tdefault:\n\t\t\t\tresourceName = \"GPUs\"\n\t\t\t}\n\n\t\t\tmsgText = fmt.Sprintf(\"Waiting for resources. %s %s are available, %s %s required\",\n\t\t\t\tavailable, resourceName, required, resourceName)\n\t\t}\n\t}\n\n\treturn msgText\n}", "func (oo *OnuDeviceEntry) PrepareForGarbageCollection(ctx context.Context, aDeviceID string) {\n\tlogger.Debugw(ctx, \"prepare for garbage collection\", log.Fields{\"device-id\": aDeviceID})\n\too.baseDeviceHandler = nil\n\too.pOnuTP = nil\n\tif oo.PDevOmciCC != nil {\n\t\too.PDevOmciCC.PrepareForGarbageCollection(ctx, aDeviceID)\n\t}\n\too.PDevOmciCC = nil\n}", "func NewUpdateDeviceRequest(d *v1alpha2.Device) *packngo.DeviceUpdateRequest {\n\treturn &packngo.DeviceUpdateRequest{\n\t\tHostname: d.Spec.ForProvider.Hostname,\n\t\tLocked: d.Spec.ForProvider.Locked,\n\t\tUserData: d.Spec.ForProvider.UserData,\n\t\tIPXEScriptURL: d.Spec.ForProvider.IPXEScriptURL,\n\t\tAlwaysPXE: d.Spec.ForProvider.AlwaysPXE,\n\t\tTags: &d.Spec.ForProvider.Tags,\n\t\tDescription: d.Spec.ForProvider.Description,\n\t\tCustomData: d.Spec.ForProvider.CustomData,\n\t}\n}", "func (i *Installer) Prepare(d Device) error {\n\t// Sanity check inputs.\n\tif i.config == nil {\n\t\treturn fmt.Errorf(\"installer missing config: %w\", errConfig)\n\t}\n\tif i.config.ImageFile() == \"\" {\n\t\treturn fmt.Errorf(\"missing image: %w\", errInput)\n\t}\n\text := regExFileExt.FindString(i.config.ImageFile())\n\tif ext == \"\" {\n\t\treturn fmt.Errorf(\"could not find extension for %q: %w\", i.config.ImageFile(), errFile)\n\t}\n\tf, err := os.Stat(filepath.Join(i.cache, i.config.ImageFile()))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%v: %w\", err, errPath)\n\t}\n\t// Compensate for very small image files that can cause the wrong partition\n\t// to be selected.\n\tsize := uint64(f.Size())\n\tif size < oneGB {\n\t\tsize = oneGB\n\t}\n\t// Prepare the devices for provisioning.\n\tswitch {\n\tcase ext == \".iso\" && i.config.UpdateOnly():\n\t\treturn i.prepareForISOWithoutElevation(d, size)\n\tcase ext == \".iso\":\n\t\treturn i.prepareForISOWithElevation(d, size)\n\tcase ext == \".img\":\n\t\treturn i.prepareForRaw(d)\n\t}\n\treturn fmt.Errorf(\"%q is not a supported image type: %w\", ext, errProvision)\n}", "func (b *mpgBuff) Prepare() {\n\tcap := b.BufferSize()\n\t// ensure capacity is divisible by 4\n\tcap += cap % 4\n\t// make sure we have an even cap value\n\tcap += (cap % 2)\n\t// get individual buffer length\n\tl := cap / 2\n\tb.eof = false\n\t// make and initialize buffers\n\tb.bufA = &concBuff{\n\t\tdata: make([]byte, l)}\n\tb.fill(b.bufA)\n\tb.bufB = &concBuff{\n\t\tdata: make([]byte, l)}\n\tb.fill(b.bufB)\n}", "func (s *PBFTServer) PrePrepare(args PrePrepareArgs, reply *PrePrepareReply) error {\n\t// Verify message signature and digest\n\n\ts.lock.Lock()\n\n\ts.stopTimer()\n\n\tif !s.changing && s.view == args.View && s.h <= args.Seq && args.Seq < s.H {\n\t\tUtil.Dprintf(\"%s[R/PrePrepare]:Args:%+v\", s, args)\n\n\t\tent := s.getEntry(entryID{args.View, args.Seq})\n\t\ts.lock.Unlock()\n\n\t\tent.lock.Lock()\n\t\tif ent.pp == nil || (ent.pp.Digest == args.Digest && ent.pp.Seq == args.Seq) {\n\t\t\tpArgs := PrepareArgs{\n\t\t\t\tView: args.View,\n\t\t\t\tSeq: args.Seq,\n\t\t\t\tDigest: args.Digest,\n\t\t\t\tRid: s.id,\n\t\t\t}\n\t\t\tent.pp = &args\n\n\t\t\tUtil.Dprintf(\"%s[B/Prepare]:Args:%+v\", s, pArgs)\n\n\t\t\ts.broadcast(false, true, \"PBFTServer.Prepare\", pArgs, &PrepareReply{})\n\t\t}\n\t\tent.lock.Unlock()\n\t} else {\n\t\ts.lock.Unlock()\n\t}\n\n\treturn nil\n}", "func (consensus *Consensus) Prepare(chain ChainReader, header *types.Header) error {\n\t// TODO: implement prepare method\n\treturn nil\n}", "func (cs *ChatServer) Updatecapacity() {\n\tcs.capacity = cs.cpus - cs.rooms\n}", "func (client MSIXPackagesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, hostPoolName string, msixPackageFullName string, msixPackage *MSIXPackagePatch) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostPoolName\": autorest.Encode(\"path\", hostPoolName),\n\t\t\"msixPackageFullName\": autorest.Encode(\"path\", msixPackageFullName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-09-21-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/msixPackages/{msixPackageFullName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\tif msixPackage != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(msixPackage))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client CertificateOrdersClient) UpdateCertificateOrderPreparer(ctx context.Context, resourceGroupName string, name string, certificateDistinguishedName CertificateOrder) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2015-08-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CertificateRegistration/certificateOrders/{name}\", pathParameters),\n\t\tautorest.WithJSON(certificateDistinguishedName),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (e *engineImpl) Prepare(chain engine.ChainReader, header *block.Header) error {\n\t// TODO: implement prepare method\n\treturn nil\n}", "func (client *DiskEncryptionSetsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSetUpdate, options *DiskEncryptionSetsBeginUpdateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif diskEncryptionSetName == \"\" {\n\t\treturn nil, errors.New(\"parameter diskEncryptionSetName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{diskEncryptionSetName}\", url.PathEscape(diskEncryptionSetName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-04-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, diskEncryptionSet)\n}", "func (p *preImpl) Prepare(ctx context.Context, s *testing.State) interface{} {\n\tctx, st := timing.Start(ctx, \"prepare_\"+p.name)\n\tdefer st.End()\n\n\tif p.arc != nil {\n\t\tpre, err := func() (interface{}, error) {\n\t\t\tctx, cancel := context.WithTimeout(ctx, resetTimeout)\n\t\t\tdefer cancel()\n\t\t\tctx, st := timing.Start(ctx, \"reset_\"+p.name)\n\t\t\tdefer st.End()\n\t\t\tpkgs, err := p.installedPackages(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to get installed packages\")\n\t\t\t}\n\t\t\tif err := p.checkUsable(ctx, pkgs); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"existing Chrome or ARC connection is unusable\")\n\t\t\t}\n\t\t\tif err := p.resetState(ctx, pkgs); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed resetting existing Chrome or ARC session\")\n\t\t\t}\n\t\t\tif err := p.arc.setLogcatFile(filepath.Join(s.OutDir(), logcatName)); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to update logcat output file\")\n\t\t\t}\n\t\t\treturn PreData{p.cr, p.arc}, nil\n\t\t}()\n\t\tif err == nil {\n\t\t\ts.Log(\"Reusing existing ARC session\")\n\t\t\treturn pre\n\t\t}\n\t\ts.Log(\"Failed to reuse existing ARC session: \", err)\n\t\tlocked = false\n\t\tchrome.Unlock()\n\t\tp.closeInternal(ctx, s)\n\t}\n\n\t// Revert partial initialization.\n\tshouldClose := true\n\tdefer func() {\n\t\tif shouldClose {\n\t\t\tp.closeInternal(ctx, s)\n\t\t}\n\t}()\n\n\tfunc() {\n\t\tctx, cancel := context.WithTimeout(ctx, chrome.LoginTimeout)\n\t\tdefer cancel()\n\t\tvar err error\n\t\tif p.cr, err = chrome.New(ctx, chrome.ARCEnabled()); err != nil {\n\t\t\ts.Fatal(\"Failed to start Chrome: \", err)\n\t\t}\n\t}()\n\n\tfunc() {\n\t\tctx, cancel := context.WithTimeout(ctx, BootTimeout)\n\t\tdefer cancel()\n\t\tvar err error\n\t\tif p.arc, err = New(ctx, s.OutDir()); err != nil {\n\t\t\ts.Fatal(\"Failed to start ARC: \", err)\n\t\t}\n\t\tif p.origInitPID, err = InitPID(); err != nil {\n\t\t\ts.Fatal(\"Failed to get initial init PID: \", err)\n\t\t}\n\t\tif p.origPackages, err = p.installedPackages(ctx); err != nil {\n\t\t\ts.Fatal(\"Failed to list initial packages: \", err)\n\t\t}\n\t}()\n\n\t// Prevent the arc and chrome package's New and Close functions from\n\t// being called while this precondition is active.\n\tlocked = true\n\tchrome.Lock()\n\n\tshouldClose = false\n\treturn PreData{p.cr, p.arc}\n}", "func (client CertificateClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, certificateName string, parameters CertificateCreateOrUpdateParameters, ifMatch string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"accountName\": autorest.Encode(\"path\", accountName),\n\t\t\"certificateName\": autorest.Encode(\"path\", certificateName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2018-12-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\tif len(ifMatch) > 0 {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithHeader(\"If-Match\", autorest.String(ifMatch)))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (action *ActionVpsFeatureUpdateAll) Prepare() *ActionVpsFeatureUpdateAllInvocation {\n\treturn &ActionVpsFeatureUpdateAllInvocation{\n\t\tAction: action,\n\t\tPath: \"/v6.0/vpses/{vps_id}/features/update_all\",\n\t}\n}", "func (_RandomBeacon *RandomBeaconSession) UpdateAuthorizationParameters(_minimumAuthorization *big.Int, _authorizationDecreaseDelay uint64, _authorizationDecreaseChangePeriod uint64) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.UpdateAuthorizationParameters(&_RandomBeacon.TransactOpts, _minimumAuthorization, _authorizationDecreaseDelay, _authorizationDecreaseChangePeriod)\n}", "func NewContractPrepareCmd(client ioctl.Client) *cobra.Command {\n\tshort, _ := client.SelectTranslation(_prepareCmdShorts)\n\n\treturn &cobra.Command{\n\t\tUse: \"prepare\",\n\t\tShort: short,\n\t\tArgs: cobra.ExactArgs(0),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcmd.SilenceUsage = true\n\t\t\t_, err := util.SolidityVersion(_solCompiler)\n\t\t\tif err != nil {\n\t\t\t\tcmdString := \"curl --silent https://raw.githubusercontent.com/iotexproject/iotex-core/master/install-solc.sh | sh\"\n\t\t\t\tinstallCmd := exec.Command(\"bash\", \"-c\", cmdString)\n\t\t\t\tcmd.Println(\"Preparing solidity compiler ...\")\n\n\t\t\t\terr = installCmd.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"failed to prepare solc\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tsolc, err := util.SolidityVersion(_solCompiler)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"solidity compiler not ready\")\n\t\t\t}\n\t\t\tif !checkCompilerVersion(solc) {\n\t\t\t\treturn errors.Errorf(\"unsupported solc version %d.%d.%d, expects solc version 0.8.17\\n\",\n\t\t\t\t\tsolc.Major, solc.Minor, solc.Patch)\n\t\t\t}\n\n\t\t\tcmd.Println(\"Solidity compiler is ready now.\")\n\t\t\treturn nil\n\t\t},\n\t}\n}", "func (action *ActionMailTemplateTranslationUpdate) Prepare() *ActionMailTemplateTranslationUpdateInvocation {\n\treturn &ActionMailTemplateTranslationUpdateInvocation{\n\t\tAction: action,\n\t\tPath: \"/v6.0/mail_templates/{mail_template_id}/translations/{translation_id}\",\n\t}\n}", "func (_RandomBeacon *RandomBeaconTransactor) UpdateRewardParameters(opts *bind.TransactOpts, sortitionPoolRewardsBanDuration *big.Int, relayEntryTimeoutNotificationRewardMultiplier *big.Int, unauthorizedSigningNotificationRewardMultiplier *big.Int, dkgMaliciousResultNotificationRewardMultiplier *big.Int) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"updateRewardParameters\", sortitionPoolRewardsBanDuration, relayEntryTimeoutNotificationRewardMultiplier, unauthorizedSigningNotificationRewardMultiplier, dkgMaliciousResultNotificationRewardMultiplier)\n}", "func NewUpdateDeviceRequest(d *v1alpha1.Device) *packngo.DeviceUpdateRequest {\n\treturn &packngo.DeviceUpdateRequest{\n\t\tHostname: &d.Spec.ForProvider.Hostname,\n\t\tLocked: &d.Spec.ForProvider.Locked,\n\t\tUserData: &d.Spec.ForProvider.UserData,\n\t\tIPXEScriptURL: &d.Spec.ForProvider.IPXEScriptURL,\n\t\tAlwaysPXE: &d.Spec.ForProvider.AlwaysPXE,\n\t\tTags: &d.Spec.ForProvider.Tags,\n\t}\n}", "func (dl *DrawList) PrimReserve(idxCount, vtxCount int) {\n\tif sz, require := len(dl.VtxBuffer), dl.vtxIndex+vtxCount; require >= sz {\n\t\tvtxBuffer := make([]DrawVert, sz+1024)\n\t\tcopy(vtxBuffer, dl.VtxBuffer)\n\t\tdl.VtxBuffer = vtxBuffer\n\t}\n\tif sz, require := len(dl.IdxBuffer), dl.idxIndex+idxCount; require >= sz {\n\t\tidxBuffer := make([]DrawIdx, sz+1024)\n\t\tcopy(idxBuffer, dl.IdxBuffer)\n\t\tdl.IdxBuffer = idxBuffer\n\t}\n\tdl.VtxWriter = dl.VtxBuffer[dl.vtxIndex:dl.vtxIndex+vtxCount]\n\tdl.IdxWriter = dl.IdxBuffer[dl.idxIndex:dl.idxIndex+idxCount]\n}", "func NewUpdateStatement(keyspace, table string, fieldMap map[string]interface{}, rel []Relation, keys Keys) (UpdateStatement, error) {\n\tstmt := UpdateStatement{}\n\tif keyspace == \"\" || table == \"\" {\n\t\treturn stmt, fmt.Errorf(\"keyspace and table can't be empty\")\n\t}\n\n\tif len(fieldMap) < 1 {\n\t\treturn stmt, fmt.Errorf(\"fieldMap must be a map fields to insert\")\n\t}\n\n\tif len(rel) < 1 {\n\t\treturn stmt, fmt.Errorf(\"must supply at least one relation WHERE clause\")\n\t}\n\n\tif len(keys.PartitionKeys) == 0 {\n\t\treturn stmt, fmt.Errorf(\"partition key should be supplied\")\n\t}\n\n\tstmt.keyspace = keyspace\n\tstmt.table = table\n\tstmt.fieldMap = fieldMap\n\tstmt.where = rel\n\tstmt.keys = keys\n\treturn stmt, nil\n}", "func Prepare(p Preparer, query string) (st *sql.Stmt, err error) {\n\tst, err = p.Prepare(query)\n\terr = interpretError(err)\n\treturn\n}", "func (client *DedicatedHostsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHostUpdate, options *DedicatedHostsBeginUpdateOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{hostGroupName}\", url.PathEscape(hostGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{hostName}\", url.PathEscape(hostName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := azcore.NewRequest(ctx, http.MethodPatch, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2020-06-01\")\n\treq.URL.RawQuery = query.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, req.MarshalAsJSON(parameters)\n}", "func (px *Paxos) Prepare(args *PrepareArgs, reply *PrepareReply) error {\n\tif args.PNum > px.APp[args.Seq] {\n\t\t// prepare request with higher Proposal Number\n\t\tpx.APp[args.Seq] = args.PNum\n\t\treply.Err = OK\n\t\treply.Proposal = px.APa[args.Seq]\n\t} else {\n\t\t// Already promised to Proposal with a higher Proposal Number\n\t\treply.Err = Reject\n\t\treply.Proposal = Proposal{px.APp[args.Seq], nil}\n\t}\n\treturn nil\n}", "func (sc *schedulerCache) addQuotaAllocator(quotaAllocator *arbv1.QuotaAllocator) error {\n\tif _, ok := sc.quotaAllocators[quotaAllocator.Name]; ok {\n\t\treturn fmt.Errorf(\"quotaAllocator %v exist\", quotaAllocator.Name)\n\t}\n\n\tinfo := &QuotaAllocatorInfo{\n\t\tname: quotaAllocator.Name,\n\t\tquotaAllocator: quotaAllocator.DeepCopy(),\n\t\tPods: make([]*v1.Pod, 0),\n\t}\n\n\t// init Request if it is nil\n\tif info.QuotaAllocator().Spec.Request.Resources == nil {\n\t\tinfo.QuotaAllocator().Spec.Request.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\n\t// init Deserved/Allocated/Used/Preemping if it is nil\n\tif info.QuotaAllocator().Status.Deserved.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Deserved.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Allocated.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Allocated.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Used.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Used.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tif info.QuotaAllocator().Status.Preempting.Resources == nil {\n\t\tinfo.QuotaAllocator().Status.Preempting.Resources = map[arbv1.ResourceName]resource.Quantity{\n\t\t\t\"cpu\": resource.MustParse(\"0\"),\n\t\t\t\"memory\": resource.MustParse(\"0\"),\n\t\t}\n\t}\n\tsc.quotaAllocators[quotaAllocator.Name] = info\n\treturn nil\n}", "func (out *OutBuffer) Prepare(size int) {\n\tif out.Data == nil {\n\t\tout.pos = 0\n\t\tout.Data = globalPool.GetOutDataBuffer(size)\n\t}\n\n\tpos := out.pos\n\n\tif cap(out.Data)-pos < size {\n\t\tdata := globalPool.GetOutDataBuffer(pos + size)\n\t\tif out.pos > 0 && len(out.Data) > 0 {\n\t\t\tcopy(data, out.Data[0:out.pos])\n\t\t}\n\t\toldData := out.Data\n\t\tglobalPool.PutOutDataBuffer(oldData)\n\t\tout.Data = data\n\t} else {\n\t\tout.Data = out.Data[0 : pos+size]\n\t}\n}", "func (client ServicesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPatch(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}\", pathParameters),\n\t\tautorest.WithJSON(resource),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *mockSpdkNvme) Update(pciAddr string, path string, slot int32) (\n\t[]Controller, []Namespace, error) {\n\n\tfor i, ctrlr := range m.initCtrlrs {\n\t\tif ctrlr.PCIAddr == pciAddr && m.updateRet == nil {\n\t\t\tm.initCtrlrs[i].FWRev = m.fwRevAfter\n\t\t}\n\t}\n\n\treturn m.initCtrlrs, m.initNss, m.updateRet\n}", "func Prepare() error {\n\n\t// log.Println(\"Preparing work...\")\n\n\t// commands := [][]string{\n\t// \t[]string{\"yum\", \"update\", \"-y\"},\n\t// \t[]string{\"yum\", \"install\", \"-y\", \"docker\"},\n\t// \t[]string{\"service\", \"docker\", \"start\"},\n\t// \t[]string{\"docker\", \"pull\", \"tnolet/scraper:0.1.0\"},\n\t// }\n\n\t// for _, command := range commands {\n\t// \tout, err := exec.Command(command).Output()\n\n\t// \tif err != nil {\n\t// \t\tlog.Printf(\"Prepare command unsuccessful: %v, %v\", err.Error(), out)\n\t// \t\treturn err\n\t// \t}\n\n\t// \tlog.Printf(\"Succesfully executed preparation: %v\", out)\n\t// }\n\treturn nil\n\n}", "func (h *consulGRPCSocketHook) Update(req *interfaces.RunnerUpdateRequest) error {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\th.alloc = req.Alloc\n\n\tif !h.shouldRun() {\n\t\treturn nil\n\t}\n\n\treturn h.proxy.run(h.alloc)\n}", "func (db *DB) Prepare(query string) (Stmt, error) {\n\tstmts := make([]*sql.Stmt, len(db.cpdbs))\n\n\terr := scatter(len(db.cpdbs), func(i int) (err error) {\n\t\tstmts[i], err = db.cpdbs[i].db.Prepare(query)\n\t\treturn errors.WithStack(err)\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &stmt{db: db, stmts: stmts}, nil\n}", "func NewUpdateParamsCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"update [change-file]\",\n\t\tShort: \"UpdateValidator params\",\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclientCtx, err := client.GetClientTxContext(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tchanges, _ := utils.ParseParamChange(clientCtx.LegacyAmino, args[0])\n\n\t\t\tmsg := types.NewMsgUpdateParams(\n\t\t\t\tchanges.ToParamChanges(),\n\t\t\t\tclientCtx.GetFromAddress(),\n\t\t\t)\n\n\t\t\tif err := msg.ValidateBasic(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)\n\t\t},\n\t}\n\n\tflags.AddTxFlagsToCmd(cmd)\n\t_ = cmd.MarkFlagRequired(flags.FlagFrom)\n\n\treturn cmd\n}" ]
[ "0.7424789", "0.5677787", "0.5536896", "0.5494887", "0.53911835", "0.5362883", "0.53093344", "0.52692324", "0.5254965", "0.5247992", "0.51920253", "0.51712793", "0.5147966", "0.5011077", "0.5002912", "0.4989964", "0.48652557", "0.48066962", "0.47724175", "0.47566584", "0.47195667", "0.47023305", "0.4686456", "0.46021235", "0.46005666", "0.45783454", "0.45699158", "0.45429024", "0.45266357", "0.452046", "0.45096803", "0.4509138", "0.4507075", "0.44880393", "0.44823208", "0.44823208", "0.44823208", "0.44729355", "0.44669476", "0.44577768", "0.44483525", "0.44424304", "0.44294766", "0.44243592", "0.44024333", "0.4400741", "0.4397658", "0.43969405", "0.43892333", "0.43837065", "0.43825734", "0.43816105", "0.43787733", "0.43714362", "0.43713537", "0.43708798", "0.43707442", "0.43532276", "0.43426168", "0.4339708", "0.43373013", "0.43317693", "0.4329482", "0.4329482", "0.4329482", "0.4329482", "0.4329482", "0.43235755", "0.43149957", "0.43121323", "0.43049544", "0.43031088", "0.4302492", "0.43009222", "0.42973953", "0.42952096", "0.42874128", "0.42853817", "0.42790735", "0.42787963", "0.42745325", "0.42728996", "0.4272612", "0.42704937", "0.42694998", "0.42590466", "0.42545283", "0.4252241", "0.425063", "0.42466584", "0.42354137", "0.42345986", "0.42326608", "0.42324015", "0.42247424", "0.4223482", "0.42216295", "0.42214578", "0.42181906", "0.42166966" ]
0.75170195
0
PrepareDelete reserves an allocator and uses it to prepare a delete operation. See Allocator.PrepareDelete for details
func (idx *Tree) PrepareDelete(key []byte) (found bool, op *DeleteOperation) { id := idx.allocatorQueue.get() op = newDeleteOperation(idx, idx.allocators[id], true) if op.prepare(key) { return true, op } op.Abort() return false, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client Client) DeletePreparer(resourceGroupName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": url.QueryEscape(name),\n\t\t\"resourceGroupName\": url.QueryEscape(resourceGroupName),\n\t\t\"subscriptionId\": url.QueryEscape(client.SubscriptionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/Redis/{name}\"),\n\t\tautorest.WithPathParameters(pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n}", "func (client MeshNetworkClient) DeletePreparer(ctx context.Context, networkResourceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"networkResourceName\": networkResourceName,\n\t}\n\n\tconst APIVersion = \"6.4-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/Resources/Networks/{networkResourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client AccountClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsDelete(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (vfs *VirtualFilesystem) PrepareDeleteDentry(mntns *MountNamespace, d *Dentry) error {\n\tif checkInvariants {\n\t\tif d.parent == nil {\n\t\t\tpanic(\"d is independent\")\n\t\t}\n\t\tif d.IsDisowned() {\n\t\t\tpanic(\"d is already disowned\")\n\t\t}\n\t}\n\tvfs.mountMu.Lock()\n\tif mntns.mountpoints[d] != 0 {\n\t\tvfs.mountMu.Unlock()\n\t\treturn syserror.EBUSY\n\t}\n\td.mu.Lock()\n\tvfs.mountMu.Unlock()\n\t// Return with d.mu locked to block attempts to mount over it; it will be\n\t// unlocked by AbortDeleteDentry or CommitDeleteDentry.\n\treturn nil\n}", "func (client CertificateClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, certificateName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"accountName\": autorest.Encode(\"path\", accountName),\n\t\t\"certificateName\": autorest.Encode(\"path\", certificateName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2018-12-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *CassandraClustersClient) deallocateCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *CassandraClustersClientBeginDeallocateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/deallocate\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif clusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter clusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{clusterName}\", url.PathEscape(clusterName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-03-15-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func MakeDeleter(\n\tcodec keys.SQLCodec, tableDesc catalog.TableDescriptor, requestedCols []descpb.ColumnDescriptor,\n) Deleter {\n\tindexes := tableDesc.DeletableNonPrimaryIndexes()\n\tindexDescs := make([]descpb.IndexDescriptor, len(indexes))\n\tfor i, index := range indexes {\n\t\tindexDescs[i] = *index.IndexDesc()\n\t}\n\n\tvar fetchCols []descpb.ColumnDescriptor\n\tvar fetchColIDtoRowIndex catalog.TableColMap\n\tif requestedCols != nil {\n\t\tfetchCols = requestedCols[:len(requestedCols):len(requestedCols)]\n\t\tfetchColIDtoRowIndex = ColIDtoRowIndexFromCols(fetchCols)\n\t} else {\n\t\tmaybeAddCol := func(colID descpb.ColumnID) error {\n\t\t\tif _, ok := fetchColIDtoRowIndex.Get(colID); !ok {\n\t\t\t\tcol, err := tableDesc.FindColumnWithID(colID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfetchColIDtoRowIndex.Set(col.GetID(), len(fetchCols))\n\t\t\t\tfetchCols = append(fetchCols, *col.ColumnDesc())\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tfor j := 0; j < tableDesc.GetPrimaryIndex().NumColumns(); j++ {\n\t\t\tcolID := tableDesc.GetPrimaryIndex().GetColumnID(j)\n\t\t\tif err := maybeAddCol(colID); err != nil {\n\t\t\t\treturn Deleter{}\n\t\t\t}\n\t\t}\n\t\tfor _, index := range indexes {\n\t\t\tfor j := 0; j < index.NumColumns(); j++ {\n\t\t\t\tcolID := index.GetColumnID(j)\n\t\t\t\tif err := maybeAddCol(colID); err != nil {\n\t\t\t\t\treturn Deleter{}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// The extra columns are needed to fix #14601.\n\t\t\tfor j := 0; j < index.NumExtraColumns(); j++ {\n\t\t\t\tcolID := index.GetExtraColumnID(j)\n\t\t\t\tif err := maybeAddCol(colID); err != nil {\n\t\t\t\t\treturn Deleter{}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\trd := Deleter{\n\t\tHelper: newRowHelper(codec, tableDesc, indexDescs),\n\t\tFetchCols: fetchCols,\n\t\tFetchColIDtoRowIndex: fetchColIDtoRowIndex,\n\t}\n\n\treturn rd\n}", "func (client OpenShiftManagedClustersClient) DeletePreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": v20180930preview.APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/openShiftManagedClusters/{resourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client GroupClient) DeleteSecretPreparer(accountName string, databaseName string, secretName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"secretName\": autorest.Encode(\"path\", secretName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/secrets/{secretName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func prepareDeletecluster(params map[string]string, clusterName string, Region string) {\n\tif clusterName != \"\" {\n\t\tparams[\"clusterName\"] = clusterName\n\t}\n\tif Region != \"\" {\n\t\tparams[\"Region\"] = Region\n\t}\n\tparams[\"amztarget\"] = \"AmazonEC2ContainerServiceV20141113.DeleteCluster\"\n}", "func (oo *OmciCC) PrepareForGarbageCollection(ctx context.Context, aDeviceID string) {\n\tlogger.Debugw(ctx, \"prepare for garbage collection\", log.Fields{\"device-id\": aDeviceID})\n\too.pBaseDeviceHandler = nil\n\too.pOnuDeviceEntry = nil\n\too.pOnuAlarmManager = nil\n}", "func (client DeploymentsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"appName\": autorest.Encode(\"path\", appName),\n\t\t\"deploymentName\": autorest.Encode(\"path\", deploymentName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client StorageTargetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, cacheName string, storageTargetName string, force string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"cacheName\": autorest.Encode(\"path\", cacheName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"storageTargetName\": autorest.Encode(\"path\", storageTargetName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2021-09-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\tif len(force) > 0 {\n\t\tqueryParameters[\"force\"] = autorest.Encode(\"query\", force)\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StorageCache/caches/{cacheName}/storageTargets/{storageTargetName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ThreatIntelligenceIndicatorClient) DeletePreparer(ctx context.Context, resourceGroupName string, workspaceName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t\t\"workspaceName\": autorest.Encode(\"path\", workspaceName),\n\t}\n\n\tconst APIVersion = \"2022-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{name}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func preparedeleteserviceparams(params map[string]string, deleteservice Deleteservice, Region string) {\n\tif Region != \"\" {\n\t\tparams[\"Region\"] = Region\n\t}\n\tparams[\"amztarget\"] = \"AmazonEC2ContainerServiceV20141113.DeleteService\"\n}", "func (client HTTPSuccessClient) Delete202Preparer(booleanValue *bool) (*http.Request, error) {\n preparer := autorest.CreatePreparer(\n autorest.AsJSON(),\n autorest.AsDelete(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPath(\"/http/success/202\"))\n if booleanValue != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithJSON(booleanValue))\n }\n return preparer.Prepare(&http.Request{})\n}", "func (c SqlDedicatedGatewayClient) preparerForServiceDelete(ctx context.Context, id ServiceId) (*http.Request, error) {\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": defaultApiVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(c.baseUri),\n\t\tautorest.WithPath(id.ID()),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client DatasetClient) DeletePreparer(ctx context.Context, datasetID string) (*http.Request, error) {\n urlParameters := map[string]interface{} {\n \"geography\": autorest.Encode(\"path\",client.Geography),\n }\n\n pathParameters := map[string]interface{} {\n \"datasetId\": autorest.Encode(\"path\",datasetID),\n }\n\n const APIVersion = \"2.0\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsDelete(),\nautorest.WithCustomBaseURL(\"https://{geography}.atlas.microsoft.com\", urlParameters),\nautorest.WithPathParameters(\"/datasets/{datasetId}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (idx *Tree) PrepareUpdate(key []byte) (found bool, op *UpdateOperation) {\n\tid := idx.allocatorQueue.get()\n\top = newUpdateOperation(idx, idx.allocators[id], true)\n\treturn op.prepareUpdate(key), op\n}", "func (client DatabasesClient) DeletePreparer(resourceGroupName string, serverName string, databaseName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serverName\": autorest.Encode(\"path\", serverName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2014-04-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (oo *OnuDeviceEntry) PrepareForGarbageCollection(ctx context.Context, aDeviceID string) {\n\tlogger.Debugw(ctx, \"prepare for garbage collection\", log.Fields{\"device-id\": aDeviceID})\n\too.baseDeviceHandler = nil\n\too.pOnuTP = nil\n\tif oo.PDevOmciCC != nil {\n\t\too.PDevOmciCC.PrepareForGarbageCollection(ctx, aDeviceID)\n\t}\n\too.PDevOmciCC = nil\n}", "func (client ReferenceDataSetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, environmentName string, referenceDataSetName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"environmentName\": autorest.Encode(\"path\", environmentName),\n\t\t\"referenceDataSetName\": autorest.Encode(\"path\", referenceDataSetName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-05-15\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TimeSeriesInsights/environments/{environmentName}/referenceDataSets/{referenceDataSetName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client VersionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, templateSpecName string, templateSpecVersion string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t\t\"templateSpecName\": autorest.Encode(\"path\", templateSpecName),\n\t\t\"templateSpecVersion\": autorest.Encode(\"path\", templateSpecVersion),\n\t}\n\n\tconst APIVersion = \"2019-06-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Resources/templateSpecs/{templateSpecName}/versions/{templateSpecVersion}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client CloudEndpointsClient) DeletePreparer(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string, cloudEndpointName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"cloudEndpointName\": autorest.Encode(\"path\", cloudEndpointName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"storageSyncServiceName\": autorest.Encode(\"path\", storageSyncServiceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t\t\"syncGroupName\": autorest.Encode(\"path\", syncGroupName),\n\t}\n\n\tconst APIVersion = \"2020-03-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups/{syncGroupName}/cloudEndpoints/{cloudEndpointName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (c *Conn) Deallocate(ctx context.Context, name string) error {\n\tdelete(c.preparedStatements, name)\n\t_, err := c.pgConn.Exec(ctx, \"deallocate \"+quoteIdentifier(name)).ReadAll()\n\treturn err\n}", "func (client MSIXPackagesClient) DeletePreparer(ctx context.Context, resourceGroupName string, hostPoolName string, msixPackageFullName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"hostPoolName\": autorest.Encode(\"path\", hostPoolName),\n\t\t\"msixPackageFullName\": autorest.Encode(\"path\", msixPackageFullName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-09-21-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/msixPackages/{msixPackageFullName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ViewsClient) DeletePreparer(ctx context.Context, viewName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"viewName\": autorest.Encode(\"path\", viewName),\n\t}\n\n\tconst APIVersion = \"2019-11-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/providers/Microsoft.CostManagement/views/{viewName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *CapacityReservationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif capacityReservationGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter capacityReservationGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{capacityReservationGroupName}\", url.PathEscape(capacityReservationGroupName))\n\tif capacityReservationName == \"\" {\n\t\treturn nil, errors.New(\"parameter capacityReservationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{capacityReservationName}\", url.PathEscape(capacityReservationName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client JobClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, jobName string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"jobName\": jobName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsDelete(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/jobs/{jobName}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client IotHubResourceClient) DeletePreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-04-30-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ApplicationsClient) DeletePreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"applicationObjectId\": autorest.Encode(\"path\", applicationObjectID),\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/applications/{applicationObjectId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client ServicesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client CertificateOrdersClient) DeleteCertificateOrderPreparer(ctx context.Context, resourceGroupName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2015-08-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CertificateRegistration/certificateOrders/{name}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client CertificateOrdersClient) DeleteCertificatePreparer(ctx context.Context, resourceGroupName string, certificateOrderName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"certificateOrderName\": autorest.Encode(\"path\", certificateOrderName),\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2015-08-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CertificateRegistration/certificateOrders/{certificateOrderName}/certificates/{name}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func TestAllocRunner_Destroy(t *testing.T) {\n\tci.Parallel(t)\n\n\t// Ensure task takes some time\n\talloc := mock.BatchAlloc()\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Config[\"run_for\"] = \"10s\"\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\n\t// Use a MemDB to assert alloc state gets cleaned up\n\tconf.StateDB = state.NewMemDB(conf.Logger)\n\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tgo ar.Run()\n\n\t// Wait for alloc to be running\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tstate := ar.AllocState()\n\n\t\treturn state.ClientStatus == structs.AllocClientStatusRunning,\n\t\t\tfmt.Errorf(\"got client status %v; want running\", state.ClientStatus)\n\t}, func(err error) {\n\t\trequire.NoError(t, err)\n\t})\n\n\t// Assert state was stored\n\tls, ts, err := conf.StateDB.GetTaskRunnerState(alloc.ID, task.Name)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, ls)\n\trequire.NotNil(t, ts)\n\n\t// Now destroy\n\tar.Destroy()\n\n\tselect {\n\tcase <-ar.DestroyCh():\n\t\t// Destroyed properly!\n\tcase <-time.After(10 * time.Second):\n\t\trequire.Fail(t, \"timed out waiting for alloc to be destroyed\")\n\t}\n\n\t// Assert alloc is dead\n\tstate := ar.AllocState()\n\trequire.Equal(t, structs.AllocClientStatusComplete, state.ClientStatus)\n\n\t// Assert the state was cleaned\n\tls, ts, err = conf.StateDB.GetTaskRunnerState(alloc.ID, task.Name)\n\trequire.NoError(t, err)\n\trequire.Nil(t, ls)\n\trequire.Nil(t, ts)\n\n\t// Assert the alloc directory was cleaned\n\tif _, err := os.Stat(ar.allocDir.AllocDir); err == nil {\n\t\trequire.Fail(t, \"alloc dir still exists: %v\", ar.allocDir.AllocDir)\n\t} else if !os.IsNotExist(err) {\n\t\trequire.Failf(t, \"expected NotExist error\", \"found %v\", err)\n\t}\n}", "func (client PublishedBlueprintsClient) DeletePreparer(ctx context.Context, resourceScope string, blueprintName string, versionID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"blueprintName\": autorest.Encode(\"path\", blueprintName),\n\t\t\"resourceScope\": resourceScope,\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tconst APIVersion = \"2018-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}/versions/{versionId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client WorkloadNetworksClient) DeleteSegmentPreparer(ctx context.Context, resourceGroupName string, privateCloudName string, segmentID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"privateCloudName\": autorest.Encode(\"path\", privateCloudName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"segmentId\": autorest.Encode(\"path\", segmentID),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2020-07-17-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/workloadNetworks/default/segments/{segmentId}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (c *AgonesDiscoverAllocator) Allocate(ctx context.Context, req *pb.AssignTicketsRequest) error {\n\tlogger := runtime.Logger().WithField(\"component\", \"allocator\")\n\n\tfor _, assignmentGroup := range req.Assignments {\n\t\tif err := IsAssignmentGroupValidForAllocation(assignmentGroup); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfilter, err := extensions.ExtractFilterFromExtensions(assignmentGroup.Assignment.Extensions)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"the assignment does not have a valid filter extension\")\n\t\t}\n\n\t\tgameservers, err := c.ListGameServers(ctx, filter)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\tif len(gameservers) == 0 {\n\t\t\tlogger.Debugf(\"gameservers not found for request with filter %v\", filter.Map())\n\t\t\tcontinue\n\t\t}\n\n\t\t// NiceToHave: Filter GameServers by Capacity and Count\n\t\t// Remove not assigned tickets based on playersCapacity - Count\n\t\t// strategy: allTogether, CapacityBased FallBack\n\t\tfor _, gs := range gameservers {\n\t\t\tif HasCapacity(assignmentGroup, gs) {\n\t\t\t\tassignmentGroup.Assignment.Connection = gs.Status.Address\n\t\t\t\t//logger.Debugf(\"extension %v\", assignmentGroup.Assignment.Extensions)\n\t\t\t\tlogger.Infof(\"gameserver %s connection %s assigned to request, total tickets: %d\", gs.Name, assignmentGroup.Assignment.Connection, len(assignmentGroup.TicketIds))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (sc *schedulerCache) deleteQuotaAllocator(quotaAllocator *arbv1.QuotaAllocator) error {\n\tif _, ok := sc.quotaAllocators[quotaAllocator.Name]; !ok {\n\t\treturn fmt.Errorf(\"quotaAllocator %v doesn't exist\", quotaAllocator.Name)\n\t}\n\tdelete(sc.quotaAllocators, quotaAllocator.Name)\n\treturn nil\n}", "func (client CertificateClient) CancelDeletionPreparer(ctx context.Context, resourceGroupName string, accountName string, certificateName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"accountName\": autorest.Encode(\"path\", accountName),\n\t\t\"certificateName\": autorest.Encode(\"path\", certificateName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2018-12-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}/cancelDelete\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client FirewallPolicyRuleGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleGroupName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"firewallPolicyName\": autorest.Encode(\"path\", firewallPolicyName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"ruleGroupName\": autorest.Encode(\"path\", ruleGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2019-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/ruleGroups/{ruleGroupName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client DeviceClient) DeletePreparer(ctx context.Context, serviceID string, userID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"serviceId\": serviceID,\n\t\t\"userId\": autorest.Encode(\"path\", userID),\n\t}\n\n\ttimestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)\n\tsec := security.NewSignature(client.Secretkey, crypto.SHA256)\n\tsignature, err := sec.Signature(\"DELETE\", common.GetPathParameters(DefaultBaseURI, \"/push/v2/services/{serviceId}/users/{userId}\", pathParameters), client.AccessKey, timestamp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/push/v2/services/{serviceId}/users/{userId}\", pathParameters),\n\t\tautorest.WithHeader(\"x-ncp-apigw-api-key\", client.APIGatewayAPIKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-timestamp\", timestamp),\n\t\tautorest.WithHeader(\"x-ncp-iam-access-key\", client.AccessKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-signature-v2\", signature))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (n *SQSNotify) ReserveDelete(m *SQSMessage) {\n\tn.addDeleteQueue(m)\n\t// flush to delete ASAP when the queue beyond max delete messages.\n\tif n.dqID.Len() >= maxDelete {\n\t\t_ = n.flushDeleteQueue()\n\t}\n}", "func (client *DiskEncryptionSetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif diskEncryptionSetName == \"\" {\n\t\treturn nil, errors.New(\"parameter diskEncryptionSetName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{diskEncryptionSetName}\", url.PathEscape(diskEncryptionSetName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-04-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func PrepareForDeleteUser(roundTripper *mhttp.MockRoundTripper, rootURL, userName, user, passwd string) (\n\tresponse *http.Response) {\n\trequest, _ := http.NewRequest(http.MethodPost, fmt.Sprintf(\"%s/securityRealm/user/%s/doDelete\", rootURL, userName), nil)\n\trequest.Header.Add(httpdownloader.ContentType, httpdownloader.ApplicationForm)\n\tresponse = PrepareCommonPost(request, \"\", roundTripper, user, passwd, rootURL)\n\treturn\n}", "func (p *MemoryProposer) RemovePreparer(target Acceptor) error {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tif _, ok := p.preparers[target.Address()]; !ok {\n\t\treturn ErrNotFound\n\t}\n\tdelete(p.preparers, target.Address())\n\treturn nil\n}", "func (client HTTPSuccessClient) Delete204Preparer(booleanValue *bool) (*http.Request, error) {\n preparer := autorest.CreatePreparer(\n autorest.AsJSON(),\n autorest.AsDelete(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPath(\"/http/success/204\"))\n if booleanValue != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithJSON(booleanValue))\n }\n return preparer.Prepare(&http.Request{})\n}", "func (client ScheduleMessageClient) DeletePreparer(ctx context.Context, serviceID string, scheduleCode string, messageID string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"messageId\": autorest.Encode(\"path\", messageID),\n\t\t\"scheduleCode\": autorest.Encode(\"path\", scheduleCode),\n\t\t\"serviceId\": serviceID,\n\t}\n\n\ttimestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)\n\tsec := security.NewSignature(client.Secretkey, crypto.SHA256)\n\tsignature, err := sec.Signature(\"DELETE\", common.GetPathParameters(DefaultBaseURI, \"/push/v2/services/{serviceId}/schedules/{scheduleCode}/messages/{messageId}\", pathParameters), client.AccessKey, timestamp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/push/v2/services/{serviceId}/schedules/{scheduleCode}/messages/{messageId}\", pathParameters),\n\t\tautorest.WithHeader(\"x-ncp-apigw-api-key\", client.APIGatewayAPIKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-timestamp\", timestamp),\n\t\tautorest.WithHeader(\"x-ncp-iam-access-key\", client.AccessKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-signature-v2\", signature))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (a *Acceptor) DeliverPrepare(prp Prepare) {\n\t//TODO(student): Task 3 - distributed implementation\n\ta.prepareChan <- prp\n}", "func (a *Acceptor) DeliverPrepare(prp Prepare) {\n\t//TODO(student): Task 3 - distributed implementation\n\ta.prepareChan <- prp\n}", "func (client IngestionSettingsClient) DeletePreparer(ctx context.Context, ingestionSettingName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"ingestionSettingName\": autorest.Encode(\"path\", ingestionSettingName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2021-01-15-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/providers/Microsoft.Security/ingestionSettings/{ingestionSettingName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (idx *Tree) ReleaseAllocator(a *Allocator) {\n\tidx.allocatorQueue.put(a.id)\n}", "func (m *RdmaDevPlugin) Allocate(ctx context.Context, r *pluginapi.AllocateRequest) (*pluginapi.AllocateResponse, error) {\n\tlog.Println(\"allocate request:\", r)\n\n\tress := make([]*pluginapi.ContainerAllocateResponse, len(r.GetContainerRequests()))\n\n\tfor i := range r.GetContainerRequests() {\n\t\tress[i] = &pluginapi.ContainerAllocateResponse{\n\t\t\tDevices: m.deviceSpec,\n\t\t}\n\t}\n\n\tresponse := pluginapi.AllocateResponse{\n\t\tContainerResponses: ress,\n\t}\n\n\tlog.Println(\"allocate response: \", response)\n\treturn &response, nil\n}", "func (client *CapacitiesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, dedicatedCapacityName string, options *CapacitiesClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif dedicatedCapacityName == \"\" {\n\t\treturn nil, errors.New(\"parameter dedicatedCapacityName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{dedicatedCapacityName}\", url.PathEscape(dedicatedCapacityName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-01-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client BaseClient) DeleteExpectationPreparer(ctx context.Context, pathParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"path\": autorest.Encode(\"path\", pathParameter),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/api/expectations/{path}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *PacketCoreDataPlanesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, packetCoreControlPlaneName string, packetCoreDataPlaneName string, options *PacketCoreDataPlanesClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MobileNetwork/packetCoreControlPlanes/{packetCoreControlPlaneName}/packetCoreDataPlanes/{packetCoreDataPlaneName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif packetCoreControlPlaneName == \"\" {\n\t\treturn nil, errors.New(\"parameter packetCoreControlPlaneName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{packetCoreControlPlaneName}\", url.PathEscape(packetCoreControlPlaneName))\n\tif packetCoreDataPlaneName == \"\" {\n\t\treturn nil, errors.New(\"parameter packetCoreDataPlaneName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{packetCoreDataPlaneName}\", url.PathEscape(packetCoreDataPlaneName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (na *cnmNetworkAllocator) Deallocate(n *api.Network) error {\n\tlocalNet := na.getNetwork(n.ID)\n\tif localNet == nil {\n\t\treturn fmt.Errorf(\"could not get networker state for network %s\", n.ID)\n\t}\n\n\t// No swarm-level resource deallocation needed for node-local networks\n\tif localNet.isNodeLocal {\n\t\tdelete(na.networks, n.ID)\n\t\treturn nil\n\t}\n\n\tif err := na.freeDriverState(n); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to free driver state for network %s\", n.ID)\n\t}\n\n\tdelete(na.networks, n.ID)\n\n\treturn na.freePools(n, localNet.pools)\n}", "func (client RosettaNetProcessConfigurationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, rosettaNetProcessConfigurationName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"integrationAccountName\": autorest.Encode(\"path\", integrationAccountName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"rosettaNetProcessConfigurationName\": autorest.Encode(\"path\", rosettaNetProcessConfigurationName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2016-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/rosettanetprocessconfigurations/{rosettaNetProcessConfigurationName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client BaseClient) DeleteSystemPreparer(ctx context.Context, pathParameter string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"path\": autorest.Encode(\"path\", pathParameter),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/api/systems/{path}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client BaseClient) DeleteSubscriptionPreparer(ctx context.Context, subscriptionID uuid.UUID, APIVersion string, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"subscriptionId\": autorest.Encode(\"path\",subscriptionID),\n }\n\n queryParameters := map[string]interface{} {\n \"ApiVersion\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\n autorest.AsDelete(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPathParameters(\"/{subscriptionId}\",pathParameters),\n autorest.WithQueryParameters(queryParameters),\n autorest.WithHeader(\"Content-Type\", \"application/json\"))\n if xMsRequestid != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithHeader(\"x-ms-requestid\",autorest.String(xMsRequestid)))\n }\n if xMsCorrelationid != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithHeader(\"x-ms-correlationid\",autorest.String(xMsCorrelationid)))\n }\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client HTTPSuccessClient) Delete200Preparer(booleanValue *bool) (*http.Request, error) {\n preparer := autorest.CreatePreparer(\n autorest.AsJSON(),\n autorest.AsDelete(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPath(\"/http/success/200\"))\n if booleanValue != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithJSON(booleanValue))\n }\n return preparer.Prepare(&http.Request{})\n}", "func (client LabClient) DeleteResourcePreparer(ctx context.Context, resourceGroupName string, name string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"name\": autorest.Encode(\"path\", name),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2015-05-21-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{name}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (t *Table) PrepareUpdate(tu fibdef.Update) (*UpdateCommand, error) {\n\tu := &UpdateCommand{}\n\tu.real.RealUpdate = tu.Real()\n\tu.virt.VirtUpdate = tu.Virt()\n\n\tu.allocSplit = u.real.prepare(t)\n\tu.allocated = make([]*Entry, u.allocSplit+u.virt.prepare(t))\n\tif e := t.allocBulk(u.allocated); e != nil {\n\t\treturn nil, e\n\t}\n\n\treturn u, nil\n}", "func (client DeletedCertificateListResult) DeletedCertificateListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func (client *DedicatedHostsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif hostGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter hostGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{hostGroupName}\", url.PathEscape(hostGroupName))\n\tif hostName == \"\" {\n\t\treturn nil, errors.New(\"parameter hostName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{hostName}\", url.PathEscape(hostName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (p AzurePKEClusterCreationParamsPreparer) Prepare(ctx context.Context, params *AzurePKEClusterCreationParams) error {\n\tif params.Name == \"\" {\n\t\treturn validationErrorf(\"Name cannot be empty\")\n\t}\n\tif params.OrganizationID == 0 {\n\t\treturn validationErrorf(\"OrganizationID cannot be 0\")\n\t}\n\t// TODO check org exists\n\t// TODO check creator user exists if present\n\tif params.SecretID == \"\" {\n\t\treturn validationErrorf(\"SecretID cannot be empty\")\n\t}\n\t// TODO validate secret ID\n\t// TODO validate SSH secret ID if present\n\n\tif params.ResourceGroup == \"\" {\n\t\tparams.ResourceGroup = fmt.Sprintf(\"%s-rg\", params.Name)\n\t\tp.logger.Debugf(\"ResourceGroup not specified, defaulting to [%s]\", params.ResourceGroup)\n\t}\n\n\tif err := p.k8sPreparer.Prepare(&params.Kubernetes); err != nil {\n\t\treturn emperror.Wrap(err, \"failed to prepare k8s network\")\n\t}\n\n\tsir, err := secret.Store.Get(params.OrganizationID, params.SecretID)\n\tif err != nil {\n\t\treturn emperror.Wrap(err, \"failed to fetch secret from store\")\n\t}\n\tcc, err := azure.NewCloudConnection(&autoazure.PublicCloud, azure.NewCredentials(sir.Values))\n\tif err != nil {\n\t\treturn emperror.Wrap(err, \"failed to create Azure cloud connection\")\n\t}\n\tif err := p.getVNetPreparer(cc, params.Name, params.ResourceGroup).Prepare(ctx, &params.Network); err != nil {\n\t\treturn emperror.Wrap(err, \"failed to prepare cluster network\")\n\t}\n\n\tif err := p.nodePoolsPreparer.Prepare(params.NodePools); err != nil {\n\t\treturn emperror.Wrap(err, \"failed to prepare node pools\")\n\t}\n\n\treturn nil\n}", "func (connection *Connection) CreateMapDeleteRequest(param ...interface{}) (request *DeleteRequest, err error) {\n\tt := reflect.TypeOf(param[0])\n\tswitch t.Kind() {\n\tcase reflect.Ptr, reflect.Struct:\n\t\tif connection.repository == nil {\n\t\t\tif connection.adabasMap != nil && connection.adabasMap.Name == inmapMapName {\n\t\t\t\t// Lock this Adabas Map for ReadRequest creation process of dynamic part\n\t\t\t\tconnection.adabasMap.lock.Lock()\n\t\t\t\tdefer connection.adabasMap.lock.Unlock()\n\t\t\t\tadatypes.Central.Log.Debugf(\"InMap used: %s\", connection.adabasMap.Name)\n\t\t\t\terr = connection.adabasMap.defineByInterface(param[0])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\trequest, err = NewMapDeleteRequest(connection.adabasToData, connection.adabasMap)\n\t\t\t} else {\n\t\t\t\tadatypes.Central.Log.Debugf(\"No repository used: %#v\", connection.adabasToMap)\n\t\t\t\trequest, err = NewMapNameDeleteRequest(connection.adabasToMap, evaluateInterface(param[0]))\n\t\t\t}\n\t\t} else {\n\t\t\tadatypes.Central.Log.Debugf(\"With repository used: %#v\", connection.adabasMap)\n\t\t\trequest, err = NewMapNameDeleteRequestRepo(evaluateInterface(param[0]), connection.adabasToMap, connection.repository)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif len(param) > 1 {\n\t\t\tswitch t := param[1].(type) {\n\t\t\tcase int:\n\t\t\t\tconnection.fnr = Fnr(t)\n\t\t\t\trequest.repository.Fnr = Fnr(t)\n\t\t\tcase Fnr:\n\t\t\t\tconnection.fnr = t\n\t\t\t\trequest.repository.Fnr = t\n\t\t\t}\n\t\t} else {\n\t\t\tconnection.fnr = request.adabasMap.Data.Fnr\n\t\t}\n\t\tconnection.adabasMap = request.adabasMap\n\tcase reflect.String:\n\t\tmapName := param[0].(string)\n\t\terr = connection.prepareMapUsage(mapName)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t// if connection.repository == nil {\n\t\t// \terr = adatypes.NewGenericError(9)\n\t\t// \treturn\n\t\t// }\n\t\t// connection.repository.SearchMapInRepository(connection.adabasToMap, mapName)\n\t\tif connection.adabasMap == nil {\n\t\t\terr = adatypes.NewGenericError(8, mapName)\n\t\t\treturn\n\t\t}\n\t\tconnection.adabasToData = connection.ID.getAdabas(connection.adabasMap.URL())\n\t\t// NewAdabas(connection.adabasMap.URL(), connection.ID)\n\t\t// if err != nil {\n\t\t// \treturn\n\t\t// }\n\t\tconnection.fnr = connection.adabasMap.Data.Fnr\n\t\tadatypes.Central.Log.Debugf(\"Connection FNR=%d, Map referenced : %#v\", connection.fnr, connection.adabasMap)\n\t\trequest, err = NewMapDeleteRequest(connection.adabasToData, connection.adabasMap)\n\t}\n\treturn\n}", "func (client Client) DeletePreparer(ctx context.Context, nasVolumeInstanceNoListN string) (*http.Request, error) {\n\tqueryParameters := map[string]interface{}{\n\t\t\"nasVolumeInstanceNoList.N\": autorest.Encode(\"query\", nasVolumeInstanceNoListN),\n\t\t\"responseFormatType\": autorest.Encode(\"query\", \"json\"),\n\t}\n\n\tqueryParameters[\"regionCode\"] = autorest.Encode(\"query\", \"FKR\")\n\n\ttimestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)\n\tsec := security.NewSignature(client.Secretkey, crypto.SHA256)\n\tsignature, err := sec.Signature(\"POST\", common.GetPath(DefaultBaseURI, \"/deleteNasVolumeInstances\")+\"?\"+common.GetQuery(queryParameters), client.AccessKey, timestamp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/deleteNasVolumeInstances\"),\n\t\tautorest.WithQueryParameters(queryParameters),\n\t\tautorest.WithHeader(\"x-ncp-apigw-timestamp\", timestamp),\n\t\tautorest.WithHeader(\"x-ncp-iam-access-key\", client.AccessKey),\n\t\tautorest.WithHeader(\"x-ncp-apigw-signature-v2\", signature))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (c *Inventory) PrepareDeletableObjects() error {\n\tvar deleteObjects []runtime.Object\n\n\tcurrentObjects := c.inventoryData.CurrentObjects\n\tfor _, currentObject := range currentObjects {\n\t\tmetaobj, err := meta.Accessor(currentObject)\n\t\tif err != nil {\n\t\t\treturn errors.WrapIfWithDetails(err,\n\t\t\t\t\"could not access object metadata\",\n\t\t\t\t\"gvk\", currentObject.GetObjectKind().GroupVersionKind().String())\n\t\t}\n\n\t\tisClusterScoped, err := c.IsClusterScoped(currentObject)\n\t\tif err != nil {\n\t\t\tc.log.Error(err, \"scope check failed, unable to determine whether object is eligible for deletion\")\n\t\t\tcontinue\n\t\t}\n\t\t// check if current object still exists\n\t\tif !isClusterScoped && metaobj.GetNamespace() == \"\" {\n\t\t\tc.log.Info(\"object namespace is unknown, unable to determine whether is eligible for deletion\", \"gvk\", currentObject.GetObjectKind().GroupVersionKind().String(), \"name\", metaobj.GetName())\n\t\t\tcontinue\n\t\t}\n\t\terr = c.genericClient.Get(context.TODO(), types.NamespacedName{Namespace: metaobj.GetNamespace(), Name: metaobj.GetName()}, currentObject.(client.Object))\n\t\tif err != nil && !meta.IsNoMatchError(err) && !apierrors.IsNotFound(err) {\n\t\t\treturn errors.WrapIfWithDetails(err,\n\t\t\t\t\"could not verify if object exists\",\n\t\t\t\t\"namespace\", metaobj.GetNamespace(), \"objectName\", metaobj.GetName())\n\t\t}\n\n\t\tcurrentObjGVK := currentObject.GetObjectKind().GroupVersionKind()\n\n\t\tif metaobj.GetDeletionTimestamp() != nil || currentObjGVK.Kind == CustomResourceDefinition || currentObjGVK.Kind == Namespace {\n\t\t\tcontinue\n\t\t}\n\n\t\tdesiredObjects := c.inventoryData.DesiredObjects\n\t\tfound := false\n\n\t\tfor _, desiredObject := range desiredObjects {\n\t\t\tdesiredObjGVK := desiredObject.GetObjectKind().GroupVersionKind()\n\t\t\tdesiredObjMeta, _ := meta.Accessor(desiredObject)\n\n\t\t\tif currentObjGVK.Group == desiredObjGVK.Group &&\n\t\t\t\tcurrentObjGVK.Version == desiredObjGVK.Version &&\n\t\t\t\tcurrentObjGVK.Kind == desiredObjGVK.Kind &&\n\t\t\t\tmetaobj.GetNamespace() == desiredObjMeta.GetNamespace() &&\n\t\t\t\tmetaobj.GetName() == desiredObjMeta.GetName() {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tc.log.Info(\"object eligible for delete\", \"gvk\", currentObjGVK.String(), \"namespace\", metaobj.GetNamespace(), \"name\", metaobj.GetName())\n\t\t\tdeleteObjects = append(deleteObjects, currentObject)\n\t\t}\n\t}\n\n\tc.inventoryData.ObjectsToDelete = deleteObjects\n\treturn nil\n}", "func (client AppsClient) DeletePreparer(ctx context.Context, appID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *VirtualMachineScaleSetsClient) deallocateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsBeginDeallocateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/deallocate\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif vmScaleSetName == \"\" {\n\t\treturn nil, errors.New(\"parameter vmScaleSetName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{vmScaleSetName}\", url.PathEscape(vmScaleSetName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\tif options != nil && options.VMInstanceIDs != nil {\n\t\treturn req, runtime.MarshalAsJSON(req, *options.VMInstanceIDs)\n\t}\n\treturn req, nil\n}", "func InitAllocator(addr uint32) {\n\t// Warning: Lot of unsafe pointer usage and manipulation ahead.\n\t// This function basically initializes memory at given address, so that\n\t// _buddyAllocator, and it's members, point to this address.\n\n\t// create freeBuddiesList\n\tvar _freeBuddiesList *[MaxOrder + 1]freeBuddiesList\n\t_freeBuddiesList = (*[MaxOrder + 1]freeBuddiesList)(pointer.Get(addr))\n\taddr += (MaxOrder + 1) * uint32(unsafe.Sizeof(freeBuddiesList{}))\n\n\t// set freeBuddiesList in buddyAllocator\n\t_buddyAllocator.buddies = (*_freeBuddiesList)[:MaxOrder+1]\n\n\t// create bigPagesBitmap\n\t// _nBigPages size for array is way more than needed. this is done since\n\t// array sizes need to be constant.\n\tvar _bigPagesBitmap *[_nBigPages]uint32\n\t_bigPagesBitmap = (*[_nBigPages]uint32)(pointer.Get(addr))\n\taddr += nMaps(_nBigPages) * 4\n\n\t// set bigPagesBitmap in buddyAllocator\n\t_buddyAllocator.buddies[MaxOrder].freeMap.maps = (*_bigPagesBitmap)[:nMaps(_nBigPages)]\n\n\t// mark all big pages as free\n\tfor i := uint32(0); i < nMaps(_nBigPages); i++ {\n\t\t_buddyAllocator.buddies[MaxOrder].freeMap.maps[i] = _allSet\n\t}\n\n\t// create the individual freeBuddiesList\n\tfor i := 0; i < MaxOrder; i++ {\n\t\t// maxOrder - 1 pages of order i, further divide by 2 since we use 1 bit\n\t\t// for buddy pair.\n\t\tvar nBuddies uint32 = _nBigPages * (1 << uint32(MaxOrder-i-1))\n\t\tnMaps := nMaps(nBuddies)\n\n\t\t// set address for this freeBuddiesList\n\t\t// we are addressing way more memory than needed, because array sizes need\n\t\t// to be constant. this will be more than enough for largest freeBuddiesList\n\t\tvar maps *[_nBigPages * _nBigPages]uint32\n\t\tmaps = (*[_nBigPages * _nBigPages]uint32)(pointer.Get(addr))\n\t\taddr += nMaps * 4\n\n\t\t// set the freeBuddiesList\n\t\t_buddyAllocator.buddies[i].freeMap.maps = (*maps)[:nMaps]\n\n\t\t// zero out the freeBuddiesList\n\t\tfor j := uint32(0); j < nMaps; j++ {\n\t\t\t_buddyAllocator.buddies[i].freeMap.maps[j] = 0\n\t\t}\n\t}\n\n\tinitNodePool(addr)\n}", "func (client DataControllersClient) DeleteDataControllerPreparer(ctx context.Context, resourceGroupName string, dataControllerName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"dataControllerName\": autorest.Encode(\"path\", dataControllerName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2019-07-24-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureData/dataControllers/{dataControllerName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *IPAllocationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, ipAllocationName string, options *IPAllocationsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/IpAllocations/{ipAllocationName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif ipAllocationName == \"\" {\n\t\treturn nil, errors.New(\"parameter ipAllocationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{ipAllocationName}\", url.PathEscape(ipAllocationName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-04-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (allocator *Allocator) ReleaseAllocator() {\n\tC.zj_AllocatorRelease(allocator.A)\n}", "func (client *DedicatedHostsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsBeginDeleteOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{hostGroupName}\", url.PathEscape(hostGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{hostName}\", url.PathEscape(hostName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := azcore.NewRequest(ctx, http.MethodDelete, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2020-06-01\")\n\treq.URL.RawQuery = query.Encode()\n\treturn req, nil\n}", "func (client DeletedSecretListResult) DeletedSecretListResultPreparer() (*http.Request, error) {\n\tif client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(client.NextLink)))\n}", "func PrepareTape(hDevice HANDLE, dwOperation DWORD, bImmediate bool) DWORD {\n\tret1 := syscall3(prepareTape, 3,\n\t\tuintptr(hDevice),\n\t\tuintptr(dwOperation),\n\t\tgetUintptrFromBool(bImmediate))\n\treturn DWORD(ret1)\n}", "func (client ListManagementTermListsClient) DeletePreparer(ctx context.Context, listID string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"listId\": autorest.Encode(\"path\", listID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/contentmoderator/lists/v1.0/termlists/{listId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *AgentPoolsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, kubernetesClusterName string, agentPoolName string, options *AgentPoolsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkCloud/kubernetesClusters/{kubernetesClusterName}/agentPools/{agentPoolName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif kubernetesClusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter kubernetesClusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{kubernetesClusterName}\", url.PathEscape(kubernetesClusterName))\n\tif agentPoolName == \"\" {\n\t\treturn nil, errors.New(\"parameter agentPoolName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{agentPoolName}\", url.PathEscape(agentPoolName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (p *Preparer) Prepare(fullInfo chan resource.Resource, done chan bool, mapWg *sync.WaitGroup) {\n\tmapWg.Wait()\n\n\tvar wg sync.WaitGroup\n\n\tidentifierSend := false\n\n\tfor data := range fullInfo {\n\t\tif !identifierSend {\n\t\t\terr := p.prep.SendIdentifier()\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(log.Fields{\"error\": err}).Fatal(\"error send identifier\")\n\t\t\t}\n\t\t\tidentifierSend = true\n\t\t}\n\t\twg.Add(1)\n\t\tgo p.prep.Preparation(data, &wg)\n\t}\n\n\twg.Wait()\n\n\t// If the identifier was not sent, there is no resource to prepare and send,\n\t// a gRPC connection was not open and no finishing and closing of a connection are needed.\n\tif identifierSend {\n\t\tp.prep.Finish()\n\t}\n\n\tdone <- true\n}", "func (client PatternClient) DeletePatternPreparer(ctx context.Context, appID uuid.UUID, versionID string, patternID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"patternId\": autorest.Encode(\"path\", patternID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/patternrules/{patternId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (p VspherePKEClusterCreationParamsPreparer) Prepare(ctx context.Context, params *VspherePKEClusterCreationParams) error {\n\tif params.Name == \"\" {\n\t\treturn validationErrorf(\"Name cannot be empty\")\n\t}\n\tif params.OrganizationID == 0 {\n\t\treturn validationErrorf(\"OrganizationID cannot be 0\")\n\t}\n\n\t_, err := auth.GetOrganizationById(params.OrganizationID)\n\tif err != nil {\n\t\treturn validationErrorf(\"OrganizationID cannot be found %s\", err.Error())\n\t}\n\n\t// validate secretID\n\tif params.SecretID == \"\" {\n\t\treturn validationErrorf(\"SecretID cannot be empty\")\n\t}\n\tif err := p.verifySecretIsOfType(params.OrganizationID, params.SecretID, secrettype.Vsphere); err != nil {\n\t\treturn err\n\t}\n\n\t// validate storageSecretID if present\n\tif err := p.verifySecretIsOfType(params.OrganizationID, params.StorageSecretID, secrettype.Vsphere); err != nil {\n\t\treturn err\n\t}\n\n\t// validate SSH secret ID if present\n\tif err := p.verifySecretIsOfType(params.OrganizationID, params.SSHSecretID, secrettype.SSHSecretType); err != nil {\n\t\treturn err\n\t}\n\n\tif err := p.k8sPreparer.Prepare(&params.Kubernetes); err != nil {\n\t\treturn errors.WrapIf(err, \"failed to prepare k8s network\")\n\t}\n\n\tif err := p.getNodePoolsPreparer(clusterCreatorNodePoolPreparerDataProvider{}).Prepare(ctx, params.NodePools); err != nil {\n\t\treturn errors.WrapIf(err, \"failed to prepare node pools\")\n\t}\n\n\treturn nil\n}", "func (l *blocksLRU) prepareForAdd() {\n\tswitch {\n\tcase l.ll.Len() > l.capacity:\n\t\tpanic(\"impossible\")\n\tcase l.ll.Len() == l.capacity:\n\t\toldest := l.ll.Remove(l.ll.Back()).(block)\n\t\tdelete(l.blocks, oldest.offset)\n\t\tl.evicted(oldest)\n\t}\n}", "func (dl *DrawList) PrimReserve(idxCount, vtxCount int) {\n\tif sz, require := len(dl.VtxBuffer), dl.vtxIndex+vtxCount; require >= sz {\n\t\tvtxBuffer := make([]DrawVert, sz+1024)\n\t\tcopy(vtxBuffer, dl.VtxBuffer)\n\t\tdl.VtxBuffer = vtxBuffer\n\t}\n\tif sz, require := len(dl.IdxBuffer), dl.idxIndex+idxCount; require >= sz {\n\t\tidxBuffer := make([]DrawIdx, sz+1024)\n\t\tcopy(idxBuffer, dl.IdxBuffer)\n\t\tdl.IdxBuffer = idxBuffer\n\t}\n\tdl.VtxWriter = dl.VtxBuffer[dl.vtxIndex:dl.vtxIndex+vtxCount]\n\tdl.IdxWriter = dl.IdxBuffer[dl.idxIndex:dl.idxIndex+idxCount]\n}", "func (client ViewsClient) DeleteByScopePreparer(ctx context.Context, scope string, viewName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"scope\": autorest.Encode(\"path\", scope),\n\t\t\"viewName\": autorest.Encode(\"path\", viewName),\n\t}\n\n\tconst APIVersion = \"2019-11-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{scope}/providers/Microsoft.CostManagement/views/{viewName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (sb *spdkBackend) prepare(req storage.BdevPrepareRequest, vmdDetect vmdDetectFn, hpClean hpCleanFn) (*storage.BdevPrepareResponse, error) {\n\tresp := &storage.BdevPrepareResponse{}\n\n\tif req.CleanHugepagesOnly {\n\t\t// Remove hugepages that were created by a no-longer-active SPDK process. Note that\n\t\t// when running prepare, it's unlikely that any SPDK processes are active as this\n\t\t// is performed prior to starting engines.\n\t\tnrRemoved, err := hpClean(sb.log, hugepageDir)\n\t\tif err != nil {\n\t\t\treturn resp, errors.Wrapf(err, \"clean spdk hugepages\")\n\t\t}\n\t\tresp.NrHugepagesRemoved = nrRemoved\n\n\t\tlogNUMAStats(sb.log)\n\n\t\treturn resp, nil\n\t}\n\n\t// Update request if VMD has been explicitly enabled and there are VMD endpoints configured.\n\tif err := updatePrepareRequest(sb.log, &req, vmdDetect); err != nil {\n\t\treturn resp, errors.Wrapf(err, \"update prepare request\")\n\t}\n\tresp.VMDPrepared = req.EnableVMD\n\n\t// Before preparing, reset device bindings.\n\tif req.EnableVMD {\n\t\t// Unbind devices to speed up VMD re-binding as per\n\t\t// https://github.com/spdk/spdk/commit/b0aba3fcd5aceceea530a702922153bc75664978.\n\t\t//\n\t\t// Applies block (not allow) list if VMD is configured so specific NVMe devices can\n\t\t// be reserved for other use (bdev_exclude).\n\t\tif err := sb.script.Unbind(&req); err != nil {\n\t\t\treturn resp, errors.Wrap(err, \"un-binding devices\")\n\t\t}\n\t} else {\n\t\tif err := sb.script.Reset(&req); err != nil {\n\t\t\treturn resp, errors.Wrap(err, \"resetting device bindings\")\n\t\t}\n\t}\n\n\treturn resp, errors.Wrap(sb.script.Prepare(&req), \"binding devices to userspace drivers\")\n}", "func CreateDeleteSurveyResourcesRequest() (request *DeleteSurveyResourcesRequest) {\n\trequest = &DeleteSurveyResourcesRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"apds\", \"2022-03-31\", \"DeleteSurveyResources\", \"/okss-services/confirm-resource/destroy\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func allocateSpace(ctx *downloaderContext, status *types.DownloaderStatus,\n\tsize uint64) {\n\tif status.Size != 0 {\n\t\tlog.Errorf(\"%s, request for duplicate storage allocation\\n\", status.Name)\n\t\treturn\n\t}\n\tkb := types.RoundupToKB(size)\n\tctx.globalStatusLock.Lock()\n\tctx.globalStatus.ReservedSpace -= status.ReservedSpace\n\tctx.globalStatus.UsedSpace += kb\n\tupdateRemainingSpace(ctx)\n\tctx.globalStatusLock.Unlock()\n\tstatus.ReservedSpace = 0\n\tstatus.Size = size\n\tpublishGlobalStatus(ctx)\n}", "func (client ModelClient) DeletePrebuiltPreparer(ctx context.Context, appID uuid.UUID, versionID string, prebuiltID uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"Endpoint\": client.Endpoint,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"prebuiltId\": autorest.Encode(\"path\", prebuiltID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"{Endpoint}/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/prebuilts/{prebuiltId}\", pathParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (action *ActionUserDelete) Prepare() *ActionUserDeleteInvocation {\n\treturn &ActionUserDeleteInvocation{\n\t\tAction: action,\n\t\tPath: \"/v6.0/users/{user_id}\",\n\t}\n}", "func (cp *connPool) Allocate(\n\tcfg *config.SQL,\n\tresolver resolver.ServiceResolver,\n\tcreate func(cfg *config.SQL, resolver resolver.ServiceResolver) (*sqlx.DB, error),\n) (db *sqlx.DB, err error) {\n\tcp.mu.Lock()\n\tdefer cp.mu.Unlock()\n\n\tdsn, err := buildDSN(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif entry, ok := cp.pool[dsn]; ok {\n\t\tentry.refCount++\n\t\treturn entry.db, nil\n\t}\n\n\tdb, err = create(cfg, resolver)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcp.pool[dsn] = entry{db: db, refCount: 1}\n\n\treturn db, nil\n}", "func CreateDeleteApDeviceRequest() (request *DeleteApDeviceRequest) {\n\trequest = &DeleteApDeviceRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"cloudesl\", \"2020-02-01\", \"DeleteApDevice\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (m *manager) Reserve(d *structs.AllocatedDeviceResource) (*device.ContainerReservation, error) {\n\t// Go through each plugin and see if it can reserve the resources\n\tfor _, i := range m.instances {\n\t\tif !i.HasDevices(d) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// We found a match so reserve\n\t\treturn i.Reserve(d)\n\t}\n\n\treturn nil, UnknownDeviceErrFromAllocated(\"failed to reserve devices\", d)\n}", "func (client *AvailabilitySetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, availabilitySetName string, options *AvailabilitySetsDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif availabilitySetName == \"\" {\n\t\treturn nil, errors.New(\"parameter availabilitySetName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{availabilitySetName}\", url.PathEscape(availabilitySetName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (a *Allocator) ResetMaybeReallocate(\n\ttyps []*types.T, oldBatch coldata.Batch, minCapacity int, maxBatchMemSize int64,\n) (newBatch coldata.Batch, reallocated bool) {\n\tif minCapacity < 0 {\n\t\tcolexecerror.InternalError(errors.AssertionFailedf(\"invalid minCapacity %d\", minCapacity))\n\t} else if minCapacity == 0 {\n\t\tminCapacity = 1\n\t} else if minCapacity > coldata.BatchSize() {\n\t\tminCapacity = coldata.BatchSize()\n\t}\n\treallocated = true\n\tif oldBatch == nil {\n\t\tnewBatch = a.NewMemBatchWithFixedCapacity(typs, minCapacity)\n\t} else {\n\t\t// If old batch is already of the largest capacity, we will reuse it.\n\t\tuseOldBatch := oldBatch.Capacity() == coldata.BatchSize()\n\t\t// Avoid calculating the memory footprint if possible.\n\t\tvar oldBatchMemSize int64\n\t\tif !useOldBatch {\n\t\t\t// Check if the old batch already reached the maximum memory size,\n\t\t\t// and use it if so. Note that we must check that the old batch has\n\t\t\t// enough capacity too.\n\t\t\toldBatchMemSize = GetBatchMemSize(oldBatch)\n\t\t\tuseOldBatch = oldBatchMemSize >= maxBatchMemSize && oldBatch.Capacity() >= minCapacity\n\t\t}\n\t\tif useOldBatch {\n\t\t\treallocated = false\n\t\t\toldBatch.ResetInternalBatch()\n\t\t\tnewBatch = oldBatch\n\t\t} else {\n\t\t\ta.ReleaseMemory(oldBatchMemSize)\n\t\t\tnewCapacity := oldBatch.Capacity() * 2\n\t\t\tif newCapacity < minCapacity {\n\t\t\t\tnewCapacity = minCapacity\n\t\t\t}\n\t\t\tif newCapacity > coldata.BatchSize() {\n\t\t\t\tnewCapacity = coldata.BatchSize()\n\t\t\t}\n\t\t\tnewBatch = a.NewMemBatchWithFixedCapacity(typs, newCapacity)\n\t\t}\n\t}\n\treturn newBatch, reallocated\n}", "func (client *PrivateDNSZoneGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, options *PrivateDNSZoneGroupsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif privateEndpointName == \"\" {\n\t\treturn nil, errors.New(\"parameter privateEndpointName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{privateEndpointName}\", url.PathEscape(privateEndpointName))\n\tif privateDNSZoneGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter privateDNSZoneGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{privateDnsZoneGroupName}\", url.PathEscape(privateDNSZoneGroupName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-04-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (endpointSliceStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tendpointSlice := obj.(*discovery.EndpointSlice)\n\tendpointSlice.Generation = 1\n\n\tdropDisabledConditionsOnCreate(endpointSlice)\n}", "func (client *VirtualNetworkTapsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, tapName string, options *VirtualNetworkTapsBeginDeleteOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{tapName}\", url.PathEscape(tapName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := azcore.NewRequest(ctx, http.MethodDelete, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2020-07-01\")\n\treq.URL.RawQuery = query.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client PatternClient) DeletePatternsPreparer(ctx context.Context, appID uuid.UUID, versionID string, patternIds []uuid.UUID) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t\t\"versionId\": autorest.Encode(\"path\", versionID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/versions/{versionId}/patternrules\", pathParameters),\n\t\tautorest.WithJSON(patternIds))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}" ]
[ "0.52881616", "0.5262748", "0.5250947", "0.51915395", "0.51663846", "0.5157574", "0.51027143", "0.50212806", "0.49939945", "0.49535996", "0.49505183", "0.49463445", "0.49417627", "0.49401733", "0.49396092", "0.49217606", "0.49027976", "0.4893439", "0.4889526", "0.48798436", "0.48636538", "0.48604572", "0.4852044", "0.484313", "0.4810996", "0.4810434", "0.48058358", "0.47897765", "0.47731048", "0.4770574", "0.47650862", "0.47509113", "0.47167692", "0.47110742", "0.47033072", "0.46956378", "0.46651572", "0.4650921", "0.46395397", "0.46283084", "0.4621157", "0.4614807", "0.46130496", "0.46028414", "0.46012732", "0.45998585", "0.4588479", "0.45834482", "0.457999", "0.457999", "0.4574488", "0.45615423", "0.45505762", "0.4544602", "0.4521481", "0.45194003", "0.4486145", "0.44834992", "0.44800392", "0.44229165", "0.44184166", "0.4396064", "0.4372618", "0.43641576", "0.43615744", "0.43530807", "0.43511218", "0.43437427", "0.43415195", "0.43263972", "0.4319228", "0.43182853", "0.43099466", "0.43084496", "0.4288889", "0.42871842", "0.42806348", "0.427231", "0.42684782", "0.42607883", "0.4235968", "0.42333505", "0.42322484", "0.42311874", "0.4218239", "0.42168736", "0.4212839", "0.42109028", "0.42106557", "0.42052257", "0.41985473", "0.41955143", "0.4180018", "0.4178601", "0.41782945", "0.41766337", "0.41667384", "0.41623294", "0.41583794", "0.41579723" ]
0.7151367
0
MaxKey returns the maximum key having the given searchPrefix, or the maximum key in the whole index if searchIndex is nil. Maximum means the last key in the lexicographic order. If keys are uint64 in BigEndian it is also the largest number. If ok is false the index is empty. For example, if we store temperature readings using the key "temp_TIMESTAMP" where timestamp is an 8 byte BigEndian ns timestamp MaxKey([]byte("temp_")) returns the last made reading.
func (idx *Tree) MaxKey(searchPrefix []byte) (v uint64, ok bool) { raw, _ := idx.partialSearch(searchPrefix) if raw == 0 { return 0, false } if isLeaf(raw) { return getLeafValue(raw), true } // now find the max searchLoop: for { _, node, count, prefixLen := explodeNode(raw) block := int(node >> blockSlotsShift) offset := int(node & blockSlotsOffsetMask) data := idx.blocks[block].data[offset:] var prefixSlots int if prefixLen > 0 { if prefixLen == 255 { prefixLen = int(data[0]) prefixSlots = (prefixLen + 15) >> 3 } else { prefixSlots = (prefixLen + 7) >> 3 } data = data[prefixSlots:] } if count >= fullAllocFrom { // find max, iterate from top for k := 255; k >= 0; k-- { a := atomic.LoadUint64(&data[k]) if a != 0 { if isLeaf(a) { return getLeafValue(a), true } raw = a continue searchLoop } } // BUG: this might happen if all children in the node has been deleted, since we currently don't shrink node-256. we should go back in the tree! return 0, false } // load the last child (since they are ordered) a := atomic.LoadUint64(&data[count-1]) if isLeaf(a) { return getLeafValue(a), true } raw = a } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetMaxIndexKey(shardID uint64, key []byte) []byte {\n\tkey = getKeySlice(key, idKeyLength)\n\treturn getIDKey(maxIndexSuffix, shardID, key)\n}", "func MaxKey() Val { return Val{t: bsontype.MaxKey} }", "func (this *AllOne) GetMaxKey() string {\n\tif this.tail.pre != this.head {\n\t\tfor k := range this.tail.pre.keys {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn \"\"\n}", "func (tf tFiles) searchMax(icmp *iComparer, ikey internalKey) int {\n\treturn sort.Search(len(tf), func(i int) bool {\n\t\treturn icmp.Compare(tf[i].imax, ikey) >= 0\n\t})\n}", "func Max(key []byte, nodes []*memberlist.Node) (max *memberlist.Node) {\n\tmaxValue := big.NewInt(0)\n\n\tCompute(key, nodes, func(node *memberlist.Node, bi *big.Int) {\n\t\tif bi.Cmp(maxValue) == 1 {\n\t\t\tmaxValue = bi\n\t\t\tmax = node\n\t\t}\n\t})\n\n\treturn max\n}", "func (this *AllOne) GetMaxKey() string {\n\tif this.Head.Next != this.Tail {\n\t\tnmap := this.Head.Next.NodeMap\n\t\tret := \"\"\n\t\tfor k, _ := range nmap {\n\t\t\tret = k\n\t\t\tbreak\n\t\t}\n\t\treturn ret\n\t}\n\n\treturn \"\"\n}", "func (n *Node) LongestPrefix(k []byte) ([]byte, interface{}, bool) {\n\tvar last *leafNode\n\tsearch := k\n\tfor {\n\t\t// Look for a leaf node\n\t\tif n.isLeaf() {\n\t\t\tlast = n.leaf\n\t\t}\n\n\t\t// Check for key exhaution\n\t\tif len(search) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// Look for an edge\n\t\t_, n = n.getEdge(search[0])\n\t\tif n == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Consume the search prefix\n\t\tif bytes.HasPrefix(search, n.prefix) {\n\t\t\tsearch = search[len(n.prefix):]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tif last != nil {\n\t\treturn last.key, last.val, true\n\t}\n\treturn nil, nil, false\n}", "func (this *AllOne) GetMaxKey() string {\n if len(this.m) == 0{\n return \"\"\n }\n return this.g[this.max][1].k\n}", "func (this *AllOne) GetMaxKey() string {\n\tif this.head == nil {\n\t\treturn \"\"\n\t}\n\tfor k := range this.head.set {\n\t\treturn k\n\t}\n\treturn \"ERROR\"\n}", "func ComputeMaxKey() *big.Int {\n\tbase := big.NewInt(2)\n\tm := big.NewInt(int64(MBits))\n\n\tmax_key := big.NewInt(0)\n\tmax_key.Exp(base, m, nil)\n\tmax_key.Sub(max_key, big.NewInt(1))\n\n\treturn max_key\n}", "func (t *BinarySearch[T]) Max() (T, bool) {\n\tret := maximum[T](t.Root, t._NIL)\n\tif ret == t._NIL {\n\t\tvar dft T\n\t\treturn dft, false\n\t}\n\treturn ret.Key(), true\n}", "func (st *RedBlackBST) Max() Key {\n\tif st.IsEmpty() {\n\t\tpanic(\"call Max on empty RedBlackbst\")\n\t}\n\treturn st.max(st.root).key\n}", "func (tree *avlBetterTree) MaxKey() (key string, value interface{}, exist bool) {\n\ttree.Lock()\n\tdefer tree.Unlock()\n\tif tree.root == nil {\n\t\t// 如果是空树,返回空\n\t\treturn\n\t}\n\n\tnode := tree.root.maxNode()\n\treturn node.k, node.v, true\n}", "func (table *Table) SearchLast(searchValues ...interface{}) (int, error) {\n\n\terr := table.checkSearchArguments(searchValues...)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\trowIndex, err := table.searchByKeysLast(searchValues)\n\n\treturn rowIndex, err\n}", "func (sa *SuffixArray) MaxValue() uint64 { return sa.ba.MaxValue() }", "func getTableMaxKey(stub shim.ChaincodeStubInterface, tableName string) ([]byte, error) {\n\t// Use emty columns slice to get all rows for count\n\tvar cols []shim.Column\n\n\tvar key string\n\tkey = \"0\"\n\tkeyint, _ := strconv.Atoi(key)\n\n\trowChan, err := stub.GetRows(tableName, cols)\n\tif err != nil {\n\t\treturn []byte(key), err\n\t}\n\n\trow, ok := <-rowChan\n\n\tfor ok {\n\t\t// Key column should be the first and table key should be single-column key\n\t\tkey = row.GetColumns()[0].GetString_()\n\t\tkeyintc, _ := strconv.Atoi(key)\n\t\tif keyintc > keyint {\n\t\t\tkeyint = keyintc\n\t\t}\n\t\trow, ok = <-rowChan\n\t}\n\n\treturn []byte(strconv.Itoa(keyint)), nil\n}", "func (cache *LRUCache) GetMostRecentKey() (string, bool) {\n\tif len(cache.hash) == 0 {\n\t\treturn \"\", false\n\t}\n\n\treturn cache.curr.key, true\n}", "func (b *raftBadger) LastIndex() (uint64, error) {\n\tstore := b.gs.GetStore().(*badger.DB)\n\tlast := uint64(0)\n\tif err := store.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\t\topts.Reverse = true\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\t\t// see https://github.com/dgraph-io/badger/issues/436\n\t\t// and https://github.com/dgraph-io/badger/issues/347\n\t\tseekKey := append(dbLogPrefix, 0xFF)\n\t\tit.Seek(seekKey)\n\t\tif it.ValidForPrefix(dbLogPrefix) {\n\t\t\titem := it.Item()\n\t\t\tk := string(item.Key()[len(dbLogPrefix):])\n\t\t\tidx, err := strconv.ParseUint(k, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlast = idx\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn 0, err\n\t}\n\treturn last, nil\n}", "func (tc *sklImpl) GetMax(start, end roachpb.Key) (hlc.Timestamp, uuid.UUID) {\n\tvar val cacheValue\n\tif len(end) == 0 {\n\t\tval = tc.cache.LookupTimestamp(nonNil(start))\n\t} else {\n\t\tval = tc.cache.LookupTimestampRange(nonNil(start), end, excludeTo)\n\t}\n\treturn val.ts, val.txnID\n}", "func (entries Entries) max() (uint64, bool) {\n\tif len(entries) == 0 {\n\t\treturn 0, false\n\t}\n\n\treturn entries[len(entries)-1].Key(), true\n}", "func (l *LevelDB) LastIndex() (uint64, error) {\n\titer := l.db.NewIterator(&util.Range{Start: nil, Limit: nil}, nil)\n\tdefer iter.Release()\n\titer.Last()\n\titer.Prev()\n\n\tfor iter.Next() {\n\t\tkey := binary.LittleEndian.Uint64(iter.Key())\n\t\treturn key, nil\n\t}\n\n\treturn 0, nil\n}", "func TestIntMaxProperties(t *testing.T) {\n\tf := func(c intMaxTestCase) bool {\n\t\tvar (\n\t\t\tks []int\n\t\t\tvs []int\n\t\t)\n\t\tfor k, kVals := range c.valsByKey {\n\t\t\tfor _, v := range kVals {\n\t\t\t\tks = append(ks, k)\n\t\t\t\tvs = append(vs, v)\n\t\t\t}\n\t\t}\n\t\tslice := bigslice.Const(c.numShards, ks, vs)\n\t\tslice = IntMax(slice)\n\t\tscanner := slicetest.Run(t, slice)\n\t\tvar (\n\t\t\tk int\n\t\t\tmax int\n\t\t\tgot = make(map[int]int)\n\t\t)\n\t\tfor scanner.Scan(context.Background(), &k, &max) {\n\t\t\t// Each key exists in the input.\n\t\t\tinVs, ok := c.valsByKey[k]\n\t\t\tif !ok {\n\t\t\t\tt.Logf(\"key not in input: %v\", k)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t// The maximum value exists in the input for the key.\n\t\t\tvar found bool\n\t\t\tfor _, inV := range inVs {\n\t\t\t\tif max == inV {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tt.Logf(\"value not found key inputs for key %v: %v\", k, max)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t// No input for the key is greater than the computed maximum.\n\t\t\tfor _, inV := range inVs {\n\t\t\t\tif max < inV {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\t// No key is duplicated.\n\t\t\tif _, ok = got[k]; ok {\n\t\t\t\tt.Logf(\"duplicate k: %v\", k)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tgot[k] = max\n\t\t}\n\n\t\treturn true\n\t}\n\tc := quick.Config{MaxCount: 10}\n\tif err := quick.Check(f, &c); err != nil {\n\t\tt.Error(err)\n\t}\n}", "func MaxAckSeqKey(sourceChain, destinationChain string) []byte {\n\treturn []byte(MaxAckSeqPath(sourceChain, destinationChain))\n}", "func (cache *LRUCache) GetMostRecentKey() (string, bool) {\n\tif cache.listofMostRecent.head == nil {\n\t\treturn \"\", false\n\t}\n\treturn cache.listofMostRecent.head.key, true\n}", "func (n *Node) Max() int {\n\tif n.Right == nil {\n\t\treturn n.Key\n\t}\n\n\treturn n.Right.Max()\n}", "func FindNextGreatestToKey(k int64, l int64, h int64, s []int64) (int64, error) {\n\tintervalLength := h - l\n\tswitch {\n\tcase intervalLength == 0:\n\t\tswitch {\n\t\tcase s[h] > k:\n\t\t\treturn h, nil\n\t\tcase h+1 < int64(len(s)):\n\t\t\treturn h + 1, nil\n\t\tdefault:\n\t\t\treturn 0, errors.New(\"no elem > than key\")\n\t\t}\n\tcase intervalLength == 1:\n\t\tswitch {\n\t\tcase s[l] > k:\n\t\t\treturn l, nil\n\t\tcase s[h] > k:\n\t\t\treturn h, nil\n\t\tcase h+1 < int64(len(s)):\n\t\t\treturn h + 1, nil\n\t\tdefault:\n\t\t\treturn 0, errors.New(\"no elem > than key\")\n\t\t\t//no k\n\t\t}\n\tdefault:\n\t\tmidIntervalIndex := (h + l) / 2\n\t\tmid := s[midIntervalIndex]\n\t\tswitch {\n\t\tcase mid > k:\n\t\t\th = midIntervalIndex - 1\n\t\tcase mid <= k:\n\t\t\tl = midIntervalIndex + 1\n\t\t}\n\t\treturn FindNextGreatestToKey(k, l, h, s)\n\t}\n}", "func (t *Table) Biggest() y.Key { return t.biggest }", "func longestPrefix(k1, k2 []byte) int {\n\tlimit := min(len(k1), len(k2))\n\tfor i := 0; i < limit; i++ {\n\t\tif k1[i] != k2[i] {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn limit\n}", "func (i *InmemStore) LastIndex() (uint64, error) {\n\ti.l.RLock()\n\tdefer i.l.RUnlock()\n\treturn i.highIndex, nil\n}", "func GetNodeMaxKeys(node []byte) uint32 {\n\tswitch GetNodeType(node) {\n\tcase TypeInternalNode:\n\t\t// For an internal node, the maximum key is always its right key.\n\t\treturn *InternalNodeKey(node, *InternalNodeNumKeys(node)-1)\n\tcase TypeLeafNode:\n\t\t// For a leaf node, it’s the key at the maximum index\n\t\treturn *LeafNodeKey(node, *LeafNodeNumCells(node)-1)\n\tdefault:\n\t\tfmt.Printf(\"Unkown node type\\n\")\n\t\tos.Exit(util.ExitFailure)\n\t\treturn 0\n\t}\n}", "func (h *hashLongestMatchQuickly) FindLongestMatch(dictionary *encoderDictionary, data []byte, ring_buffer_mask uint, distance_cache []int, cur_ix uint, max_length uint, max_backward uint, gap uint, max_distance uint, out *hasherSearchResult) {\n\tvar best_len_in uint = out.len\n\tvar cur_ix_masked uint = cur_ix & ring_buffer_mask\n\tvar key uint32 = h.HashBytes(data[cur_ix_masked:])\n\tvar compare_char int = int(data[cur_ix_masked+best_len_in])\n\tvar min_score uint = out.score\n\tvar best_score uint = out.score\n\tvar best_len uint = best_len_in\n\tvar cached_backward uint = uint(distance_cache[0])\n\tvar prev_ix uint = cur_ix - cached_backward\n\tvar bucket []uint32\n\tout.len_code_delta = 0\n\tif prev_ix < cur_ix {\n\t\tprev_ix &= uint(uint32(ring_buffer_mask))\n\t\tif compare_char == int(data[prev_ix+best_len]) {\n\t\t\tvar len uint = findMatchLengthWithLimit(data[prev_ix:], data[cur_ix_masked:], max_length)\n\t\t\tif len >= 4 {\n\t\t\t\tvar score uint = backwardReferenceScoreUsingLastDistance(uint(len))\n\t\t\t\tif best_score < score {\n\t\t\t\t\tbest_score = score\n\t\t\t\t\tbest_len = uint(len)\n\t\t\t\t\tout.len = uint(len)\n\t\t\t\t\tout.distance = cached_backward\n\t\t\t\t\tout.score = best_score\n\t\t\t\t\tcompare_char = int(data[cur_ix_masked+best_len])\n\t\t\t\t\tif h.bucketSweep == 1 {\n\t\t\t\t\t\th.buckets[key] = uint32(cur_ix)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif h.bucketSweep == 1 {\n\t\tvar backward uint\n\t\tvar len uint\n\n\t\t/* Only one to look for, don't bother to prepare for a loop. */\n\t\tprev_ix = uint(h.buckets[key])\n\n\t\th.buckets[key] = uint32(cur_ix)\n\t\tbackward = cur_ix - prev_ix\n\t\tprev_ix &= uint(uint32(ring_buffer_mask))\n\t\tif compare_char != int(data[prev_ix+best_len_in]) {\n\t\t\treturn\n\t\t}\n\n\t\tif backward == 0 || backward > max_backward {\n\t\t\treturn\n\t\t}\n\n\t\tlen = findMatchLengthWithLimit(data[prev_ix:], data[cur_ix_masked:], max_length)\n\t\tif len >= 4 {\n\t\t\tvar score uint = backwardReferenceScore(uint(len), backward)\n\t\t\tif best_score < score {\n\t\t\t\tout.len = uint(len)\n\t\t\t\tout.distance = backward\n\t\t\t\tout.score = score\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\tbucket = h.buckets[key:]\n\t\tvar i int\n\t\tprev_ix = uint(bucket[0])\n\t\tbucket = bucket[1:]\n\t\tfor i = 0; i < h.bucketSweep; (func() { i++; tmp3 := bucket; bucket = bucket[1:]; prev_ix = uint(tmp3[0]) })() {\n\t\t\tvar backward uint = cur_ix - prev_ix\n\t\t\tvar len uint\n\t\t\tprev_ix &= uint(uint32(ring_buffer_mask))\n\t\t\tif compare_char != int(data[prev_ix+best_len]) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif backward == 0 || backward > max_backward {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlen = findMatchLengthWithLimit(data[prev_ix:], data[cur_ix_masked:], max_length)\n\t\t\tif len >= 4 {\n\t\t\t\tvar score uint = backwardReferenceScore(uint(len), backward)\n\t\t\t\tif best_score < score {\n\t\t\t\t\tbest_score = score\n\t\t\t\t\tbest_len = uint(len)\n\t\t\t\t\tout.len = best_len\n\t\t\t\t\tout.distance = backward\n\t\t\t\t\tout.score = score\n\t\t\t\t\tcompare_char = int(data[cur_ix_masked+best_len])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif h.useDictionary && min_score == out.score {\n\t\tsearchInStaticDictionary(dictionary, h, data[cur_ix_masked:], max_length, max_backward+gap, max_distance, out, true)\n\t}\n\n\th.buckets[key+uint32((cur_ix>>3)%uint(h.bucketSweep))] = uint32(cur_ix)\n}", "func MaxKeys(value int) Option {\n\treturn addParam(\"maxkeys\", strconv.Itoa(value))\n}", "func (ls *LevelDBStore) LastIndex() (uint64, error) {\n\tls.rwMtx.Lock()\n\tdefer ls.rwMtx.Unlock()\n\titer := ls.ldb.NewIterator(nil, nil)\n\tdefer iter.Release()\n\tif iter.Last() {\n\t\tkey := iter.Key()\n\t\treturn bytesToUint64(key), nil\n\t}\n\treturn 0, nil\n}", "func calcUpperBound(prefix string) []byte {\n\tif len(prefix) == 0 {\n\t\treturn []byte{}\n\t}\n\n\tp := []byte(prefix)\n\n\tp[len(p)-1] = p[len(p)-1] + 1\n\treturn p\n}", "func MaxKeys(max int) Option {\n\treturn func(lc *memoryCache) error {\n\t\tlc.maxKeys = max\n\t\treturn nil\n\t}\n}", "func MaxKeys(max int) Option {\n\treturn func(lc *loadingCache) error {\n\t\tlc.maxKeys = max\n\t\treturn nil\n\t}\n}", "func (ms *MemoryStorage) LastIndex() (uint64, error) {\n\tms.Lock()\n\tdefer ms.Unlock()\n\treturn ms.lastIndex(), nil\n}", "func (n *Node) Maximum() ([]byte, interface{}, bool) {\n\tfor {\n\t\tif num := len(n.edges); num > 0 {\n\t\t\tn = n.edges[num-1].node\n\t\t\tcontinue\n\t\t}\n\t\tif n.isLeaf() {\n\t\t\treturn n.leaf.key, n.leaf.val, true\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil, nil, false\n}", "func TestPrefixEndKey(t *testing.T) {\n\tdefer leaktest.AfterTest(t)\n\ttestData := []struct {\n\t\tprefix, expEnd proto.Key\n\t}{\n\t\t{proto.KeyMin, proto.KeyMax},\n\t\t{proto.Key(\"0\"), proto.Key(\"1\")},\n\t\t{proto.Key(\"a\"), proto.Key(\"b\")},\n\t\t{proto.Key(\"db0\"), proto.Key(\"db1\")},\n\t\t{proto.Key(\"\\xfe\"), proto.Key(\"\\xff\")},\n\t\t{proto.KeyMax, proto.KeyMax},\n\t\t{proto.Key(\"\\xff\\xff\"), proto.Key(\"\\xff\\xff\")},\n\t}\n\n\tfor i, test := range testData {\n\t\tif !test.prefix.PrefixEnd().Equal(test.expEnd) {\n\t\t\tt.Errorf(\"%d: %q end key %q != %q\", i, test.prefix, test.prefix.PrefixEnd(), test.expEnd)\n\t\t}\n\t}\n}", "func MaxKeys(max int) Option {\n\treturn func(lc cacheWithOpts) error {\n\t\treturn lc.setMaxKeys(max)\n\t}\n}", "func (bst *StringBinarySearchTree) Max() *string {\n\tbst.lock.RLock()\n\tdefer bst.lock.RUnlock()\n\tn := bst.root\n\tif n == nil {\n\t\treturn nil\n\t}\n\tfor {\n\t\tif n.right == nil {\n\t\t\treturn &n.value\n\t\t}\n\t\tn = n.right\n\t}\n}", "func (p *partitionImpl) FindLastRowKey(keyBuf []byte, key uint64, keyfn sif.KeyingOperation) (int, error) {\n\t// find the first matching uint64 key\n\tfirstKey, err := p.FindFirstRowKey(keyBuf, key, keyfn) // this will error with missing key if it doesn't exist\n\tif err != nil {\n\t\treturn firstKey, err\n\t}\n\tlastKey := firstKey\n\t// iterate over each row with a matching key to find the last one with identical key bytes\n\tfor i := firstKey + 1; i < p.GetNumRows(); i++ {\n\t\tif k, err := p.GetKey(i); err != nil {\n\t\t\treturn -1, err\n\t\t} else if k != key {\n\t\t\tbreak // current key isn't the same, break out\n\t\t}\n\t\trowKey, err := keyfn(&rowImpl{\n\t\t\tmeta: p.GetRowMeta(i),\n\t\t\tdata: p.GetRowData(i),\n\t\t\tvarData: p.GetVarRowData(i),\n\t\t\tserializedVarData: p.GetSerializedVarRowData(i),\n\t\t\tschema: p.GetCurrentSchema(),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn -1, err\n\t\t} else if reflect.DeepEqual(keyBuf, rowKey) {\n\t\t\tlastKey = i\n\t\t} else {\n\t\t\tbreak // current key isn't the same, break out\n\t\t}\n\t}\n\treturn lastKey, nil\n}", "func MaxKeys(max int) Option {\n\treturn func(lc *cacheImpl) error {\n\t\tlc.maxKeys = max\n\t\treturn nil\n\t}\n}", "func FixMaxEntryIndex(rdb *Store, profile *pb.Profile) error {\n\tuuid1, err := uuid.FromString(profile.Uuid)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// MAX Delimiter Key\n\tkey := MaxUUIDFlakeKey(TableEntryIndex, uuid1)\n\treturn rdb.Put(key.Bytes(), []byte(\"0000\"))\n}", "func ExampleClient_TdMax() {\n\thost := \"localhost:6379\"\n\tvar client = redisbloom.NewClient(host, \"nohelp\", nil)\n\n\tkey := \"example\"\n\t_, err := client.TdCreate(key, 10)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tsamples := map[float64]float64{1.0: 1.0, 2.0: 2.0, 3.0: 3.0}\n\t_, err = client.TdAdd(key, samples)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tmax, err := client.TdMax(key)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tfmt.Println(max)\n\t// Output: 3\n}", "func (idx *Tree) MinKey(searchPrefix []byte) (v uint64, ok bool) {\n\traw, _ := idx.partialSearch(searchPrefix)\n\tif raw == 0 {\n\t\treturn 0, false\n\t}\n\tif isLeaf(raw) {\n\t\treturn getLeafValue(raw), true\n\t}\n\t// now find the min\nsearchLoop:\n\tfor {\n\t\t_, node, count, prefixLen := explodeNode(raw)\n\t\tblock := int(node >> blockSlotsShift)\n\t\toffset := int(node & blockSlotsOffsetMask)\n\t\tdata := idx.blocks[block].data[offset:]\n\t\tvar prefixSlots int\n\t\tif prefixLen > 0 {\n\t\t\tif prefixLen == 255 {\n\t\t\t\tprefixLen = int(data[0])\n\t\t\t\tprefixSlots = (prefixLen + 15) >> 3\n\t\t\t} else {\n\t\t\t\tprefixSlots = (prefixLen + 7) >> 3\n\t\t\t}\n\t\t\tdata = data[prefixSlots:]\n\t\t}\n\t\tif count >= fullAllocFrom {\n\t\t\t// find min, iterate from bottom\n\t\t\tfor k := range data[:count] {\n\t\t\t\ta := atomic.LoadUint64(&data[k])\n\t\t\t\tif a != 0 {\n\t\t\t\t\tif isLeaf(a) {\n\t\t\t\t\t\treturn getLeafValue(a), true\n\t\t\t\t\t}\n\t\t\t\t\traw = a\n\t\t\t\t\tcontinue searchLoop\n\t\t\t\t}\n\t\t\t}\n\t\t\t// BUG: this might happen if all children in the node has been deleted, since we currently don't shrink node-256. we should go back in the tree!\n\t\t\treturn 0, false\n\t\t}\n\t\t// load first child (since they are ordered)\n\t\ta := atomic.LoadUint64(&data[0])\n\t\tif isLeaf(a) {\n\t\t\treturn getLeafValue(a), true\n\t\t}\n\t\traw = a\n\t}\n}", "func GetMaxIndexes() int {\r\n\treturn converter.StrToInt(SysString(MaxIndexes))\r\n}", "func _enumerateLimitedKeysReversedForPrefix(db *badger.DB, dbPrefix []byte, limit uint64) (_keysFound [][]byte, _valsFound [][]byte) {\n\tkeysFound := [][]byte{}\n\tvalsFound := [][]byte{}\n\n\tdbErr := db.View(func(txn *badger.Txn) error {\n\t\tvar err error\n\t\tkeysFound, valsFound, err = _enumerateLimitedKeysReversedForPrefixWithTxn(txn, dbPrefix, limit)\n\t\treturn err\n\t})\n\tif dbErr != nil {\n\t\tglog.Errorf(\"_enumerateKeysForPrefix: Problem fetching keys and vlaues from db: %v\", dbErr)\n\t\treturn nil, nil\n\t}\n\n\treturn keysFound, valsFound\n}", "func (b *BadgerStore) LastIndex() (uint64, error) {\n\treturn b.firstIndex(true)\n}", "func (b *BadgerStore) LastIndex() (uint64, error) {\n\treturn b.firstIndex(true)\n}", "func assertLongestSuffix(t *testing.T, tree *Tree, key string, expectedFound bool) {\n\tmatchedKey, value, found := tree.LongestSuffix([]byte(key))\n\tassert.Equal(t, expectedFound, found)\n\tif expectedFound && value != nil {\n\t\tassert.Equal(t, string(matchedKey), value.(string))\n\t}\n}", "func (c *Client) BZPopMax(_ context.Context, timeout time.Duration, keys ...string) *redis.ZWithKeyCmd {\n\treturn c.cli.BZPopMax(timeout, keys...)\n}", "func (p *MessagePartition) calculateMaxMessageIdFromIndex(fileId uint64) (uint64, error) {\n\tstat, err := os.Stat(p.indexFilenameByMessageId(fileId))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tentriesInIndex := uint64(stat.Size() / int64(INDEX_ENTRY_SIZE))\n\n\treturn (entriesInIndex - 1 + fileId), nil\n}", "func (m *Matcher) GetLongest(sw *util.SlidingWindow) (*matcher.Encoded, error) {\n\tlongestMatch := 0\n\tstartSearch := -1\n\tstartLookAhead := -1\n\t//fmt.Println(\"***********************************************\")\n\t//fmt.Printf(\"finding longest match!!\\nSearch<head: %v, tail:%v, numElems: %v>, Look Ahead<head: %v, tail:%v, numElems: %v>\\n\",\n\t//\tsw.Search.GetFront(), sw.Search.GetRear(), sw.Search.GetCount(),\n\t//\tsw.LookAhead.GetFront(), sw.LookAhead.GetRear(), sw.LookAhead.GetCount())\n\n\t//fmt.Println(\"Search isEmpty:\", sw.Search.IsEmpty(), \" Look Ahead isEmpty:\", sw.LookAhead.IsEmpty())\n\n\tif !sw.Search.IsEmpty() && !sw.LookAhead.IsEmpty() {\n\t\tfor i := int(sw.Search.GetFront()); i != int(sw.Search.GetRear()); i = (i + 1) % int(sw.Search.GetSize()) {\n\t\t\tcounter := 0\n\t\t\tj := int(sw.LookAhead.GetFront())\n\t\t\tfor sw.Search.GetBuffer()[i+counter] == sw.LookAhead.GetBuffer()[j+counter] {\n\t\t\t\tcounter++\n\t\t\t\tif ((i + counter) >= int(sw.Search.GetSize())) || ((j + counter) >= int(sw.LookAhead.GetSize())) {\n\t\t\t\t\t//fmt.Println(\"breaking!!!\")\n\t\t\t\t\tbreak\n\t\t\t\t} else if counter > longestMatch {\n\t\t\t\t\tlongestMatch = counter\n\t\t\t\t\tstartSearch = i\n\t\t\t\t\tstartLookAhead = j\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//fmt.Println(\"found longest match =\", longestMatch)\n\t//fmt.Println(\"***********************************************\")\n\n\t// If the longest match is less than 3, then just ignore it\n\tif longestMatch <= util.MaxUncompressed {\n\t\tdatum, err := sw.LookAhead.Peek()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &matcher.Encoded{\n\t\t\tType: matcher.UNCOMPRESSED,\n\t\t\tDatum: datum,\n\t\t\tOffset: 0,\n\t\t\tLength: 0,\n\t\t}, nil\n\t}\n\n\t//fmt.Printf(\"longest match found!! search start idx: %v, look ahead start idx: %v\\n\",\n\t//\tstartSearch, startLookAhead)\n\t// If not, then calculate the offset and return\n\t// offset = dist of startSearch from search.rear + dist of startLookAhead from lookahead.front\n\toffset := sw.Search.GetDist(int32(startSearch), sw.Search.GetRear()) +\n\t\tsw.LookAhead.GetDist(sw.LookAhead.GetFront(), int32(startLookAhead)) - 1\n\n\treturn &matcher.Encoded{\n\t\tType: matcher.COMPRESSED,\n\t\tOffset: offset,\n\t\tLength: uint8(longestMatch),\n\t}, nil\n}", "func (s *GoSort) FindMaxElementAndIndex() (interface{},int) {\n var index = 0\n \n for i := 1; i < s.Len(); i++ {\n if s.GreaterThan(i, index) {\n index = i\n }\n }\n return s.values[index], index\n}", "func (bst *BinarySearch) Max() (int, error) {\n\tbst.lock.RLock()\n\tdefer bst.lock.RUnlock()\n\n\tn := bst.root\n\tif n == nil {\n\t\treturn 0, fmt.Errorf(\"max: no nodes exist in tree\")\n\t}\n\tfor {\n\t\tif n.right == nil {\n\t\t\treturn n.value, nil\n\t\t}\n\t\tn = n.right\n\t}\n}", "func maxNamespace(hash []byte, size namespace.IDSize) []byte {\n\tmax := make([]byte, 0, size)\n\treturn append(max, hash[size:size*2]...)\n}", "func findLongestPrefix(names []string) int {\n\tif len(names) < 1 {\n\t\treturn 0\n\t}\n\treaders := make([]*strings.Reader, 0, len(names))\n\tfor _, m := range names {\n\t\treaders = append(readers, strings.NewReader(m))\n\t}\n\n\tfor {\n\t\trune0, _, err := readers[0].ReadRune()\n\t\tif err != nil {\n\t\t\treturn int(readers[0].Size())\n\t\t}\n\t\tfor _, re := range readers[1:] {\n\t\t\tr, _, err := re.ReadRune()\n\t\t\tif err != nil {\n\t\t\t\treturn int(re.Size())\n\t\t\t}\n\t\t\tif r != rune0 {\n\t\t\t\tre.UnreadRune()\n\t\t\t\treturn int(re.Size()) - re.Len()\n\t\t\t}\n\t\t}\n\t}\n\treturn 0\n}", "func (px *Paxos) Max() int {\n\tkeys := px.sortedSeqs()\n\tif len(keys) == 0 {\n\t\treturn -1\n\t} else {\n\t\tsort.Ints(keys)\n\t}\n\treturn keys[len(keys)-1]\n}", "func getMaxID() int {\n\n\tif len(cdb.classMap) != 0 {\n\t\tkeys := make([]int, 0, len(cdb.classMap))\n\t\tfor k := range cdb.classMap {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Ints(keys)\n\t\treturn keys[len(keys)-1]\n\t}\n\n\treturn -1\n\n}", "func (o LookupManagedPrefixListResultOutput) MaxEntries() pulumi.IntOutput {\n\treturn o.ApplyT(func(v LookupManagedPrefixListResult) int { return v.MaxEntries }).(pulumi.IntOutput)\n}", "func (params *KeyParameters) MaxMsgBytes() int {\n\treturn (params.P.BitLen() / 8) - 4\n}", "func getLocationWithLongestPrefix(locations []Location) *Location {\n\tlongest := &locations[0]\n\tlength := len(locations[0].Prefix)\n\n\tfor _, location := range locations {\n\t\tif len(location.Prefix) > length {\n\t\t\tlongest, length = &location, len(location.Prefix)\n\t\t}\n\t}\n\n\treturn longest\n}", "func FindKthMax(nums []int, k int) (int, error) {\n\tindex := len(nums) - k\n\treturn kthNumber(nums, index)\n}", "func (t *tree) longestPrefix(k1, k2 string) int {\n\tmax := len(k1)\n\tif l := len(k2); l < max {\n\t\tmax = l\n\t}\n\tvar i int\n\tfor i = 0; i < max; i++ {\n\t\tif k1[i] != k2[i] {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn i\n}", "func FindWords(prefix string, max string) []string {\n convertedMax, _ := strconv.ParseInt(max, 10, 8)\n var listOfWords []string\n listOfWords = trie.FindEntries(prefix, uint8(convertedMax))\n return listOfWords\n}", "func (s *OverflowShelf) PopMax(temp string) (maxOrderID uuid.UUID, found bool, err error) {\n\tvar orders map[uuid.UUID]float32\n\torders, err = s.getOrders(temp)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(orders) == 0 {\n\t\t// no orders for temp, return not found.\n\t\treturn\n\t}\n\n\tmaxDecayRate := float32(-1)\n\n\t// O(n) scan is quick for small sets. When size gets bigger,\n\t// use priority queues instead of slices to Store the orders.\n\tfor orderID, decayRate := range orders {\n\t\tif decayRate > maxDecayRate {\n\t\t\tmaxDecayRate = decayRate\n\t\t\tmaxOrderID = orderID\n\t\t\tfound = true\n\t\t}\n\t}\n\n\tdelete(orders, maxOrderID)\n\treturn\n}", "func (t *Indexed) Max(i, j int) int {\n\treturn -1\n}", "func (k Keeper) GetLastValidatorPower(ctx sdk.Context, index string) (val types.LastValidatorPower, found bool) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.LastValidatorPowerKey))\n\n\tb := store.Get(types.KeyPrefix(index))\n\tif b == nil {\n\t\treturn val, false\n\t}\n\n\tk.cdc.MustUnmarshalBinaryBare(b, &val)\n\treturn val, true\n}", "func (i *LogStore) LastIndex() (uint64, error) {\n\ti.l.RLock()\n\tdefer i.l.RUnlock()\n\treturn i.highIndex, nil\n}", "func (k Keeper) GetMaxBlockLock(ctx sdk.Context) uint64 {\n\tparams := k.GetParams(ctx)\n\treturn params.MaxBlockLock\n}", "func (tree *RedBlack[K, V]) Max() (v alg.Pair[K, V], ok bool) {\n\tif max := tree.root.max(); max != nil {\n\t\treturn alg.Two(max.key, max.value), true\n\t}\n\treturn\n}", "func MostLikelyXorKey(cypherBlock []byte) byte {\n\tbestScore := 0.0\n\tvar winnerK byte\n\tfor k := 0; k < 255; k++ {\n\t\tdata := SingleCharXor(cypherBlock, byte(k))\n\t\tcMap := NewCharMap(data)\n\t\tscore := cMap.EnglishScore(true)\n\t\tif score >= bestScore {\n\t\t\t// give a preference to ascii letters\n\t\t\tif score == bestScore && IsASCIILetter(winnerK) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbestScore = score\n\t\t\twinnerK = byte(k)\n\t\t}\n\t}\n\n\treturn winnerK\n}", "func (w *WaterMark) LastIndex() uint64 {\n\treturn w.lastIndex.Load()\n}", "func (c *Signature) Max() int {\n\tif c.MaxValue == nil {\n\t\treturn 0\n\t}\n\treturn toolbox.AsInt(c.MaxValue)\n}", "func FindLastIndex(data, callback interface{}, args ...int) (int, error) {\n\tvar err error\n\n\tresult := func(err *error) int {\n\t\tdefer catch(err)\n\n\t\tif !isNonNilData(err, \"data\", data) {\n\t\t\treturn -1\n\t\t}\n\n\t\tdataValue, _, _, dataValueLen := inspectData(data)\n\n\t\tif !isSlice(err, \"data\", dataValue) {\n\t\t\treturn -1\n\t\t}\n\n\t\tcallbackValue, callbackType := inspectFunc(err, callback)\n\t\tif *err != nil {\n\t\t\treturn -1\n\t\t}\n\n\t\tcallbackTypeNumIn := validateFuncInputForSliceLoop(err, callbackType, dataValue)\n\t\tif *err != nil {\n\t\t\treturn -1\n\t\t}\n\n\t\tvalidateFuncOutputOneVarBool(err, callbackType, true)\n\t\tif *err != nil {\n\t\t\treturn -1\n\t\t}\n\n\t\tif dataValueLen == 0 {\n\t\t\treturn -1\n\t\t}\n\n\t\tendIndex := dataValueLen\n\t\tif len(args) > 0 {\n\t\t\tendIndex = args[0]\n\t\t}\n\n\t\tresult := -1\n\n\t\tforEachSliceStoppable(dataValue, dataValueLen, func(each reflect.Value, i int) bool {\n\t\t\tif i > endIndex {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tres := callFuncSliceLoop(callbackValue, each, i, callbackTypeNumIn)\n\t\t\tif res[0].Bool() {\n\t\t\t\tresult = i\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\n\t\tif result < 0 {\n\t\t\treturn result\n\t\t}\n\n\t\treturn result\n\t}(&err)\n\n\treturn result, err\n}", "func MaxValue(freqMap map[string]int) int {\n m := 0\n firstTimeThrough := true\n\n for _, value := range freqMap {\n if firstTimeThrough || value > m {\n m = value\n firstTimeThrough = false\n }\n }\n\n return m\n}", "func (k Keeper) MaxValidators(ctx sdk.Context) (res uint32) {\n\tk.paramspace.Get(ctx, types.KeyMaxValidators, &res)\n\treturn\n}", "func getLastKnownPosition(txn *badger.Txn, pn insolar.PulseNumber) (uint32, error) {\n\tkey := lastKnownRecordPositionKey{pn: pn}\n\n\tfullKey := append(key.Scope().Bytes(), key.ID()...)\n\n\titem, err := txn.Get(fullKey)\n\tif err != nil {\n\t\tif err == badger.ErrKeyNotFound {\n\t\t\treturn 0, ErrNotFound\n\t\t}\n\t\treturn 0, err\n\t}\n\n\tbuff, err := item.ValueCopy(nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn binary.BigEndian.Uint32(buff), nil\n}", "func (na *NArray) MaxIdx() (float32, []int) {\n\n\tvar offset int\n\tmax := float32(-math.MaxFloat32)\n\tfor i := 0; i < len(na.Data); i++ {\n\t\tif na.Data[i] > max {\n\t\t\tmax = na.Data[i]\n\t\t\toffset = i\n\t\t}\n\t}\n\treturn max, na.ReverseIndex(offset)\n}", "func (tb *TimeBucket) Max() int64 { return tb.max }", "func (t *BinarySearchTree) FindMax() int {\n\tnode := t.root\n\tfor {\n\t\tif node.right != nil {\n\t\t\tnode = node.right\n\t\t} else {\n\t\t\treturn node.data\n\t\t}\n\t}\n}", "func Max(bs []byte) int {\n\tvar max int\n\tfor _, dist := range All(bs) {\n\t\tif dist > max {\n\t\t\tmax = dist\n\t\t}\n\t}\n\treturn max\n}", "func LastIndex(key string) string {\n\treturn key[strings.LastIndexAny(key, \"/\")+1:]\n}", "func GetHighestVersion(tags map[string]string) (*int64, error) {\n\tif tags == nil {\n\t\treturn nil, errNoKnownVersions\n\t}\n\tvar result *int64\n\tfor tag := range tags {\n\t\tversion, err := strconv.ParseInt(tag, 10, 64)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif result == nil || version > *result {\n\t\t\tresult = &version\n\t\t}\n\t}\n\tif result == nil {\n\t\treturn nil, errNoKnownVersions\n\t}\n\treturn result, nil\n}", "func getMaxName() string {\n\tl, err := filepath.Glob(\"*.cert\")\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to Glob *.pem: %s\", err)\n\t}\n\tres := []int{}\n\tfor _, k := range l {\n\t\tres = append(res, tonum(k))\n\t}\n\tmax := 0\n\tfor _, p := range res {\n\t\tif p > max {\n\t\t\tmax = p\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%d\", max+1)\n}", "func searchInDiskTables(dbDir string, maxIndex int, key []byte) ([]byte, bool, error) {\n\tfor index := maxIndex; index >= 0; index-- {\n\t\tvalue, exists, err := searchInDiskTable(dbDir, index, key)\n\t\tif err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"failed to search in disk table with index %d: %w\", index, err)\n\t\t}\n\n\t\tif exists {\n\t\t\treturn value, exists, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}", "func (na *NArray) Max() float32 {\n\tif na == nil || len(na.Data) == 0 {\n\t\tpanic(\"unable to take max of nil or zero-sizes array\")\n\t}\n\treturn maxSliceElement(na.Data)\n}", "func (r *Redis) MaxSize() int64 {\n\treturn r.maxSize\n}", "func LastIndexOf(data interface{}, search interface{}, args ...int) (int, error) {\n\tvar err error\n\n\tresult := func(err *error) int {\n\t\tdefer catch(err)\n\n\t\tif !isNonNilData(err, \"data\", data) {\n\t\t\treturn -1\n\t\t}\n\n\t\tdataValue, _, _, dataValueLen := inspectData(data)\n\n\t\tif !isSlice(err, \"data\", dataValue) {\n\t\t\treturn -1\n\t\t}\n\n\t\tstartIndex := dataValueLen - 1\n\t\tif len(args) > 0 {\n\t\t\tstartIndex = args[0]\n\t\t}\n\n\t\tif dataValueLen == 0 {\n\t\t\treturn -1\n\t\t}\n\n\t\tresult := -1\n\n\t\tforEachSliceStoppable(dataValue, dataValueLen, func(each reflect.Value, i int) bool {\n\t\t\tif startIndex > -1 {\n\t\t\t\tiFromRight := startIndex - i\n\t\t\t\tif iFromRight > (dataValueLen-1) || iFromRight < 0 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\teachFromRight := dataValue.Index(iFromRight)\n\t\t\t\tif eachFromRight.Interface() == search && result == -1 {\n\t\t\t\t\tresult = iFromRight\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tiFromRight := dataValueLen + startIndex - i\n\t\t\t\tif iFromRight > (dataValueLen-1) || iFromRight < 0 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\teachFromRight := dataValue.Index(iFromRight)\n\t\t\t\tif eachFromRight.Interface() == search && result == -1 {\n\t\t\t\t\tresult = iFromRight\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\n\t\treturn result\n\t}(&err)\n\n\treturn result, err\n}", "func (master *MasterIndex) LastIndex() Index {\n\treturn master.indexCache[len(master.indexCache)-1]\n}", "func (transaction *TokenUpdateTransaction) GetMaxBackoff() time.Duration {\n\tif transaction.maxBackoff != nil {\n\t\treturn *transaction.maxBackoff\n\t}\n\n\treturn 8 * time.Second\n}", "func MaxIndex(vec mat.Vector) int {\n\tmax := math.Inf(-1)\n\tmaxIndex := -1\n\n\tfor i := 0; i < vec.Len(); i++ {\n\t\tvalue := vec.AtVec(i)\n\t\tif value > max {\n\t\t\tmax = value\n\t\t\tmaxIndex = i\n\t\t}\n\t}\n\n\treturn maxIndex\n}", "func MaxLen(n int) PktCnf1 {\n\treturn PktCnf1(n & 0xff)\n}", "func (r *radNode) getLast() *radNode {\n\tn := r.desc\n\tif n == nil {\n\t\treturn nil\n\t}\n\tif n.sis == nil {\n\t\treturn n\n\t}\n\tkey := string(n.prefix)\n\tfor d := n.sis; d != nil; d = d.sis {\n\t\tk := string(d.prefix)\n\t\tif k > key {\n\t\t\tn = d\n\t\t\tkey = k\n\t\t}\n\t}\n\treturn n\n}", "func (q *SimpleQueue) searchMaxExtID(ctx context.Context, source string, dt time.Time) (extID int64, ok bool, err *mft.Error) {\n\tblocks := make([]*SimpleQueueBlock, 0)\n\n\tif !q.mx.RTryLock(ctx) {\n\t\treturn extID, false, GenerateError(10027000)\n\t}\n\n\tfor i := len(q.Blocks) - 1; i >= 0; i-- {\n\t\tblocks = append(blocks, q.Blocks[i])\n\t\tif q.Blocks[i].Dt.Unix() < dt.Unix() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tq.mx.RUnlock()\n\tmaxID := int64(0)\n\tfor _, block := range blocks {\n\t\tif !block.mx.RTryLock(ctx) {\n\t\t\treturn extID, false, GenerateError(10027001)\n\t\t}\n\n\t\tif block.IsUnload {\n\t\t\terr = block.load(ctx, q)\n\t\t\tif err != nil {\n\t\t\t\treturn extID, false, err\n\t\t\t}\n\t\t} else {\n\t\t\tblock.LastGet = time.Now()\n\t\t}\n\n\t\tif len(block.Data) == 0 {\n\t\t\tblock.mx.RUnlock()\n\t\t\tcontinue\n\t\t}\n\n\t\tfor i := len(block.Data) - 1; i >= 0; i-- {\n\t\t\tif block.Data[i].Source == source {\n\t\t\t\tif maxID == 0 {\n\t\t\t\t\tmaxID = block.Data[i].ExternalID\n\t\t\t\t} else if maxID < block.Data[i].ExternalID {\n\t\t\t\t\tmaxID = block.Data[i].ExternalID\n\t\t\t\t}\n\t\t\t\tblock.mx.RUnlock()\n\t\t\t}\n\t\t}\n\n\t\tblock.mx.RUnlock()\n\t}\n\tif maxID != 0 {\n\t\treturn maxID, true, nil\n\t}\n\n\treturn extID, false, nil\n}", "func Max(Len int, Less func(i, j int) bool) int {\n\tmx := 0\n\tfor i := 1; i < Len; i++ {\n\t\tif Less(mx, i) {\n\t\t\tmx = i\n\t\t}\n\t}\n\treturn mx\n}", "func (_IUniswapV2Pair *IUniswapV2PairCallerSession) KLast() (*big.Int, error) {\r\n\treturn _IUniswapV2Pair.Contract.KLast(&_IUniswapV2Pair.CallOpts)\r\n}", "func (m *OrderedMap[K, V]) Max() *OrderedMapElement[K, V] {\n\treturn m.max(nil)\n}", "func NextLargerKey(key string) string {\n\treturn key + \"\\x00\" // the next string that is larger than key, but smaller than any other keys > key\n}" ]
[ "0.64017457", "0.63471687", "0.5947757", "0.5752474", "0.56805396", "0.55782866", "0.5567208", "0.55566853", "0.5465598", "0.54230475", "0.5320258", "0.53081363", "0.52548325", "0.52321553", "0.51663005", "0.515594", "0.51534414", "0.5117315", "0.5105535", "0.5103728", "0.5066215", "0.5051428", "0.49883723", "0.49680877", "0.4918796", "0.48976338", "0.48824608", "0.48644868", "0.48408487", "0.48233145", "0.48196343", "0.48148632", "0.48089647", "0.48060033", "0.48034284", "0.4797153", "0.4790417", "0.4777355", "0.4741937", "0.47248837", "0.4724738", "0.4721507", "0.4714758", "0.46947756", "0.46870172", "0.4661575", "0.46531954", "0.46435317", "0.46275347", "0.46275347", "0.46079528", "0.4576393", "0.456697", "0.45637247", "0.45523494", "0.4542613", "0.4530932", "0.45264518", "0.4508717", "0.45081908", "0.45030898", "0.4498837", "0.4496378", "0.44925576", "0.4483645", "0.44788378", "0.44483516", "0.4437768", "0.44250444", "0.44210643", "0.44064808", "0.4399684", "0.43917146", "0.43910456", "0.43669796", "0.4348235", "0.4347853", "0.43449336", "0.43229994", "0.43086445", "0.4304247", "0.42946216", "0.42764285", "0.42697185", "0.42643636", "0.42601842", "0.4248395", "0.423215", "0.4225136", "0.4218835", "0.41982841", "0.41920185", "0.4188973", "0.41654685", "0.41648984", "0.41627952", "0.41596484", "0.41397256", "0.41381666", "0.41349587" ]
0.76495737
0
MinKey returns the minimum key having the given searchPrefix, or the minimum key in the whole index if searchIndex is nil. Minimum means the first key in the lexicographic order. If keys are uint64 in BigEndian it is also the smallest number. If ok is false the index is empty.
func (idx *Tree) MinKey(searchPrefix []byte) (v uint64, ok bool) { raw, _ := idx.partialSearch(searchPrefix) if raw == 0 { return 0, false } if isLeaf(raw) { return getLeafValue(raw), true } // now find the min searchLoop: for { _, node, count, prefixLen := explodeNode(raw) block := int(node >> blockSlotsShift) offset := int(node & blockSlotsOffsetMask) data := idx.blocks[block].data[offset:] var prefixSlots int if prefixLen > 0 { if prefixLen == 255 { prefixLen = int(data[0]) prefixSlots = (prefixLen + 15) >> 3 } else { prefixSlots = (prefixLen + 7) >> 3 } data = data[prefixSlots:] } if count >= fullAllocFrom { // find min, iterate from bottom for k := range data[:count] { a := atomic.LoadUint64(&data[k]) if a != 0 { if isLeaf(a) { return getLeafValue(a), true } raw = a continue searchLoop } } // BUG: this might happen if all children in the node has been deleted, since we currently don't shrink node-256. we should go back in the tree! return 0, false } // load first child (since they are ordered) a := atomic.LoadUint64(&data[0]) if isLeaf(a) { return getLeafValue(a), true } raw = a } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (tf tFiles) searchMin(icmp *iComparer, ikey internalKey) int {\n\treturn sort.Search(len(tf), func(i int) bool {\n\t\treturn icmp.Compare(tf[i].imin, ikey) >= 0\n\t})\n}", "func (t *binarySearchST) Min() interface{} {\n\tutils.AssertF(!t.IsEmpty(), \"called Min() with empty symbol table\")\n\treturn t.keys[0]\n}", "func MinKey() Val { return Val{t: bsontype.MinKey} }", "func (t *BinarySearch[T]) Min() (T, bool) {\n\tret := minimum[T](t.Root, t._NIL)\n\tif ret == t._NIL {\n\t\tvar dft T\n\t\treturn dft, false\n\t}\n\treturn ret.Key(), true\n}", "func (this *AllOne) GetMinKey() string {\n\tif this.head.next != this.tail {\n\t\tfor k := range this.head.next.keys {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn \"\"\n}", "func (this *AllOne) GetMinKey() string {\n\tif this.Tail.Pre != this.Head {\n\t\tnmap := this.Tail.Pre.NodeMap\n\t\tret := \"\"\n\t\tfor k, _ := range nmap {\n\t\t\tret = k\n\t\t\tbreak\n\t\t}\n\t\treturn ret\n\t}\n\n\treturn \"\"\n}", "func (this *AllOne) GetMinKey() string {\n if len(this.m) == 0{\n return \"\"\n }\n return this.g[this.min][0].k\n}", "func (this *AllOne) GetMinKey() string {\n\tif this.tail == nil {\n\t\treturn \"\"\n\t}\n\tfor k := range this.tail.set {\n\t\treturn k\n\t}\n\treturn \"ERROR\"\n}", "func (vm *FstVM) PrefixSearch(input string) (int, []string) {\n\ttape, snap, _ := vm.run(input)\n\tif len(snap) == 0 {\n\t\treturn -1, nil\n\t}\n\tc := snap[len(snap)-1]\n\tpc := c.pc\n\tsz := int(vm.prog[pc] & valMask)\n\tpc++\n\tif sz == 0 {\n\t\treturn c.inp, []string{string(tape[0:c.tape])}\n\t}\n\ts := toInt(vm.prog[pc : pc+sz])\n\tpc += sz\n\tsz = int(vm.prog[pc])\n\tpc++\n\te := toInt(vm.prog[pc : pc+sz])\n\tvar outs []string\n\tfor i := s; i < e; i++ {\n\t\th := i\n\t\tfor vm.data[i] != 0 {\n\t\t\ti++\n\t\t}\n\t\tt := append(tape[0:c.tape], vm.data[h:i]...)\n\t\touts = append(outs, string(t))\n\t}\n\tpc += sz\n\treturn c.inp, outs\n}", "func (t *Trie) GetShortestPrefix(key string) interface{} {\n\treturn t.getShortestPrefix(key, false)\n}", "func (p *partitionImpl) FindFirstKey(key uint64) (int, error) {\n\tl := 0\n\tr := p.GetNumRows() - 1\n\tfor l <= r {\n\t\tm := (l + r) >> 1\n\t\tif key > p.keys[m] {\n\t\t\tl = m + 1\n\t\t} else if key < p.keys[m] {\n\t\t\tr = m - 1\n\t\t} else if l != m {\n\t\t\tr = m\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tif l < len(p.keys) && key == p.keys[l] {\n\t\treturn l, nil\n\t}\n\treturn l, errors.MissingKeyError{}\n}", "func (st *RedBlackBST) Min() Key {\n\tif st.IsEmpty() {\n\t\tpanic(\"call Min on empty RedBlackbst\")\n\t}\n\treturn st.min(st.root).key\n}", "func (n *Node) LongestPrefix(k []byte) ([]byte, interface{}, bool) {\n\tvar last *leafNode\n\tsearch := k\n\tfor {\n\t\t// Look for a leaf node\n\t\tif n.isLeaf() {\n\t\t\tlast = n.leaf\n\t\t}\n\n\t\t// Check for key exhaution\n\t\tif len(search) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// Look for an edge\n\t\t_, n = n.getEdge(search[0])\n\t\tif n == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Consume the search prefix\n\t\tif bytes.HasPrefix(search, n.prefix) {\n\t\t\tsearch = search[len(n.prefix):]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tif last != nil {\n\t\treturn last.key, last.val, true\n\t}\n\treturn nil, nil, false\n}", "func FindKthMin(nums []int, k int) (int, error) {\n\tindex := k - 1\n\treturn kthNumber(nums, index)\n}", "func (tree *avlBetterTree) MinKey() (key string, value interface{}, exist bool) {\n\ttree.Lock()\n\tdefer tree.Unlock()\n\tif tree.root == nil {\n\t\t// 如果是空树,返回空\n\t\treturn\n\t}\n\n\tnode := tree.root.minNode()\n\treturn node.k, node.v, true\n}", "func (t *BoundedTable) IndexPrefix() kv.Key {\n\treturn nil\n}", "func lowestMatch(op string) int {\n\tfor i, prec := range precs {\n\t\tfor _, op2 := range prec {\n\t\t\tif op == op2 {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t}\n\treturn -1\n}", "func (n *Node) Min() int {\n\tif n.Left == nil {\n\t\treturn n.Key\n\t}\n\treturn n.Left.Min()\n}", "func (s *Store) FindPrefix(bucket, prefix []byte, next func(key, val []byte) bool) error {\n\treturn s.db.View(func(tx *bolt.Tx) error {\n\t\tc := tx.Bucket(bucket).Cursor()\n\t\tfor k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {\n\t\t\tif !next(k, v) {\n\t\t\t\treturn io.EOF\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (t *Trie) GetShortestPrefixRK(key string) interface{} {\n\treturn t.getShortestPrefix(key, true)\n}", "func (n *Node) Minimum() ([]byte, interface{}, bool) {\n\tfor {\n\t\tif n.isLeaf() {\n\t\t\treturn n.leaf.key, n.leaf.val, true\n\t\t}\n\t\tif len(n.edges) > 0 {\n\t\t\tn = n.edges[0].node\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil, nil, false\n}", "func (bst *BinarySearch) Min() (int, error) {\n\tbst.lock.RLock()\n\tdefer bst.lock.RUnlock()\n\n\tn := bst.root\n\tif n == nil {\n\t\treturn 0, fmt.Errorf(\"min: no nodes exist in tree\")\n\t}\n\tfor {\n\t\tif n.left == nil {\n\t\t\treturn n.value, nil\n\t\t}\n\t\tn = n.left\n\t}\n}", "func (bst *StringBinarySearchTree) Min() *string {\n\tbst.lock.RLock()\n\tdefer bst.lock.RUnlock()\n\tn := bst.root\n\tif n == nil {\n\t\treturn nil\n\t}\n\tfor {\n\t\tif n.left == nil {\n\t\t\treturn &n.value\n\t\t}\n\t\tn = n.left\n\t}\n}", "func (n *Node) min() int {\n\tif n.left == nil {\n\t\treturn n.key\n\t}\n\treturn n.left.min()\n}", "func (t *ArtTree) PrefixSearch(key []byte) []interface{} {\n\tret := make([]interface{}, 0)\n\tfor r := range t.PrefixSearchChan(key) {\n\t\tret = append(ret, r.Value)\n\t}\n\treturn ret\n}", "func searchInSparseIndex(r io.Reader, searchKey []byte) (int, int, bool, error) {\n\tfrom := -1\n\tfor {\n\t\tkey, value, err := decode(r)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn 0, 0, false, fmt.Errorf(\"failed to read: %w\", err)\n\t\t}\n\t\tif err == io.EOF {\n\t\t\treturn from, 0, from != -1, nil\n\t\t}\n\t\toffset := decodeInt(value)\n\n\t\tcmp := bytes.Compare(key, searchKey)\n\t\tif cmp == 0 {\n\t\t\treturn offset, offset, true, nil\n\t\t} else if cmp < 0 {\n\t\t\tfrom = offset\n\t\t} else if cmp > 0 {\n\t\t\tif from == -1 {\n\t\t\t\t// if the first key in the sparse index is larger than\n\t\t\t\t// the search key, it means there is no key\n\t\t\t\treturn 0, 0, false, nil\n\t\t\t} else {\n\t\t\t\treturn from, offset, true, nil\n\t\t\t}\n\t\t}\n\t}\n}", "func (vt *perfSchemaTable) IndexPrefix() kv.Key {\n\treturn nil\n}", "func (s *GoSort) FindMinElementAndIndex() (interface{}, int) {\n var index = 0\n \n for i := 1; i < s.Len(); i++ {\n if s.LessThan(i, index) {\n index = i\n }\n }\n return s.values[index], index\n}", "func (sk *SkipList) PrefixScan(prefix store.Key, n int) []interface{} {\n\tx := sk.head\n\tfor i := sk.level - 1; i >= 0; i-- {\n\t\tfor x.next[i] != nil && x.next[i].key.Less(prefix) {\n\t\t\tx = x.next[i]\n\t\t}\n\t}\n\t//now x is the biggest element which is less than key\n\tx = x.next[0]\n\tvar res []interface{}\n\tfor n > 0 && x != nil && x.key.HasPrefix(prefix) {\n\t\tres = append(res, x.key)\n\t\tn--\n\t\tx = x.next[0]\n\t}\n\treturn res\n}", "func (t *Tree)FindMin()(int,bool){\n\tcurr := t.root\n\tif curr==nil{\n\t\treturn 0,false\n\t}\n\tfor curr.left !=nil{\n\t\tcurr = curr.left\n\t}\n\treturn curr.data,true\n}", "func (c *Client) WatchPrefix(prefix string, keys []string, waitIndex uint64, stopChan chan bool) (uint64, error) {\n\t<-stopChan\n\treturn 0, nil\n}", "func (c *Client) WatchPrefix(prefix string, keys []string, waitIndex uint64, stopChan chan bool) (uint64, error) {\n\t<-stopChan\n\treturn 0, nil\n}", "func (t *tableCommon) FirstKey() kv.Key {\n\ttrace_util_0.Count(_tables_00000, 64)\n\treturn t.RecordKey(math.MinInt64)\n}", "func (idx *Tree) MaxKey(searchPrefix []byte) (v uint64, ok bool) {\n\traw, _ := idx.partialSearch(searchPrefix)\n\tif raw == 0 {\n\t\treturn 0, false\n\t}\n\tif isLeaf(raw) {\n\t\treturn getLeafValue(raw), true\n\t}\n\t// now find the max\nsearchLoop:\n\tfor {\n\t\t_, node, count, prefixLen := explodeNode(raw)\n\t\tblock := int(node >> blockSlotsShift)\n\t\toffset := int(node & blockSlotsOffsetMask)\n\t\tdata := idx.blocks[block].data[offset:]\n\t\tvar prefixSlots int\n\t\tif prefixLen > 0 {\n\t\t\tif prefixLen == 255 {\n\t\t\t\tprefixLen = int(data[0])\n\t\t\t\tprefixSlots = (prefixLen + 15) >> 3\n\t\t\t} else {\n\t\t\t\tprefixSlots = (prefixLen + 7) >> 3\n\t\t\t}\n\t\t\tdata = data[prefixSlots:]\n\t\t}\n\t\tif count >= fullAllocFrom {\n\t\t\t// find max, iterate from top\n\t\t\tfor k := 255; k >= 0; k-- {\n\t\t\t\ta := atomic.LoadUint64(&data[k])\n\t\t\t\tif a != 0 {\n\t\t\t\t\tif isLeaf(a) {\n\t\t\t\t\t\treturn getLeafValue(a), true\n\t\t\t\t\t}\n\t\t\t\t\traw = a\n\t\t\t\t\tcontinue searchLoop\n\t\t\t\t}\n\t\t\t}\n\t\t\t// BUG: this might happen if all children in the node has been deleted, since we currently don't shrink node-256. we should go back in the tree!\n\t\t\treturn 0, false\n\t\t}\n\t\t// load the last child (since they are ordered)\n\t\ta := atomic.LoadUint64(&data[count-1])\n\t\tif isLeaf(a) {\n\t\t\treturn getLeafValue(a), true\n\t\t}\n\t\traw = a\n\t}\n}", "func (t *BinarySearchTree) FindMin() int {\n\tnode := t.root\n\tfor {\n\t\tif node.left != nil {\n\t\t\tnode = node.left\n\t\t} else {\n\t\t\treturn node.data\n\t\t}\n\t}\n}", "func (t *RbTree[K, V]) FindLowerBoundNode(key K) *Node[K, V] {\n\treturn t.findLowerBoundNode(t.root, key)\n}", "func (l *LevelDB) FirstIndex() (uint64, error) {\n\titer := l.db.NewIterator(&util.Range{Start: nil, Limit: nil}, nil)\n\tdefer iter.Release()\n\n\tfor iter.Next() {\n\t\tkey := binary.LittleEndian.Uint64(iter.Key())\n\t\treturn key, nil\n\t}\n\n\treturn 0, nil\n}", "func prefixIndex(addr uint8, prefixLen int) int {\n\t// the prefixIndex of addr/prefixLen is the prefixLen most significant bits\n\t// of addr, with a 1 tacked onto the left-hand side. For example:\n\t//\n\t// - 0/0 is 1: 0 bits of the addr, with a 1 tacked on\n\t// - 42/8 is 1_00101010 (298): all bits of 42, with a 1 tacked on\n\t// - 48/4 is 1_0011 (19): 4 most-significant bits of 48, with a 1 tacked on\n\treturn (int(addr) >> (8 - prefixLen)) + (1 << prefixLen)\n}", "func (tree *RedBlack[K, V]) Min() (v alg.Pair[K, V], ok bool) {\n\tif min := tree.root.min(); min != nil {\n\t\treturn alg.Two(min.key, min.value), true\n\t}\n\treturn\n}", "func (i *InmemStore) FirstIndex() (uint64, error) {\n\ti.l.RLock()\n\tdefer i.l.RUnlock()\n\treturn i.lowIndex, nil\n}", "func (m *Memory) FirstIndex() (uint64, error) {\n\tfirst := m.kvstore[KeyFirstIndex]\n\treturn first, nil\n}", "func longestPrefix(k1, k2 []byte) int {\n\tlimit := min(len(k1), len(k2))\n\tfor i := 0; i < limit; i++ {\n\t\tif k1[i] != k2[i] {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn limit\n}", "func ExampleClient_TdMin() {\n\thost := \"localhost:6379\"\n\tvar client = redisbloom.NewClient(host, \"nohelp\", nil)\n\n\tkey := \"example\"\n\t_, err := client.TdCreate(key, 10)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tsamples := map[float64]float64{1.0: 1.0, 2.0: 2.0, 3.0: 3.0}\n\t_, err = client.TdAdd(key, samples)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tmin, err := client.TdMin(key)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tfmt.Println(min)\n\t// Output: 1\n}", "func (c *Client) WatchPrefix(ctx context.Context, prefix string, opts ...easykv.WatchOption) (uint64, error) {\n\tvar options easykv.WatchOptions\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\trespChan := make(chan watchResponse)\n\tgo func() {\n\t\topts := api.QueryOptions{\n\t\t\tWaitIndex: options.WaitIndex,\n\t\t}\n\t\t_, meta, err := c.client.List(prefix, &opts)\n\t\tif err != nil {\n\t\t\trespChan <- watchResponse{options.WaitIndex, err}\n\t\t\treturn\n\t\t}\n\t\trespChan <- watchResponse{meta.LastIndex, err}\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn options.WaitIndex, easykv.ErrWatchCanceled\n\t\tcase r := <-respChan:\n\t\t\treturn r.waitIndex, r.err\n\t\t}\n\t}\n}", "func (t *Table) Smallest() y.Key { return t.smallest }", "func (t *BPTree) PrefixSearchScan(prefix []byte, reg string, offsetNum int, limitNum int) (records Records, off int, err error) {\n\tvar (\n\t\tn *Node\n\t\tscanFlag bool\n\t\tkeys [][]byte\n\t\tpointers []interface{}\n\t\ti, j, numFound int\n\t)\n\n\trgx, err := regexp.Compile(reg)\n\tif err != nil {\n\t\treturn nil, off, ErrBadRegexp\n\t}\n\n\tn = t.FindLeaf(prefix)\n\n\tif n == nil {\n\t\treturn nil, off, ErrPrefixSearchScansNoResult\n\t}\n\n\tfor j = 0; j < n.KeysNum && compare(n.Keys[j], prefix) < 0; {\n\t\tj++\n\t}\n\n\tscanFlag = true\n\tnumFound = 0\n\n\tcoff := 0\n\n\tfor n != nil && scanFlag {\n\t\tfor i = j; i < n.KeysNum; i++ {\n\n\t\t\tif !bytes.HasPrefix(n.Keys[i], prefix) {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif coff < offsetNum {\n\t\t\t\tcoff++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !rgx.Match(bytes.TrimPrefix(n.Keys[i], prefix)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, n.Keys[i])\n\t\t\tpointers = append(pointers, n.pointers[i])\n\t\t\tnumFound++\n\n\t\t\tif limitNum > 0 && numFound == limitNum {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tn, _ = n.pointers[order-1].(*Node)\n\t\tj = 0\n\t}\n\n\toff = coff\n\n\tesr, err := getRecordWrapper(numFound, keys, pointers)\n\treturn esr, off, err\n}", "func (c *KVClient) PathPrefixSearch(prefix string) (map[string]*domain.Package, error) {\n\tpkgs := map[string]*domain.Package{}\n\terr := c.be.Update(func(tx Transaction) error {\n\t\tvar (\n\t\t\tprefixBs = []byte(prefix)\n\t\t\tcursor = tx.Cursor(TablePackages)\n\t\t\terrs = []error{}\n\t\t)\n\t\tdefer cursor.Close()\n\t\tfor k, v := cursor.Seek(prefixBs).Data(); cursor.Err() == nil && k != nil && bytes.HasPrefix(k, prefixBs); k, v = cursor.Next().Data() {\n\t\t\tpkg := &domain.Package{}\n\t\t\tif err := proto.Unmarshal(v, pkg); err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpkgs[pkg.Path] = pkg\n\t\t}\n\t\tif err := errorlib.Merge(errs); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := cursor.Err(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn pkgs, err\n\t}\n\tif len(pkgs) == 0 {\n\t\treturn nil, ErrKeyNotFound\n\t}\n\treturn pkgs, nil\n}", "func SmallestWindow(s string, t string) string {\n\tstr := []byte(s)\n\ttst := []byte(t)\n\ttmap := make(map[byte]bool)\n\tfor _, val := range tst {\n\t\ttmap[val] = true\n\t}\n\ttype pair struct {\n\t\tval byte\n\t\tidx int\n\t}\n\tvar arr []pair\n\tfor idx, val := range str {\n\t\tif _, ok := tmap[val]; ok {\n\t\t\tarr = append(arr, pair{val, idx})\n\t\t}\n\t}\n\tfmt.Println(arr)\n\t//Now min window\n\tleft := 0\n\tright := 0\n\trequired := len(tmap)\n\tminwindow := math.MaxInt32\n\tvar startIdx, endIdx int\n\tkmap := make(map[byte]int)\n\n\tfor right < len(arr) {\n\t\tkmap[arr[right].val] += 1\n\t\tfmt.Println(\"Kmap Len: \", len(kmap))\n\t\tfor required == len(kmap) && left < right {\n\t\t\tfmt.Println(\"Kmap Len: \", len(kmap), \"Required: \", required)\n\t\t\tlength := arr[right].idx - arr[left].idx\n\n\t\t\tif minwindow > length {\n\t\t\t\tminwindow = length\n\t\t\t\tstartIdx = arr[left].idx\n\t\t\t\tendIdx = arr[right].idx\n\t\t\t}\n\t\t\tkmap[arr[left].val] -= 1\n\t\t\tif kmap[arr[left].val] == 0 {\n\t\t\t\tdelete(kmap, arr[left].val)\n\t\t\t}\n\t\t\tleft++\n\t\t}\n\t\tright++\n\t}\n\treturn string(str[startIdx : endIdx+1])\n}", "func prefixIsLessThan(b []byte, s string) bool {\n\tfor i := 0; i < len(s); i++ {\n\t\tif i >= len(b) {\n\t\t\treturn true\n\t\t}\n\t\tif b[i] != s[i] {\n\t\t\treturn b[i] < s[i]\n\t\t}\n\t}\n\treturn false\n}", "func (p *partitionImpl) FindFirstRowKey(keyBuf []byte, key uint64, keyfn sif.KeyingOperation) (int, error) {\n\t// find the first matching uint64 key\n\tfirstKey, err := p.FindFirstKey(key)\n\tif err != nil {\n\t\treturn firstKey, err\n\t}\n\t// iterate over each row with a matching key to find the first one with identical key bytes\n\tfor i := firstKey; i < p.GetNumRows(); i++ {\n\t\tif k, err := p.GetKey(i); err != nil || k != key {\n\t\t\treturn -1, err\n\t\t}\n\t\trowKey, err := keyfn(&rowImpl{\n\t\t\tmeta: p.GetRowMeta(i),\n\t\t\tdata: p.GetRowData(i),\n\t\t\tvarData: p.GetVarRowData(i),\n\t\t\tserializedVarData: p.GetSerializedVarRowData(i),\n\t\t\tschema: p.GetCurrentSchema(),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn -1, err\n\t\t} else if reflect.DeepEqual(keyBuf, rowKey) {\n\t\t\treturn i, nil\n\t\t}\n\t}\n\treturn firstKey, errors.MissingKeyError{}\n}", "func (na *NArray) MinIdx() (float32, []int) {\n\n\tvar offset int\n\tmin := float32(math.MaxFloat32)\n\tfor i := 0; i < len(na.Data); i++ {\n\t\tif na.Data[i] < min {\n\t\t\tmin = na.Data[i]\n\t\t\toffset = i\n\t\t}\n\t}\n\treturn min, na.ReverseIndex(offset)\n}", "func (na *NArray) Min() float32 {\n\tif na == nil || len(na.Data) == 0 {\n\t\tpanic(\"unable to take min of nil or zero-sizes array\")\n\t}\n\treturn minSliceElement(na.Data)\n}", "func (table *Table) SearchFirst(searchValues ...interface{}) (int, error) {\n\n\terr := table.checkSearchArguments(searchValues...)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\trowIndex, err := table.searchByKeysFirst(searchValues)\n\n\treturn rowIndex, err\n}", "func minIndex(slice []float64) int {\n\tif len(slice) == 0 {\n\t\treturn -1\n\t}\n\tmin := slice[0]\n\tminIndex := 0\n\tfor index := 0; index < len(slice); index++ {\n\t\tif slice[index] < min {\n\t\t\tmin = slice[index]\n\t\t\tminIndex = index\n\t\t}\n\t}\n\treturn minIndex\n}", "func (r Uint32Slice) Search(x uint32) int { return SearchUint32s(r, x) }", "func (o MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationPropertiesS3ConfigurationPropertiesPtrOutput) ObjectKeyPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationPropertiesS3ConfigurationProperties) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ObjectKeyPrefix\n\t}).(pulumi.StringPtrOutput)\n}", "func GetMinValue(ft *types.FieldType) (min types.Datum) {\n\tswitch ft.Tp {\n\tcase mysql.TypeTiny, mysql.TypeShort, mysql.TypeInt24, mysql.TypeLong, mysql.TypeLonglong:\n\t\tif mysql.HasUnsignedFlag(ft.Flag) {\n\t\t\tmin.SetUint64(0)\n\t\t} else {\n\t\t\tmin.SetInt64(types.IntergerSignedLowerBound(ft.Tp))\n\t\t}\n\tcase mysql.TypeFloat:\n\t\tmin.SetFloat32(float32(-types.GetMaxFloat(ft.Flen, ft.Decimal)))\n\tcase mysql.TypeDouble:\n\t\tmin.SetFloat64(-types.GetMaxFloat(ft.Flen, ft.Decimal))\n\tcase mysql.TypeString, mysql.TypeVarString, mysql.TypeVarchar, mysql.TypeBlob, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob:\n\t\tval := types.MinNotNullDatum()\n\t\tbytes, err := codec.EncodeKey(nil, nil, val)\n\t\t// should not happen\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Error(\"encode key fail\", zap.Error(err))\n\t\t}\n\t\tmin.SetBytes(bytes)\n\tcase mysql.TypeNewDecimal:\n\t\tmin.SetMysqlDecimal(types.NewMaxOrMinDec(true, ft.Flen, ft.Decimal))\n\tcase mysql.TypeDuration:\n\t\tmin.SetMysqlDuration(types.Duration{Duration: types.MinTime})\n\tcase mysql.TypeDate, mysql.TypeDatetime, mysql.TypeTimestamp:\n\t\tif ft.Tp == mysql.TypeDate || ft.Tp == mysql.TypeDatetime {\n\t\t\tmin.SetMysqlTime(types.Time{Time: types.MinDatetime, Type: ft.Tp})\n\t\t} else {\n\t\t\tmin.SetMysqlTime(types.MinTimestamp)\n\t\t}\n\t}\n\treturn\n}", "func GetPrefixIfLocked(ctx context.Context, prefix string, lock KVLocker) (string, *string, error) {\n\tk, bv, err := Client().GetPrefixIfLocked(ctx, prefix, lock)\n\tTrace(\"GetPrefixIfLocked\", err, logrus.Fields{fieldPrefix: prefix, fieldKey: k, fieldValue: string(bv)})\n\tif bv == nil {\n\t\treturn k, nil, err\n\t}\n\tv := string(bv)\n\treturn k, &v, err\n}", "func (t *BPTree) PrefixScan(prefix []byte, offsetNum int, limitNum int) (records Records, off int, err error) {\n\tvar (\n\t\tn *Node\n\t\tscanFlag bool\n\t\tkeys [][]byte\n\t\tpointers []interface{}\n\t\ti, j, numFound int\n\t)\n\n\tn = t.FindLeaf(prefix)\n\n\tif n == nil {\n\t\treturn nil, off, ErrPrefixScansNoResult\n\t}\n\n\tfor j = 0; j < n.KeysNum && compare(n.Keys[j], prefix) < 0; {\n\t\tj++\n\t}\n\n\tscanFlag = true\n\tnumFound = 0\n\n\tcoff := 0\n\n\tfor n != nil && scanFlag {\n\t\tfor i = j; i < n.KeysNum; i++ {\n\n\t\t\tif !bytes.HasPrefix(n.Keys[i], prefix) {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif coff < offsetNum {\n\t\t\t\tcoff++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, n.Keys[i])\n\t\t\tpointers = append(pointers, n.pointers[i])\n\t\t\tnumFound++\n\n\t\t\tif limitNum > 0 && numFound == limitNum {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tn, _ = n.pointers[order-1].(*Node)\n\t\tj = 0\n\t}\n\n\toff = coff\n\n\tesr, err := getRecordWrapper(numFound, keys, pointers)\n\treturn esr, off, err\n}", "func (f *FibonacciHeap) FindMin() (Value, error) {\n\tif !f.IsEmpty() {\n\t\treturn f.min.key, nil\n\t} else {\n\t\treturn nil, errors.New(\"unable to get minimum from an empty heap\")\n\t}\n}", "func (b *BinarySearch) kthSmallest(matrix [][]int, k int) int {\n\tm, n := len(matrix), len(matrix[0])\n\tl, h := matrix[0][0], matrix[m-1][n-1]\n\n\tvar mid int\n\tvar cnt int\n\tfor l <= h {\n\t\tmid = l + (h-l)/2\n\t\tcnt = 0\n\t\tfor i := 0; i < m; i++ {\n\t\t\tfor j := 0; j < n && matrix[i][j] <= mid; j++ {\n\t\t\t\tcnt++\n\t\t\t}\n\t\t}\n\t\tif cnt < k {\n\t\t\tl = mid + 1\n\t\t} else {\n\t\t\th = mid - 1\n\t\t}\n\t}\n\treturn l\n}", "func MinUint32(x, min uint32) uint32 { return x }", "func (o DatabaseOutput) KeyPrefix() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Database) pulumi.StringOutput { return v.KeyPrefix }).(pulumi.StringOutput)\n}", "func (t *Indexed) Min(i, j int) int {\n\treturn -1\n}", "func RoundMin(k float64) MinFunc {\n\treturn func(a, b float64) float64 {\n\t\tu := V2{k - a, k - b}.Max(V2{0, 0})\n\t\treturn Max(k, Min(a, b)) - u.Length()\n\t}\n}", "func (da *DoubleArray) PrefixLookup(key string) ([]string, []int) {\n\tkeys := make([]string, 0)\n\tvalues := make([]int, 0)\n\n\tnpos := 0\n\tdepth := 0\n\n\tfor ; depth < len(key); depth++ {\n\t\tif da.array[npos].base < 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tbase := da.array[npos].base\n\n\t\tif da.array[base].check == npos {\n\t\t\tkeys = append(keys, key[:depth])\n\t\t\tvalues = append(values, da.array[base].base)\n\t\t}\n\n\t\tcpos := base ^ int(key[depth])\n\t\tif da.array[cpos].check != npos {\n\t\t\treturn keys, values\n\t\t}\n\t\tnpos = cpos\n\t}\n\n\tbase := da.array[npos].base\n\n\tif base >= 0 {\n\t\tif da.array[base].check == npos {\n\t\t\tkeys = append(keys, key[:depth])\n\t\t\tvalues = append(values, da.array[base].base)\n\t\t}\n\t\treturn keys, values\n\t}\n\n\ttpos := -base\n\tfor ; depth < len(key); depth++ {\n\t\tif da.tail[tpos] != key[depth] {\n\t\t\treturn keys, values\n\t\t}\n\t\ttpos++\n\t}\n\n\tif da.tail[tpos] == terminator {\n\t\tkeys = append(keys, key[:depth])\n\t\tvalues = append(values, da.getValue(tpos+1))\n\t}\n\n\treturn keys, values\n}", "func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) {\n\tsearch := prefix\n\tfor {\n\t\t// Check for key exhaution\n\t\tif len(search) == 0 {\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t}\n\n\t\t// Look for an edge\n\t\t_, n = n.getEdge(search[0])\n\t\tif n == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Consume the search prefix\n\t\tif bytes.HasPrefix(search, n.prefix) {\n\t\t\tsearch = search[len(n.prefix):]\n\n\t\t} else if bytes.HasPrefix(n.prefix, search) {\n\t\t\t// Child may be under our search prefix\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func KeyLT(v string) predicate.Blob {\n\treturn predicate.Blob(\n\t\tfunc(s *sql.Selector) {\n\t\t\ts.Where(sql.LT(s.C(FieldKey), v))\n\t\t},\n\t)\n}", "func MinPos32(a, b float32) float32 {\n\tif a > 0.0 && b > 0.0 {\n\t\treturn Min32(a, b)\n\t} else if a > 0.0 {\n\t\treturn a\n\t} else if b > 0.0 {\n\t\treturn b\n\t}\n\treturn a\n}", "func (i *blockIter) SeekLT(key []byte, flags base.SeekLTFlags) (*InternalKey, base.LazyValue) {\n\tif invariants.Enabled && i.isDataInvalidated() {\n\t\tpanic(errors.AssertionFailedf(\"invalidated blockIter used\"))\n\t}\n\n\ti.clearCache()\n\t// Find the index of the smallest restart point whose key is >= the key\n\t// sought; index will be numRestarts if there is no such restart point.\n\ti.offset = 0\n\tvar index int32\n\n\t{\n\t\t// NB: manually inlined sort.Search is ~5% faster.\n\t\t//\n\t\t// Define f(-1) == false and f(n) == true.\n\t\t// Invariant: f(index-1) == false, f(upper) == true.\n\t\tupper := i.numRestarts\n\t\tfor index < upper {\n\t\t\th := int32(uint(index+upper) >> 1) // avoid overflow when computing h\n\t\t\t// index ≤ h < upper\n\t\t\toffset := decodeRestart(i.data[i.restarts+4*h:])\n\t\t\t// For a restart point, there are 0 bytes shared with the previous key.\n\t\t\t// The varint encoding of 0 occupies 1 byte.\n\t\t\tptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(offset+1))\n\n\t\t\t// Decode the key at that restart point, and compare it to the key\n\t\t\t// sought. See the comment in readEntry for why we manually inline the\n\t\t\t// varint decoding.\n\t\t\tvar v1 uint32\n\t\t\tif a := *((*uint8)(ptr)); a < 128 {\n\t\t\t\tv1 = uint32(a)\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 1)\n\t\t\t} else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {\n\t\t\t\tv1 = uint32(b)<<7 | uint32(a)\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 2)\n\t\t\t} else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {\n\t\t\t\tv1 = uint32(c)<<14 | uint32(b)<<7 | uint32(a)\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 3)\n\t\t\t} else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {\n\t\t\t\tv1 = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 4)\n\t\t\t} else {\n\t\t\t\td, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))\n\t\t\t\tv1 = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 5)\n\t\t\t}\n\n\t\t\tif *((*uint8)(ptr)) < 128 {\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 1)\n\t\t\t} else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))) < 128 {\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 2)\n\t\t\t} else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))) < 128 {\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 3)\n\t\t\t} else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))) < 128 {\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 4)\n\t\t\t} else {\n\t\t\t\tptr = unsafe.Pointer(uintptr(ptr) + 5)\n\t\t\t}\n\n\t\t\t// Manually inlining part of base.DecodeInternalKey provides a 5-10%\n\t\t\t// speedup on BlockIter benchmarks.\n\t\t\ts := getBytes(ptr, int(v1))\n\t\t\tvar k []byte\n\t\t\tif n := len(s) - 8; n >= 0 {\n\t\t\t\tk = s[:n:n]\n\t\t\t}\n\t\t\t// Else k is invalid, and left as nil\n\n\t\t\tif i.cmp(key, k) > 0 {\n\t\t\t\t// The search key is greater than the user key at this restart point.\n\t\t\t\t// Search beyond this restart point, since we are trying to find the\n\t\t\t\t// first restart point with a user key >= the search key.\n\t\t\t\tindex = h + 1 // preserves f(i-1) == false\n\t\t\t} else {\n\t\t\t\t// k >= search key, so prune everything after index (since index\n\t\t\t\t// satisfies the property we are looking for).\n\t\t\t\tupper = h // preserves f(j) == true\n\t\t\t}\n\t\t}\n\t\t// index == upper, f(index-1) == false, and f(upper) (= f(index)) == true\n\t\t// => answer is index.\n\t}\n\n\t// index is the first restart point with key >= search key. Define the keys\n\t// between a restart point and the next restart point as belonging to that\n\t// restart point. Note that index could be equal to i.numRestarts, i.e., we\n\t// are past the last restart.\n\t//\n\t// Since keys are strictly increasing, if index > 0 then the restart point\n\t// at index-1 will be the first one that has some keys belonging to it that\n\t// are less than the search key. If index == 0, then all keys in this block\n\t// are larger than the search key, so there is no match.\n\ttargetOffset := i.restarts\n\tif index > 0 {\n\t\ti.offset = decodeRestart(i.data[i.restarts+4*(index-1):])\n\t\tif index < i.numRestarts {\n\t\t\ttargetOffset = decodeRestart(i.data[i.restarts+4*(index):])\n\t\t}\n\t} else if index == 0 {\n\t\t// If index == 0 then all keys in this block are larger than the key\n\t\t// sought.\n\t\ti.offset = -1\n\t\ti.nextOffset = 0\n\t\treturn nil, base.LazyValue{}\n\t}\n\n\t// Iterate from that restart point to somewhere >= the key sought, then back\n\t// up to the previous entry. The expectation is that we'll be performing\n\t// reverse iteration, so we cache the entries as we advance forward.\n\ti.nextOffset = i.offset\n\n\tfor {\n\t\ti.offset = i.nextOffset\n\t\ti.readEntry()\n\t\t// When hidden keys are common, there is additional optimization possible\n\t\t// by not caching entries that are hidden (note that some calls to\n\t\t// cacheEntry don't decode the internal key before caching, but checking\n\t\t// whether a key is hidden does not require full decoding). However, we do\n\t\t// need to use the blockEntry.offset in the cache for the first entry at\n\t\t// the reset point to do the binary search when the cache is empty -- so\n\t\t// we would need to cache that first entry (though not the key) even if\n\t\t// was hidden. Our current assumption is that if there are large numbers\n\t\t// of hidden keys we will be able to skip whole blocks (using block\n\t\t// property filters) so we don't bother optimizing.\n\t\thiddenPoint := i.decodeInternalKey(i.key)\n\n\t\t// NB: we don't use the hiddenPoint return value of decodeInternalKey\n\t\t// since we want to stop as soon as we reach a key >= ikey.UserKey, so\n\t\t// that we can reverse.\n\t\tif i.cmp(i.ikey.UserKey, key) >= 0 {\n\t\t\t// The current key is greater than or equal to our search key. Back up to\n\t\t\t// the previous key which was less than our search key. Note that this for\n\t\t\t// loop will execute at least once with this if-block not being true, so\n\t\t\t// the key we are backing up to is the last one this loop cached.\n\t\t\treturn i.Prev()\n\t\t}\n\n\t\tif i.nextOffset >= targetOffset {\n\t\t\t// We've reached the end of the current restart block. Return the\n\t\t\t// current key if not hidden, else call Prev().\n\t\t\t//\n\t\t\t// When the restart interval is 1, the first iteration of the for loop\n\t\t\t// will bring us here. In that case ikey is backed by the block so we\n\t\t\t// get the desired key stability guarantee for the lifetime of the\n\t\t\t// blockIter. That is, we never cache anything and therefore never\n\t\t\t// return a key backed by cachedBuf.\n\t\t\tif hiddenPoint {\n\t\t\t\treturn i.Prev()\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\ti.cacheEntry()\n\t}\n\n\tif !i.valid() {\n\t\treturn nil, base.LazyValue{}\n\t}\n\tif !i.lazyValueHandling.hasValuePrefix ||\n\t\tbase.TrailerKind(i.ikey.Trailer) != InternalKeyKindSet {\n\t\ti.lazyValue = base.MakeInPlaceValue(i.val)\n\t} else if i.lazyValueHandling.vbr == nil || !isValueHandle(valuePrefix(i.val[0])) {\n\t\ti.lazyValue = base.MakeInPlaceValue(i.val[1:])\n\t} else {\n\t\ti.lazyValue = i.lazyValueHandling.vbr.getLazyValueForPrefixAndValueHandle(i.val)\n\t}\n\treturn &i.ikey, i.lazyValue\n}", "func (o MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationPropertiesS3ConfigurationPropertiesOutput) ObjectKeyPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationPropertiesS3ConfigurationProperties) *string {\n\t\treturn v.ObjectKeyPrefix\n\t}).(pulumi.StringPtrOutput)\n}", "func WithCursorHintPrefix(prefix string) CursorHint {\n\treturn func(o *CursorHints) {\n\t\to.KeyPrefix = &prefix\n\t}\n}", "func Min(Len int, Less func(i, j int) bool) int {\n\tmn := 0\n\tfor i := 1; i < Len; i++ {\n\t\tif Less(i, mn) {\n\t\t\tmn = i\n\t\t}\n\t}\n\treturn mn\n}", "func (t *tableCommon) IndexPrefix() kv.Key {\n\ttrace_util_0.Count(_tables_00000, 62)\n\treturn t.indexPrefix\n}", "func minNamespace(hash []byte, size namespace.IDSize) []byte {\n\tmin := make([]byte, 0, size)\n\treturn append(min, hash[:size]...)\n}", "func (klq *K8sLabelQuery) FirstIDX(ctx context.Context) uint {\n\tid, err := klq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func MinInt32(x, min int32) int32 { return x }", "func (i *blockIter) SeekPrefixGE(\n\tprefix, key []byte, flags base.SeekGEFlags,\n) (*base.InternalKey, base.LazyValue) {\n\t// This should never be called as prefix iteration is handled by sstable.Iterator.\n\tpanic(\"pebble: SeekPrefixGE unimplemented\")\n}", "func (n *nodeHeader) prefix() []byte {\n\tpLen, pBytes := n.prefixFields()\n\n\tif *pLen <= maxPrefixLen {\n\t\t// We have the whole prefix from the node\n\t\treturn pBytes[0:*pLen]\n\t}\n\n\t// Prefix is too long for node, we have to go find it from the leaf\n\tminLeaf := n.minChild().leafNode()\n\treturn minLeaf.key[0:*pLen]\n}", "func readableGetSmallest(r *ring.Ring) (float64, error) {\n // index 0 = smallest\n // index 1 = second smallest\n // index 2 = third smallest\n var index int = 0\n return flexibleGetSmallest(r, index)\n}", "func getStartIndex(st int32, a []int32) int {\n\tif st <= a[0] {\n\t\treturn 0 // st a[0]......a[len(a) - 1]\n\t}\n\tif st == a[len(a)-1] {\n\t\treturn len(a) - 1\n\t}\n\tif st > a[len(a)-1] {\n\t\treturn -1 // a[0]......a[len(a) - 1] st\n\t}\n\treturn sort.Search(len(a), func(i int) bool {\n\t\treturn a[i] >= st // a[0], a[1], st, a[2], a[3]....a[len(a) - 1]\n\t})\n}", "func searchToken(tokens []uint32, key uint32) int {\n\ti := sort.Search(len(tokens), func(x int) bool {\n\t\treturn tokens[x] > key\n\t})\n\tif i >= len(tokens) {\n\t\ti = 0\n\t}\n\treturn i\n}", "func Min(a, b uint32) uint32 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func (c *Signature) Min() int {\n\tif c.MinValue == nil {\n\t\treturn 0\n\t}\n\treturn toolbox.AsInt(c.MinValue)\n}", "func (t *tree) longestPrefix(k1, k2 string) int {\n\tmax := len(k1)\n\tif l := len(k2); l < max {\n\t\tmax = l\n\t}\n\tvar i int\n\tfor i = 0; i < max; i++ {\n\t\tif k1[i] != k2[i] {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn i\n}", "func (ksq *KqiSourceQuery) FirstIDX(ctx context.Context) int {\n\tid, err := ksq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (o ClusterNodeGroupOptionsPtrOutput) MinSize() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ClusterNodeGroupOptions) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MinSize\n\t}).(pulumi.IntPtrOutput)\n}", "func (km KeyValueMap) Prefix() string {\n\treturn km[kmPrefix]\n}", "func (i *BTreeIndex) Keys(from string, n int) []string {\r\n\ti.RLock()\r\n\tdefer i.RUnlock()\r\n\r\n\tif i.BTree == nil || i.LessFunction == nil {\r\n\t\tpanic(\"uninitialized index\")\r\n\t}\r\n\r\n\tif i.BTree.Len() <= 0 {\r\n\t\treturn []string{}\r\n\t}\r\n\r\n\tbtreeFrom := btreeString{s: from, l: i.LessFunction}\r\n\tskipFirst := true\r\n\tif len(from) <= 0 || !i.BTree.Has(btreeFrom) {\r\n\t\t// no such key, so fabricate an always-smallest item\r\n\t\tbtreeFrom = btreeString{s: \"\", l: func(string, string) bool { return true }}\r\n\t\tskipFirst = false\r\n\t}\r\n\r\n\tkeys := []string{}\r\n\titerator := func(i btree.Item) bool {\r\n\t\tkeys = append(keys, i.(btreeString).s)\r\n\t\treturn len(keys) < n\r\n\t}\r\n\ti.BTree.AscendGreaterOrEqual(btreeFrom, iterator)\r\n\r\n\tif skipFirst && len(keys) > 0 {\r\n\t\tkeys = keys[1:]\r\n\t}\r\n\r\n\treturn keys\r\n}", "func (o BucketLifecycleRuleItemConditionPtrOutput) MatchesPrefix() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *BucketLifecycleRuleItemCondition) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MatchesPrefix\n\t}).(pulumi.StringArrayOutput)\n}", "func kthSmallest(root *TreeNode, k int) int {\n\tif root == nil {\n\t\treturn -1\n\t}\n\n\tarr := make([]int, 0)\n\tinorder230(root, &arr, k)\n\treturn arr[k-1]\n}", "func BinarySearch(src []int, key int) bool {\n\tstart := 0\n\tend := len(src) - 1\n\tfor start <= end {\n\t\tmid := (start + end) / 2\n\t\ttmp := src[mid]\n\t\tif tmp == key {\n\t\t\treturn true\n\t\t} else if key < tmp {\n\t\t\tend = mid - 1\n\t\t} else {\n\t\t\tstart = mid + 1\n\t\t}\n\t}\n\treturn false\n}", "func getCommonPrefix(p []string, f []int, lmin int) string {\n r := []rune(p[f[0]])\n newR := make([]rune, lmin)\n for j := 0; j < lmin; j++ {\n newR[j] = r[j]\n }\n return string(newR)\n}", "func min_index(row []int) int {\n\tvar min int = math.MaxInt8\n\tvar ind int = -1\n\n\tfor i := 0; i < len(row); i++ {\n\t\tif row[i] < min {\n\t\t\tmin = row[i]\n\t\t\tind = i\n\t\t}\n\t}\n\n\treturn ind\n}", "func (t *BoundedTable) FirstKey() kv.Key {\n\treturn t.RecordKey(0)\n}", "func KeyHasPrefix(v string) predicate.Blob {\n\treturn predicate.Blob(\n\t\tfunc(s *sql.Selector) {\n\t\t\ts.Where(sql.HasPrefix(s.C(FieldKey), v))\n\t\t},\n\t)\n}", "func (root *TreeNode) minValueNode() *TreeNode {\n\tif root.left == nil {\n\t\t// If no left element is available, we are at the smallest key\n\t\t// so we return ourself\n\t\treturn root\n\t}\n\n\treturn root.left.minValueNode()\n}", "func (b *raftBadger) FirstIndex() (uint64, error) {\n\tfirst := uint64(0)\n\terr := b.gs.GetStore().(*badger.DB).View(func(txn *badger.Txn) error {\n\t\tit := txn.NewIterator(badger.DefaultIteratorOptions)\n\t\tdefer it.Close()\n\t\tit.Seek(dbLogPrefix)\n\t\tif it.ValidForPrefix(dbLogPrefix) {\n\t\t\titem := it.Item()\n\t\t\tk := string(item.Key()[len(dbLogPrefix):])\n\t\t\tidx, err := strconv.ParseUint(k, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfirst = idx\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn first, nil\n}", "func ExampleUInt32_setMin() {\n\tfmt.Print(chance.UInt32(chance.SetUInt32Min(10)))\n\t// Output: 1532597480\n}", "func (o *V0037JobProperties) GetMinimumNodesOk() (*bool, bool) {\n\tif o == nil || o.MinimumNodes == nil {\n\t\treturn nil, false\n\t}\n\treturn o.MinimumNodes, true\n}" ]
[ "0.6254368", "0.5750522", "0.57202524", "0.5673002", "0.5619895", "0.55524933", "0.5537136", "0.5501438", "0.5443638", "0.5435102", "0.540519", "0.536403", "0.53208256", "0.5270773", "0.51773477", "0.5168706", "0.5153912", "0.51201713", "0.51032627", "0.510243", "0.50744075", "0.50491226", "0.5026225", "0.49616006", "0.49611366", "0.4907176", "0.49006286", "0.48840016", "0.48546994", "0.48435682", "0.48306432", "0.48306432", "0.4823679", "0.48196402", "0.48028794", "0.47918767", "0.47632122", "0.47604445", "0.47491837", "0.47442335", "0.4735139", "0.47307506", "0.4726546", "0.47172824", "0.47132656", "0.47088352", "0.47039577", "0.46747816", "0.46317807", "0.46310413", "0.46273685", "0.46149272", "0.46140337", "0.46133894", "0.4611012", "0.4607212", "0.46057096", "0.45981407", "0.45914584", "0.45688185", "0.4557692", "0.45544726", "0.45523125", "0.4549096", "0.45374966", "0.45358345", "0.4518468", "0.45128992", "0.45086417", "0.4508342", "0.4508234", "0.44984207", "0.44957712", "0.44815263", "0.44774392", "0.44648033", "0.4462917", "0.44580716", "0.44541487", "0.44400644", "0.44393623", "0.44343975", "0.44310525", "0.4427767", "0.44251835", "0.44251296", "0.44199437", "0.44084477", "0.44069612", "0.4406752", "0.4406131", "0.44055223", "0.4391425", "0.4389563", "0.4389207", "0.43891466", "0.4388766", "0.43887168", "0.43864638", "0.43797892" ]
0.7585947
0
NewIterator returns an Iterator for iterating in order over all keys having the given prefix, or the complete index if searchPrefix is nil.
func (idx *Tree) NewIterator(searchPrefix []byte) *Iterator { return NewIterator(idx, searchPrefix) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (db *MemoryCache) NewIteratorWithPrefix(prefix []byte) Iterator {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\tvar (\n\t\tpr = string(prefix)\n\t\tkeys = make([]string, 0, len(db.db))\n\t\tvalues = make([][]byte, 0, len(db.db))\n\t)\n\t// Collect the keys from the memory database corresponding to the given prefix\n\tfor key := range db.db {\n\t\tif strings.HasPrefix(key, pr) {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t}\n\t// Sort the items and retrieve the associated values\n\tsort.Strings(keys)\n\tfor _, key := range keys {\n\t\tvalues = append(values, db.db[key])\n\t}\n\treturn &iterator{\n\t\tkeys: keys,\n\t\tvalues: values,\n\t}\n}", "func (k *KVAdapter) NewIterator(prefix, start []byte) ethdb.Iterator {\n\tit := &iterator{\n\t\tnext: make(chan struct{}),\n\t\titems: make(chan keyvalue, 1),\n\t\terrCh: make(chan error, 1),\n\t}\n\tinited := false\n\tgo func() {\n\t\t_, ok := <-it.next\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tit.errCh <- k.kv.IterateSorted(kv.Key(prefix), func(key kv.Key, value []byte) bool {\n\t\t\tif start != nil && !inited && key < kv.Key(prefix)+kv.Key(start) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tinited = true\n\t\t\tit.items <- keyvalue{key: []byte(key), value: value}\n\t\t\t_, ok := <-it.next\n\t\t\treturn ok\n\t\t})\n\t\tclose(it.items)\n\t}()\n\treturn it\n}", "func (db *Database) NewIteratorWithPrefix(prefix []byte) database.Iterator {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\tswitch {\n\tcase db.db == nil:\n\t\treturn &nodb.Iterator{Err: database.ErrClosed}\n\tcase db.corrupted():\n\t\treturn &nodb.Iterator{Err: database.ErrAvoidCorruption}\n\t}\n\n\tit := db.db.NewIterator(db.iteratorOptions)\n\tif it == nil {\n\t\treturn &nodb.Iterator{Err: errFailedToCreateIterator}\n\t}\n\tit.Seek(prefix)\n\treturn &iterator{\n\t\tit: it,\n\t\tdb: db,\n\t\tprefix: prefix,\n\t}\n}", "func (r *Reader) PrefixIterator(prefix []byte) store.KVIterator {\n\tprefixRange, err := r.store.getPrefixRange(prefix)\n\tif err != nil {\n\t\treturn &Iterator{\n\t\t\terr: err,\n\t\t}\n\t}\n\n\treturn newIterator(r.store, r.db, prefixRange)\n}", "func (db *Database) NewIteratorWithPrefix(prefix []byte) database.Iterator {\n\treturn &iter{\n\t\tdb: db,\n\t\tIterator: db.DB.NewIterator(util.BytesPrefix(prefix), nil),\n\t}\n}", "func (s *Storage) PrefixIterator(prefix []byte) (storage.Iterator, error) {\n\treturn s.iterator(prefix, storage.PrefixEnd(prefix))\n}", "func (db *Database) NewIteratorWithStartAndPrefix(start, prefix []byte) database.Iterator {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\tswitch {\n\tcase db.db == nil:\n\t\treturn &nodb.Iterator{Err: database.ErrClosed}\n\tcase db.corrupted():\n\t\treturn &nodb.Iterator{Err: database.ErrAvoidCorruption}\n\t}\n\n\tit := db.db.NewIterator(db.iteratorOptions)\n\tif it == nil {\n\t\treturn &nodb.Iterator{Err: errFailedToCreateIterator}\n\t}\n\tif bytes.Compare(start, prefix) == 1 {\n\t\tit.Seek(start)\n\t} else {\n\t\tit.Seek(prefix)\n\t}\n\treturn &iterator{\n\t\tit: it,\n\t\tdb: db,\n\t\tprefix: prefix,\n\t}\n}", "func (db *Database) NewIteratorWithStartAndPrefix(start, prefix []byte) database.Iterator {\n\titerRange := util.BytesPrefix(prefix)\n\tif bytes.Compare(start, prefix) == 1 {\n\t\titerRange.Start = start\n\t}\n\treturn &iter{\n\t\tdb: db,\n\t\tIterator: db.DB.NewIterator(iterRange, nil),\n\t}\n}", "func (db *memorydb) IterKeysWithPrefix(ctx context.Context, prefix []byte) <-chan []byte {\n\tkeys := db.KeysWithPrefix(prefix)\n\n\tout := make(chan []byte)\n\tgo func() {\n\t\tdefer close(out)\n\n\t\tfor _, k := range keys {\n\t\t\tselect {\n\t\t\tcase out <- k:\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn out\n}", "func (db *FlatDatabase) NewIterator(prefix []byte, start []byte) *FlatIterator {\n\tdb.lock.Lock()\n\tdefer db.lock.Unlock()\n\n\tif db.iterating {\n\t\treturn nil\n\t}\n\tdb.iterating = true\n\tdb.data.Seek(0, 0)\n\tdb.index.Seek(0, 0)\n\tdb.offset = 0\n\tdb.buff = db.buff[:0]\n\treturn &FlatIterator{db: db}\n}", "func (tx *remoteTx) ForPrefix(bucket string, prefix []byte, walker func(k, v []byte) error) error {\n\tc, err := tx.Cursor(bucket)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Close()\n\n\tfor k, v, err := c.Seek(prefix); k != nil; k, v, err = c.Next() {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !bytes.HasPrefix(k, prefix) {\n\t\t\tbreak\n\t\t}\n\t\tif err := walker(k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (db *DB) IteratePrefix(key interface{}, value interface{}, prefix interface{}, fn func() error) error {\n\treturn db.bolt.View(func(tx *bolt.Tx) error {\n\t\treturn db.IteratePrefixTx(tx, key, value, prefix, fn)\n\t})\n}", "func (db *MemoryCache) NewIteratorWithStart(start []byte) Iterator {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\tvar (\n\t\tst = string(start)\n\t\tkeys = make([]string, 0, len(db.db))\n\t\tvalues = make([][]byte, 0, len(db.db))\n\t)\n\t// Collect the keys from the memory database corresponding to the given start\n\tfor key := range db.db {\n\t\tif key >= st {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t}\n\t// Sort the items and retrieve the associated values\n\tsort.Strings(keys)\n\tfor _, key := range keys {\n\t\tvalues = append(values, db.db[key])\n\t}\n\treturn &iterator{\n\t\tkeys: keys,\n\t\tvalues: values,\n\t}\n}", "func (t *ArtTree) PrefixSearch(key []byte) []interface{} {\n\tret := make([]interface{}, 0)\n\tfor r := range t.PrefixSearchChan(key) {\n\t\tret = append(ret, r.Value)\n\t}\n\treturn ret\n}", "func (s *Store) FindPrefix(bucket, prefix []byte, next func(key, val []byte) bool) error {\n\treturn s.db.View(func(tx *bolt.Tx) error {\n\t\tc := tx.Bucket(bucket).Cursor()\n\t\tfor k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {\n\t\t\tif !next(k, v) {\n\t\t\t\treturn io.EOF\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (b *index) Iterate(prefix string, cb func(Info) error) error {\n\tstartPos, err := b.findEntryPosition(prefix)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not find starting position\")\n\t}\n\tstride := b.hdr.keySize + b.hdr.valueSize\n\tentry := make([]byte, stride)\n\tfor i := startPos; i < b.hdr.entryCount; i++ {\n\t\tn, err := b.readerAt.ReadAt(entry, int64(8+stride*i))\n\t\tif err != nil || n != len(entry) {\n\t\t\treturn errors.Wrap(err, \"unable to read from index\")\n\t\t}\n\n\t\tkey := entry[0:b.hdr.keySize]\n\t\tvalue := entry[b.hdr.keySize:]\n\n\t\ti, err := b.entryToInfo(bytesToContentID(key), value)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"invalid index data\")\n\t\t}\n\t\tif !strings.HasPrefix(i.BlockID, prefix) {\n\t\t\tbreak\n\t\t}\n\t\tif err := cb(i); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (t *BPTree) PrefixScan(prefix []byte, offsetNum int, limitNum int) (records Records, off int, err error) {\n\tvar (\n\t\tn *Node\n\t\tscanFlag bool\n\t\tkeys [][]byte\n\t\tpointers []interface{}\n\t\ti, j, numFound int\n\t)\n\n\tn = t.FindLeaf(prefix)\n\n\tif n == nil {\n\t\treturn nil, off, ErrPrefixScansNoResult\n\t}\n\n\tfor j = 0; j < n.KeysNum && compare(n.Keys[j], prefix) < 0; {\n\t\tj++\n\t}\n\n\tscanFlag = true\n\tnumFound = 0\n\n\tcoff := 0\n\n\tfor n != nil && scanFlag {\n\t\tfor i = j; i < n.KeysNum; i++ {\n\n\t\t\tif !bytes.HasPrefix(n.Keys[i], prefix) {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif coff < offsetNum {\n\t\t\t\tcoff++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, n.Keys[i])\n\t\t\tpointers = append(pointers, n.pointers[i])\n\t\t\tnumFound++\n\n\t\t\tif limitNum > 0 && numFound == limitNum {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tn, _ = n.pointers[order-1].(*Node)\n\t\tj = 0\n\t}\n\n\toff = coff\n\n\tesr, err := getRecordWrapper(numFound, keys, pointers)\n\treturn esr, off, err\n}", "func (s *Store) Iterate(q storage.Query, fn storage.IterateFn) error {\n\tif err := q.Validate(); err != nil {\n\t\treturn fmt.Errorf(\"failed iteration: %w\", err)\n\t}\n\n\tvar retErr error\n\n\tvar iter iterator.Iterator\n\tvar prefix string\n\n\tdefer func() {\n\t\tif iter != nil {\n\t\t\titer.Release()\n\t\t}\n\t}()\n\n\titerOpts := &opt.ReadOptions{\n\t\tDontFillCache: true,\n\t}\n\n\tif q.PrefixAtStart {\n\t\tprefix = q.Factory().Namespace()\n\t\titer = s.db.NewIterator(util.BytesPrefix([]byte(prefix)), iterOpts)\n\t\texists := iter.Seek([]byte(prefix + separator + q.Prefix))\n\t\tif !exists {\n\t\t\treturn nil\n\t\t}\n\t\t_ = iter.Prev()\n\t} else {\n\t\t// this is a small hack to make the iteration work with the\n\t\t// old implementation of statestore. this allows us to do a\n\t\t// full iteration without looking at the prefix.\n\t\tif q.Factory().Namespace() != \"\" {\n\t\t\tprefix = q.Factory().Namespace() + separator + q.Prefix\n\t\t}\n\t\titer = s.db.NewIterator(util.BytesPrefix([]byte(prefix)), iterOpts)\n\t}\n\n\tnextF := iter.Next\n\n\tif q.Order == storage.KeyDescendingOrder {\n\t\tnextF = func() bool {\n\t\t\tnextF = iter.Prev\n\t\t\treturn iter.Last()\n\t\t}\n\t}\n\n\tfirstSkipped := !q.SkipFirst\n\n\tfor nextF() {\n\t\tkeyRaw := iter.Key()\n\t\tnextKey := make([]byte, len(keyRaw))\n\t\tcopy(nextKey, keyRaw)\n\n\t\tvalRaw := iter.Value()\n\t\tnextVal := make([]byte, len(valRaw))\n\t\tcopy(nextVal, valRaw)\n\n\t\tkey := strings.TrimPrefix(string(nextKey), prefix)\n\n\t\tif filters(q.Filters).matchAny(key, nextVal) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif q.SkipFirst && !firstSkipped {\n\t\t\tfirstSkipped = true\n\t\t\tcontinue\n\t\t}\n\n\t\tvar (\n\t\t\tres *storage.Result\n\t\t\terr error\n\t\t)\n\n\t\tswitch q.ItemProperty {\n\t\tcase storage.QueryItemID, storage.QueryItemSize:\n\t\t\tres = &storage.Result{ID: key, Size: len(nextVal)}\n\t\tcase storage.QueryItem:\n\t\t\tnewItem := q.Factory()\n\t\t\terr = newItem.Unmarshal(nextVal)\n\t\t\tres = &storage.Result{ID: key, Entry: newItem}\n\t\t}\n\n\t\tif err != nil {\n\t\t\tretErr = errors.Join(retErr, fmt.Errorf(\"failed unmarshaling: %w\", err))\n\t\t\tbreak\n\t\t}\n\n\t\tif res == nil {\n\t\t\tretErr = errors.Join(retErr, fmt.Errorf(\"unknown object attribute type: %v\", q.ItemProperty))\n\t\t\tbreak\n\t\t}\n\n\t\tif stop, err := fn(*res); err != nil {\n\t\t\tretErr = errors.Join(retErr, fmt.Errorf(\"iterate callback function errored: %w\", err))\n\t\t\tbreak\n\t\t} else if stop {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif err := iter.Error(); err != nil {\n\t\tretErr = errors.Join(retErr, err)\n\t}\n\n\treturn retErr\n}", "func IterateKey(prefix string) []string {\n\tvar results []string\n\n\tdb.View(func(tx *bolt.Tx) error {\n\t\tc := tx.Bucket([]byte(DefaultBucket)).Cursor()\n\n\t\tpre := []byte(prefix)\n\t\tfor k, _ := c.Seek(pre); k != nil && bytes.HasPrefix(k, pre); k, _ = c.Next() {\n\t\t\tresults = append(results, string(k))\n\t\t}\n\t\treturn nil\n\t})\n\treturn results\n}", "func (t *Set) Iter(prefix []byte, handler func([]byte) bool) bool {\n\t// test empty tree\n\tif t.Empty() {\n\t\treturn true\n\t}\n\t// shortcut for empty prefix\n\tvar lpre = len(prefix)\n\n\tif lpre == 0 {\n\t\treturn t.iterate(t.root, handler)\n\t}\n\t// walk for best member\n\tp, top := t.root, t.root\n\tfor p.node != nil {\n\t\tbyteoff := int(p.node.bitoff >> 3)\n\t\tnewtop := byteoff < lpre\n\t\t// try next node\n\t\tp = p.node.child[p.node.dir(prefix)]\n\t\tif newtop {\n\t\t\ttop = p\n\t\t}\n\t}\n\tif len(p.Key) < lpre {\n\t\treturn true\n\t}\n\tfor i := 0; i < lpre; i++ {\n\t\tif p.Key[i] != prefix[i] {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn t.iterate(top, handler)\n}", "func (iter *ServicePrefixListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *RegisteredPrefixListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (trieInst *Trie) GetByPrefix(prefix string, limit int) ([]DataForKey, error) {\n\tif err := trieInst.checkKey(prefix); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif limit <= 0 {\n\t\tlimit = -1\n\t}\n\n\ttr := trieInst\n\tfor _, char := range prefix {\n\t\ttr.rw.RLock()\n\t\t_, _, subTrie := tr.getSubTrie(char)\n\t\ttr.rw.RUnlock()\n\n\t\tif subTrie == nil {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\ttr = subTrie\n\t}\n\n\tvar ret []DataForKey\n\ttr.rw.RLock()\n\tif tr.data != nil {\n\t\tret = append(ret, DataForKey{Key: prefix, Data: tr.data})\n\n\t\tif limit > 0 {\n\t\t\tlimit--\n\t\t}\n\t}\n\ttr.rw.RUnlock()\n\n\tvar toTraverse []*TraverseNode\n\ttoTraverse = append(toTraverse, &TraverseNode{key: prefix, trie: tr})\n\tfor limit != 0 && len(toTraverse) > 0 {\n\t\ttoTr := toTraverse[0]\n\n\t\titems := toTr.getChildren()\n\n\t\tfor _, item := range items {\n\t\t\titem.trie.rw.RLock()\n\t\t\tif item.trie.data != nil {\n\t\t\t\tret = append(ret, DataForKey{Key: item.key, Data: item.trie.data})\n\n\t\t\t\tif limit > 0 {\n\t\t\t\t\tlimit--\n\t\t\t\t}\n\t\t\t}\n\t\t\titem.trie.rw.RUnlock()\n\n\t\t\tif limit == 0 {\n\t\t\t\treturn ret, nil\n\t\t\t}\n\t\t}\n\n\t\ttoTraverse = append(toTraverse, items...)\n\n\t\tif len(toTraverse) > 0 {\n\t\t\ttoTraverse = toTraverse[1:]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn ret, nil\n}", "func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) {\n\tsearch := prefix\n\tfor {\n\t\t// Check for key exhaution\n\t\tif len(search) == 0 {\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t}\n\n\t\t// Look for an edge\n\t\t_, n = n.getEdge(search[0])\n\t\tif n == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Consume the search prefix\n\t\tif bytes.HasPrefix(search, n.prefix) {\n\t\t\tsearch = search[len(n.prefix):]\n\n\t\t} else if bytes.HasPrefix(n.prefix, search) {\n\t\t\t// Child may be under our search prefix\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func _enumerateKeysForPrefix(db *badger.DB, dbPrefix []byte) (_keysFound [][]byte, _valsFound [][]byte) {\n\tkeysFound := [][]byte{}\n\tvalsFound := [][]byte{}\n\n\tdbErr := db.View(func(txn *badger.Txn) error {\n\t\tvar err error\n\t\tkeysFound, valsFound, err = _enumerateKeysForPrefixWithTxn(txn, dbPrefix)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif dbErr != nil {\n\t\tglog.Errorf(\"_enumerateKeysForPrefix: Problem fetching keys and vlaues from db: %v\", dbErr)\n\t\treturn nil, nil\n\t}\n\n\treturn keysFound, valsFound\n}", "func (sk *SkipList) PrefixScan(prefix store.Key, n int) []interface{} {\n\tx := sk.head\n\tfor i := sk.level - 1; i >= 0; i-- {\n\t\tfor x.next[i] != nil && x.next[i].key.Less(prefix) {\n\t\t\tx = x.next[i]\n\t\t}\n\t}\n\t//now x is the biggest element which is less than key\n\tx = x.next[0]\n\tvar res []interface{}\n\tfor n > 0 && x != nil && x.key.HasPrefix(prefix) {\n\t\tres = append(res, x.key)\n\t\tn--\n\t\tx = x.next[0]\n\t}\n\treturn res\n}", "func NewServicePrefixListResultIterator(page ServicePrefixListResultPage) ServicePrefixListResultIterator {\n\treturn ServicePrefixListResultIterator{page: page}\n}", "func (it *Iterator) ValidForPrefix(prefix []byte) bool {\n\treturn it.item != nil && bytes.HasPrefix(it.item.key, prefix)\n}", "func (c *Client) WatchPrefix(prefix string, keys []string, waitIndex uint64, stopChan chan bool) (uint64, error) {\n\t<-stopChan\n\treturn 0, nil\n}", "func (c *Client) WatchPrefix(prefix string, keys []string, waitIndex uint64, stopChan chan bool) (uint64, error) {\n\t<-stopChan\n\treturn 0, nil\n}", "func (rad *Radix) Prefix(prefix string) *list.List {\n\trad.lock.Lock()\n\tdefer rad.lock.Unlock()\n\tl := list.New()\n\tn, _ := rad.root.lookup([]rune(prefix))\n\tif n == nil {\n\t\treturn l\n\t}\n\tn.addToList(l)\n\treturn l\n}", "func (db *DB) IteratePrefixTx(tx *bolt.Tx, key interface{}, value interface{}, prefix interface{}, fn func() error) error {\n\tbb := db.bucket(value)\n\tb := tx.Bucket(bb)\n\tif b == nil {\n\t\treturn nil\n\t}\n\tc := b.Cursor()\n\n\tbPrefix, err := db.encode(prefix)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := c.Seek(bPrefix); k != nil && bytes.HasPrefix(k, bPrefix); k, v = c.Next() {\n\t\tif err := db.decode(k, key); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := db.decode(v, value); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := fn(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (t *BPTree) PrefixSearchScan(prefix []byte, reg string, offsetNum int, limitNum int) (records Records, off int, err error) {\n\tvar (\n\t\tn *Node\n\t\tscanFlag bool\n\t\tkeys [][]byte\n\t\tpointers []interface{}\n\t\ti, j, numFound int\n\t)\n\n\trgx, err := regexp.Compile(reg)\n\tif err != nil {\n\t\treturn nil, off, ErrBadRegexp\n\t}\n\n\tn = t.FindLeaf(prefix)\n\n\tif n == nil {\n\t\treturn nil, off, ErrPrefixSearchScansNoResult\n\t}\n\n\tfor j = 0; j < n.KeysNum && compare(n.Keys[j], prefix) < 0; {\n\t\tj++\n\t}\n\n\tscanFlag = true\n\tnumFound = 0\n\n\tcoff := 0\n\n\tfor n != nil && scanFlag {\n\t\tfor i = j; i < n.KeysNum; i++ {\n\n\t\t\tif !bytes.HasPrefix(n.Keys[i], prefix) {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif coff < offsetNum {\n\t\t\t\tcoff++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !rgx.Match(bytes.TrimPrefix(n.Keys[i], prefix)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, n.Keys[i])\n\t\t\tpointers = append(pointers, n.pointers[i])\n\t\t\tnumFound++\n\n\t\t\tif limitNum > 0 && numFound == limitNum {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tn, _ = n.pointers[order-1].(*Node)\n\t\tj = 0\n\t}\n\n\toff = coff\n\n\tesr, err := getRecordWrapper(numFound, keys, pointers)\n\treturn esr, off, err\n}", "func (it *MockIndexTree) Iterator(start, end []byte) Iterator {\n\titer := &ForwardIter{start: start, end: end}\n\tif bytes.Compare(start, end) >= 0 {\n\t\titer.err = io.EOF\n\t\treturn iter\n\t}\n\titer.enumerator, _ = it.bt.Seek(start)\n\titer.Next() //fill key, value, err\n\treturn iter\n}", "func NewRegisteredPrefixListResultIterator(page RegisteredPrefixListResultPage) RegisteredPrefixListResultIterator {\n\treturn RegisteredPrefixListResultIterator{page: page}\n}", "func (db *Database) NewIteratorWithStart(start []byte) database.Iterator {\n\tdb.lock.RLock()\n\tdefer db.lock.RUnlock()\n\n\tswitch {\n\tcase db.db == nil:\n\t\treturn &nodb.Iterator{Err: database.ErrClosed}\n\tcase db.corrupted():\n\t\treturn &nodb.Iterator{Err: database.ErrAvoidCorruption}\n\t}\n\n\tit := db.db.NewIterator(db.iteratorOptions)\n\tif it == nil {\n\t\treturn &nodb.Iterator{Err: errFailedToCreateIterator}\n\t}\n\tit.Seek(start)\n\treturn &iterator{\n\t\tit: it,\n\t\tdb: db,\n\t}\n}", "func (s *DiffStore) GetByPrefix(prefix []byte) (items []KV) {\n\ts.tree.AscendGreaterOrEqual(&storeKV{key: prefix}, func(i btree.Item) bool {\n\t\tv := i.(*storeKV)\n\n\t\tif !bytes.HasPrefix(v.key, prefix) {\n\t\t\treturn false\n\t\t}\n\n\t\tif v.state == ItemDeleted {\n\t\t\treturn true\n\t\t}\n\n\t\titems = append(items, KV{v.key, v.value})\n\n\t\treturn true\n\t})\n\n\treturn\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\n}", "func (t *Trie) StartWith(prefix string) bool {\n\tcurr := t.Root\n\tfor _, char := range prefix {\n\t\tif _, ok := curr.Children[char]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tcurr = curr.Children[char]\n\t}\n\treturn true\n}", "func (c *Client) WatchPrefix(ctx context.Context, prefix string, opts ...easykv.WatchOption) (uint64, error) {\n\tvar options easykv.WatchOptions\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\trespChan := make(chan watchResponse)\n\tgo func() {\n\t\topts := api.QueryOptions{\n\t\t\tWaitIndex: options.WaitIndex,\n\t\t}\n\t\t_, meta, err := c.client.List(prefix, &opts)\n\t\tif err != nil {\n\t\t\trespChan <- watchResponse{options.WaitIndex, err}\n\t\t\treturn\n\t\t}\n\t\trespChan <- watchResponse{meta.LastIndex, err}\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn options.WaitIndex, easykv.ErrWatchCanceled\n\t\tcase r := <-respChan:\n\t\t\treturn r.waitIndex, r.err\n\t\t}\n\t}\n}", "func (db *Database) NewIteratorWithStart(start []byte) database.Iterator {\n\treturn &iter{\n\t\tdb: db,\n\t\tIterator: db.DB.NewIterator(&util.Range{Start: start}, nil),\n\t}\n}", "func (dbm *DBManager) GetByPrefix(bucket, prefix string) ([][]byte, error) {\n\tvar err error\n\tvar results [][]byte\n\tif err = dbm.openDB(); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer dbm.closeDB()\n\n\tresults = make([][]byte, 0)\n\n\tseekPrefix := func(tx *boltsecTx) error {\n\t\tprefixKey := []byte(prefix)\n\n\t\tbkt := tx.Bucket([]byte(bucket))\n\n\t\tif bkt == nil {\n\t\t\treturn bolt.ErrBucketNotFound\n\t\t}\n\n\t\tcursor := bkt.Cursor()\n\t\tfor k, v := cursor.Seek(prefixKey); bytes.HasPrefix(k, prefixKey); k, v = cursor.Next() {\n\n\t\t\tif dbm.cryptor != nil {\n\t\t\t\t//secret key is set, decrypt the content before return\n\t\t\t\tcontent := make([]byte, len(v))\n\t\t\t\tcopy(content, v)\n\n\t\t\t\tdec, err := dbm.cryptor.decrypt(content)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.New(\"Decrypt error from db\")\n\t\t\t\t}\n\t\t\t\tresults = append(results, dec)\n\t\t\t} else {\n\t\t\t\tresults = append(results, v)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err = dbm.db.view(seekPrefix); err != nil {\n\t\tLogger.Printf(\"GetByPrefix return %s\", err)\n\t}\n\n\treturn results, err\n}", "func (t *Trie) StartsWith(prefix string) bool {\n\tcur := t.Root\n\tfor _, c := range prefix {\n\t\t_, ok := cur.Next[c]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\tcur = cur.Next[c]\n\t}\n\n\treturn true\n}", "func GetAddressScopeCacheIteratorPrefix(addr sdk.AccAddress) []byte {\n\treturn append(AddressScopeCacheKeyPrefix, address.MustLengthPrefix(addr.Bytes())...)\n}", "func GetAddressContractSpecCacheIteratorPrefix(addr sdk.AccAddress) []byte {\n\treturn append(AddressContractSpecCacheKeyPrefix, address.MustLengthPrefix(addr.Bytes())...)\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tt := this\n\tfor i := range prefix {\n\t\tif t.trie == nil {\n\t\t\treturn false\n\t\t}\n\t\tif !t.trie[prefix[i]-'a'].exist {\n\t\t\treturn false\n\t\t}\n\t\tt = &t.trie[prefix[i]-'a'].trie\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\treturn this.SearchGen(prefix, func(t *Trie) bool {\n\t\treturn true\n\t})\n}", "func (b *Bucket) Iter(ctx context.Context, dir string, f func(string) error, opt ...objstore.IterOption) error {\n\tif dir != \"\" {\n\t\tdir = strings.TrimSuffix(dir, objstore.DirDelim) + objstore.DirDelim\n\t}\n\n\tdelimiter := objstore.DirDelim\n\n\tif objstore.ApplyIterOptions(opt...).Recursive {\n\t\tdelimiter = \"\"\n\t}\n\n\tvar marker string\n\tfor {\n\t\tif err := ctx.Err(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tobjects, err := b.client.ListObjects(b.name, &api.ListObjectsArgs{\n\t\t\tDelimiter: delimiter,\n\t\t\tMarker: marker,\n\t\t\tMaxKeys: 1000,\n\t\t\tPrefix: dir,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmarker = objects.NextMarker\n\t\tfor _, object := range objects.Contents {\n\t\t\tif err := f(object.Key); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tfor _, object := range objects.CommonPrefixes {\n\t\t\tif err := f(object.Prefix); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif !objects.IsTruncated {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (this *Trie) StartsWith(prefix string) bool {\n for _,v :=range prefix{\n if this.name[v-'a'] == nil{\n return false\n }\n \n this = this.name[v-'a']\n }\n return true\n}", "func (t *BoundedTable) IndexPrefix() kv.Key {\n\treturn nil\n}", "func scanWithPrefix(scanner *bufio.Scanner, prefix string) []string {\n\tvar result []string\n\tfor scanner.Scan() {\n\t\tresult = append(result, prefix+scanner.Text())\n\t}\n\treturn result\n}", "func (c *client) WatchPrefix(prefix string, ch chan struct{}) {\n\twatch := c.keysAPI.Watcher(prefix, &etcd.WatcherOptions{AfterIndex: 0, Recursive: true})\n\tch <- struct{}{} // make sure caller invokes GetEntries\n\tfor {\n\t\tif _, err := watch.Next(c.ctx); err != nil {\n\t\t\treturn\n\t\t}\n\t\tch <- struct{}{}\n\t}\n}", "func (i *blockIter) SeekPrefixGE(\n\tprefix, key []byte, flags base.SeekGEFlags,\n) (*base.InternalKey, base.LazyValue) {\n\t// This should never be called as prefix iteration is handled by sstable.Iterator.\n\tpanic(\"pebble: SeekPrefixGE unimplemented\")\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tbytes := []byte(prefix)\n\tif len(bytes) <= 0 {\n\t\treturn true\n\t}\n\tfor _, value := range bytes {\n\t\t//如果数据存在\n\t\tif _, ok := this.nexts[value]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tthis = this.nexts[value]\n\t}\n\treturn true\n}", "func (s *StateStorerAdapter) Iterate(prefix string, iterFunc storage.StateIterFunc) (err error) {\n\treturn s.storage.Iterate(\n\t\tstorage.Query{\n\t\t\tFactory: func() storage.Item { return &rawItem{newProxyItem(\"\", []byte(nil))} },\n\t\t\tPrefix: prefix,\n\t\t},\n\t\tfunc(res storage.Result) (stop bool, err error) {\n\t\t\tkey := []byte(prefix + res.ID)\n\t\t\tval, err := res.Entry.(*rawItem).Marshal()\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\treturn iterFunc(key, val)\n\t\t},\n\t)\n}", "func prefixLoad(db *gorocksdb.DB, prefix string) ([]string, []string, error) {\n\tif db == nil {\n\t\treturn nil, nil, errors.New(\"Rocksdb instance is nil when do prefixLoad\")\n\t}\n\treadOpts := gorocksdb.NewDefaultReadOptions()\n\tdefer readOpts.Destroy()\n\treadOpts.SetPrefixSameAsStart(true)\n\titer := db.NewIterator(readOpts)\n\tdefer iter.Close()\n\tkeys := make([]string, 0)\n\tvalues := make([]string, 0)\n\titer.Seek([]byte(prefix))\n\tfor ; iter.Valid(); iter.Next() {\n\t\tkey := iter.Key()\n\t\tvalue := iter.Value()\n\t\tkeys = append(keys, string(key.Data()))\n\t\tkey.Free()\n\t\tvalues = append(values, string(value.Data()))\n\t\tvalue.Free()\n\t}\n\treturn keys, values, nil\n}", "func WithCursorHintPrefix(prefix string) CursorHint {\n\treturn func(o *CursorHints) {\n\t\to.KeyPrefix = &prefix\n\t}\n}", "func BucketGetKeysWithPrefix(tx *bolt.Tx, bucket string, prefix string, stripPrefix bool) []string {\n\tb := tx.Bucket([]byte(bucket))\n\tif b == nil {\n\t\treturn nil\n\t}\n\tc := b.Cursor()\n\tvar results []string\n\tprefixBytes := []byte(prefix)\n\tfor k, _ := c.Seek(prefixBytes); k != nil && bytes.HasPrefix(k, prefixBytes); k, _ = c.Next() {\n\t\tif stripPrefix {\n\t\t\tk = k[len(prefix):]\n\t\t}\n\t\tresults = append(results, string(k))\n\t}\n\treturn results\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\troot := this\n\tfor _, chartV := range prefix {\n\t\tnext, ok := root.next[string(chartV)]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\troot = next\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tcurr := this\n\tfor _, c := range prefix {\n\t\tif curr.next[c-'a'] == nil {\n\t\t\treturn false\n\t\t}\n\t\tcurr = curr.next[c-'a']\n\t}\n\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tfor i := 0; i < len(prefix); i++ {\n\t\tif this.son[prefix[i]-'a'] == nil {\n\t\t\treturn false\n\t\t}\n\t\tthis = this.son[prefix[i]-'a']\n\t}\n\treturn true\n}", "func (db *RocksDB) Iterator(start, end []byte) (Iterator, error) {\n\titr := db.db.NewIterator(db.ro)\n\treturn newRocksDBIterator(itr, start, end, false), nil\n}", "func (this *Trie) StartsWith(prefix string) bool {\n node := this.searchPrefix(prefix)\n \n return node != nil\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tif prefix == \"\" {\n\t\treturn false\n\t}\n\thead := this\n\tfor e := range prefix {\n\t\tif head.data[prefix[e]-'a'] == nil {\n\t\t\treturn false\n\t\t}\n\t\thead = head.data[prefix[e]-'a']\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n node := this.root\n for _, r := range prefix {\n child, existed := node.children[r]\n if !existed {\n return false\n }\n node = child\n }\n return true\n}", "func (m *memory) IteratorWithRange(start, limit []byte) (Iterator, error) {\n\tm.RLock()\n\tdefer m.RUnlock()\n\tkeys := []string{} // using slice as keys has an unknown size\n\tif len(limit) == 0 {\n\t\tlimit = util.BytesPrefix(start).Limit\n\t}\n\tstorage := make(map[string][]byte)\n\tfor _, k := range m.keys {\n\t\tif bytes.Compare([]byte(k), start) > -1 && bytes.Compare([]byte(k), limit) < 1 {\n\t\t\tkeys = append(keys, k)\n\t\t\tstorage[k] = m.storage[k]\n\t\t}\n\t}\n\n\treturn &memiter{-1, keys, storage}, nil\n}", "func ExampleBucket_MapPrefix() {\n\tbx, _ := buckets.Open(tempfile())\n\tdefer os.Remove(bx.Path())\n\tdefer bx.Close()\n\n\t// Create a new things bucket.\n\tthings, _ := bx.New([]byte(\"things\"))\n\n\t// Setup items to insert.\n\titems := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"A\"), []byte(\"1\")}, // `A` prefix match\n\t\t{[]byte(\"AA\"), []byte(\"2\")}, // match\n\t\t{[]byte(\"AAA\"), []byte(\"3\")}, // match\n\t\t{[]byte(\"AAB\"), []byte(\"2\")}, // match\n\t\t{[]byte(\"B\"), []byte(\"O\")},\n\t\t{[]byte(\"BA\"), []byte(\"0\")},\n\t\t{[]byte(\"BAA\"), []byte(\"0\")},\n\t}\n\n\t// Insert 'em.\n\tif err := things.Insert(items); err != nil {\n\t\tfmt.Printf(\"could not insert items in `things` bucket: %v\\n\", err)\n\t}\n\n\t// Now collect each item whose key starts with \"A\".\n\tprefix := []byte(\"A\")\n\n\t// Setup slice of items.\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 := things.MapPrefix(do, prefix); err != nil {\n\t\tfmt.Printf(\"could not map items with prefix %s: %v\\n\", prefix, 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// A -> 1\n\t// AA -> 2\n\t// AAA -> 3\n\t// AAB -> 2\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tcur := this\n\tfor i := 0; i < len(prefix); i++ {\n\t\tb := prefix[i]\n\t\tif cur.next[b-97] == nil {\n\t\t\treturn false\n\t\t}\n\t\tcur = cur.next[b-97]\n\t}\n\treturn cur != nil\n}", "func (c *KVClient) PathPrefixSearch(prefix string) (map[string]*domain.Package, error) {\n\tpkgs := map[string]*domain.Package{}\n\terr := c.be.Update(func(tx Transaction) error {\n\t\tvar (\n\t\t\tprefixBs = []byte(prefix)\n\t\t\tcursor = tx.Cursor(TablePackages)\n\t\t\terrs = []error{}\n\t\t)\n\t\tdefer cursor.Close()\n\t\tfor k, v := cursor.Seek(prefixBs).Data(); cursor.Err() == nil && k != nil && bytes.HasPrefix(k, prefixBs); k, v = cursor.Next().Data() {\n\t\t\tpkg := &domain.Package{}\n\t\t\tif err := proto.Unmarshal(v, pkg); err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpkgs[pkg.Path] = pkg\n\t\t}\n\t\tif err := errorlib.Merge(errs); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := cursor.Err(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn pkgs, err\n\t}\n\tif len(pkgs) == 0 {\n\t\treturn nil, ErrKeyNotFound\n\t}\n\treturn pkgs, nil\n}", "func ScanKeys(keyPrefix string, keySuffix string) ([]string, error) {\n\tvar foundKeys []string\n\tvar cursor uint64\n\tvar err error\n\tfor {\n\t\tvar keys []string\n\t\tkeys, cursor, err = Redis.Scan(cursor, keyPrefix+\"*\"+keySuffix, 10).Result()\n\t\tfoundKeys = append(foundKeys, keys...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error while scanning the Redis: %v\", err)\n\t\t}\n\t\tif cursor == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn foundKeys, nil\n}", "func (hm HashMap) StartIter() (iter hashMapIter) {\n\titer = hashMapIter{&hm, 0, hm.data[0].Front()}\n\titer.findNext()\n\treturn\n}", "func ListPrefix(ctx context.Context, prefix string) (KeyValuePairs, error) {\n\tv, err := Client().ListPrefix(ctx, prefix)\n\tTrace(\"ListPrefix\", err, logrus.Fields{fieldPrefix: prefix, fieldNumEntries: len(v)})\n\treturn v, err\n}", "func (d *Dtrie) Iterator(stop <-chan struct{}) <-chan Entry {\n\treturn iterate(d.root, stop)\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\ttemp := this\n\tfor _, v := range prefix {\n\t\tnxt := v - 'a'\n\t\tif temp.next[nxt] == nil {\n\t\t\treturn false\n\t\t} else {\n\t\t\ttemp = temp.next[nxt]\n\t\t}\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\treturn this.dict[prefix] || this.dictPrefix[prefix]\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tcur := this.Root\n\tfor _, c := range prefix {\n\t\tif _, ok := cur.Child[c]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tcur = cur.Child[c]\n\t}\n\treturn true\n}", "func (c *FileSystemCache) Prefix(p ...string) Cache {\n\tc.prefix = p\n\treturn c\n}", "func (t *Trie) FindWithPrefix(prefix string) []string {\n\twords := make([]string, 0)\n\tn := t.find(prefix)\n\tif n == nil {\n\t\treturn words\n\t}\n\tsuffix := t.getSuffix(n)\n\tfor _, s := range suffix {\n\t\twords = append(words, prefix+s)\n\t}\n\treturn words\n}", "func WithCursorPrefix(prefix []byte) CursorOption {\n\treturn func(c *CursorConfig) {\n\t\tc.Prefix = prefix\n\t}\n}", "func (kv *KV) Iterator(f func([]byte, []byte) bool) error {\n\treturn kv.db.View(func(tx *buntdb.Tx) error {\n\t\terr := tx.Ascend(\"\", func(key, value string) bool {\n\t\t\treturn f(gkv.Stob(key), gkv.Stob(value))\n\t\t})\n\t\treturn err\n\t})\n}", "func (b *Bucket) Iter(ctx context.Context, dir string, f func(string) error, options ...objstore.IterOption) error {\n\t// Ensure the object name actually ends with a dir suffix. Otherwise we'll just iterate the\n\t// object itself as one prefix item.\n\tif dir != \"\" {\n\t\tdir = strings.TrimSuffix(dir, DirDelim) + DirDelim\n\t}\n\n\t// If recursive iteration is enabled we should pass an empty delimiter.\n\tdelimiter := DirDelim\n\tif objstore.ApplyIterOptions(options...).Recursive {\n\t\tdelimiter = \"\"\n\t}\n\n\tit := b.bkt.Objects(ctx, &storage.Query{\n\t\tPrefix: dir,\n\t\tDelimiter: delimiter,\n\t})\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\t\tattrs, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := f(attrs.Prefix + attrs.Name); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (kvStore *MemoryKVStore) Iterate(schema string, keyPrefix string) (entries chan [2]string) {\n\tresponseChan := make(chan [2]string, 100)\n\tkvStore.mutex.Lock()\n\ts := kvStore.getSchema(schema)\n\tkvStore.mutex.Unlock()\n\tgo func() {\n\t\tkvStore.mutex.Lock()\n\t\tfor key, value := range s {\n\t\t\tif strings.HasPrefix(key, keyPrefix) {\n\t\t\t\tresponseChan <- [2]string{key, string(value)}\n\t\t\t}\n\t\t}\n\t\tkvStore.mutex.Unlock()\n\t\tclose(responseChan)\n\t}()\n\treturn responseChan\n}", "func (kvStore *MemoryKVStore) IterateKeys(schema string, keyPrefix string) chan string {\n\tresponseChan := make(chan string, 100)\n\tkvStore.mutex.Lock()\n\ts := kvStore.getSchema(schema)\n\tkvStore.mutex.Unlock()\n\tgo func() {\n\t\tkvStore.mutex.Lock()\n\t\tfor key, _ := range s {\n\t\t\tif strings.HasPrefix(key, keyPrefix) {\n\t\t\t\tresponseChan <- key\n\t\t\t}\n\t\t}\n\t\tkvStore.mutex.Unlock()\n\n\t\tclose(responseChan)\n\t}()\n\treturn responseChan\n}", "func (wk *wkAPI) GetPrefixResults(pfx string, limit int) ([]WikipediaPage, error) {\n\tif limit == 0 {\n\t\tlimit = 50\n\t}\n\n\tf := url.Values{\n\t\t\"action\": {\"query\"},\n\t\t\"generator\": {\"prefixsearch\"},\n\t\t\"prop\": {\"pageprops|pageimages|description\"},\n\t\t\"ppprop\": {\"displaytitle\"},\n\t\t\"gpssearch\": {pfx},\n\t\t\"gpsnamespace\": {\"0\"},\n\t\t\"gpslimit\": {strconv.Itoa(limit)},\n\t}\n\n\tres, err := wk.w.Query(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar values []WikipediaPage\n\tfor _, p := range res.Query.Pages {\n\t\tvalues = append(values, WikipediaPage{\n\t\t\tID: p.PageId,\n\t\t\tTitle: p.Title,\n\t\t\tURL: getWikipediaURL(p.Title),\n\t\t})\n\t}\n\n\treturn values, nil\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tif len(prefix) == 0 {\n\t\treturn true\n\t}\n\tfor _, e := range this.edges {\n\t\tif e.char == prefix[0] {\n\t\t\treturn e.next.StartsWith(prefix[1:])\n\t\t}\n\t}\n\treturn false\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tnode := this\n\tfor _, v := range prefix {\n\t\tif node = node.next[v-'a']; node == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\n\tnode := this.searchPrefix(prefix)\n\tif node == nil {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (tx *dbTxn) Iterator(start, end []byte) (db.Iterator, error) {\n\tif tx.btree == nil {\n\t\treturn nil, db.ErrTransactionClosed\n\t}\n\tif (start != nil && len(start) == 0) || (end != nil && len(end) == 0) {\n\t\treturn nil, db.ErrKeyEmpty\n\t}\n\treturn newMemDBIterator(tx, start, end, false), nil\n}", "func GetValueOwnerScopeCacheIteratorPrefix(addr sdk.AccAddress) []byte {\n\treturn append(ValueOwnerScopeCacheKeyPrefix, address.MustLengthPrefix(addr.Bytes())...)\n}", "func (l *ChainLedger) QueryByPrefix(addr types.Address, prefix string) (bool, [][]byte) {\n\taccount := l.GetOrCreateAccount(addr)\n\treturn account.Query(prefix)\n}", "func (h *DBHandle) GetIterator(startKey []byte, endKey []byte) *Iterator {\n\tsKey := constructLevelKey(h.dbName, startKey)\n\teKey := constructLevelKey(h.dbName, endKey)\n\tif endKey == nil {\n\t\t// replace the last byte 'dbNameKeySep' by 'lastKeyIndicator'\n\t\teKey[len(eKey)-1] = lastKeyIndicator\n\t}\n\tlogger.Debugf(\"Getting iterator for range [%#v] - [%#v]\", sKey, eKey)\n\treturn &Iterator{h.db.GetIterator(sKey, eKey)}\n}", "func (this *Trie) StartsWith(prefix string) bool {\n if len(prefix) == 0 {return true}\n if this == nil || this.path == nil || this.path[prefix[0] - 'a'] == nil {return false}\n if len(prefix) == 1 {return this.path[prefix[0] - 'a'] != nil}\n this = this.path[prefix[0] - 'a']\n return this.StartsWith(prefix[1:])\n}", "func (f *Footer) StartIterator(startKeyIncl, endKeyExcl []byte,\n\titeratorOptions IteratorOptions) (Iterator, error) {\n\t_, ss := f.segmentLocs()\n\tif ss == nil {\n\t\tf.DecRef()\n\t\treturn nil, nil\n\t}\n\n\titer, err := ss.StartIterator(startKeyIncl, endKeyExcl, iteratorOptions)\n\tif err != nil || iter == nil {\n\t\tf.DecRef()\n\t\treturn nil, err\n\t}\n\n\tinitCloser, ok := iter.(InitCloser)\n\tif !ok || initCloser == nil {\n\t\titer.Close()\n\t\tf.DecRef()\n\t\treturn nil, ErrUnexpected\n\t}\n\n\terr = initCloser.InitCloser(f)\n\tif err != nil {\n\t\titer.Close()\n\t\tf.DecRef()\n\t\treturn nil, err\n\t}\n\n\treturn iter, nil\n}", "func (vt *perfSchemaTable) IndexPrefix() kv.Key {\n\treturn nil\n}", "func (this *Trie) StartsWith(prefix string) bool {\r\n\tstrbyte := []byte(prefix)\r\n\tcurroot := this\r\n\tfor _, char := range strbyte {\r\n\t\tcurroot = curroot.childs[char-'a']\r\n\t\tif curroot == nil {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}", "func (s *StatsdClient) GetByPrefix(prefix string) map[string]int64 {\n\tresult := make(map[string]int64)\n\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\n\tfor key, value := range s.counts {\n\t\tif strings.HasPrefix(key, prefix) {\n\t\t\tk := strings.Replace(key, prefix, \"\", -1)\n\t\t\tresult[k] = value\n\t\t}\n\t}\n\n\treturn result\n}", "func (t *Trie) getNodeAtPrefix(prefix string) (*Node, error) {\n\trunner := t.Root\n\n\tfor _, currChar := range prefix {\n\t\tif _, ok := runner.Children[currChar]; !ok {\n\t\t\treturn nil, errors.New(\"prefix not found\")\n\t\t}\n\t\trunner = runner.Children[currChar]\n\t}\n\n\treturn runner, nil\n}", "func (o *ObjectStorage) ListObjectsWithPrefixInBucket(bucket *string, prefix *string) (*s3.ListObjectsOutput, error) {\n\tlistObjectInput := &s3.ListObjectsInput{\n\t\tBucket: bucket,\n\t\tPrefix: prefix,\n\t}\n\n\treturn o.Client.ListObjects(listObjectInput)\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tcur := this.root\n\n\t// go through prefix\n\tfor _, c := range prefix {\n\t\t// check if in children\n\t\tif child, ok := cur.children[c]; ok {\n\t\t\t// set cur\n\t\t\tcur = child\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// no probs\n\treturn true\n}", "func (b *Bucket) GetFileEncryptionKeysForPrefix(pre string) (map[string][]byte, error) {\n\tif b.Version == 0 {\n\t\treturn map[string][]byte{\"\": b.GetLinkEncryptionKey()}, nil\n\t}\n\n\tkeys := make(map[string][]byte)\n\tfor p := range b.Metadata {\n\t\tif strings.HasPrefix(p, pre) {\n\t\t\tmd, _, ok := b.GetMetadataForPath(p, true)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"could not resolve path: %s\", p)\n\t\t\t}\n\t\t\tkeys[p] = keyBytes(md.Key)\n\t\t}\n\t}\n\treturn keys, nil\n}" ]
[ "0.7525866", "0.7403449", "0.7257108", "0.7165401", "0.711629", "0.6804367", "0.6732594", "0.6561419", "0.6538172", "0.63779676", "0.62592065", "0.6080891", "0.6077097", "0.60245144", "0.59363127", "0.58752656", "0.58317125", "0.58209616", "0.579653", "0.5795732", "0.5774168", "0.57376975", "0.5719928", "0.5700986", "0.5695124", "0.5689754", "0.566831", "0.55631346", "0.5558333", "0.5558333", "0.5545897", "0.55164975", "0.5508935", "0.55031294", "0.5496316", "0.5472947", "0.54345274", "0.54302096", "0.54233104", "0.54132926", "0.5412188", "0.54093593", "0.5392313", "0.5391666", "0.53894925", "0.53847694", "0.5380783", "0.5363032", "0.53388035", "0.5324042", "0.53194356", "0.5319201", "0.5308458", "0.5302111", "0.52795315", "0.527526", "0.52643937", "0.5257998", "0.5250543", "0.5247742", "0.5232389", "0.5231758", "0.5214155", "0.52121174", "0.52054036", "0.5201065", "0.5200754", "0.519769", "0.5195767", "0.51947474", "0.5189394", "0.5186724", "0.51848733", "0.51816124", "0.51744884", "0.5168591", "0.51237816", "0.51224375", "0.5115043", "0.5112395", "0.51032096", "0.509898", "0.5098279", "0.5093978", "0.50810546", "0.5078171", "0.50778943", "0.507309", "0.50607604", "0.5057525", "0.5056868", "0.50555587", "0.5035286", "0.5029303", "0.5021769", "0.5020902", "0.5020685", "0.5013125", "0.5013113", "0.50127935" ]
0.6987235
5
Count returns the number of nodes and leaves in the part of tree having the given prefix, or the whole tree if searchPrefix is nil.
func (idx *Tree) Count(searchPrefix []byte) (nodes, leaves int) { return NewCounter(idx).Count(searchPrefix) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (db *DB) CountPrefix(prefix interface{}, value interface{}, count *int) error {\n\treturn db.bolt.View(func(tx *bolt.Tx) error {\n\t\treturn db.CountPrefixTx(tx, prefix, value, count)\n\t})\n}", "func (db *DB) CountPrefixTx(tx *bolt.Tx, prefix interface{}, value interface{}, count *int) error {\n\t*count = 0\n\tbb := db.bucket(value)\n\tb := tx.Bucket(bb)\n\tif b == nil {\n\t\treturn nil\n\t}\n\n\tpb, err := db.encode(prefix)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc := b.Cursor()\n\tfor k, _ := c.Seek(pb); k != nil && bytes.HasPrefix(k, pb); k, _ = c.Next() {\n\t\t*count++\n\t}\n\treturn nil\n}", "func (n *Node) HasPrefix(prefix string) (*Node, error) {\n\tletters := []rune(prefix)\n\tcurrent := n\n\tfor i := 0; current != nil && i < len(letters); i++ {\n\t\tcurrent = current.GetChild(letters[i])\n\t}\n\tif current == nil {\n\t\terr := fmt.Errorf(\"%s not found\", prefix)\n\t\treturn nil, err\n\t}\n\treturn current, nil\n}", "func (t *Trie) FindWithPrefix(p string) (counts map[string]int) {\n\tcounts = make(map[string]int)\n\tcharIdx := p[0] - 'a'\n\tt.children[charIdx].findWithPrefix(p, &counts)\n\treturn\n}", "func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) {\n\tsearch := prefix\n\tfor {\n\t\t// Check for key exhaution\n\t\tif len(search) == 0 {\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t}\n\n\t\t// Look for an edge\n\t\t_, n = n.getEdge(search[0])\n\t\tif n == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Consume the search prefix\n\t\tif bytes.HasPrefix(search, n.prefix) {\n\t\t\tsearch = search[len(n.prefix):]\n\n\t\t} else if bytes.HasPrefix(n.prefix, search) {\n\t\t\t// Child may be under our search prefix\n\t\t\trecursiveWalk(n, fn)\n\t\t\treturn\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (t *BPTree) PrefixScan(prefix []byte, offsetNum int, limitNum int) (records Records, off int, err error) {\n\tvar (\n\t\tn *Node\n\t\tscanFlag bool\n\t\tkeys [][]byte\n\t\tpointers []interface{}\n\t\ti, j, numFound int\n\t)\n\n\tn = t.FindLeaf(prefix)\n\n\tif n == nil {\n\t\treturn nil, off, ErrPrefixScansNoResult\n\t}\n\n\tfor j = 0; j < n.KeysNum && compare(n.Keys[j], prefix) < 0; {\n\t\tj++\n\t}\n\n\tscanFlag = true\n\tnumFound = 0\n\n\tcoff := 0\n\n\tfor n != nil && scanFlag {\n\t\tfor i = j; i < n.KeysNum; i++ {\n\n\t\t\tif !bytes.HasPrefix(n.Keys[i], prefix) {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif coff < offsetNum {\n\t\t\t\tcoff++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, n.Keys[i])\n\t\t\tpointers = append(pointers, n.pointers[i])\n\t\t\tnumFound++\n\n\t\t\tif limitNum > 0 && numFound == limitNum {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tn, _ = n.pointers[order-1].(*Node)\n\t\tj = 0\n\t}\n\n\toff = coff\n\n\tesr, err := getRecordWrapper(numFound, keys, pointers)\n\treturn esr, off, err\n}", "func (t *BPTree) PrefixSearchScan(prefix []byte, reg string, offsetNum int, limitNum int) (records Records, off int, err error) {\n\tvar (\n\t\tn *Node\n\t\tscanFlag bool\n\t\tkeys [][]byte\n\t\tpointers []interface{}\n\t\ti, j, numFound int\n\t)\n\n\trgx, err := regexp.Compile(reg)\n\tif err != nil {\n\t\treturn nil, off, ErrBadRegexp\n\t}\n\n\tn = t.FindLeaf(prefix)\n\n\tif n == nil {\n\t\treturn nil, off, ErrPrefixSearchScansNoResult\n\t}\n\n\tfor j = 0; j < n.KeysNum && compare(n.Keys[j], prefix) < 0; {\n\t\tj++\n\t}\n\n\tscanFlag = true\n\tnumFound = 0\n\n\tcoff := 0\n\n\tfor n != nil && scanFlag {\n\t\tfor i = j; i < n.KeysNum; i++ {\n\n\t\t\tif !bytes.HasPrefix(n.Keys[i], prefix) {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif coff < offsetNum {\n\t\t\t\tcoff++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !rgx.Match(bytes.TrimPrefix(n.Keys[i], prefix)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, n.Keys[i])\n\t\t\tpointers = append(pointers, n.pointers[i])\n\t\t\tnumFound++\n\n\t\t\tif limitNum > 0 && numFound == limitNum {\n\t\t\t\tscanFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tn, _ = n.pointers[order-1].(*Node)\n\t\tj = 0\n\t}\n\n\toff = coff\n\n\tesr, err := getRecordWrapper(numFound, keys, pointers)\n\treturn esr, off, err\n}", "func (vm *FstVM) PrefixSearch(input string) (int, []string) {\n\ttape, snap, _ := vm.run(input)\n\tif len(snap) == 0 {\n\t\treturn -1, nil\n\t}\n\tc := snap[len(snap)-1]\n\tpc := c.pc\n\tsz := int(vm.prog[pc] & valMask)\n\tpc++\n\tif sz == 0 {\n\t\treturn c.inp, []string{string(tape[0:c.tape])}\n\t}\n\ts := toInt(vm.prog[pc : pc+sz])\n\tpc += sz\n\tsz = int(vm.prog[pc])\n\tpc++\n\te := toInt(vm.prog[pc : pc+sz])\n\tvar outs []string\n\tfor i := s; i < e; i++ {\n\t\th := i\n\t\tfor vm.data[i] != 0 {\n\t\t\ti++\n\t\t}\n\t\tt := append(tape[0:c.tape], vm.data[h:i]...)\n\t\touts = append(outs, string(t))\n\t}\n\tpc += sz\n\treturn c.inp, outs\n}", "func (t *ArtTree) PrefixSearch(key []byte) []interface{} {\n\tret := make([]interface{}, 0)\n\tfor r := range t.PrefixSearchChan(key) {\n\t\tret = append(ret, r.Value)\n\t}\n\treturn ret\n}", "func (tr *d8RTree) Count() int {\n\tvar count int\n\td8countRec(tr.root, &count)\n\treturn count\n}", "func (d *Driver) Count(ctx context.Context, prefix string) (revRet int64, count int64, err error) {\n\tstart := time.Now()\n\tdefer func() {\n\t\tdur := time.Since(start)\n\t\tfStr := \"COUNT %s => rev=%d, count=%d, err=%v, duration=%s\"\n\t\td.logMethod(dur, fStr, prefix, revRet, count, err, dur)\n\t}()\n\n\tentries, err := d.getKeys(ctx, prefix, false)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\t// current revision\n\tcurrentRev, err := d.currentRevision()\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\treturn currentRev, int64(len(entries)), nil\n}", "func (t *Trie) Search(w string) int {\n\tcur := t.root\n\tfor _, c := range []byte(w) {\n\t\ti := c - 'a'\n\t\tif cur.children[i] == nil {\n\t\t\treturn 0\n\t\t}\n\t\tcur = cur.children[i]\n\t}\n\treturn cur.count\n}", "func (n IPv4Network) GetPrefixLength() int {\n\tslice := strings.Split(n.CIDR, \"/\")\n\tlen, _ := strconv.Atoi(slice[1])\n\treturn len\n}", "func (t *Trie) HasPrefix(word string) bool {\n\tnode := t.root.nodeByPrefix(word)\n\tif node == nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n node := this.root\n for _, r := range prefix {\n child, existed := node.children[r]\n if !existed {\n return false\n }\n node = child\n }\n return true\n}", "func (tr *d19RTree) Count() int {\n\tvar count int\n\td19countRec(tr.root, &count)\n\treturn count\n}", "func (t *Trie) Len() uint32 {\n\tif t.root == nil {\n\t\treturn 0\n\t}\n\treturn t.root.count\n}", "func (tr *d10RTree) Count() int {\n\tvar count int\n\td10countRec(tr.root, &count)\n\treturn count\n}", "func (t *Tree) Count() (int, error) {\n\tif t == nil {\n\t\treturn 0, errors.New(errors.KsiInvalidArgumentError)\n\t}\n\n\treturn len(t.leafs), nil\n}", "func (tr *d3RTree) Count() int {\n\tvar count int\n\td3countRec(tr.root, &count)\n\treturn count\n}", "func (c *Client) WatchPrefix(prefix string, keys []string, waitIndex uint64, stopChan chan bool) (uint64, error) {\n\t<-stopChan\n\treturn 0, nil\n}", "func (c *Client) WatchPrefix(prefix string, keys []string, waitIndex uint64, stopChan chan bool) (uint64, error) {\n\t<-stopChan\n\treturn 0, nil\n}", "func (tr *d13RTree) Count() int {\n\tvar count int\n\td13countRec(tr.root, &count)\n\treturn count\n}", "func (tr *d14RTree) Count() int {\n\tvar count int\n\td14countRec(tr.root, &count)\n\treturn count\n}", "func (pf *pebbleFetcher) fetchRangeWithPrefix() (int, error) {\n\tvar lowerBound, middleBound, upperBound []byte\n\n\tif pf.opts.Prefix != \"\" {\n\t\tlowerBound = []byte(pf.opts.Prefix)\n\t\tmiddleBound = lowerBound\n\t\tupperBound = calcUpperBound(pf.opts.Prefix)\n\n\t\tif pf.opts.CurrentDir != \"\" && pf.opts.CurrentDir != pf.opts.Prefix {\n\t\t\tmiddleBound = []byte(pf.opts.CurrentDir)\n\t\t}\n\t}\n\n\tvar err error\n\tpf.count, err = pf.fetchRange(middleBound, upperBound)\n\tif err != nil {\n\t\treturn pf.count, err\n\t}\n\n\treturn pf.fetchRange(lowerBound, middleBound)\n\n}", "func (tr *d11RTree) Count() int {\n\tvar count int\n\td11countRec(tr.root, &count)\n\treturn count\n}", "func (tr *d1RTree) Count() int {\n\tvar count int\n\td1countRec(tr.root, &count)\n\treturn count\n}", "func (this *Trie) StartsWith(prefix string) bool {\n node := this.searchPrefix(prefix)\n \n return node != nil\n}", "func (tr *d12RTree) Count() int {\n\tvar count int\n\td12countRec(tr.root, &count)\n\treturn count\n}", "func Count(root *Node) int {\n\t// base case\n\tif root == nil{\n\t\treturn 0\n\t}\n\n\t// 自己加上子树的节点数就是整棵树的节点数\n\treturn 1 + Count(root.Left) + Count(root.Right)\n}", "func (tr *d6RTree) Count() int {\n\tvar count int\n\td6countRec(tr.root, &count)\n\treturn count\n}", "func (t *TST) Prefix(p string) []string {\n\tif p == \"\" {\n\t\treturn nil\n\t}\n\tn := t.root.get(p)\n\tif n == nil {\n\t\treturn nil // nothing has this prefix\n\t}\n\tmatches := []string{}\n\tif n.val != nil {\n\t\tmatches = append(matches, p)\n\t}\n\tn.eqkid.rprefix(p, &matches)\n\tif len(matches) > 0 {\n\t\treturn matches\n\t}\n\treturn nil\n}", "func (tr *d4RTree) Count() int {\n\tvar count int\n\td4countRec(tr.root, &count)\n\treturn count\n}", "func (q treeQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count trees rows\")\n\t}\n\n\treturn count, nil\n}", "func (c *Client) WatchPrefix(ctx context.Context, prefix string, opts ...easykv.WatchOption) (uint64, error) {\n\tvar options easykv.WatchOptions\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\trespChan := make(chan watchResponse)\n\tgo func() {\n\t\topts := api.QueryOptions{\n\t\t\tWaitIndex: options.WaitIndex,\n\t\t}\n\t\t_, meta, err := c.client.List(prefix, &opts)\n\t\tif err != nil {\n\t\t\trespChan <- watchResponse{options.WaitIndex, err}\n\t\t\treturn\n\t\t}\n\t\trespChan <- watchResponse{meta.LastIndex, err}\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn options.WaitIndex, easykv.ErrWatchCanceled\n\t\tcase r := <-respChan:\n\t\t\treturn r.waitIndex, r.err\n\t\t}\n\t}\n}", "func (t *Tree) Count() int {\n\tif t.root != nil {\n\t\treturn t.root.size\n\t}\n\n\treturn 0\n}", "func PrefixDetector(prefix string, handler Handler) Detector {\n\treturn Detector{\n\t\tNeeded: len([]byte(prefix)),\n\t\tTest: func(b []byte) bool { return string(b) == prefix },\n\t\tHandler: handler,\n\t}\n}", "func (tr *d18RTree) Count() int {\n\tvar count int\n\td18countRec(tr.root, &count)\n\treturn count\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tcur := this.root\n\n\t// go through prefix\n\tfor _, c := range prefix {\n\t\t// check if in children\n\t\tif child, ok := cur.children[c]; ok {\n\t\t\t// set cur\n\t\t\tcur = child\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// no probs\n\treturn true\n}", "func (o NetworkInterfaceOutput) Ipv4PrefixCount() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *NetworkInterface) pulumi.IntPtrOutput { return v.Ipv4PrefixCount }).(pulumi.IntPtrOutput)\n}", "func (tr *d17RTree) Count() int {\n\tvar count int\n\td17countRec(tr.root, &count)\n\treturn count\n}", "func (t *Trie) existsPrefix(prefix string, validWord bool) bool {\n\trunner := t.Root\n\n\tfor _, currChar := range prefix {\n\t\tif _, ok := runner.Children[currChar]; !ok {\n\t\t\treturn false\n\t\t}\n\t\trunner = runner.Children[currChar]\n\t}\n\n\tif validWord && !runner.IsWord {\n\t\treturn false\n\t}\n\treturn true\n}", "func (tr *d7RTree) Count() int {\n\tvar count int\n\td7countRec(tr.root, &count)\n\treturn count\n}", "func (tr *d9RTree) Count() int {\n\tvar count int\n\td9countRec(tr.root, &count)\n\treturn count\n}", "func (t *Trie) FindPrefixes(key string, f Visitor) {\n\tcur := t.root\n\tif cur.value != nil && !f(\"\", cur.value) {\n\t\treturn\n\t}\n\n\tfor i, r := range key {\n\t\tnext, ok := cur.children[r]\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\tif next.value != nil && !f(key[:(i+1)], next.value) {\n\t\t\treturn\n\t\t}\n\t\tcur = next\n\t}\n}", "func HasPrefix(prefix, operand string) bool { return strings.HasPrefix(operand, prefix) }", "func (tr *d20RTree) Count() int {\n\tvar count int\n\td20countRec(tr.root, &count)\n\treturn count\n}", "func (this *Trie) Search(word string) bool {\n node := this.searchPrefix(word)\n \n return node != nil && node.isEnd\n}", "func (trie *Trie) Count() int {\n\tcount := 0\n\tfor _, child := range trie.children {\n\t\tif child.isLeaf == true {\n\t\t\tcount++\n\t\t}\n\n\t\tcount += child.Count()\n\t}\n\n\treturn count\n}", "func (b *Builder) HasPrefix(rhs interface{}) *predicate.Predicate {\n\tb.p.RegisterPredicate(impl.HasPrefix(rhs))\n\tif b.t != nil {\n\t\tb.t.Helper()\n\t\tEvaluate(b)\n\t}\n\treturn &b.p\n}", "func (r *Root) Count() (c *CountResult) {\n\tc = new(CountResult)\n\tc.Add(r.Roots.BookmarkBar.Name, len(r.Roots.BookmarkBar.Children))\n\tc.Add(r.Roots.Other.Name, len(r.Roots.Other.Children))\n\tc.Add(r.Roots.Synced.Name, len(r.Roots.Synced.Children))\n\n\treturn\n}", "func (n *NodeServiceImpl) Count(namespace string) (map[string]int, error) {\n\tlist, err := n.List(namespace, &models.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn map[string]int{\n\t\tplugin.QuotaNode: len(list.Items),\n\t}, nil\n}", "func (t *Tree) Count() int {\n\t// Only test the Left node (this binary tree is expected to be complete).\n\tif t.Left == nil {\n\t\treturn 1\n\t}\n\treturn 1 + t.Right.Count() + t.Left.Count()\n}", "func (tr *d16RTree) Count() int {\n\tvar count int\n\td16countRec(tr.root, &count)\n\treturn count\n}", "func prefixIndex(addr uint8, prefixLen int) int {\n\t// the prefixIndex of addr/prefixLen is the prefixLen most significant bits\n\t// of addr, with a 1 tacked onto the left-hand side. For example:\n\t//\n\t// - 0/0 is 1: 0 bits of the addr, with a 1 tacked on\n\t// - 42/8 is 1_00101010 (298): all bits of 42, with a 1 tacked on\n\t// - 48/4 is 1_0011 (19): 4 most-significant bits of 48, with a 1 tacked on\n\treturn (int(addr) >> (8 - prefixLen)) + (1 << prefixLen)\n}", "func (tr *d15RTree) Count() int {\n\tvar count int\n\td15countRec(tr.root, &count)\n\treturn count\n}", "func (c *Client) WatchPrefix(ctx context.Context, prefix string, opts ...easykv.WatchOption) (uint64, error) {\n\tif c.isURL {\n\t\t// watch is not supported for urls\n\t\treturn 0, easykv.ErrWatchNotSupported\n\t}\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer watcher.Close()\n\n\terr = watcher.Add(c.filepath)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase event := <-watcher.Events:\n\t\t\tif event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Remove == fsnotify.Remove {\n\t\t\t\treturn 1, nil\n\t\t\t}\n\t\tcase err := <-watcher.Errors:\n\t\t\treturn 0, err\n\t\tcase <-ctx.Done():\n\t\t\treturn 0, easykv.ErrWatchCanceled\n\t\t}\n\t}\n}", "func (t *Trie) StartWith(prefix string) bool {\n\tcurr := t.Root\n\tfor _, char := range prefix {\n\t\tif _, ok := curr.Children[char]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tcurr = curr.Children[char]\n\t}\n\treturn true\n}", "func (tr *d2RTree) Count() int {\n\tvar count int\n\td2countRec(tr.root, &count)\n\treturn count\n}", "func (s *Store) FindPrefix(bucket, prefix []byte, next func(key, val []byte) bool) error {\n\treturn s.db.View(func(tx *bolt.Tx) error {\n\t\tc := tx.Bucket(bucket).Cursor()\n\t\tfor k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {\n\t\t\tif !next(k, v) {\n\t\t\t\treturn io.EOF\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (t *TrieNode) Find(prefix string, max int) []int64 {\n\tt.mx.RLock()\n\tdefer t.mx.RUnlock()\n\n\tif len(t.children) == 0 || prefix == \"\" || max <= 0 {\n\t\treturn nil\n\t}\n\n\t// iterate through trie until at end of prefix\n\tprefixRunes := []rune(prefix)\n\ttriePointer := t\n\tfor _, s := range prefixRunes {\n\t\tif triePointer.children[s] == nil {\n\t\t\treturn nil\n\t\t}\n\t\ttriePointer = triePointer.children[s]\n\t}\n\n\t// create int64 slice\n\tvar returnSlice []int64\n\ttriePointer.findDFS(&returnSlice, max)\n\treturn returnSlice\n}", "func (b DeleteBuilder) Prefix(sql string, args ...interface{}) DeleteCondition {\n\treturn builder.Append(b, \"Prefixes\", Expr(sql, args...)).(DeleteBuilder)\n}", "func (n *nodeHeader) prefixFields() (*uint16, []byte) {\n\tswitch n.typ {\n\tcase typLeaf:\n\t\t// Leaves have no prefix\n\t\treturn nil, nil\n\tcase typNode4:\n\t\tn4 := n.node4()\n\t\treturn &n4.prefixLen, n4.prefix[:]\n\n\tcase typNode16:\n\t\tn16 := n.node16()\n\t\treturn &n16.prefixLen, n16.prefix[:]\n\n\tcase typNode48:\n\t\tn48 := n.node48()\n\t\treturn &n48.prefixLen, n48.prefix[:]\n\n\tcase typNode256:\n\t\tn256 := n.node256()\n\t\treturn &n256.prefixLen, n256.prefix[:]\n\t}\n\tpanic(\"invalid type\")\n}", "func (b UpdateBuilder) Prefix(sql string, args ...interface{}) UpdateCondition {\n\treturn builder.Append(b, \"Prefixes\", Expr(sql, args...)).(UpdateBuilder)\n}", "func (am *AppchainManager) CountAll(_ []byte) (bool, []byte) {\n\tok, value := am.Query(PREFIX)\n\tif !ok {\n\t\treturn true, []byte(\"0\")\n\t}\n\treturn true, []byte(strconv.Itoa(len(value)))\n}", "func (t *TrieNode) Len() int {\n\tt.mx.RLock()\n\tdefer t.mx.RUnlock()\n\treturn t.LenHelper()\n}", "func (tr *d5RTree) Count() int {\n\tvar count int\n\td5countRec(tr.root, &count)\n\treturn count\n}", "func PrefixLength(be Lister, t Type) (int, error) {\n\t// load all IDs of the given type\n\tlist, err := be.List(t)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tsort.Sort(list)\n\n\t// select prefixes of length l, test if the last one is the same as the current one\nouter:\n\tfor l := MinPrefixLength; l < IDSize; l++ {\n\t\tvar last ID\n\n\t\tfor _, id := range list {\n\t\t\tif bytes.Equal(last, id[:l]) {\n\t\t\t\tcontinue outer\n\t\t\t}\n\t\t\tlast = id[:l]\n\t\t}\n\n\t\treturn l, nil\n\t}\n\n\treturn IDSize, nil\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\n\tnode := this.searchPrefix(prefix)\n\tif node == nil {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (n *nodeHeader) prefix() []byte {\n\tpLen, pBytes := n.prefixFields()\n\n\tif *pLen <= maxPrefixLen {\n\t\t// We have the whole prefix from the node\n\t\treturn pBytes[0:*pLen]\n\t}\n\n\t// Prefix is too long for node, we have to go find it from the leaf\n\tminLeaf := n.minChild().leafNode()\n\treturn minLeaf.key[0:*pLen]\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tcur := this.Root\n\tfor _, c := range prefix {\n\t\tif _, ok := cur.Child[c]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tcur = cur.Child[c]\n\t}\n\treturn true\n}", "func (triple *TripleNode) NodeCounts() (nodeCount, nilCount int) {\n\tvar leftCount, leftNilCount, middleCount, middleNilCount, rightCount, rightNilCount int\n\t// Handle left branch\n\tif triple.LeftChild == nil {\n\t\t// No left child\n\t\tleftNilCount = 1\n\t\tleftCount = 0\n\t} else {\n\t\t// There is a left child\n\t\tleftCount, leftNilCount = triple.LeftChild.NodeCounts()\n\t}\n\n\t// Handle middle branch\n\tif triple.MiddleChild == nil {\n\t\t// No middle child\n\t\tmiddleNilCount = 1\n\t\tmiddleCount = 0\n\t} else {\n\t\t// There is a middle child\n\t\tmiddleCount, middleNilCount = triple.MiddleChild.NodeCounts()\n\t}\n\n\t// Handle right branch\n\tif triple.RightChild == nil {\n\t\t// No right child\n\t\trightNilCount = 1\n\t\trightCount = 0\n\t} else {\n\t\t// There is a right child\n\t\trightCount, rightNilCount = triple.RightChild.NodeCounts()\n\t}\n\n\treturn 1 + leftCount + middleCount + rightCount, leftNilCount + middleNilCount + rightNilCount // + 1 is ourself\n}", "func (t *Trie) FindWithPrefix(prefix string) []string {\n\twords := make([]string, 0)\n\tn := t.find(prefix)\n\tif n == nil {\n\t\treturn words\n\t}\n\tsuffix := t.getSuffix(n)\n\tfor _, s := range suffix {\n\t\twords = append(words, prefix+s)\n\t}\n\treturn words\n}", "func (t *Trie) StartsWith(prefix string) bool {\n\tp := t.root\n\twordArr := []rune(prefix)\n\n\tfor i := 0; i < len(wordArr); i++ {\n\t\tif p.edges[wordArr[i]-'a'] == nil {\n\t\t\treturn false\n\t\t} else {\n\t\t\tp = p.edges[wordArr[i]-'a']\n\t\t}\n\t}\n\treturn true\n}", "func (id ID) PrefixLen() int {\n\tfor i, b := range id.EthAddress {\n\t\tif b != 0 {\n\t\t\treturn i*8 + bits.LeadingZeros8(uint8(b))\n\t\t}\n\t}\n\treturn len(id.EthAddress)*8 - 1\n}", "func (this *Trie) StartsWith(prefix string) bool {\n if len(prefix) == 0 {return true}\n if this == nil || this.path == nil || this.path[prefix[0] - 'a'] == nil {return false}\n if len(prefix) == 1 {return this.path[prefix[0] - 'a'] != nil}\n this = this.path[prefix[0] - 'a']\n return this.StartsWith(prefix[1:])\n}", "func (a *Assertions) HasPrefix(corpus, prefix string, userMessageComponents ...interface{}) bool {\n\ta.assertion()\n\tif didFail, message := shouldHasPrefix(corpus, prefix); didFail {\n\t\treturn a.fail(message, userMessageComponents...)\n\t}\n\treturn true\n}", "func MatchPrefix(prefixes ...string) MatcherFunc { return MatchPrefixes(prefixes) }", "func (this *Trie) StartsWith(prefix string) bool {\n\tn := this.root\n\n\tfor i := 0; i < len(prefix); i++ {\n\t\twid := prefix[i] - 'a'\n\t\tif n.children[wid] == nil {\n\t\t\treturn false\n\t\t}\n\t\tn = n.children[wid]\n\t}\n\n\treturn true\n}", "func (q nodeQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count node rows\")\n\t}\n\n\treturn count, nil\n}", "func (pars *Parser) parsePrefixExpression() tree.Expression {\n\texpression := &tree.PrefixExpression{\n\t\tToken: pars.thisToken,\n\t\tOperator: pars.thisToken.Val,\n\t}\n\n\tpars.nextToken()\n\n\texpression.Right = pars.parseExpression(PREFIX)\n\treturn expression\n}", "func (t *Trie) Search(word string) bool {\n\tnode := t.searchPrefix(word)\n\treturn node != nil && node.isEnd\n}", "func (this *Trie) StartsWith(prefix string) bool {\r\n\tstrbyte := []byte(prefix)\r\n\tcurroot := this\r\n\tfor _, char := range strbyte {\r\n\t\tcurroot = curroot.childs[char-'a']\r\n\t\tif curroot == nil {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}", "func (n Nodes) Len() int", "func (this *Trie) StartsWith(prefix string) bool {\n\tif prefix == \"\" {\n\t\treturn true\n\t}\n\tif this == nil {\n\t\treturn false\n\t}\n\tindex := ([]byte(prefix[0:1]))[0] - byte('a')\n\tif this.child[index] == nil {\n\t\treturn false\n\t}\n\tif prefix[1:] == \"\" {\n\t\treturn true\n\t}\n\treturn this.child[index].StartsWith(prefix[1:])\n\n}", "func (s *searchServiceServer) PathPrefix() string {\n\treturn baseServicePath(s.pathPrefix, \"buf.alpha.registry.v1alpha1\", \"SearchService\")\n}", "func (b *BTree) Len() int {\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\treturn int(b.rootNod.GetLength())\n}", "func (t *Tree) Len() int {\n\treturn t.Count\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\ttrie := this\n\tfor _, char := range prefix {\n\t\tif trie.childs[char-97] == nil {\n\t\t\treturn false\n\t\t}\n\t\ttrie = trie.childs[char-97]\n\t}\n\treturn true\n}", "func (pu *PrefixUpdate) Save(ctx context.Context) (int, error) {\n\tif v, ok := pu.mutation.Prefix(); ok {\n\t\tif err := prefix.PrefixValidator(v); err != nil {\n\t\t\treturn 0, &ValidationError{Name: \"prefix\", err: fmt.Errorf(\"ent: validator failed for field \\\"prefix\\\": %w\", err)}\n\t\t}\n\t}\n\n\tvar (\n\t\terr error\n\t\taffected int\n\t)\n\tif len(pu.hooks) == 0 {\n\t\taffected, err = pu.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*PrefixMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tpu.mutation = mutation\n\t\t\taffected, err = pu.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn affected, err\n\t\t})\n\t\tfor i := len(pu.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = pu.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, pu.mutation); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn affected, err\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tnode := this\n\tn := len(prefix)\n\tfor i := 0; i < n; i++ {\n\t\tidx := prefix[i] - 'a'\n\t\tif node.sons[idx] == nil {\n\t\t\treturn false\n\t\t}\n\t\tnode = node.sons[idx]\n\t}\n\treturn true\n}", "func (t *Tree) Len() int { return t.Count }", "func countListParents(opt *Options, selec *goquery.Selection) (int, int) {\n\tvar values []int\n\tfor n := selec.Parent(); n != nil; n = n.Parent() {\n\t\tif n.Is(\"li\") {\n\t\t\tcontinue\n\t\t}\n\t\tif !n.Is(\"ul\") && !n.Is(\"ol\") {\n\t\t\tbreak\n\t\t}\n\n\t\tprefix := n.Children().First().AttrOr(attrListPrefix, \"\")\n\n\t\tvalues = append(values, len(prefix))\n\t}\n\n\t// how many spaces are reserved for the prefixes of my siblings\n\tvar prefixCount int\n\n\t// how many spaces are reserved in total for all of the other\n\t// list parents up the tree\n\tvar previousPrefixCounts int\n\n\tfor i, val := range values {\n\t\tif i == 0 {\n\t\t\tprefixCount = val\n\t\t\tcontinue\n\t\t}\n\n\t\tpreviousPrefixCounts += val\n\t}\n\n\treturn prefixCount, previousPrefixCounts\n}", "func (this *Trie) Search(s string, allowPrefix bool) bool {\n\tvar t *TrieNode = this.root\n\tfor _, a := range s {\n\t\tt = t.HasChild(a)\n\t\tif t == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn allowPrefix || t.GetEnd()\n}", "func PrefixLen(f EncryptFunc, bs int) int {\n\tstart := FirstModBlock(f, bs) * bs\n\tend := start + bs\n\n\t// Figure out what the modifiable block looks like when its remaining bytes\n\t// are filled with our own characters.\n\ta := f(A(bs))[start:end]\n\tb := f(B(bs))[start:end]\n\n\t// Add bytes until we see the expected blocks.\n\tfor i := 0; i < bs; i++ {\n\t\tif bytes.Equal(f(A(i + 1))[start:end], a) &&\n\t\t\tbytes.Equal(f(B(i + 1))[start:end], b) {\n\t\t\treturn end - i - 1\n\t\t}\n\t}\n\tpanic(\"couldn't find prefix length\")\n}", "func (p *Parser) parsePrefixExpression() ast.Expression {\n\texpression := &ast.PrefixExpression{\n\t\tToken: p.curToken,\n\t\tOperator: p.curToken.Literal}\n\tp.nextToken()\n\texpression.Right = p.parseExpression(PREFIX)\n\treturn expression\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\troot := this\n\tfor _, chartV := range prefix {\n\t\tnext, ok := root.next[string(chartV)]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\troot = next\n\t}\n\treturn true\n}", "func (this *Trie) StartsWith(prefix string) bool {\n\tif len(prefix) == 0 {\n\t\treturn true\n\t}\n\tfor _, e := range this.edges {\n\t\tif e.char == prefix[0] {\n\t\t\treturn e.next.StartsWith(prefix[1:])\n\t\t}\n\t}\n\treturn false\n}", "func (p *Parser) parsePrefixExpression() asti.ExpressionI {\n\texpression := &ast.PrefixExpression{\n\t\tToken: p.curToken,\n\t\tOperator: p.curToken.Type,\n\t}\n\tp.nextToken()\n\texpression.Right = p.parseExpression(precedence.PREFIX)\n\treturn expression\n}" ]
[ "0.676077", "0.6484417", "0.63465744", "0.6022248", "0.6011498", "0.5960126", "0.5949926", "0.57407993", "0.5624859", "0.5569003", "0.5540688", "0.54302657", "0.54262424", "0.5414123", "0.5365138", "0.5362125", "0.53595495", "0.5323589", "0.53140223", "0.53023636", "0.5278311", "0.5278311", "0.52627194", "0.52550304", "0.5246604", "0.52394", "0.52348846", "0.5229449", "0.5223332", "0.5221897", "0.5213063", "0.5201663", "0.5196343", "0.5193746", "0.5193686", "0.5184753", "0.51841897", "0.5182623", "0.5181127", "0.51810455", "0.5178577", "0.5178004", "0.5177767", "0.51765907", "0.5150194", "0.5137543", "0.5125225", "0.5122387", "0.51215273", "0.51166666", "0.5115429", "0.5113338", "0.51124185", "0.5088814", "0.508275", "0.50816625", "0.50659484", "0.50633276", "0.50496143", "0.50392985", "0.50331295", "0.50175375", "0.50142956", "0.5010535", "0.5009873", "0.4988309", "0.49821255", "0.49814966", "0.49802244", "0.49633896", "0.4956749", "0.49554884", "0.49550077", "0.49411118", "0.49349904", "0.49169853", "0.48813793", "0.4871062", "0.48574397", "0.4848166", "0.48465896", "0.4831551", "0.4829912", "0.48292503", "0.4826334", "0.48194522", "0.4818557", "0.48181185", "0.48000684", "0.47963518", "0.4793899", "0.47827333", "0.47820684", "0.47754598", "0.47742593", "0.47710064", "0.47676992", "0.47652376", "0.47602051", "0.47569117" ]
0.77689135
0
LookupCalled looks up ssa.Instruction that call the `fn` func in the given instr
func LookupCalled(instr ssa.Instruction, fn *types.Func) ([]ssa.Instruction, bool) { instrs := []ssa.Instruction{} call, ok := instr.(ssa.CallInstruction) if !ok { return instrs, false } ssaCall := call.Value() if ssaCall == nil { return instrs, false } common := ssaCall.Common() if common == nil { return instrs, false } val := common.Value called := false switch fnval := val.(type) { case *ssa.Function: for _, block := range fnval.Blocks { for _, instr := range block.Instrs { if analysisutil.Called(instr, nil, fn) { called = true instrs = append(instrs, instr) } } } } return instrs, called }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Module) instCall(old *ast.InstCall, resolved, unresolved map[ast.NamedValue]value.Named) bool {\n\tif isUnresolved(unresolved, old.Callee) || isUnresolved(unresolved, old.Args...) {\n\t\treturn false\n\t}\n\tv := m.getLocal(old.Name)\n\tinst, ok := v.(*ir.InstCall)\n\tif !ok {\n\t\tpanic(fmt.Errorf(\"invalid instruction type for instruction %s; expected *ir.InstCall, got %T\", enc.Local(old.Name), v))\n\t}\n\tvar (\n\t\ttyp *types.PointerType\n\t\tsig *types.FuncType\n\t)\n\tvar args []value.Value\n\tfor _, oldArg := range old.Args {\n\t\targ := m.irValue(oldArg)\n\t\targs = append(args, arg)\n\t}\n\tcallee := m.irValue(old.Callee)\n\tif c, ok := callee.(*ir.InlineAsm); ok {\n\t\tswitch t := c.Typ.(type) {\n\t\tcase *types.FuncType:\n\t\t\tsig = t\n\t\tdefault:\n\t\t\t// Result type stored in t, get parameters for function signature from\n\t\t\t// arguments. Not perfect, but the best we can do. In particular, this\n\t\t\t// approach is known to fail for variadic parameters.\n\t\t\tvar params []*types.Param\n\t\t\tfor _, arg := range args {\n\t\t\t\tparam := types.NewParam(\"\", arg.Type())\n\t\t\t\tparams = append(params, param)\n\t\t\t}\n\t\t\tsig = types.NewFunc(t, params...)\n\t\t}\n\t\ttyp = types.NewPointer(sig)\n\t} else {\n\t\tvar ok bool\n\t\ttyp, ok = callee.Type().(*types.PointerType)\n\t\tif !ok {\n\t\t\tpanic(fmt.Errorf(\"invalid callee type, expected *types.PointerType, got %T\", callee.Type()))\n\t\t}\n\t\tsig, ok = typ.Elem.(*types.FuncType)\n\t\tif !ok {\n\t\t\tpanic(fmt.Errorf(\"invalid callee signature type, expected *types.FuncType, got %T\", typ.Elem))\n\t\t}\n\t}\n\tinst.Callee = callee\n\tinst.Sig = sig\n\t// TODO: Validate old.Type against inst.Sig.\n\tinst.Args = args\n\tinst.CallConv = ir.CallConv(old.CallConv)\n\tinst.Metadata = m.irMetadata(old.Metadata)\n\treturn true\n}", "func FnCall() bool {\n\treturn fnCall\n}", "func (th *Thread) CallLookup(this Value, method string, args ...Value) Value {\n\treturn th.CallThis(th.Lookup(this, method), this, args...)\n}", "func (l *Loader) SetLookupFn(fn func(string) (string, bool)) {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tl.lookUp = fn\n}", "func (l *InfosT) ByRuntimeFunc(argFunc *runtime.Func) Info {\n\n\tfor i := 0; i < len(*l); i++ {\n\t\tlpFunc := (*l)[i].Handler\n\t\tlpFuncType := reflect.ValueOf(lpFunc)\n\t\tif lpFuncType.Pointer() == argFunc.Entry() {\n\t\t\treturn (*l)[i]\n\t\t}\n\t}\n\tlog.Panicf(\"unknown runtime func %+v\", argFunc)\n\treturn Info{}\n}", "func (_f6 *FakeResolver) ResolveCalledWith(name string) (found bool) {\n\tfor _, call := range _f6.ResolveCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Name, name) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func callFn(name string, unit reflect.Value, args []reflect.Value) error {\n\tif fn := unit.MethodByName(name); fn.IsValid() == false {\n\t\treturn nil\n\t} else if ret := fn.Call(args); len(ret) != 1 {\n\t\treturn nil\n\t} else if err, ok := ret[0].Interface().(error); ok {\n\t\treturn err\n\t} else if err == nil {\n\t\treturn nil\n\t} else {\n\t\treturn gopi.ErrBadParameter.WithPrefix(name)\n\t}\n}", "func Lookup(key string) RunnerFunc {\n\tv, ok := runners.Load(key)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn v.(RunnerFunc)\n}", "func (_f2 *FakeInterfacer) InterfaceCalledWith(ident1 interface{}) (found bool) {\n\tfor _, call := range _f2.InterfaceCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Ident1, ident1) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (bi *BinaryInfo) LookupGenericFunc() map[string][]*Function {\n\tif bi.lookupGenericFunc == nil {\n\t\tbi.lookupGenericFunc = make(map[string][]*Function)\n\t\tfor i := range bi.Functions {\n\t\t\tdn := bi.Functions[i].NameWithoutTypeParams()\n\t\t\tif dn != bi.Functions[i].Name {\n\t\t\t\tbi.lookupGenericFunc[dn] = append(bi.lookupGenericFunc[dn], &bi.Functions[i])\n\t\t\t}\n\t\t}\n\t}\n\treturn bi.lookupGenericFunc\n}", "func (m *Mock) Called(arguments ...interface{}) Arguments {\n\t// get the calling function's name\n\tpc, _, _, ok := runtime.Caller(1)\n\tif !ok {\n\t\tpanic(\"Couldn't get the caller information\")\n\t}\n\tfunctionPath := runtime.FuncForPC(pc).Name()\n\t// Next four lines are required to use GCCGO function naming conventions.\n\t// For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock\n\t// uses interface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree\n\t// With GCCGO we need to remove interface information starting from pN<dd>.\n\tif gccgoRE.MatchString(functionPath) {\n\t\tfunctionPath = gccgoRE.Split(functionPath, -1)[0]\n\t}\n\tparts := strings.Split(functionPath, \".\")\n\tfunctionName := parts[len(parts)-1]\n\treturn m.MethodCalled(functionName, arguments...)\n}", "func (a *ActorInfo) LookupMethod(num uint64) (MethodInfo, bool) {\n\tif idx, ok := a.methodMap[num]; ok {\n\t\treturn a.Methods[idx], true\n\t}\n\n\treturn MethodInfo{}, false\n}", "func (bi *BinaryInfo) symLookup(addr uint64) (string, uint64) {\n\tfn := bi.PCToFunc(addr)\n\tif fn != nil {\n\t\tif fn.Entry == addr {\n\t\t\t// only report the function name if it's the exact address because it's\n\t\t\t// easier to read the absolute address than function_name+offset.\n\t\t\treturn fn.Name, fn.Entry\n\t\t}\n\t\treturn \"\", 0\n\t}\n\tif sym, ok := bi.SymNames[addr]; ok {\n\t\treturn sym.Name, addr\n\t}\n\ti := sort.Search(len(bi.packageVars), func(i int) bool {\n\t\treturn bi.packageVars[i].addr >= addr\n\t})\n\tif i >= len(bi.packageVars) {\n\t\treturn \"\", 0\n\t}\n\tif bi.packageVars[i].addr > addr {\n\t\t// report previous variable + offset if i-th variable starts after addr\n\t\ti--\n\t}\n\tif i >= 0 && bi.packageVars[i].addr != 0 {\n\t\treturn bi.packageVars[i].name, bi.packageVars[i].addr\n\t}\n\treturn \"\", 0\n}", "func (mr *MockResolverMockRecorder) Lookup(service, key interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Lookup\", reflect.TypeOf((*MockResolver)(nil).Lookup), service, key)\n}", "func (s *fnSignature) Execute(ctx context.Context) ([]reflect.Value, error) {\n\tglobalBackendStatsClient().TaskExecutionCount().Inc(1)\n\ttargetArgs := make([]reflect.Value, 0, len(s.Args)+1)\n\ttargetArgs = append(targetArgs, reflect.ValueOf(ctx))\n\tfor _, arg := range s.Args {\n\t\ttargetArgs = append(targetArgs, reflect.ValueOf(arg))\n\t}\n\tif fn, ok := fnLookup.getFn(s.FnName); ok {\n\t\tfnValue := reflect.ValueOf(fn)\n\t\treturn fnValue.Call(targetArgs), nil\n\t}\n\treturn nil, fmt.Errorf(\"function: %q not found. Did you forget to register?\", s.FnName)\n}", "func TakeCallableAddr(fn interface{}) unsafe.Pointer {\n\n\t// There is no need nil checks,\n\t// because TakeRealAddr and AddrConvert2Callable already has it\n\treturn AddrConvert2Callable(TakeRealAddr(fn))\n}", "func (b *BananaPhone) GetFuncPtr(funcname string) (uint64, error) {\n\texports, err := b.banana.Exports()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfor _, ex := range exports {\n\t\tif strings.ToLower(funcname) == strings.ToLower(ex.Name) {\n\t\t\treturn uint64(b.memloc) + uint64(ex.VirtualAddress), nil\n\t\t}\n\t}\n\treturn 0, fmt.Errorf(\"could not find function: %s\", funcname)\n}", "func LookupInstruction(ctx *pulumi.Context, args *LookupInstructionArgs, opts ...pulumi.InvokeOption) (*LookupInstructionResult, error) {\n\tvar rv LookupInstructionResult\n\terr := ctx.Invoke(\"google-native:datalabeling/v1beta1:getInstruction\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func (t *LineTable) findFunc(pc uint64) funcData {\n\tft := t.funcTab()\n\tif pc < ft.pc(0) || pc >= ft.pc(ft.Count()) {\n\t\treturn funcData{}\n\t}\n\tidx := sort.Search(int(t.nfunctab), func(i int) bool {\n\t\treturn ft.pc(i) > pc\n\t})\n\tidx--\n\treturn t.funcData(uint32(idx))\n}", "func (mr *MockDirStoreMockRecorder) Lookup(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Lookup\", reflect.TypeOf((*MockDirStore)(nil).Lookup), arg0, arg1, arg2)\n}", "func (p *Process) FindFunc(pc core.Address) *Func {\n\treturn p.funcTab.find(pc)\n}", "func (info *Info) FindFunc(path string) (*ssa.Function, error) {\n\tpkgPath, fnName := parseFuncPath(path)\n\tgraph, err := info.BuildCallGraph(\"rta\", false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfuncs, err := graph.UsedFunctions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, f := range funcs {\n\t\tif f.Pkg.Pkg.Path() == pkgPath && f.Name() == fnName {\n\t\t\treturn f, nil\n\t\t}\n\t}\n\treturn nil, nil\n}", "func reflectFuncCall(fn reflect.Value, args []reflect.Value) error {\n\terrValue := fn.Call(args)\n\tvar errResult error\n\terrInter := errValue[0].Interface()\n\tif errInter != nil {\n\t\terrResult = errInter.(error)\n\t}\n\treturn errResult\n}", "func (s *BasejossListener) EnterFuncSin(ctx *FuncSinContext) {}", "func LookupFunction(ctx *pulumi.Context, args *GetFunctionArgs) (*GetFunctionResult, error) {\n\tinputs := make(map[string]interface{})\n\tif args != nil {\n\t\tinputs[\"functionName\"] = args.FunctionName\n\t\tinputs[\"qualifier\"] = args.Qualifier\n\t\tinputs[\"tags\"] = args.Tags\n\t}\n\toutputs, err := ctx.Invoke(\"aws:lambda/getFunction:getFunction\", inputs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &GetFunctionResult{\n\t\tArn: outputs[\"arn\"],\n\t\tDeadLetterConfig: outputs[\"deadLetterConfig\"],\n\t\tDescription: outputs[\"description\"],\n\t\tEnvironment: outputs[\"environment\"],\n\t\tFunctionName: outputs[\"functionName\"],\n\t\tHandler: outputs[\"handler\"],\n\t\tInvokeArn: outputs[\"invokeArn\"],\n\t\tKmsKeyArn: outputs[\"kmsKeyArn\"],\n\t\tLastModified: outputs[\"lastModified\"],\n\t\tLayers: outputs[\"layers\"],\n\t\tMemorySize: outputs[\"memorySize\"],\n\t\tQualifiedArn: outputs[\"qualifiedArn\"],\n\t\tQualifier: outputs[\"qualifier\"],\n\t\tReservedConcurrentExecutions: outputs[\"reservedConcurrentExecutions\"],\n\t\tRole: outputs[\"role\"],\n\t\tRuntime: outputs[\"runtime\"],\n\t\tSourceCodeHash: outputs[\"sourceCodeHash\"],\n\t\tSourceCodeSize: outputs[\"sourceCodeSize\"],\n\t\tTags: outputs[\"tags\"],\n\t\tTimeout: outputs[\"timeout\"],\n\t\tTracingConfig: outputs[\"tracingConfig\"],\n\t\tVersion: outputs[\"version\"],\n\t\tVpcConfig: outputs[\"vpcConfig\"],\n\t\tId: outputs[\"id\"],\n\t}, nil\n}", "func (t *ManagePatient) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n fmt.Println(\"invoke is running \" + function)\n\n // Handle different functions\n if function == \"init\" { //initialize the chaincode state, used as reset\n return t.Init(stub, \"init\", args)\n } else if function == \"create_patient\" { //create a new Patient\n return t.create_patient(stub, args)\n }\n fmt.Println(\"invoke did not find func: \" + function) //error\n return nil, errors.New(\"Received unknown function invocation\")\n}", "func (_mr *MockDraOpMockRecorder) LookupFileByMd5(arg0, arg1 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"LookupFileByMd5\", reflect.TypeOf((*MockDraOp)(nil).LookupFileByMd5), arg0, arg1)\n}", "func (mr *MockRemotesMockRecorder) Lookup(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Lookup\", reflect.TypeOf((*MockRemotes)(nil).Lookup), arg0)\n}", "func (ui *UI) DynamicCommandLookup(impl interface{}) func(string) (func(), bool) {\n\tt := reflect.TypeOf(impl)\n\treturn func(name string) (func(), bool) {\n\t\tcmd := ui.GetCommand(name)\n\t\tif cmd == nil {\n\t\t\treturn nil, false\n\t\t}\n\t\tfn, found := t.MethodByName(cmd.Original)\n\t\tif !found {\n\t\t\treturn nil, found\n\t\t}\n\t\treturn fn.Func.Interface().(func()), true\n\t}\n}", "func (mr *MockUserFinderMockRecorder) Lookup(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Lookup\", reflect.TypeOf((*MockUserFinder)(nil).Lookup), arg0)\n}", "func (bi *BinaryInfo) FindFunction(funcName string) ([]*Function, error) {\n\tif fns := bi.LookupFunc()[funcName]; fns != nil {\n\t\treturn fns, nil\n\t}\n\tfns := bi.LookupGenericFunc()[funcName]\n\tif len(fns) == 0 {\n\t\treturn nil, &ErrFunctionNotFound{funcName}\n\t}\n\treturn fns, nil\n}", "func isFunction(c *Context, callee string) {\r\n possibleFunc := c.lookup(callee)\r\n _, isFuncDec := possibleFunc.(*FuncDeclaration)\r\n performCheck(isFuncDec, fmt.Sprintf(\"ERROR: %d: Semantic: ID: %s is not a function.\", callee, possibleFunc))\r\n}", "func WrapFunc(fn interface{}) Func {\n\treturn func(hit *Hit) error {\n\t\t// TODO: hit as first arg?\n\t\treturn CallFunc(fn, hit.Args)\n\t}\n}", "func (*InstFPExt) isInst() {}", "func _getFuncPtrVal() uintptr {\n // frame 0 : assertXXX\n // frame 1 : TestXXX <- the one we want\n // frame 2 : testing.tRunner\n var frameCnt = 3\n\n // Extract the top few frames\n var pc = make([]uintptr, frameCnt)\n runtime.Callers(frameCnt, pc)\n\n return pc[1]\n}", "func (*InstFPToSI) isInst() {}", "func (cb callBacker) maybeCall(fn_name string) error {\n\tif cb.Scripter.HasEraValue(fn_name) {\n\t\treturn cb.Scripter.EraCall(fn_name)\n\t}\n\treturn nil\n}", "func (c *Container) funcOf(typ reflect.Type, method string) reflect.Value {\n\tc.lock.RLock()\n\tins, ok := c.instances[typ]\n\tc.lock.RUnlock()\n\tif !ok {\n\t\tpanic(fmt.Errorf(\"no instance for type %s\", typ))\n\t}\n\treturn reflect.ValueOf(ins).MethodByName(method)\n}", "func invokeHook(fn func() error) error {\n\tif fn != nil {\n\t\treturn fn()\n\t}\n\n\treturn nil\n}", "func GetFunc(fn func(string) string) LookupFunc {\n\treturn func(key string) (string, bool) {\n\t\tv := fn(key)\n\t\treturn v, v != \"\"\n\t}\n}", "func (fs *fsMutable) lookup(p fuseops.InodeID, c string) (le lookupEntry, found bool, lk []byte) {\n\treturn lookup(p, c, fs.lookupTree)\n}", "func (fs *fsMutable) lookup(p fuseops.InodeID, c string) (le lookupEntry, found bool, lk []byte) {\n\treturn lookup(p, c, fs.lookupTree)\n}", "func (r FunctionRegistry) Function(name string) (Function, error) {\n\tif len(r) == 0 {\n\t\treturn nil, ErrFunctionNotFound.New(name)\n\t}\n\n\tif fn, ok := r[name]; ok {\n\t\treturn fn, nil\n\t}\n\tsimilar := similartext.FindFromMap(r, name)\n\treturn nil, ErrFunctionNotFound.New(name + similar)\n}", "func (me *messageEvents) Called(ctx context.Context, check CheckFunc, msgHnd MsgHandler, rev RevertHandler, confidence int, timeout abi.ChainEpoch, mf MsgMatchFunc) error {\n\thnd := func(ctx context.Context, data eventData, prevTs, ts *types.TipSet, height abi.ChainEpoch) (bool, error) {\n\t\tmsg, ok := data.(*types.Message)\n\t\tif data != nil && !ok {\n\t\t\tpanic(\"expected msg\")\n\t\t}\n\n\t\tml, err := me.cs.StateSearchMsg(ctx, ts.Key(), msg.Cid(), stmgr.LookbackNoLimit, true)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif ml == nil {\n\t\t\treturn msgHnd(msg, nil, ts, height)\n\t\t}\n\n\t\treturn msgHnd(msg, &ml.Receipt, ts, height)\n\t}\n\n\tid, err := me.hcAPI.onHeadChanged(ctx, check, hnd, rev, confidence, timeout)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"on head changed error: %w\", err)\n\t}\n\n\tme.lk.Lock()\n\tdefer me.lk.Unlock()\n\tme.matchers[id] = mf\n\n\treturn nil\n}", "func (_f28 *FakeContext) StartSpanCalledWith(ident1 string, ident2 ...opentracing.StartSpanOption) (found bool) {\n\tfor _, call := range _f28.StartSpanCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Ident1, ident1) && reflect.DeepEqual(call.Parameters.Ident2, ident2) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (fi *FsCache) lookup(key *fs.FsFile) (*fs.FsData, bool) {\n\tfdata, ok := fi.dict[key.String()]\n\treturn fdata, ok\n}", "func FuncOf(fn func(this Value, args []Value) interface{}) Func {\n\tpanic(message)\n}", "func (hook *CallInfoHook) Fire(entry *logrus.Entry) error {\n\tfile, line, fn := GetStackInfo()\n\n\tif rel, err := filepath.Rel(filepath.Join(build.Default.GOPATH, \"/src\"), file); err == nil {\n\t\tfile = rel\n\t}\n\n\tentry.WithField(\"file\", file)\n\tentry.WithField(\"line\", line)\n\tentry.WithField(\"func\", fn)\n\n\treturn nil\n}", "func (s *BaseConcertoListener) EnterFuncCallArg(ctx *FuncCallArgContext) {}", "func (*InstSExt) isInst() {}", "func FireFunc(data FunctionData) bool {\n\tif fun, found := funcHandler.Load(data.FuncName); found {\n\t\tgo func() {\n\t\t\tfun.(func(data FunctionData))(data)\n\t\t}()\n\t\treturn true\n\t}\n\treturn false\n}", "func (vm *VM) opCall(instr []uint16, nextI int) int {\n\ta := vm.get(instr[0])\n\tvm.stack = append(vm.stack, uint16(nextI)+2)\n\t//fmt.Printf(\"stack after call: %v\\n\", vm.stack)\n\n\treturn int(a)\n}", "func (s Struct) Fn(fn string) Function {\n\treturn Function{s, make(map[string]interface{}), fn}\n}", "func (_f8 *FakeInterfacer) NamedInterfaceCalledWith(a interface{}) (found bool) {\n\tfor _, call := range _f8.NamedInterfaceCalls {\n\t\tif reflect.DeepEqual(call.Parameters.A, a) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (mock *Serf) IDCalled() bool {\n\tlockSerfID.RLock()\n\tdefer lockSerfID.RUnlock()\n\treturn len(mock.calls.ID) > 0\n}", "func (r *Resolver) ResolveFunc(module, field string) FunctionImport {\n\t//fmt.Printf(\"Resolve func: %s %s\\n\", module, field) // Log resolve\n\n\tswitch module { // Handle module types\n\tcase \"env\": // Env module\n\t\tswitch field { // Handle fields\n\t\tcase \"__ursa_ping\":\n\t\t\treturn func(vm *VirtualMachine) int64 {\n\t\t\t\treturn vm.GetCurrentFrame().Locals[0] + 1\n\t\t\t}\n\t\tcase \"__ursa_log\":\n\t\t\treturn func(vm *VirtualMachine) int64 {\n\t\t\t\tptr := int(uint32(vm.GetCurrentFrame().Locals[0]))\n\t\t\t\tmsgLen := int(uint32(vm.GetCurrentFrame().Locals[1]))\n\t\t\t\tmsg := vm.Memory[ptr : ptr+msgLen]\n\t\t\t\tfmt.Printf(\"[app] %s\\n\", string(msg))\n\t\t\t\treturn 0\n\t\t\t}\n\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"unknown field: %s\", field)) // Panic\n\t\t}\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown module: %s\", module)) // Panic\n\t}\n}", "func (_mr *MockDraOpMockRecorder) LookupFileById(arg0 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"LookupFileById\", reflect.TypeOf((*MockDraOp)(nil).LookupFileById), arg0)\n}", "func (s *BaseConcertoListener) EnterFuncCallSpec(ctx *FuncCallSpecContext) {}", "func IsCalled(v *govulncheck.Vuln) bool {\n\tfor _, m := range v.Modules {\n\t\tfor _, p := range m.Packages {\n\t\t\tif len(p.CallStacks) > 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func FuncIn() {\n\tsimlog.FuncIn()\n}", "func FuncOf(fn func(this Value, args []Value) interface{}) Func {\n\tfuncsMu.Lock()\n\tid := nextFuncID\n\tnextFuncID++\n\tfuncs[id] = fn\n\tfuncsMu.Unlock()\n\treturn Func{\n\t\tid: id,\n\t\tValue: jsGo.Call(\"_makeFuncWrapper\", id),\n\t}\n}", "func walkCall(n *ir.CallExpr, init *ir.Nodes) ir.Node {\n\tif n.Op() == ir.OCALLMETH {\n\t\tbase.FatalfAt(n.Pos(), \"OCALLMETH missed by typecheck\")\n\t}\n\tif n.Op() == ir.OCALLINTER || n.X.Op() == ir.OMETHEXPR {\n\t\t// We expect both interface call reflect.Type.Method and concrete\n\t\t// call reflect.(*rtype).Method.\n\t\tusemethod(n)\n\t}\n\tif n.Op() == ir.OCALLINTER {\n\t\treflectdata.MarkUsedIfaceMethod(n)\n\t}\n\n\tif n.Op() == ir.OCALLFUNC && n.X.Op() == ir.OCLOSURE {\n\t\tdirectClosureCall(n)\n\t}\n\n\tif isFuncPCIntrinsic(n) {\n\t\t// For internal/abi.FuncPCABIxxx(fn), if fn is a defined function, rewrite\n\t\t// it to the address of the function of the ABI fn is defined.\n\t\tname := n.X.(*ir.Name).Sym().Name\n\t\targ := n.Args[0]\n\t\tvar wantABI obj.ABI\n\t\tswitch name {\n\t\tcase \"FuncPCABI0\":\n\t\t\twantABI = obj.ABI0\n\t\tcase \"FuncPCABIInternal\":\n\t\t\twantABI = obj.ABIInternal\n\t\t}\n\t\tif isIfaceOfFunc(arg) {\n\t\t\tfn := arg.(*ir.ConvExpr).X.(*ir.Name)\n\t\t\tabi := fn.Func.ABI\n\t\t\tif abi != wantABI {\n\t\t\t\tbase.ErrorfAt(n.Pos(), \"internal/abi.%s expects an %v function, %s is defined as %v\", name, wantABI, fn.Sym().Name, abi)\n\t\t\t}\n\t\t\tvar e ir.Node = ir.NewLinksymExpr(n.Pos(), fn.Sym().LinksymABI(abi), types.Types[types.TUINTPTR])\n\t\t\te = ir.NewAddrExpr(n.Pos(), e)\n\t\t\te.SetType(types.Types[types.TUINTPTR].PtrTo())\n\t\t\te = ir.NewConvExpr(n.Pos(), ir.OCONVNOP, n.Type(), e)\n\t\t\treturn e\n\t\t}\n\t\t// fn is not a defined function. It must be ABIInternal.\n\t\t// Read the address from func value, i.e. *(*uintptr)(idata(fn)).\n\t\tif wantABI != obj.ABIInternal {\n\t\t\tbase.ErrorfAt(n.Pos(), \"internal/abi.%s does not accept func expression, which is ABIInternal\", name)\n\t\t}\n\t\targ = walkExpr(arg, init)\n\t\tvar e ir.Node = ir.NewUnaryExpr(n.Pos(), ir.OIDATA, arg)\n\t\te.SetType(n.Type().PtrTo())\n\t\te = ir.NewStarExpr(n.Pos(), e)\n\t\te.SetType(n.Type())\n\t\treturn e\n\t}\n\n\twalkCall1(n, init)\n\treturn n\n}", "func (r *Resolver) lookupFunc(key string) func() (interface{}, error) {\n\tif len(key) == 0 {\n\t\tpanic(\"lookupFunc with empty key\")\n\t}\n\tresolver := net.DefaultResolver\n\tif r.Resolver != nil {\n\t\tresolver = r.Resolver\n\t}\n\tswitch key[0] {\n\tcase 'h':\n\t\treturn func() (interface{}, error) {\n\t\t\tctx, cancel := r.getCtx()\n\t\t\tdefer cancel()\n\t\t\treturn resolver.LookupHost(ctx, key[1:])\n\t\t}\n\tcase 'r':\n\t\treturn func() (interface{}, error) {\n\t\t\tctx, cancel := r.getCtx()\n\t\t\tdefer cancel()\n\t\t\treturn resolver.LookupAddr(ctx, key[1:])\n\t\t}\n\tcase 'm':\n\t\treturn func() (interface{}, error) {\n\t\t\tctx, cancel := r.getCtx()\n\t\t\tdefer cancel()\n\t\t\treturn resolver.LookupMX(ctx, key[1:])\n\t\t}\n\tdefault:\n\t\tpanic(\"lookupFunc invalid key type: \" + key)\n\t}\n}", "func (*InstZExt) isInst() {}", "func FindFunctionLocation(p Process, funcName string, lineOffset int) ([]uint64, error) {\n\tbi := p.BinInfo()\n\torigfns, err := bi.FindFunction(funcName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif lineOffset > 0 {\n\t\tfn := origfns[0]\n\t\tfilename, lineno := bi.EntryLineForFunc(fn)\n\t\treturn FindFileLocation(p, filename, lineno+lineOffset)\n\t}\n\n\tr := make([]uint64, 0, len(origfns[0].InlinedCalls)+len(origfns))\n\n\tfor _, origfn := range origfns {\n\t\tif origfn.Entry > 0 {\n\t\t\t// add concrete implementation of the function\n\t\t\tpc, err := FirstPCAfterPrologue(p, origfn, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tr = append(r, pc)\n\t\t}\n\t\t// add inlined calls to the function\n\t\tfor _, call := range origfn.InlinedCalls {\n\t\t\tr = append(r, call.LowPC)\n\t\t}\n\t\tif len(r) == 0 {\n\t\t\treturn nil, &ErrFunctionNotFound{funcName}\n\t\t}\n\t}\n\tsort.Slice(r, func(i, j int) bool { return r[i] < r[j] })\n\treturn r, nil\n}", "func (_f68 *FakeContext) WithSpanCalledWith(ident1 opentracing.Span) (found bool) {\n\tfor _, call := range _f68.WithSpanCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Ident1, ident1) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func Trace(info string) {\n\tpc := make([]uintptr, 1)\n\n\t// get call stack, ommitting 2 elements on stack, which is runtime.Callers and Trace2, respectively\n\truntime.Callers(2 , pc)\n\tf := runtime.FuncForPC(pc[0])\n\t// get the file and line number of the instruction immediately following the call\n\tfile, line := f.FileLine(pc[0])\n\n\tif len(info) == 0 {\n\t\tlogrus.Debugf(\"Lele: %s:%d; funcName: '%s'\", file, line, f.Name())\n\t}else{\n\t\tlogrus.Debugf(\"Lele: %s, %s:%d; funcName: '%s'\", info, file, line, f.Name())\n\t}\n\n}", "func GetCaller(offset int) (file string, line int) {\n\tfpcs := make([]uintptr, 1)\n\n\tn := runtime.Callers(offset, fpcs)\n\tif n == 0 {\n\t\treturn \"n/a\", -1\n\t}\n\n\tfun := runtime.FuncForPC(fpcs[0] - 1)\n\tif fun == nil {\n\t\treturn \"n/a\", -1\n\t}\n\n\treturn fun.FileLine(fpcs[0] - 1)\n}", "func (state *State) IsFunc(index int) bool { return state.TypeAt(index) == FuncType }", "func (e *Event) Lookup(name string) (arg uint64, found bool) {\n\tfor idx, v := range schemas[e.Type%EvCount].Args {\n\t\tif idx > len(e.Args) {\n\t\t\treturn\n\t\t}\n\t\tif v == name {\n\t\t\treturn e.Args[idx], true\n\t\t}\n\t}\n\treturn\n}", "func fn(labels ...string) string {\n\tfunction, _, _, _ := runtime.Caller(1)\n\n\tlongname := runtime.FuncForPC(function).Name()\n\n\tnameparts := strings.Split(longname, \".\")\n\tshortname := nameparts[len(nameparts)-1]\n\n\tif labels == nil {\n\t\treturn fmt.Sprintf(\"[%s()]\", shortname)\n\t}\n\n\treturn fmt.Sprintf(\"[%s():%s]\", shortname, strings.Join(labels, \":\"))\n}", "func (f *FakeResolver) ResolveCalledN(n int) bool {\n\treturn len(f.ResolveCalls) >= n\n}", "func (m Matcher) Fn() MatchFn {\n\tswitch m.matchType {\n\tcase PathEqual:\n\t\treturn m.matchPathFn(func(s, t string) bool { return s == t })\n\tcase PathContains:\n\t\treturn m.matchPathFn(strings.Contains)\n\tcase PathPrefix:\n\t\treturn m.matchPathFn(strings.HasPrefix)\n\tcase ExecutableEqual:\n\t\treturn m.matchExecutableFn(func(s, t string) bool { return s == t })\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (cb callBacker) mustCall(fn_name string) error {\n\treturn cb.Scripter.EraCall(fn_name)\n}", "func lookupFail(c *C, dnsNames []string) (DNSIPs map[string]*DNSIPRecords, errorDNSNames map[string]error) {\n\tc.Error(\"Lookup function called when it should not\")\n\treturn nil, nil\n}", "func seen(p *profile.Profile, fname string) bool {\n\tlocIDs := map[*profile.Location]bool{}\n\tfor _, loc := range p.Location {\n\t\tfor _, l := range loc.Line {\n\t\t\tif strings.Contains(l.Function.Name, fname) {\n\t\t\t\tlocIDs[loc] = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tfor _, sample := range p.Sample {\n\t\tfor _, loc := range sample.Location {\n\t\t\tif locIDs[loc] {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (*InstPtrToInt) isInst() {}", "func (s *service) lookupExecutable(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\texists, err := s.store.ExecutableExists(p.ByName(\"hash\"))\n\tif err != nil {\n\t\ts.logger.Warn(\"looking up executable\", \"hash\", p.ByName(\"hash\"), \"err\", err)\n\t\twriteError(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tif !exists {\n\t\twriteError(w, http.StatusNotFound, errors.New(`not found`))\n\t\treturn\n\t}\n\n\twrite(w, http.StatusOK, map[string]interface{}{\"found\": true})\n}", "func execLookupFieldOrMethod(_ int, p *gop.Context) {\n\targs := p.GetArgs(4)\n\tret, ret1, ret2 := types.LookupFieldOrMethod(args[0].(types.Type), args[1].(bool), args[2].(*types.Package), args[3].(string))\n\tp.Ret(4, ret, ret1, ret2)\n}", "func (*InstSIToFP) isInst() {}", "func (f funcTab) funcOff(i int) uint64 {\n\treturn f.uint(f.functab[(2*i+1)*f.sz:])\n}", "func (*InstIntToPtr) isInst() {}", "func fn1() {}", "func InjectDebugCall(gp *g, fn any, regArgs *abi.RegArgs, stackArgs any, tkill func(tid int) error, returnOnUnsafePoint bool) (any, error) {\n\tif gp.lockedm == 0 {\n\t\treturn nil, plainError(\"goroutine not locked to thread\")\n\t}\n\n\ttid := int(gp.lockedm.ptr().procid)\n\tif tid == 0 {\n\t\treturn nil, plainError(\"missing tid\")\n\t}\n\n\tf := efaceOf(&fn)\n\tif f._type == nil || f._type.kind&kindMask != kindFunc {\n\t\treturn nil, plainError(\"fn must be a function\")\n\t}\n\tfv := (*funcval)(f.data)\n\n\ta := efaceOf(&stackArgs)\n\tif a._type != nil && a._type.kind&kindMask != kindPtr {\n\t\treturn nil, plainError(\"args must be a pointer or nil\")\n\t}\n\targp := a.data\n\tvar argSize uintptr\n\tif argp != nil {\n\t\targSize = (*ptrtype)(unsafe.Pointer(a._type)).elem.size\n\t}\n\n\th := new(debugCallHandler)\n\th.gp = gp\n\t// gp may not be running right now, but we can still get the M\n\t// it will run on since it's locked.\n\th.mp = gp.lockedm.ptr()\n\th.fv, h.regArgs, h.argp, h.argSize = fv, regArgs, argp, argSize\n\th.handleF = h.handle // Avoid allocating closure during signal\n\n\tdefer func() { testSigtrap = nil }()\n\tfor i := 0; ; i++ {\n\t\ttestSigtrap = h.inject\n\t\tnoteclear(&h.done)\n\t\th.err = \"\"\n\n\t\tif err := tkill(tid); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Wait for completion.\n\t\tnotetsleepg(&h.done, -1)\n\t\tif h.err != \"\" {\n\t\t\tswitch h.err {\n\t\t\tcase \"call not at safe point\":\n\t\t\t\tif returnOnUnsafePoint {\n\t\t\t\t\t// This is for TestDebugCallUnsafePoint.\n\t\t\t\t\treturn nil, h.err\n\t\t\t\t}\n\t\t\t\tfallthrough\n\t\t\tcase \"retry _Grunnable\", \"executing on Go runtime stack\", \"call from within the Go runtime\":\n\t\t\t\t// These are transient states. Try to get out of them.\n\t\t\t\tif i < 100 {\n\t\t\t\t\tusleep(100)\n\t\t\t\t\tGosched()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, h.err\n\t\t}\n\t\treturn h.panic, nil\n\t}\n}", "func (h CallerHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {\n var file, line, function string\n if pc, filePath, lineNum, ok := runtime.Caller(CallerSkipFrameCount); ok {\n if f := runtime.FuncForPC(pc); f != nil {\n function = f.Name()\n }\n line = fmt.Sprintf(\"%d\", lineNum)\n parts := strings.Split(filePath, \"/\")\n file = parts[len(parts)-1]\n }\n e.Dict(\"logging.googleapis.com/sourceLocation\",\n zerolog.Dict().Str(\"file\", file).Str(\"line\", line).Str(\"function\", function))\n}", "func FuncOf(ctx context.Context, e Expr, vs Values) (Func, error) {\r\n\tfc, ok := ctxutil.Value(ctx, (*funcCache)(nil)).(*funcCache)\r\n\tvar fk funcKey\r\n\tif ok {\r\n\t\tfk = makeFuncKey(ctx, e, vs)\r\n\t\tif fn, ok := fc.load(fk); ok {\r\n\t\t\treturn fn, nil\r\n\t\t}\r\n\t}\r\n\tfn, err := funcFromExpr(ctx, e, vs)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tif ok {\r\n\t\tfn, _ = fc.loadOrStore(fk, fn)\r\n\t}\r\n\treturn fn, nil\r\n}", "func (_mr *MockDraOpMockRecorder) LookupRefById(arg0 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"LookupRefById\", reflect.TypeOf((*MockDraOp)(nil).LookupRefById), arg0)\n}", "func (_f6 *FakelogicalReader) ReadCalledWith(path string) (found bool) {\n\tfor _, call := range _f6.ReadCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Path, path) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (_f2 *FakeQualifier) QualifyCalledWith(ident1 fmt.Scanner) (found bool) {\n\tfor _, call := range _f2.QualifyCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Ident1, ident1) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func EvalCall(a, b Attrib) (*AddrCode, error) {\n\tentry_ := a.(*AddrCode).Symbol\n\tentry, ok := entry_.(*codegen.TargetEntry)\n\tvar varEntry *codegen.VariableEntry\n\tif !ok {\n\t\tif variable, ok1 := entry_.(*codegen.VariableEntry); ok1 {\n\t\t\tif t, ok2 := variable.Type().(codegen.FuncType); ok2 {\n\t\t\t\tentry = t.Target\n\t\t\t\tvarEntry = variable\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid function call statement\")\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"invalid function call statement\")\n\t\t}\n\t}\n\texprList, ok := b.([]*AddrCode)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unable to type cast %v to []*AddrCode\", b)\n\t}\n\n\tvar isSystem bool\n\n\tif entry.Target == \"printf\" || entry.Target == \"scanf\" {\n\t\tisSystem = true\n\t}\n\n\tif !isSystem && len(exprList) != len(entry.InType) {\n\t\treturn nil, fmt.Errorf(\"wrong number of arguments in function call. expected %d, got %d\", len(entry.InType), len(exprList))\n\t}\n\tcode := a.(*AddrCode).Code\n\tfor i := len(exprList) - 1; i >= 0; i-- {\n\t\tif !isSystem && !SameType(exprList[i].Symbol.Type(), entry.InType[i]) {\n\t\t\treturn nil, fmt.Errorf(\"wrong type of argument %d in function call. expected %v, got %v\", i, entry.InType[i], exprList[i].Symbol.Type())\n\t\t}\n\t\tif isSystem && i == 0 {\n\t\t\tif !SameType(exprList[i].Symbol.Type(), stringType) {\n\t\t\t\treturn nil, fmt.Errorf(\"wrong type of 1st argument in function call. expected %v, got %v\", stringType, exprList[i].Symbol.Type())\n\t\t\t}\n\t\t}\n\t\tevaluatedExpr := EvalWrapped(exprList[i])\n\t\tcode = append(code, evaluatedExpr.Code...)\n\t\tcode = append(code, codegen.IRIns{\n\t\t\tTyp: codegen.KEY,\n\t\t\tOp: codegen.PARAM,\n\t\t\tArg1: evaluatedExpr.Symbol,\n\t\t})\n\t}\n\tif varEntry == nil {\n\t\tcode = append(code, codegen.IRIns{\n\t\t\tTyp: codegen.KEY,\n\t\t\tOp: codegen.CALL,\n\t\t\tArg1: entry,\n\t\t})\n\t} else {\n\t\tcode = append(code, codegen.IRIns{\n\t\t\tTyp: codegen.KEY,\n\t\t\tOp: codegen.CALL,\n\t\t\tArg1: varEntry,\n\t\t})\n\t}\n\t// code = append(code, codegen.IRIns{\n\t// \tTyp: codegen.KEY,\n\t// \tOp: codegen.UNALLOC,\n\t// \tArg1: &codegen.LiteralEntry{\n\t// \t\tValue: len(exprList) * 4,\n\t// \t\tLType: intType,\n\t// \t},\n\t// })\n\tentry1 := CreateTemporary(entry.RetType)\n\tcode = append(code, entry1.Code...)\n\tcode = append(code, codegen.IRIns{\n\t\tTyp: codegen.KEY,\n\t\tOp: codegen.SETRET,\n\t\tArg1: entry1.Symbol,\n\t})\n\treturn &AddrCode{\n\t\tCode: code,\n\t\tSymbol: entry1.Symbol,\n\t}, nil\n}", "func (ast *Call) Eval(env *Env, ctx *Codegen, gen *ssa.Generator) (\n\tssa.Value, bool, error) {\n\n\t// Resolve called.\n\tvar pkgName string\n\tif len(ast.Ref.Name.Package) > 0 {\n\t\tpkgName = ast.Ref.Name.Package\n\t} else {\n\t\tpkgName = ast.Ref.Name.Defined\n\t}\n\tpkg, ok := ctx.Packages[pkgName]\n\tif !ok {\n\t\treturn ssa.Undefined, false,\n\t\t\tctx.Errorf(ast, \"package '%s' not found\", pkgName)\n\t}\n\t_, ok = pkg.Functions[ast.Ref.Name.Name]\n\tif ok {\n\t\treturn ssa.Undefined, false, nil\n\t}\n\t// Check builtin functions.\n\tfor _, bi := range builtins {\n\t\tif bi.Name != ast.Ref.Name.Name {\n\t\t\tcontinue\n\t\t}\n\t\tif bi.Type != BuiltinFunc {\n\t\t\treturn ssa.Undefined, false,\n\t\t\t\tfmt.Errorf(\"builtin %s used as function\", bi.Name)\n\t\t}\n\t\tif bi.Eval == nil {\n\t\t\treturn ssa.Undefined, false, nil\n\t\t}\n\t\treturn bi.Eval(ast.Exprs, env, ctx, gen, ast.Location())\n\t}\n\n\treturn ssa.Undefined, false, nil\n}", "func _caller(n int) string {\n\tif pc, _, _, ok := runtime.Caller(n); ok {\n\t\tfns := strings.Split(runtime.FuncForPC(pc).Name(), \"/\")\n\t\treturn fns[len(fns)-1]\n\t}\n\n\treturn \"unknown\"\n}", "func (*FuncExpr) iCallable() {}", "func (f EventHandlerFunc) Call(ctx context.Context, jobId string) error {\n\treturn f(ctx, jobId)\n}", "func this() *runtime.Func {\n pc := make([]uintptr, 10) // at least 1 entry needed\n runtime.Callers(2, pc)\n f:= runtime.FuncForPC(pc[1])\n return f\n}", "func (_f58 *FakeContext) WithRequestIDCalledWith(ident1 string) (found bool) {\n\tfor _, call := range _f58.WithRequestIDCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Ident1, ident1) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (_ArbSys *ArbSysCaller) AddressTableLookup(opts *bind.CallOpts, addr common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ArbSys.contract.Call(opts, &out, \"addressTable_lookup\", addr)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (mr *MockFullNodeMockRecorder) StateLookupID(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"StateLookupID\", reflect.TypeOf((*MockFullNode)(nil).StateLookupID), arg0, arg1, arg2)\n}", "func Lookup(code cid.Cid) (ActorInfo, bool) {\n\tact, ok := actorInfos[code]\n\treturn act, ok\n}", "func funcHasIP(ctx context.Context, out io.Writer, args []string) error {\n\tif len(args) != 1 {\n\t\treturn errors.New(\"usage: act has-ip [IP1] [IP2]... \")\n\t}\n\treturn executor.RunExecutorConfigReadOnly(ctx, func(executor executor.Executor) error {\n\t\tif err := executor.Runner.HasIP(out, args); err != nil {\n\t\t\tlogrus.Errorf(err.Error())\n\t\t}\n\t\treturn nil\n\t})\n}" ]
[ "0.55088776", "0.51450753", "0.5084626", "0.49590853", "0.49253467", "0.49151275", "0.49031597", "0.48806983", "0.48682708", "0.4830155", "0.48227826", "0.47652534", "0.47241217", "0.46917644", "0.4687812", "0.46794826", "0.46600193", "0.46538463", "0.4650809", "0.46494117", "0.46383056", "0.4636756", "0.46328318", "0.46300247", "0.46284673", "0.46276116", "0.4615816", "0.46115842", "0.46102592", "0.460791", "0.46028826", "0.45844704", "0.4571431", "0.4570194", "0.4517809", "0.45079294", "0.4503673", "0.4482793", "0.44807994", "0.44749445", "0.44696933", "0.44696933", "0.44656765", "0.4459201", "0.44465247", "0.44461298", "0.44372997", "0.4432157", "0.44203812", "0.44153333", "0.44046074", "0.44032925", "0.43953833", "0.4380883", "0.43755051", "0.4374393", "0.437411", "0.4363866", "0.43601498", "0.43555757", "0.4350508", "0.4336466", "0.43353626", "0.43329236", "0.43047968", "0.42990345", "0.42983863", "0.42951363", "0.42946437", "0.42926756", "0.4291027", "0.42868116", "0.42855924", "0.4285253", "0.42844692", "0.4277797", "0.4271881", "0.42712307", "0.42664817", "0.4253215", "0.42495072", "0.4245601", "0.42433628", "0.42422584", "0.42356083", "0.42322177", "0.42321402", "0.42276013", "0.4225643", "0.4225523", "0.42242858", "0.42200407", "0.42143106", "0.42129484", "0.42105737", "0.42098084", "0.42041355", "0.42040923", "0.42015338", "0.4200038" ]
0.8261184
0
HasArgs returns whether the given ssa.Instruction has `typ` type args
func HasArgs(instr ssa.Instruction, typ types.Type) bool { call, ok := instr.(ssa.CallInstruction) if !ok { return false } ssaCall := call.Value() if ssaCall == nil { return false } for _, arg := range ssaCall.Call.Args { if types.Identical(arg.Type(), typ) { return true } } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i Instruction) IsVariadic() bool {\n\treturn len(i.Arities()) > 1\n}", "func (TypesObject) IsVariadicParam() bool { return boolResult }", "func (f flagString) HasArg() bool {\n\treturn true\n}", "func (a *Args) Has(arg rune) bool {\n\t_, ok := a.marhalers[arg]\n\treturn ok\n}", "func (f flagBool) HasArg() bool {\n\treturn false\n}", "func isTypeParam(_ *ast.Field, _ []*ast.FuncDecl, _ []*ast.FuncLit) bool {\n\treturn false\n}", "func (p *FuncInfo) IsVariadic() bool {\n\tif p.nVariadic == 0 {\n\t\tlog.Panicln(\"FuncInfo is unintialized.\")\n\t}\n\treturn p.nVariadic == nVariadicVariadicArgs\n}", "func (t *Type) IsFuncArgStruct() bool", "func (*InstTrunc) isInst() {}", "func hasContextParam(handlerType reflect.Type) bool {\n\t//if the handler doesn't take arguments, false\n\tif handlerType.NumIn() == 0 {\n\t\treturn false\n\t}\n\n\t//if the first argument is not a pointer, false\n\tp1 := handlerType.In(0)\n\tif p1.Kind() != reflect.Ptr {\n\t\treturn false\n\t}\n\t//but if the first argument is a context, true\n\tif p1.Elem() == contextType {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (*InstFPTrunc) isInst() {}", "func (t Type) HasAttr(name string) bool {\n\treturn t.AttrType(name) != NilType\n}", "func (m *Method) HasParameters() bool {\n\treturn len(m.Parameters) != 0\n}", "func (*InstZExt) isInst() {}", "func HasFlag(args []string, flag string) bool {\n\tfor _, item := range args {\n\t\tif item == flag {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func IsHasMethod(st interface{}, methodName string) bool {\n\treturn HasMethod(st, methodName)\n}", "func isOperandOfLen(i interface{}, length int) bool {\n\toperand, ok := i.(Operand)\n\treturn ok && len(operand) == length\n}", "func (n Name) HasType() bool {\n\t_, s := n.GetLookupAndType()\n\treturn s != \"\"\n}", "func isVariadicArgument(value string) (bool, string) {\n\tif !isFlag(value) && strings.HasSuffix(value, \"...\") {\n\t\treturn true, strings.TrimRight(value, \"...\") // trim `...` suffix\n\t}\n\n\treturn false, \"\"\n}", "func typeIs(target string, src interface{}) bool {\n\treturn target == typeOf(src)\n}", "func Argsize(t *Type) int", "func analysisArgs() bool {\n\t//没有选项的情况显示帮助信息\n\tif len(os.Args) <= 1 {\n\t\tfor _, v := range gCommandItems {\n\t\t\tlog(v.mBuilder.getCommandDesc())\n\t\t}\n\t\treturn false\n\t}\n\n\t//解析指令\n\targs := os.Args[1:]\n\tvar pItem *sCommandItem = nil\n\tfor i := 0; i < len(args); i++ {\n\t\tparm := args[i]\n\t\tif parm[0] == '-' {\n\t\t\tpItem = findCommandItem(parm)\n\t\t\tif pItem == nil {\n\t\t\t\tlogErr(\"illegal command:\" + parm)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpItem.mCanExecute = true\n\t\t} else {\n\t\t\tif pItem == nil {\n\t\t\t\tlogErr(\"illegal command:\" + parm)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpItem.mParm = append(pItem.mParm, parm)\n\t\t}\n\t}\n\n\treturn true\n}", "func hasName(t Type) bool {\n\tswitch t.(type) {\n\tcase *Basic, *Named, *TypeParam:\n\t\treturn true\n\t}\n\treturn false\n}", "func (a *Args) IsOn(s string) bool {\n\tfor _, u := range a.uniOpts {\n\t\tif u == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (*InstFPExt) isInst() {}", "func attrsContain(attrs []netlink.Attribute, typ uint16) bool {\n\tfor _, a := range attrs {\n\t\tif a.Type == typ {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func CountArgs(args MyType) int {\n\treturn len(args)\n}", "func check_args(parsed_query []string, num_expected int) bool {\n\treturn (len(parsed_query) >= num_expected)\n}", "func (t Type) IsUnary() bool {\n\treturn unop_start < t && t < unop_end\n}", "func hasUpdateArg(args []string) bool {\n\tfor _, arg := range args {\n\t\tif ArgWorkflowUpdate == arg {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *WorkflowCliCommandAllOf) HasType() bool {\n\tif o != nil && o.Type != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p RProc) IsNoArg() bool { return (C._mrb_rproc_flags(p.p) & C.MRB_PROC_NOARG) != 0 }", "func IsCommandLineArguments(id PackageID) bool {\n\treturn strings.Contains(string(id), \"command-line-arguments\")\n}", "func (*InstSExt) isInst() {}", "func (t Type) Is(ty Type) bool {\n\treturn t&ty != 0\n}", "func (l Lambda) IsThunk() bool {\n\treturn len(l.arguments) == 0\n}", "func (s *Instruction) IsInstType(instructionType InstType) bool {\n\treturn instructionType == s.Type\n}", "func (p Typed) IsCommand() bool {\n\treturn p.Kind() == TypeIDKindCommand\n}", "func IsHasMethod(v interface{}, methodName string) bool {\n\treturn String(methodName).IsInArrayIgnoreCase(GetMethods(v))\n}", "func IsType(v interface{}, params ...string) bool {\n\tif len(params) == 1 {\n\t\ttyp := params[0]\n\t\treturn strings.Replace(reflect.TypeOf(v).String(), \" \", \"\", -1) == strings.Replace(typ, \" \", \"\", -1)\n\t}\n\treturn false\n}", "func (runner *suiteRunner) checkFixtureArgs() bool {\n succeeded := true\n argType := reflect.Typeof(&C{})\n for _, fv := range []*reflect.FuncValue{runner.setUpSuite,\n runner.tearDownSuite,\n runner.setUpTest,\n runner.tearDownTest} {\n if fv != nil {\n fvType := fv.Type().(*reflect.FuncType)\n if fvType.In(1) != argType || fvType.NumIn() != 2 {\n succeeded = false\n runner.runFunc(fv, fixtureKd, func(c *C) {\n c.logArgPanic(fv, \"*gocheck.C\")\n c.status = panickedSt\n })\n }\n }\n }\n return succeeded\n}", "func hasRendererParam(handlerType reflect.Type) bool {\n\t//if the handler doesn't take arguments, false\n\tif handlerType.NumIn() == 0 {\n\t\treturn false\n\t}\n\n\t//if the first argument is not a pointer, false\n\tp1 := handlerType.In(0)\n\tif p1.Kind() != reflect.Ptr {\n\t\treturn false\n\t}\n\t//but if the first argument is a renderer, true\n\tif p1.Elem() == rendererType {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (typ Type) HasAny(t Type) bool { return typ&t != 0 }", "func HasMethod(st interface{}, methodName string) bool {\n\tvalueIface := reflect.ValueOf(st)\n\n\t// Check if the passed interface is a pointer\n\tif valueIface.Type().Kind() != reflect.Ptr {\n\t\t// Create a new type of Iface, so we have a pointer to work with\n\t\tvalueIface = reflect.New(reflect.TypeOf(st))\n\t}\n\n\t// Get the method by name\n\tmethod := valueIface.MethodByName(methodName)\n\treturn method.IsValid()\n}", "func doAnyParametersExist(args ...string) bool {\n\tif args == nil {\n\t\treturn false\n\t}\n\tfor _, arg := range args {\n\t\tif arg != \"\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func isTypeParam(t Type) bool {\n\t_, ok := t.(*TypeParam)\n\treturn ok\n}", "func (*InstAddrSpaceCast) isInst() {}", "func (args MyType) CountArgs() int {\n\treturn len(args)\n}", "func IsComplete(t Type) bool {\n\tswitch v := t.Root().(type) {\n\tcase *Variable:\n\t\treturn false\n\tcase *Operator:\n\t\tfor _, a := range v.Args {\n\t\t\tif !IsComplete(a) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}", "func suitable(m reflect.Method) bool {\n\treturn m.Type.NumIn() <= 2\n}", "func (*InstBitCast) isInst() {}", "func (x *fastReflection_PositionalArgDescriptor) Has(fd protoreflect.FieldDescriptor) bool {\n\tswitch fd.FullName() {\n\tcase \"cosmos.autocli.v1.PositionalArgDescriptor.proto_field\":\n\t\treturn x.ProtoField != \"\"\n\tcase \"cosmos.autocli.v1.PositionalArgDescriptor.varargs\":\n\t\treturn x.Varargs != false\n\tcase \"cosmos.autocli.v1.PositionalArgDescriptor.optional\":\n\t\treturn x.Optional != false\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.autocli.v1.PositionalArgDescriptor\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.autocli.v1.PositionalArgDescriptor does not contain field %s\", fd.FullName()))\n\t}\n}", "func (a *Args) HasOpt(key string) bool {\n\tfor _, b := range a.binOpts {\n\t\tif b.key == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *DeviceParameterValue) HasType() bool {\n\tif o != nil && o.Type != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsValidArgsLength(args []string, n int) bool {\n\tif args == nil && n == 0 {\n\t\treturn true\n\t}\n\tif args == nil {\n\t\treturn false\n\t}\n\n\tif n < 0 {\n\t\treturn false\n\t}\n\n\targsNr := len(args)\n\tif argsNr < n || argsNr > n {\n\t\treturn false\n\t}\n\treturn true\n}", "func (v *Argument) IsSetType() bool {\n\treturn v != nil && v.Type != nil\n}", "func isTyped(t Type) bool {\n\t// isTyped is called with types that are not fully\n\t// set up. Must not call under()!\n\tb, _ := t.(*Basic)\n\treturn b == nil || b.info&IsUntyped == 0\n}", "func isNoCopyType(typ types.Type) bool {\n\tst, ok := typ.Underlying().(*types.Struct)\n\tif !ok {\n\t\treturn false\n\t}\n\tif st.NumFields() != 0 {\n\t\treturn false\n\t}\n\n\tnamed, ok := typ.(*types.Named)\n\tif !ok {\n\t\treturn false\n\t}\n\tif named.NumMethods() != 1 {\n\t\treturn false\n\t}\n\tmeth := named.Method(0)\n\tif meth.Name() != \"Lock\" {\n\t\treturn false\n\t}\n\tsig := meth.Type().(*types.Signature)\n\tif sig.Params().Len() != 0 || sig.Results().Len() != 0 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (t *Transaction) HasAttribute(typ AttrType) bool {\n\tfor i := range t.Attributes {\n\t\tif t.Attributes[i].Type == typ {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (calls Calls) Has(method string, args ...interface{}) bool {\n\twant := call{method, args}\n\tfor _, have := range calls {\n\t\tif reflect.DeepEqual(want, have) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func CanConvertArgs(args []DataType, params []FunctionParameter) bool {\n\n\tif len(args) != len(params) {\n\t\treturn false\n\t}\n\n\tfor i, param := range params {\n\t\targ := args[i]\n\n\t\tif param.AutoConvert {\n\t\t\tif !CanConvert(arg, param.DType) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\tif !TypeMatches(arg, param.DType) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func CommandArgExists(mapArr map[string]string, key string) bool {\n\tif _, ok := mapArr[key]; ok {\n\t\treturn true\n\t}\n\treturn false\n}", "func (typ Type) HasAll(t Type) bool { return typ&t == t }", "func HasVectorExpansions(t BareType) bool { return vectorTypes[t] != nil }", "func execIsInterface(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := types.IsInterface(args[0].(types.Type))\n\tp.Ret(1, ret)\n}", "func (*InstFPToUI) isInst() {}", "func (args *Args) isEmpty() bool {\n\treturn len(args.items) == 0\n}", "func IsUint(data interface{}) bool {\n\treturn typeIs(data,\n\t\treflect.Uint,\n\t\treflect.Uint8,\n\t\treflect.Uint16,\n\t\treflect.Uint32,\n\t\treflect.Uint64,\n\t\treflect.Uintptr,\n\t)\n}", "func (o Op) Variadic() bool {\n\treturn o == In || o == NotIn\n}", "func (SinkType) Is(typ string) bool { return boolResult }", "func (ExprType) HasMethod(fn string) bool { return boolResult }", "func (d Definition) IsValid(args ...interface{}) bool {\n\tif d.Inputs == nil {\n\t\treturn true\n\t}\n\tif len(args) != len(d.Inputs) {\n\t\treturn false\n\t}\n\tfor i, a := range args {\n\t\tswitch x := d.Inputs[i].(type) {\n\t\tcase reflect.Type:\n\t\t\txv := reflect.ValueOf(x)\n\t\t\tav := reflect.ValueOf(a)\n\t\t\tif !xv.IsNil() {\n\t\t\t\tif !av.IsValid() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif ak := reflect.TypeOf(a).Kind(); (ak == reflect.Chan || ak == reflect.Func || ak == reflect.Map || ak == reflect.Ptr || ak == reflect.Slice) && av.IsNil() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif !av.Type().AssignableTo(x) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\tcase reflect.Kind:\n\t\t\txv := reflect.ValueOf(x)\n\t\t\tav := reflect.ValueOf(a)\n\t\t\tif xv.IsValid() || !xv.IsNil() {\n\t\t\t\tif !av.IsValid() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif xv.IsValid() && av.Type().Kind() != x {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func (x *fastReflection_PositionalArgDescriptor) IsValid() bool {\n\treturn x != nil\n}", "func IsBuiltin(t Type) bool {\n\tname, ok := t.(TName)\n\treturn ok && IsBuiltinTypeString(name.TypeName)\n}", "func (i KeyInfo) IsType(typeName string) bool {\n\tfor _, t := range i.Types {\n\t\tif t == typeName {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (t Token) IsLength() bool {\n\tif t.TokenType == css.DimensionToken {\n\t\treturn true\n\t} else if t.TokenType == css.NumberToken && t.Data[0] == '0' {\n\t\treturn true\n\t} else if t.TokenType == css.FunctionToken {\n\t\tfun := ToHash(t.Data[:len(t.Data)-1])\n\t\tif fun == Calc || fun == Min || fun == Max || fun == Clamp || fun == Attr || fun == Var || fun == Env {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (args Arguments) Is(objects ...interface{}) bool {\n\tfor i, obj := range args {\n\t\tif obj != objects[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func checkIns(m reflect.Method) (in0, in1, in2, in3 reflect.Type, err error) {\n\tmtype := m.Type\n\tif mtype.NumIn() != 4 {\n\t\terr = fmt.Errorf(\"method %s has wrong number of ins: %d\", m.Name, mtype.NumIn())\n\t\treturn\n\t}\n\tin0 = mtype.In(0)\n\tin1 = mtype.In(1)\n\tif !in1.Implements(typeOfContext) {\n\t\terr = fmt.Errorf(\"method %s context type not implements context.Context: %s\", m.Name, in1)\n\t\treturn\n\t}\n\tin2 = mtype.In(2)\n\tif !isExportedOrBuiltinType(in2) {\n\t\terr = fmt.Errorf(\"method %s args type not exported: %s\", m.Name, in2)\n\t\treturn\n\t}\n\tin3 = mtype.In(3)\n\tif in3.Kind() != reflect.Ptr && in3 != typeOfNilInterface {\n\t\terr = fmt.Errorf(\"method %s reply type not a pointer or interface{}: %s\", m.Name, in3)\n\t\treturn\n\t}\n\tif !isExportedOrBuiltinType(in3) {\n\t\terr = fmt.Errorf(\"method %s reply type not exported: %s\", m.Name, in3)\n\t\treturn\n\t}\n\treturn\n}", "func (p *Packet) HasAttr(key AttributeType) bool {\n\tfor _, a := range p.Attrs {\n\t\tif a.Type() == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func ServerArgsPresent(neededArgs []string) bool {\n\tcurrentArgs := K3sServerArgs()\n\tfor _, arg := range neededArgs {\n\t\tif !contains(currentArgs, arg) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p ParameterFile) IsArray() bool {\n\treturn strings.HasSuffix(p.Type, \"[]\")\n}", "func hasType(node ast.Node) bool {\n\tswitch n := node.(type) {\n\tcase *ast.BinaryNode:\n\t\tif hasType(n.Left) || hasType(n.Right) {\n\t\t\treturn true\n\t\t}\n\tcase *ast.IdentifierNode:\n\t\tif n.Value == \"type\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (obj *testInstruction) IsInstruction() bool {\n\treturn obj.ins != nil\n}", "func occursInType(v Type, t2 Type) bool {\n\troot := t2.Root()\n\tif Equals(root, v) {\n\t\treturn true\n\t}\n\tif to, ok := root.(*Operator); ok {\n\t\treturn OccursIn(v, to.Args)\n\t}\n\treturn false\n}", "func (ob *PyObject) HasAttr(name string) bool {\n\tattr := C.CString(name)\n\tdefer C.free(unsafe.Pointer(attr))\n\treturn C.PyObject_HasAttrString(ob.rawptr, attr) > 0\n}", "func (fn *Function) TypeArgs() []types.Type { return fn.typeargs }", "func validateArgs(linkIndex int, fn reflect.Type, args []Argument) error {\n\tif !fn.IsVariadic() && (fn.NumIn() != len(args)) {\n\t\treturn argumentMismatchError(linkIndex, len(args), fn.NumIn())\n\t}\n\n\treturn nil\n}", "func HasEntry(entries interface{}, entry interface{}) bool {\n\tcontainerValue := reflect.ValueOf(entries)\n\n\tswitch reflect.TypeOf(entries).Kind() {\n\tcase reflect.Slice, reflect.Array:\n\t\tfor i := 0; i < containerValue.Len(); i++ {\n\t\t\tif containerValue.Index(i).Interface() == entry {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\tcase reflect.Map:\n\t\tif containerValue.MapIndex(reflect.ValueOf(entry)).IsValid() {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (w *whisperer) HasParameters(paths ...*string) (bool, error) {\n\tfilters := []*ssm.ParameterStringFilter{\n\t\t{\n\t\t\tKey: aws.String(\"Name\"),\n\t\t\tOption: aws.String(\"Equals\"),\n\t\t\tValues: paths,\n\t\t},\n\t}\n\tparameters := []*ssm.ParameterMetadata{}\n\tinput := &ssm.DescribeParametersInput{ParameterFilters: filters}\n\terr := w.SSMClient.DescribeParametersPages(input, func(out *ssm.DescribeParametersOutput, lastPage bool) bool {\n\t\tparameters = append(parameters, out.Parameters...)\n\t\treturn !lastPage\n\t})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfmt.Printf(\"Parameters: %+v\\n\", parameters)\n\treturn len(parameters) == len(paths), nil\n}", "func (o *WorkflowSshCmd) HasCommandType() bool {\n\tif o != nil && o.CommandType != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func DiagnoseInferableTypeArgs(fset *token.FileSet, inspect *inspector.Inspector, start, end token.Pos, pkg *types.Package, info *types.Info) []analysis.Diagnostic {\n\treturn nil\n}", "func validArgs(args *runtimeArgs) bool {\n\tflag.Usage = showHelp\n\n\targs.fg = flag.String(\"fg\", \"black\", \"foreground color\")\n\targs.bg = flag.String(\"bg\", \"green\", \"background color\")\n\n\tflag.Parse()\n\n\tif args.fg == nil || hue.StringToHue[*args.fg] == 0 {\n\t\tbadColor(*args.fg) // prints an error message w/ a list of supported colors\n\t\treturn false\n\t}\n\n\tif args.fg == nil || hue.StringToHue[*args.bg] == 0 {\n\t\tbadColor(*args.bg)\n\t\treturn false\n\t}\n\n\t// Get the remaining flags, which should\n\t// consist of a pattern, and optionally, one or more file names.\n\trem := flag.Args()\n\n\tswitch {\n\tcase len(rem) == 0:\n\t\tfmt.Println(\"Error: No pattern specified.\")\n\t\tshowHelp()\n\t\treturn false\n\tcase len(rem) == 1:\n\t\targs.pattern = &rem[0]\n\tcase len(rem) >= 2:\n\t\targs.pattern = &rem[0]\n\n\t\tfor i := 1; i < len(rem); i++ {\n\t\t\targs.files = append(args.files, &rem[i])\n\t\t}\n\t}\n\n\treturn true\n}", "func argsOK() bool {\n\tif len(os.Args) > 1 {\n\t\tif os.Args[1] == \"--file\" && len(os.Args[2]) > 0 {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\treturn false\n}", "func (s ReleaseSpec) IsKindExecute() (bool, error) {\n\tswitch s.Type {\n\tcase ReleaseImageSpecType:\n\t\tif s.ReleaseImageSpec != nil && s.ReleaseImageSpec.Kind == update.ReleaseKindExecute {\n\t\t\treturn true, nil\n\t\t}\n\tcase ReleaseContainersSpecType:\n\t\tif s.ReleaseContainersSpec != nil && s.ReleaseContainersSpec.Kind == update.ReleaseKindExecute {\n\t\t\treturn true, nil\n\t\t}\n\n\tdefault:\n\t\treturn false, errors.Errorf(\"unknown release spec type %s\", s.Type)\n\t}\n\treturn false, nil\n}", "func (m NoSides) HasQuantityType() bool {\n\treturn m.Has(tag.QuantityType)\n}", "func TypeHasCapability(kv *api.KV, deploymentID, typeName, capabilityTypeName string) (bool, error) {\n\tcapabilities, err := GetCapabilitiesOfType(kv, deploymentID, typeName, capabilityTypeName)\n\treturn len(capabilities) > 0, err\n}", "func (t Type) IsKeyword() bool {\n\treturn key_start < t && t < key_end\n}", "func checkArguments(hash string, privateKey string) bool {\n\t// easy check\n\t// if len(hash) != 46 || len(privateKey) != 64 {\n\t// \treturn false\n\t// }\n\n\treturn true\n}", "func (v *Function) IsSetArguments() bool {\n\treturn v != nil && v.Arguments != nil\n}", "func isCompatibleArg(arg, param types.Type) bool {\n\tif isCompatible(arg, param) {\n\t\treturn true\n\t}\n\tif arg, ok := arg.(*types.Array); ok {\n\t\tif param, ok := param.(*types.Array); ok {\n\t\t\t// TODO: Check for other compatible types (e.g. pointers, array names,\n\t\t\t// strings).\n\t\t\tif param.Len != 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn types.Equal(arg.Elem, param.Elem)\n\t\t}\n\t}\n\treturn false\n}" ]
[ "0.6620399", "0.6070014", "0.58602", "0.5559968", "0.551633", "0.5394115", "0.53795916", "0.5353696", "0.5310007", "0.5298867", "0.52459556", "0.52079266", "0.5189788", "0.51717234", "0.51651365", "0.5159262", "0.51278657", "0.5124402", "0.51076514", "0.5105842", "0.50955737", "0.50827265", "0.5068359", "0.5043159", "0.5039188", "0.50265473", "0.49888113", "0.4971622", "0.4945414", "0.4944646", "0.49427438", "0.49421072", "0.49364662", "0.49363536", "0.49237967", "0.49193102", "0.49118662", "0.49045524", "0.48871848", "0.48817638", "0.48798928", "0.48790714", "0.48713198", "0.48702854", "0.48225248", "0.48197818", "0.4816477", "0.48151174", "0.48118684", "0.48115885", "0.48070294", "0.47893637", "0.47764906", "0.47680828", "0.47628078", "0.476057", "0.47513914", "0.4744463", "0.47405696", "0.47395328", "0.47338685", "0.47167948", "0.4710176", "0.47039503", "0.47037658", "0.47032392", "0.46965584", "0.46948636", "0.46811777", "0.46742845", "0.46705315", "0.4666586", "0.46657553", "0.46553543", "0.46509445", "0.46380863", "0.46333498", "0.46117765", "0.4609888", "0.46053088", "0.46036202", "0.4599336", "0.4594286", "0.4590657", "0.458976", "0.45880038", "0.45865765", "0.45831543", "0.45775568", "0.45772898", "0.45764175", "0.45713258", "0.4564464", "0.45631468", "0.45474452", "0.45434615", "0.45377478", "0.45372462", "0.453515", "0.4533453" ]
0.8171181
0
Timestamp gen unix time stamp from string to int64
func Timestamp(createdBy string) (createdAtUnix int64) { timestamp, err := time.Parse(time.RFC3339, createdBy) if err != nil { createdAtUnix = time.Now().Unix() ErrorLog(err) } else { createdAtUnix = timestamp.Unix() } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func makeTimestamp() int64 {\n return time.Now().UnixNano() / int64(time.Millisecond)\n}", "func Str2TimeStampS(s string) int64 {\n\tloc, _ := time.LoadLocation(\"UTC\")\n\tt, err := time.ParseInLocation(DATE_FORMAT_SHORT, s, loc)\n\tCheckErr(err, CHECK_FLAG_LOGONLY)\n\treturn t.Unix()\n}", "func getTimestamp() uint64 {\n\treturn uint64(time.Since(Epoch).Nanoseconds() / 1e6)\n}", "func makeTimestamp() int64 {\n\treturn time.Now().UnixNano()/int64(time.Microsecond)\n}", "func makeTimestamp() int64 {\n\treturn time.Now().UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))\n}", "func makeTimestamp() int64 {\n\treturn time.Now().UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))\n}", "func makeTimestamp() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func timestamp32(b []byte) string {\n\tif len(b) != 4 {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%v\", time.Unix(int64(binary.BigEndian.Uint32(b)), 0))\n}", "func Str2TimeStampL(s string) int64 {\n\tloc, _ := time.LoadLocation(\"UTC\")\n\tt, err := time.ParseInLocation(DATE_FORMAT_LONG, s, loc)\n\tCheckErr(err, CHECK_FLAG_LOGONLY)\n\treturn t.Unix()\n}", "func (gdb *Gdb) getUnixTimeStamp(t string, d int) (int64, error) {\n\tif st, err := time.Parse(timeFormatString, t); err != nil {\n\t\treturn -1, err\n\t} else {\n\t\treturn st.Add(time.Duration(d) * time.Second).Unix(), nil\n\t}\n}", "func RdTimestamp() time.Time {\n\tmin := time.Date(1970, 1, 0, 0, 0, 0, 0, time.UTC).Unix()\n\tmax := time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC).Unix()\n\tdelta := max - min\n\n\tsec := rand.Int63n(delta) + min\n\treturn time.Unix(sec, 0)\n}", "func timestamp() int64 {\n\treturn time.Now().Unix()\n}", "func getTimestamp() string {\n\treturn strconv.FormatInt(time.Now().UTC().Unix(), 10)\n}", "func timeStamp() int64 {\n\tnow := time.Now()\n\n\ttimestamp := now.Unix()\n\n\treturn timestamp\n}", "func timestamp() string {\n\treturn fmt.Sprintf(\"%d\", time.Now().UTC().UnixNano()/1000000)\n}", "func UnixTimestamp(sec int64, layout string) string {\n\treturn time.Unix(sec, 0).Format(layout)\n}", "func timestamp(ctx iscp.SandboxBase) uint64 {\n\ttsNano := time.Duration(ctx.GetTimestamp()) * time.Nanosecond\n\treturn uint64(tsNano / time.Second)\n}", "func getUnixTime(val []byte) (uint64, error) {\n\tif len(val) < 8 {\n\t\treturn 0, errors.New(\"len(val) < 8, want len(val) => 8\")\n\t}\n\tunixTime := ((uint64)(val[0]) | // 1st\n\t\t((uint64)(val[1]) << 8) | // 2nd\n\t\t((uint64)(val[2]) << 16) | // 3rd\n\t\t((uint64)(val[3]) << 24) | // 4th\n\t\t((uint64)(val[4]) << 32) | // 5th\n\t\t((uint64)(val[5]) << 40) | // 6th\n\t\t((uint64)(val[6]) << 48) | // 7th\n\t\t((uint64)(val[7]) << 56)) // 8th\n\treturn unixTime, nil\n}", "func toMSTimestamp(t time.Time) int64 {\n\treturn t.UnixNano() / 1e6\n}", "func (t Time) Unix() int64 {}", "func ConvertUnixEpochToDate(timeStamp uint32) (time.Time) {\n stamp64 := int64(timeStamp)\n ret := time.Unix(stamp64, 0)\n return ret\n}", "func getTimestampFromEntry(data []byte) uint64 {\n\treturn binary.LittleEndian.Uint64(data)\n}", "func Timestamp() int32 {\n\treturn int32(time.Now().Unix())\n}", "func (v Timestamp) Int64() int64 {\n\tif !v.Valid() || v.time.Unix() == 0 {\n\t\treturn 0\n\t}\n\treturn v.time.Unix()\n}", "func ts() string {\n\tt := time.Now()\n\treturn strconv.FormatInt(t.UnixNano(), 10)\n}", "func tdParseTimestamp( t string, a string ) int64 {\n n, err := strconv.ParseInt( t, 10, 64 )\n if err == nil {\n // NR feed is in Java time (millis) so convert to Unix time (seconds)\n n := n / int64(1000)\n\n if a != \"\" {\n dt := time.Now().Unix() - n\n // Hide anomaly around local midnight where a blip is recorded going from\n // +- 2400 (14400 when merged into 1m samples)\n if dt > -2400 && dt < 2400 {\n statistics.Set( \"td.\" + a, dt )\n }\n }\n\n return n\n }\n return 0\n}", "func dateInt(timestamp int64) uint64 {\n\tdate := time.Unix(timestamp, 0)\n\tlabel := fmt.Sprintf(\"%.4d%.2d%.2d\", date.Year(), date.Month(), date.Day())\n\ti, _ := strconv.ParseUint(label, 10, 64)\n\treturn i\n}", "func TimestampAsInt64(t string) (int64, error) {\n\ttimestamp, err := time.Parse(time.RFC3339Nano, t)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn timestamp.Unix(), err\n}", "func ToTimestamp(t time.Time, unit TimeUnit) (int64, error) {\n\tepoch := t.Unix()\n\n\tswitch unit {\n\tcase UnitSeconds:\n\t\t// calculated as default value,\n\t\t// nothing to to\n\tcase UnitMilliseconds:\n\t\tepoch = t.UnixNano() / (1000 * 1000)\n\tcase UnitMicroseconds:\n\t\tepoch = t.UnixNano() / 1000\n\tcase UnitNanoseconds:\n\t\tepoch = t.UnixNano()\n\tdefault:\n\t\treturn 255, fmt.Errorf(\"unknown unit '%v'\", unit)\n\t}\n\n\treturn epoch, nil\n}", "func timestampFromUUID(muuid muuid.MUUID) int64 {\n\tvar timestamp int64 = 0\n\n\tfor i := 0; i < 6; i++ {\n\t\ttimestamp = (timestamp * 256) + int64(muuid[i])\n\t}\n\n\treturn timestamp\n}", "func Unix(sec int64, nsec int64) Time {}", "func makeTimestampMilli() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func makeTimestampMilli() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func timestampAsString() string {\n\treturn fmt.Sprintf(\"%d\", makeTimestamp())\n}", "func Unix(sec, nsec int64) *Timestamp {\n\tt := time.Unix(sec, nsec).UTC()\n\treturn Time(t)\n}", "func makeTimestampNano() int64 {\n\treturn time.Now().UnixNano()\n}", "func makeTimestampNano() int64 {\n\treturn time.Now().UnixNano()\n}", "func GetUnixTimestamp() uint64 {\n\treturn uint64(time.Now().UnixNano()) / uint64(time.Millisecond)\n}", "func NewTimestampString() string {\n\treturn fmt.Sprintf(\"%d\", time.Now().Unix()+ChinaTimeZoneOffset)\n}", "func timestamp() int64 {\n\treturn time.Now().UnixNano() / int64(time.Second)\n}", "func fileTimestamp(file string) int64 {\n\tmatch := regexp.MustCompile(\"(\\\\D|^)(20\\\\d{10})(\\\\D|$)\").FindStringSubmatch(filepath.Base(file))\n\tif match == nil || len(match[2]) != 12 {\n\t\treturn -1\n\t}\n\tdigits := match[2]\n\tyear, _ := strconv.ParseInt(digits[0:4], 10, 64)\n\tmonth, _ := strconv.ParseInt(digits[4:6], 10, 64)\n\tday, _ := strconv.ParseInt(digits[6:8], 10, 64)\n\thour, _ := strconv.ParseInt(digits[8:10], 10, 64)\n\tminute, _ := strconv.ParseInt(digits[10:12], 10, 64)\n\tt := time.Date(int(year), time.Month(month), int(day), int(hour),\n\t\tint(minute), 0, 0, time.UTC)\n\n\treturn t.Unix()\n}", "func Timestamp() int64 {\n\treturn atomic.LoadInt64(&_genesisTs)\n}", "func convertTimeStamp(timestamp uint64) int64 {\n\treturn int64(timestamp / uint64(int64(time.Millisecond)/int64(time.Nanosecond)))\n}", "func timestamp() string {\n\ttimestamp := time.Now().Format(\"15:04:05.99\")\n\tif len(timestamp) < 11 {\n\t\ttimestamp += strings.Repeat(\"0\", 11-len(timestamp))\n\t}\n\treturn timestamp\n}", "func GetTimeFromTimestamp(datatype Datatype, timestamp int64) time.Time {\n\tvar then time.Time\n\tswitch datatype {\n\tcase TILEDB_DATETIME_YEAR:\n\t\tnumOfSeconds := secondsFromEpochYears(timestamp)\n\t\tthen = time.Unix(int64(numOfSeconds), 0)\n\tcase TILEDB_DATETIME_MONTH:\n\t\tnumOfSeconds := secondsFromEpochMonths(timestamp)\n\t\tthen = time.Unix(int64(numOfSeconds), 0)\n\tcase TILEDB_DATETIME_WEEK:\n\t\tnumOfSeconds := 7 * timestamp * secondsInDay\n\t\tthen = time.Unix(int64(numOfSeconds), 0)\n\tcase TILEDB_DATETIME_DAY:\n\t\tnumOfSeconds := timestamp * secondsInDay\n\t\tthen = time.Unix(int64(numOfSeconds), 0)\n\tcase TILEDB_DATETIME_HR, TILEDB_TIME_HR:\n\t\tnumOfSeconds := timestamp * secondsInHour\n\t\tthen = time.Unix(int64(numOfSeconds), 0)\n\tcase TILEDB_DATETIME_MIN, TILEDB_TIME_MIN:\n\t\tnumOfSeconds := timestamp * secondsInMin\n\t\tthen = time.Unix(int64(numOfSeconds), 0)\n\tcase TILEDB_DATETIME_SEC, TILEDB_TIME_SEC:\n\t\tthen = time.Unix(timestamp, 0)\n\tcase TILEDB_DATETIME_MS, TILEDB_TIME_MS:\n\t\tthen = time.Unix(0, int64(timestamp*1000*1000))\n\tcase TILEDB_DATETIME_US, TILEDB_TIME_US:\n\t\tthen = time.Unix(0, int64(timestamp*1000))\n\tcase TILEDB_DATETIME_NS, TILEDB_TIME_NS:\n\t\tthen = time.Unix(0, timestamp)\n\tcase TILEDB_DATETIME_PS, TILEDB_TIME_PS:\n\t\tthen = time.Unix(0, int64(timestamp/1000))\n\tcase TILEDB_DATETIME_FS, TILEDB_TIME_FS:\n\t\tthen = time.Unix(0, int64(timestamp/(1000*1000)))\n\tcase TILEDB_DATETIME_AS, TILEDB_TIME_AS:\n\t\tthen = time.Unix(0, int64(timestamp/(1000*1000)))\n\t}\n\n\treturn then.UTC()\n}", "func Timestamp() int64 {\n\treturn time.Now().UTC().UnixNano()\n}", "func generateExpirationTimestamp() int64 {\n\treturn time.Now().Unix() + int64(3600)\n}", "func TestGetTimeFromUnixTime(t *testing.T) {\n\tvar basetime int64\n\tbasetime = 1500000000\n\n\tts := Timestamp{}\n\n\ttime := ts.GetTimeFromUnixTime(basetime)\n\n\tif time != \"Fri, 14 Jul 2017 02:40:00 UTC\" {\n\t\tt.Errorf(\"ts = \\t\\\"%v\\\";\\twant\\t\\\"Fri, 14 Jul 2017 02:40:00 UTC\\\"\", time)\n\t}\n}", "func Time2Int64(t int64) int64 {\n\tdatestring := UnixMilli2TimeStr(t)\n\t_time := datestring[11:]\n\ttimestr := _time + strings.Repeat(\"0\", 12-len(_time))\n\ttimeintstr := strings.Replace(strings.Replace(timestr, \":\", \"\", -1), \".\", \"\", -1)\n\ttimeToInt, _ := strconv.ParseInt(timeintstr, 10, 64)\n\treturn timeToInt\n}", "func stringToUnixTime(s string) int64 {\n\t// Parse YYYY-MM-DD\n\ttimeT, err := time.Parse(\"2006-01-02\", s)\n\tif err != nil {\n\t\tErrorLog(\"cannot convert string: \"+s+\"to millisecond: %s\", err.Error())\n\t\treturn 0\n\t}\n\treturn timeT.Unix()\n}", "func render_date_to_unix_timestamp(value string) ( int64 , error ) {\n ti , err := time.ParseInLocation(dateformat_onlydate,value,time.Local)\n if err != nil {\n return 0 , err\n }\n return ti.Unix() , nil\n}", "func (t Timestamp) Unix() int64 {\n\treturn time.Time(t).Unix()\n}", "func GetTimeStamp(year, month, day int) int64 {\n\treturn time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC).Unix()\n}", "func (d *Discord) TimestampForID(id string) (time.Time, error) {\n\t_id, err := strconv.ParseInt(id, 10, 64)\n\tif err != nil {\n\t\treturn time.Unix(0, 0), err\n\t}\n\treturn time.Unix(((_id>>22)+1420070400000)/1000, 0), nil\n}", "func GetTimestamp() string {\n\treturn strconv.FormatInt(time.Now().Unix(), 10)\n}", "func Timestamp() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func (id UUID) Timestamp() (sec uint32, millisec uint16) {\n\tsec = uint32(id[0])<<24 | uint32(id[1])<<16 | uint32(id[2])<<8 | uint32(id[3])\n\tmillisec = uint16(id[4])<<8 | uint16(id[5])\n\treturn\n}", "func parseTimeStamp(s string) (int64, error) {\n\tt, err := time.Parse(TimeStampLayout, s)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn t.UnixNano() / int64(time.Millisecond), nil\n}", "func (dt DateTime) UnixTimestamp() int64 {\n\treturn dt.Time().Unix()\n}", "func TimeStamp2StrL(ts int64) string {\n\tt := time.Unix(ts, 0).UTC()\n\treturn t.Format(DATE_FORMAT_LONG)\n}", "func ReadTimestamp(buffer []byte, offset int) Timestamp {\n nanoseconds := ReadUInt64(buffer, offset)\n return TimestampFromNanoseconds(nanoseconds)\n}", "func DecodeTimestamp(b []byte) time.Time {\n\tt := binary.LittleEndian.Uint64(b[:8])\n\treturn time.Unix(0, int64((t-116444736000000000)*100)).UTC()\n}", "func ExampleTime_Timestamp() {\n\tt := gtime.Timestamp()\n\n\tfmt.Println(t)\n\n\t// May output:\n\t// 1533686888\n}", "func convertUnixTime(timeInt int) time.Time {\n\n\ti := int64(timeInt)\n\treturn time.Unix(i, 0)\n\n}", "func StrTime13() string {\n\treturn strconv.FormatInt(time.Now().UnixNano()/1e6, 10) //\"1576395361\"\n}", "func MakeTimestampMilli() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func Timestamp(t, i uint32) Val {\n\tv := Val{t: bsontype.Timestamp}\n\tv.bootstrap[0] = byte(i)\n\tv.bootstrap[1] = byte(i >> 8)\n\tv.bootstrap[2] = byte(i >> 16)\n\tv.bootstrap[3] = byte(i >> 24)\n\tv.bootstrap[4] = byte(t)\n\tv.bootstrap[5] = byte(t >> 8)\n\tv.bootstrap[6] = byte(t >> 16)\n\tv.bootstrap[7] = byte(t >> 24)\n\treturn v\n}", "func TimeUnix() string {\r\n\tnaiveTime := time.Now().Unix()\r\n\tnaiveTimeString := strconv.FormatInt(naiveTime, 10)\r\n\treturn naiveTimeString\r\n}", "func byteArrToTime(byteArr []byte) int64 {\n\t//This is set to bigendian so that the timestamp is sorted in binary format.\n\ttimeVal := int64(binary.BigEndian.Uint64(byteArr))\n\treturn timeVal\n}", "func TimestampString(secs int64) string {\n\treturn time.Unix(secs, 0).UTC().Format(time.RFC3339)\n}", "func TimeStamp2Str(t uint32) string {\n\treturn fmt.Sprintf(\"%010d\", t)\n}", "func (t Timestamp) Unix() int64 {\n\treturn t.Time().Unix()\n}", "func GetTs() int64 {\n\treturn time.Now().UnixNano() / 1e6\n}", "func getTimeStamp(A []int) time {\n\ttimeStamp := time{}\n\ttimeStamp.hour = A[0]*10 + A[1]\n\ttimeStamp.minute = A[2]*10 + A[3]\n\treturn timeStamp\n}", "func GoTimeToTS(t time.Time) uint64 {\n\tts := (t.UnixNano() / int64(time.Millisecond)) << epochShiftBits\n\treturn uint64(ts)\n}", "func WriteTimestamp(buffer []byte, offset int, value Timestamp) {\n nanoseconds := uint64(value.UnixNano())\n WriteUInt64(buffer, offset, nanoseconds)\n}", "func (v Timestamp) Int() int {\n\treturn int(v.Int64())\n}", "func NewTimestampTsCellFromInt64(v int64) TsCell {\n\ttsc := riak_ts.TsCell{TimestampValue: &v}\n\ttsct := riak_ts.TsColumnType_TIMESTAMP\n\treturn TsCell{columnType: tsct, cell: &tsc}\n}", "func NewTimeStamp(i int64) *TimeStamp {\n\tt, _ := time.Parse(DateTimeFormatString, \"1970-01-01 00:00:00\")\n\tif i < 1e12 {\n\t\tt = t.Add(time.Duration(i) * time.Second)\n\t} else if i < 1e15 {\n\t\tt = t.Add(time.Duration(i/1e3) * time.Second).Add(time.Duration(i%1e3) * time.Millisecond)\n\t} else if i < 1e18 {\n\t\tt = t.Add(time.Duration(i/1e6) * time.Second).Add(time.Duration(i%1e6) * time.Microsecond)\n\t} else {\n\t\tt = t.Add(time.Duration(i/1e9) * time.Second).Add(time.Duration(i%1e9) * time.Nanosecond)\n\t}\n\tt = t.Local()\n\tts := &TimeStamp{t, t.Unix(), t.UnixNano()}\n\treturn ts\n}", "func CurrentTimeStampStr() string {\n\treturn strconv.FormatInt(time.Now().Unix(), 10)\n}", "func getMaiAuthTimestamp(token string) (time.Time, error) {\n\tvar timestamp time.Time\n\tfields := strings.Split(token, \"@\")\n\tif len(fields) != 2 {\n\t\treturn timestamp, errors.New(\"Token should be MAI-AUTHENTICATION@{time}\")\n\t}\n\t// parse rfc\n\tt, err := time.Parse(time.RFC3339Nano, fields[1])\n\tif err == nil {\n\t\treturn t, err\n\t}\n\tn, err := strconv.ParseInt(fields[1], 10, 64)\n\tif err == nil {\n\t\treturn time.Unix(n/1000, n%1000*1e6), nil\n\t}\n\treturn timestamp, errors.New(\"Time field should be a unix timestamp or an rfc3339 time string\")\n}", "func (ts Timestamp) Time() time.Time { return time.Unix(int64(ts), 0) }", "func Int64ToTime(timeStamp int64) time.Time {\n\treturn time.Unix(timeStamp, 0).UTC()\n}", "func MysqlTimeToUnix(ts string) int64 {\n\tloc, _ := time.LoadLocation(\"Local\")\n\tt, _ := time.ParseInLocation(goMysqlTimeFormat, ts, loc)\n\treturn t.Unix()\n}", "func NewTimestamp(unixTime int64) *Timestamp {\n\tstamp := Timestamp(time.Unix(unixTime, 0))\n\treturn &stamp\n}", "func generateToptToken(secret string) string {\n\t// actual unix timestamp\n\tnow := time.Now().Unix()\n\t// TODO: make me variable\n\tintervalLength := 30\n\tcounter := uint64(math.Floor(float64(now) / float64(intervalLength)))\n\n\treturn generateHotpToken(secret, counter)\n}", "func TimeStrToInt(ts, layout string) int64 {\n\tif ts == \"\" {\n\t\treturn 0\n\t}\n\tif layout == \"\" {\n\t\tlayout = \"2006-01-02 15:04:05\"\n\t}\n\tt, err := time.ParseInLocation(layout, ts, time.Local)\n\tif err != nil {\n\t\tlogs.Error(err)\n\t\treturn 0\n\t}\n\treturn t.Unix()\n}", "func TimeStr2Unix(timeStr string) (int64, error) {\n\tt, err := time.ParseInLocation(\"2006-01-02 15:04:05\", timeStr, time.Local)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn t.Unix(), nil\n}", "func (client *Client) generateRequestTimestamp() int64 {\n return time.Now().UnixNano() / 1000000\n}", "func parseTimestamp(s string) (time.Time, error) {\n\tsp := strings.Split(s, \".\")\n\tsec, nsec := int64(0), int64(0)\n\tvar err error\n\tif len(sp) > 0 {\n\t\tif sec, err = strconv.ParseInt(sp[0], 10, 64); err != nil {\n\t\t\treturn time.Time{}, fmt.Errorf(\"unable to parse timestamp %s: %s\",\n\t\t\t\ts, err.Error())\n\t\t}\n\t}\n\n\tif len(sp) > 1 {\n\t\tif nsec, err = strconv.ParseInt(sp[1], 10, 64); err != nil {\n\t\t\treturn time.Time{}, fmt.Errorf(\"unable to parse timestamp %s: %s\",\n\t\t\t\ts, err.Error())\n\t\t}\n\n\t\tnsec *= 1000000\n\t}\n\n\treturn time.Unix(sec, nsec), nil\n}", "func parseTimestamp(ts interface{}) (time.Time, bool) {\n\tswitch ts.(type) {\n\tcase float64:\n\t\treturn time.Unix(int64(ts.(float64)), 0), true\n\tcase int64:\n\t\treturn time.Unix(ts.(int64), 0), true\n\tcase string:\n\t\tif tm, err := strconv.ParseInt(ts.(string), 10, 64); err == nil {\n\t\t\treturn time.Unix(tm, 0), true\n\t\t} else {\n\t\t\tlogging.Warn(\"parseTimestamp: %s\", err)\n\t\t}\n\t}\n\treturn time.Now(), false\n}", "func id(now time.Time) int64 {\n\treturn now.UTC().UnixNano()\n}", "func TimestampFromJSEpoch(epoch int64) Timestamp {\n\treturn Timestamp(time.Unix(epoch/1000, (epoch%1000)*1000000))\n}", "func unixTimeNow() int64 {\n\treturn time.Now().Unix()\n}", "func (util *MigrateUtil) IdByTimestamp() string {\n\treturn strconv.FormatInt(time.Now().Unix(), 10)\n}", "func (e *Entry) Timestamp() uint64 {\n\tif e.stamp == 0 {\n\t\treturn uint64(time.Now().Unix())\n\t}\n\treturn e.stamp\n}", "func (v TimestampNano) Int64() int64 {\n\tif !v.Valid() || v.time.UnixNano() == 0 {\n\t\treturn 0\n\t}\n\treturn v.time.UnixNano()\n}", "func generaTimeStampDateDateTime() string {\n\tnow := time.Now()\n\treturn now.String()[0:17]\n}", "func TimeStampFrom(timestamp string) *TimeStamp {\n\tif len(timestamp) < 10 {\n\t\treturn nil\n\t}\n\tseconds, err := strconv.ParseInt(timestamp[0:10], 10, 64)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tnanoSeconds := 0\n\tswitch n := timestamp[10:]; len(n) {\n\tcase 3:\n\t\tif i, err := strconv.Atoi(n); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\tnanoSeconds = i * 1e6\n\t\t}\n\tcase 6:\n\t\tif i, err := strconv.Atoi(n); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\tnanoSeconds = i * 1e3\n\t\t}\n\tcase 9:\n\t\tif i, err := strconv.Atoi(n); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\tnanoSeconds = i\n\t\t}\n\tdefault:\n\t\treturn nil\n\t}\n\treturn TimeStampFromSeconds(seconds, int64(nanoSeconds))\n}", "func DateFromEpoch(t int64) time.Time {\n\treturn time.Unix(0, t*1000000)\n}", "func TimestampToUnixMillisecondsString(time time.Time) string {\n\treturn strconv.FormatInt(time.Unix()*1000, 10)\n}" ]
[ "0.7013703", "0.6621233", "0.6551284", "0.6531924", "0.6515391", "0.6515391", "0.65082395", "0.6502291", "0.6467381", "0.64590216", "0.64448416", "0.6431059", "0.6380952", "0.62893873", "0.62606484", "0.62140614", "0.6206639", "0.62042296", "0.62012553", "0.6159245", "0.61543936", "0.61511356", "0.6135398", "0.60650116", "0.6050832", "0.603456", "0.60302615", "0.6022073", "0.6000874", "0.6000125", "0.5932531", "0.593245", "0.593245", "0.5906824", "0.5891181", "0.588224", "0.588224", "0.5873772", "0.5873123", "0.58592355", "0.5855364", "0.5851091", "0.58488476", "0.58360523", "0.5827304", "0.58270633", "0.58210975", "0.58011127", "0.5800376", "0.5793777", "0.57775867", "0.575145", "0.57417923", "0.5714424", "0.5709035", "0.5706552", "0.5704254", "0.5691199", "0.56900257", "0.5680134", "0.5633886", "0.562772", "0.56219923", "0.5613986", "0.5598468", "0.5595845", "0.5592423", "0.5583565", "0.55620855", "0.5553746", "0.55459625", "0.5531305", "0.55146074", "0.55000925", "0.5489231", "0.5480734", "0.5475041", "0.54739726", "0.5443283", "0.54328936", "0.54232764", "0.54192436", "0.54169834", "0.54057205", "0.5404773", "0.5382781", "0.5382505", "0.53633183", "0.53589666", "0.5342458", "0.53399986", "0.5330116", "0.5329623", "0.53283244", "0.5327217", "0.532717", "0.53216213", "0.53206587", "0.53185815", "0.5293389", "0.5289266" ]
0.0
-1
implement function to return ServiceMiddleware
func newTracingMiddleware(tracer opentracing.Tracer) linkManagerMiddleware { return func(next om.LinkManager) om.LinkManager { return tracingMiddleware{next, tracer} } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Middleware(s Service) func(http.Handler) http.Handler {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tua := r.Header.Get(\"token\")\n\t\t\tauthrze, err := s.ParseToken(ua)\n\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !authrze {\n\t\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// user, _ := s.GetUser(ua)\n\t\t\t// r.Header.Set(\"user\", user)\n\t\t\th.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func NewServiceMiddleware(config environments.Config, services services.ServiceDirectory) *ServiceMiddleware {\n\treturn &ServiceMiddleware{\n\t\tConfig: config,\n\t\tServices: services,\n\t}\n\n}", "func NewMiddleware(service services.Keys) Middleware {\n\n\treturn &middlewareStruct{\n\t\tservice: service,\n\t}\n}", "func WrapperMiddleware(w HandlerFuncWrapper) Middleware { return w }", "func (svc *Service) createMiddleware(cfg *config.Configuration) alice.Chain {\n\tidentityHandler := dphandlers.IdentityWithHTTPClient(svc.identityClient)\n\treturn alice.New(\n\t\tmiddleware.Whitelist(middleware.HealthcheckFilter(svc.healthCheck.Handler)),\n\t\tdprequest.HandlerRequestID(16),\n\t\tidentityHandler,\n\t)\n}", "func (c *DefaultApiController) Middleware() func(http.Handler) http.Handler {\n\treturn c.middleware\n}", "func WrapperHandlerMiddleware(w HandlerWrapper) Middleware { return w }", "func Middleware(\n\tenv *Env,\n) func(http.Handler) http.Handler {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn middleware{h, env}\n\t}\n}", "func MetricsMiddleware(svc exapp.Service, counter metrics.Counter, latency metrics.Histogram) exapp.Service {\n\treturn &metricsMiddleware{\n\t\tcounter: counter,\n\t\tlatency: latency,\n\t\tsvc: svc,\n\t}\n}", "func LoggingMiddleware(svc k8s_client.Service, logger log.Logger) k8s_client.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func LoggingMiddleware(svc things.Service, logger log.Logger) things.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func TraceMiddleware() Middleware {\n\treturn func(next Service) Service {\n\t\treturn traceMiddleware{\n\t\t\tnext: next,\n\t\t}\n\t}\n}", "func (s *JSONService) Middleware(h http.Handler) http.Handler {\n\treturn gziphandler.GzipHandler(h)\n}", "func ValidationMiddleware() func(Service) Service {\n\treturn func(next Service) Service {\n\t\treturn &validationMiddleware{\n\t\t\tService: next,\n\t\t}\n\t}\n}", "func Middleware() echo.MiddlewareFunc {\n\tstats.Do(func() {\n\t\tstats.init()\n\t})\n\treturn echo.WrapMiddleware(handlerFunc)\n}", "func (mw MiddlewareFunc) Middleware(handler http.Handler) http.Handler {\n\treturn mw(handler)\n}", "func (mw MiddlewareFunc) Middleware(handler http.Handler) http.Handler {\n\treturn mw(handler)\n}", "func Middleware(service string, opts ...Option) echo.MiddlewareFunc {\n\tcfg := config{}\n\tfor _, opt := range opts {\n\t\topt.apply(&cfg)\n\t}\n\tif cfg.TracerProvider == nil {\n\t\tcfg.TracerProvider = otel.GetTracerProvider()\n\t}\n\ttracer := cfg.TracerProvider.Tracer(\n\t\ttracerName,\n\t\toteltrace.WithInstrumentationVersion(Version()),\n\t)\n\tif cfg.Propagators == nil {\n\t\tcfg.Propagators = otel.GetTextMapPropagator()\n\t}\n\n\tif cfg.Skipper == nil {\n\t\tcfg.Skipper = middleware.DefaultSkipper\n\t}\n\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tif cfg.Skipper(c) {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\tc.Set(tracerKey, tracer)\n\t\t\trequest := c.Request()\n\t\t\tsavedCtx := request.Context()\n\t\t\tdefer func() {\n\t\t\t\trequest = request.WithContext(savedCtx)\n\t\t\t\tc.SetRequest(request)\n\t\t\t}()\n\t\t\tctx := cfg.Propagators.Extract(savedCtx, propagation.HeaderCarrier(request.Header))\n\t\t\topts := []oteltrace.SpanStartOption{\n\t\t\t\toteltrace.WithAttributes(semconvutil.HTTPServerRequest(service, request)...),\n\t\t\t\toteltrace.WithSpanKind(oteltrace.SpanKindServer),\n\t\t\t}\n\t\t\tif path := c.Path(); path != \"\" {\n\t\t\t\trAttr := semconv.HTTPRoute(path)\n\t\t\t\topts = append(opts, oteltrace.WithAttributes(rAttr))\n\t\t\t}\n\t\t\tspanName := c.Path()\n\t\t\tif spanName == \"\" {\n\t\t\t\tspanName = fmt.Sprintf(\"HTTP %s route not found\", request.Method)\n\t\t\t}\n\n\t\t\tctx, span := tracer.Start(ctx, spanName, opts...)\n\t\t\tdefer span.End()\n\n\t\t\t// pass the span through the request context\n\t\t\tc.SetRequest(request.WithContext(ctx))\n\n\t\t\t// serve the request to the next middleware\n\t\t\terr := next(c)\n\t\t\tif err != nil {\n\t\t\t\tspan.SetAttributes(attribute.String(\"echo.error\", err.Error()))\n\t\t\t\t// invokes the registered HTTP error handler\n\t\t\t\tc.Error(err)\n\t\t\t}\n\n\t\t\tstatus := c.Response().Status\n\t\t\tspan.SetStatus(semconvutil.HTTPServerStatus(status))\n\t\t\tif status > 0 {\n\t\t\t\tspan.SetAttributes(semconv.HTTPStatusCode(status))\n\t\t\t}\n\n\t\t\treturn err\n\t\t}\n\t}\n}", "func LoggingMiddleware(svc pms.Service, logger log.Logger) pms.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func LoggingMiddleware(svc authz.Service, logger log.Logger) authz.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func LoggingMiddleware(svc authz.Service, logger log.Logger) authz.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func LoggingMiddleware(svc ws.Service, logger log.Logger) ws.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func (s *SavedItemsService) Middleware(h http.Handler) http.Handler {\n\t// wrap the response with our GZIP Middleware\n\treturn context.ClearHandler(gziphandler.GzipHandler(h))\n}", "func LoggingMiddleware(logger log.Logger) service.ServiceMiddleware {\n\treturn func(next service.Service) service.Service {\n\t\treturn loggingMiddleware{next, logger}\n\t}\n}", "func LoggingMiddleware(logger log.Logger) service.ServiceMiddleware {\n\treturn func(next service.Service) service.Service {\n\t\treturn loggingMiddleware{next, logger}\n\t}\n}", "func LoggingMiddleware(svc authn.Service, logger log.Logger) authn.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func middleware(ctx *fasthttp.RequestCtx, redisClient *redis.Client) {\n\tctx.Response.Header.SetContentType(\"application/json; charset=utf-8\")\n\tlog.Info(\"CTX: \", string(ctx.PostBody())) // Logging the arguments of the request\n\tvar req datastructures.MiddlewareRequest\n\terr := json.Unmarshal(ctx.PostBody(), &req) // Populate the structure from the json\n\tcommonutils.Check(err, \"middleware\")\n\tlog.Info(\"Request unmarshalled: \", req)\n\tlog.Debug(\"Validating request ...\")\n\tif authutils.ValidateMiddlewareRequest(&req) { // Verify it the json is valid\n\t\tlog.Info(\"Request valid! Verifying token from Redis ...\")\n\t\tauth := authutils.VerifyCookieFromRedisHTTPCore(req.Username, req.Token, redisClient) // Call the core function for recognize if the user have the token\n\t\tif strings.Compare(auth, \"AUTHORIZED\") == 0 { // Token in redis, call the external service..\n\t\t\tlog.Info(\"REQUEST OK> \", req)\n\t\t\tlog.Warn(\"Using service \", req.Method, \" | ARGS: \", req.Data, \" | Token: \", req.Token, \" | USR: \", req.Username)\n\t\t\t_, err := ctx.Write(sendGet(req))\n\t\t\tcommonutils.Check(err, \"middleware\")\n\t\t\treturn\n\t\t}\n\t\terr = json.NewEncoder(ctx).Encode(datastructures.Response{Status: false, Description: \"NOT AUTHORIZED!!\", ErrorCode: \"YOU_SHALL_NOT_PASS\", Data: nil})\n\t\tcommonutils.Check(err, \"middleware\")\n\t\treturn\n\t}\n\terr = json.NewEncoder(ctx).Encode(datastructures.Response{Status: false, Description: \"Not Valid Json!\", ErrorCode: \"\", Data: req})\n\tcommonutils.Check(err, \"middleware\")\n}", "func Middleware(client Client) gin.HandlerFunc {\n\t// Initialize and configure the client and set options if given.\n\tcc := newConfiguredClient(client)\n\n\treturn func(c *gin.Context) {\n\t\tlog.Debug(\"Starting Statsd middleware\")\n\t\tstart := time.Now()\n\t\tc.Next()\n\n\t\thandler := c.HandlerName()\n\t\tcc.IncrThroughput(handler)\n\t\tcc.IncrStatusCode(c.Writer.Status(), handler)\n\t\tcc.IncrSuccess(c.Errors, handler)\n\t\tcc.IncrError(c.Errors, handler)\n\t\tcc.Timing(start, handler)\n\t}\n}", "func LogServiceMiddleware(logger log.Logger, store string) ServiceMiddleware {\n\treturn func(next Service) Service {\n\t\tlogger = log.NewContext(logger).With(\n\t\t\t\"service\", \"event\",\n\t\t\t\"store\", store,\n\t\t)\n\n\t\treturn &logService{logger: logger, next: next}\n\t}\n}", "func ToMiddleware(classicMiddleware func(http.HandlerFunc) http.HandlerFunc) Middleware {\n\treturn func(c Container, next Handler) {\n\t\tclassicMiddleware(func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\tnext(c)\n\t\t})(c.GetResponseWriter(), c.GetRequest())\n\t}\n}", "func NewInstrumentingService(duration metrics.Histogram) Middleware {\n\treturn func(s Service) Service {\n\t\treturn &instrumentingMiddleware{\n\t\t\tduration: duration,\n\t\t\tService: s,\n\t\t}\n\t}\n}", "func Middleware(o ...Option) func(http.Handler) http.Handler {\n\topts := options{\n\t\ttracer: apm.DefaultTracer(),\n\t}\n\tfor _, o := range o {\n\t\to(&opts)\n\t}\n\tif opts.requestIgnorer == nil {\n\t\topts.requestIgnorer = apmhttp.NewDynamicServerRequestIgnorer(opts.tracer)\n\t}\n\treturn func(h http.Handler) http.Handler {\n\t\tserverOpts := []apmhttp.ServerOption{\n\t\t\tapmhttp.WithTracer(opts.tracer),\n\t\t\tapmhttp.WithServerRequestName(routeRequestName),\n\t\t\tapmhttp.WithServerRequestIgnorer(opts.requestIgnorer),\n\t\t}\n\t\tif opts.panicPropagation {\n\t\t\tserverOpts = append(serverOpts, apmhttp.WithPanicPropagation())\n\t\t}\n\t\treturn apmhttp.Wrap(\n\t\t\th,\n\t\t\tserverOpts...,\n\t\t)\n\t}\n}", "func Middleware(t *elasticapm.Tracer) mux.MiddlewareFunc {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn &apmhttp.Handler{\n\t\t\tHandler: h,\n\t\t\tRecovery: apmhttp.NewTraceRecovery(t),\n\t\t\tRequestName: routeRequestName,\n\t\t\tTracer: t,\n\t\t}\n\t}\n}", "func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {\n\treturn func(handle http.HandlerFunc) http.HandlerFunc {\n\t\treturn handler(handle).ServeHTTP\n\t}\n}", "func (m MiddlewareFunc) Handler(next http.Handler) http.Handler {\n\treturn m(next)\n}", "func service() typhon.Service {\r\n\trouter := typhon.Router{}\r\n\trouter.GET(\"/oxcross\", serveResponse)\r\n\trouter.GET(\"/healthz\", serveResponse)\r\n\r\n\tsvc := router.Serve().Filter(typhon.ErrorFilter).Filter(typhon.H2cFilter)\r\n\r\n\treturn svc\r\n}", "func (s *Server) wrapMiddleware(h handler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\terr := h(s, w, r)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[Error][Server] %+v\", err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t}\n}", "func Middleware(next HandlerFunc) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tsession, _ := GetCurrentSession(r)\n\t\tnext(session, w, r)\n\t})\n}", "func Middleware() func(http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\t// Put incoming request auth headers into the context or use later\n\t\t\t// to verify signature\n\t\t\treqTs := r.Header.Get(reqTsHeader)\n\t\t\tsignature := r.Header.Get(signatureHeader)\n\t\t\tdid := r.Header.Get(didHeader)\n\t\t\t// didKey is optional\n\t\t\tif reqTs == \"\" && signature == \"\" {\n\t\t\t\tlog.Infof(\"No auth headers found\")\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Store values into context\n\t\t\tctx := context.WithValue(r.Context(), DidCtxKey, did)\n\t\t\tctx = context.WithValue(ctx, ReqTsCtxKey, reqTs)\n\t\t\tctx = context.WithValue(ctx, SignatureCtxKey, signature)\n\n\t\t\t// and call the next with our new context\n\t\t\tr = r.WithContext(ctx)\n\t\t\tnext.ServeHTTP(w, r)\n\n\t\t})\n\t}\n}", "func (l *Logger) Middleware(next http.Handler) http.Handler {\n\treturn httpHandler{\n\t\tlogger: l,\n\t\tnext: next,\n\t}\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next Service) Service {\n\t\treturn loggingMiddleware{logger, next}\n\t}\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next Service) Service {\n\t\treturn loggingMiddleware{logger, next}\n\t}\n}", "func NewMiddlewareWrapper(logger Logger, metrics Metrics, corsOptions *CORSOptions, globals ServiceGlobals) MiddlewareWrapper {\n\tm := &middlewareWrapperImpl{\n\t\tlogger: logger,\n\t\tmetrics: metrics,\n\t\tglobals: globals,\n\t}\n\tm.corsOptions = m.mergeCORSOptions(corsOptions)\n\treturn m\n}", "func Middleware(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tappengineCtx := appengine.NewContext(r)\n\t\tctx := context.WithValue(r.Context(), contextKeyContext, appengineCtx)\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func (client *Client) Middleware() echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tif !client.isAllowedPathToCache(c.Request().URL.String()) {\n\t\t\t\tnext(c)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif client.cacheableMethod(c.Request().Method) {\n\t\t\t\tsortURLParams(c.Request().URL)\n\t\t\t\tkey := generateKey(c.Request().URL.String())\n\t\t\t\tif c.Request().Method == http.MethodPost && c.Request().Body != nil {\n\t\t\t\t\tbody, err := ioutil.ReadAll(c.Request().Body)\n\t\t\t\t\tdefer c.Request().Body.Close()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tnext(c)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\treader := ioutil.NopCloser(bytes.NewBuffer(body))\n\t\t\t\t\tkey = generateKeyWithBody(c.Request().URL.String(), body)\n\t\t\t\t\tc.Request().Body = reader\n\t\t\t\t}\n\n\t\t\t\tparams := c.Request().URL.Query()\n\t\t\t\tif _, ok := params[client.refreshKey]; ok {\n\t\t\t\t\tdelete(params, client.refreshKey)\n\n\t\t\t\t\tc.Request().URL.RawQuery = params.Encode()\n\t\t\t\t\tkey = generateKey(c.Request().URL.String())\n\n\t\t\t\t\tclient.adapter.Release(key)\n\t\t\t\t} else {\n\t\t\t\t\tb, ok := client.adapter.Get(key)\n\t\t\t\t\tresponse := BytesToResponse(b)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tif response.Expiration.After(time.Now()) {\n\t\t\t\t\t\t\tresponse.LastAccess = time.Now()\n\t\t\t\t\t\t\tresponse.Frequency++\n\t\t\t\t\t\t\tclient.adapter.Set(key, response.Bytes(), response.Expiration)\n\n\t\t\t\t\t\t\t//w.WriteHeader(http.StatusNotModified)\n\t\t\t\t\t\t\tfor k, v := range response.Header {\n\t\t\t\t\t\t\t\tc.Response().Header().Set(k, strings.Join(v, \",\"))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tc.Response().WriteHeader(http.StatusOK)\n\t\t\t\t\t\t\tc.Response().Write(response.Value)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tclient.adapter.Release(key)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresBody := new(bytes.Buffer)\n\t\t\t\tmw := io.MultiWriter(c.Response().Writer, resBody)\n\t\t\t\twriter := &bodyDumpResponseWriter{Writer: mw, ResponseWriter: c.Response().Writer}\n\t\t\t\tc.Response().Writer = writer\n\t\t\t\tif err := next(c); err != nil {\n\t\t\t\t\tc.Error(err)\n\t\t\t\t}\n\n\t\t\t\tstatusCode := writer.statusCode\n\t\t\t\tvalue := resBody.Bytes()\n\t\t\t\tif statusCode < 400 {\n\t\t\t\t\tnow := time.Now()\n\n\t\t\t\t\tresponse := Response{\n\t\t\t\t\t\tValue: value,\n\t\t\t\t\t\tHeader: writer.Header(),\n\t\t\t\t\t\tExpiration: now.Add(client.ttl),\n\t\t\t\t\t\tLastAccess: now,\n\t\t\t\t\t\tFrequency: 1,\n\t\t\t\t\t}\n\t\t\t\t\tclient.adapter.Set(key, response.Bytes(), response.Expiration)\n\t\t\t\t}\n\t\t\t\t//for k, v := range writer.Header() {\n\t\t\t\t//\tc.Response().Header().Set(k, strings.Join(v, \",\"))\n\t\t\t\t//}\n\t\t\t\t//c.Response().WriteHeader(statusCode)\n\t\t\t\t//c.Response().Write(value)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif err := next(c); err != nil {\n\t\t\t\tc.Error(err)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func MakeTracingMiddleware(component string) func(http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn MakeTracingHandler(next, component)\n\t}\n}", "func Middleware() func(next echo.HandlerFunc) echo.HandlerFunc {\n\tl := logger.New()\n\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\t// Record the time start time of the middleware invocation\n\t\t\tt1 := time.Now()\n\n\t\t\t// Generate a new UUID that will be used to recognize this particular\n\t\t\t// request\n\t\t\tid, err := uuid.NewV4()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.WithStack(err)\n\t\t\t}\n\n\t\t\t// Create a child logger with the unique UUID created and attach it to\n\t\t\t// the echo.Context. By attaching it to the context it can be fetched by\n\t\t\t// later middleware or handler functions to emit events with a logger\n\t\t\t// that contains this ID. This is useful as it allows us to emit all\n\t\t\t// events with the same request UUID.\n\t\t\tlog := l.ID(id.String())\n\t\t\tc.Set(key, log)\n\n\t\t\t// Execute the next middleware/handler function in the stack.\n\t\t\tif err := next(c); err != nil {\n\t\t\t\tc.Error(err)\n\t\t\t}\n\n\t\t\t// We have now succeeded executing all later middlewares in the stack and\n\t\t\t// have come back to the logger middleware. Record the time at which we\n\t\t\t// came back to this middleware. We can use the difference between t2 and\n\t\t\t// t1 to calculate the request duration.\n\t\t\tt2 := time.Now()\n\n\t\t\t// Get the request IP address.\n\t\t\tvar ipAddress string\n\t\t\tif xff := c.Request().Header.Get(\"x-forwarded-for\"); xff != \"\" {\n\t\t\t\tsplit := strings.Split(xff, \",\")\n\t\t\t\tipAddress = strings.TrimSpace(split[len(split)-1])\n\t\t\t} else {\n\t\t\t\tipAddress = c.Request().RemoteAddr\n\t\t\t}\n\n\t\t\t// Emit a log event with as much metadata as we can.\n\t\t\tlog.Root(logger.Data{\n\t\t\t\t\"status_code\": c.Response().Status,\n\t\t\t\t\"method\": c.Request().Method,\n\t\t\t\t\"path\": c.Request().URL.Path,\n\t\t\t\t\"route\": c.Path(),\n\t\t\t\t\"response_time\": t2.Sub(t1).Seconds() * 1000,\n\t\t\t\t\"referer\": c.Request().Referer(),\n\t\t\t\t\"user_agent\": c.Request().UserAgent(),\n\t\t\t\t\"ip_address\": ipAddress,\n\t\t\t\t\"trace_id\": c.Request().Header.Get(\"x-amzn-trace-id\"),\n\t\t\t}).Info(\"request handled\")\n\n\t\t\t// Succeeded executing the middleware invocation. A nil response\n\t\t\t// represents no errors happened.\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func Wrap(\n\tmiddleware Middleware,\n\thandler Handler,\n) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tmiddleware(handler)(context.Background(), w, r)\n\t}\n}", "func Middleware(next http.Handler, options MiddlewareOptions) http.Handler {\n\treturn &ipFilteringMiddleware{IpFiltering: New(options.Options), options: options, next: next}\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next Service) Service {\n\t\treturn loggingMiddleware{\n\t\t\tlogger,\n\t\t\tnext,\n\t\t}\n\t}\n}", "func (h MiddlewareFunc) Handler(next http.Handler) http.Handler {\n\treturn h(next)\n}", "func (h MiddlewareFunc) Handler(next http.Handler) http.Handler {\n\treturn h(next)\n}", "func (mf MiddlewareFunc) Run(req *Request, handler Handler) (*Response, error) {\n\treturn mf(req, handler)\n}", "func Service() typhon.Service {\n\treturn router.Serve()\n}", "func Middleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next AuthService) AuthService {\n\t\treturn &loggingMiddleware{logger, next}\n\t}\n\n}", "func Middleware() func(http.Handler) http.Handler {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn orhttp.Wrap(\n\t\t\thttp.HandlerFunc(\n\t\t\t\tfunc(w http.ResponseWriter, req *http.Request) {\n\t\t\t\t\th.ServeHTTP(w, req)\n\t\t\t\t}))\n\t}\n}", "func Middleware(store *Store) func(h http.Handler) http.Handler {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(\n\t\t\tw http.ResponseWriter,\n\t\t\tr *http.Request,\n\t\t) {\n\t\t\tctx := r.Context()\n\t\t\tctx = context.WithValue(ctx, contextKey, store)\n\t\t\th.ServeHTTP(w, r.WithContext(ctx))\n\t\t})\n\t}\n}", "func Middleware(fn AppHandler, c interface{}) AppHandler {\n\treturn func(w http.ResponseWriter, r *http.Request) *AppError {\n\t\tr = r.WithContext(context.WithValue(r.Context(), \"env\", c))\n\t\tr = r.WithContext(context.WithValue(r.Context(), \"vars\", mux.Vars(r)))\n\t\treturn fn(w, r)\n\t}\n}", "func svcHandler()", "func (aps *ApiServer) setMiddleware() {\n\t/*\n\t\taps.Engine.Use(func(c *gin.Context) {\n\t\t\tstart := time.Now()\n\t\t\tc.Next()\n\t\t\tend := time.Now()\n\t\t\tlatency := end.Sub(start)\n\t\t\tpath := c.Request.URL.Path\n\t\t\tclientIP := c.ClientIP()\n\t\t\tmethod := c.Request.Method\n\t\t\tstatusCode := c.Writer.Status()\n\t\t\tlogger.Info(\"api request\",\n\t\t\t\tzap.Int(\"status_code\", statusCode),\n\t\t\t\tzap.Duration(\"latency\", latency),\n\t\t\t\tzap.String(\"client_ip\", clientIP),\n\t\t\t\tzap.String(\"method\", method),\n\t\t\t\tzap.String(\"path\", path),\n\t\t\t)\n\t\t})\n\t*/\n\taps.Engine.Use(gin.Recovery())\n}", "func (zm *ZipkinMiddleware) GetMiddlewareHandler() func(http.ResponseWriter, *http.Request, http.HandlerFunc) {\n\treturn func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t\twireContext, err := zm.tracer.Extract(\n\t\t\topentracing.TextMap,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header),\n\t\t)\n\t\tif err != nil {\n\t\t\tcommon.ServerObj.Logger.Debug(\"Error encountered while trying to extract span \", zap.Error(err))\n\t\t\tnext(rw, r)\n\t\t}\n\t\tspan := zm.tracer.StartSpan(r.URL.Path, ext.RPCServerOption(wireContext))\n\t\tdefer span.Finish()\n\t\tctx := opentracing.ContextWithSpan(r.Context(), span)\n\t\tr = r.WithContext(ctx)\n\t\tnext(rw, r)\n\t}\n}", "func Middleware(db Datastore) func(http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tctx := context.WithValue(r.Context(), dbCtxKey, db)\n\n\t\t\t// and call the next with our new context\n\t\t\tr = r.WithContext(ctx)\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func Middleware(f MiddlewareFunc) {\n\tDefaultMux.Middleware(f)\n}", "func Middleware(e *echo.Echo) {\n\te.Use(\n\t\tmiddleware.Logger(),\n\t\tmiddleware.Recover(),\n\t\tcontext.InjectBezuncAPIContext,\n\t)\n}", "func New(db *database.DB, m ...Middleware) Service {\n\tstore := NewStore(db, database.Users)\n\tmodel := NewModel(store)\n\tservice := NewService(model)\n\tservice = Decorate(service, m...)\n\treturn service\n}", "func NewMiddleWare(\n\tcustomClaimsFactory CustomClaimsFactory,\n\tvalidFunction CustomClaimsValidateFunction,\n) *Middleware {\n\treturn &Middleware{\n\t\t// todo: customize signing algorithm\n\t\tSigningAlgorithm: \"HS256\",\n\t\tJWTHeaderKey: \"Authorization\",\n\t\tJWTHeaderPrefixWithSplitChar: \"Bearer \",\n\t\tSigningKeyString: GetSignKey(),\n\t\tSigningKey: []byte(GetSignKey()),\n\t\tcustomClaimsFactory: customClaimsFactory,\n\t\tvalidFunction: validFunction,\n\t\t// MaxRefresh: default zero\n\t}\n}", "func New(middleware []Middleware) ApiService {\n\tvar svc ApiService = NewBasicApiService()\n\tfor _, m := range middleware {\n\t\tsvc = m(svc)\n\t}\n\treturn svc\n}", "func (c *Config) Middleware(next http.Handler) http.Handler {\n\tfun := func(w http.ResponseWriter, r *http.Request) {\n\t\tc.l.Lock()\n\t\texpirable, ok := c.content[r.URL.Path]\n\t\tif !ok {\n\t\t\texpirable = futures.NewExpirable(c.timeout,\n\t\t\t\tfunc() interface{} {\n\t\t\t\t\treturn execute(r, next)\n\t\t\t\t})\n\t\t\tc.content[r.URL.Path] = expirable\n\t\t}\n\t\tc.l.Unlock()\n\t\trecorded := expirable.Read().(*httptest.ResponseRecorder)\n\t\tfor k, v := range recorded.Header() {\n\t\t\tw.Header()[k] = v\n\t\t}\n\t\tw.WriteHeader(recorded.Code)\n\t\tw.Write(recorded.Body.Bytes())\n\t}\n\treturn http.HandlerFunc(fun)\n}", "func wrap(handler http.Handler) mwFunc {\n\tif handler == nil {\n\t\treturn nil\n\t}\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params, next httprouter.Handle) {\n\t\thandler.ServeHTTP(w, r)\n\t\tnext(w, r, ps)\n\t}\n}", "func NewMiddleware() Middleware {\n\treturn Middleware{}\n}", "func Use(filter HandlerFunc) {\n\tApp.middlewares = append(App.middlewares, filter)\n}", "func Middleware(store sessions.Store) echo.MiddlewareFunc {\n\tc := DefaultConfig\n\tc.Store = store\n\treturn MiddlewareWithConfig(c)\n}", "func (middleware *Middleware) Middleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif urlBlacklisted(r.RequestURI) {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tnow := time.Now().UTC()\n\t\tsw := &customResponseWriter{ResponseWriter: w}\n\t\trequestID := requestID()\n\t\tctx := context.WithValue(r.Context(), \"request-id\", requestID)\n\t\tr = r.WithContext(ctx)\n\t\tnext.ServeHTTP(sw, r)\n\t\tfinishTime := time.Now().UTC()\n\n\t\tdefer func() {\n\t\t\tgo func(req *http.Request, sw *customResponseWriter) {\n\t\t\t\tvar match mux.RouteMatch\n\t\t\t\tif middleware.router.Match(r, &match) && match.Route != nil {\n\t\t\t\t\tvar routeName string\n\t\t\t\t\trouteName = match.Route.GetName()\n\t\t\t\t\tif len(routeName) == 0 {\n\t\t\t\t\t\tif r, err := match.Route.GetPathTemplate(); err == nil {\n\t\t\t\t\t\t\trouteName = r\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\trecord := &Record{\n\t\t\t\t\t\tRouteName: routeName,\n\t\t\t\t\t\tIPAddr: req.RemoteAddr,\n\t\t\t\t\t\tTimestamp: finishTime,\n\t\t\t\t\t\tMethod: req.Method,\n\t\t\t\t\t\tURI: req.RequestURI,\n\t\t\t\t\t\tProtocol: req.Proto,\n\t\t\t\t\t\tReferer: req.Referer(),\n\t\t\t\t\t\tUserAgent: req.UserAgent(),\n\t\t\t\t\t\tStatus: sw.status,\n\t\t\t\t\t\tElapsedTime: finishTime.Sub(now),\n\t\t\t\t\t\tResponseBytes: sw.length,\n\t\t\t\t\t\tRequestID: requestID,\n\t\t\t\t\t}\n\n\t\t\t\t\tmiddleware.processHooks(record)\n\t\t\t\t}\n\t\t\t}(r, sw)\n\t\t}()\n\t})\n}", "func (c *Client) Middleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == \"GET\" || r.Method == \"\" {\n\t\t\tprefix, key := c.GeneratePrefixAndKey(r)\n\t\t\tctxlog := c.log.WithFields(log.Fields{\"prefix\": prefix, \"key\": key})\n\t\t\tparams := r.URL.Query()\n\t\t\tif _, ok := params[c.refreshKey]; ok {\n\t\t\t\tctxlog.Debug(\"refresh key found, releasing\")\n\t\t\t\tdelete(params, c.refreshKey)\n\n\t\t\t\tr.URL.RawQuery = params.Encode()\n\t\t\t\tkey = generateKey(r.URL.String())\n\n\t\t\t\tc.adapter.Release(prefix, key)\n\t\t\t} else {\n\t\t\t\tb, ok := c.adapter.Get(prefix, key)\n\t\t\t\tresponse := BytesToResponse(b)\n\t\t\t\tif ok {\n\t\t\t\t\tif response.Expiration.After(time.Now()) {\n\t\t\t\t\t\tctxlog.Debug(\"serving from cache\")\n\t\t\t\t\t\tresponse.LastAccess = time.Now()\n\t\t\t\t\t\tresponse.Frequency++\n\t\t\t\t\t\tc.adapter.Set(prefix, key, response.Bytes())\n\n\t\t\t\t\t\t//w.WriteHeader(http.StatusNotModified)\n\t\t\t\t\t\tfor k, v := range response.Header {\n\t\t\t\t\t\t\tw.Header().Set(k, strings.Join(v, \",\"))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tw.Header().Set(\"X-Cached-At\", response.CachedAt.Format(time.RFC822Z))\n\t\t\t\t\t\tw.Write(response.Value)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tctxlog.Debug(\"requested object is in cache, but expried - releasing\")\n\t\t\t\t\tc.adapter.Release(prefix, key)\n\t\t\t\t}\n\t\t\t}\n\t\t\tctxlog.Debug(\"requested object is not in cache or expired - taking it from DB\")\n\t\t\tresponse, value := c.PutItemToCache(next, r, prefix, key)\n\t\t\tfor k, v := range response.Header {\n\t\t\t\tw.Header().Set(k, strings.Join(v, \",\"))\n\t\t\t}\n\t\t\tw.Header().Set(\"X-Cached-At\", time.Now().Format(time.RFC822Z))\n\t\t\tw.WriteHeader(response.StatusCode)\n\t\t\tw.Write(value)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (s *JSONService) JSONMiddleware(j server.JSONEndpoint) server.JSONEndpoint {\n\treturn func(r *http.Request) (int, interface{}, error) {\n\n\t\tstatus, res, err := j(r)\n\t\tif err != nil {\n\t\t\tserver.LogWithFields(r).WithFields(logrus.Fields{\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"problems with serving request\")\n\t\t\treturn http.StatusServiceUnavailable, nil, &jsonErr{\"sorry, this service is unavailable\"}\n\t\t}\n\n\t\tserver.LogWithFields(r).Info(\"success!\")\n\t\treturn status, res, nil\n\t}\n}", "func New(cfg Config, reg prometheus.Registerer) Middleware {\n\t// If no registerer then set the default one.\n\tif reg == nil {\n\t\treg = prometheus.DefaultRegisterer\n\t}\n\n\t// Validate the configuration.\n\tcfg.validate()\n\n\t// Create our middleware with all the configuration options.\n\tm := &middleware{\n\t\thttpRequestHistogram: prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\t\tNamespace: cfg.Prefix,\n\t\t\tSubsystem: \"http\",\n\t\t\tName: \"request_duration_seconds\",\n\t\t\tHelp: \"The latency of the HTTP requests.\",\n\t\t\tBuckets: cfg.Buckets,\n\t\t}, []string{\"handler\", \"method\", \"code\"}),\n\n\t\tcfg: cfg,\n\t\treg: reg,\n\t}\n\n\t// Register all the middleware metrics on prometheus registerer.\n\tm.registerMetrics()\n\n\treturn m\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next VentasService) VentasService {\n\t\treturn &loggingMiddleware{logger, next}\n\t}\n\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next Service) Service {\n\t\treturn loggingMiddleware{\n\t\t\tnext: next,\n\t\t\tlogger: logger,\n\t\t}\n\t}\n}", "func NewMiddlewareProviderService(\n\tlogger *zap.Logger,\n\tlogMessageDetails bool,\n\tdateTimeFormat string) (MiddlewareProviderContract, error) {\n\tif logger == nil {\n\t\treturn nil, commonErrors.NewArgumentNilError(\"logger\", \"logger is required\")\n\t}\n\n\tif dateTimeFormat == \"\" {\n\t\tdateTimeFormat = time.RFC3339Nano\n\t}\n\n\treturn &middlewareProviderService{\n\t\tlogger: logger,\n\t\tlogMessageDetails: logMessageDetails,\n\t\tdateTimeFormat: dateTimeFormat,\n\t}, nil\n}", "func Middleware(ce *casbin.Enforcer, sc DataSource) echo.MiddlewareFunc {\n\tc := DefaultConfig\n\tc.Enforcer = ce\n\tc.Source = sc\n\treturn MiddlewareWithConfig(c)\n}", "func Middleware(next http.Handler) http.Handler {\n\t// requests that go through it.\n\treturn nethttp.Middleware(opentracing.GlobalTracer(),\n\t\tnext,\n\t\tnethttp.OperationNameFunc(func(r *http.Request) string {\n\t\t\treturn \"HTTP \" + r.Method + \" \" + r.URL.String()\n\t\t}))\n}", "func Middleware(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\ttracer := opentracing.GlobalTracer()\n\t\toperationName := fmt.Sprintf(\"%s %s%s\", req.Method, req.Host, req.URL.Path)\n\n\t\tvar span opentracing.Span\n\t\tvar ctx context.Context\n\t\tif spanCtx, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header)); err != nil {\n\t\t\tspan, ctx = opentracing.StartSpanFromContext(req.Context(), operationName)\n\t\t\text.SpanKindRPCServer.Set(span)\n\t\t} else {\n\t\t\tspan = tracer.StartSpan(operationName, ext.RPCServerOption((spanCtx)))\n\t\t\tctx = opentracing.ContextWithSpan(req.Context(), span)\n\t\t\text.SpanKindRPCClient.Set(span)\n\t\t}\n\n\t\tbody, _ := ioutil.ReadAll(req.Body)\n\t\tbodyString := string(golib.MaskJSONPassword(body))\n\t\tbodyString = golib.MaskPassword(bodyString)\n\n\t\tisRemoveBody, ok := req.Context().Value(\"remove-tag-body\").(bool)\n\t\tif ok {\n\t\t\tif !isRemoveBody {\n\t\t\t\tspan.SetTag(\"body\", bodyString)\n\t\t\t}\n\t\t} else {\n\t\t\tspan.SetTag(\"body\", bodyString)\n\t\t}\n\n\t\treq.Body = ioutil.NopCloser(bytes.NewBuffer(body)) // reuse body\n\n\t\tspan.SetTag(\"http.headers\", req.Header)\n\t\text.HTTPUrl.Set(span, req.Host+req.RequestURI)\n\t\text.HTTPMethod.Set(span, req.Method)\n\n\t\tspan.LogEvent(\"start_handling_request\")\n\n\t\tdefer func() {\n\t\t\tspan.LogEvent(\"complete_handling_request\")\n\t\t\tspan.Finish()\n\t\t}()\n\n\t\th.ServeHTTP(w, req.WithContext(ctx))\n\t})\n}", "func NewInstrumentingService(counter metrics.Counter, latency metrics.Histogram, countResult metrics.Histogram, s Service) Service {\n\treturn &instrumentingMiddleware{\n\t\trequestCount: counter,\n\t\trequestLatency: latency,\n\t\tcountResult: countResult,\n\t\tnext: s,\n\t}\n}", "func Middleware(handler http.Handler) http.Handler {\n\twrappedHandler := func(w http.ResponseWriter, r *http.Request) {\n\t\t// get a new context with our trace from the request, and add common fields\n\t\tctx, span := common.StartSpanOrTraceFromHTTP(r)\n\t\tdefer span.Send()\n\t\t// push the context with our trace and span on to the request\n\t\tr = r.WithContext(ctx)\n\n\t\t// replace the writer with our wrapper to catch the status code\n\t\twrappedWriter := common.NewResponseWriter(w)\n\n\t\t// get bits about the handler\n\t\thandler := middleware.Handler(ctx)\n\t\tif handler == nil {\n\t\t\tspan.AddField(\"handler.name\", \"http.NotFound\")\n\t\t\thandler = http.NotFoundHandler()\n\t\t} else {\n\t\t\thType := reflect.TypeOf(handler)\n\t\t\tspan.AddField(\"handler.type\", hType.String())\n\t\t\tname := runtime.FuncForPC(reflect.ValueOf(handler).Pointer()).Name()\n\t\t\tspan.AddField(\"handler.name\", name)\n\t\t\tspan.AddField(\"name\", name)\n\t\t}\n\t\t// find any matched patterns\n\t\tpm := middleware.Pattern(ctx)\n\t\tif pm != nil {\n\t\t\t// TODO put a regex on `p.String()` to pull out any `:foo` and then\n\t\t\t// use those instead of trying to pull them out of the pattern some\n\t\t\t// other way\n\t\t\tif p, ok := pm.(*pat.Pattern); ok {\n\t\t\t\tspan.AddField(\"goji.pat\", p.String())\n\t\t\t\tspan.AddField(\"goji.methods\", p.HTTPMethods())\n\t\t\t\tspan.AddField(\"goji.path_prefix\", p.PathPrefix())\n\t\t\t\tpatvar := strings.TrimPrefix(p.String(), p.PathPrefix()+\":\")\n\t\t\t\tspan.AddField(\"goji.pat.\"+patvar, pat.Param(r, patvar))\n\t\t\t} else {\n\t\t\t\tspan.AddField(\"pat\", \"NOT pat.Pattern\")\n\n\t\t\t}\n\t\t}\n\t\t// TODO get all the parameters and their values\n\t\thandler.ServeHTTP(wrappedWriter.Wrapped, r)\n\t\tif wrappedWriter.Status == 0 {\n\t\t\twrappedWriter.Status = 200\n\t\t}\n\t\tspan.AddField(\"response.status_code\", wrappedWriter.Status)\n\t}\n\treturn http.HandlerFunc(wrappedHandler)\n}", "func (s *server) middleware(n httprouter.Handle) httprouter.Handle {\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\t\t// Log the basics\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"method\": r.Method,\n\t\t\t\"remote-addr\": r.RemoteAddr,\n\t\t\t\"http-protocol\": r.Proto,\n\t\t\t\"headers\": r.Header,\n\t\t\t\"content-length\": r.ContentLength,\n\t\t}).Debugf(\"HTTP Request to %s\", r.URL)\n\n\t\tif r.ContentLength > 0 {\n\t\t\t// Dump payload into logs for visibility\n\t\t\tb, err := ioutil.ReadAll(r.Body)\n\t\t\tif err == nil {\n\t\t\t\tlog.Debugf(\"Dumping Payload for request to %s: %s\", r.URL, b)\n\t\t\t}\n\t\t}\n\n\t\t// Call registered handler\n\t\tn(w, r, ps)\n\t}\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next FaultService) FaultService {\n\t\treturn &loggingMiddleware{logger, next}\n\t}\n\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next Service) Service {\n\t\treturn &loggingMiddleware{\n\t\t\tlogger: logger,\n\t\t\tnext: next,\n\t\t}\n\t}\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next Service) Service {\n\t\treturn &loggingMiddleware{\n\t\t\tlogger: logger,\n\t\t\tnext: next,\n\t\t}\n\t}\n}", "func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc {\n\treturn func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) (err error) {\n\t\t\tm(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tc.SetRequest(r)\n\t\t\t\tc.SetResponse(newResponse(w))\n\t\t\t\terr = next(c)\n\t\t\t})).ServeHTTP(c.Response(), c.Request())\n\t\t\treturn\n\t\t}\n\t}\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next UsersService) UsersService {\n\t\treturn &loggingMiddleware{logger, next}\n\t}\n\n}", "func Middleware() func(http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\ttokenString := r.Header.Get(\"Authorization\")\n\n\t\t\tif tokenString == \"\" {\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif len(tokenString) == 0 {\n\t\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\t\tw.Write([]byte(\"Missing Authorization Header\"))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttokenString = strings.Replace(tokenString, \"Bearer \", \"\", 1)\n\t\t\t_, err := auth.ValidateToken(tokenString)\n\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\t\tw.Write([]byte(\"Error verifying JWT token: \" + err.Error()))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tctx := context.WithValue(r.Context(), contextTokenKey, tokenString)\n\t\t\tr = r.WithContext(ctx)\n\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func New(middleware []Middleware) AddService {\n\tvar svc AddService = NewBasicAddService()\n\tfor _, m := range middleware {\n\t\tsvc = m(svc)\n\t}\n\treturn svc\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next Service) Service {\n\t\treturn &loggingMiddleware{\n\t\t\tnext: next,\n\t\t\tlogger: logger,\n\t\t}\n\t}\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next Service) Service {\n\t\treturn &loggingMiddleware{\n\t\t\tnext: next,\n\t\t\tlogger: logger,\n\t\t}\n\t}\n}", "func WrapMiddlewareFromHandler(h HandlerFunc) Middleware {\n\treturn MiddlewareFunc(func(next Handler) Handler {\n\t\treturn HandlerFunc(func(c Context) error {\n\t\t\tif err := h.Handle(c); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn next.Handle(c)\n\t\t})\n\t})\n}", "func LoggingMiddleware(logger log.Logger) Middleware {\n\treturn func(next BalanceService) BalanceService {\n\t\treturn &loggingMiddleware{logger, next}\n\t}\n\n}", "func (s *State) Middleware(h middleware.Handler) middleware.Handler {\n\treturn func(c context.Context, rw http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\t\tstate, settings := s.checkSettings(c)\n\t\th(c, rw, r, p)\n\t\tif settings.Enabled {\n\t\t\ts.flushIfNeeded(c, state, settings)\n\t\t}\n\t}\n}", "func useMiddlewareHandler(h http.Handler, mw ...Middleware) http.Handler {\n\tfor i := range mw {\n\t\th = mw[len(mw)-1-i](h)\n\t}\n\n\treturn h\n}", "func targetService(endpoint, authEndpoint string, authPK *bakery.PublicKey) (http.Handler, error) {\n\tkey, err := bakery.GenerateKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpkLocator := httpbakery.NewThirdPartyLocator(nil, nil)\n\tpkLocator.AllowInsecure()\n\tb := bakery.New(bakery.BakeryParams{\n\t\tKey: key,\n\t\tLocation: endpoint,\n\t\tLocator: pkLocator,\n\t\tChecker: httpbakery.NewChecker(),\n\t\tAuthorizer: authorizer{\n\t\t\tthirdPartyLocation: authEndpoint,\n\t\t},\n\t})\n\tmux := http.NewServeMux()\n\tsrv := &targetServiceHandler{\n\t\tchecker: b.Checker,\n\t\toven: &httpbakery.Oven{Oven: b.Oven},\n\t\tauthEndpoint: authEndpoint,\n\t}\n\tmux.Handle(\"/gold/\", srv.auth(http.HandlerFunc(srv.serveGold)))\n\tmux.Handle(\"/silver/\", srv.auth(http.HandlerFunc(srv.serveSilver)))\n\treturn mux, nil\n}", "func (hs *HTTPSpanner) Decorate(appName string, next http.Handler) http.Handler {\n\tif hs == nil {\n\t\t// allow DI of nil values to shut off money trace\n\t\treturn next\n\t}\n\n\treturn http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {\n\t\tif span, err := hs.SD(request); err == nil {\n\t\t\tspan.AppName, span.Name = appName, \"ServeHTTP\"\n\t\t\ttracker := hs.Start(request.Context(), span)\n\n\t\t\tctx := context.WithValue(request.Context(), contextKeyTracker, tracker)\n\n\t\t\ts := simpleResponseWriter{\n\t\t\t\tcode: http.StatusOK,\n\t\t\t\tResponseWriter: response,\n\t\t\t}\n\n\t\t\tnext.ServeHTTP(s, request.WithContext(ctx))\n\n\t\t\t//TODO: application and not library code should finish the above tracker\n\t\t\t//such that information on it could be forwarded\n\t\t\t//once confirmed, delete the below\n\n\t\t\t// tracker.Finish(Result{\n\t\t\t// \tName: \"ServeHTTP\",\n\t\t\t// \tAppName: appName,\n\t\t\t// \tCode: s.code,\n\t\t\t// \tSuccess: s.code < 400,\n\t\t\t// })\n\n\t\t} else {\n\t\t\tnext.ServeHTTP(response, request)\n\t\t}\n\t})\n}" ]
[ "0.67944986", "0.67008346", "0.6686849", "0.6646141", "0.6577811", "0.64825916", "0.6465787", "0.63078403", "0.62981313", "0.62688965", "0.6257751", "0.62544674", "0.62497014", "0.62410784", "0.62030065", "0.6193984", "0.6193984", "0.6141814", "0.61197424", "0.6118263", "0.6118263", "0.6106121", "0.6051151", "0.60493886", "0.60493886", "0.6041746", "0.6040312", "0.6014423", "0.6012479", "0.60118604", "0.59664685", "0.596547", "0.59523237", "0.59303284", "0.5851129", "0.5840279", "0.58355325", "0.5818257", "0.579839", "0.5786013", "0.577897", "0.577897", "0.57747144", "0.5774574", "0.57738084", "0.57722676", "0.57672346", "0.57663834", "0.5764324", "0.5762322", "0.57545537", "0.57545537", "0.5751634", "0.5732084", "0.57274854", "0.57190025", "0.5714834", "0.5714372", "0.5702344", "0.5700693", "0.5699692", "0.569954", "0.5697513", "0.56805384", "0.56666476", "0.56658787", "0.5663023", "0.5648172", "0.5646747", "0.56410784", "0.56220675", "0.561693", "0.5609324", "0.56017154", "0.55935", "0.5592454", "0.5591575", "0.5589572", "0.55888313", "0.5588083", "0.5583806", "0.557754", "0.55638903", "0.5540396", "0.5533292", "0.55310565", "0.55308443", "0.5517856", "0.5517856", "0.5510581", "0.55096865", "0.55090916", "0.55088127", "0.5508087", "0.5508087", "0.5502975", "0.5501371", "0.5495603", "0.54941905", "0.54779416", "0.5475102" ]
0.0
-1
withClerk invokes the specified callback with a clerk that manages the specified queue. If there is no such clerk, withClerk first creates one. The clerk's reference count is incremented for the duration of the callback. withClerk returns whatever the callback returns.
func (registry *Registry) withClerk(queue string, callback func(*clerk) error) error { registry.mutex.Lock() entry, found := registry.queues[queue] if !found { entry = &refCountedClerk{ Clerk: clerk{ // TODO: context Enqueue: make(chan messageSend), Dequeue: make(chan messageReceive), Registry: registry, Queue: queue, }, RefCount: 0, } go entry.Clerk.Run() registry.queues[queue] = entry } entry.RefCount++ registry.mutex.Unlock() result := callback(&entry.Clerk) registry.mutex.Lock() entry.RefCount-- registry.mutex.Unlock() return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *ModuleManager) CallWithCallback(topic string, f, cb interface{}, cbParams, params []interface{}) (err error) {\n\tif m := this.GetModule(topic); m != nil {\n\t\terr = m.CallWithCallback(f, cb, cbParams, params)\n\t} else {\n\t\t// fmt.Println(this)\n\t\terr = Post.PutQueueWithCallback(f, cb, cbParams, params...)\n\t}\n\treturn\n}", "func (client *Client) GetClusterQueueInfoWithCallback(request *GetClusterQueueInfoRequest, callback func(response *GetClusterQueueInfoResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *GetClusterQueueInfoResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.GetClusterQueueInfo(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func GoCallbackWrapper(ptr_q *unsafe.Pointer, ptr_nfad *unsafe.Pointer) int {\n q := (*Queue)(unsafe.Pointer(ptr_q))\n payload := build_payload(q.c_gh, ptr_nfad)\n return q.cb(payload)\n}", "func (q *Queue) SetCallback(cb Callback) error {\n\tq.cb = cb\n\treturn nil\n}", "func (ac *asyncCallbacksHandler) push(f func()) {\n\tac.cbQueue <- f\n}", "func (r *RabbitMq) registerCallback() {\r\n\tr.RabbitMqChannel.QueueDeclare(\r\n\t\t\"callback-mq-producer\",\r\n\t\ttrue,\r\n\t\tfalse,\r\n\t\tfalse,\r\n\t\tfalse,\r\n\t\tnil,\r\n\t)\r\n\tr.StartConsumeCallback()\r\n\tlog.Println(\"Create Queue callback\")\r\n}", "func (x *MQQueueManager) Ctl(goOperation int32, goctlo *MQCTLO) error {\n\tvar mqrc C.MQLONG\n\tvar mqcc C.MQLONG\n\tvar mqOperation C.MQLONG\n\tvar mqctlo C.MQCTLO\n\n\tmqOperation = C.MQLONG(goOperation)\n\tcopyCTLOtoC(&mqctlo, goctlo)\n\n\t// Need to make sure control information is available before the callback\n\t// is enabled. So this gets setup even if the MQCTL fails.\n\tkey := makePartialKey(x.hConn)\n\tmapLock()\n\tfor k, info := range cbMap {\n\t\tif strings.HasPrefix(k, key) {\n\t\t\tinfo.connectionArea = goctlo.ConnectionArea\n\t\t}\n\t}\n\tmapUnlock()\n\n\tC.MQCTL(x.hConn, mqOperation, (C.PMQVOID)(unsafe.Pointer(&mqctlo)), &mqcc, &mqrc)\n\n\tmqreturn := MQReturn{MQCC: int32(mqcc),\n\t\tMQRC: int32(mqrc),\n\t\tverb: \"MQCTL\",\n\t}\n\n\tif mqcc != C.MQCC_OK {\n\t\treturn &mqreturn\n\t}\n\n\treturn nil\n}", "func (client *Client) RecognizeFlowerWithCallback(request *RecognizeFlowerRequest, callback func(response *RecognizeFlowerResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *RecognizeFlowerResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.RecognizeFlower(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) GetClusterQueueInfoWithChan(request *GetClusterQueueInfoRequest) (<-chan *GetClusterQueueInfoResponse, <-chan error) {\n\tresponseChan := make(chan *GetClusterQueueInfoResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.GetClusterQueueInfo(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (ac *asyncCallbacksHandler) run() {\n\tfor {\n\t\tf := <-ac.cbQueue\n\t\tif f == nil {\n\t\t\treturn\n\t\t}\n\t\tf()\n\t}\n}", "func (p *asyncPipeline) DoCmdWithCallback(cmder redis.Cmder, callback func(redis.Cmder) error) error {\n\n\tif cmder == nil {\n\t\treturn fmt.Errorf(\"Cmder passing in is nil\")\n\t}\n\n\tcmders := make([]redis.Cmder, 0)\n\tcmders = append(cmders, cmder)\n\tp.chQueue <- &asyncPipelineCmd{\n\t\tcmders: cmders,\n\t\tcallback: func(cmders []redis.Cmder) error {\n\t\t\tfor _, cmder := range cmders {\n\t\t\t\tif callback != nil {\n\t\t\t\t\tif err := callback(cmder); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn nil\n}", "func WithConcurrency(concurrency int) Option {\n\treturn func(c *queue) {\n\t\tc.concurrency = concurrency\n\t}\n}", "func (q *Queue) Queue(action func()) {\n\tif !q.stopped {\n\t\tq.pendingC <- action\n\t} else {\n\t\tq.l.Error(\"queue failed: queue is stopped, cannot queue more elements\")\n\t}\n}", "func (client *Client) GetTotalQueueReportWithCallback(request *GetTotalQueueReportRequest, callback func(response *GetTotalQueueReportResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *GetTotalQueueReportResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.GetTotalQueueReport(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) CreateFabricChannelWithCallback(request *CreateFabricChannelRequest, callback func(response *CreateFabricChannelResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateFabricChannelResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateFabricChannel(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func consumer(queueChannel chan int, doneChannel chan bool) {\n\tdefer reset.Done()\n\n\tvar counter = 0\n\tfor value := range queueChannel {\n\t\tprintln(\"Consuming value from queue: \" + strconv.Itoa(value))\n\t\tcounter++\n\t\tif counter == 23 {\n\t\t\tprintln(\"Consumed 23 values from queue Channel, stop consuming.\")\n\t\t\tclose(doneChannel)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (ec *EstablishingController) QueueCRD(key string, timeout time.Duration) {\r\n\tec.queue.AddAfter(key, timeout)\r\n}", "func (client *Client) QueryInnerJobWithCallback(request *QueryInnerJobRequest, callback func(response *QueryInnerJobResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *QueryInnerJobResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.QueryInnerJob(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (clt *Client) redisListener(buf io.ReadWriter, queue chan *lib.Request) {\n\tlib.Debugf(\"Net listener started\")\n\tdefer clt.close() // Will force to close net connection\n\n\treader := redis.NewRespReader(buf)\n\tfor req := range queue {\n\t\tr := reader.Read()\n\t\tif req == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif r.Err != nil && r.IsType(redis.IOErr) {\n\t\t\tif redis.IsTimeout(r) {\n\t\t\t\tlog.Printf(\"Timeout (%d secs) at %s\", clt.config.Timeout, clt.config.Host())\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Error with server %s connection: %s\", clt.config.Host(), r.Err)\n\t\t\t}\n\t\t\tif req.Conn != nil {\n\t\t\t\trespKO.WriteTo(req.Conn)\n\t\t\t}\n\t\t\tclt.disconnect()\n\t\t\treturn\n\t\t}\n\n\t\tif clt.config.Compress || clt.config.Uncompress || clt.config.Gzip != 0 || clt.config.Gunzip {\n\t\t\tr.Uncompress()\n\t\t}\n\n\t\tif req.Conn != nil {\n\t\t\tr.WriteTo(req.Conn)\n\t\t}\n\t\tr.ReleaseBuffers()\n\t}\n\tlib.Debugf(\"Net listener exiting\")\n}", "func (client *Client) AddBsnFabricBizChainWithCallback(request *AddBsnFabricBizChainRequest, callback func(response *AddBsnFabricBizChainResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *AddBsnFabricBizChainResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.AddBsnFabricBizChain(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (c *consulClient) CAS(ctx context.Context, key string, out interface{}, f CASCallback) error {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"Consul CAS\", opentracing.Tag{Key: \"key\", Value: key})\n\tdefer span.Finish()\n\tvar (\n\t\tindex = uint64(0)\n\t\tretries = 10\n\t\tretry = true\n\t\tintermediate interface{}\n\t)\n\tfor i := 0; i < retries; i++ {\n\t\tkvp, _, err := c.kv.Get(key, queryOptions)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error getting %s: %v\", key, err)\n\t\t\tcontinue\n\t\t}\n\t\tif kvp != nil {\n\t\t\tif err := json.NewDecoder(bytes.NewReader(kvp.Value)).Decode(out); err != nil {\n\t\t\t\tlog.Errorf(\"Error deserialising %s: %v\", key, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tindex = kvp.ModifyIndex // if key doesn't exist, index will be 0\n\t\t\tintermediate = out\n\t\t}\n\n\t\tintermediate, retry, err = f(intermediate)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error CASing %s: %v\", key, err)\n\t\t\tif !retry {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif intermediate == nil {\n\t\t\tpanic(\"Callback must instantiate value!\")\n\t\t}\n\n\t\tvalue := bytes.Buffer{}\n\t\tif err := json.NewEncoder(&value).Encode(intermediate); err != nil {\n\t\t\tlog.Errorf(\"Error serialising value for %s: %v\", key, err)\n\t\t\tcontinue\n\t\t}\n\t\tok, _, err := c.kv.CAS(&consul.KVPair{\n\t\t\tKey: key,\n\t\t\tValue: value.Bytes(),\n\t\t\tModifyIndex: index,\n\t\t}, writeOptions)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error CASing %s: %v\", key, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !ok {\n\t\t\tlog.Errorf(\"Error CASing %s, trying again %d\", key, index)\n\t\t\tcontinue\n\t\t}\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"Failed to CAS %s\", key)\n}", "func (client *Client) ContextQueryLogWithCallback(request *ContextQueryLogRequest, callback func(response *ContextQueryLogResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ContextQueryLogResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ContextQueryLog(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) AssociateAclsWithListenerWithCallback(request *AssociateAclsWithListenerRequest, callback func(response *AssociateAclsWithListenerResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *AssociateAclsWithListenerResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.AssociateAclsWithListener(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func NewSucker(amqpURI, queueName, ctag string, work func(delivery amqp.Delivery) error) (*Spaceballz, error) {\n\tc := &Spaceballz{\n\t\tconn: nil,\n\t\tchannel: nil,\n\t\ttag: ctag,\n\t\tdone: make(chan error),\n\t\tWork: work,\n\t}\n\n\tvar err error\n\n\tlog.Printf(\"dialing %q\", amqpURI)\n\tc.conn, err = amqp.Dial(amqpURI)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Dial: %s\", err)\n\t}\n\n\tgo func() {\n\t\tfmt.Printf(\"closing: %s\", <-c.conn.NotifyClose(make(chan *amqp.Error)))\n\t}()\n\n\tlog.Printf(\"got Connection, getting Channel\")\n\tc.channel, err = c.conn.Channel()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Channel: %s\", err)\n\t}\n\n\tdeliveries, err := c.channel.Consume(\n\t\tqueueName, // name\n\t\tc.tag, // consumerTag,\n\t\tfalse, // noAck\n\t\tfalse, // exclusive\n\t\tfalse, // noLocal\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Queue Consume: %s\", err)\n\t}\n\n\tgo c.handle(deliveries, c.done)\n\n\treturn c, nil\n}", "func Call(f func()) {\n\tcheckRun()\n\tdone := make(chan struct{})\n\tcallQueue <- func() {\n\t\tf()\n\t\tdone <- struct{}{}\n\t}\n\t<-done\n}", "func (client *Client) GetClusterMetricsWithCallback(request *GetClusterMetricsRequest, callback func(response *GetClusterMetricsResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *GetClusterMetricsResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.GetClusterMetrics(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (p *asyncPipeline) DoCmdsWithCallback(cmders []redis.Cmder, callback func([]redis.Cmder) error) error {\n\n\tfor _, cmder := range cmders {\n\t\tif cmder == nil {\n\t\t\treturn fmt.Errorf(\"Cmder passing in is nil\")\n\t\t}\n\t}\n\tp.chQueue <- &asyncPipelineCmd{\n\t\tcmders: cmders,\n\t\tcallback: callback,\n\t}\n\n\treturn nil\n}", "func (c *QueuedChan) run() {\n\t// Notify close channel coroutine.\n\tdefer close(c.done)\n\n\tfor {\n\t\tvar elem *list.Element\n\t\tvar item interface{}\n\t\tvar popc chan<- interface{}\n\n\t\t// Get front element of the queue.\n\t\tif elem = c.Front(); nil != elem {\n\t\t\tpopc, item = c.popc, elem.Value\n\t\t}\n\n\t\tselect {\n\t\t// Put the new object into the end of queue.\n\t\tcase i := <-c.pushc:\n\t\t\tc.PushBack(i)\n\t\t// Remove the front element from queue if send out success\n\t\tcase popc <- item:\n\t\t\tc.List.Remove(elem)\n\t\t// Control command\n\t\tcase cmd := <-c.ctrlc:\n\t\t\tc.control(cmd)\n\t\t// Channel is closed\n\t\tcase <-c.close:\n\t\t\treturn\n\t\t}\n\t\t// Update channel length\n\t\tatomic.StoreInt32(&c.len, int32(c.List.Len()))\n\t}\n}", "func WithQueue(queue workqueue.RateLimitingInterface) Option {\n\treturn func(config *queueInformerConfig) {\n\t\tconfig.queue = queue\n\t}\n}", "func (b *testBroker) queue(pipe *Pipeline) *testQueue {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tq, ok := b.queues[pipe]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn q\n}", "func worker(queue workqueue.RateLimitingInterface, resourceType string, maxRetries int, forgetAfterSuccess bool, reconciler func(key string) error) func() {\n\treturn func() {\n\t\texit := false\n\t\tfor !exit {\n\t\t\texit = func() bool {\n\t\t\t\tkey, quit := queue.Get()\n\t\t\t\tif quit {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\tdefer queue.Done(key)\n\n\t\t\t\terr := reconciler(key.(string))\n\t\t\t\tif err == nil {\n\t\t\t\t\tif forgetAfterSuccess {\n\t\t\t\t\t\tqueue.Forget(key)\n\t\t\t\t\t}\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\tif queue.NumRequeues(key) < maxRetries {\n\t\t\t\t\tglog.V(4).Infof(\"Error syncing %s %v: %v\", resourceType, key, err)\n\t\t\t\t\tqueue.AddRateLimited(key)\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\tglog.V(4).Infof(\"Dropping %s %q out of the queue: %v\", resourceType, key, err)\n\t\t\t\tqueue.Forget(key)\n\t\t\t\treturn false\n\t\t\t}()\n\t\t}\n\t}\n}", "func (c *Consumer) consume(ctx context.Context) {\n\t// We need to run startConsuming to make sure that we are okay and ready to start consuming. This is mainly to\n\t// avoid a race condition where Listen() will attempt to read the messages channel prior to consume()\n\t// initializing it. We can then launch a goroutine to handle the actual consume operation.\n\tif !c.startConsuming() {\n\t\treturn\n\t}\n\tgo func() {\n\t\tdefer c.stopConsuming()\n\n\t\tchildCtx, cancel := context.WithCancel(ctx)\n\t\tdefer cancel()\n\t\tfor {\n\t\t\t// The consume loop can be cancelled by a calling the cancellation function on the context or by\n\t\t\t// closing the pipe of death. Note that in the case of context cancellation, the getRecords\n\t\t\t// call below will be allowed to complete (as getRecords does not regard context cancellation).\n\t\t\t// In the case of cancellation by pipe of death, however, the getRecords will immediately abort\n\t\t\t// and allow the consume function to immediately abort as well.\n\t\t\tif ok, _ := c.shouldConsume(ctx); !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tc.enqueueBatch(childCtx)\n\t\t}\n\t}()\n}", "func (c *QueueClient) Use(hooks ...Hook) {\n\tc.hooks.Queue = append(c.hooks.Queue, hooks...)\n}", "func (lp *loop) HandleCb(cb handleCb) {\n\tlp.handleCb = cb\n}", "func (a *answer) queueCall(result *answer, transform []capnp.PipelineOp, call *capnp.Call) error {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\tif a.done {\n\t\tpanic(\"answer.queueCall called on resolved answer\")\n\t}\n\tif len(a.queue) == cap(a.queue) {\n\t\treturn errQueueFull\n\t}\n\tcc, err := call.Copy(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.queue = append(a.queue, pcall{\n\t\ttransform: transform,\n\t\tqcall: qcall{\n\t\t\ta: result,\n\t\t\tcall: cc,\n\t\t},\n\t})\n\treturn nil\n}", "func NewRedisQueueWithFunc(\n\tr *redis.Client,\n\tpush func(interface{}) (interface{}, error),\n\tpop func(interface{}) (interface{}, error)) *RedisQueue {\n\treturn &RedisQueue{\n\t\tkey: fmt.Sprintf(\"queue:%v\", time.Now().Nanosecond()),\n\t\tr: r,\n\t\tpush: push,\n\t\tpop: pop,\n\t}\n}", "func (client *Client) RecognizeFlowerWithChan(request *RecognizeFlowerRequest) (<-chan *RecognizeFlowerResponse, <-chan error) {\n\tresponseChan := make(chan *RecognizeFlowerResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.RecognizeFlower(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (f *Fixer) QueueChain(cert *x509.Certificate, chain []*x509.Certificate, roots *x509.CertPool) {\n\tf.toFix <- &toFix{\n\t\tcert: cert,\n\t\tchain: newDedupedChain(chain),\n\t\troots: roots,\n\t\tcache: f.cache,\n\t}\n}", "func WithTracer(tracer trace.Tracer) OptionFunc {\n\treturn func(c *callbacks) {\n\t\tc.tracer = tracer\n\t}\n}", "func CallErr(f func() error) error {\n\tcheckRun()\n\terrChan := make(chan error)\n\tcallQueue <- func() {\n\t\terrChan <- f()\n\t}\n\treturn <-errChan\n}", "func (client *Client) KillSparkJobWithCallback(request *KillSparkJobRequest, callback func(response *KillSparkJobResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *KillSparkJobResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.KillSparkJob(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func queueRedo(queue, cgroup string) (exWrap, error) {\n\tk, err := queueKeyMarshal(core.Key{Base: queue, Subs: []string{cgroup, \"redo\"}})\n\tif err != nil {\n\t\treturn exWrap{}, err\n\t}\n\treturn newExWrap(k), nil\n}", "func (q *GCPPubSubQueue) receive(ctx context.Context, f func(interface{})) {\n\terr := q.subscription.Receive(ctx, func(ctx xContext.Context, msg *pubsub.Message) {\n\t\tlogger := q.logger.With(\"messageID\", msg.ID)\n\n\t\tlogger.With(\"publishTime\", msg.PublishTime).Info(\"processing job published\")\n\n\t\t// Acknowledge the job now, anything else that could fail by this instance\n\t\t// will probably fail for others.\n\t\tmsg.Ack()\n\t\tlogger.Info(\"acknowledged job\")\n\n\t\treader := bytes.NewReader(msg.Data)\n\t\tdec := gob.NewDecoder(reader)\n\n\t\tvar job container\n\t\tif err := dec.Decode(&job); err != nil {\n\t\t\tlogger.With(\"error\", err).Errorf(\"could not decode job\")\n\t\t\treturn\n\t\t}\n\t\tlogger.Info(\"processing\")\n\n\t\tf(job.Job)\n\t})\n\tif err != nil && err != context.Canceled {\n\t\tq.logger.With(\"error\", err).Error(\"could not receive on subscription\")\n\t}\n}", "func (client *Client) DescribeAcceleratorWithCallback(request *DescribeAcceleratorRequest, callback func(response *DescribeAcceleratorResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DescribeAcceleratorResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DescribeAccelerator(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func NewChannelQueue(handle HandlerFunc, cfg, exemplar interface{}) (Queue, error) {\n\tconfigInterface, err := toConfig(ChannelQueueConfiguration{}, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig := configInterface.(ChannelQueueConfiguration)\n\tif config.BatchLength == 0 {\n\t\tconfig.BatchLength = 1\n\t}\n\n\tterminateCtx, terminateCtxCancel := context.WithCancel(context.Background())\n\tshutdownCtx, shutdownCtxCancel := context.WithCancel(terminateCtx)\n\n\tqueue := &ChannelQueue{\n\t\tshutdownCtx: shutdownCtx,\n\t\tshutdownCtxCancel: shutdownCtxCancel,\n\t\tterminateCtx: terminateCtx,\n\t\tterminateCtxCancel: terminateCtxCancel,\n\t\texemplar: exemplar,\n\t\tworkers: config.Workers,\n\t\tname: config.Name,\n\t}\n\tqueue.WorkerPool = NewWorkerPool(func(data ...Data) []Data {\n\t\tunhandled := handle(data...)\n\t\tif len(unhandled) > 0 {\n\t\t\t// We can only pushback to the channel if we're paused.\n\t\t\tif queue.IsPaused() {\n\t\t\t\tatomic.AddInt64(&queue.numInQueue, int64(len(unhandled)))\n\t\t\t\tgo func() {\n\t\t\t\t\tfor _, datum := range data {\n\t\t\t\t\t\tqueue.dataChan <- datum\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn unhandled\n\t}, config.WorkerPoolConfiguration)\n\n\tqueue.qid = GetManager().Add(queue, ChannelQueueType, config, exemplar)\n\treturn queue, nil\n}", "func (client *Client) GetTaobaoOrderWithCallback(request *GetTaobaoOrderRequest, callback func(response *GetTaobaoOrderResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *GetTaobaoOrderResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.GetTaobaoOrder(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func WithGomockController(t *testing.T, f func(ctrl *gomock.Controller)) {\n\tctrl := gomock.NewController(t)\n\n\tf(ctrl)\n}", "func (runner *TestRunner) handleQueue (queueControl <-chan batchExecQueueControl) {\n\texecEndSignal := make(chan string)\n\n\texecute := func (enq batchExecQueueControlEnqueue, stopRequest <-chan struct{}, executionLogQuery <-chan chan<- string) {\n\t\t// Handle the execution log in a separate goroutine rather than in\n\t\t// the main loop of runner.executeBatch, so that any stalls in\n\t\t// executeBatch don't delay execution log queries.\n\t\t// The handler is controlled via the following channels.\n\t\texecutionLogAppend\t:= make(chan string)\t// Append a string to the log; don't commit to DB yet.\n\t\texecutionLogCommit\t:= make(chan struct{})\t// Commit uncommitted changes to DB.\n\t\texecutionLogStop\t:= make(chan struct{})\t// Stop the goroutine.\n\t\tgo func() {\n\t\t\texecutionLog := bytes.Buffer{}\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\t\tcase dst := <-executionLogQuery:\n\t\t\t\t\t\tdst <- runner.getBatchResultPastExecutionLog(enq.batchResultId) + executionLog.String()\n\t\t\t\t\tcase str := <-executionLogAppend:\n\t\t\t\t\t\texecutionLog.WriteString(str)\n\t\t\t\t\tcase <-executionLogCommit:\n\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\topSet.Call(typeBatchResultExecutionLog, enq.batchResultId, \"Append\", executionLog.String())\n\t\t\t\t\t\terr := runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\tif err != nil { panic(err) }\n\t\t\t\t\t\texecutionLog.Reset()\n\t\t\t\t\tcase <-executionLogStop:\n\t\t\t\t\t\tif executionLog.Len() > 0 { panic(\"Execution log handler stopped, but non-committed data remains\") }\n\t\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\texecutionLogAppend <- fmt.Sprintf(\"Batch reached front of its queue at %v\\n\", time.Now().Format(defaultHumanReadableTimeFormat))\n\n\t\tvar batchResult BatchResult\n\t\terr := runner.rtdbServer.GetObject(enq.batchResultId, &batchResult)\n\t\tif err != nil { panic(err) }\n\n\t\tvar testCaseList TestCaseList\n\t\terr = runner.rtdbServer.GetObject(enq.batchResultId, &testCaseList)\n\t\tif err != nil { panic(err) }\n\n\t\tcasePaths := testCaseList.Paths\n\t\tif runner.isPartiallyExecutedBatch(enq.batchResultId) {\n\t\t\texecutionLogAppend <- fmt.Sprintf(\"Batch is partially executed, filtering pending cases\\n\")\n\t\t\tcasePaths = runner.filterPendingCasePaths(enq.batchResultId, casePaths)\n\t\t}\n\n\t\trunner.executeBatch(enq.batchResultId, batchResult.ExecParams, casePaths, stopRequest, executionLogAppend)\n\n\t\texecutionLogCommit <- struct{}{}\n\t\texecEndSignal <- enq.queueId\n\t\texecutionLogStop <- struct{}{}\n\t}\n\n\tqueueStopRequest\t\t:= make(map[string]chan<- struct{})\n\tqueueExecutionLogQuery\t:= make(map[string]chan<- chan<- string)\n\n\tlaunch := func (enq batchExecQueueControlEnqueue) {\n\t\tstopRequest\t\t\t:= make(chan struct{}, 1)\n\t\texecutionLogQuery\t:= make(chan chan<- string, 1)\n\t\tqueueStopRequest[enq.queueId]\t\t\t= stopRequest\n\t\tqueueExecutionLogQuery[enq.queueId]\t\t= executionLogQuery\n\t\tgo execute(enq, stopRequest, executionLogQuery)\n\t}\n\n\tfor {\n\t\tselect {\n\t\t\tcase command := <-queueControl:\n\t\t\t\tswitch cmd := command.(type) {\n\t\t\t\t\tcase batchExecQueueControlEnqueue:\n\t\t\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\t\t\terr := runner.rtdbServer.GetObject(cmd.queueId, &queue)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t// Queue does not exist; create it.\n\n\t\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\t\topSet.Call(typeDeviceBatchQueueList, \"deviceBatchQueueList\", \"Append\", cmd.queueId)\n\t\t\t\t\t\t\topSet.Call(typeDeviceBatchQueue, cmd.queueId, \"Init\")\n\t\t\t\t\t\t\terr = runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\t\tif err != nil { panic(err) }\n\n\t\t\t\t\t\t\tlog.Printf(\"[runner] created queue '%s'\", cmd.queueId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\topSet.Call(typeDeviceBatchQueue, cmd.queueId, \"Append\", cmd.batchResultId)\n\t\t\t\t\t\terr = runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\tif err != nil { panic(err) }\n\n\t\t\t\t\t\tif len(queue.BatchResultIds) == 0 { // \\note queue is the queue before appending.\n\t\t\t\t\t\t\tlaunch(cmd);\n\t\t\t\t\t\t}\n\n\t\t\t\t\tcase batchExecQueueControlStopBatch:\n\t\t\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\t\t\terr := runner.rtdbServer.GetObject(cmd.queueId, &queue)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: stop request for non-existent queue '%s'\", cmd.queueId)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfound := false\n\t\t\t\t\t\tfor ndx, enqueuedId := range queue.BatchResultIds {\n\t\t\t\t\t\t\tif enqueuedId == cmd.batchResultId {\n\t\t\t\t\t\t\t\tif ndx == 0 {\n\t\t\t\t\t\t\t\t\tselect {\n\t\t\t\t\t\t\t\t\t\tcase queueStopRequest[cmd.queueId] <- struct{}{}:\n\t\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] stop request sent for batch '%s'\\n\", cmd.batchResultId)\n\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] stop request already sent for batch '%s'\\n\", cmd.batchResultId)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] cancelled pending batch '%s'\\n\", cmd.batchResultId)\n\n\t\t\t\t\t\t\t\t\t// Set batch status, and remove it from the queue and active batch list.\n\t\t\t\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\t\t\t\topSet.Call(typeBatchResult, cmd.batchResultId, \"SetStatus\", BATCH_STATUS_CODE_CANCELED)\n\t\t\t\t\t\t\t\t\topSet.Call(typeActiveBatchResultList, \"activeBatchResultList\", \"Remove\", cmd.batchResultId)\n\t\t\t\t\t\t\t\t\topSet.Call(typeDeviceBatchQueue, cmd.queueId, \"Remove\", cmd.batchResultId)\n\t\t\t\t\t\t\t\t\terr = runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\t\t\t\tif err != nil { panic(err) }\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif !found {\n\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: stop request for batch '%s', does not exist in queue '%s'\\n\", cmd.batchResultId, cmd.queueId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\tcase batchExecQueueControlMove:\n\t\t\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\t\t\terr := runner.rtdbServer.GetObject(cmd.queueId, &queue)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: move command for non-existent queue '%s'\", cmd.queueId)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfound := false\n\t\t\t\t\t\tfor srcNdx, enqueuedId := range queue.BatchResultIds {\n\t\t\t\t\t\t\tif enqueuedId == cmd.batchResultId {\n\t\t\t\t\t\t\t\tdstNdx := srcNdx + cmd.offset\n\t\t\t\t\t\t\t\tif srcNdx == 0 || dstNdx == 0 {\n\t\t\t\t\t\t\t\t\t// \\todo [nuutti] Support moving running batch? We'd have to automatically\n\t\t\t\t\t\t\t\t\t//\t\t\t\t stop it first, which can be slow, so it could get confusing?\n\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: trying to move currently to/from running batch in queue\\n\")\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif dstNdx < 0 || dstNdx >= len(queue.BatchResultIds) {\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: trying to move batch to position %d\\n\", dstNdx)\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\t\t\t\t\topSet.Call(typeDeviceBatchQueue, cmd.queueId, \"Move\", srcNdx, dstNdx)\n\t\t\t\t\t\t\t\t\t\terr := runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\t\t\t\t\tif err != nil { panic(err) }\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif !found {\n\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: move command for batch '%s', does not exist in queue '%s'\\n\", cmd.batchResultId, cmd.queueId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\tcase batchExecQueueControlExecutionLogQuery:\n\t\t\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\t\t\terr := runner.rtdbServer.GetObject(cmd.queueId, &queue)\n\t\t\t\t\t\tif err != nil { cmd.dst <- runner.getBatchResultPastExecutionLog(cmd.batchResultId); continue }\n\n\t\t\t\t\t\tquerySent := false\n\t\t\t\t\t\tfor ndx, enqueueId := range queue.BatchResultIds {\n\t\t\t\t\t\t\tif enqueueId == cmd.batchResultId {\n\t\t\t\t\t\t\t\tif ndx == 0 {\n\t\t\t\t\t\t\t\t\tqueueExecutionLogQuery[cmd.queueId] <- cmd.dst\n\t\t\t\t\t\t\t\t\tquerySent = true\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif !querySent {\n\t\t\t\t\t\t\tcmd.dst <- runner.getBatchResultPastExecutionLog(cmd.batchResultId)\n\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tcase queueId := <-execEndSignal:\n\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\terr := runner.rtdbServer.GetObject(queueId, &queue)\n\t\t\t\tif err != nil { panic(err) } // \\note This shouldn't happen (a batch run ends while it's not even in the queue).\n\n\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\topSet.Call(typeDeviceBatchQueue, queueId, \"Remove\", queue.BatchResultIds[0])\n\t\t\t\terr = runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\tif err != nil { panic(err) }\n\n\t\t\t\tif len(queue.BatchResultIds) > 1 { // \\note queue is the queue before removal.\n\t\t\t\t\tlaunch(batchExecQueueControlEnqueue{\n\t\t\t\t\t\tbatchResultId:\tqueue.BatchResultIds[1],\n\t\t\t\t\t\tqueueId:\t\tqueueId,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t}\n\t}\n}", "func (c *Connection) ConsumerWithConfig(done chan bool, config *Config, callback func(msgs <-chan amqp.Delivery)) error {\n\tmsgs, err := c.Channel.Consume(\n\t\tconfig.Queue,\n\t\tconfig.ConsumerTag,\n\t\tconfig.Options.Consume.AutoAck,\n\t\tconfig.Options.Consume.Exclusive,\n\t\tconfig.Options.Consume.NoLocal,\n\t\tconfig.Options.Consume.NoWait,\n\t\tconfig.Options.Consume.Args,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo callback(msgs)\n\n\tlog.Println(\"Waiting for messages...\")\n\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\tc.Channel.Close()\n\t\t\tc.Conn.Close()\n\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (c *Controller) enqueueTagger(obj interface{}) {\n\tvar key string\n\tvar err error\n\tif key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {\n\t\truntime.HandleError(err)\n\t\treturn\n\t}\n\tglog.Infof(\"Enqueueing tagger %s\", key)\n\tc.workqueue.AddRateLimited(key)\n}", "func (client *Client) RunMedQAWithCallback(request *RunMedQARequest, callback func(response *RunMedQAResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *RunMedQAResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.RunMedQA(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (q *ChannelQueue) Run(atShutdown, atTerminate func(func())) {\n\tpprof.SetGoroutineLabels(q.baseCtx)\n\tatShutdown(q.Shutdown)\n\tatTerminate(q.Terminate)\n\tlog.Debug(\"ChannelQueue: %s Starting\", q.name)\n\t_ = q.AddWorkers(q.workers, 0)\n}", "func New(c *Config) (Poller, error) {\n\tcfg := c.withDefaults()\n\n\tkq, err := KqueueCreate(&KqueueConfig{\n\t\tOnWaitError: cfg.OnWaitError,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn poller{kq}, nil\n}", "func (q *execQueue) queue(f func()) bool {\n\tq.mu.Lock()\n\tok := !q.isClosed() && len(q.funcs) < cap(q.funcs)\n\tif ok {\n\t\tq.funcs = append(q.funcs, f)\n\t\tq.cond.Signal()\n\t}\n\tq.mu.Unlock()\n\treturn ok\n}", "func TestConsumerControlLoop(t *testing.T) {\n\texpect := ttesting.NewExpect(t)\n\tmockC := getMockConsumer()\n\n\tstop := new(int32)\n\troll := new(int32)\n\tmockC.SetStopCallback(func() {\n\t\tatomic.StoreInt32(stop, 1)\n\t})\n\n\tmockC.SetRollCallback(func() {\n\t\tatomic.StoreInt32(roll, 1)\n\t})\n\n\tgo mockC.ControlLoop()\n\t// let the go routine start\n\ttime.Sleep(50 * time.Millisecond)\n\tmockC.control <- PluginControlStopConsumer\n\ttime.Sleep(50 * time.Millisecond)\n\texpect.Equal(atomic.LoadInt32(stop), int32(1))\n\n\tgo mockC.ControlLoop()\n\ttime.Sleep(50 * time.Millisecond)\n\tmockC.control <- PluginControlRoll\n\ttime.Sleep(50 * time.Millisecond)\n\texpect.Equal(atomic.LoadInt32(roll), int32(1))\n}", "func (cb *ZVControllerBuilder) withWorkqueueRateLimiting() *ZVControllerBuilder {\n\tcb.ZVController.workqueue = workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"ZV\")\n\treturn cb\n}", "func (client *Client) RunContactReviewWithCallback(request *RunContactReviewRequest, callback func(response *RunContactReviewResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *RunContactReviewResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.RunContactReview(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (lp *loop) RedrawCb(cb redrawCb) {\n\tlp.redrawCb = cb\n}", "func (q *Queue) RunWithTimer(c *config.Config) error {\n\tstart := time.Now()\n\tif err := q.run(c); err != nil {\n\t\treturn fmt.Errorf(\"run queue failed: %s\", err)\n\t}\n\tlog.Printf(\"%sFinished in %.3f seconds%s\", colors.Green,\n\t\ttime.Since(start).Seconds(), colors.Reset)\n\treturn nil\n}", "func (client *Client) QueryWorksWithCallback(request *QueryWorksRequest, callback func(response *QueryWorksResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *QueryWorksResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.QueryWorks(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func TestConsumerControlLoop(t *testing.T) {\n\texpect := shared.NewExpect(t)\n\tmockC := getMockConsumer()\n\n\tstop := new(int32)\n\troll := new(int32)\n\tmockC.SetStopCallback(func() {\n\t\tatomic.StoreInt32(stop, 1)\n\t})\n\n\tmockC.SetRollCallback(func() {\n\t\tatomic.StoreInt32(roll, 1)\n\t})\n\n\tgo mockC.ControlLoop()\n\t// let the go routine start\n\ttime.Sleep(50 * time.Millisecond)\n\tmockC.control <- PluginControlStopConsumer\n\ttime.Sleep(50 * time.Millisecond)\n\texpect.Equal(atomic.LoadInt32(stop), int32(1))\n\n\tgo mockC.ControlLoop()\n\ttime.Sleep(50 * time.Millisecond)\n\tmockC.control <- PluginControlRoll\n\ttime.Sleep(50 * time.Millisecond)\n\texpect.Equal(atomic.LoadInt32(roll), int32(1))\n}", "func HandleQuee(c chan<- string) {\n\tc <- \"one\" //queue(\"one\")\n\tc <- \"two\" //queue(\"one\",\"two\")\n\tfmt.Println(\"isEnough\")\n\tclose(c)\n}", "func RunConsumer(ctx context.Context, qUser, qPassword, qUri, qName string, prefetchCount, prefetchSize,\n\tmaxRetries, workers int, handler MessageHandler) {\n\tconn := NewConnection(ctx, qUser, qPassword, qUri)\n\tfor id := 0; id < workers; id++ {\n\t\tc := newRetryableConsumer(id, qName, prefetchCount, prefetchSize, handler, maxRetries)\n\t\tc.run(conn)\n\t}\n\tconn.start()\n}", "func (q *queueDriverDefault) Run(ctx context.Context) error {\n\tvar (\n\t\tmsg etl.Message\n\t\tsize int\n\t\terr error\n\t\tok bool\n\t)\n\tfor {\n\t\tfor true {\n\t\t\t// dequeue message\n\t\t\tmsg, size, ok = q.dequeue()\n\t\t\t// if no message was dequeued, break and wait for new message in a queue\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// send dequeued message to output channel\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\tcase q.outputCh <- msg:\n\t\t\t}\n\n\t\t\t// call dequeue hooks\n\t\t\terr = q.callDequeueHooks(ctx, size)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// wait until new item is enqueued\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-q.enqueuedCh:\n\t\t}\n\t}\n\n\treturn nil\n}", "func WithBlockingCallback() Option {\n\treturn func(i interface{}) error {\n\t\tif c, ok := i.(*ceClient); ok {\n\t\t\tc.blockingCallback = true\n\t\t}\n\t\treturn nil\n\t}\n}", "func TestChainWithClosure(t *testing.T) {\n\twriter := os.Stdout\n\tvar chainC ChainCClosure\n\tchainC = ChainCClosure{\n\t\tWriter: writer,\n\t\tClosure: func(msg *string) {\n\t\t\tfmt.Println(\"chain c\")\n\t\t\tchainC.Msg = msg // side effect on outside of block\n\t\t},\n\t}\n\tchainB := ChainBClosure{\n\t\tNextChain: &chainC,\n\t\tClosure: func(msg *string) {\n\t\t\tfmt.Println(\"chain B\")\n\t\t},\n\t}\n\n\tchainA := ChainAClosure{\n\t\tNextChain: &chainB,\n\t\tClosure: func(msg *string) {\n\t\t\tfmt.Println(\"chain A\")\n\t\t},\n\t}\n\n\tmsg := \"hello\"\n\tchainA.Next(&msg)\n\n\tif *chainC.Msg != \"hello\" {\n\t\tt.Errorf(\"chainC msg should be 'hello' but got: %s\\n\", *chainC.Msg)\n\t}\n}", "func (client *Client) SetCasterConfigWithCallback(request *SetCasterConfigRequest, callback func(response *SetCasterConfigResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *SetCasterConfigResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.SetCasterConfig(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func demo_queue() {\n fmt.Print(\"\\n---QUEUE Logic---\\n\\n\")\n q := queue.Queue{}\n\n for i := 0; i <= 5; i++ {\n q.Enqueue(i)\n }\n fmt.Print(\"---Queue Before Dequeue---\\n\")\n q.PrintAll()\n dequeued := q.Dequeue()\n fmt.Printf(\"Dequeued Value: %v\\n\", dequeued)\n fmt.Print(\"---Queue After Dequeue---\\n\")\n q.PrintAll()\n}", "func (client *Client) VerifyCenWithCallback(request *VerifyCenRequest, callback func(response *VerifyCenResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *VerifyCenResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.VerifyCen(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func causalityWrap(inCh chan *job, syncer *Syncer) chan *job {\n\tcausality := &causality{\n\t\trelations: make(map[string]string),\n\t\ttask: syncer.cfg.Name,\n\t\tsource: syncer.cfg.SourceID,\n\t\tlogger: syncer.tctx.Logger.WithFields(zap.String(\"component\", \"causality\")),\n\t\tinCh: inCh,\n\t\toutCh: make(chan *job, syncer.cfg.QueueSize),\n\t}\n\n\tgo func() {\n\t\tcausality.run()\n\t\tcausality.close()\n\t}()\n\n\treturn causality.outCh\n}", "func (client *Client) ModifyPlanWithCallback(request *ModifyPlanRequest, callback func(response *ModifyPlanResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ModifyPlanResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ModifyPlan(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (f *ccFixture) popQueue() {\n\tf.T().Helper()\n\n\tdone := make(chan error)\n\tgo func() {\n\t\titem, _ := f.q.Get()\n\t\t_, err := f.tfr.Reconcile(f.ctx, item.(reconcile.Request))\n\t\tf.q.Done(item)\n\t\tdone <- err\n\t}()\n\n\tselect {\n\tcase <-time.After(time.Second):\n\t\tf.T().Fatal(\"timeout waiting for workqueue\")\n\tcase err := <-done:\n\t\tassert.NoError(f.T(), err)\n\t}\n}", "func (r *Request) getCallback() mq.Response {\n\tif r.cb == nil {\n\t\tpanic(\"test: request already responded to\")\n\t}\n\n\tcb := r.cb\n\tr.cb = nil\n\treturn cb\n}", "func (gq *Dispatch) Enqueue(t queues.Task) int64 {\n // Wrap the function so it works with the goroutine limiting code.\n var f = t.Func()\n var dtFunc = func(id int64) {\n // Run the given function.\n f(id)\n\n // Decrement the process counter.\n gq.pLock.Lock()\n //log.Printf(\"processing: %d, waiting: %v\", gq.processing, gq.waitingToRun)\n gq.processing--\n if gq.waitingToRun {\n gq.waitingToRun = false\n gq.nextWait.Done()\n }\n gq.pLock.Unlock()\n }\n t.SetFunc(dtFunc)\n\n // Lock the queue and enqueue a new task.\n gq.qLock.Lock()\n gq.idcount++\n var id = gq.idcount\n gq.queue.Enqueue(dispatchTaskWrapper{id, t})\n if gq.waitingOnQ {\n gq.waitingOnQ = false\n gq.restart.Done()\n }\n if gq.queue.Len() > gq.maxlength {\n gq.maxlength = gq.queue.Len()\n }\n gq.qLock.Unlock()\n\n return id\n}", "func (client *Client) StartK8sApplicationWithCallback(request *StartK8sApplicationRequest, callback func(response *StartK8sApplicationResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *StartK8sApplicationResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.StartK8sApplication(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (e Enumerable) Queue(f func(item interface{})) (q Queue) {\n\tq.AddJob = func(jobs *chan interface{}) {\n\t\tfor _, item := range e {\n\t\t\t*jobs <- item\n\t\t}\n\t}\n\tq.DoJob = func(job *interface{}) {\n\t\tf(*job)\n\t\treturn\n\t}\n\treturn\n}", "func (client *Client) AssociateRouteTableWithGatewayWithCallback(request *AssociateRouteTableWithGatewayRequest, callback func(response *AssociateRouteTableWithGatewayResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *AssociateRouteTableWithGatewayResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.AssociateRouteTableWithGateway(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (object *MQObject) CB(goOperation int32, gocbd *MQCBD, gomd *MQMD, gogmo *MQGMO) error {\n\tvar mqrc C.MQLONG\n\tvar mqcc C.MQLONG\n\tvar mqOperation C.MQLONG\n\tvar mqcbd C.MQCBD\n\tvar mqmd C.MQMD\n\tvar mqgmo C.MQGMO\n\n\terr := checkMD(gomd, \"MQCB\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = checkGMO(gogmo, \"MQCB\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmqOperation = C.MQLONG(goOperation)\n\tcopyCBDtoC(&mqcbd, gocbd)\n\tcopyMDtoC(&mqmd, gomd)\n\tcopyGMOtoC(&mqgmo, gogmo)\n\n\tkey := makeKey(object.qMgr.hConn, object.hObj)\n\n\t// The callback function is a C function that is a proxy for the MQCALLBACK_Go function\n\t// defined here. And that in turn will call the user's callback function\n\tmqcbd.CallbackFunction = (C.MQPTR)(unsafe.Pointer(C.MQCALLBACK_C))\n\n\tC.MQCB(object.qMgr.hConn, mqOperation, (C.PMQVOID)(unsafe.Pointer(&mqcbd)),\n\t\tobject.hObj,\n\t\t(C.PMQVOID)(unsafe.Pointer(&mqmd)), (C.PMQVOID)(unsafe.Pointer(&mqgmo)),\n\t\t&mqcc, &mqrc)\n\n\tmqreturn := MQReturn{MQCC: int32(mqcc),\n\t\tMQRC: int32(mqrc),\n\t\tverb: \"MQCB\",\n\t}\n\n\tif mqcc != C.MQCC_OK {\n\t\treturn &mqreturn\n\t}\n\n\t// Add or remove the control information in the map used by the callback routines\n\tswitch mqOperation {\n\tcase C.MQOP_DEREGISTER:\n\t\tmapLock()\n\t\tdelete(cbMap, key)\n\t\tmapUnlock()\n\tcase C.MQOP_REGISTER:\n\t\t// Stash the hObj and real function to be called\n\t\tinfo := &cbInfo{hObj: object,\n\t\t\tcallbackFunction: gocbd.CallbackFunction,\n\t\t\tconnectionArea: nil,\n\t\t\tcallbackArea: gocbd.CallbackArea}\n\t\tmapLock()\n\t\tcbMap[key] = info\n\t\tmapUnlock()\n\tdefault: // Other values leave the map alone\n\t}\n\n\treturn nil\n}", "func (f *FakeWatchEventQ) Dequeue(ctx context.Context,\n\tfromver uint64, ignoreBulk bool, cb apiintf.EventHandlerFn, cleanupfn func(), opts *api.ListWatchOptions) {\n\tdefer f.Unlock()\n\tf.Lock()\n\tclose(f.DqCh)\n\tf.Dequeues++\n\tif f.DQFn != nil {\n\t\tf.DQFn(ctx, fromver, cb, cleanupfn)\n\t}\n}", "func (client *Client) QueryBlockWithCallback(request *QueryBlockRequest, callback func(response *QueryBlockResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *QueryBlockResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.QueryBlock(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) MetastoreCreateKafkaTopicWithCallback(request *MetastoreCreateKafkaTopicRequest, callback func(response *MetastoreCreateKafkaTopicResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *MetastoreCreateKafkaTopicResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.MetastoreCreateKafkaTopic(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (c *ConsumerManager) Handle(topic, channel string, handler HandlerFunc) {\n\tfor i := range c.middlewares {\n\t\thandler = c.middlewares[len(c.middlewares)-i-1](handler)\n\t}\n\n\tc.mu.RLock()\n\tgHandler, ok := c.handlers[mergeTopicAndChannel(topic, channel)]\n\tc.mu.RUnlock()\n\n\tif !ok {\n\t\tc.err = fmt.Errorf(\"gonsq: consumer with topic %s and channel %s does not exist\", topic, channel)\n\t\treturn\n\t}\n\n\tif gHandler.handler != nil {\n\t\tc.err = fmt.Errorf(\"gonsq: handler for topic %s and channel %s registered twice\", topic, channel)\n\t\treturn\n\t}\n\n\t// Set the gonsq handler.\n\tgHandler.handler = handler\n\t// Set the nsq handler for HandleMessage.\n\t// Use AddHandler instead of AddConcurrentHandler,\n\t// consuming message from nsqd is very fast and\n\t// most of the timewe don't need to use concurrent handler.\n\tgHandler.client.AddHandler(gHandler)\n\t// Change the MaxInFlight to buffLength as the number\n\t// of message won't exceed the buffLength.\n\tgHandler.client.ChangeMaxInFlight(gHandler.stats.BufferLength())\n\n\tc.mu.Lock()\n\tc.handlers[mergeTopicAndChannel(topic, channel)] = gHandler\n\tc.mu.Unlock()\n}", "func WithCounter(counter Counter) Option {\n\treturn func(c *Consumer) error {\n\t\tc.counter = counter\n\t\treturn nil\n\t}\n}", "func WithThrottler(ctx context.Context, thr Throttler, freq time.Duration) context.Context {\n\treturn ctxthr{Context: ctx, thr: thr, freq: freq}\n}", "func runConsumer() {\n\tlog.Info(\"consumer starting ...\")\n\tdone := make(chan bool, 1)\n\tfor _, consumer := range cc.consumers {\n\t\tgo func(c *ConsumerWrapper) {\n\t\t\tlog.Info(\"consumer runing\", c.name)\n\t\t\tfor {\n\t\t\t\tif c.pause {\n\t\t\t\t\tlog.Info(\"consumer pause\", c.name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tc.consumer.Pop(c.queue, c.name)\n\t\t\t}\n\t\t}(consumer)\n\t}\n\t<-done\n}", "func (client *Client) QueryContactInfoWithCallback(request *QueryContactInfoRequest, callback func(response *QueryContactInfoResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *QueryContactInfoResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.QueryContactInfo(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (cb *ControllerBuilder) WithWorkqueueRateLimiting() *ControllerBuilder {\n\tcb.Controller.workqueue = workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"CSPC\")\n\treturn cb\n}", "func TestConsumerTickerLoop(t *testing.T) {\n\texpect := shared.NewExpect(t)\n\tmockC := getMockConsumer()\n\tmockC.setState(PluginStateActive)\n\t// accept timeroff by abs( 8 ms)\n\tdelta := float64(8 * time.Millisecond)\n\tcounter := new(int32)\n\ttickerLoopTimeout := 20 * time.Millisecond\n\tvar timeRecorded time.Time\n\tonTimeOut := func() {\n\t\tif atomic.LoadInt32(counter) > 3 {\n\t\t\tmockC.setState(PluginStateDead)\n\t\t\treturn\n\t\t}\n\t\t//this was fired as soon as the ticker started. So ignore but save the time\n\t\tif atomic.LoadInt32(counter) == 0 {\n\t\t\ttimeRecorded = time.Now()\n\t\t\tatomic.AddInt32(counter, 1)\n\t\t\treturn\n\t\t}\n\t\tdiff := time.Now().Sub(timeRecorded)\n\t\tdeltaDiff := math.Abs(float64(tickerLoopTimeout - diff))\n\t\texpect.True(deltaDiff < delta)\n\t\ttimeRecorded = time.Now()\n\t\tatomic.AddInt32(counter, 1)\n\t\treturn\n\t}\n\n\tmockC.tickerLoop(tickerLoopTimeout, onTimeOut)\n\ttime.Sleep(2 * time.Second)\n\t// in anycase, the callback has to be called atleast once\n\texpect.Greater(atomic.LoadInt32(counter), int32(1))\n}", "func (f *FPC) enqueue() {\n\tf.queueMu.Lock()\n\tdefer f.queueMu.Unlock()\n\tf.ctxsMu.Lock()\n\tdefer f.ctxsMu.Unlock()\n\tfor ele := f.queue.Front(); ele != nil; ele = f.queue.Front() {\n\t\tvoteCtx := ele.Value.(*vote.Context)\n\t\tf.ctxs[voteCtx.ID] = voteCtx\n\t\tf.queue.Remove(ele)\n\t\tdelete(f.queueSet, voteCtx.ID)\n\t}\n}", "func main() {\n\tctx := cliContext()\n\tflag.Parse()\n\tpool := &red.Pool{\n\t\tDial: func() (red.Conn, error) {\n\t\t\treturn red.Dial(\"tcp\", *redisServer)\n\t\t},\n\t\tTestOnBorrow: func(c red.Conn, _ time.Time) error {\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t\tMaxIdle: 1,\n\t}\n\t// Create the driver for queue\n\tdriver, err := redis.NewDriver(\n\t\tctx,\n\t\tredis.WithQueuePrefix(*prefix),\n\t\tredis.WithRedisPool(pool),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Create the manager\n\tm := workers.NewManager(driver, driver)\n\t// Register a global middleware\n\tm.RegisterMiddleware(\n\t\tmiddleware(\"Global\"),\n\t\tstorage.NewStorageMiddleware(&redisStorage{red: pool}),\n\t)\n\t// Register workers\n\terr = m.RegisterWorker(\"dummy\", dummyWorker{}, workers.WithMiddleware(middleware(\"DummyMiddle\")))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// Process queues\n\t// this hangs until the context is done\n\tm.Process(ctx, workers.WithParallelLimit(10), workers.WithRetryCount(1))\n}", "func Call(f func()) {\n\tdone := dPool.Get().(chan struct{})\n\tdefer dPool.Put(done)\n\tfq <- fun{fn: f, done: done}\n\t<-done\n}", "func (client *Client) PutMetricAlarmWithCallback(request *PutMetricAlarmRequest, callback func(response *PutMetricAlarmResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *PutMetricAlarmResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.PutMetricAlarm(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func WithQueueSubscriber(queue string) ConsumerOption {\n\treturn func(c *Consumer) error {\n\t\tif queue == \"\" {\n\t\t\treturn ErrInvalidQueueName\n\t\t}\n\t\tc.Subscriber = &QueueSubscriber{Queue: queue}\n\t\treturn nil\n\t}\n}", "func (client *Client) GetContactWithCallback(request *GetContactRequest, callback func(response *GetContactResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *GetContactResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.GetContact(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (p *unlimitedPool) Queue(fn WorkFunc) WorkUnit {\n\n\tw := &workUnit{\n\t\tdone: make(chan struct{}),\n\t\tfn: fn,\n\t}\n\n\tp.m.Lock()\n\n\tif p.closed {\n\t\tw.err = &ErrPoolClosed{s: errClosed}\n\t\t// if w.cancelled.Load() == nil {\n\t\tclose(w.done)\n\t\t// }\n\t\tp.m.Unlock()\n\t\treturn w\n\t}\n\n\tp.units = append(p.units, w)\n\tgo func(w *workUnit) {\n\n\t\tdefer func(w *workUnit) {\n\t\t\tif err := recover(); err != nil {\n\n\t\t\t\ttrace := make([]byte, 1<<16)\n\t\t\t\tn := runtime.Stack(trace, true)\n\n\t\t\t\ts := fmt.Sprintf(errRecovery, err, string(trace[:int(math.Min(float64(n), float64(7000)))]))\n\n\t\t\t\tw.cancelled.Store(struct{}{})\n\t\t\t\tw.err = &ErrRecovery{s: s}\n\t\t\t\tclose(w.done)\n\t\t\t}\n\t\t}(w)\n\n\t\t// support for individual WorkUnit cancellation\n\t\t// and batch job cancellation\n\t\tif w.cancelled.Load() == nil {\n\t\t\tval, err := w.fn(w)\n\n\t\t\tw.writing.Store(struct{}{})\n\n\t\t\t// need to check again in case the WorkFunc cancelled this unit of work\n\t\t\t// otherwise we'll have a race condition\n\t\t\tif w.cancelled.Load() == nil && w.cancelling.Load() == nil {\n\n\t\t\t\tw.value, w.err = val, err\n\n\t\t\t\t// who knows where the Done channel is being listened to on the other end\n\t\t\t\t// don't want this to block just because caller is waiting on another unit\n\t\t\t\t// of work to be done first so we use close\n\t\t\t\tclose(w.done)\n\t\t\t}\n\t\t}\n\t}(w)\n\n\tp.m.Unlock()\n\n\treturn w\n}", "func (o *GetLolCareerStatsV1ChampionAveragesByChampionIDByPositionByTierByQueueParams) WithQueue(queue string) *GetLolCareerStatsV1ChampionAveragesByChampionIDByPositionByTierByQueueParams {\n\to.SetQueue(queue)\n\treturn o\n}", "func (h *HTTPClient) Enqueue(ctx context.Context, token, projID, qName string, msgs []NewMessage) (*Enqueued, error) {\n\treqBody := &bytes.Buffer{}\n\tif err := json.NewEncoder(reqBody).Encode(enqueueReq{Messages: msgs}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := h.newReq(\"POST\", token, projID, fmt.Sprintf(\"queues/%s/messages\", qName), reqBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tret := new(Enqueued)\n\tdoFunc := func(resp *http.Response, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tif err := json.NewDecoder(resp.Body).Decode(ret); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tif err := gorion.HTTPDo(ctx, h.client, h.transport, req, doFunc); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}", "func (cl *DelayCaller) runner() {\n\tfor {\n\t\t// Run all the functions in the queue, whose timeout has expired. After\n\t\t// the loop, the variable |delay| contains the time until the next timeout.\n\t\tdelay := time.Duration(0)\n\t\tfor cl.queue.Len() > 0 {\n\t\t\tc := cl.queue.topCall()\n\t\t\tnow := time.Now()\n\t\t\tif now.Before(c.Tm) {\n\t\t\t\tdelay = c.Tm.Sub(now)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcl.queue.popCall()\n\t\t\tcl.p.send(c.Fn)\n\t\t}\n\t\t// Wait for a new timeout request, but block at most until the next\n\t\t// already scheduled timeout.\n\t\tvar timeout <-chan time.Time\n\t\tif delay == 0 {\n\t\t\ttimeout = nil\n\t\t} else {\n\t\t\ttimeout = time.After(delay)\n\t\t}\n\t\tselect {\n\t\tcase c, ok := <-cl.queueIn:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tcl.queue.pushCall(c)\n\t\t\t}\n\t\tcase <-timeout:\n\t\t}\n\t}\n}", "func runCallback(receivedMessage *Message, consumerMessage *sarama.ConsumerMessage) {\n\tcallback := subscribeMap[consumerMessage.Topic][receivedMessage.MessageType]\n\n\tif callback == nil {\n\t\tlogrus.Error(fmt.Sprintf(\"callback not found for topic : %s, message type : %s\", consumerMessage.Topic,\n\t\t\treceivedMessage.MessageType))\n\t\treturn\n\t}\n\n\tgo callback(&Message{\n\t\tTopic: consumerMessage.Topic,\n\t\tMessage: receivedMessage.Message,\n\t\tMessageType: receivedMessage.MessageType,\n\t\tService: receivedMessage.Service,\n\t\tTraceId: receivedMessage.TraceId,\n\t\tMessageId: receivedMessage.MessageId,\n\t}, nil)\n}", "func TestConsumerTickerLoop(t *testing.T) {\n\texpect := ttesting.NewExpect(t)\n\tmockC := getMockConsumer()\n\tmockC.setState(PluginStateActive)\n\n\t// accept timeroff by abs( 15 ms)\n\ttickThreshold := float64(15 * time.Millisecond)\n\ttickerLoopTimeout := 20 * time.Millisecond\n\tlastTick := time.Now()\n\tcounter := new(int32)\n\n\tonTimeOut := func() {\n\t\tdefer func() {\n\t\t\tatomic.AddInt32(counter, 1)\n\t\t\tlastTick = time.Now()\n\t\t}()\n\n\t\tif atomic.LoadInt32(counter) > 3 {\n\t\t\tmockC.setState(PluginStateDead)\n\t\t\treturn\n\t\t}\n\n\t\tif atomic.LoadInt32(counter) > 0 {\n\t\t\tdeltaDiff := math.Abs(float64(tickerLoopTimeout - time.Since(lastTick)))\n\t\t\texpect.Less(deltaDiff, tickThreshold)\n\t\t}\n\t}\n\n\tmockC.tickerLoop(tickerLoopTimeout, onTimeOut)\n\ttime.Sleep(2 * time.Second)\n\t// in anycase, the callback has to be called atleast once\n\texpect.Greater(atomic.LoadInt32(counter), int32(1))\n}" ]
[ "0.5876569", "0.56525135", "0.53222644", "0.47999582", "0.47828177", "0.47699308", "0.47098765", "0.46049252", "0.45920306", "0.4560763", "0.45019993", "0.44990736", "0.4407609", "0.4383445", "0.42866144", "0.42831054", "0.42361563", "0.42217386", "0.4204431", "0.42024133", "0.4200147", "0.41932052", "0.41853583", "0.41822237", "0.41760316", "0.41300935", "0.4128459", "0.41247618", "0.4104638", "0.41005486", "0.4092167", "0.40907085", "0.40825716", "0.40749297", "0.40726155", "0.40721485", "0.40674758", "0.40590805", "0.40569532", "0.40265998", "0.40256128", "0.40189782", "0.4015255", "0.40138492", "0.40068057", "0.39973462", "0.39962187", "0.3995733", "0.39949635", "0.39938197", "0.39934778", "0.39875737", "0.3982926", "0.39752552", "0.3973805", "0.39707705", "0.39697373", "0.3966761", "0.39665523", "0.39584213", "0.39572668", "0.39572343", "0.39548144", "0.3953937", "0.39509052", "0.394783", "0.3940888", "0.39378253", "0.39356485", "0.3913344", "0.39131007", "0.3912053", "0.39030346", "0.3902831", "0.39027768", "0.39008138", "0.38971153", "0.389136", "0.3887498", "0.3885404", "0.38834408", "0.38824725", "0.38824302", "0.38758948", "0.3871928", "0.3870089", "0.38658443", "0.38521808", "0.38511652", "0.38501006", "0.3849449", "0.38464737", "0.38450384", "0.38405353", "0.3838324", "0.38364825", "0.3827314", "0.3817864", "0.38171208", "0.38148075" ]
0.79700077
0
optionalTimeout returns a channel on which the current time will be sent when the specified deadline arrives. Or, if deadline is nil, optionalTimeout returns a nil channel (receives will block forever, i.e. no timeout).
func optionalTimeout(deadline *time.Time) <-chan time.Time { var timeout <-chan time.Time if deadline != nil { timeout = time.NewTimer(time.Until(*deadline)).C } return timeout }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *Sink) TimeoutChan() <-chan time.Time {\n\treturn f.timeoutTimer.C\n}", "func With_timeout_nowait(ctx context.Context, timeout time.Duration) option {\n\treturn func(o *Group) {\n\t\tif o.Context != nil {\n\t\t\tpanic(\"context already set\")\n\t\t}\n\t\tif ctx == nil {\n\t\t\to.Context, o.CancelFunc = context.WithTimeout(context.Background(), timeout)\n\t\t\treturn\n\t\t}\n\t\to.Context, o.CancelFunc = context.WithTimeout(ctx, timeout)\n\t}\n}", "func (w *ChannelWriter) SetDeadline(t time.Time) {\n\tw.deadline = t\n}", "func WithDeadline(d time.Duration) RingOption {\n\treturn func(r *Ring) error {\n\t\tr.deadline = d\n\t\ts := newRingSubmitter(r, d)\n\t\t// This is an ugly hack....\n\t\tgo s.run()\n\t\tr.submitter = s\n\t\treturn nil\n\t}\n}", "func Timeout() <-chan time.Time {\n\treturn Timeouts(GetNonSubscribeTimeout())\n}", "func NewTimeoutChan(ctx context.Context, resolution time.Duration, limit int) *TimeoutChan {\n\tsize := limit\n\tif limit == 0 {\n\t\tsize = 1024\n\t}\n\tin := make(chan Deadliner)\n\tout := make(chan Deadliner)\n\ttc := &TimeoutChan{\n\t\tIn: in,\n\t\tOut: out,\n\n\t\tctx: ctx,\n\t\tpushCtrl: NewController(ctx, \"TimeoutChan Push\"),\n\t\tpopCtrl: NewController(ctx, \"TimeoutChan Pop\"),\n\t\tresolution: resolution,\n\t\tlimit: limit,\n\t\tin: in,\n\t\tout: out,\n\t\tresumePush: make(chan interface{}),\n\t\tresumePop: make(chan interface{}),\n\t\treschedule: make(chan interface{}),\n\t\tclosePush: make(chan interface{}),\n\n\t\tmu: &sync.RWMutex{},\n\t\tpq: NewPriorityQueue(false, size),\n\t\tpushed: 0,\n\t\tpopped: 0,\n\t\tcleared: 0,\n\t}\n\ttc.popCtrl.Go(tc.popProcess)\n\ttc.pushCtrl.Go(tc.pushProcess)\n\treturn tc\n}", "func TestDeadline(t *testing.T) {\n\tmsgChan, _, wg := initTest()\n\teb := eventbus.New()\n\tsupervisor, err := monitor.Launch(eb, unixSoc)\n\tassert.NoError(t, err)\n\n\tlog.AddHook(supervisor)\n\n\t// Send an error entry, to trigger Send\n\tlog.Errorln(\"pippo\")\n\n\tmsg := <-msgChan\n\tassert.Equal(t, \"error\", msg[\"level\"])\n\tassert.Equal(t, \"pippo\", msg[\"msg\"])\n\n\t// The write deadline is 3 seconds, so let's wait for that to expire\n\ttime.Sleep(3 * time.Second)\n\n\tblk := helper.RandomBlock(t, 23, 4)\n\tmsgBlk := message.New(topics.AcceptedBlock, *blk)\n\teb.Publish(topics.AcceptedBlock, msgBlk)\n\n\t// Should get the accepted block message on the msgchan\n\tfor {\n\t\tmsg = <-msgChan\n\t\t// We should discard any other messages\n\t\tif msg[\"code\"] == \"round\" {\n\t\t\t// Success\n\t\t\tbreak\n\t\t}\n\t}\n\n\t_ = supervisor.Stop()\n\twg.Wait()\n}", "func timeoutDialer(secs int) func(net, addr string) (c net.Conn, err error) {\n\treturn func(netw, addr string) (net.Conn, error) {\n\t\tc, err := net.Dial(netw, addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tc.SetDeadline(time.Now().Add(time.Duration(secs) * time.Second))\n\t\treturn c, nil\n\t}\n}", "func NewOptionalTicker(d time.Duration) *OptionalTicker {\n\tvar ticker OptionalTicker\n\tif d != 0 {\n\t\tticker.t = time.NewTicker(d)\n\t\tticker.C = ticker.t.C\n\t}\n\n\treturn &ticker\n}", "func ReceiveWait(t time.Duration) ReceiveOpt {\n\treturn func(m ReceiveMatcher) ReceiveMatcher {\n\t\tm.timeout = t\n\t\treturn m\n\t}\n}", "func ContextWithOptionalTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {\n\tif timeout < 0 {\n\t\t// This should be handled in validation\n\t\tklog.Errorf(\"Timeout for context shall not be negative!\")\n\t\ttimeout = 0\n\t}\n\n\tif timeout == 0 {\n\t\treturn context.WithCancel(parent)\n\t}\n\n\treturn context.WithTimeout(parent, timeout)\n}", "func TestMock_WithDeadlineCancel(t *testing.T) {\n\tm := NewMock()\n\tctx, cancel := m.WithDeadline(context.Background(), m.Now().Add(time.Second))\n\tcancel()\n\tselect {\n\tcase <-ctx.Done():\n\t\tif !errors.Is(ctx.Err(), context.Canceled) {\n\t\t\tt.Error(\"invalid type of error returned after cancellation\")\n\t\t}\n\tcase <-time.After(time.Second):\n\t\tt.Error(\"context is not cancelled after cancel was called\")\n\t}\n}", "func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) Dialer {\n\treturn func(ctx context.Context, network, addr string) (net.Conn, error) {\n\t\tconn, err := net.DialTimeout(network, addr, cTimeout)\n\t\tif err != nil {\n\t\t\treturn conn, err\n\t\t}\n\n\t\tif rwTimeout > 0 {\n\t\t\terr = conn.SetDeadline(time.Now().Add(rwTimeout))\n\t\t}\n\n\t\treturn conn, err\n\t}\n}", "func (c *ChannelConn) SetDeadline(_ time.Time) error {\n\treturn nil\n}", "func TestMock_WithDeadlineImmediate(t *testing.T) {\n\tm := NewMock()\n\tctx, _ := m.WithDeadline(context.Background(), m.Now().Add(-time.Second))\n\tselect {\n\tcase <-ctx.Done():\n\t\tif !errors.Is(ctx.Err(), context.DeadlineExceeded) {\n\t\t\tt.Error(\"invalid type of error returned when deadline has already passed\")\n\t\t}\n\tdefault:\n\t\tt.Error(\"context is not cancelled when deadline has already passed\")\n\t}\n}", "func newNullableTicker(d time.Duration) (<-chan time.Time, func()) {\n\tif d > 0 {\n\t\tt := time.NewTicker(d)\n\t\treturn t.C, t.Stop\n\t}\n\treturn nil, func() {}\n}", "func (r *ChannelReader) SetDeadline(deadline time.Time) {\n\tr.deadline = deadline\n}", "func getDrainTimeout(ctx thrift.Context) time.Duration {\n\tif ctx != nil {\n\t\tif deadline, ok := ctx.Deadline(); ok {\n\t\t\treturn deadline.Sub(time.Now())\n\t\t}\n\t}\n\treturn defaultDrainTimeout\n}", "func (client *AmqpConsumer) ReceiveWithoutTimeout(exchange string, routingKeys []string, queue string, queueOptions QueueOptions) chan AmqpMessage {\n\treturn client.Receive(exchange, routingKeys, queue, queueOptions, 0*time.Second)\n}", "func TestMock_WithDeadline(t *testing.T) {\n\tm := NewMock()\n\tctx, _ := m.WithDeadline(context.Background(), m.Now().Add(time.Second))\n\tm.Add(time.Second)\n\tselect {\n\tcase <-ctx.Done():\n\t\tif !errors.Is(ctx.Err(), context.DeadlineExceeded) {\n\t\t\tt.Error(\"invalid type of error returned when deadline exceeded\")\n\t\t}\n\tdefault:\n\t\tt.Error(\"context is not cancelled when deadline exceeded\")\n\t}\n}", "func Timeout(timeout time.Duration) OptionFunc {\n\treturn func(tc *TracedClient) error {\n\t\tif timeout <= 0 {\n\t\t\treturn errors.New(\"timeout must be positive\")\n\t\t}\n\t\ttc.cl.Timeout = timeout\n\t\treturn nil\n\t}\n}", "func Timeout(d time.Duration) func(*Attacker) {\n\treturn func(a *Attacker) {\n\t\ta.client.Timeout = d\n\t}\n}", "func RedisOptIdleTimeout(idleTimeout time.Duration) RedisOpt {\n\treturn func(p *redis.Pool) {\n\t\tp.IdleTimeout = idleTimeout\n\t}\n}", "func (c *Conn) SetDeadline(t time.Time) error {\n // return c.conn.SetDeadline(t)\n fmt.Println(\"set deadline\", t)\n return nil\n}", "func (cfg *Config) Timeout(msg hotstuff.TimeoutMsg) {\n\tif cfg.cfg == nil {\n\t\treturn\n\t}\n\tvar ctx context.Context\n\tcfg.timeoutCancel()\n\tctx, cfg.timeoutCancel = context.WithCancel(context.Background())\n\tcfg.cfg.Timeout(ctx, proto.TimeoutMsgToProto(msg), gorums.WithNoSendWaiting())\n}", "func timeoutDialer(timeout time.Duration) func(string, string) (net.Conn, error) {\n\treturn func(network, addr string) (c net.Conn, err error) {\n\t\tc, err = net.DialTimeout(network, addr, timeout)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn\n\t}\n}", "func (o BuildSpecPtrOutput) Timeout() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Timeout\n\t}).(pulumi.StringPtrOutput)\n}", "func Timeout(d time.Duration) func(*Server) {\n\treturn func(s *Server) {\n\t\ts.timeout = d\n\t}\n}", "func TestTimeout(t *testing.T) {\n\tgo func() {\n\t\ttime.Sleep(10 * time.Second)\n\t\tt.Fatal()\n\t}()\n\n\tpub, sub := testClients(t, 500*time.Millisecond)\n\trequire.Nil(t, sub.Subscribe(\"timeoutTestChannel\").Err)\n\n\tr := sub.Receive() // should timeout after a second\n\tassert.Equal(t, Error, r.Type)\n\tassert.NotNil(t, r.Err)\n\tassert.True(t, r.Timeout())\n\n\twaitCh := make(chan struct{})\n\tgo func() {\n\t\tr = sub.Receive()\n\t\tclose(waitCh)\n\t}()\n\trequire.Nil(t, pub.Cmd(\"PUBLISH\", \"timeoutTestChannel\", \"foo\").Err)\n\t<-waitCh\n\n\tassert.Equal(t, Message, r.Type)\n\tassert.Equal(t, \"timeoutTestChannel\", r.Channel)\n\tassert.Equal(t, \"foo\", r.Message)\n\tassert.Nil(t, r.Err, \"%s\", r.Err)\n\tassert.False(t, r.Timeout())\n}", "func (b *ASCIIOverTCP) Timeout(timeout time.Duration) time.Duration {\n\tt := b.Handler.Timeout\n\tb.Handler.Timeout = timeout\n\treturn t\n}", "func (async *async) waitOrTimeout(duration time.Duration) error {\n\ttimer := time.NewTimer(duration)\n\tdefer timer.Stop()\n\tselect {\n\tcase <-timer.C:\n\t\treturn errors.New(\"operation cancelled\")\n\tcase <-async.done:\n\t\treturn nil\n\t}\n}", "func Timeout(o int) interface {\n\ttimeoutOptionSetter\n} {\n\treturn &timeoutOption{o}\n}", "func Timeout(timeout time.Duration, timeoutFunction OnTimeout) crOption {\n\treturn func(cr *ConsumerRegistration) *ConsumerRegistration {\n\t\tcr.timeout = timeout\n\t\tcr.onTimeout = timeoutFunction\n\t\treturn cr\n\t}\n}", "func WithoutPongDeadline() Option {\n\treturn func(o *options) {\n\t\to.pongWait = 0\n\t}\n}", "func (rw *NopConn) SetDeadline(time.Time) error { return nil }", "func (ch Ch) Receive(timeout int) (interface{}, error){\n\tif timeout<=0{\n\t\treturn nil,errors.New(\"timeout variable cannot be below or equals zero\")\n\t}\n\tselect {\n\tcase b:=<- ch:\n\t\treturn b, nil\n\tcase <-time.After(time.Duration(timeout)*time.Second):\n\t\treturn nil, errors.New(\"timeout data reception from channel\")\n\t}\n}", "func (p *Peer) heartbeatTimeoutFunc(startChannel chan bool) {\n\tstartChannel <- true\n\n\tfor {\n\t\t// Grab the current timer channel.\n\t\tp.mutex.Lock()\n\n\t\tvar c chan time.Time\n\t\tif p.heartbeatTimer != nil {\n\t\t\tc = p.heartbeatTimer.C()\n\t\t}\n\t\tp.mutex.Unlock()\n\n\t\t// If the channel or timer are gone then exit.\n\t\tif c == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Flush the peer when we get a heartbeat timeout. If the channel is\n\t\t// closed then the peer is getting cleaned up and we should exit.\n\t\tif _, ok := <-c; ok {\n\t\t\tp.flush(false)\n\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func TestMock_WithDeadlineLaterThanCurrent(t *testing.T) {\n\tm := NewMock()\n\tctx, _ := m.WithDeadline(context.Background(), m.Now().Add(time.Second))\n\tctx, _ = m.WithDeadline(ctx, m.Now().Add(10*time.Second))\n\tm.Add(time.Second)\n\tselect {\n\tcase <-ctx.Done():\n\t\tif !errors.Is(ctx.Err(), context.DeadlineExceeded) {\n\t\t\tt.Error(\"invalid type of error returned when deadline exceeded\")\n\t\t}\n\tdefault:\n\t\tt.Error(\"context is not cancelled when deadline exceeded\")\n\t}\n}", "func (r *timeoutReader) SetDeadline(t time.Time) {\n\tr.t = t\n}", "func WithRecvTimeout(timeout time.Duration) SessionOpt {\n\treturn func(so SessionOpts) SessionOpts {\n\t\tso.recvTimeout = timeout\n\t\treturn so\n\t}\n}", "func LeaveTimeoutOpt(timeout time.Duration) NodeDiscoverOpt {\n\treturn func(o *options) error {\n\t\to.leaveTimeout = timeout\n\t\treturn nil\n\t}\n}", "func WithDefaultTimeout(t time.Duration) Option {\n\treturn func(opt *options) {\n\t\topt.timeout = t\n\t}\n}", "func (c *Ctx) WithDeadline(deadline time.Time) (cf context.CancelFunc) {\n\tc.netContext, cf = context.WithDeadline(c.netContext, deadline)\n\treturn\n}", "func contextWithDeadline(t *testing.T) context.Context {\n\tt.Helper()\n\n\tdeadline, ok := t.Deadline()\n\tif !ok {\n\t\treturn context.Background()\n\t}\n\n\tctx, cancel := context.WithDeadline(context.Background(), deadline.Truncate(timeoutGracePeriod))\n\n\tt.Cleanup(cancel)\n\n\treturn ctx\n}", "func TimeoutOption(d time.Duration) Option {\n\treturn func(w *Webman) {\n\t\tw.timeout = d\n\t}\n}", "func (s *Sniffer) Recv(t *testing.T, timeout time.Duration) []byte {\n\tt.Helper()\n\n\tdeadline := time.Now().Add(timeout)\n\tfor {\n\t\ttimeout = time.Until(deadline)\n\t\tif timeout <= 0 {\n\t\t\treturn nil\n\t\t}\n\t\tusec := timeout.Microseconds()\n\t\tif usec == 0 {\n\t\t\t// Timeout is less than a microsecond; set usec to 1 to avoid\n\t\t\t// blocking indefinitely.\n\t\t\tusec = 1\n\t\t}\n\t\tconst microsInOne = 1e6\n\t\ttv := unix.Timeval{\n\t\t\tSec: usec / microsInOne,\n\t\t\tUsec: usec % microsInOne,\n\t\t}\n\t\tif err := unix.SetsockoptTimeval(s.fd, unix.SOL_SOCKET, unix.SO_RCVTIMEO, &tv); err != nil {\n\t\t\tt.Fatalf(\"can't setsockopt SO_RCVTIMEO: %s\", err)\n\t\t}\n\n\t\tbuf := make([]byte, maxReadSize)\n\t\tnread, _, err := unix.Recvfrom(s.fd, buf, unix.MSG_TRUNC)\n\t\tif err == unix.EINTR || err == unix.EAGAIN {\n\t\t\t// There was a timeout.\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"can't read: %s\", err)\n\t\t}\n\t\tif nread > maxReadSize {\n\t\t\tt.Fatalf(\"received a truncated frame of %d bytes, want at most %d bytes\", nread, maxReadSize)\n\t\t}\n\t\treturn buf[:nread]\n\t}\n}", "func (ch Ch) Send(value interface{}, timeout int) error{\n\tif timeout<=0{\n\t\treturn errors.New(\"timeout variable cannot be below or equals zero\")\n\t}\n\tselect {\n\tcase ch<-value:\n\t\treturn errors.New(\"sending data to channel timeout\")\n\tcase <-time.After(time.Duration(timeout)*time.Second):\n\t\treturn nil\n\t}\n}", "func (c *TestConnection) SetDeadline(t time.Time) error {\n return errors.New(\"Not implemented\")\n}", "func TestClock_AfterElectionTimeout(t *testing.T) {\n\tc := raft.NewClock()\n\tc.ElectionTimeout = 10 * time.Millisecond\n\tt0 := time.Now()\n\t<-c.AfterElectionTimeout()\n\tif d := time.Since(t0); d < c.ElectionTimeout {\n\t\tt.Fatalf(\"channel fired too soon: %v\", d)\n\t}\n}", "func (o TriggerBuildPtrOutput) Timeout() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TriggerBuild) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Timeout\n\t}).(pulumi.StringPtrOutput)\n}", "func (c *context) Deadline() (deadline time.Time, ok bool) { return c.c.Deadline() }", "func (ls *LState) OptChannel(n int, ch chan LValue) chan LValue {\n\tv := ls.Get(n)\n\tif v == LNil {\n\t\treturn ch\n\t}\n\tif ch, ok := v.(LChannel); ok {\n\t\treturn (chan LValue)(ch)\n\t}\n\tls.TypeError(n, LTChannel)\n\treturn nil\n}", "func (c *Clock) AfterReconnectTimeout() <-chan chan struct{} { return newClockChan(c.ReconnectTimeout) }", "func ConstructTimeoutQueue( workers int ) chan *packet_metadata {\n\n timeoutQueue := make(chan *packet_metadata, 1000000)\n return timeoutQueue\n}", "func (me Broker) TimeoutContext(ctx context.Context) (\n\tcontext.Context, context.CancelFunc,\n) {\n\treturn context.WithTimeout(ctx, me.Timeout)\n}", "func (o BuildSpecOutput) Timeout() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BuildSpec) *string { return v.Timeout }).(pulumi.StringPtrOutput)\n}", "func (rp *RaftProcess) GetWithTimeout(serial uint64, timeout int) (etf.Ref, error) {\n\tvar ref etf.Ref\n\tif rp.quorum == nil {\n\t\treturn ref, ErrRaftNoQuorum\n\t}\n\n\tpeers := []etf.Pid{}\n\tfor _, pid := range rp.quorum.Peers {\n\t\tif pid == rp.Self() {\n\t\t\tcontinue\n\t\t}\n\t\tif c := rp.quorumCandidates.GetOnline(pid); c != nil {\n\t\t\tif serial > c.serial {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpeers = append(peers, pid)\n\t\t}\n\t}\n\tif len(peers) == 0 {\n\t\treturn ref, ErrRaftNoSerial\n\t}\n\n\t// get random member of quorum and send the request\n\tn := 0\n\tif len(peers) > 1 {\n\t\trand.Intn(len(peers) - 1)\n\t}\n\tpeer := peers[n]\n\tref = rp.MakeRef()\n\trequestGet := etf.Tuple{\n\t\tetf.Atom(\"$request_get\"),\n\t\trp.Self(),\n\t\tetf.Tuple{\n\t\t\trp.options.ID,\n\t\t\tref,\n\t\t\trp.Self(), // origin\n\t\t\tserial,\n\t\t},\n\t}\n\n\tif err := rp.Cast(peer, requestGet); err != nil {\n\t\treturn ref, err\n\t}\n\tcancel := rp.CastAfter(rp.Self, messageRaftRequestClean{ref: ref}, time.Duration(timeout)*time.Second)\n\trp.requests[ref] = cancel\n\treturn ref, nil\n}", "func (c *Clock) AfterElectionTimeout() <-chan chan struct{} {\n\td := c.ElectionTimeout + time.Duration(rand.Intn(int(c.ElectionTimeout)))\n\treturn newClockChan(d)\n}", "func SubscribeTimeout() <-chan time.Time {\n\treturn Timeouts(GetSubscribeTimeout())\n}", "func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {\n\tctx, f := context.WithDeadline(parent, deadline)\n\treturn ctx, f\n}", "func WithTimeout(duration time.Duration) Option {\n\treturn wrappedOption{oconf.WithTimeout(duration)}\n}", "func CollectiveBcastRecvTimeoutSeconds(value float32) CollectiveBcastRecvAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"timeout_seconds\"] = value\n\t}\n}", "func (p *Peer) heartbeatTimeoutFunc() {\n\tfor {\n\t\t// Grab the current timer channel.\n\t\tp.mutex.Lock()\n\t\tvar c chan time.Time\n\t\tif p.heartbeatTimer != nil {\n\t\t\tc = p.heartbeatTimer.C()\n\t\t}\n\t\tp.mutex.Unlock()\n\n\t\t// If the channel or timer are gone then exit.\n\t\tif c == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Flush the peer when we get a heartbeat timeout. If the channel is\n\t\t// closed then the peer is getting cleaned up and we should exit.\n\t\tif _, ok := <-c; ok {\n\t\t\t// Retrieve the peer data within a lock that is separate from the\n\t\t\t// server lock when creating the request. Otherwise a deadlock can\n\t\t\t// occur.\n\t\t\tp.mutex.Lock()\n\t\t\tserver, prevLogIndex := p.server, p.prevLogIndex\n\t\t\tp.mutex.Unlock()\n\n\t\t\t// Lock the server to create a request.\n\t\t\treq := server.createAppendEntriesRequest(prevLogIndex)\n\n\t\t\tp.mutex.Lock()\n\t\t\tp.sendFlushRequest(req)\n\t\t\tp.mutex.Unlock()\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (p *tubePool) setDeadline(ctx context.Context, tube tube) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\tvar deadline time.Time\n\tif d, ok := ctx.Deadline(); ok {\n\t\tdeadline = d\n\t}\n\treturn tube.SetDeadline(deadline)\n}", "func (w *WebrtcConn) SetDeadline(t time.Time) error {\n\treturn nil\n}", "func AbsoluteTimeout(idle int) Option {\n\treturn func(s *storage) {\n\t\ts.idleTimeout = idle\n\t}\n}", "func Timeout(t time.Duration) DiscoverOption {\n\treturn func(o *dOpts) {\n\t\to.timeout = t\n\t}\n}", "func (p *Peer) maybeAddDeadline(pendingResponses map[string]time.Time, msgCmd string) {\n\t// Setup a deadline for each message being sent that expects a response.\n\t//\n\t// NOTE: Pings are intentionally ignored here since they are typically\n\t// sent asynchronously and as a result of a long backlock of messages,\n\t// such as is typical in the case of initial block download, the\n\t// response won't be received in time.\n\tdeadline := time.Now().Add(stallResponseTimeout)\n\tswitch msgCmd {\n\tcase wire.CmdVersion:\n\t\t// Expects a verack message.\n\t\tpendingResponses[wire.CmdVerAck] = deadline\n\n\tcase wire.CmdMemPool:\n\t\t// Expects an inv message.\n\t\tpendingResponses[wire.CmdInv] = deadline\n\n\tcase wire.CmdGetBlocks:\n\t\t// Expects an inv message.\n\t\tpendingResponses[wire.CmdInv] = deadline\n\n\tcase wire.CmdGetData:\n\t\t// Expects a block, merkleblock, tx, or notfound message.\n\t\tpendingResponses[wire.CmdBlock] = deadline\n\t\tpendingResponses[wire.CmdMerkleBlock] = deadline\n\t\tpendingResponses[wire.CmdTx] = deadline\n\t\tpendingResponses[wire.CmdNotFound] = deadline\n\n\tcase wire.CmdGetHeaders:\n\t\t// Expects a headers message. Use a longer deadline since it\n\t\t// can take a while for the remote peer to load all of the\n\t\t// headers.\n\t\tdeadline = time.Now().Add(stallResponseTimeout * 3)\n\t\tpendingResponses[wire.CmdHeaders] = deadline\n\t}\n}", "func (o TaskOutput) DispatchDeadline() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Task) pulumi.StringOutput { return v.DispatchDeadline }).(pulumi.StringOutput)\n}", "func (d *Dialer) SetDeadline(deadline time.Time) {\n\td.deadline = deadline\n\td.okdeadline = true\n}", "func timeout(c chan int, t int) {\n\tgo func() {\n\t\ttime.Sleep(time.Second * time.Duration(t))\n\t\tc <- 1\n\t}()\n}", "func (filterdev *NetworkTap) Timeout() (*syscall.Timeval, error) {\n\tvar tv syscall.Timeval\n\t_, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(filterdev.device.Fd()), syscall.BIOCGRTIMEOUT, uintptr(unsafe.Pointer(&tv)))\n\tif err != 0 {\n\t\treturn nil, syscall.Errno(err)\n\t}\n\treturn &tv, nil\n}", "func (s stdlib) Timeout(time.Duration) {}", "func After(d Duration) <-chan Time {}", "func newDeadlineTimer(deadline time.Time) *deadlineTimer {\n\treturn &deadlineTimer{\n\t\tt: time.NewTimer(time.Until(deadline)),\n\t}\n}", "func (mq *LinuxMessageQueue) ReceiveTimeout(data []byte, timeout time.Duration) (int, error) {\n\tlen, _, err := mq.ReceiveTimeoutPriority(data, timeout) // ignore proirity\n\treturn len, err\n}", "func Timeout(t time.Duration) Option {\n\treturn func(o *Options) {\n\t\to.Timeout = t\n\t}\n}", "func Timeout(t time.Duration) Option {\n\treturn func(o *Options) {\n\t\to.Timeout = t\n\t}\n}", "func Timeout(t time.Duration) Option {\n\treturn func(o *Options) {\n\t\to.Timeout = t\n\t}\n}", "func Timeout(t time.Duration) Option {\n\treturn func(o *Options) {\n\t\to.Timeout = t\n\t}\n}", "func (o *Basic) Timeout() int {\n\tif 0 == o.Options.Timeout {\n\t\treturn timeout\n\t}\n\treturn o.Options.Timeout\n}", "func Timeout(timeout time.Duration) ServerOption {\n\treturn func(s *Server) {\n\t\ts.timeout = timeout\n\t}\n}", "func (mq *LinuxMessageQueue) ReceiveTimeoutPriority(input []byte, timeout time.Duration) (int, int, error) {\n\tdataToReceive := input\n\tcurMaxMsgSize := len(mq.inputBuff)\n\tif len(input) < curMaxMsgSize {\n\t\tdataToReceive = mq.inputBuff\n\t}\n\tvar prio, actualMsgSize, maxMsgSize int\n\terr := common.UninterruptedSyscallTimeout(func(curTimeout time.Duration) error {\n\t\tvar err error\n\t\tactualMsgSize, maxMsgSize, err = mq_timedreceive(\n\t\t\tmq.ID(),\n\t\t\tdataToReceive,\n\t\t\t&prio,\n\t\t\tcommon.AbsTimeoutToTimeSpec(curTimeout))\n\t\treturn err\n\t}, timeout)\n\tif maxMsgSize != 0 && actualMsgSize != 0 {\n\t\tif curMaxMsgSize != maxMsgSize {\n\t\t\tmq.inputBuff = make([]byte, maxMsgSize)\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn 0, 0, errors.Wrap(err, \"linux mq: receive failed\")\n\t}\n\tif len(input) < curMaxMsgSize {\n\t\tif len(input) < actualMsgSize {\n\t\t\treturn 0, 0, errors.Errorf(\"the buffer of %d bytes is too small for a %d bytes message\", len(input), actualMsgSize)\n\t\t}\n\t\tcopy(input, dataToReceive[:actualMsgSize])\n\t}\n\treturn actualMsgSize, prio, nil\n}", "func (o BuildRunStatusBuildSpecPtrOutput) Timeout() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildRunStatusBuildSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Timeout\n\t}).(pulumi.StringPtrOutput)\n}", "func Timeout() time.Duration { return note.Timeout }", "func goTimeout(t *testing.T, d time.Duration, f func()) {\n\tch := make(chan bool, 2)\n\ttimer := time.AfterFunc(d, func() {\n\t\tt.Errorf(\"Timeout expired after %v\", d)\n\t\tch <- true\n\t})\n\tdefer timer.Stop()\n\tgo func() {\n\t\tdefer func() { ch <- true }()\n\t\tf()\n\t}()\n\t<-ch\n}", "func UnaryUniversalDeadline(d time.Duration) grpc.UnaryServerInterceptor {\n\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\n\t\t//Also can get a deadline from the metadata\n\t\tctx, _ = context.WithDeadline(ctx, time.Now().Add(d))\n\n\t\tdone := make(chan bool)\n\n\t\tgo func() {\n\t\t\tresp, err = handler(ctx, req)\n\t\t\tdone <- true\n\t\t}()\n\n\t\t//Will return an error if the deadline passes before the handler is finished... should also figure out how to stop the handler from continuing if possible?\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, errors.New(\"Unable to complete request due to deadline\")\n\t\tcase <-done:\n\t\t\treturn resp, err\n\t\t}\n\t}\n}", "func (s *Conn) Timeout() time.Duration {\n\tif s.state == stateClosed {\n\t\treturn -1\n\t}\n\tnow := s.timeFn()\n\ts.logLossTimer(now)\n\tvar deadline time.Time\n\tif !s.drainingTimer.IsZero() {\n\t\tdeadline = s.drainingTimer\n\t} else if !s.recovery.lossDetectionTimer.IsZero() {\n\t\t// Minimum of loss and idle timer\n\t\tdeadline = s.recovery.lossDetectionTimer\n\t\tif !s.idleTimer.IsZero() && deadline.After(s.idleTimer) {\n\t\t\tdeadline = s.idleTimer\n\t\t}\n\t} else if !s.idleTimer.IsZero() {\n\t\tdeadline = s.idleTimer\n\t} else {\n\t\treturn -1\n\t}\n\ttimeout := deadline.Sub(now)\n\tif timeout < 0 {\n\t\ttimeout = 0\n\t}\n\treturn timeout\n}", "func (c *HostClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error {\n\treq.timeout = time.Until(deadline)\n\tif req.timeout < 0 {\n\t\treturn ErrTimeout\n\t}\n\treturn c.Do(req, resp)\n}", "func TestMock_WithDeadlineCancelledWithParent(t *testing.T) {\n\tm := NewMock()\n\tparent, cancel := context.WithCancel(context.Background())\n\tctx, _ := m.WithDeadline(parent, m.Now().Add(time.Second))\n\tcancel()\n\tselect {\n\tcase <-ctx.Done():\n\t\tif !errors.Is(ctx.Err(), context.Canceled) {\n\t\t\tt.Error(\"invalid type of error returned after cancellation\")\n\t\t}\n\tcase <-time.After(time.Second):\n\t\tt.Error(\"context is not cancelled when parent context is cancelled\")\n\t}\n}", "func DefaultChooseTimeout(timeout time.Duration) Option {\n\treturn optionFunc(func(options *options) {\n\t\toptions.defaultChooseTimeout = &timeout\n\t})\n}", "func (w *ChannelWriter) Write(b []byte) (sz int, err error) {\n\tselect {\n\tcase w.c <- b:\n\t\treturn len(b), nil\n\tdefault:\n\t}\n\n\tif w.deadline.IsZero() {\n\t\tw.c <- b\n\t\treturn len(b), nil\n\t}\n\n\ttimer := time.NewTimer(w.deadline.Sub(time.Now()))\n\tdefer timer.Stop()\n\n\tselect {\n\tcase w.c <- b:\n\t\treturn len(b), nil\n\tcase <-timer.C:\n\t\treturn 0, context.DeadlineExceeded\n\t}\n}", "func (c *MockedHTTPContext) Deadline() (deadline time.Time, ok bool) {\n\tif c.MockedDeadline != nil {\n\t\treturn c.MockedDeadline()\n\t}\n\treturn time.Now(), false\n}", "func (c *txnClientCtx) commitTimeout(waitmsync bool) time.Duration {\n\tif waitmsync {\n\t\treturn c.timeout.host + c.timeout.netw\n\t}\n\treturn c.timeout.netw\n}", "func GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error) {\n\treturn defaultClient.GetDeadline(dst, url, deadline)\n}", "func Timeout(timeout int64) Option {\n\treturn func(opts *options) {\n\t\topts.timeout = time.Duration(timeout) * time.Second\n\t}\n}", "func (bw *BlockWriter) SetDeadline(t time.Time) error {\n\tbw.deadline = t\n\tif bw.conn != nil {\n\t\treturn bw.conn.SetDeadline(t)\n\t}\n\n\t// Return the error at connection time.\n\treturn nil\n}", "func TestWait_timeout(t *testing.T) {\n\tdefer check(t)\n\tcontent := \"hello world!\"\n\treq := &showcasepb.WaitRequest{\n\t\tEnd: &showcasepb.WaitRequest_Ttl{\n\t\t\tTtl: &durationpb.Duration{Seconds: 1},\n\t\t},\n\t\tResponse: &showcasepb.WaitRequest_Success{\n\t\t\tSuccess: &showcasepb.WaitResponse{Content: content},\n\t\t},\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)\n\tdefer cancel()\n\n\top, err := echo.Wait(ctx, req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err := op.Wait(ctx)\n\tif err == nil {\n\t\tt.Errorf(\"Wait() = %+v, want error\", resp)\n\t}\n}", "func (o *ChatNewParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func TestClock_AfterReconnectTimeout(t *testing.T) {\n\tc := raft.NewClock()\n\tc.ReconnectTimeout = 10 * time.Millisecond\n\tt0 := time.Now()\n\t<-c.AfterReconnectTimeout()\n\tif d := time.Since(t0); d < c.ReconnectTimeout {\n\t\tt.Fatalf(\"channel fired too soon: %v\", d)\n\t}\n}" ]
[ "0.5174397", "0.5156724", "0.5065961", "0.5060068", "0.5043165", "0.50363374", "0.4978916", "0.49680018", "0.4962167", "0.49414706", "0.4929812", "0.48641688", "0.4854244", "0.48350728", "0.48332527", "0.48316026", "0.48256624", "0.48114562", "0.47939524", "0.4789711", "0.47847196", "0.47820517", "0.4776915", "0.47548705", "0.473034", "0.4723146", "0.46795171", "0.46763182", "0.46665353", "0.46609327", "0.46577755", "0.46575493", "0.46482185", "0.46426922", "0.46171218", "0.46170467", "0.4607814", "0.46071237", "0.45909518", "0.45901194", "0.45803556", "0.45725545", "0.45688236", "0.4547528", "0.45288515", "0.4518878", "0.45178142", "0.45161188", "0.45082343", "0.45046124", "0.44831705", "0.44797885", "0.44760364", "0.4474829", "0.4473707", "0.44691256", "0.44633913", "0.44555062", "0.44487435", "0.44480565", "0.44454473", "0.44409165", "0.44384676", "0.4432694", "0.4429949", "0.44201207", "0.44200516", "0.441241", "0.44016257", "0.43789184", "0.4372708", "0.43649206", "0.43616393", "0.43600416", "0.4357924", "0.43565834", "0.4347601", "0.4347601", "0.4347601", "0.4347601", "0.4345919", "0.43438876", "0.4342106", "0.43370944", "0.43344143", "0.43302944", "0.43174005", "0.43167153", "0.43138948", "0.4309054", "0.43069974", "0.43054056", "0.4301684", "0.43007502", "0.43001688", "0.42981714", "0.42959014", "0.42866904", "0.42802998", "0.42761993" ]
0.8052867
0
copyHeader adds the HTTP header whose name is the specified `which` from the specified headers `from` to the specified headers `to`.
func copyHeader(which string, from http.Header, to http.Header) { for _, value := range from.Values(which) { to.Add(which, value) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func copyHeader(target, source http.Header) {\n\tfor k, vs := range source {\n\t\ttarget[k] = vs\n\t}\n}", "func copyHeader(src, dest http.Header) {\n\tfor key, val := range src {\n\t\tfor _, v := range val {\n\t\t\tdest.Add(key, v)\n\t\t}\n\t}\n}", "func copyHeader(dst http.Header, src http.Header) {\n\tfor k, _ := range dst {\n\t\tdst.Del(k)\n\t}\n\tfor k, vv := range src {\n\t\tfor _, v := range vv {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}", "func copyHeaders(source http.Header, destination http.Header) {\n\tfor h, vs := range source {\n\t\tfor _, v := range vs {\n\t\t\tdestination.Set(h, v)\n\t\t}\n\t}\n}", "func (h *RequestHeader) CopyTo(dst *RequestHeader) {\n\tdst.Reset()\n\n\tdst.disableNormalizing = h.disableNormalizing\n\tdst.noHTTP11 = h.noHTTP11\n\tdst.connectionClose = h.connectionClose\n\tdst.noDefaultContentType = h.noDefaultContentType\n\n\tdst.contentLength = h.contentLength\n\tdst.contentLengthBytes = append(dst.contentLengthBytes, h.contentLengthBytes...)\n\tdst.method = append(dst.method, h.method...)\n\tdst.proto = append(dst.proto, h.proto...)\n\tdst.requestURI = append(dst.requestURI, h.requestURI...)\n\tdst.host = append(dst.host, h.host...)\n\tdst.contentType = append(dst.contentType, h.contentType...)\n\tdst.userAgent = append(dst.userAgent, h.userAgent...)\n\tdst.trailer = append(dst.trailer, h.trailer...)\n\tdst.h = copyArgs(dst.h, h.h)\n\tdst.cookies = copyArgs(dst.cookies, h.cookies)\n\tdst.cookiesCollected = h.cookiesCollected\n\tdst.rawHeaders = append(dst.rawHeaders, h.rawHeaders...)\n}", "func CopyHeader(w http.ResponseWriter, r *http.Response) {\n\t// copy headers\n\tdst, src := w.Header(), r.Header\n\tfor k := range dst {\n\t\tdst.Del(k)\n\t}\n\tfor k, vs := range src {\n\t\tfor _, v := range vs {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}", "func CopyRequestHeaders(from, to *http.Request, headers []string) {\n\tfor _, header := range headers {\n\t\tvalue := from.Header.Get(header)\n\t\tif value != \"\" {\n\t\t\tto.Header.Set(header, value)\n\t\t}\n\t}\n}", "func copyHeaders(dst, src http.Header) {\n\tfor key, vals := range src {\n\t\tfor _, val := range vals {\n\t\t\tdst.Add(key, val)\n\t\t}\n\t}\n}", "func copySourceHeaders(sh http.Header) (th http.Header) {\n\tth = make(http.Header)\n\n\tif sh == nil {\n\t\treturn nil\n\t}\n\n\tfor key, values := range sh {\n\t\tif dhHeadersRe.MatchString(key) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, val := range values {\n\t\t\tth.Add(key, val)\n\t\t}\n\t}\n\n\treturn th\n}", "func CopyHeaders(dst, src http.Header) {\n\tfor k, vv := range src {\n\t\tdst[k] = append([]string{}, vv...)\n\t}\n}", "func copyHeaders(headerNames []string, srcRequest *http.Request, destRequest *http.Request) {\n for _, headerName := range headerNames {\n // TODO: make sure headerName exists in srcRequest.Header\n if headerValue := srcRequest.Header.Get(headerName); headerValue != \"\" {\n destRequest.Header.Set(headerName, headerValue)\n }\n }\n}", "func (h *ResponseHeader) CopyTo(dst *ResponseHeader) {\n\tdst.Reset()\n\n\tdst.disableNormalizing = h.disableNormalizing\n\tdst.noHTTP11 = h.noHTTP11\n\tdst.connectionClose = h.connectionClose\n\tdst.noDefaultContentType = h.noDefaultContentType\n\tdst.noDefaultDate = h.noDefaultDate\n\n\tdst.statusCode = h.statusCode\n\tdst.statusMessage = append(dst.statusMessage, h.statusMessage...)\n\tdst.protocol = append(dst.protocol, h.protocol...)\n\tdst.contentLength = h.contentLength\n\tdst.contentLengthBytes = append(dst.contentLengthBytes, h.contentLengthBytes...)\n\tdst.contentType = append(dst.contentType, h.contentType...)\n\tdst.contentEncoding = append(dst.contentEncoding, h.contentEncoding...)\n\tdst.server = append(dst.server, h.server...)\n\tdst.h = copyArgs(dst.h, h.h)\n\tdst.cookies = copyArgs(dst.cookies, h.cookies)\n\tdst.trailer = copyArgs(dst.trailer, h.trailer)\n}", "func CopyHeader(h *Header) *Header {\n\tcpy := *h\n\tif cpy.Time = new(big.Int); h.Time != nil {\n\t\tcpy.Time.Set(h.Time)\n\t}\n\tif cpy.SnailNumber = new(big.Int); h.SnailNumber != nil {\n\t\tcpy.SnailNumber.Set(h.SnailNumber)\n\t}\n\tif cpy.Number = new(big.Int); h.Number != nil {\n\t\tcpy.Number.Set(h.Number)\n\t}\n\tif len(h.Extra) > 0 {\n\t\tcpy.Extra = make([]byte, len(h.Extra))\n\t\tcopy(cpy.Extra, h.Extra)\n\t}\n\treturn &cpy\n}", "func CopyHeader(dst *LogBuffer, src *LogBuffer) {\n\tsrc.headerMU.Lock()\n\tdup, err := copystructure.Copy(src.header)\n\tdupBanner := src.AddBanner\n\tsrc.headerMU.Unlock()\n\n\tdst.headerMU.Lock()\n\tif err != nil {\n\t\tdst.header = map[string]interface{}{}\n\t} else {\n\t\tdst.header = dup.(map[string]interface{})\n\t}\n\tdst.AddBanner = dupBanner\n\tdst.headerMU.Unlock()\n}", "func copyHeaders(resp *http.Response, w http.ResponseWriter) {\n\tfor key, values := range resp.Header {\n\t\tfor _, value := range values {\n\t\t\tw.Header().Add(key, value)\n\t\t}\n\t}\n}", "func copyHeaders(headers map[string]interface{}) map[string]interface{} {\n\treturn copyHeader(headers).(map[string]interface{})\n}", "func (w *responseWrapper) copy(rw http.ResponseWriter) {\n\trw.WriteHeader(w.status)\n\n\tfor k, v := range w.header {\n\t\tfor _, vv := range v {\n\t\t\trw.Header().Add(k, vv)\n\t\t}\n\t}\n\tio.Copy(rw, w.buffer)\n}", "func copyHeader(v interface{}) interface{} {\n\tswitch x := v.(type) {\n\tcase string:\n\t\treturn x\n\tcase []interface{}:\n\t\tres := make([]interface{}, len(x))\n\t\tfor i, elem := range x {\n\t\t\tres[i] = copyHeader(elem)\n\t\t}\n\t\treturn res\n\tcase map[string]interface{}:\n\t\tres := make(map[string]interface{}, len(x))\n\t\tfor name, value := range x {\n\t\t\tif value == nil {\n\t\t\t\tcontinue // normalize nils out\n\t\t\t}\n\t\t\tres[name] = copyHeader(value)\n\t\t}\n\t\treturn res\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"internal error: encountered unexpected value type copying headers: %v\", v))\n\t}\n}", "func (_m *requestHeaderMapUpdatable) AddCopy(name string, value string) {\n\t_m.Called(name, value)\n}", "func copyHeadersToSend(headersToSend []string, r *ProxyRequest) map[string][]string {\n\tif len(headersToSend) == 0 {\n\t\theadersToSend = defaultHeadersToSend\n\t}\n\n\theaders := make(map[string][]string, len(headersToSend))\n\n\tfor _, k := range headersToSend {\n\t\tif k == requestParamsAsterisk {\n\t\t\tfor name, vs := range r.Headers {\n\t\t\t\ttmp := make([]string, len(vs))\n\t\t\t\tcopy(tmp, vs)\n\t\t\t\theaders[name] = tmp\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tvs, ok := r.Headers[k]\n\t\tif ok {\n\t\t\ttmp := make([]string, len(vs))\n\t\t\tcopy(tmp, vs)\n\t\t\theaders[k] = tmp\n\t\t}\n\t}\n\n\treturn headers\n}", "func newHTTPHeader(header, value string) httpHeader {\n\treturn httpHeader{Header: header, Value: value}\n}", "func CopyZipkinHeaders(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdata := make(map[string]string, 7)\n\t\tfor _, key := range zipkinHeaders {\n\t\t\tv := r.Header.Get(key)\n\t\t\tif v != \"\" {\n\t\t\t\tdata[key] = v\n\t\t\t}\n\t\t}\n\t\tmd := metadata.New(data)\n\t\tctx := metadata.NewOutgoingContext(r.Context(), md)\n\t\tr = r.WithContext(ctx)\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (_m *requestHeaderMapUpdatable) AppendCopy(name string, value string) {\n\t_m.Called(name, value)\n}", "func (params *headerParams) Copy() Params {\n\tdup := NewParams()\n\tfor _, key := range params.Keys() {\n\t\tif val, ok := params.Get(key); ok {\n\t\t\tdup.Add(key, val)\n\t\t}\n\t}\n\n\treturn dup\n}", "func writeToHeader(w *http.ResponseWriter, statusCode int, payload interface{}) {\n\t(*w).WriteHeader(statusCode)\n\t(*w).Write(payload.([]byte))\n}", "func (h CommonHeader) Clone() api.HeaderMap {\n\tcopy := make(map[string]string)\n\n\tfor k, v := range h {\n\t\tcopy[k] = v\n\t}\n\n\treturn CommonHeader(copy)\n}", "func (t *Target) AddHeader(key, value string) {\n t.header.Add(key, value)\n}", "func (_m *requestHeaderMapUpdatable) SetCopy(name string, value string) {\n\t_m.Called(name, value)\n}", "func copyRequest(req *http.Request) *http.Request {\n\treq2 := new(http.Request)\n\t*req2 = *req\n\treq2.URL = new(url.URL)\n\t*req2.URL = *req.URL\n\treq2.Header = make(http.Header, len(req.Header))\n\tfor k, s := range req.Header {\n\t\treq2.Header[k] = append([]string(nil), s...)\n\t}\n\treturn req2\n}", "func (i *ICoreWebView2HttpRequestHeaders) SetHeader(name, value string) error {\n\t_name, err := windows.UTF16PtrFromString(name)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t_value, err := windows.UTF16PtrFromString(value)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tres, _, err := i.vtbl.SetHeader.Call(\n\t\tuintptr(unsafe.Pointer(i)),\n\t\tuintptr(unsafe.Pointer(_name)),\n\t\tuintptr(unsafe.Pointer(_value)),\n\t)\n\tif err != windows.ERROR_SUCCESS {\n\t\treturn err\n\t}\n\tif windows.Handle(res) != windows.S_OK {\n\t\treturn syscall.Errno(res)\n\t}\n\treturn nil\n}", "func copy(to, from string) error {\n\ttoFd, err := os.Create(to)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer toFd.Close()\n\tfromFd, err := os.Open(from)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fromFd.Close()\n\t_, err = io.Copy(toFd, fromFd)\n\treturn err\n}", "func copy(to, from string) error {\n\ttoFd, err := os.Create(to)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer toFd.Close()\n\tfromFd, err := os.Open(from)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fromFd.Close()\n\t_, err = io.Copy(toFd, fromFd)\n\treturn err\n}", "func NewHeader(m map[string]string) Header {\n\tfor k, v := range m {\n\t\tdelete(m, k)\n\t\tm[http.CanonicalHeaderKey(k)] = v\n\t}\n\treturn Header(m)\n}", "func addHeaders(req *http.Request, opt *Options) {\n\tfor i := 0; i < len(opt.Headers); i += 2 {\n\t\tkey := opt.Headers[i]\n\t\tvalue := opt.Headers[i+1]\n\t\treq.Header.Add(key, value)\n\t}\n}", "func (this *SIPMessage) AddHeader(sipHeader header.Header) {\n\t// Content length is never stored. Just computed.\n\tsh := sipHeader.(header.Header)\n\t//try {\n\tif _, ok := sipHeader.(header.ViaHeader); ok {\n\t\tthis.AttachHeader3(sh, false, true)\n\t} else {\n\t\tthis.AttachHeader3(sh, false, false)\n\t}\n\t// } catch (SIPDuplicateHeaderException ex) {\n\t//try {\n\t//if cl, ok := sipHeader.(header.ContentLengthHeader); ok {\n\t//\t\tcontentLengthHeader.SetContentLength(cl.GetContentLength())\n\t//\t}\n\t// } catch (InvalidArgumentException e) {}\n\t//}\n}", "func (h *RequestHeader) WriteTo(w io.Writer) (int64, error) {\n\tn, err := w.Write(h.Header())\n\treturn int64(n), err\n}", "func (framer *HTTPFramer) Copy(dest io.Writer, src io.Reader) error {\n\tresp, err := http.ReadResponse(bufio.NewReader(src), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn resp.Write(dest)\n}", "func CopySnailHeader(h *SnailHeader) *SnailHeader {\n\tcpy := *h\n\tif cpy.Time = new(big.Int); h.Time != nil {\n\t\tcpy.Time.Set(h.Time)\n\t}\n\tif cpy.Difficulty = new(big.Int); h.Difficulty != nil {\n\t\tcpy.Difficulty.Set(h.Difficulty)\n\t}\n\tif cpy.FruitDifficulty = new(big.Int); h.FruitDifficulty != nil {\n\t\tcpy.FruitDifficulty.Set(h.FruitDifficulty)\n\t}\n\tif cpy.Number = new(big.Int); h.Number != nil {\n\t\tcpy.Number.Set(h.Number)\n\t}\n\tif cpy.FastNumber = new(big.Int); h.FastNumber != nil {\n\t\tcpy.FastNumber.Set(h.FastNumber)\n\t}\n\tif cpy.PointerNumber = new(big.Int); h.PointerNumber != nil {\n\t\tcpy.PointerNumber.Set(h.PointerNumber)\n\t}\n\tif len(h.Publickey) > 0 {\n\t\tcpy.Publickey = make([]byte, len(h.Publickey))\n\t\tcopy(cpy.Publickey, h.Publickey)\n\t}\n\tif len(h.Extra) > 0 {\n\t\tcpy.Extra = make([]byte, len(h.Extra))\n\t\tcopy(cpy.Extra, h.Extra)\n\t}\n\treturn &cpy\n}", "func (b binder) setFromHeaders() HTTPError {\n\tfor k, values := range b.req.Header {\n\t\tk = strings.ToLower(k)\n\t\tfor _, v := range values {\n\t\t\tif err := b.setField(k, v, ParamSourceHeader); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func DirtHeader(req *http.Request, header string, oldValue ...string) {\n\tvar dirtyHeaders map[string]string = make(map[string]string)\n\theader = sanitizeHeaderName(header)\n\toldVal := \"\"\n\tif len(oldVal) > 0 {\n\t\toldVal = oldValue[0]\n\t}\n\tdirtyHeadersPtr := DirtyHeaders(req)\n\tif dirtyHeadersPtr == nil {\n\t\tdirtyHeaders[header] = oldVal\n\t\tAddContextValue(req, dirtyHeadersKey, &dirtyHeaders)\n\t\treturn\n\t}\n\tdirtyHeaders = *dirtyHeadersPtr\n\tdirtyHeaders[header] = oldVal\n\t*dirtyHeadersPtr = dirtyHeaders\n}", "func (in *HTTPHeader) DeepCopyInto(out *HTTPHeader) {\n\t*out = *in\n\tif in.HeaderName != nil {\n\t\tin, out := &in.HeaderName, &out.HeaderName\n\t\t*out = new(string)\n\t\t**out = **in\n\t}\n\tif in.HeaderValue != nil {\n\t\tin, out := &in.HeaderValue, &out.HeaderValue\n\t\t*out = new(string)\n\t\t**out = **in\n\t}\n}", "func (hs *headers) PrependHeader(header Header) {\n\tname := strings.ToLower(header.Name())\n\tif hers, ok := hs.headers[name]; ok {\n\t\ths.headers[name] = append([]Header{header}, hers...)\n\t} else {\n\t\ths.headers[name] = []Header{header}\n\t\tnewOrder := make([]string, 1, len(hs.headerOrder)+1)\n\t\tnewOrder[0] = name\n\t\ths.headerOrder = append(newOrder, hs.headerOrder...)\n\t}\n}", "func ApplyHeaders(req *http.Request, h string) error {\n\tvar list = strings.Split(h, \"\\x1e\")\n\tfor _, fv := range list {\n\t\tvar parts = strings.SplitN(fv, \":\", 2)\n\t\tif len(parts) != 2 {\n\t\t\treturn fmt.Errorf(\"invalid header declaration %q\", fv)\n\t\t}\n\t\treq.Header.Set(parts[0], parts[1])\n\t}\n\n\treturn nil\n}", "func (self *AbtabURL) SetHeader(header []string) {\n\tself.Header = header\n\tself.HeaderMap = make(map[string]int)\n\tfor idx, fname := range header {\n\t\t//fmt.Printf(\"SetHeader: %s=%d\\n\", fname, idx)\n\t\tself.HeaderMap[fname] = idx\n\t}\n}", "func (h HeaderV2) WriteTo(w io.Writer) (int64, error) {\n\tif h.Command > CmdProxy {\n\t\treturn 0, errors.New(\"invalid command\")\n\t}\n\n\tvar rawHdr rawV2\n\tcopy(rawHdr.Sig[:], sigV2)\n\trawHdr.VerCmd = (2 << 4) | (0xf & byte(h.Command))\n\tsendEmpty := func() (int64, error) {\n\t\terr := binary.Write(w, binary.BigEndian, rawHdr)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn 16, nil\n\t}\n\tif h.Command == CmdLocal {\n\t\treturn sendEmpty()\n\t}\n\n\tbuf := newBuffer(16, 232)\n\n\tsetAddr := func(srcIP, dstIP net.IP, srcPort, dstPort int) (fam byte) {\n\t\tsrc := srcIP.To4()\n\t\tdst := dstIP.To4()\n\t\tif src != nil && dst != nil {\n\t\t\tfam = 0x1 // INET\n\t\t} else if src == nil && dst == nil {\n\t\t\tsrc = srcIP.To16()\n\t\t\tdst = dstIP.To16()\n\t\t\tfam = 0x2 // INET6\n\t\t}\n\t\tif src == nil || dst == nil {\n\t\t\treturn 0 // UNSPEC\n\t\t}\n\n\t\tbuf.Write(src)\n\t\tbuf.Write(dst)\n\t\tbinary.Write(buf, binary.BigEndian, uint16(srcPort))\n\t\tbinary.Write(buf, binary.BigEndian, uint16(dstPort))\n\n\t\treturn fam\n\t}\n\n\tswitch src := h.Src.(type) {\n\tcase *net.TCPAddr:\n\t\tdst, ok := h.Dest.(*net.TCPAddr)\n\t\tif !ok {\n\t\t\treturn sendEmpty()\n\t\t}\n\t\taddrFam := setAddr(src.IP, dst.IP, src.Port, dst.Port)\n\t\tif addrFam == 0 {\n\t\t\treturn sendEmpty()\n\t\t}\n\t\trawHdr.FamProto = (addrFam << 4) | 0x1 // 0x1 == STREAM\n\tcase *net.UDPAddr:\n\t\tdst, ok := h.Dest.(*net.UDPAddr)\n\t\tif !ok {\n\t\t\treturn sendEmpty()\n\t\t}\n\t\taddrFam := setAddr(src.IP, dst.IP, src.Port, dst.Port)\n\t\tif addrFam == 0 {\n\t\t\treturn sendEmpty()\n\t\t}\n\t\trawHdr.FamProto = (addrFam << 4) | 0x2 // 0x2 == DGRAM\n\tcase *net.UnixAddr:\n\t\tdst, ok := h.Dest.(*net.UnixAddr)\n\t\tif !ok || src.Net != dst.Net {\n\t\t\treturn sendEmpty()\n\t\t}\n\t\tif len(src.Name) > 108 || len(dst.Name) > 108 {\n\t\t\t// name too long to use\n\t\t\treturn sendEmpty()\n\t\t}\n\t\tswitch src.Net {\n\t\tcase \"unix\":\n\t\t\trawHdr.FamProto = (0x3 << 4) | 0x1 // 0x3 (UNIX) | 0x1 (STREAM)\n\t\tcase \"unixgram\":\n\t\t\trawHdr.FamProto = (0x3 << 4) | 0x2 // 0x3 (UNIX) | 0x2 (DGRAM)\n\t\tdefault:\n\t\t\treturn sendEmpty()\n\t\t}\n\t\tbuf.Write([]byte(src.Name))\n\t\tbuf.Seek(108 + 16)\n\t\tbuf.Write([]byte(dst.Name))\n\t\tbuf.Seek(232)\n\t}\n\n\trawHdr.Len = uint16(buf.Len() - 16)\n\n\tbuf.Seek(0)\n\terr := binary.Write(buf, binary.BigEndian, rawHdr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn buf.WriteTo(w)\n}", "func (this *SIPMessage) AttachHeader3(h header.Header, replaceFlag, top bool) error { //throws SIPDuplicateHeaderException {\n\tif h == nil {\n\t\terrors.New(\"NullPointerException: nil header\")\n\t}\n\n\tif replaceFlag {\n\t\tdelete(this.nameTable, strings.ToLower(h.GetName()))\n\t} else {\n\t\tif _, present := this.nameTable[strings.ToLower(h.GetName())]; present {\n\t\t\tif _, ok := h.(header.SIPHeaderLister); !ok {\n\t\t\t\tif cl, ok := h.(*header.ContentLength); ok {\n\t\t\t\t\tthis.contentLengthHeader.SetContentLength(cl.GetContentLength())\n\t\t\t\t}\n\t\t\t\t// Just ignore duplicate header.\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\toriginalHeader := this.GetHeader(h.GetName())\n\n\t// Delete the original sh from our list structure.\n\tif originalHeader != nil {\n\t\tfor li := this.headers.Front(); li != nil; li = li.Next() {\n\t\t\tnext := li.Value.(header.Header)\n\t\t\tif next == originalHeader {\n\t\t\t\tthis.headers.Remove(li)\n\t\t\t}\n\t\t}\n\t}\n\n\tif this.GetHeader(h.GetName()) == nil {\n\t\tthis.nameTable[strings.ToLower(h.GetName())] = h\n\t\tthis.headers.PushBack(h)\n\t} else {\n\t\tif hs, ok := h.(header.SIPHeaderLister); ok {\n\t\t\thdrlist := this.nameTable[strings.ToLower(h.GetName())].(header.SIPHeaderLister)\n\t\t\tif hdrlist != nil {\n\t\t\t\thdrlist.Concatenate(hs, top)\n\t\t\t} else {\n\t\t\t\tthis.nameTable[strings.ToLower(h.GetName())] = h\n\t\t\t}\n\t\t} else {\n\t\t\tthis.nameTable[strings.ToLower(h.GetName())] = h\n\t\t}\n\t}\n\n\t// Direct accessor fields for frequently accessed headers.\n\tif sh, ok := h.(*header.From); ok {\n\t\tthis.fromHeader = sh\n\t} else if sh, ok := h.(*header.ContentLength); ok {\n\t\tthis.contentLengthHeader = sh\n\t} else if sh, ok := h.(*header.To); ok {\n\t\tthis.toHeader = sh\n\t} else if sh, ok := h.(*header.CSeq); ok {\n\t\tthis.cSeqHeader = sh\n\t} else if sh, ok := h.(*header.CallID); ok {\n\t\tthis.callIdHeader = sh\n\t} else if sh, ok := h.(*header.MaxForwards); ok {\n\t\tthis.maxForwardsHeader = sh\n\t}\n\n\treturn nil\n}", "func copyInnerNodeHeader(dst, src *innerNodeHeader) {\n\t// Shallow copy is sufficient because prefix is an embedded array of byte\n\t// not a slice pointing to a shared array, but we can't just use = since\n\t// that would override the id and ref in nodeHeader\n\tdst.leaf = src.leaf\n\tdst.nChildren = src.nChildren\n\tdst.prefixLen = src.prefixLen\n\tdst.prefix = src.prefix\n}", "func (c *Action) AddHeader(key string, value string) {\n\tc.Header().Add(key, value)\n}", "func (f *FileAttributes) HeaderAttributesCopy() map[string]any {\n\treturn mapCopy(f.HeaderAttributes)\n}", "func (proxy *Proxy) copyRequest(originalRequest *http.Request) *http.Request {\n\tproxyRequest := new(http.Request)\n\tproxyURL := new(url.URL)\n\t*proxyRequest = *originalRequest\n\t*proxyURL = *originalRequest.URL\n\tproxyRequest.URL = proxyURL\n\tproxyRequest.Proto = \"HTTP/1.1\"\n\tproxyRequest.ProtoMajor = 1\n\tproxyRequest.ProtoMinor = 1\n\tproxyRequest.Close = false\n\tproxyRequest.Header = make(http.Header)\n\tproxyRequest.URL.Scheme = \"http\"\n\tproxyRequest.URL.Path = originalRequest.URL.Path\n\n\t// Copy all header fields except ignoredHeaderNames'.\n\tnv := 0\n\tfor _, vv := range originalRequest.Header {\n\t\tnv += len(vv)\n\t}\n\tsv := make([]string, nv)\n\tfor k, vv := range originalRequest.Header {\n\t\tif _, ok := ignoredHeaderNames[k]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tn := copy(sv, vv)\n\t\tproxyRequest.Header[k] = sv[:n:n]\n\t\tsv = sv[n:]\n\t}\n\n\treturn proxyRequest\n}", "func (t Header) Clone() Header {\n\tt.Key = append([]KeyField{}, t.Key...)\n\tt.Data = append([]Field{}, t.Data...)\n\treturn t\n}", "func (hs *headers) CloneHeaders() []Header {\n\thers := make([]Header, 0)\n\tfor _, header := range hs.Headers() {\n\t\thers = append(hers, header.Copy())\n\t}\n\n\treturn hers\n}", "func copyTo(dst []byte, src []byte, offset int) {\n\tfor j, k := range src {\n\t\tdst[offset+j] = k\n\t}\n}", "func CopySourceIfMatch(value string) Option {\n\treturn setHeader(\"X-Oss-Copy-Source-If-Match\", value)\n}", "func (h *Header) Clone() *Header {\n\thc := &Header{slice: make([]string, len(h.slice))}\n\tcopy(hc.slice, h.slice)\n\treturn hc\n}", "func (headers Headers) UpdateHeader(reqHeaders http.Header) {\n\tfor _, h := range headers {\n\t\tswitch h.Op {\n\t\tcase \"\", \"set\":\n\t\t\treqHeaders.Set(h.Key, h.Value)\n\t\tcase \"add\":\n\t\t\treqHeaders.Add(h.Key, h.Value)\n\t\tcase \"del\":\n\t\t\treqHeaders.Del(h.Key)\n\t\t}\n\t}\n}", "func Header(k, v string) RequestOpt { return func(r *http.Request) { r.Header.Add(k, v) } }", "func InjectHeader(h http.Header) InterceptorFn {\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn RoundTripperFn(func(req *http.Request) (*http.Response, error) {\n\t\t\tfor k, v := range h {\n\t\t\t\tfor _, vv := range v {\n\t\t\t\t\treq.Header.Add(k, vv)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn rt.RoundTrip(req)\n\t\t})\n\t}\n}", "func mergeHeaders(h1, h2 http.Header) http.Header {\n\th := http.Header{}\n\tfor key, values := range h2 {\n\t\tfor _, value := range values {\n\t\t\th.Set(key, value)\n\t\t}\n\t}\n\tfor key, values := range h1 {\n\t\tfor _, value := range values {\n\t\t\th.Set(key, value)\n\t\t}\n\t}\n\treturn h\n}", "func (c *PrivateClient) addHeaders(req *http.Request, h headers) *http.Request {\n\tfor k, v := range c.headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tif h != nil {\n\t\tfor k, v := range h {\n\t\t\treq.Header[k] = v\n\t\t}\n\t}\n\treturn req\n}", "func PassThroughHeaders(headers http.Header) http.Header {\n\th := http.Header{}\n\n\tfor n, v := range headers {\n\t\tlower := strings.ToLower(n)\n\t\tif forwardHeaders.Has(lower) {\n\t\t\th[n] = v\n\t\t\tcontinue\n\t\t}\n\t\tfor _, prefix := range forwardPrefixes {\n\t\t\tif strings.HasPrefix(lower, prefix) {\n\t\t\t\th[n] = v\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn h\n}", "func ConvertHeader(ctx context.Context, src, dst types.Protocol, srcHeader types.HeaderMap) (types.HeaderMap, error) {\n\tif sub, subOk := protoConvFactory[src]; subOk {\n\t\tif f, ok := sub[dst]; ok {\n\t\t\treturn f.ConvHeader(ctx, srcHeader)\n\t\t}\n\t}\n\treturn nil, ErrNotFound\n}", "func (f *Fs) addHeaders(headers fs.CommaSepList) {\n\tfor i := 0; i < len(headers); i += 2 {\n\t\tkey := f.opt.Headers[i]\n\t\tvalue := f.opt.Headers[i+1]\n\t\tf.srv.SetHeader(key, value)\n\t}\n}", "func Copy(\n\tctx context.Context,\n\tfrom ReadBucket,\n\tto ReadWriteBucket,\n\toptions ...normalpath.TransformerOption,\n) (int, error) {\n\treturn CopyPrefix(ctx, from, to, \"\", options...)\n}", "func InjectHeader(r *http.Request, key, val string) {\n\tr.Header.Add(key, val)\n}", "func addHeaders(req *http.Request, header http.Header) {\n\tfor key, values := range header {\n\t\tfor _, value := range values {\n\t\t\treq.Header.Add(key, value)\n\t\t}\n\t}\n}", "func (pw *pooledWriter) SetHeader(h writer.Header) {\n\tpw.Name = h.Name\n\tpw.Extra = h.Extra\n\tpw.Comment = h.Comment\n\tpw.ModTime = h.ModTime\n\tpw.OS = h.OS\n}", "func (h HandshakeHeaderHTTP) WriteTo(w io.Writer) (int64, error) {\n\twr := writer{w: w}\n\terr := http.Header(h).Write(&wr)\n\treturn wr.n, err\n}", "func (c *Action) SetHeader(key string, value string) {\n\tc.Header().Set(key, value)\n}", "func (c *CommandDescriptor) SetHeader(key string, value interface{}) {\n\tc.headers[key] = value\n}", "func CopySource(sourceBucket, sourceObject string) Option {\n\treturn setHeader(\"X-Oss-Copy-Source\", \"/\"+sourceBucket+\"/\"+sourceObject)\n}", "func (hs *headers) AddHeader(header Header) {\n\tname := strings.ToLower(header.Name())\n\tif headerList, ok := hs.headers[name]; ok {\n\t\ta := headerList[0]\n\t\tlogger.Error(headerList[0])\n\t\tlogger.Error(a)\n\t\tlogger.Error(headerList[0].Equals(Header(nil)))\n\t\tlogger.Error(headerList[0].String())\n\t\tif len(headerList) > 0 && !headerList[0].Equals(nil) {\n\t\t\ths.headers[name] = append(headerList, header)\n\t\t} else {\n\t\t\ths.headers[name] = []Header{header}\n\t\t}\n\t} else {\n\t\ths.headers[name] = []Header{header}\n\t\ths.headerOrder = append(hs.headerOrder, name)\n\t}\n}", "func FilterHeader(header http.Header) http.Header {\n\tnewHeader := make(http.Header)\n\tfor k, v := range header {\n\t\tswitch k {\n\t\tcase \"Authorization\":\n\t\t// ignore these headers\n\t\tdefault:\n\t\t\tnewHeader[k] = v\n\t\t}\n\t}\n\n\treturn newHeader\n}", "func Copy(c *gophercloud.ServiceClient, containerName, objectName string, opts CopyOptsBuilder) CopyResult {\n\tvar res CopyResult\n\th := c.AuthenticatedHeaders()\n\n\theaders, err := opts.ToObjectCopyMap()\n\tif err != nil {\n\t\tres.Err = err\n\t\treturn res\n\t}\n\n\tfor k, v := range headers {\n\t\th[k] = v\n\t}\n\n\turl := copyURL(c, containerName, objectName)\n\tresp, err := c.Request(\"COPY\", url, gophercloud.RequestOpts{\n\t\tMoreHeaders: h,\n\t\tOkCodes: []int{201},\n\t})\n\tif resp != nil {\n\t\tres.Header = resp.Header\n\t}\n\tres.Err = err\n\treturn res\n}", "func ExtractHeader(name string, dest *string) func(http.RoundTripper) http.RoundTripper {\n\treturn func(tr http.RoundTripper) http.RoundTripper {\n\t\treturn &funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) {\n\t\t\tres, err := tr.RoundTrip(req)\n\t\t\tif err == nil {\n\t\t\t\tif value := res.Header.Get(name); value != \"\" {\n\t\t\t\t\t*dest = value\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn res, err\n\t\t}}\n\t}\n}", "func (c *PublicClient) addHeaders(req *http.Request, h headers) *http.Request {\n\tfor k, v := range c.headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tif h != nil {\n\t\tfor k, v := range h {\n\t\t\treq.Header[k] = v\n\t\t}\n\t}\n\treturn req\n}", "func AddHeader(name, value string) ClientOption {\n\treturn func(tr http.RoundTripper) http.RoundTripper {\n\t\treturn &funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) {\n\t\t\thost := req.Host\n\t\t\tlog.Logger().Debugf(\"sending request to host '%s'\", host)\n\t\t\tif name == \"Authorization\" {\n\t\t\t\tif host == \"api.github.com\" {\n\t\t\t\t\tlog.Logger().Debugf(\"Adding Authorization Header %s=%s\", name, Mask(value))\n\t\t\t\t\treq.Header.Add(name, value)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Logger().Debugf(\"Adding Header %s=%s\", name, Mask(value))\n\t\t\t\treq.Header.Add(name, value)\n\t\t\t}\n\n\t\t\treturn tr.RoundTrip(req)\n\t\t}}\n\t}\n}", "func (m *Modifier) ChangeHeader(index int, name, value string) error {\n\tvar buffer bytes.Buffer\n\tif err := binary.Write(&buffer, binary.BigEndian, uint32(index)); err != nil {\n\t\treturn err\n\t}\n\tbuffer.WriteString(name + null)\n\tbuffer.Write(crlfToLF([]byte(value)))\n\tbuffer.WriteString(null)\n\treturn m.writePacket(NewResponse('m', buffer.Bytes()).Response())\n}", "func writeRequestHeaders(writer io.Writer, request *http.Request) error {\n\tif _, err := fmt.Fprintf(\n\t\twriter,\n\t\t\"%s %s %s\\r\\n\",\n\t\trequest.Method,\n\t\trequest.URL.RequestURI(),\n\t\trequest.Proto,\n\t); err != nil {\n\t\treturn err\n\t}\n\n\tif err := request.Header.Write(writer); err != nil {\n\t\treturn err\n\t}\n\n\t_, err := io.WriteString(writer, \"\\r\\n\")\n\treturn err\n}", "func (in *HTTPHeader) DeepCopy() *HTTPHeader {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HTTPHeader)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (msg *Message) writeHeader(buffer *bytes.Buffer) {\n\tfor key, values := range msg.Headers {\n\t\tfor _, keyval := range values {\n\t\t\tio.WriteString(buffer, key)\n\t\t\tio.WriteString(buffer, \": \")\n\t\t\tswitch {\n\t\t\tcase key == \"Content-Type\" || key == \"Content-Disposition\":\n\t\t\t\tbuffer.Write([]byte(keyval))\n\t\t\tdefault:\n\t\t\t\tbuffer.Write([]byte(mime.QEncoding.Encode(\"UTF-8\", keyval)))\n\t\t\t}\n\t\t\tio.WriteString(buffer, \"\\r\\n\")\n\t\t}\n\t}\n\tio.WriteString(buffer, \"\\r\\n\")\n}", "func (client *graphqlClient)AddHeader(headerName string, headerValue string){\n client.header.Add(headerName,headerValue)\n}", "func (g *Generator) NewHeader(step *pathway.Step) *message.HeaderInfo {\n\treturn g.headerGenerator.NewHeader(step)\n}", "func (h blockHeader) appendTo(b []byte) []byte {\n\treturn append(b, uint8(h), uint8(h>>8), uint8(h>>16))\n}", "func Headers(self *C.PyObject, args, kwargs *C.PyObject) *C.PyObject {\n\th := util.HTTPHeaders()\n\n\tdict := C.PyDict_New()\n\tfor k, v := range h {\n\t\tcKey := C.CString(k)\n\t\tpyKey := C.PyString_FromString(cKey)\n\t\tdefer C.Py_DecRef(pyKey)\n\t\tC.free(unsafe.Pointer(cKey))\n\n\t\tcVal := C.CString(v)\n\t\tpyVal := C.PyString_FromString(cVal)\n\t\tdefer C.Py_DecRef(pyVal)\n\t\tC.free(unsafe.Pointer(cVal))\n\n\t\tC.PyDict_SetItem(dict, pyKey, pyVal)\n\t}\n\n\t// some checks need to add an extra header when they pass `http_host`\n\tif kwargs != nil {\n\t\tcKey := C.CString(\"http_host\")\n\t\t// in case of failure, the following doesn't set an exception\n\t\t// pyHttpHost is borrowed\n\t\tpyHTTPHost := C.PyDict_GetItemString(kwargs, cKey)\n\t\tC.free(unsafe.Pointer(cKey))\n\t\tif pyHTTPHost != nil {\n\t\t\t// set the Host header\n\t\t\tcKey = C.CString(\"Host\")\n\t\t\tC.PyDict_SetItemString(dict, cKey, pyHTTPHost)\n\t\t\tC.free(unsafe.Pointer(cKey))\n\t\t}\n\t}\n\n\treturn dict\n}", "func (h *Header) AddHeader(header *Header) {\n\tif header != nil {\n\t\tfor i := 0; i < header.Len(); i++ {\n\t\t\tkey, value := header.GetAt(i)\n\t\t\th.Add(key, value)\n\t\t}\n\t}\n}", "func SpanTransferFromContextToHeader(ctx context.Context) context.Context {\n\tvar parentCtx opentracing.SpanContext\n\tif parent := opentracing.SpanFromContext(ctx); parent != nil {\n\t\tparentCtx = parent.Context()\n\t}\n\tsp := opentracing.StartSpan(\n\t\t\"GRPCToHTTP\",\n\t\topentracing.FollowsFrom(parentCtx),\n\t\text.SpanKindRPCClient,\n\t)\n\tdefer sp.Finish()\n\treturn opentracing.ContextWithSpan(context.Background(), sp)\n}", "func (h *Histogram) copyHDataFrom(src *Histogram) {\n\tif h.Divider == src.Divider && h.Offset == src.Offset {\n\t\tfor i := 0; i < len(h.Hdata); i++ {\n\t\t\th.Hdata[i] += src.Hdata[i]\n\t\t}\n\t\treturn\n\t}\n\n\thData := src.Export()\n\tfor _, data := range hData.Data {\n\t\th.record((data.Start+data.End)/2, int(data.Count))\n\t}\n}", "func (rp *ReqParams) AddHeader(key, value string) {\n\tif rp.headers == nil {\n\t\trp.headers = make(map[string]string)\n\t}\n\n\trp.headers[key] = value\n}", "func existingOrNewHeader(cfg exportConfig, src StorageDriver, key *CryptoKey, ct CompressionType) (*Header, error) {\n\theader, err := LoadHeader(cfg.SnapshotID, src, key, ct)\n\n\tif errors.Cause(err) == ErrDataDidNotExist {\n\t\t// deduped map did not exist yet,\n\t\t// return a new one based on the given export config\n\t\treturn newExportHeader(cfg), nil\n\t}\n\tif err != nil {\n\t\t// deduped map did exist, but we couldn't load it.\n\t\tif cfg.Force {\n\t\t\t// we forcefully create a new one anyhow if `force == true`\n\t\t\tlog.Debugf(\n\t\t\t\t\"couldn't read header for snapshot '%s' due to an error (%s), forcefully creating a new one\",\n\t\t\t\tcfg.SnapshotID, err)\n\t\t\treturn newExportHeader(cfg), nil\n\t\t}\n\t\t// deduped map did exist,\n\t\t// but an error was triggered while fetching it\n\t\treturn nil, err\n\t}\n\n\tif header.Metadata.BlockSize != cfg.DstBlockSize {\n\t\tif cfg.Force {\n\t\t\t// we forcefully create a new one anyhow if `force == true`\n\t\t\tlog.Debugf(\n\t\t\t\t\"existing header for snapshot '%s' defined incompatible snapshot blocksize, forcefully creating a new one\",\n\t\t\t\tcfg.SnapshotID)\n\t\t\treturn newExportHeader(cfg), nil\n\t\t}\n\n\t\treturn nil, errIncompatibleHeader\n\t}\n\n\t// update information to match new export session\n\theader.Metadata.Created = time.Now().Format(time.RFC3339)\n\theader.Metadata.Source.VdiskID = cfg.VdiskID\n\theader.Metadata.Source.BlockSize = cfg.SrcBlockSize\n\theader.Metadata.Source.Size = int64(cfg.VdiskSize)\n\theader.Metadata.Version = zerodisk.CurrentVersion\n\n\t// return existing header, which was updated\n\tlog.Debugf(\"loaded and updated existing header for snapshot %s\", cfg.SnapshotID)\n\treturn header, nil\n}", "func (w *Writer) WriteHeader(hdr *index.Header) error {\n\t// Flush out preceding file's content before starting new range.\n\tif !w.first {\n\t\tif err := w.tw.Flush(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tw.first = false\n\t// Setup index header for next file.\n\t// (bryce) might want to deep copy the passed in header.\n\tw.hdr = &index.Header{\n\t\tHdr: hdr.Hdr,\n\t\tIdx: &index.Index{DataOp: &index.DataOp{}},\n\t}\n\tw.cw.StartRange(w.callback(w.hdr))\n\tif err := w.tw.WriteHeader(w.hdr.Hdr); err != nil {\n\t\treturn err\n\t}\n\t// Setup first tag for header.\n\tw.hdr.Idx.DataOp.Tags = []*index.Tag{&index.Tag{Id: headerTag, SizeBytes: w.cw.RangeSize()}}\n\treturn nil\n}", "func (request *ActivityRecordHeartbeatRequest) CopyTo(target IProxyMessage) {\n\trequest.ActivityRequest.CopyTo(target)\n\tif v, ok := target.(*ActivityRecordHeartbeatRequest); ok {\n\t\tv.SetDetails(request.GetDetails())\n\t}\n}", "func addProxyAddToHeader(remoteAddr, realIP string, fwd []string, header http.Header, omitForward bool) {\n\trip, _, err := net.SplitHostPort(remoteAddr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif realIP != \"\" {\n\t\theader.Set(\"X-Real-IP\", realIP)\n\t} else {\n\t\theader.Set(\"X-Real-IP\", rip)\n\t}\n\n\tif !omitForward {\n\t\theader[\"X-Forwarded-For\"] = fwd[:]\n\t\theader.Add(\"X-Forwarded-For\", rip)\n\t}\n}", "func (ctx *Context) SetHeader(hdr string, val string, unique bool) {\n\tif unique {\n\t\tctx.Header().Set(hdr, val)\n\t} else {\n\t\tctx.Header().Add(hdr, val)\n\t}\n}", "func (b *Builder) AddHeader(headers ...string) *Builder {\n\tfor i := range headers {\n\t\tb.headers = append(b.headers, headers[i]+\"\\r\\n\")\n\t}\n\treturn b\n}", "func (v *DCHttpClient) SetCommonHeader(key string, value string) {\n\tv.CHeader[key] = value\n}", "func mergeHeaders(headers, extraHeaders map[string]string) map[string]string {\n\tfor k, v := range extraHeaders {\n\t\theaders[k] = v\n\t}\n\treturn headers\n}", "func Copy(h *hdrhistogram.Histogram) *hdrhistogram.Histogram {\n\tdup := hdrhistogram.New(h.LowestTrackableValue(), h.HighestTrackableValue(),\n\t\tint(h.SignificantFigures()))\n\tdup.Merge(h)\n\treturn dup\n}", "func (rwp *ResponseWriterProxy) WriteHeader(statusCode int) {\n\trwp.response.Status = statusCode\n\trwp.response.Headers = parseStringArrMap(rwp.under.Header())\n\trwp.under.WriteHeader(statusCode)\n}", "func OptHeader(headers http.Header) Option {\n\treturn RequestOption(webutil.OptHeader(headers))\n}" ]
[ "0.7428583", "0.73180294", "0.6969307", "0.6939664", "0.68874514", "0.68320334", "0.68258685", "0.68127483", "0.6698579", "0.66148335", "0.6614227", "0.65428376", "0.62228173", "0.61663586", "0.6070402", "0.5893018", "0.572726", "0.5709158", "0.5704184", "0.56725305", "0.5646608", "0.5645388", "0.5574246", "0.5555903", "0.54837346", "0.542251", "0.5371328", "0.5345336", "0.53015137", "0.52920705", "0.52531844", "0.52531844", "0.5229696", "0.5226522", "0.5220001", "0.52038217", "0.5201821", "0.5197332", "0.5156163", "0.5150092", "0.5130715", "0.51217115", "0.5114498", "0.5106032", "0.5099308", "0.5089942", "0.50800717", "0.5078758", "0.5067956", "0.5047841", "0.5040618", "0.5032649", "0.5026464", "0.50258803", "0.5010079", "0.5007416", "0.5007155", "0.50043637", "0.499278", "0.4988924", "0.4987665", "0.49784976", "0.4977679", "0.49716467", "0.49663723", "0.49580267", "0.49558127", "0.4941594", "0.49379838", "0.49378836", "0.49272296", "0.49200714", "0.4915111", "0.49147546", "0.49099168", "0.49092948", "0.49052823", "0.49048206", "0.48995703", "0.48898464", "0.48847663", "0.48797214", "0.48782638", "0.4877883", "0.48679817", "0.4863784", "0.48572177", "0.48525876", "0.4851444", "0.48451784", "0.48417372", "0.48406094", "0.48389497", "0.48356885", "0.48334682", "0.48292223", "0.48230276", "0.48180714", "0.48122036", "0.4802366" ]
0.83915895
0
RemoveIfUnused deletes the entry for the specified queue in this registry if its reference count is zero. Return whether the entry has been removed, and any error that occurred.
func (registry *Registry) RemoveIfUnused(queue string) (bool, error) { registry.mutex.Lock() defer registry.mutex.Unlock() entry, found := registry.queues[queue] if !found { // "Not found" is unexpected, since I expect only the clerk itself // would be trying to remove its queue (so why, then, is it already // missing?). return true, fmt.Errorf("no entry for queue %q", queue) } if entry.RefCount > 0 { // Someone is using the queue. Return `false`, meaning "not removed." return false, nil } // Nobody is using the queue. Remove it. delete(registry.queues, queue) // Return `true`, meaning "removed." return true, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DeleteTimerQueue(timerQueue HANDLE) bool {\n\tret1 := syscall3(deleteTimerQueue, 1,\n\t\tuintptr(timerQueue),\n\t\t0,\n\t\t0)\n\treturn ret1 != 0\n}", "func (q *Queue) MaybeRemoveMissing(names []string) int {\n\tq.mu.Lock()\n\tsameSize := len(q.items) == len(names)\n\tq.mu.Unlock()\n\n\t// heuristically skip expensive work\n\tif sameSize {\n\t\treturn -1\n\t}\n\n\tset := make(map[string]struct{}, len(names))\n\tfor _, name := range names {\n\t\tset[name] = struct{}{}\n\t}\n\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tcount := 0\n\tfor name, item := range q.items {\n\t\tif _, ok := set[name]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif item.heapIdx >= 0 {\n\t\t\theap.Remove(&q.pq, item.heapIdx)\n\t\t}\n\t\titem.setIndexState(\"\")\n\t\tdelete(q.items, name)\n\t\tcount++\n\t}\n\n\tmetricQueueLen.Set(float64(len(q.pq)))\n\tmetricQueueCap.Set(float64(len(q.items)))\n\n\treturn count\n}", "func (t *TopicCache) IsQueueEmpty(projectName, serviceName string) bool {\n\tt.RLock()\n\tdefer t.RUnlock()\n\n\t_, ok := t.inQueue[projectName+serviceName]\n\n\treturn !ok\n}", "func (q *LinkQueue) DeQueue() bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif q.IsEmpty() {\n\t\treturn false\n\t}\n\n\tq.head = q.head.Next\n\tq.size--\n\treturn true\n}", "func TestRemoveFromEmptyQueue(t *testing.T) {\n\ttarget := teaser.New()\n\tdeleted := target.Delete(\"6e0c9774-2674-4c6f-906e-6ccaebad3772\")\n\tif deleted {\n\t\tt.Fatal(\"deleting from an empty queue should not be possbile!\")\n\t}\n}", "func (eq *ExpiryQueue) Remove(orderId int64) bool {\n\tindex, ok := eq.hp.mapIndexByOrderId[orderId]\n\tif !ok {\n\t\treturn false\n\t}\n\theap.Remove(eq.hp, index)\n\treturn true\n}", "func (mcq *MyCircularQueue) DeQueue() bool {\n\tif mcq.length == 0 {\n\t\treturn false\n\t}\n\tshouldDeleteNode := mcq.dummyHead.Next\n\tdeleteNodeInList(shouldDeleteNode)\n\tmcq.length--\n\treturn true\n}", "func (q *SliceQueue) DeQueue() bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif q.IsEmpty() {\n\t\treturn false\n\t}\n\n\tq.Data = q.Data[1:]\n\treturn true\n}", "func (q *UniqueQueue) Dequeue() (string, interface{}, bool) {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tif q.head == q.tail {\n\t\treturn \"\", nil, false\n\t}\n\n\tentry := q.queue[q.head]\n\tq.head = q.inc(q.head)\n\tdelete(q.queuedSet, entry.key)\n\treturn entry.key, entry.val, true\n}", "func (q *Queue) Remove() (interface{}, bool) {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tif q.queueLen == 0 {\n\t\treturn nil, false\n\t}\n\treturn q.popFront(), true\n}", "func (sb *shardBuffer) remove(toRemove *entry) {\n\tsb.mu.Lock()\n\tdefer sb.mu.Unlock()\n\n\tif sb.queue == nil {\n\t\t// Queue is cleared because we're already in the DRAIN phase.\n\t\treturn\n\t}\n\n\t// If entry is still in the queue, delete it and cancel it internally.\n\tfor i, e := range sb.queue {\n\t\tif e == toRemove {\n\t\t\t// Delete entry at index \"i\" from slice.\n\t\t\tsb.queue = append(sb.queue[:i], sb.queue[i+1:]...)\n\n\t\t\t// Cancel the entry's \"bufferCtx\".\n\t\t\t// The usual drain or eviction code would unblock the request and then\n\t\t\t// wait for the \"bufferCtx\" to be done.\n\t\t\t// But this code path is different because it's going to return an error\n\t\t\t// to the request and not the \"e.bufferCancel\" function i.e. the request\n\t\t\t// cannot cancel the \"bufferCtx\" itself.\n\t\t\t// Therefore, we call \"e.bufferCancel\". This also avoids that the\n\t\t\t// context's Go routine could leak.\n\t\t\te.bufferCancel()\n\t\t\t// Release the buffer slot and close the \"e.done\" channel.\n\t\t\t// By closing \"e.done\", we finish it explicitly and timeoutThread will\n\t\t\t// find out about it as well.\n\t\t\tsb.unblockAndWait(e, nil /* err */, true /* releaseSlot */, false /* blockingWait */)\n\n\t\t\t// Track it as \"ContextDone\" eviction.\n\t\t\tstatsKeyWithReason := append(sb.statsKey, string(evictedContextDone))\n\t\t\trequestsEvicted.Add(statsKeyWithReason, 1)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Entry was already removed. Keep the queue as it is.\n}", "func (q *Queue) DeQueue() (interface{}, bool) {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif q.closed && q.items.Len() == 0 {\n\t\treturn nil, false\n\t}\n\n\tfor !q.closed && q.items.Len() == 0 {\n\t\tq.cond.Wait()\n\t}\n\n\tif q.closed && q.items.Len() == 0 {\n\t\treturn nil, false\n\t}\n\n\thi := heap.Pop(&q.items).(*heapItem)\n\titem := hi.value\n\tq.vt += hi.size * q.inv_wsum\n\thi.fi.size -= hi.size\n\tq.size -= hi.size\n\tif hi.fi.size == 0 && hi.fi.pendSize == 0 {\n\t\t// The flow is empty (i.e. inactive), delete it\n\t\tdelete(q.flows, hi.key)\n\t\tq.wsum += uint64(hi.fi.weight)\n\t\tq.inv_wsum = scaledOne / uint64(q.wsum)\n\t\tputFlowInfo(hi.fi)\n\t\tputHeapItem(hi)\n\t} else {\n\t\thi.fi.cond.Signal()\n\t\tputHeapItem(hi)\n\t}\n\n\tif !q.closed {\n\t\t// While there is room in the queue move items from the overflow to the main heap.\n\t\tfor q.next_ohi != nil && q.size+q.next_ohi.hi.size <= q.maxQueueSize {\n\t\t\tq.size += q.next_ohi.hi.size\n\t\t\theap.Push(&q.items, q.next_ohi.hi)\n\t\t\tq.next_ohi.wg.Done()\n\t\t\tif q.overflow.Len() > 0 {\n\t\t\t\tq.next_ohi = heap.Pop(&q.overflow).(*overflowHeapItem)\n\t\t\t} else {\n\t\t\t\tq.next_ohi = nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn item, true\n}", "func (q *dStarLiteQueue) remove(n *dStarLiteNode) {\n\theap.Remove(q, n.idx)\n\tn.key = badKey\n\tn.idx = -1\n}", "func (s *SliceQueue) Dequeue() (val string, ok bool) {\n\tif s.Len() == 0 {\n\t\treturn \"\", false\n\t}\n\n\tval = s.elements[0] // Obtain the first inserted element.\n\ts.elements = s.elements[1:] // Remove the first inserted element.\n\treturn val, true\n}", "func (c *caches) remove(qname string) (ok bool) {\n\tc.Lock()\n\tfor e := c.lru.Front(); e != nil; e = e.Next() {\n\t\tanswer := e.Value.(*answer)\n\t\tif answer.qname != qname {\n\t\t\tcontinue\n\t\t}\n\n\t\tc.lru.Remove(e)\n\t\tdelete(c.v, qname)\n\t\tanswer.clear()\n\t\tok = true\n\t\tbreak\n\t}\n\tif !ok {\n\t\t_, ok = c.v[qname]\n\t\tif ok {\n\t\t\t// If the qname is not found in non-local caches, it\n\t\t\t// may exist as local answer.\n\t\t\tdelete(c.v, qname)\n\t\t}\n\t}\n\tc.Unlock()\n\treturn ok\n}", "func (block *SimpleQueueBlock) clearOldStorage(ctx context.Context, q *SimpleQueue) (notNeed bool, err *mft.Error) {\n\n\tif !block.mxFileSave.TryLock(ctx) {\n\t\treturn false, GenerateError(10017000)\n\t}\n\tdefer block.mxFileSave.Unlock()\n\n\tif len(block.RemoveMarks) == 0 {\n\t\treturn true, nil\n\t}\n\n\tfileName := block.blockFileName()\n\n\tfor _, stName := range block.RemoveMarks {\n\t\tif block.Mark == stName {\n\t\t\tcontinue\n\t\t}\n\t\tst, err := q.getStorageLock(ctx, stName)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\terr = storage.DeleteIfExists(ctx, st, fileName)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tif !q.mx.TryLock(ctx) {\n\t\treturn false, GenerateError(10017001)\n\t}\n\n\tblock.RemoveMarks = make([]string, 0)\n\n\tq.ChangesRv = q.IDGenerator.RvGetPart()\n\n\tq.mx.Unlock()\n\n\treturn false, nil\n}", "func (c *CircularBuffer[T]) Dequeue() (T, bool) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tvar msg T\n\t// record that we have accessed the buffer\n\tc.lastAccess = time.Now()\n\t// if our head and tail are equal there is nothing in our buffer to return\n\tif c.head == c.tail {\n\t\treturn msg, false\n\t}\n\n\tmsg = c.buffer[c.tail]\n\tc.tail = (c.tail + 1) % BUFLEN\n\treturn msg, true\n}", "func (this *MyCircularQueue) DeQueue() bool {\n\tif this.Count == 0 {\n\t\treturn false\n\t}\n\tthis.Count--\n\tthis.Head++\n\tif this.Head == len(this.Queue) {\n\t\tthis.Head = 0\n\t}\n\treturn true\n}", "func (b *backend) removeUnsafe(id *entroq.TaskID) {\n\tif !b.existsIDVersionUnsafe(id) {\n\t\tlog.Panicf(\"Item not found for removal: %v\", id)\n\t}\n\titem := b.byID[id.ID]\n\tif item.task.Version != id.Version {\n\t\tlog.Panicf(\"Item removal version mismatch: wanted %q, got %q\", id, item.task.IDVersion())\n\t}\n\th, ok := b.heaps[item.task.Queue]\n\tif !ok {\n\t\tlog.Panicf(\"Queues not in sync; found item to remove in queues but not index: %v\", id)\n\t}\n\n\tdelete(b.byID, id.ID)\n\theap.Remove(h, item.idx)\n\tif h.Len() == 0 {\n\t\tdelete(b.heaps, item.task.Queue)\n\t}\n}", "func (lru *LRUMap) removeFromQueue(node *keyValNode) {\n\tif node.prev != nil {\n\t\tnode.prev.next = node.next\n\t} else {\n\t\tlru.rear = node.next\n\t}\n\n\tif node.next != nil {\n\t\tnode.next.prev = node.prev\n\t} else {\n\t\tlru.front = node.prev\n\t}\n}", "func (q *Queue) Remove(v interface{}) bool {\r\n\tq.mu.Lock()\r\n\tdefer q.mu.Unlock()\r\n\r\n\tel, ok := q.m[v]\r\n\tif !ok {\r\n\t\treturn false\r\n\t}\r\n\r\n\tfirst := q.first\r\n\tdelete(q.m, v)\r\n\tq.remove(el)\r\n\r\n\t// If the element was first, we need to start a new timer\r\n\tif first == el && q.first != nil {\r\n\t\tgo q.timer(q.first, q.first.time)\r\n\t}\r\n\treturn true\r\n}", "func (gc *GceCache) UnregisterMig(toBeRemoved Mig) bool {\n\tgc.cacheMutex.Lock()\n\tdefer gc.cacheMutex.Unlock()\n\n\t_, found := gc.migs[toBeRemoved.GceRef()]\n\tif found {\n\t\tklog.V(1).Infof(\"Unregistered Mig %s\", toBeRemoved.GceRef().String())\n\t\tdelete(gc.migs, toBeRemoved.GceRef())\n\t\tgc.removeMigInstances(toBeRemoved.GceRef())\n\t\treturn true\n\t}\n\treturn false\n}", "func (q *Queue) DeQueue() error {\r\n\tif len(q.QueueList) > 0 {\r\n\t\tq.QueueList = q.QueueList[1:]\r\n\t\treturn nil\r\n\t}\r\n\treturn errors.New(\"Queue is empty\")\r\n}", "func (sl *LockFreeSkipList) Remove(value interface{}) bool {\n\tvar prevs [maxLevel]*node\n\tvar nexts [maxLevel]*node\n\tif !sl.find(value, &prevs, &nexts) {\n\t\treturn false\n\t}\n\tremoveNode := nexts[0]\n\tfor level := removeNode.level - 1; level > 0; level-- {\n\t\tnext := removeNode.loadNext(level)\n\t\tfor !isMarked(next) {\n\t\t\t// Make sure that all but the bottom next are marked from top to bottom.\n\t\t\tremoveNode.casNext(level, next, getMarked(next))\n\t\t\tnext = removeNode.loadNext(level)\n\t\t}\n\t}\n\tfor next := removeNode.loadNext(0); true; next = removeNode.loadNext(0) {\n\t\tif isMarked(next) {\n\t\t\t// Other thread already maked the next, so this thread delete failed.\n\t\t\treturn false\n\t\t}\n\t\tif removeNode.casNext(0, next, getMarked(next)) {\n\t\t\t// This thread marked the bottom next, delete successfully.\n\t\t\tbreak\n\t\t}\n\t}\n\tatomic.AddInt32(&sl.size, -1)\n\treturn true\n}", "func (gc *GceCache) UnregisterMig(toBeRemoved Mig) bool {\n\tgc.cacheMutex.Lock()\n\tdefer gc.cacheMutex.Unlock()\n\n\t_, found := gc.migs[toBeRemoved.GceRef()]\n\tif found {\n\t\tklog.V(1).Infof(\"Unregistered Mig %s\", toBeRemoved.GceRef().String())\n\t\tdelete(gc.migs, toBeRemoved.GceRef())\n\t\tgc.removeInstancesForMigs(toBeRemoved.GceRef())\n\t\treturn true\n\t}\n\treturn false\n}", "func (q *SignalQueue) Dequeue() int {\n\tq.Cond.L.Lock()\n\t// Wait for not empty\n\tfor len(q.Queue) == 0 {\n\t\tq.Cond.Wait()\n\t}\n\tretval := q.Queue[0]\n\tq.Queue[0] = 0\n\tq.Queue = q.Queue[1:]\n\tq.Cond.L.Unlock()\n\n\treturn retval\n}", "func (queues *requestQueueImpl) CleanupQueue(gwId string) chan *protos.SyncRPCRequest {\n\tqueues.Lock()\n\tdefer queues.Unlock()\n\tif queue, ok := queues.reqQueueByGwId[gwId]; ok {\n\t\t// sends on a closed queue will panic, but no one will send onto this queue,\n\t\t// because all sends are through enqueue.\n\t\tclose(queue)\n\t\tdelete(queues.reqQueueByGwId, gwId)\n\t\t// the broker will cleanup requests in the queue\n\t\treturn queue\n\t} else {\n\t\tglog.Warningf(\"HWID %v: no request queue found to clean up\", gwId)\n\t}\n\treturn nil\n}", "func (i *invocation) removeIfEmpty() {\n\tif i.queuedOperations.Len() == 0 && i.executingWorkersCount == 0 && i.idleWorkersCount == 0 {\n\t\tscq := i.sizeClassQueue\n\t\tif scq.invocations[i.invocationKey] != i {\n\t\t\tpanic(\"Attempted to remove an invocation that was already removed\")\n\t\t}\n\t\tdelete(scq.invocations, i.invocationKey)\n\t}\n}", "func (q *Queue) TryDequeue() (ptr unsafe.Pointer, dequeued bool) {\n\tvar c *cell\n\tpos := atomic.LoadUintptr(&q.deqPos)\n\tfor {\n\t\tc = &q.cells[pos&q.mask]\n\t\tseq := atomic.LoadUintptr(&c.seq)\n\t\tcmp := int(seq - (pos + 1))\n\t\tif cmp == 0 {\n\t\t\tvar swapped bool\n\t\t\tif pos, swapped = primitive.CompareAndSwapUintptr(&q.deqPos, pos, pos+1); swapped {\n\t\t\t\tdequeued = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif cmp < 0 {\n\t\t\treturn\n\t\t}\n\t\tpos = atomic.LoadUintptr(&q.deqPos)\n\t}\n\tptr = c.ptr\n\tc.ptr = primitive.Null\n\tatomic.StoreUintptr(&c.seq, pos+q.mask)\n\treturn\n}", "func (q *LockFree) Dequeue() memory.Bytes {\nretry:\n\tfirst := atomic.LoadUintptr(&q.head)\n\tfirstV := (*lockFreeNode)(unsafe.Pointer(first))\n\tlast := atomic.LoadUintptr(&q.tail)\n\tnext := atomic.LoadUintptr(&firstV.next)\n\t// Are first, tail, and next consistent?\n\tif first == atomic.LoadUintptr(&q.head) {\n\t\t// Is queue empty or tail falling behind?\n\t\tif first == last {\n\t\t\t// Is queue empty?\n\t\t\tif next == 0 {\n\t\t\t\t//println(\"empty\")\n\t\t\t\treturn memory.Bytes{}\n\t\t\t}\n\t\t\t//println(\"first == tail\")\n\t\t\tatomic.CompareAndSwapUintptr(&q.tail, last, next) // tail is falling behind, try to advance it.\n\t\t} else {\n\t\t\t// Read value before CAS, otherwise another dequeue might free the next node.\n\t\t\ttask := (*lockFreeNode)(unsafe.Pointer(next)).value\n\t\t\tif atomic.CompareAndSwapUintptr(&q.head, first, next) { // dequeue is done, return value.\n\t\t\t\tatomic.AddInt32(&q.length, -1)\n\t\t\t\tmemory.Free(memory.Pointer(first))\n\t\t\t\treturn task\n\t\t\t}\n\t\t}\n\t}\n\tgoto retry\n}", "func (q *Queue) RemoveResource(resUUID string) error {\n\t// Check for the resource with given UUID\n\t_, ok := q.pool[resUUID]\n\tif !ok {\n\t\treturn errors.New(\"Given Resource UUID does not exist.\")\n\t}\n\n\t// Lock the queue\n\tq.Lock()\n\tdefer q.Unlock()\n\n\t// Loop through any jobs assigned to the resource and quit them if they are not completed\n\tfor i, v := range q.stack {\n\t\tif v.ResAssigned == resUUID {\n\t\t\t// Check status\n\t\t\tif v.Status == common.STATUS_RUNNING || v.Status == common.STATUS_PAUSED {\n\t\t\t\t// Quit the task\n\t\t\t\tquitTask := common.RPCCall{Job: v}\n\n\t\t\t\terr := q.pool[resUUID].Client.Call(\"Queue.TaskQuit\", quitTask, &q.stack[i])\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Close the connection to the client\n\tq.pool[resUUID].Client.Close()\n\n\t// Remove information that might affect additional resource adding\n\tres, _ := q.pool[resUUID]\n\tres.Address = \"closed\"\n\tres.Status = common.STATUS_QUIT\n\tfor key := range res.Tools {\n\t\tdelete(res.Tools, key)\n\t}\n\tq.pool[resUUID] = res\n\tfor i, _ := range q.pool[resUUID].Hardware {\n\t\tq.pool[resUUID].Hardware[i] = false\n\t}\n\n\treturn nil\n}", "func (m *MemoryQueueStorage) Dequeue(queue string) (*frame.Frame, error) {\n\tl, ok := m.lists[queue]\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\telement := l.Front()\n\tif element == nil {\n\t\treturn nil, nil\n\t}\n\n\treturn l.Remove(element).(*frame.Frame), nil\n}", "func CancelTimerQueueTimer(timerQueue HANDLE, timer HANDLE) bool {\n\tret1 := syscall3(cancelTimerQueueTimer, 2,\n\t\tuintptr(timerQueue),\n\t\tuintptr(timer),\n\t\t0)\n\treturn ret1 != 0\n}", "func (s *ConcurrentSet) Remove(e interface{}) bool {\n\t_, exists := s.hash.Load(e)\n\ts.hash.Delete(e)\n\tif exists {\n\t\tatomic.AddUint32(&s.size, ^uint32(0))\n\t}\n\treturn exists\n}", "func (k *Kuzzle) cleanQueue() {\n\tnow := time.Now()\n\tnow = now.Add(-k.queueTTL * time.Millisecond)\n\n\t// Clean queue of timed out query\n\tif k.queueTTL > 0 {\n\t\tvar query *types.QueryObject\n\t\tfor _, query = range k.offlineQueue {\n\t\t\tif query.Timestamp.Before(now) {\n\t\t\t\tk.offlineQueue = k.offlineQueue[1:]\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif k.queueMaxSize > 0 && len(k.offlineQueue) > k.queueMaxSize {\n\t\tfor len(k.offlineQueue) > k.queueMaxSize {\n\t\t\teventListener := k.eventListeners[event.OfflineQueuePop]\n\t\t\tfor c := range eventListener {\n\t\t\t\tjson, _ := json.Marshal(k.offlineQueue[0])\n\t\t\t\tc <- json\n\t\t\t}\n\n\t\t\teventListener = k.eventListenersOnce[event.OfflineQueuePop]\n\t\t\tfor c := range eventListener {\n\t\t\t\tjson, _ := json.Marshal(k.offlineQueue[0])\n\t\t\t\tc <- json\n\t\t\t\tdelete(k.eventListenersOnce[event.OfflineQueuePop], c)\n\t\t\t}\n\n\t\t\tk.offlineQueue = k.offlineQueue[1:]\n\t\t}\n\t}\n}", "func (q *Queue) Drop() {\n\tif q.isShared {\n\t\treturn\n\t}\n\tq.Close()\n\tos.RemoveAll(q.Path())\n}", "func Unregister(qi inomap.QIno) {\n\tt.Lock()\n\tdefer t.Unlock()\n\n\te := t.entries[qi]\n\te.refCount--\n\tif e.refCount == 0 {\n\t\tdelete(t.entries, qi)\n\t}\n}", "func (q *CircularQueue) DeQueue() interface{} {\n\tif q.IsEmpty() {\n\t\treturn false\n\t}\n\tval := q.q[q.head]\n\tq.head = (q.head + 1) % q.capacity\n\treturn val\n}", "func (gcq *gcQueue) shouldQueue(\n\tctx context.Context, now hlc.ClockTimestamp, repl *Replica, _ *config.SystemConfig,\n) (bool, float64) {\n\n\t// Consult the protected timestamp state to determine whether we can GC and\n\t// the timestamp which can be used to calculate the score.\n\t_, zone := repl.DescAndZone()\n\tcanGC, _, gcTimestamp, oldThreshold, newThreshold := repl.checkProtectedTimestampsForGC(ctx, *zone.GC)\n\tif !canGC {\n\t\treturn false, 0\n\t}\n\t// If performing a GC will not advance the GC threshold, there's no reason\n\t// to GC again.\n\tif newThreshold.Equal(oldThreshold) {\n\t\treturn false, 0\n\t}\n\tr := makeGCQueueScore(ctx, repl, gcTimestamp, *zone.GC)\n\treturn r.ShouldQueue, r.FinalScore\n}", "func (f *fileScorer) trimQueue() {\n\tfor {\n\t\te := f.queue.Back()\n\t\tif e == nil {\n\t\t\treturn\n\t\t}\n\t\tv := e.Value.(queuedFile)\n\t\tif f.queuedBytes-v.size < f.saveBytes {\n\t\t\treturn\n\t\t}\n\t\tf.queue.Remove(e)\n\t\tf.queuedBytes -= v.size\n\t}\n}", "func (scq *sizeClassQueue) remove(bq *InMemoryBuildQueue) {\n\t// Cancel all queued operations.\n\tfor scq.queuedInvocations.Len() > 0 {\n\t\ti := scq.queuedInvocations[scq.queuedInvocations.Len()-1]\n\t\ti.queuedOperations[i.queuedOperations.Len()-1].task.complete(bq, &remoteexecution.ExecuteResponse{\n\t\t\tStatus: status.New(codes.Unavailable, \"Workers for this instance name, platform and size class disappeared while task was queued\").Proto(),\n\t\t}, false)\n\t}\n\n\tdelete(bq.sizeClassQueues, scq.getKey())\n\tpq := scq.platformQueue\n\ti := 0\n\tfor pq.sizeClassQueues[i] != scq {\n\t\ti++\n\t}\n\tpq.sizeClasses = append(pq.sizeClasses[:i], pq.sizeClasses[i+1:]...)\n\tpq.sizeClassQueues = append(pq.sizeClassQueues[:i], pq.sizeClassQueues[i+1:]...)\n\n\tif len(pq.sizeClasses) == 0 {\n\t\t// No size classes remain for this platform queue,\n\t\t// meaning that we can remove it. We must make sure the\n\t\t// list of platform queues remains contiguous.\n\t\tindex := bq.platformQueuesTrie.GetExact(pq.platformKey)\n\t\tnewLength := len(bq.platformQueues) - 1\n\t\tlastPQ := bq.platformQueues[newLength]\n\t\tbq.platformQueues[index] = lastPQ\n\t\tbq.platformQueues = bq.platformQueues[:newLength]\n\t\tbq.platformQueuesTrie.Set(lastPQ.platformKey, index)\n\t\tbq.platformQueuesTrie.Remove(pq.platformKey)\n\t}\n}", "func (this *MyCircularQueue) DeQueue() bool {\n\tif this.IsEmpty() {\n\t\treturn false\n\t}\n\n\tif this.Head == this.Tail {\n\t\tthis.CircularQueue[this.Head] = -1\n\t\treturn true\n\t}\n\n\t// 余数除法,指针向后移一位\n\tthis.CircularQueue[this.Head] = -1\n\tthis.Head = (this.Head + 1) % len(this.CircularQueue)\n\t/*\n\t\tthis.CircularQueue[this.Head] = -1\n\t\tthis.Head = this.Head + 1\n\t\tif this.Head > len(this.CircularQueue) - 1 {\n\t\t\tthis.Head = 0\n\t\t}*/\n\treturn true\n}", "func (m *MRUQueue) Empty() bool {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\treturn m.store.Len() == 0\n}", "func (c *LRU) RemoveUnused() (key string, value interface{}, ok bool) {\n\tif e := c.l.Back(); e != nil {\n\t\tc.l.Remove(e)\n\t\tent := e.Value.(*lruEntry)\n\t\tdelete(c.m, ent.k)\n\t\treturn ent.k, ent.v, true\n\t}\n\treturn\n}", "func (this *MyCircularQueue) DeQueue() bool {\n\tif this.IsEmpty() {\n\t\treturn false\n\t}\n\t//\n\tthis.front = (this.front + 1) % this.size\n\t//\n\treturn true\n}", "func (c *changeCache) CleanSkippedSequenceQueue(ctx context.Context) error {\n\n\toldSkippedSequences := c.GetSkippedSequencesOlderThanMaxWait()\n\tif len(oldSkippedSequences) == 0 {\n\t\treturn nil\n\t}\n\n\tbase.InfofCtx(ctx, base.KeyCache, \"Starting CleanSkippedSequenceQueue, found %d skipped sequences older than max wait for database %s\", len(oldSkippedSequences), base.MD(c.db.Name))\n\n\t// Purge sequences not found from the skipped sequence queue\n\tnumRemoved := c.RemoveSkippedSequences(ctx, oldSkippedSequences)\n\tc.db.DbStats.Cache().AbandonedSeqs.Add(numRemoved)\n\n\tbase.InfofCtx(ctx, base.KeyCache, \"CleanSkippedSequenceQueue complete. Not Found:%d for database %s.\", len(oldSkippedSequences), base.MD(c.db.Name))\n\treturn nil\n}", "func (q *Queue) TryEnqueue(ptr unsafe.Pointer) (enqueued bool) {\n\tc := &q.cells[q.enqPos&q.mask]\n\tseq := atomic.LoadUintptr(&c.seq)\n\tif seq < q.enqPos {\n\t\treturn\n\t}\n\tq.enqPos++\n\tc.ptr = ptr\n\tatomic.StoreUintptr(&c.seq, q.enqPos)\n\treturn true\n}", "func (q *PriorityQueue) Remove() interface{} {\n\tif q.count <= 0 {\n\t\tpanic(\"queue: Remove() called on empty queue\")\n\t}\n\tret := q.buf[q.head]\n\tq.buf[q.head] = nil\n\t// bitwise modulus\n\tq.head = (q.head + 1) & (len(q.buf) - 1)\n\tq.count--\n\t// Resize down if buffer 1/4 full.\n\tif len(q.buf) > minQueueLen && (q.count<<2) == len(q.buf) {\n\t\tq.resize()\n\t}\n\treturn ret\n}", "func (s *SyncStorage) RemoveIf(ns string, key string, data interface{}) (bool, error) {\n\tstatus, err := s.getDbBackend(ns).DelIE(getNsPrefix(ns)+key, data)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn status, nil\n}", "func (d *deferredConfirmations) remove(tag uint64) {\n\td.m.Lock()\n\tdefer d.m.Unlock()\n\tdc, found := d.confirmations[tag]\n\tif !found {\n\t\treturn\n\t}\n\tclose(dc.done)\n\tdelete(d.confirmations, tag)\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) HasExitQueue(opts *bind.CallOpts, vaultId *big.Int, token common.Address) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"hasExitQueue\", vaultId, token)\n\treturn *ret0, err\n}", "func (h *sendPacketHeap) Remove(packetID packet.PacketID) bool {\n\tlen := len(*h)\n\tidx := 0\n\tfor idx < len {\n\t\tpid := (*h)[idx].pkt.Seq\n\t\tif pid.Seq == packetID.Seq {\n\t\t\theap.Remove(h, idx)\n\t\t\treturn true\n\t\t} else if pid.Seq > packetID.Seq {\n\t\t\tidx = idx * 2\n\t\t} else {\n\t\t\tidx = idx*2 + 1\n\t\t}\n\t}\n\treturn false\n}", "func (q *Queue) Dequeue() interface{} {\n\tvar first, last, firstnext *queueitem\n\tfor {\n\t\tfirst = loadqitem(&q.head)\n\t\tlast = loadqitem(&q.tail)\n\t\tfirstnext = loadqitem(&first.next)\n\t\tif first == loadqitem(&q.head) { // are head, tail and next consistent?\n\t\t\tif first == last { // is queue empty?\n\t\t\t\tif firstnext == nil { // queue is empty, couldn't dequeue\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tcasqitem(&q.tail, last, firstnext) // tail is falling behind, try to advance it\n\t\t\t} else { // read value before cas, otherwise another dequeue might free the next node\n\t\t\t\tv := firstnext.v\n\t\t\t\tif casqitem(&q.head, first, firstnext) { // try to swing head to the next node\n\t\t\t\t\tatomic.AddUint64(&q.len, ^uint64(0))\n\t\t\t\t\treturn v // queue was not empty and dequeue finished.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (this *MyQueue) Empty() bool {\n return len(this.q) == 0\n}", "func (m *etcdMinion) checkQueue() error {\n\topts := &etcdclient.GetOptions{\n\t\tRecursive: true,\n\t\tSort: true,\n\t}\n\n\t// Get backlog tasks if any\n\t// If the directory key in etcd is missing that is okay, since\n\t// it means there are no pending tasks for processing\n\tresp, err := m.kapi.Get(context.Background(), m.queueDir, opts)\n\tif err != nil {\n\t\tif eerr, ok := err.(etcdclient.Error); !ok || eerr.Code == etcdclient.ErrorCodeKeyNotFound {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tbacklog := resp.Node.Nodes\n\tif len(backlog) == 0 {\n\t\t// No backlog tasks found\n\t\treturn nil\n\t}\n\n\tlog.Printf(\"Found %d pending tasks in queue\", len(backlog))\n\tfor _, node := range backlog {\n\t\tt, err := EtcdUnmarshalTask(node)\n\t\tm.kapi.Delete(context.Background(), node.Key, nil)\n\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tm.taskQueue <- t\n\t}\n\n\treturn nil\n}", "func (q *OperationQueue) Remove(op *SignedOperation) {\n\tif op == nil {\n\t\treturn\n\t}\n\tq.set.Remove(op)\n}", "func (s *API) UntagQueue(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"UntagQueue\")\n\tw.WriteHeader(http.StatusNotImplemented)\n}", "func (s *API) PurgeQueue(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"PurgeQueue\")\n\tw.WriteHeader(http.StatusNotImplemented)\n}", "func ClearQueue(queueLetter ...string) error {\n\tif len(queueLetter) == 0 {\n\t\tqueueLetter = []string{\"a\"}\n\t}\n\n\tatqCmd := exec.Command(\"atq\", \"-q\", fmt.Sprintf(\"%c\", queueLetter[0][0]))\n\tatqStdout, err := atqCmd.Output()\n\tif err != nil {\n\t\treturn errors.New(\"could not get job IDs\")\n\t}\n\n\tjobIDs := regexp.MustCompile(`(?m:^\\d+)`).FindAllStringSubmatch(string(atqStdout), -1)\n\n\tfor _, idToken := range jobIDs {\n\t\tjobID, _ := strconv.Atoi(idToken[0])\n\n\t\tif err := RemoveJob(jobID); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (q *dStarLiteNode) inQueue() bool {\n\treturn q.idx >= 0\n}", "func (q LinkedListQueue) Dequeue() (data interface{}, err error) {\n\tif q.list.Len() == 0 {\n\t\treturn data, errors.New(\"The queue is empty\")\n\t}\n\n\tdata = q.list.Remove(q.list.Front())\n\n\treturn data, nil\n}", "func (q *Queue) Disposed() bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\treturn q.disposed\n}", "func (s *MyStack) Empty() bool {\n return len(s.queue1) == 0\n}", "func (f *ccFixture) popQueue() {\n\tf.T().Helper()\n\n\tdone := make(chan error)\n\tgo func() {\n\t\titem, _ := f.q.Get()\n\t\t_, err := f.tfr.Reconcile(f.ctx, item.(reconcile.Request))\n\t\tf.q.Done(item)\n\t\tdone <- err\n\t}()\n\n\tselect {\n\tcase <-time.After(time.Second):\n\t\tf.T().Fatal(\"timeout waiting for workqueue\")\n\tcase err := <-done:\n\t\tassert.NoError(f.T(), err)\n\t}\n}", "func (f *FakeWatchEventQ) Dequeue(ctx context.Context,\n\tfromver uint64, ignoreBulk bool, cb apiintf.EventHandlerFn, cleanupfn func(), opts *api.ListWatchOptions) {\n\tdefer f.Unlock()\n\tf.Lock()\n\tclose(f.DqCh)\n\tf.Dequeues++\n\tif f.DQFn != nil {\n\t\tf.DQFn(ctx, fromver, cb, cleanupfn)\n\t}\n}", "func (ls *ListStack) Remove(item adts.ContainerElement) bool {\n\tif ls.threadSafe {\n\t\tls.lock.Lock()\n\t\tdefer ls.lock.Unlock()\n\t\treturn ls.removeHelper(item)\n\t}\n\n\treturn ls.removeHelper(item)\n}", "func (q *queue) Dequeue() (interface{}, error) {\n\tif q.Empty() {\n\t\treturn nil, errors.New(\"error: can not remove from empty queue\")\n\t}\n\n\tdata := q.items[q.head].Data\n\tq.items[q.head] = item{}\n\tq.head = (q.head + 1) % q.capacity\n\tq.len--\n\n\treturn data, nil\n}", "func (q *Queue) Dequeue() (string, error) {\n\t// TODO: fewer round trips by fetching more than one key\n\tresp, err := q.client.Get(q.ctx, q.keyPrefix, v3.WithFirstRev()...)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkv, err := claimFirstKey(q.client, resp.Kvs)\n\tif err != nil {\n\t\treturn \"\", err\n\t} else if kv != nil {\n\t\treturn string(kv.Value), nil\n\t} else if resp.More {\n\t\t// missed some items, retry to read in more\n\t\treturn q.Dequeue()\n\t}\n\n\t// nothing yet; wait on elements\n\tev, err := WaitPrefixEvents(\n\t\tq.client,\n\t\tq.keyPrefix,\n\t\tresp.Header.Revision,\n\t\t[]mvccpb.Event_EventType{mvccpb.PUT})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tok, err := deleteRevKey(q.client, string(ev.Kv.Key), ev.Kv.ModRevision)\n\tif err != nil {\n\t\treturn \"\", err\n\t} else if !ok {\n\t\treturn q.Dequeue()\n\t}\n\treturn string(ev.Kv.Value), err\n}", "func (sq *SegmentQueue) Remove(seg *Segment) {\n\tsq.mtx.Lock()\n\tdefer sq.mtx.Unlock()\n\n\tfor i, segi := range sq.pq {\n\t\tif seg == segi {\n\t\t\theap.Remove(&sq.pq, i)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (o *StorageHyperFlexStorageContainer) HasUnCompressedUsedBytes() bool {\n\tif o != nil && o.UnCompressedUsedBytes != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func groomQueues(queues *Queues) (err kv.Error) {\n\tfor qName, qDetails := range *queues {\n\t\t// If we have enough runners drop the queue as it needs nothing done to it\n\t\tif len(qDetails.NodeGroup) == 0 || qDetails.Running >= qDetails.Ready+qDetails.NotVisible {\n\t\t\tif logger.IsTrace() {\n\t\t\t\tlogger.Trace(\"queue already handled\", \"queue\", qName, \"stack\", stack.Trace().TrimRuntime())\n\t\t\t}\n\t\t\tdelete(*queues, qName)\n\t\t}\n\t}\n\treturn nil\n}", "func (b *CompactableBuffer) Remove(address *EntryAddress) error {\n\taddress.LockForWrite()\n\tdefer address.UnlockWrite()\n\tresult := b.removeWithoutLock(address)\n\treturn result\n}", "func (q *Queue) Dequeue() interface{} {\n\treturn q.Elements.Remove(q.Elements.Front())\n}", "func (reg *registry[Item]) remove(topic string, ch chan Item, drain_channel bool) {\n\treg.lock.Lock()\n\tdefer reg.lock.Unlock()\n\tif _, ok := reg.topics[topic]; !ok {\n\t\treturn\n\t}\n\n\tif _, ok := reg.topics[topic][ch]; !ok {\n\t\treturn\n\t}\n\n\tdelete(reg.topics[topic], ch)\n\tdelete(reg.revTopics[ch], topic)\n\n\tif len(reg.topics[topic]) == 0 {\n\t\tdelete(reg.topics, topic)\n\t}\n\n\tif len(reg.revTopics[ch]) == 0 {\n\t\tif drain_channel {\n\t\t\treg.drainAndScheduleCloseChannel(ch)\n\t\t}\n\t\tdelete(reg.revTopics, ch)\n\t}\n}", "func (q *Queue) Dequeue() Lit {\n\tif len(q.items) == 0 {\n\t\treturn Undef\n\t}\n\tfirst := q.items[0]\n\tq.items = q.items[1:len(q.items)]\n\n\treturn first\n}", "func (j *JPNSoftwareMap) Del(ID string) (ok bool) {\n\tdelete(*j, ID)\n\tok = j.Has(ID) == false\n\treturn\n}", "func (q *Queue) Empty() bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\treturn len(q.items) == 0\n}", "func (n *trieNode) okToRemove() bool {\n\tif n.member {\n\t\treturn false\n\t}\n\tfor _, c := range n.children {\n\t\tif c != nil {\n\t\t\t// Still has a child, can't remove\n\t\t\treturn false\n\t\t}\n\t}\n\tif n.bitmap == nil {\n\t\t// not a bitmap node, so OK to remove.\n\t\treturn true\n\t}\n\treturn n.bitmap.isEmpty()\n}", "func (m *Map) Drop(seqno uint16, pid uint16) bool {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tif seqno != m.next {\n\t\treturn false\n\t}\n\n\tif len(m.entries) == 0 {\n\t\tm.entries = []entry{\n\t\t\tentry{\n\t\t\t\tfirst: seqno - 8192,\n\t\t\t\tcount: 8192,\n\t\t\t\tdelta: 0,\n\t\t\t\tpidDelta: 0,\n\t\t\t},\n\t\t}\n\t}\n\n\tm.pidDelta += pid - m.nextPid\n\tm.nextPid = pid\n\n\tm.delta--\n\tm.next = seqno + 1\n\treturn true\n}", "func (q *Queue) Remove() (int, error) {\r\n\tif len(q.data) == 0 {\r\n\t\treturn 0, fmt.Errorf(\"Queue is empty\")\r\n\t}\r\n\telement := q.data[0]\r\n\tq.data = q.data[1:]\r\n\treturn element, nil\r\n}", "func (this *MyQueue) Empty() bool {\n\treturn this.stack.IsEmpty()\n}", "func (st *FixedFIFO) Dequeue() (interface{}, error) {\n\tif st.IsLocked() {\n\t\treturn nil, NewQueueError(QueueErrorCodeLockedQueue, \"The queue is locked\")\n\t}\n\n\tselect {\n\tcase value, ok := <-st.queue:\n\t\tif ok {\n\t\t\treturn value, nil\n\t\t}\n\t\treturn nil, NewQueueError(QueueErrorCodeInternalChannelClosed, \"internal channel is closed\")\n\tdefault:\n\t\treturn nil, NewQueueError(QueueErrorCodeEmptyQueue, \"empty queue\")\n\t}\n}", "func (this *MyQueue) Empty() bool {\n\treturn len(this.Stack) == 0\n}", "func (q *Queue) Dequeue() error {\n\tif q.IsEmpty() {\n\t\treturn fmt.Errorf(\"the queue is empty\")\n\t}\n\telement := q.tail\n\tfor i := 0; i < q.len-2; i++ {\n\t\telement = element.next\n\t}\n\tq.head = element\n\tq.head.next = nil\n\tq.len--\n\treturn nil\n}", "func (q *Queue) Pop() (repoName string, opts IndexOptions, ok bool) {\n\tq.mu.Lock()\n\tif len(q.pq) == 0 {\n\t\tq.mu.Unlock()\n\t\treturn \"\", IndexOptions{}, false\n\t}\n\titem := heap.Pop(&q.pq).(*queueItem)\n\trepoName = item.repoName\n\topts = item.opts\n\n\tmetricQueueLen.Set(float64(len(q.pq)))\n\tmetricQueueCap.Set(float64(len(q.items)))\n\n\tq.mu.Unlock()\n\treturn repoName, opts, true\n}", "func (q *wantConnQueue) clearFront() (cleaned bool) {\n\tfor {\n\t\tw := q.peekFront()\n\t\tif w == nil || w.waiting() {\n\t\t\treturn cleaned\n\t\t}\n\t\tq.popFront()\n\t\tcleaned = true\n\t}\n}", "func (q *Queue) updateQueue() {\n\tpurge := []int{}\n\t// Loop through jobs and get the status of running jobs\n\tfor i, _ := range q.stack {\n\t\tif q.stack[i].Status == common.STATUS_RUNNING {\n\t\t\t// Build status update call\n\t\t\tjobStatus := common.RPCCall{Job: q.stack[i]}\n\n\t\t\terr := q.pool[q.stack[i].ResAssigned].Client.Call(\"Queue.TaskStatus\", jobStatus, &q.stack[i])\n\t\t\t// we care about the errors, but only from a logging perspective\n\t\t\tif err != nil {\n\t\t\t\tlog.WithField(\"rpc error\", err.Error()).Error(\"Error during RPC call.\")\n\t\t\t}\n\n\t\t\t// Check if this is now no longer running\n\t\t\tif q.stack[i].Status != common.STATUS_RUNNING {\n\t\t\t\t// Release the resources from this change\n\t\t\t\tlog.WithField(\"JobID\", q.stack[i].UUID).Debug(\"Job has finished.\")\n\n\t\t\t\t// Call out to the registered hooks that the job is complete\n\t\t\t\tgo HookOnJobFinish(Hooks.JobFinish, q.stack[i])\n\n\t\t\t\tvar hw string\n\t\t\t\tfor _, v := range q.pool[q.stack[i].ResAssigned].Tools {\n\t\t\t\t\tif v.UUID == q.stack[i].ToolUUID {\n\t\t\t\t\t\thw = v.Requirements\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tq.pool[q.stack[i].ResAssigned].Hardware[hw] = true\n\n\t\t\t\t// Set a purge time\n\t\t\t\tq.stack[i].PurgeTime = time.Now().Add(time.Duration(q.jpurge*24) * time.Hour)\n\t\t\t\t// Log purge time\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"JobID\": q.stack[i].UUID,\n\t\t\t\t\t\"PurgeTime\": q.stack[i].PurgeTime,\n\t\t\t\t}).Debug(\"Updated PurgeTime value\")\n\t\t\t}\n\t\t}\n\n\t\t// Check and delete jobs past their purge timer\n\t\tif q.stack[i].Status == common.STATUS_DONE || q.stack[i].Status == common.STATUS_FAILED || q.stack[i].Status == common.STATUS_QUIT {\n\t\t\tif time.Now().After(q.stack[i].PurgeTime) {\n\t\t\t\tpurge = append(purge, i)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Do we need to purge?\n\tif len(purge) > 0 {\n\t\t// Let the purge begin\n\t\tnewStack := []common.Job{}\n\t\t// Loop on the stack looking for index values that patch a value in the purge\n\t\tfor i := range q.stack {\n\t\t\t// Check if our index is in the purge\n\t\t\tvar inPurge bool\n\t\t\tfor _, v := range purge {\n\t\t\t\tif i == v {\n\t\t\t\t\tinPurge = true\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// It is not in the purge so append to new stack\n\t\t\tif !inPurge {\n\t\t\t\tnewStack = append(newStack, q.stack[i])\n\t\t\t}\n\t\t}\n\t\tq.stack = newStack\n\t}\n}", "func (f *frontier) Dequeue() {\n\tf.lk.Lock()\n\tdefer f.lk.Unlock()\n\tif len(f.nbs) == 0 {\n\t\treturn\n\t}\n\tf.nbs = f.nbs[1:]\n}", "func EnsureNoQueue(ctx context.Context, cli sqsiface.SQSAPI) error {\n\tsrc := commonv1alpha1.ReconcilableFromContext(ctx)\n\ttypedSrc := src.(*v1alpha1.AWSS3Source)\n\n\tif dest := typedSrc.Spec.Destination; dest != nil {\n\t\tif userProvidedQueue := dest.SQS; userProvidedQueue != nil {\n\t\t\t// do not delete queues managed by the user\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tqueueURL, err := sqs.QueueURL(cli, queueName(typedSrc))\n\tswitch {\n\tcase isNotFound(err):\n\t\tevent.Warn(ctx, ReasonUnsubscribed, \"Queue not found, skipping deletion\")\n\t\treturn nil\n\tcase isDenied(err):\n\t\t// it is unlikely that we recover from auth errors in the\n\t\t// finalizer, so we simply record a warning event and return\n\t\tevent.Warn(ctx, ReasonFailedUnsubscribe,\n\t\t\t\"Authorization error getting SQS queue. Ignoring: %s\", toErrMsg(err))\n\t\treturn nil\n\tcase err != nil:\n\t\treturn reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedUnsubscribe,\n\t\t\t\"Failed to determine URL of SQS queue: %s\", toErrMsg(err))\n\t}\n\n\towns, err := assertOwnership(cli, queueURL, typedSrc)\n\tif err != nil {\n\t\treturn reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedUnsubscribe,\n\t\t\t\"Failed to verify owner of SQS queue: %s\", toErrMsg(err))\n\t}\n\n\tif !owns {\n\t\tevent.Warn(ctx, ReasonUnsubscribed, \"Queue %q is not owned by this source instance, \"+\n\t\t\t\"skipping deletion\", queueURL)\n\t\treturn nil\n\t}\n\n\terr = sqs.DeleteQueue(cli, queueURL)\n\tswitch {\n\tcase isDenied(err):\n\t\t// it is unlikely that we recover from auth errors in the\n\t\t// finalizer, so we simply record a warning event and return\n\t\tevent.Warn(ctx, ReasonFailedUnsubscribe,\n\t\t\t\"Authorization error deleting SQS queue. Ignoring: %s\", toErrMsg(err))\n\t\treturn nil\n\tcase err != nil:\n\t\treturn reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedUnsubscribe,\n\t\t\t\"Error deleting SQS queue: %s\", toErrMsg(err))\n\t}\n\n\tevent.Normal(ctx, ReasonQueueDeleted, \"Deleted SQS queue %q\", queueURL)\n\n\treturn nil\n}", "func (m refCountedUrlSet) removeUrl(urlStr string) bool {\n\tremoved := false\n\tif ref, ok := m[urlStr]; ok {\n\t\tif ref == 1 {\n\t\t\tremoved = true\n\t\t\tdelete(m, urlStr)\n\t\t} else {\n\t\t\tm[urlStr]--\n\t\t}\n\t}\n\treturn removed\n}", "func (s *MQImpressionsStorage) Empty() bool {\n\ts.mutexQueue.Lock()\n\tdefer s.mutexQueue.Unlock()\n\treturn s.queue.Len() == 0\n}", "func whetherRemoveHost(info storage.HostInfo, currentBlockHeight uint64) bool {\n\tupRate := getHostUpRate(info)\n\tcriteria := calcHostRemoveCriteria(info, currentBlockHeight)\n\tif upRate > criteria {\n\t\treturn false\n\t}\n\treturn true\n}", "func (this *MyQueue) Empty() bool {\n\treturn len(this.q) == 0\n}", "func (q *QueueWatcher) checkQueueEmpty(jobName string) (bool, error) {\n\tqueues, err := q.client.Queues()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, queue := range queues {\n\t\tif queue.JobName == jobName {\n\t\t\treturn queue.Count == 0, nil\n\t\t}\n\t}\n\n\t// If queue does not exist consider it empty.\n\t// QueueWatcher is not active in the initial phase during which no items\n\t// have been enqueued yet.\n\t// E.g. when active checks start, the ProductionExhausted channel has been\n\t// closed.\n\treturn true, nil\n}", "func (q *FileQueue) Dequeue() (int64, []byte, error) {\n\n\tif q.IsEmpty() {\n\t\treturn -1, nil, nil\n\t}\n\n\t// check and update queue front index info\n\tindex, err := q.updateQueueFrontIndex()\n\tif err != nil {\n\t\treturn -1, nil, err\n\t}\n\tbb, err := q.peek(index)\n\treturn index, bb, err\n}", "func (pq *packetQueue) remove(s *sender, seqno int64, scope int) {\n\tpq.Lock()\n\tdefer pq.Unlock()\n\tfor next := pq.Front(); next != nil; next = next.Next() {\n\t\tp := next.Value.(*Packet)\n\t\tif p.sender.getID() == s.id && p.seqno == seqno && p.scope == scope {\n\t\t\tpq.Remove(next)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (storage *SrvStorage) DelQueue(vhost string, queue *queue.Queue) error {\n\tkey := fmt.Sprintf(\"%s.%s.%s\", queuePrefix, vhost, queue.GetName())\n\treturn storage.db.Del(key)\n}", "func (rate *Ratelimiter) cleanup() (empty bool) {\n\trate.mu.Lock()\n\tdefer rate.mu.Unlock()\n\n\tfor key, entry := range rate.tableIPv4 {\n\t\tentry.mu.Lock()\n\t\tif rate.timeNow().Sub(entry.lastTime) > garbageCollectTime {\n\t\t\tdelete(rate.tableIPv4, key)\n\t\t}\n\t\tentry.mu.Unlock()\n\t}\n\n\tfor key, entry := range rate.tableIPv6 {\n\t\tentry.mu.Lock()\n\t\tif rate.timeNow().Sub(entry.lastTime) > garbageCollectTime {\n\t\t\tdelete(rate.tableIPv6, key)\n\t\t}\n\t\tentry.mu.Unlock()\n\t}\n\n\treturn len(rate.tableIPv4) == 0 && len(rate.tableIPv6) == 0\n}", "func (Q *Queue) Dequeue() error {\n\tif Q.head == nil {\n\t\treturn errors.New(\"your queue is empty and impossible delete element\")\n\t}\n\telement := Node {}\n\telement.value = Q.head.value\n\tif Q.head.next != nil {\n\t\tQ.head = Q.head.next\n\t} else {\n\t\tQ.head = nil\n\t\tQ.tail = nil\n\t}\n\tQ.size--\n\treturn nil\n}", "func (svc *SQS) XPurgeQueue(ctx context.Context, queueURL string) error {\n\t_, err := svc.PurgeQueue(ctx, PurgeQueueRequest{\n\t\tQueueURL: queueURL,\n\t})\n\treturn err\n}" ]
[ "0.60027367", "0.5677631", "0.563571", "0.5616582", "0.5497436", "0.5481202", "0.54472536", "0.54457", "0.54185396", "0.53994423", "0.5352575", "0.5277354", "0.52290535", "0.5129753", "0.5122774", "0.5116718", "0.5096262", "0.5095654", "0.50874686", "0.5082583", "0.50537497", "0.5035871", "0.5032258", "0.50291175", "0.49949875", "0.49812487", "0.4974222", "0.49680665", "0.4962087", "0.49320486", "0.4899363", "0.48835176", "0.48524597", "0.48419195", "0.48312575", "0.48282716", "0.48249096", "0.48233986", "0.48196465", "0.48193744", "0.4815103", "0.48008442", "0.48003933", "0.4800091", "0.47984758", "0.479751", "0.47862777", "0.47790205", "0.477492", "0.4762616", "0.47606456", "0.4760467", "0.47589296", "0.47570157", "0.4753619", "0.4748258", "0.4739021", "0.4730927", "0.4724802", "0.47224575", "0.4715394", "0.47058278", "0.4701159", "0.47008216", "0.46910936", "0.46872234", "0.4679357", "0.46789578", "0.46784747", "0.46750498", "0.4674063", "0.4670224", "0.4658082", "0.46545246", "0.46303105", "0.46267974", "0.4626767", "0.46217495", "0.46135563", "0.46108082", "0.4609327", "0.46045154", "0.46002463", "0.45996818", "0.45897272", "0.45854053", "0.45818788", "0.45813116", "0.45803353", "0.45691097", "0.456546", "0.45589873", "0.45588738", "0.45564783", "0.45540878", "0.45534775", "0.45524666", "0.4550421", "0.45349345", "0.45346123" ]
0.83653677
0
ConnectDB connect to database
func ConnectDB() (db *gorm.DB, err error) { config := GetConfig() dbURI := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable", config.DB.Host, config.DB.Port, config.DB.Username, config.DB.Name, config.DB.Password) db, err = gorm.Open(config.DB.Dialect, dbURI) if os.Getenv("ENV") == "prod" { db.LogMode(false) } return db, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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() *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 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 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 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 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\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 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 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 ConnectMe() (db *sql.DB, err error) {\n\tgodotenv.Load()\n\tconnString := fmt.Sprintf(\"server=%s;user id=%s;password=%s;port=%s;database=%s;\",\n\t\tutilities.GoDotEnvVariable(\"Server\"), utilities.GoDotEnvVariable(\"user\"), utilities.GoDotEnvVariable(\"Password\"), utilities.GoDotEnvVariable(\"Port\"), utilities.GoDotEnvVariable(\"Database\"))\n\tdb, err = sql.Open(\"sqlserver\", connString)\n\tctx := context.Background()\n\terr = db.PingContext(ctx)\n\treturn db, err\n}", "func ConnectDB() 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 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 (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 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(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(p *DBConfig) (*sql.DB, error) {\n\tconnStr := fmt.Sprintf(connFmt, p.Host, p.Port, p.User, p.Pass, p.DB)\n\tdb, err := sql.Open(\"postgres\", connStr)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = db.Ping(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func ConnectDb () (*sql.DB, error) {\n\tvar Db *sql.DB\n\tvar err error\n\tpsqlconn := fmt.Sprintf(\"host = %s port = %d user = %s dbname = %s sslmode = disable\", host, port, user, dbname)\n\tDb, err = sql.Open(\"postgres\", psqlconn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err = Db.Ping(); err != nil {\n\t\treturn nil, err\n\t\tDb.Close()\n\t}\n\tfmt.Println(\"psql connected\")\n\treturn Db, 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(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 (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 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 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 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 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 Connect() (*sql.DB, error) {\n\treturn db.Connect(*dbURI)\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 ConnectDB() (*sql.DB) {\n\tdb, error := sql.Open(\"sqlite3\", \"/home/ashwini/P4\")\n\tif error != nil { panic(error) }\n\tif db == nil { panic(\"db nil\") }\n\t\n\treturn db\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 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 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 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 Connect(driver, db string) *sql.DB {\n\tDB, err := sql.Open(driver, db)\n\tcheckErr(err)\n\treturn DB\n}", "func ConnectDb(dbName string) *sql.DB {\n\tdb, err := sql.Open(\"sqlite3\", dbName)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn db\n}", "func ConnectDB(ctx context.Context, conf config.MongoConfiguration) *mongo.Database {\n\tconnection := options.Client().ApplyURI(conf.Server)\n\t// establish connection\n\tclient, err := mongo.Connect(ctx, connection)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn client.Database(conf.Database)\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 Connect(host string, port int, user, password, dbname string, sslmode bool) (*sql.DB, error) {\n\n\tconnStr := fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s\", host, port, user, password, dbname)\n\tif sslmode {\n\t\tconnStr += \" sslmode=require\"\n\t}\n\n\tvar err error\n\tdb, err = sql.Open(\"postgres\", connStr)\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\treturn db, nil\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 Connect(cf *SQLConfig) (*DB, error) {\n\tconnectionString := fmt.Sprintf(\"postgres://%v:%v@%v:%v/%v?sslmode=%v\", cf.Username, cf.Password, cf.Host, cf.Post, cf.Database, cf.SSLMode)\n\tdb, err := sql.Open(\"postgres\", connectionString)\n\tif err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tpingErr := db.Ping()\n\t\tif pingErr != nil {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Cannot connect to database. Error: %s\", pingErr.Error()))\n\t\t} else {\n\t\t\treturn &DB{db}, nil\n\t\t}\n\t}\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() (*DB, error) {\n\tpsqlInfo := fmt.Sprintf(\"host=db port=5432 user=ggp-user password=password dbname=development_db sslmode=disable\")\n\tdb, err := gorm.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = db.DB().Ping()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &DB{DB: db}, nil\n}", "func ConnectDB() *sql.DB {\n\tdb, err := sql.Open(\"postgres\", env.DatabaseDSN)\n\tif err != nil {\n\t\tpanic(errors.Wrap(err, \"failed to call sql.open\"))\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\tpanic(errors.Wrap(err, \"failed to ping database\"))\n\t}\n\n\treturn db\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 ConnectDB() *sql.DB {\n\tpgURL, _ := pq.ParseURL(os.Getenv(\"DATABASE_URL\"))\n\tdb, _ := sql.Open(\"postgres\", pgURL)\n\n\terr := db.Ping() // check connection to db and log error\n\tLogFatal(err)\n\n\treturn db\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 Connect(c *config.Config) (*sql.DB, error) {\n\tstr := fmt.Sprintf(\"postgres://%s:%s@%s:%s/%s?sslmode=disable\", c.DatabaseUser, c.DatabasePassword, c.DatabaseHost, c.DatabasePort, c.DatabaseName)\n\tdb, err := sql.Open(\"postgres\", str)\n\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\n\treturn db, err\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() (*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 ConnectDB(database string, parameters *Parameters) (*sql.DB, error) {\n\tif database == \"postgres\" {\n\t\treturn postgresConnect(parameters)\n\t}\n\treturn nil, errors.New(\"Unknown/unsupported database type \\\"\" + database + \"\\\"\")\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 (m *PersonDAO) Connect() {\n\n\tdialInfo := &mgo.DialInfo{\n\t\tAddrs: []string{m.Server},\n\t\tTimeout: 60 * time.Second,\n\t\tDatabase: m.Database,\n\t\tUsername: m.Username,\n\t\tPassword: m.Password,\n\t}\n\n\tsession, err := mgo.DialWithInfo(dialInfo)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdb = session.DB(m.Database)\n}", "func (m *CDatabase) Connect() {\n\tsession, err := mgo.Dial(m.Server)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdb = session.DB(m.Database)\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 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 ConnectDB() (*sql.DB, error) {\n\tpgURL, err := pq.ParseURL(os.Getenv(\"SQL_URL\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb, err := sql.Open(\"postgres\", pgURL)\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\treturn db, 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 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 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 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 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 Connect() *sql.DB {\n\tdbinfo := fmt.Sprintf(\"user=%s password=%s dbname=%s sslmode=disable\", DbUser, DbPassword, DbName)\n\n\tdb, _ := sql.Open(\"postgres\", dbinfo)\n\n\treturn db\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 Connect() *sql.DB {\n\tURL := fmt.Sprintf(\"user=%s password=%s dbname=%s sslmode=%s\", configs.Database.User, configs.Database.Pass, configs.Database.Name, \"disable\")\n\tdb, err := sql.Open(\"postgres\", URL)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil\n\t}\n\treturn db\n}", "func Connect() *gorm.DB {\n\tdsn := fmt.Sprintf(\n\t\t\"host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=America/Bogota\",\n\t\tconfig.Load(\"DB_HOST\"), config.Load(\"DB_USER\"), config.Load(\"DB_PWD\"), config.Load(\"DB_NAME\"),\n\t\tconfig.Load(\"DB_PORT\"),\n\t)\n\n\tdb, err := gorm.Open(postgres.Open(dsn), &gorm.Config{\n\t\tQueryFields: true,\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn db\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 Connect(dburl string) (Database, error) {\n\tu, err := url.Parse(dburl)\n\tif err != nil {\n\t\treturn Database{}, err\n\t}\n\n\thost := u.Host\n\tport := \"80\"\n\tif hp := strings.Split(u.Host, \":\"); len(hp) > 1 {\n\t\thost = hp[0]\n\t\tport = hp[1]\n\t}\n\n\tdb := Database{host, port, u.Path[1:], u.User,\n\t\tmap[string][]string{}, net.Dial, defaultChangeDelay}\n\tif !db.Running() {\n\t\treturn Database{}, errNotRunning\n\t}\n\tif !db.Exists() {\n\t\treturn Database{}, errors.New(\"database does not exist\")\n\t}\n\n\treturn db, nil\n}", "func connectDB() error {\n\n\tdbInfos := fmt.Sprintf(`host=%s port=%d user=%s password=%s dbname=%s sslmode=disable`,\n\t\thost, port, user, password, dbname)\n\n\tdb, err := sql.Open(\"postgres\", dbInfos)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprovider := &pr.PostgresProvider{DB: db, TableName: \"users\"}\n\ttestService = &Service{\n\t\tprovider: provider,\n\t}\n\terr = cleanDB(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Connect() (*sql.DB, error) {\n\thost := viper.GetString(\"google.cloudsql.host\")\n\tname := viper.GetString(\"google.cloudsql.name\")\n\tuser := viper.GetString(\"google.cloudsql.user\")\n\tpass := viper.GetString(\"google.cloudsql.pass\")\n\tdsn := fmt.Sprintf(\"host=%s dbname=%s user=%s password=%s sslmode=disable\",\n\t\thost, name, user, pass)\n\tdb, err := sql.Open(\"cloudsqlpostgres\", dsn)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while connecting to cloudsql: %v\", err)\n\t}\n\tlog.Printf(\"Connected to cloudsql %q\", host)\n\treturn db, nil\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 ConnectDB() *mongo.Client {\n\t//toma la coneccion de clientOption\n\tclient, err := mongo.Connect(context.TODO(), clientOptions)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t\treturn client\n\t}\n\terr = client.Ping(context.TODO(), nil)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t\treturn client\n\t}\n\n\tlog.Println(\"conexion exitosa con la DB\")\n\treturn client\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 (m *DAOUtil) Connect() *mgo.Database {\n\tsession, err := mgo.Dial(m.Server)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn session.DB(m.Database)\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 (d DbConfig) Connect() (*gorm.DB, error) {\n\t/*\n\t * We will build the connection string\n\t * Then will connect to the database\n\t */\n\tcStr := fmt.Sprintf(\"host=%s port=%s dbname=%s user=%s password=%s sslmode=disable\",\n\t\td.Host, d.Port, d.Database, d.Username, d.Password)\n\n\treturn gorm.Open(\"postgres\", cStr)\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(address string) {\n\tvar err error\n\n\tdb, err = sql.Open(\"mysql\", address)\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening DB\")\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.Fatal(\"Error connecting to DB\")\n\t}\n}", "func Connect() *sql.DB {\n\tfmtStr := \"host=%s port=%s user=%s \" +\n\t\t\"password=%s dbname=%s sslmode=disable\"\n\tpsqlInfo := fmt.Sprintf(\n\t\tfmtStr,\n\t\tos.Getenv(\"PG_HOST\"),\n\t\tos.Getenv(\"PG_PORT\"),\n\t\tos.Getenv(\"PG_USER\"),\n\t\tos.Getenv(\"PG_PASSWORD\"),\n\t\tos.Getenv(\"PG_DBNAME\"),\n\t)\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn db\n}", "func ConnectDB(connection, dbname string) (*MovieDatabase, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(connection))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tctxping, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\terr = client.Ping(ctxping, readpref.Primary())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdb := client.Database(dbname)\n\treturn &MovieDatabase{DB: db, Client: client, Context: ctx}, nil\n}", "func Connect() (db *sql.DB, err error) {\n\treturn sql.Open(DBDriver, DBSource+DBParams)\n}", "func DbConnect(c *gin.Context) {\n\ts := db.Properties.Sess.Clone()\n\n\tdefer s.Close()\n\n\tc.Set(\"db\", s.DB(db.Properties.Conn.Name))\n\tc.Next()\n}", "func Connect() error {\n\n\tdb, err := sql.Open(\"postgres\", config.Get().DatabaseConnection)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdatabase = db\n\treturn nil\n}", "func (db *BlabDb) Connect() {\n\tpath, err := filepath.Abs(\"/run/secrets/blabber-db-password\")\n\tif (err != nil) {\n\t\tpanic(err)\n\t}\n\tdata, err := ioutil.ReadFile(path)\n\tif (err != nil) {\n\t\tpanic(err)\n\t}\n\n\tpassword := string(data)\n\n\tpsqlInfo := 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.DB, err = sql.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func Connect() *pg.DB {\n\topt := &pg.Options{\n\t\tAddr: \"localhost:5432\",\n\t\tUser: \"postgres\",\n\t\tPassword: \"changeme\",\n\t\tDatabase: \"auth_db\",\n\t}\n\t//create db pointer\n\tvar db *pg.DB = pg.Connect(opt)\n\tif db == nil {\n\t\tlog.Printf(\"Failed to connect to db\\n\")\n\t\tos.Exit(401)\n\t}\n\tlog.Printf(\"Connected to db\\n\")\n\treturn db\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() *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 ConnectDB() *mongo.Client {\n\tclient, err := mongo.Connect(context.TODO(), clientOptions)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t\treturn client\n\t}\n\n\terr = client.Ping(context.TODO(), nil)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t\treturn client\n\t}\n\tlog.Println(\"Conexion exitosa con la DB\")\n\treturn client\n}", "func (c *CoursesDAO) Connect() {\n\tsession, err := mgo.Dial(c.Server)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t//create session\n\tdb = session.DB(c.Database)\n}", "func (d *Database) Connect() (*sqlx.DB, error) {\n\tconnectParams := fmt.Sprintf(\"user=%s host=localhost port=%s dbname=%s sslmode=%s password=%s\", d.Cf.GetDBUser(), d.Cf.DbPort, d.Cf.GetDBName(), d.Cf.GetDBSSL(), d.Cf.DbPassword)\n\tdb, err := sqlx.Connect(\"postgres\", connectParams)\n\tutil.Handle(\"Error creating a DB connection: \", err)\n\treturn db, err\n}", "func ConnectDSN(username, password, databaseName string) (*sql.DB, error) {\n\t//Connect to the database\n\tdatabaseDSN := username + \":\" + password + \"@/\" + databaseName + \"?parseTime=true&charset=utf8mb4\"\n\tdb, err := sql.Open(\"mysql\", databaseDSN)\n\tif err != nil {\n\t\tlog.Fatal(\"Error connecting to the database\")\n\t\treturn nil, err\n\t}\n\tDatabase = db\n\treturn db, nil\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 (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 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 Connect(cfg *Config) (*Connection, error) {\n\td, err := gorm.Open(cfg.Driver, cfg.Args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &Connection{\n\t\tC: d,\n\t\tlog: logrus.WithField(\"context\", \"db\"),\n\t}\n\tc.log.Info(\"connected to database\")\n\treturn c, nil\n}", "func Connect() (*gorm.DB, error) {\n\n\tdb, err := gorm.Open(\"postgres\", config.ConnectionString)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, 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() 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() (*pg.DB, error) {\n\tvar (\n\t\tconn *pg.DB\n\t\tn int\n\t)\n\taddr := fmt.Sprintf(\"%s:%v\", \"192.168.0.103\", 6001)\n\tconn = pg.Connect(&pg.Options{\n\t\tAddr: addr,\n\t\tUser: User,\n\t\tPassword: Password,\n\t\tDatabase: DatabaseName,\n\t})\n\t_, err := conn.QueryOne(pg.Scan(&n), \"SELECT 1\")\n\tif err != nil {\n\t\treturn conn, fmt.Errorf(\"Error conecting to DB. addr: %s, user: %s, db: %s,%v\", addr, User, DatabaseName, err)\n\t}\n\n\tif err := createSchema(conn); err != nil {\n\t\treturn conn, fmt.Errorf(\"Error creating DB schemas. %v\", err)\n\t}\n\treturn conn, nil\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 Connect() (*sqlx.DB, error) {\n\tpsqlInfo := 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 := sqlx.Connect(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tdb.Close()\n\t\treturn nil, err\n\t}\n\tlogrus.Debugf(\"Successfully connected to database %s\", psqlInfo)\n\treturn db, nil\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}" ]
[ "0.8131591", "0.79059196", "0.77978474", "0.77385414", "0.76394755", "0.7557192", "0.7537929", "0.7522747", "0.75134176", "0.7506408", "0.7488831", "0.7472738", "0.745338", "0.745188", "0.74491537", "0.7444304", "0.74430364", "0.7442776", "0.74337655", "0.74329805", "0.7432598", "0.7431254", "0.7396554", "0.73866934", "0.7370882", "0.7369967", "0.73676", "0.73453987", "0.7344217", "0.73436236", "0.73296493", "0.7326051", "0.73147124", "0.73096305", "0.7309218", "0.7307173", "0.73047256", "0.7303271", "0.7296911", "0.729522", "0.72917336", "0.728721", "0.7285741", "0.72810006", "0.7280238", "0.72800744", "0.72423583", "0.7240513", "0.7238067", "0.72207475", "0.7218029", "0.7217597", "0.72164994", "0.7212935", "0.7208509", "0.7205915", "0.7203204", "0.71814066", "0.7181144", "0.71759576", "0.71753883", "0.71747816", "0.71706325", "0.7155856", "0.7151396", "0.71506876", "0.7146834", "0.7135884", "0.71338195", "0.71337485", "0.7132684", "0.713236", "0.7131256", "0.711881", "0.71186787", "0.71167433", "0.7114915", "0.7113532", "0.7111253", "0.7109623", "0.71063465", "0.7085075", "0.70731276", "0.70703334", "0.7069727", "0.70663196", "0.70657206", "0.70631504", "0.7043026", "0.7034156", "0.70252675", "0.70240855", "0.7021427", "0.70199007", "0.701089", "0.7010882", "0.70038056", "0.700288", "0.69916123", "0.69896674" ]
0.72602135
46
GetConditions returns the list of conditions from the status
func (s NovaSchedulerStatus) GetConditions() condition.Conditions { return s.Conditions }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in HelmRepository) GetConditions() []metav1.Condition {\n\treturn in.Status.Conditions\n}", "func GetConditions(t *Target) ([]target.Condition, error) {\n\tif t.err != nil {\n\t\treturn nil, errors.New(\"GetConditions called on erroneous target\")\n\t}\n\ttype resource struct {\n\t\tStatus struct {\n\t\t\tConditions []target.Condition `json:\"conditions\"`\n\t\t} `json:\"status\"`\n\t}\n\tvar ro = resource{}\n\terr := runtime.DefaultUnstructuredConverter.\n\t\tFromUnstructured(t.infService.Object, &ro)\n\treturn ro.Status.Conditions, err\n}", "func getConditions(cs v1.ConditionStatus) []*statusCondition {\n\tms := make([]*statusCondition, len(conditionStatuses))\n\n\tfor i, status := range conditionStatuses {\n\t\tms[i] = &statusCondition{\n\t\t\tstatus: strings.ToLower(string(status)),\n\t\t\tvalue: boolFloat64(cs == status),\n\t\t}\n\t}\n\n\treturn ms\n}", "func (in OCIRepository) GetConditions() []metav1.Condition {\n\treturn in.Status.Conditions\n}", "func (a Authenticate) GetConditions(ctx weave.Context) []weave.Condition {\n\t// (val, ok) form to return nil instead of panic if unset\n\tval, _ := ctx.Value(contextKeyGov).([]weave.Condition)\n\treturn val\n}", "func (ks *KeystoneServiceHelper) GetConditions() *condition.Conditions {\n\treturn &ks.service.Status.Conditions\n}", "func (group *ResourceGroup) GetConditions() conditions.Conditions {\n\treturn group.Status.Conditions\n}", "func (group *ResourceGroup) GetConditions() conditions.Conditions {\n\treturn group.Status.Conditions\n}", "func (profile *Profile) GetConditions() conditions.Conditions {\n\treturn profile.Status.Conditions\n}", "func (k *Konfiguration) GetStatusConditions() *[]metav1.Condition {\n\treturn &k.Status.Conditions\n}", "func (in *GitRepository) GetStatusConditions() *[]metav1.Condition {\n\treturn &in.Status.Conditions\n}", "func (w *Wug) GetConditions(query *Query) (*Conditions, error) {\n\tdata, err := w.GetRawConditions(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconditions := &Conditions{}\n\terr = json.Unmarshal(data, conditions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn conditions, nil\n}", "func (image *Image) GetConditions() conditions.Conditions {\n\treturn image.Status.Conditions\n}", "func (enterprise *RedisEnterprise) GetConditions() conditions.Conditions {\n\treturn enterprise.Status.Conditions\n}", "func (topic *Topic) GetConditions() conditions.Conditions {\n\treturn topic.Status.Conditions\n}", "func (service *PrivateLinkService) GetConditions() conditions.Conditions {\n\treturn service.Status.Conditions\n}", "func (site *Site) GetConditions() conditions.Conditions {\n\treturn site.Status.Conditions\n}", "func (rule *NamespacesEventhubsAuthorizationRule) GetConditions() conditions.Conditions {\n\treturn rule.Status.Conditions\n}", "func (database *SqlDatabase) GetConditions() conditions.Conditions {\n\treturn database.Status.Conditions\n}", "func (account *DatabaseAccount) GetConditions() conditions.Conditions {\n\treturn account.Status.Conditions\n}", "func (o *AddonStatus) GetStatusConditions() (value []*AddonStatusCondition, ok bool) {\n\tok = o != nil && o.bitmap_&32 != 0\n\tif ok {\n\t\tvalue = o.statusConditions\n\t}\n\treturn\n}", "func (r *SimpleExtensionResource) GetConditions() conditions.Conditions {\n\treturn r.Status.Conditions\n}", "func (server *FlexibleServer) GetConditions() conditions.Conditions {\n\treturn server.Status.Conditions\n}", "func (container *SqlDatabaseContainer) GetConditions() conditions.Conditions {\n\treturn container.Status.Conditions\n}", "func (c *InMemoryCluster) GetConditions() clusterv1.Conditions {\n\treturn c.Status.Conditions\n}", "func (record *PrivateDnsZonesSRVRecord) GetConditions() conditions.Conditions {\n\treturn record.Status.Conditions\n}", "func (service *StorageAccountsTableService) GetConditions() conditions.Conditions {\n\treturn service.Status.Conditions\n}", "func (machine *VirtualMachine) GetConditions() conditions.Conditions {\n\treturn machine.Status.Conditions\n}", "func (machine *VirtualMachine) GetConditions() conditions.Conditions {\n\treturn machine.Status.Conditions\n}", "func GetConditions(u *unstructured.Unstructured) ([]Condition, error) {\n\tvar conditions []Condition\n\tvar err error\n\n\tfn := GetLegacyConditionsFn(u)\n\tif fn == nil {\n\t\tfn = GetGenericConditionsFn(u)\n\t}\n\n\tif fn != nil {\n\t\tconditions, err = fn(u)\n\t}\n\n\tconditions = addTerminationCondition(u, conditions)\n\n\treturn conditions, err\n}", "func (store *ConfigurationStore) GetConditions() conditions.Conditions {\n\treturn store.Status.Conditions\n}", "func (o ApplicationStatusOutput) Conditions() ApplicationStatusConditionsArrayOutput {\n\treturn o.ApplyT(func(v ApplicationStatus) []ApplicationStatusConditions { return v.Conditions }).(ApplicationStatusConditionsArrayOutput)\n}", "func (l *License) GetConditions() []string {\n\tif l == nil || l.Conditions == nil {\n\t\treturn nil\n\t}\n\treturn *l.Conditions\n}", "func (m *MessageRule) GetConditions()(MessageRulePredicatesable) {\n return m.conditions\n}", "func (r *serviceStatusResolver) Conditions(ctx context.Context) ([]edgecluster.ServiceConditionResolverContract, error) {\n\tresponse := []edgecluster.ServiceConditionResolverContract{}\n\tfor _, condition := range r.serviceStatus.Conditions {\n\t\tif resolver, err := r.resolverCreator.NewServiceConditionResolver(ctx, condition); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tresponse = append(response, resolver)\n\t\t}\n\t}\n\n\treturn response, nil\n}", "func (credential *FederatedIdentityCredential) GetConditions() conditions.Conditions {\n\treturn credential.Status.Conditions\n}", "func (pool *WorkspacesBigDataPool) GetConditions() conditions.Conditions {\n\treturn pool.Status.Conditions\n}", "func (o *AddonStatus) StatusConditions() []*AddonStatusCondition {\n\tif o != nil && o.bitmap_&32 != 0 {\n\t\treturn o.statusConditions\n\t}\n\treturn nil\n}", "func (policy *StorageAccountsManagementPolicy) GetConditions() conditions.Conditions {\n\treturn policy.Status.Conditions\n}", "func (policy *StorageAccountsManagementPolicy) GetConditions() conditions.Conditions {\n\treturn policy.Status.Conditions\n}", "func (o ValidatingAdmissionPolicyStatusPatchOutput) Conditions() metav1.ConditionPatchArrayOutput {\n\treturn o.ApplyT(func(v ValidatingAdmissionPolicyStatusPatch) []metav1.ConditionPatch { return v.Conditions }).(metav1.ConditionPatchArrayOutput)\n}", "func (o JobStatusOutput) Conditions() JobConditionArrayOutput {\n\treturn o.ApplyT(func(v JobStatus) []JobCondition { return v.Conditions }).(JobConditionArrayOutput)\n}", "func (network *VirtualNetwork) GetConditions() conditions.Conditions {\n\treturn network.Status.Conditions\n}", "func (o ValidatingAdmissionPolicyStatusOutput) Conditions() metav1.ConditionArrayOutput {\n\treturn o.ApplyT(func(v ValidatingAdmissionPolicyStatus) []metav1.Condition { return v.Conditions }).(metav1.ConditionArrayOutput)\n}", "func (r *KVMMachine) GetConditions() clusterv1.Conditions {\n\treturn r.Status.Conditions\n}", "func (ns *Namespace) Conditions() []api.Condition {\n\t// Treat the code/msg combination as a combined key.\n\ttype codeMsg struct {\n\t\tcode api.Code\n\t\tmsg string\n\t}\n\n\t// Reorder so that the objects are grouped by code and message\n\tbyCM := map[codeMsg][]api.AffectedObject{}\n\tfor obj, codes := range ns.conditions {\n\t\tfor code, msg := range codes {\n\t\t\tcm := codeMsg{code: code, msg: msg}\n\t\t\tbyCM[cm] = append(byCM[cm], obj)\n\t\t}\n\t}\n\n\t// Flatten into a list of conditions\n\tconds := []api.Condition{}\n\tfor cm, objs := range byCM {\n\t\t// If the only affected object is unnamed (e.g., it refers to the current namespace), omit it.\n\t\tc := api.Condition{Code: cm.code, Msg: cm.msg}\n\t\tif len(objs) > 0 || objs[0].Name != \"\" {\n\t\t\tapi.SortAffectedObjects(objs)\n\t\t\tc.Affects = objs\n\t\t}\n\t\tconds = append(conds, c)\n\t}\n\n\tsort.Slice(conds, func(i, j int) bool {\n\t\tif conds[i].Code != conds[j].Code {\n\t\t\treturn conds[i].Code < conds[j].Code\n\t\t}\n\t\treturn conds[i].Msg < conds[j].Msg\n\t})\n\n\tif len(conds) == 0 {\n\t\tconds = nil // prevent anything from appearing in the status\n\t}\n\treturn conds\n}", "func (ampm *AzureMachinePoolMachine) GetConditions() clusterv1.Conditions {\n\treturn ampm.Status.Conditions\n}", "func (r *IBMPowerVSImage) GetConditions() capiv1beta1.Conditions {\n\treturn r.Status.Conditions\n}", "func (o HorizontalPodAutoscalerStatusOutput) Conditions() HorizontalPodAutoscalerConditionArrayOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerStatus) []HorizontalPodAutoscalerCondition { return v.Conditions }).(HorizontalPodAutoscalerConditionArrayOutput)\n}", "func (o HorizontalPodAutoscalerStatusOutput) Conditions() HorizontalPodAutoscalerConditionArrayOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerStatus) []HorizontalPodAutoscalerCondition { return v.Conditions }).(HorizontalPodAutoscalerConditionArrayOutput)\n}", "func (o HorizontalPodAutoscalerStatusPatchOutput) Conditions() HorizontalPodAutoscalerConditionPatchArrayOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerStatusPatch) []HorizontalPodAutoscalerConditionPatch {\n\t\treturn v.Conditions\n\t}).(HorizontalPodAutoscalerConditionPatchArrayOutput)\n}", "func (o HorizontalPodAutoscalerStatusPatchOutput) Conditions() HorizontalPodAutoscalerConditionPatchArrayOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerStatusPatch) []HorizontalPodAutoscalerConditionPatch {\n\t\treturn v.Conditions\n\t}).(HorizontalPodAutoscalerConditionPatchArrayOutput)\n}", "func (m *AzureManagedMachinePool) GetConditions() clusterv1.Conditions {\n\treturn m.Status.Conditions\n}", "func (assignment *SqlRoleAssignment) GetConditions() conditions.Conditions {\n\treturn assignment.Status.Conditions\n}", "func (scaleSet *VirtualMachineScaleSet) GetConditions() conditions.Conditions {\n\treturn scaleSet.Status.Conditions\n}", "func (setting *ServersAdvancedThreatProtectionSetting) GetConditions() conditions.Conditions {\n\treturn setting.Status.Conditions\n}", "func (ruleset *DnsForwardingRuleset) GetConditions() conditions.Conditions {\n\treturn ruleset.Status.Conditions\n}", "func (rule *NamespacesTopicsSubscriptionsRule) GetConditions() conditions.Conditions {\n\treturn rule.Status.Conditions\n}", "func (function *SqlDatabaseContainerUserDefinedFunction) GetConditions() conditions.Conditions {\n\treturn function.Status.Conditions\n}", "func (policy *ServersConnectionPolicy) GetConditions() conditions.Conditions {\n\treturn policy.Status.Conditions\n}", "func (o JobStatusPtrOutput) Conditions() JobConditionArrayOutput {\n\treturn o.ApplyT(func(v JobStatus) []JobCondition { return v.Conditions }).(JobConditionArrayOutput)\n}", "func (o ApplicationStatusPtrOutput) Conditions() ApplicationStatusConditionsArrayOutput {\n\treturn o.ApplyT(func(v *ApplicationStatus) []ApplicationStatusConditions {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Conditions\n\t}).(ApplicationStatusConditionsArrayOutput)\n}", "func (o MachineInstanceStatusOutput) Conditions() MachineInstanceStatusConditionsArrayOutput {\n\treturn o.ApplyT(func(v MachineInstanceStatus) []MachineInstanceStatusConditions { return v.Conditions }).(MachineInstanceStatusConditionsArrayOutput)\n}", "func (a *Agent) getConditions() map[condition]bool {\n\tresult := map[condition]bool{}\n\n\tfor _, o := range a.mind.objects() {\n\t\tfor attrType, attrVal := range o.getAttrs() {\n\t\t\tif _, seen := qualitativeAttrTypes[attrType]; !seen {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult[a.newAttributeCondition(o.getType(), attrType, attrVal)] = true\n\t\t}\n\t}\n\n\tfor stateType, stateVal := range a.state.states {\n\t\tif stateInfo, seen := agentStateInfos[stateType]; seen {\n\t\t\tresult[a.newAgentCondition(stateType, stateVal > stateInfo.threshold)] = true\n\t\t} else {\n\t\t\tresult[a.newAgentCondition(stateType, stateVal > 0)] = true\n\t\t}\n\t}\n\n\treturn result\n}", "func (o StorageClusterStatusOutput) Conditions() StorageClusterStatusConditionsArrayOutput {\n\treturn o.ApplyT(func(v StorageClusterStatus) []StorageClusterStatusConditions { return v.Conditions }).(StorageClusterStatusConditionsArrayOutput)\n}", "func (o AccessLevelBasicOutput) Conditions() AccessLevelBasicConditionArrayOutput {\n\treturn o.ApplyT(func(v AccessLevelBasic) []AccessLevelBasicCondition { return v.Conditions }).(AccessLevelBasicConditionArrayOutput)\n}", "func (o *SwitchState) GetConditions() []SwitchConditionDefinition {\n\tif o.Conditions == nil {\n\t\treturn make([]SwitchConditionDefinition, 0)\n\t}\n\n\treturn o.Conditions\n}", "func (o KubernetesClusterStatusOutput) Conditions() KubernetesClusterStatusConditionsArrayOutput {\n\treturn o.ApplyT(func(v KubernetesClusterStatus) []KubernetesClusterStatusConditions { return v.Conditions }).(KubernetesClusterStatusConditionsArrayOutput)\n}", "func (o HorizontalPodAutoscalerStatusPatchPtrOutput) Conditions() HorizontalPodAutoscalerConditionPatchArrayOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerStatusPatch) []HorizontalPodAutoscalerConditionPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Conditions\n\t}).(HorizontalPodAutoscalerConditionPatchArrayOutput)\n}", "func (o HorizontalPodAutoscalerStatusPatchPtrOutput) Conditions() HorizontalPodAutoscalerConditionPatchArrayOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerStatusPatch) []HorizontalPodAutoscalerConditionPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Conditions\n\t}).(HorizontalPodAutoscalerConditionPatchArrayOutput)\n}", "func (o HorizontalPodAutoscalerStatusPtrOutput) Conditions() HorizontalPodAutoscalerConditionArrayOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerStatus) []HorizontalPodAutoscalerCondition {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Conditions\n\t}).(HorizontalPodAutoscalerConditionArrayOutput)\n}", "func (o HorizontalPodAutoscalerStatusPtrOutput) Conditions() HorizontalPodAutoscalerConditionArrayOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerStatus) []HorizontalPodAutoscalerCondition {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Conditions\n\t}).(HorizontalPodAutoscalerConditionArrayOutput)\n}", "func (subnet *VirtualNetworksSubnet) GetConditions() conditions.Conditions {\n\treturn subnet.Status.Conditions\n}", "func (o ValidatingAdmissionPolicyStatusPatchPtrOutput) Conditions() metav1.ConditionPatchArrayOutput {\n\treturn o.ApplyT(func(v *ValidatingAdmissionPolicyStatusPatch) []metav1.ConditionPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Conditions\n\t}).(metav1.ConditionPatchArrayOutput)\n}", "func (setting *MongodbDatabaseCollectionThroughputSetting) GetConditions() conditions.Conditions {\n\treturn setting.Status.Conditions\n}", "func (o AccessLevelsAccessLevelBasicOutput) Conditions() AccessLevelsAccessLevelBasicConditionArrayOutput {\n\treturn o.ApplyT(func(v AccessLevelsAccessLevelBasic) []AccessLevelsAccessLevelBasicCondition { return v.Conditions }).(AccessLevelsAccessLevelBasicConditionArrayOutput)\n}", "func (o ValidatingAdmissionPolicyStatusPtrOutput) Conditions() metav1.ConditionArrayOutput {\n\treturn o.ApplyT(func(v *ValidatingAdmissionPolicyStatus) []metav1.Condition {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Conditions\n\t}).(metav1.ConditionArrayOutput)\n}", "func (subscription *NamespacesTopicsSubscription) GetConditions() conditions.Conditions {\n\treturn subscription.Status.Conditions\n}", "func (s *Split) Conditions() []*Condition {\n\treturn s.conditions\n}", "func MergeStatusConditions(obj *unstructured.Unstructured, newCondition map[string]string) ([]interface{}, error) {\n\treturn MergeNestedSlice(obj, newCondition, \"status\", \"conditions\")\n}", "func (o StorageNodeStatusOutput) Conditions() StorageNodeStatusConditionsArrayOutput {\n\treturn o.ApplyT(func(v StorageNodeStatus) []StorageNodeStatusConditions { return v.Conditions }).(StorageNodeStatusConditionsArrayOutput)\n}", "func (o GoogleCloudRetailV2alphaProductResponseOutput) Conditions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaProductResponse) []string { return v.Conditions }).(pulumi.StringArrayOutput)\n}", "func (o LookupWorkstationClusterResultOutput) Conditions() StatusResponseArrayOutput {\n\treturn o.ApplyT(func(v LookupWorkstationClusterResult) []StatusResponse { return v.Conditions }).(StatusResponseArrayOutput)\n}", "func (p *DefaultPolicy) GetConditions() Conditions {\n\treturn p.Conditions\n}", "func (o AccessLevelBasicPtrOutput) Conditions() AccessLevelBasicConditionArrayOutput {\n\treturn o.ApplyT(func(v *AccessLevelBasic) []AccessLevelBasicCondition {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Conditions\n\t}).(AccessLevelBasicConditionArrayOutput)\n}", "func (o StorageClusterStatusPtrOutput) Conditions() StorageClusterStatusConditionsArrayOutput {\n\treturn o.ApplyT(func(v *StorageClusterStatus) []StorageClusterStatusConditions {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Conditions\n\t}).(StorageClusterStatusConditionsArrayOutput)\n}", "func (o MachineInstanceStatusPtrOutput) Conditions() MachineInstanceStatusConditionsArrayOutput {\n\treturn o.ApplyT(func(v *MachineInstanceStatus) []MachineInstanceStatusConditions {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Conditions\n\t}).(MachineInstanceStatusConditionsArrayOutput)\n}", "func (o ListenerRuleOutput) Conditions() ListenerRuleConditionArrayOutput {\n\treturn o.ApplyT(func(v *ListenerRule) ListenerRuleConditionArrayOutput { return v.Conditions }).(ListenerRuleConditionArrayOutput)\n}", "func (o AccessLevelsAccessLevelBasicPtrOutput) Conditions() AccessLevelsAccessLevelBasicConditionArrayOutput {\n\treturn o.ApplyT(func(v *AccessLevelsAccessLevelBasic) []AccessLevelsAccessLevelBasicCondition {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Conditions\n\t}).(AccessLevelsAccessLevelBasicConditionArrayOutput)\n}", "func (w *Wug) GetRawConditions(query *Query) ([]byte, error) {\n\treturn w.Get(Cond, query)\n}", "func (o KubernetesClusterStatusPtrOutput) Conditions() KubernetesClusterStatusConditionsArrayOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterStatus) []KubernetesClusterStatusConditions {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Conditions\n\t}).(KubernetesClusterStatusConditionsArrayOutput)\n}", "func (cbo *CBO) defaultStatusConditions() []osconfigv1.ClusterOperatorStatusCondition {\n // All conditions default to False with no message.\n return []osconfigv1.ClusterOperatorStatusCondition{\n newClusterOperatorStatusCondition(\n osconfigv1.OperatorProgressing,\n osconfigv1.ConditionFalse,\n \"\", \"\",\n ),\n newClusterOperatorStatusCondition(\n osconfigv1.OperatorDegraded,\n osconfigv1.ConditionFalse,\n \"\", \"\",\n ),\n newClusterOperatorStatusCondition(\n osconfigv1.OperatorAvailable,\n osconfigv1.ConditionFalse,\n \"\", \"\",\n ),\n }\n}", "func (r *ManagementConditionStatementManagementConditionsCollectionRequest) Get(ctx context.Context) ([]ManagementCondition, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil)\n}", "func (c *TradeClient) GetConditionOrders(param *model.GetConditionOrdersParam, page, limit int) (*model.ConditionOrderList, error) {\n\tif page < 1 {\n\t\treturn nil, errors.New(\"page must >=1\")\n\t}\n\tif limit <= 0 {\n\t\treturn nil, errors.New(\"limit must >0\")\n\t}\n\n\tqueries := map[string]string{\n\t\t\"page\": strconv.Itoa(page),\n\t\t\"limit\": strconv.Itoa(limit),\n\t}\n\treq := &coremodel.ApiRequestModel{\n\t\tParam: param,\n\t}\n\tbody, err := json.Marshal(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres := model.NewGetConditionOrdersResponse()\n\terr = c.requester.Post(\"/api/v1/condition_order_info\", body, queries, true, res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res.Data, nil\n}", "func (e Endpoint) Conditions() string {\n\tvar conds []string\n\tfor _, c := range e.Constraints {\n\t\tconds = append(conds, \"(\"+c.Condition()+\")\")\n\t}\n\treturn strings.Join(conds, \" && \")\n}", "func (peering *VirtualNetworksVirtualNetworkPeering) GetConditions() conditions.Conditions {\n\treturn peering.Status.Conditions\n}", "func (o RuleResponseOutput) Conditions() ConditionResponseArrayOutput {\n\treturn o.ApplyT(func(v RuleResponse) []ConditionResponse { return v.Conditions }).(ConditionResponseArrayOutput)\n}", "func (o DiagnosticsResponseOutput) Conditions() DiagnosticConditionResponseArrayOutput {\n\treturn o.ApplyT(func(v DiagnosticsResponse) []DiagnosticConditionResponse { return v.Conditions }).(DiagnosticConditionResponseArrayOutput)\n}", "func MergeAndSetStatusConditions(obj *unstructured.Unstructured, newCondition map[string]string) ([]interface{}, error) {\n\treturn MergeAndSetNestedSlice(obj, newCondition, \"status\", \"conditions\")\n}", "func (o RuleOutput) Conditions() ConditionArrayOutput {\n\treturn o.ApplyT(func(v Rule) []Condition { return v.Conditions }).(ConditionArrayOutput)\n}" ]
[ "0.80807686", "0.7924006", "0.78700143", "0.7841353", "0.7607114", "0.7516203", "0.7490639", "0.7490639", "0.74454457", "0.73661876", "0.7353652", "0.7206037", "0.7205307", "0.7184931", "0.71787745", "0.7159376", "0.7145872", "0.71345544", "0.71258813", "0.7114645", "0.7104962", "0.70892996", "0.7080941", "0.70602286", "0.70342803", "0.7030715", "0.7003279", "0.69817334", "0.69817334", "0.6970151", "0.6929313", "0.6924792", "0.6907124", "0.6884386", "0.6883322", "0.68803275", "0.68456733", "0.6845605", "0.6838157", "0.6838157", "0.6834308", "0.6816441", "0.679429", "0.6792692", "0.67821574", "0.67786115", "0.6773416", "0.67647886", "0.6751927", "0.6751927", "0.67461944", "0.67461944", "0.67239743", "0.67214376", "0.6716455", "0.67060155", "0.67042565", "0.6697248", "0.6696223", "0.66831386", "0.66695046", "0.66292423", "0.66187626", "0.6587181", "0.6566397", "0.6552149", "0.652362", "0.65080047", "0.6478803", "0.6478803", "0.64772177", "0.64772177", "0.64659065", "0.64191663", "0.6415491", "0.63733995", "0.6369018", "0.6346557", "0.63384575", "0.63270795", "0.6321359", "0.63171124", "0.631162", "0.62799037", "0.6277121", "0.6266395", "0.6245548", "0.62352794", "0.6215136", "0.6211754", "0.6201358", "0.61906254", "0.616545", "0.6144516", "0.60700756", "0.60660034", "0.6062366", "0.6062247", "0.6005374", "0.5983023" ]
0.7768028
4
GetSecret returns the value of the NovaScheduler.Spec.Secret
func (n NovaScheduler) GetSecret() string { return n.Spec.Secret }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *AssetReportRefreshRequest) GetSecret() string {\n\tif o == nil || o.Secret == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Secret\n}", "func GetSecret(tid string) ([]byte, error) {\n\tvar token string\n\n\tif err := db.QueryRow(\"SELECT token FROM event_tasks WHERE id = $1\", tid).\n\t\tScan(&token); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn []byte(token), nil\n}", "func (p *provider) GetSecret(ctx context.Context, name string) string {\n\tsecretPath := filepath.Join(\"projects\", p.projectID, \"secrets\", name, \"versions\", \"latest\")\n\treq := &secretmanagerpb.AccessSecretVersionRequest{\n\t\tName: secretPath,\n\t}\n\n\tres, err := p.client.AccessSecretVersion(ctx, req)\n\tif err != nil {\n\t\tlog.Fatalf(\"AccessSecretVersion error: %+v\", err)\n\t}\n\n\treturn string(res.Payload.Data)\n}", "func (o *ProcessorSignalDecisionReportRequest) GetSecret() string {\n\tif o == nil || o.Secret == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Secret\n}", "func (k *Instance) GetSecret(sel *core_api.SecretKeySelector, namespace string) ([]byte, error) {\n\tif sel == nil {\n\t\treturn nil, nil\n\t}\n\tsec, err := k.k8sOps.GetSecret(sel.Name, namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sec.Data[sel.Key], nil\n}", "func GetSecret() (string, string, error) {\n\tsecretMap := make(map[string]map[string]string)\n\tsecretCfg := os.Getenv(\"SQLFLOW_WORKFLOW_SECRET\")\n\tif secretCfg == \"\" {\n\t\treturn \"\", \"\", nil\n\t}\n\tif e := json.Unmarshal([]byte(secretCfg), &secretMap); e != nil {\n\t\treturn \"\", \"\", e\n\t}\n\tif len(secretMap) != 1 {\n\t\treturn \"\", \"\", fmt.Errorf(`SQLFLOW_WORKFLOW_SECRET should be a json string, e.g. {name: {key: value, ...}}`)\n\t}\n\tname := reflect.ValueOf(secretMap).MapKeys()[0].String()\n\tvalue, e := json.Marshal(secretMap[name])\n\tif e != nil {\n\t\treturn \"\", \"\", e\n\t}\n\treturn name, string(value), nil\n}", "func (s *SsmSecret) GetSecret() (string, error) {\n\tif s.isSecretValid() {\n\t\treturn s.value, nil\n\t}\n\tlog.Println(\"Refreshing secret...\")\n\tif err := s.refreshSecret(); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn s.value, nil\n}", "func (c *Context) GetSecret(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tif c.secrets == nil {\n\t\treturn starlark.None, fmt.Errorf(\"no secrets provided\")\n\t}\n\n\tvar key starlark.String\n\tif err := starlark.UnpackPositionalArgs(\"get_secret\", args, kwargs, 1, &key); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn util.Marshal(c.secrets[string(key)])\n}", "func GetSecret(c *gin.Context) {\n\tvar (\n\t\trepo = session.Repo(c)\n\t\tname = c.Param(\"secret\")\n\t)\n\tsecret, err := Config.Services.Secrets.SecretFind(repo, name)\n\tif err != nil {\n\t\tc.String(404, \"Error getting secret %q. %s\", name, err)\n\t\treturn\n\t}\n\tc.JSON(200, secret.Copy())\n}", "func (p *ProxyTypeMtproto) GetSecret() (value string) {\n\tif p == nil {\n\t\treturn\n\t}\n\treturn p.Secret\n}", "func (m *Manager) GetSecret() string {\n\treturn m.user.Secret\n}", "func (f *FileLocation) GetSecret() (value int64) {\n\treturn f.Secret\n}", "func (f *FileLocationUnavailable) GetSecret() (value int64) {\n\treturn f.Secret\n}", "func (o *PartnerCustomerCreateRequest) GetSecret() string {\n\tif o == nil || o.Secret == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Secret\n}", "func (c *Client) GetSecret() string {\n\treturn c.Secret\n}", "func (system *System) GetSecret() (string, error) {\n\tdb := GetGORMDbConnection()\n\tdefer Close(db)\n\n\tsecret := Secret{}\n\n\terr := db.Where(\"system_id = ?\", system.ID).First(&secret).Error\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to get hashed secret for clientID %s: %s\", system.ClientID, err.Error())\n\t}\n\n\tif secret.Hash == \"\" {\n\t\treturn \"\", fmt.Errorf(\"stored hash of secret for clientID %s is blank\", system.ClientID)\n\t}\n\n\treturn secret.Hash, nil\n}", "func GetSecret(namespace string, secretName string, data string) *v1.Secret {\n\treturn &v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: secretName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{\"firstLabel\": \"temp\"},\n\t\t},\n\t\tData: map[string][]byte{\"test.url\": []byte(data)},\n\t}\n}", "func (d *KfDef) GetSecret(name string) (string, error) {\n\tfor _, s := range d.Spec.Secrets {\n\t\tif s.Name != name {\n\t\t\tcontinue\n\t\t}\n\t\tif s.SecretSource.LiteralSource != nil {\n\t\t\treturn s.SecretSource.LiteralSource.Value, nil\n\t\t}\n\t\tif s.SecretSource.HashedSource != nil {\n\t\t\treturn s.SecretSource.HashedSource.HashedValue, nil\n\t\t}\n\t\tif s.SecretSource.EnvSource != nil {\n\t\t\treturn os.Getenv(s.SecretSource.EnvSource.Name), nil\n\t\t}\n\n\t\treturn \"\", fmt.Errorf(\"No secret source provided for secret %v\", name)\n\t}\n\treturn \"\", NewSecretNotFound(name)\n}", "func getSecret() (string, error) {\n\tlog.Println(prefixLog, os.Args)\n\tif len(os.Args) == 1 || len(os.Args[1]) < 10 {\n\t\treturn \"\", errors.New(\"worker secret key invalid\")\n\t}\n\treturn os.Args[1], nil\n}", "func (s *SecretAPI) GetSecret(secretID, versionID, versionStage string) (*Secret, error) {\n\n\tif s.err != nil {\n\t\treturn nil, s.err\n\t}\n\n\tcs := C.CString(secretID)\n\tcv := C.CString(versionID)\n\tct := C.CString(versionStage)\n\n\tdefer func() {\n\t\ts.close()\n\t\tC.free(unsafe.Pointer(cs))\n\t\tC.free(unsafe.Pointer(cv))\n\t\tC.free(unsafe.Pointer(ct))\n\t}()\n\n\tres := C.gg_request_result{}\n\n\ts.APIRequest.initialize()\n\n\te := GreenGrassCode(C.gg_get_secret_value(s.request, cs, cv, ct, &res))\n\n\ts.response = s.handleRequestResponse(\n\t\t\"Failed to get secret\",\n\t\te, RequestStatus(res.request_status),\n\t)\n\n\tif s.err != nil {\n\t\treturn nil, s.err\n\t}\n\n\tLog(LogLevelInfo, \"Got Secret: %s\", s.response)\n\n\tvar secret Secret\n\tif err := json.Unmarshal([]byte(s.response), &secret); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &secret, nil\n\n}", "func GetSecret( blockchain string, key string)( *SecretResponse, error ){\r\n\t//KMS HOST\r\n\tvar kmsHost = os.Getenv(\"KMS_HOST\")\r\n\tres, err := http.Get( fmt.Sprintf(kmsHost+\"/secret?blockchain=%s&key=%s\",blockchain,key) )\r\n\tif err != nil {\r\n\t\treturn &SecretResponse{}, ErrKeyNotFound\r\n\t}\r\n\tdefer res.Body.Close()\r\n\tvar secretresp SecretResponse\r\n\tif err := json.NewDecoder(res.Body).Decode(&secretresp); err!=nil{\r\n\t\treturn &SecretResponse{}, ErrDecodeErr\r\n\t}\r\n\treturn &secretresp,nil\r\n}", "func (s Secret) Get() (*corev1.Secret, error) {\n\tsec := &corev1.Secret{}\n\terr := s.client.Get(context.TODO(), s.NamespacedName, sec)\n\treturn sec, err\n}", "func (factory *Factory) GetSecretName() string {\n\treturn factory.singleton.certificate.Name\n}", "func getSecret(name, namespace string, labels map[string]string) *corev1.Secret {\n\treturn &corev1.Secret{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: APIv1,\n\t\t\tKind: SecretKind,\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t}\n}", "func (s *provider) Get(name string) (string, error) {\n\ts.logger.Debug(\"Requesting secret\", common.LogSecretToken, name, common.LogSystemToken, logSystem)\n\tvalue, err := s.Secret.Get(name)\n\tif err != nil {\n\t\ts.logger.Error(\"Can't find requested secret\", err,\n\t\t\tcommon.LogSecretToken, name, common.LogSystemToken, logSystem)\n\t\treturn \"\", errors.Wrap(err, \"secret not found\")\n\t}\n\n\treturn value, nil\n}", "func (s *Secret) Get() (*corev1.Secret, error) {\n\tlog.Debug(\"Secret.Get()\")\n\tvar err error\n\ts.secrets, err = s.Interface.Get(s.Name, metav1.GetOptions{})\n\n\treturn s.secrets, err\n}", "func (c *Client) GetSecret(ctx context.Context, secretName string, projectId string, version string) (*pb.SecretPayload, error) {\n\tif version == \"\" {\n\t\tversion = \"latest\"\n\t}\n\t\n\tgetSecret := pb.AccessSecretVersionRequest{\n\t\tName: fmt.Sprintf(\"projects/%v/secrets/%v/versions/%v\", projectId, secretName, version),\n\t}\n\t\n\tresult, err := c.smc.AccessSecretVersion(ctx, &getSecret)\n\tif err != nil {\n\t\tlog.Printf(\"failed to get secret: %v\", err)\n\t\treturn nil, err\n\t}\n\t\n\treturn result.Payload, nil\n}", "func (s *Store) GetSecret(ctx context.Context, req secretstores.GetSecretRequest) (secretstores.GetSecretResponse, error) {\n\tres := secretstores.GetSecretResponse{Data: nil}\n\n\tif s.client == nil {\n\t\treturn res, fmt.Errorf(\"client is not initialized\")\n\t}\n\n\tif req.Name == \"\" {\n\t\treturn res, fmt.Errorf(\"missing secret name in request\")\n\t}\n\tsecretName := fmt.Sprintf(\"projects/%s/secrets/%s\", s.ProjectID, req.Name)\n\n\tversionID := \"latest\"\n\tif value, ok := req.Metadata[VersionID]; ok {\n\t\tversionID = value\n\t}\n\n\tsecret, err := s.getSecret(ctx, secretName, versionID)\n\tif err != nil {\n\t\treturn res, fmt.Errorf(\"failed to access secret version: %v\", err)\n\t}\n\n\treturn secretstores.GetSecretResponse{Data: map[string]string{req.Name: *secret}}, nil\n}", "func (ks *keystore) getSecret(input *secretsmanager.GetSecretValueInput) (string, error) {\n\tvar secret string\n\n\tresult, err := ks.manager.GetSecretValue(input)\n\n\tif err != nil {\n\t\treturn secret, err\n\t}\n\n\tif result.SecretString != nil {\n\t\tsecret = *result.SecretString\n\t} else {\n\t\tdecodedBinarySecretBytes := make([]byte, base64.StdEncoding.DecodedLen(len(result.SecretBinary)))\n\t\tlength, err := base64.StdEncoding.Decode(decodedBinarySecretBytes, result.SecretBinary)\n\t\tif err != nil {\n\t\t\treturn secret, err\n\t\t}\n\t\tsecret = string(decodedBinarySecretBytes[:length])\n\t}\n\n\treturn secret, nil\n}", "func (postgres *PostgreSQLReconciler) GetSecret(secretName string) (map[string][]byte, error) {\n\tsecret := &corev1.Secret{}\n\terr := postgres.Client.Get(types.NamespacedName{Name: secretName, Namespace: postgres.HarborCluster.Namespace}, secret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := secret.Data\n\treturn data, nil\n}", "func GetSecret(apiURL, ak, potp, secretKey string) (string, string, error) {\n\ttk, err := authenticate(apiURL, ak, potp)\n\tif err != nil {\n\t\tStatus = StatusKO\n\t\treturn \"\", \"\", err\n\t}\n\n\tns, err := getAppNamespace(apiURL, tk)\n\tif err != nil {\n\t\tStatus = StatusKO\n\t\treturn \"\", \"\", err\n\t}\n\n\tsecrets, err := getSecrets(apiURL, tk, ns)\n\tif err != nil {\n\t\tStatus = StatusKO\n\t\treturn \"\", \"\", err\n\t}\n\tif s := secrets[secretKey]; s != \"\" {\n\t\tStatus = StatusOK\n\t\treturn secretKey, s, nil\n\t}\n\tlog.Warning(\"vault.GetSecret> Unable to find %s\\n\", secretKey)\n\tStatus = StatusKO\n\treturn \"\", \"\", err\n}", "func getSecret(secretName string) (*api.Secret, error) {\n\t// Get the namespace this is running in from the env variable.\n\tnamespace := os.Getenv(\"POD_NAMESPACE\")\n\tif namespace == \"\" {\n\t\treturn nil, fmt.Errorf(\"unexpected: POD_NAMESPACE env var returned empty string\")\n\t}\n\t// Get a client to talk to the k8s apiserver, to fetch secrets from it.\n\tcc, err := restclient.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error in creating in-cluster config: %s\", err)\n\t}\n\tclient, err := clientset.NewForConfig(cc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error in creating in-cluster client: %s\", err)\n\t}\n\tvar secret *api.Secret\n\terr = wait.PollImmediate(1*time.Second, getSecretTimeout, func() (bool, error) {\n\t\tsecret, err = client.Core().Secrets(namespace).Get(secretName, metav1.GetOptions{})\n\t\tif err == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\tglog.Warningf(\"error in fetching secret: %s\", err)\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"timed out waiting for secret: %s\", err)\n\t}\n\tif secret == nil {\n\t\treturn nil, fmt.Errorf(\"unexpected: received null secret %s\", secretName)\n\t}\n\treturn secret, nil\n}", "func (h *KubernetesHelper) GetSecret(ctx context.Context, namespace, name string) (*corev1.Secret, error) {\n\treturn h.clientset.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{})\n}", "func (m *Machine) GetSecret(namespace string, name string) (*corev1.Secret, error) {\n\tsecret, err := m.Clientset.CoreV1().Secrets(namespace).Get(context.Background(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"waiting for secret \"+name)\n\t}\n\n\treturn secret, nil\n}", "func (c client) GetSecret(objectKey k8sClient.ObjectKey) (corev1.Secret, error) {\n\ts := corev1.Secret{}\n\tif err := c.Get(context.TODO(), objectKey, &s); err != nil {\n\t\treturn corev1.Secret{}, err\n\t}\n\treturn s, nil\n}", "func (p *EnvironmentProvider) GetSecret(secretName string) (string, bool) {\n\tname := strings.ToUpper(strings.Replace(secretName, \"/\", \"_\", -1))\n\treturn p.lookup(name)\n}", "func getSecret() ([]byte, error) {\n\tif err := godotenv.Load(\".env\"); err != nil {\n\t\treturn nil, err\n\t}\n\treturn []byte(os.Getenv(\"SIGKEY\")), nil\n}", "func (o FunctionServiceConfigSecretVolumeOutput) Secret() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FunctionServiceConfigSecretVolume) string { return v.Secret }).(pulumi.StringOutput)\n}", "func (c *client) Get(sType, org, name, path string) (*library.Secret, error) {\n\t// create log fields from secret metadata\n\tfields := logrus.Fields{\n\t\t\"org\": org,\n\t\t\"repo\": name,\n\t\t\"secret\": path,\n\t\t\"type\": sType,\n\t}\n\n\t// check if secret is a shared secret\n\tif strings.EqualFold(sType, constants.SecretShared) {\n\t\t// update log fields from secret metadata\n\t\tfields = logrus.Fields{\n\t\t\t\"org\": org,\n\t\t\t\"team\": name,\n\t\t\t\"secret\": path,\n\t\t\t\"type\": sType,\n\t\t}\n\t}\n\n\tc.Logger.WithFields(fields).Tracef(\"getting native %s secret %s for %s/%s\", sType, path, org, name)\n\n\t// capture the secret from the native service\n\ts, err := c.Database.GetSecret(sType, org, name, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s, nil\n}", "func Get() (*Secret, error) {\n\tif sec != nil {\n\t\treturn sec, nil\n\t}\n\n\tfile, err := ioutil.ReadFile(\"files/secret.yaml\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = yaml.Unmarshal(file, &sec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sec, nil\n}", "func (c *clientWrapper) GetSecret(namespace, name string) (*corev1.Secret, bool, error) {\n\tif !c.isWatchedNamespace(namespace) {\n\t\treturn nil, false, fmt.Errorf(\"failed to get secret %s/%s: namespace is not within watched namespaces\", namespace, name)\n\t}\n\n\tsecret, err := c.factoriesSecret[c.lookupNamespace(namespace)].Core().V1().Secrets().Lister().Secrets(namespace).Get(name)\n\texist, err := translateNotFoundError(err)\n\n\treturn secret, exist, err\n}", "func (s *server) Get(ctx context.Context, req *pb.SecretRequest) (res *pb.SecretResponse, err error) {\n\tbts, err := ioutil.ReadFile(fmt.Sprintf(\"/run/secrets/%v\", req.GetName()))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%v secret does not exist\", req.GetName())\n\t}\n\n\tres = &pb.SecretResponse{\n\t\tExists: true,\n\t\tData: bts,\n\t}\n\n\treturn\n}", "func getSecret(kubeClient client.Client, secretName, namespace string) (*corev1.Secret, error) {\n\ts := &corev1.Secret{}\n\n\terr := kubeClient.Get(context.TODO(), kubetypes.NamespacedName{Name: secretName, Namespace: namespace}, s)\n\n\tif err != nil {\n\t\treturn &corev1.Secret{}, err\n\t}\n\treturn s, nil\n}", "func (o FunctionServiceConfigSecretEnvironmentVariableOutput) Secret() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FunctionServiceConfigSecretEnvironmentVariable) string { return v.Secret }).(pulumi.StringOutput)\n}", "func Secret(c *cli.Context) string {\n\tv := c.String(flagSecret)\n\tif v == \"\" {\n\t\treturn env.GetString(EnvBittrexSecret)\n\t}\n\n\treturn v\n}", "func GetSecret(session client.ConfigProvider, secretName string) (io.Reader, error) {\n\n\t// Create a Secrets Manager client\n\tsvc := secretsmanager.New(session)\n\tinput := &secretsmanager.GetSecretValueInput{\n\t\tSecretId: aws.String(secretName),\n\t\tVersionStage: aws.String(\"AWSCURRENT\"), // VersionStage defaults to AWSCURRENT if unspecified\n\t}\n\n\tresult, err := svc.GetSecretValue(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Decrypts secret using the associated KMS CMK.\n\t// Depending on whether the secret is a string or binary, one of these fields will be populated.\n\tvar secretString string\n\tif result.SecretString != nil {\n\t\tsecretString = *result.SecretString\n\t} else {\n\t\tdecodedBinarySecretBytes := make([]byte, base64.StdEncoding.DecodedLen(len(result.SecretBinary)))\n\t\tn, err := base64.StdEncoding.Decode(decodedBinarySecretBytes, result.SecretBinary)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsecretString = string(decodedBinarySecretBytes[:n])\n\t}\n\n\treturn strings.NewReader(secretString), nil\n}", "func (c *clusterApi) getSecret(w http.ResponseWriter, r *http.Request) {\n\tmethod := \"getSecret\"\n\tparams := r.URL.Query()\n\tsecretID := params[secrets.SecretKey]\n\n\tif len(secretID) == 0 || secretID[0] == \"\" {\n\t\tc.sendError(c.name, method, w, \"Missing secret ID\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tinst, err := clustermanager.Inst()\n\tif err != nil {\n\t\tc.sendError(c.name, method, w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsecretValue, err := inst.SecretGet(secretID[0])\n\tif err != nil {\n\t\tc.sendError(c.name, method, w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsecResp := &secrets.GetSecretResponse{\n\t\tSecretValue: secretValue,\n\t}\n\tjson.NewEncoder(w).Encode(secResp)\n}", "func (ckms *CKMS) GetSecret(secretName string) (map[string]string, error) {\n\toutput, err := ckms.sm.GetSecretValue(&secretsmanager.GetSecretValueInput{SecretId: &secretName})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tvar secretObj map[string]string\n\terr = json.Unmarshal([]byte(*output.SecretString), &secretObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn secretObj, nil\n}", "func (h *Handler) getSecret(secret *corev1.Secret) (*corev1.Secret, error) {\n\tnamespace := secret.GetNamespace()\n\tif len(namespace) == 0 {\n\t\tnamespace = h.namespace\n\t}\n\treturn h.clientset.CoreV1().Secrets(namespace).Get(h.ctx, secret.Name, h.Options.GetOptions)\n}", "func GetSecret(secretName string) (secret string, err error) {\n\tdefVal := os.Getenv(secretName)\n\tif Context == ContextAWS {\n\t\tif defVal, err = getAwsSsmSecret(secretName); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else if Context == ContextOpenfaas {\n\t\tif defVal, err = getOpenFaasSecret(secretName); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif defVal == \"\" {\n\t\treturn \"\", errors.New(\"missing secret \" + secretName)\n\t}\n\treturn defVal, nil\n}", "func (c *secrets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Secret, err error) {\n\tresult = &v1.Secret{}\n\terr = c.client.Get().\n\t\tResource(\"secrets\").\n\t\tName(name).\n\t\tVersionedParams(options).\n\t\tDo(ctx).\n\t\tInto(result)\n\n\treturn\n}", "func (k Kubernetes) GetSecret(secretName, namespace string, ctx context.Context) (*corev1.Secret, error) {\n\tsecret := &corev1.Secret{}\n\terr := k.Client.Get(ctx, types.NamespacedName{Namespace: namespace, Name: secretName}, secret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn secret, err\n}", "func (o *Gojwt) GetSecretByte()([]byte){\n return []byte(o.secretKeyWord)\n}", "func (s *SecretStore) GetSecret(organizationID uint, name string) (clustersecret.SecretResponse, error) {\n\tsec, err := s.secrets.GetByName(organizationID, name)\n\tif err != nil {\n\t\treturn clustersecret.SecretResponse{}, err\n\t}\n\n\tif sec == nil {\n\t\treturn clustersecret.SecretResponse{}, clustersecret.ErrSecretNotFound\n\t}\n\n\treturn clustersecret.SecretResponse{\n\t\tName: sec.Name,\n\t\tType: sec.Type,\n\t\tValues: sec.Values,\n\t\tTags: sec.Tags,\n\t}, nil\n}", "func (client *Client) GetSmartContractSecret(secretName string) (_ string, err error) {\n\tscID := os.Getenv(\"SMART_CONTRACT_ID\")\n\tvar path string\n\t// Allow users to specify their own paths\n\tif strings.Contains(secretName, \"/\") {\n\t\tpath = secretName\n\t} else {\n\t\tpath = fmt.Sprintf(\"/var/openfaas/secrets/sc-%s-%s\", scID, secretName)\n\t}\n\n\tfile, err := os.Open(path)\n\tdefer func() {\n\t\t_ = file.Close()\n\t}()\n\tif err == nil {\n\t\treturn parseSecret(file)\n\t}\n\treturn \"\", err\n}", "func (secrets Secrets) Get(secretPath string) (interface{}, *time.Time, bool, error) {\n\tparts := strings.Split(secretPath, \"/\")\n\tif len(parts) != 2 {\n\t\treturn nil, nil, false, fmt.Errorf(\"unable to split kubernetes secret path into [namespace]/[secret]: %s\", secretPath)\n\t}\n\n\tvar namespace = parts[0]\n\tvar secretName = parts[1]\n\n\tsecret, found, err := secrets.findSecret(namespace, secretName)\n\tif err != nil {\n\t\tsecrets.logger.Error(\"failed-to-fetch-secret\", err, lager.Data{\n\t\t\t\"namespace\": namespace,\n\t\t\t\"secret-name\": secretName,\n\t\t})\n\t\treturn nil, nil, false, err\n\t}\n\n\tif found {\n\t\treturn secrets.getValueFromSecret(secret)\n\t}\n\n\tsecrets.logger.Info(\"secret-not-found\", lager.Data{\n\t\t\"namespace\": namespace,\n\t\t\"secret-name\": secretName,\n\t})\n\n\treturn nil, nil, false, nil\n}", "func (s *SecretsManagerProvider) GetSecret(name string) (string, error) {\n\tkey := strings.Replace(name, secretsManagerPrefix, \"\", 1)\n\tres, err := s.Client.GetSecretValue(&secretsmanager.GetSecretValueInput{\n\t\tSecretId: aws.String(key),\n\t})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not retrieve a value from Secrets Manager for secret %s\", err)\n\t}\n\treturn aws.StringValue(res.SecretString), nil\n}", "func (c *VaultClient) GetSecret(path string) (*vault.Secret, error) {\n\treturn c.client.Logical().Read(path)\n}", "func (s *SecretGetterFromK8s) GetSecret(namespace string, name string) (*corev1.Secret, error) {\n\tvar res corev1.Secret\n\terr := s.Reader.Get(context.TODO(), client.ObjectKey{Namespace: namespace, Name: name}, &res)\n\treturn &res, err\n}", "func (k *Key) Secret() string {\n\treturn k.Query().Get(\"secret\")\n}", "func Secret(s *dag.Secret) *envoy_api_v2_auth.Secret {\n\treturn &envoy_api_v2_auth.Secret{\n\t\tName: Secretname(s),\n\t\tType: &envoy_api_v2_auth.Secret_TlsCertificate{\n\t\t\tTlsCertificate: &envoy_api_v2_auth.TlsCertificate{\n\t\t\t\tPrivateKey: &envoy_api_v2_core.DataSource{\n\t\t\t\t\tSpecifier: &envoy_api_v2_core.DataSource_InlineBytes{\n\t\t\t\t\t\tInlineBytes: s.PrivateKey(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCertificateChain: &envoy_api_v2_core.DataSource{\n\t\t\t\t\tSpecifier: &envoy_api_v2_core.DataSource_InlineBytes{\n\t\t\t\t\t\tInlineBytes: s.Cert(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (k *Key) Secret() string {\n\tq := k.url.Query()\n\n\treturn q.Get(\"secret\")\n}", "func GetExpectedSecret(t *testing.T, fileName string) *v1.Secret {\n\tobj := getKubernetesObject(t, fileName)\n\tsecret, ok := obj.(*v1.Secret)\n\tassert.True(t, ok, \"Expected Secret object\")\n\treturn secret\n}", "func (secretsManager *SecretsManagerV2) GetSecret(getSecretOptions *GetSecretOptions) (result SecretIntf, response *core.DetailedResponse, err error) {\n\treturn secretsManager.GetSecretWithContext(context.Background(), getSecretOptions)\n}", "func (o *Gojwt) GetSecretKey()(string){\n return o.secretKeyWord\n}", "func (o IopingSpecVolumeVolumeSourceOutput) Secret() IopingSpecVolumeVolumeSourceSecretPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceSecret { return v.Secret }).(IopingSpecVolumeVolumeSourceSecretPtrOutput)\n}", "func GetSecret(secrets corev1controllers.SecretCache, repoSpec *v1.RepoSpec, repoNamespace string) (*corev1.Secret, error) {\n\tif repoSpec.ClientSecret == nil {\n\t\treturn nil, nil\n\t}\n\tns := repoSpec.ClientSecret.Namespace\n\tif repoNamespace != \"\" {\n\t\tns = repoNamespace\n\t}\n\n\treturn secrets.Get(ns, repoSpec.ClientSecret.Name)\n}", "func (k *Key) Secret() string {\n\treturn k.base.Secret()\n}", "func (s *DBSecretsService) GetSecret(ctx context.Context, organizationID string, name string, opts entitystore.Options) (*v1.Secret, error) {\n\tspan, ctx := trace.Trace(ctx, \"\")\n\tdefer span.Finish()\n\n\tif opts.Filter == nil {\n\t\topts.Filter = entitystore.FilterEverything()\n\t}\n\topts.Filter.Add(entitystore.FilterStat{\n\t\tScope: entitystore.FilterScopeField,\n\t\tSubject: \"Name\",\n\t\tVerb: entitystore.FilterVerbEqual,\n\t\tObject: name,\n\t})\n\n\tsecrets, err := s.GetSecrets(ctx, organizationID, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if len(secrets) < 1 {\n\t\treturn nil, SecretNotFound{}\n\t}\n\n\treturn secrets[0], nil\n}", "func get_auth_secret(ps *persist.PersistService, auth_token string) string {\n\tt, found := ps.Get(auth_token);\n\tif found {\n\t\treturn t.Data[\"secret\"];\n\t}\n\telse {\n\t\treturn \"BAD_TOKEN\"; // TODO better handling\n\t}\n\tpanic(\"unreachable\");\n\t// for n := range tokens.Data() {\n\t// \tt := tokens.At(n);\n\t// \ttoken, _ := t.(AuthToken);\n\t// \tif token.Token == auth_token { return token.Secret };\n\t// }\n\t// return \"BAD_TOKEN\"; // TODO: better handling this is terrible\n}", "func Get(ctx context.Context, name, namespace string, c kubernetes.Interface) (*v1.Secret, error) {\n\tsecret, err := c.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn secret, fmt.Errorf(\"error getting kubernetes secret: %s\", err)\n\t}\n\treturn secret, nil\n}", "func (s Keygen) Secret() *party.Secret {\n\treturn &party.Secret{\n\t\tID: s.selfID,\n\t}\n}", "func (c *Config) GetServiceAccountSecret() string {\n\treturn c.ServiceAccountSecret\n}", "func readVaultSecret(key string, f *framework.Framework) (string, string) {\n\tloginCmd := fmt.Sprintf(\"vault login -address=%s sample_root_token_id > /dev/null\", vaultAddr)\n\treadSecret := fmt.Sprintf(\"vault kv get -address=%s %s%s\", vaultAddr, vaultSecretNs, key)\n\tcmd := fmt.Sprintf(\"%s && %s\", loginCmd, readSecret)\n\topt := metav1.ListOptions{\n\t\tLabelSelector: \"app=vault\",\n\t}\n\tstdOut, stdErr := execCommandInPodAndAllowFail(f, cmd, cephCSINamespace, &opt)\n\treturn strings.TrimSpace(stdOut), strings.TrimSpace(stdErr)\n}", "func (s *StaticSource) ReadSecret(context.Context) (*Secret, error) {\n\treturn s.Secret, nil\n}", "func (factory *Factory) GetBackupSecretName() string {\n\treturn \"backup-credentials\"\n}", "func (c *clientImpl) GetSecret(namespace, name string) (*v1.Secret, bool, error) {\n\tvar secret *v1.Secret\n\titem, exists, err := c.secStores[c.lookupNamespace(namespace)].GetByKey(namespace + \"/\" + name)\n\tif err == nil && item != nil {\n\t\tsecret = item.(*v1.Secret)\n\t}\n\n\treturn secret, exists, err\n}", "func (c *Context) GetSecret(secretKey string) *v1.Secret {\n\tsecretInterface, exist, err := c.Caches.Secret.GetByKey(secretKey)\n\n\tif err != nil {\n\t\tglog.V(1).Infof(\"unable to get secret from store, error occurred %s\", err.Error())\n\t\treturn nil\n\t}\n\n\tif !exist {\n\t\tglog.V(1).Infof(\"unable to get secret from store, no such service %s\", secretKey)\n\t\treturn nil\n\t}\n\n\tsecret := secretInterface.(*v1.Secret)\n\treturn secret\n}", "func (client GroupClient) GetSecret(accountName string, databaseName string, secretName string) (result USQLSecret, err error) {\n\treq, err := client.GetSecretPreparer(accountName, databaseName, secretName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"catalog.GroupClient\", \"GetSecret\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetSecretSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"catalog.GroupClient\", \"GetSecret\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetSecretResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"catalog.GroupClient\", \"GetSecret\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (sp *SecretProposal) Secret() []uint32 { return sp.secret }", "func (b Banai) GetSecret(secretID string) (SecretInfo, error) {\n\tv, ok := b.secrets[secretID]\n\tif !ok {\n\t\treturn nil, ErrSecretNotFound\n\t}\n\n\treturn v, nil\n}", "func getSecretPhrase() (secret string) {\n\tsecret = \"LORAXSNUGGLEGEORGEICE\"\n\treturn\n}", "func (kv *FakeKeyVaultClient) GetSecret(ctx context.Context, vaultBaseURL string, secretName string, secretVersion string) (result azkeyvault.SecretBundle, err error) {\n\tkv.rp.Calls = append(kv.rp.Calls, \"KeyVaultClient:GetSecret:\"+secretName)\n\tfor _, s := range kv.rp.Secrets {\n\t\tif *s.ID == secretName {\n\t\t\treturn s, nil\n\t\t}\n\t}\n\treturn azkeyvault.SecretBundle{}, fmt.Errorf(\"secret %s/%s not found\", vaultBaseURL, secretName)\n}", "func (c *Client) getValue(name string) (string, error) {\n\tinput := &secretsmanager.GetSecretValueInput{\n\t\tSecretId: aws.String(name),\n\t\tVersionStage: aws.String(\"AWSCURRENT\"), // VersionStage defaults to AWSCURRENT if unspecified.\n\t}\n\tresult, err := c.Client.GetSecretValue(context.TODO(), input)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"aws get getValue : %v\", err)\n\t}\n\n\treturn *result.SecretString, nil\n}", "func (i Item) GetSecret(s Session) (Secret, error) {\n\t// spec: GetSecret(IN ObjectPath session, OUT Secret secret);\n\tvar ret Secret\n\tcall := i.Call(_ItemGetSecret, 0, s.Path())\n\tif call.Err != nil {\n\t\treturn ret, call.Err\n\t}\n\tcall.Store(&ret)\n\treturn ret, nil\n}", "func GetSecret(client client.Client, parentNamespace string, secretRef *corev1.ObjectReference) (secret *corev1.Secret, err error) {\n\tsrLogger := log.WithValues(\"package\", \"utils\", \"method\", \"getSecret\")\n\tif secretRef != nil {\n\t\tsrLogger.Info(\"Retreive secret\", \"parentNamespace\", parentNamespace, \"secretRef\", secretRef)\n\t\tns := secretRef.Namespace\n\t\tif ns == \"\" {\n\t\t\tns = parentNamespace\n\t\t}\n\t\tsecret = &corev1.Secret{}\n\t\terr = client.Get(context.TODO(), types.NamespacedName{Namespace: ns, Name: secretRef.Name}, secret)\n\t\tif err != nil {\n\t\t\tsrLogger.Error(err, \"Failed to get secret \", \"Name:\", secretRef.Name, \" on namespace: \", secretRef.Namespace)\n\t\t\treturn nil, err\n\t\t}\n\t\tsrLogger.Info(\"Secret found \", \"Name:\", secretRef.Name, \" on namespace: \", secretRef.Namespace)\n\t} else {\n\t\tsrLogger.Info(\"No secret defined\", \"parentNamespace\", parentNamespace)\n\t}\n\treturn secret, err\n}", "func GetSecretName(dev *model.Dev) string {\n\treturn fmt.Sprintf(oktetoSecretTemplate, dev.Name)\n}", "func MustGetSecret(secretName string) (secret string) {\n\tvar err error\n\tdefVal := os.Getenv(secretName)\n\tif Context == ContextAWS {\n\t\tif defVal, err = getAwsSsmSecret(secretName); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t} else if Context == ContextOpenfaas {\n\t\tif defVal, err = getOpenFaasSecret(secretName); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tif defVal == \"\" {\n\t\tlog.Fatalf(\"missing secret %s\", secretName)\n\t}\n\treturn defVal\n}", "func (c *Cluster) GetSecret(nameOrIDPrefix string) (types.Secret, error) {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\tstate := c.currentNodeState()\n\tif !state.IsActiveManager() {\n\t\treturn types.Secret{}, c.errNoManager(state)\n\t}\n\n\tctx, cancel := c.getRequestContext()\n\tdefer cancel()\n\n\tsecret, err := getSecretByNameOrIDPrefix(ctx, &state, nameOrIDPrefix)\n\tif err != nil {\n\t\treturn types.Secret{}, err\n\t}\n\treturn convert.SecretFromGRPC(secret), nil\n}", "func (k Key) Secret() []byte {\n\treturn k.secret\n}", "func (in *K8SClient) GetSecret(namespace, name string) (*core_v1.Secret, error) {\n\tconfigMap, err := in.k8s.CoreV1().Secrets(namespace).Get(in.ctx, name, emptyGetOptions)\n\tif err != nil {\n\t\treturn &core_v1.Secret{}, err\n\t}\n\n\treturn configMap, nil\n}", "func (n *namespacedSecretStore) Get(selector *corev1api.SecretKeySelector) (string, error) {\n\tcreds, err := kube.GetSecretKey(n.client, n.namespace, selector)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to get key for secret\")\n\t}\n\n\treturn string(creds), nil\n}", "func (o GroupInitContainerVolumeOutput) Secret() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v GroupInitContainerVolume) map[string]string { return v.Secret }).(pulumi.StringMapOutput)\n}", "func (o *AssetReportRefreshRequest) GetSecretOk() (*string, bool) {\n\tif o == nil || o.Secret == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Secret, true\n}", "func (s Sign) Secret() *party.Secret {\n\treturn s.secret\n}", "func (c *configuration) Secret(clientSet ClientSet) *Secret {\n\tif clientSet != nil {\n\t\treturn NewSecret(clientSet)\n\t}\n\treturn nil\n\n}", "func (l *Libvirt) SecretGetValue(OptSecret Secret, Flags uint32) (rValue []byte, err error) {\n\tvar buf []byte\n\n\targs := SecretGetValueArgs {\n\t\tOptSecret: OptSecret,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(145, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Value: []byte\n\t_, err = dec.Decode(&rValue)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (o IopingSpecVolumeVolumeSourcePtrOutput) Secret() IopingSpecVolumeVolumeSourceSecretPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceSecret {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Secret\n\t}).(IopingSpecVolumeVolumeSourceSecretPtrOutput)\n}", "func (o FioSpecVolumeVolumeSourceOutput) Secret() FioSpecVolumeVolumeSourceSecretPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSource) *FioSpecVolumeVolumeSourceSecret { return v.Secret }).(FioSpecVolumeVolumeSourceSecretPtrOutput)\n}", "func (ui *GUI) GenerateSecret() []byte {\n\tsecret := make([]byte, 32)\n\trand.Read(secret)\n\treturn secret\n}" ]
[ "0.7372657", "0.72075814", "0.7123475", "0.71159655", "0.70768034", "0.70471925", "0.7036488", "0.69847095", "0.6893502", "0.68894595", "0.68886346", "0.68447804", "0.6838665", "0.68321365", "0.67905784", "0.6787732", "0.6769878", "0.67160785", "0.67097425", "0.6685262", "0.66833276", "0.666304", "0.66231537", "0.66135746", "0.658484", "0.6578012", "0.65742016", "0.6544218", "0.65011305", "0.6480628", "0.64660364", "0.6454195", "0.6451419", "0.64454526", "0.64429957", "0.64417905", "0.64392996", "0.6429728", "0.642603", "0.64123243", "0.63927174", "0.63866884", "0.6386621", "0.6369176", "0.63638735", "0.6362147", "0.6347427", "0.6347307", "0.6341405", "0.63239026", "0.6318251", "0.6315943", "0.63123167", "0.6297722", "0.62782335", "0.6277504", "0.6276745", "0.6268179", "0.62622935", "0.6250925", "0.6235149", "0.62152946", "0.6210418", "0.6199889", "0.6196769", "0.6194789", "0.6187043", "0.61758846", "0.61737674", "0.6169456", "0.6168324", "0.6162776", "0.61563677", "0.6150255", "0.61476594", "0.6138072", "0.613422", "0.6132955", "0.6131109", "0.61254257", "0.61080134", "0.6100245", "0.60822815", "0.60706604", "0.6069727", "0.6069133", "0.6055864", "0.6048004", "0.60460013", "0.6035593", "0.60321164", "0.6024681", "0.6007601", "0.60014665", "0.5998929", "0.5994809", "0.5989177", "0.59788823", "0.59676933", "0.59416974" ]
0.9030379
0
NewTravisBuildListCommand will add a `travis build list` command which is responsible for showing a list of build
func NewTravisBuildListCommand(client *travis.Client) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "List all the builds", RunE: func(cmd *cobra.Command, args []string) error { return ListBuilds(client, os.Stdout) }, } return cmd }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ListBuilds(client *travis.Client, w io.Writer) error {\n\tfilterBranch := \"master\"\n\n\topt := &travis.RepositoryListOptions{Member: viper.GetString(\"TRAVIS_CI_OWNER\"), Active: true}\n\trepos, _, err := client.Repositories.Find(opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttr := tabwriter.NewWriter(w, 0, 0, 1, ' ', tabwriter.FilterHTML)\n\tfmt.Fprintf(tr, \"%s\\t%s\\t%s\\t%s\\n\", \"\", \"Name\", \"Branch\", \"Finished\")\n\tfor _, repo := range repos {\n\t\t// Trying to remove the items that are not really running in Travis CI\n\t\t// Assume there is a better way to do this?\n\t\tif repo.LastBuildState == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, branchName := range strings.Split(filterBranch, \",\") {\n\t\t\tbranch, _, err := client.Branches.GetFromSlug(repo.Slug, branchName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfinish, err := time.Parse(time.RFC3339, branch.FinishedAt)\n\t\t\tfinishAt := finish.Format(ui.AppDateTimeFormat)\n\t\t\tif err != nil {\n\t\t\t\tfinishAt = branch.FinishedAt\n\t\t\t}\n\n\t\t\tresult := \"\"\n\t\t\tif branch.State == \"failed\" {\n\t\t\t\tresult = ui.AppFailure\n\t\t\t} else if branch.State == \"started\" {\n\t\t\t\tresult = ui.AppProgress\n\t\t\t} else {\n\t\t\t\tresult = ui.AppSuccess\n\t\t\t}\n\n\t\t\tfmt.Fprintf(tr, \"%s \\t%s\\t%s\\t%s\\n\", result, repo.Slug, branchName, finishAt)\n\t\t}\n\t}\n\n\ttr.Flush()\n\n\treturn nil\n}", "func NewListCommand() cli.Command {\n\treturn NewListCommandWithEnv(commoncli.DefaultEnv)\n}", "func (cli *bkCli) buildList(quietList bool) error {\n\n\tvar (\n\t\tbuilds []bk.Build\n\t\terr error\n\t)\n\n\tt := time.Now()\n\n\tprojects, err := cli.listProjects()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// did we locate a project\n\tproject := git.LocateProject(projects)\n\n\tif project != nil {\n\t\tfmt.Printf(\"Listing for project = %s\\n\\n\", *project.Name)\n\n\t\torg := extractOrg(*project.URL)\n\n\t\tbuilds, _, err = cli.client.Builds.ListByProject(org, *project.Slug, nil)\n\n\t} else {\n\t\tutils.Check(fmt.Errorf(\"Failed to locate the buildkite project using git.\")) // TODO tidy this up\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif quietList {\n\t\tfor _, build := range builds {\n\t\t\tfmt.Printf(\"%-36s\\n\", *build.ID)\n\t\t}\n\t\treturn nil // we are done\n\t}\n\n\ttb := table.New(buildColumns)\n\n\tfor _, build := range builds {\n\t\tvals := utils.ToMap(buildColumns, []interface{}{*build.Project.Name, *build.Number, *build.Branch, *build.Message, *build.State, *build.Commit})\n\t\ttb.AddRow(vals)\n\t}\n\n\ttb.Markdown = true\n\ttb.Print()\n\n\tfmt.Printf(\"\\nTime taken: %s\\n\", time.Now().Sub(t))\n\n\treturn nil\n}", "func buildList(c *cli.Context) error {\n\trepo := c.Args().First()\n\towner, name, err := parseRepo(repo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := newClient(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuilds, err := client.BuildList(owner, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmpl, err := template.New(\"_\").Parse(c.String(\"format\") + \"\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbranch := c.String(\"branch\")\n\tevent := c.String(\"event\")\n\tstatus := c.String(\"status\")\n\tlimit := c.Int(\"limit\")\n\n\tvar count int\n\tfor _, build := range builds {\n\t\tif count >= limit {\n\t\t\tbreak\n\t\t}\n\t\tif branch != \"\" && build.Branch != branch {\n\t\t\tcontinue\n\t\t}\n\t\tif event != \"\" && build.Event != event {\n\t\t\tcontinue\n\t\t}\n\t\tif status != \"\" && build.Status != status {\n\t\t\tcontinue\n\t\t}\n\t\ttmpl.Execute(os.Stdout, build)\n\t\tcount++\n\t}\n\treturn nil\n}", "func NewListCommand() cli.Command {\n\treturn newListCommand(defaultEnv, newClients)\n}", "func NewAdoBuildListCommand(client *azuredevops.Client) *cobra.Command {\n\tvar opts ListOptions\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List all the builds\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts.flags = args\n\t\t\treturn ListBuilds(client, opts, os.Stdout)\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.StringVar(&opts.Branches, \"branches\", \"master\", \"Which branches should be displayed\")\n\n\treturn cmd\n}", "func buildPipelineListCmd() *cobra.Command {\n\tvars := listPipelineVars{}\n\tcmd := &cobra.Command{\n\t\tUse: \"ls\",\n\t\tShort: \"Lists all the deployed pipelines in an application.\",\n\t\tExample: `\n Lists all the pipelines for the frontend application.\n /code $ copilot pipeline ls -a frontend`,\n\t\tRunE: runCmdE(func(cmd *cobra.Command, args []string) error {\n\t\t\topts, err := newListPipelinesOpts(vars)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := opts.Ask(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn opts.Execute()\n\t\t}),\n\t}\n\n\tcmd.Flags().StringVarP(&vars.appName, appFlag, appFlagShort, tryReadingAppName(), appFlagDescription)\n\tcmd.Flags().BoolVar(&vars.shouldOutputJSON, jsonFlag, false, jsonFlagDescription)\n\treturn cmd\n}", "func NewListCommand(parent common.Registerer, globals *config.Data) *ListCommand {\n\tvar c ListCommand\n\tc.Globals = globals\n\tc.manifest.File.SetOutput(c.Globals.Output)\n\tc.manifest.File.Read(manifest.Filename)\n\tc.CmdClause = parent.Command(\"list\", \"List Syslog endpoints on a Fastly service version\")\n\tc.CmdClause.Flag(\"service-id\", \"Service ID\").Short('s').StringVar(&c.manifest.Flag.ServiceID)\n\tc.CmdClause.Flag(\"version\", \"Number of service version\").Required().IntVar(&c.Input.ServiceVersion)\n\treturn &c\n}", "func NewListCommand(c Command, run RunListFunc, subCommands SubCommands, mod ...CommandModifier) *cobra.Command {\n\treturn newCommand(c, run, subCommands, mod...)\n}", "func NewListCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List the proxies\",\n\t\tRun: listCommandFunc,\n\t}\n\n\treturn cmd\n}", "func (b Build) List(c *gin.Context) {\n\tproject := c.DefaultQuery(\"project\", \"\")\n\tpublic := c.DefaultQuery(\"public\", \"\")\n\tbuilds := []models.Build{}\n\tvar err error\n\n\tif public == \"true\" {\n\t\tbuilds, err = b.publicBuilds()\n\t} else {\n\t\tbuilds, err = b.userBuilds(c, project)\n\t}\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\tsugar.InternalError(c, err)\n\t\treturn\n\t}\n\n\tsugar.SuccessResponse(c, 200, builds)\n}", "func List() *cobra.Command {\n\tvar yamlOutput bool\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List your active cloud native development environments\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn list(yamlOutput)\n\t\t},\n\t}\n\tcmd.Flags().BoolVarP(&yamlOutput, \"yaml\", \"y\", false, \"yaml output\")\n\treturn cmd\n}", "func (c OSClientBuildClient) List(namespace string, opts kapi.ListOptions) (*buildapi.BuildList, error) {\n\treturn c.Client.Builds(namespace).List(opts)\n}", "func NewListCmd(f *cmdutil.Factory) *cobra.Command {\n\tvar output string\n\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tAliases: []string{\"ls\"},\n\t\tShort: \"List available gitignores\",\n\t\tLong: cmdutil.LongDesc(`\n\t\t\tLists all gitignore templates available via the GitHub Gitignores API (https://docs.github.com/en/rest/reference/gitignore#get-all-gitignore-templates).`),\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclient := gitignore.NewClient(f.HTTPClient())\n\n\t\t\tgitignores, err := client.ListTemplates(context.Background())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tswitch output {\n\t\t\tcase \"name\":\n\t\t\t\tfor _, gitignore := range gitignores {\n\t\t\t\t\tfmt.Fprintln(f.IOStreams.Out, gitignore)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\ttw := cli.NewTableWriter(f.IOStreams.Out)\n\t\t\t\ttw.SetHeader(\"Name\")\n\n\t\t\t\tfor _, gitignore := range gitignores {\n\t\t\t\t\ttw.Append(gitignore)\n\t\t\t\t}\n\n\t\t\t\ttw.Render()\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcmdutil.AddOutputFlag(cmd, &output, \"table\", \"name\")\n\n\treturn cmd\n}", "func BuildList(builds ...buildapi.Build) buildapi.BuildList {\n\treturn buildapi.BuildList{\n\t\tItems: builds,\n\t}\n}", "func NewListCommand(activityRepo core.ActivityRepository) *cobra.Command {\n\tlistCmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Lists all activities\",\n\t\tLong: \"Lists all the current registered activities in the system\",\n\t\tArgs: cobra.NoArgs,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tExitIfAppNotConfigured()\n\t\t\tactivities, err := activityRepo.List()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\tfor _, act := range activities {\n\t\t\t\tfmt.Println(act.ToPrintableString())\n\t\t\t}\n\t\t},\n\t}\n\treturn listCmd\n}", "func NewListCommand(commonOpts *common.Options) (cmd *cobra.Command) {\n\tcmd = &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List all images of applications\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn fmt.Errorf(\"not support yet\")\n\t\t},\n\t}\n\treturn\n}", "func ListCommand(cli *cli.SensuCli) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"list extensions\",\n\t\tRunE: runList(cli.Config.Format(), cli.Client, cli.Config.Namespace(), cli.Config.Format()),\n\t}\n\n\thelpers.AddAllNamespace(cmd.Flags())\n\thelpers.AddFormatFlag(cmd.Flags())\n\thelpers.AddFieldSelectorFlag(cmd.Flags())\n\thelpers.AddLabelSelectorFlag(cmd.Flags())\n\thelpers.AddChunkSizeFlag(cmd.Flags())\n\n\treturn cmd\n}", "func BuildsList(quietList bool) error {\n\tcli, err := newBkCli()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cli.buildList(quietList)\n}", "func NewBuildCommand() Command {\n\treturn Command{\n\t\tname: \"build\",\n\t\tshortDesc: \"Build dependencies and push to chart museum\",\n\t\tlongDesc: \"Validate, build and push dependencies from stevedore manifest(s)\",\n\t}\n}", "func newCmdJobList(ctx api.Context) *cobra.Command {\n\tvar jsonOutput bool\n\tvar quietOutput bool\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Show all job definitions\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclient, err := metronomeClient(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tjobs, err := client.Jobs(\n\t\t\t\tmetronome.EmbedActiveRun(),\n\t\t\t\tmetronome.EmbedSchedule(),\n\t\t\t\tmetronome.EmbedHistorySummary(),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif quietOutput {\n\t\t\t\tfor _, job := range jobs {\n\t\t\t\t\tfmt.Fprintln(ctx.Out(), job.ID)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif jsonOutput {\n\t\t\t\tenc := json.NewEncoder(ctx.Out())\n\t\t\t\tenc.SetIndent(\"\", \" \")\n\t\t\t\treturn enc.Encode(jobs)\n\t\t\t}\n\n\t\t\ttable := cli.NewTable(ctx.Out(), []string{\"ID\", \"STATUS\", \"LAST RUN\"})\n\t\t\tfor _, job := range jobs {\n\t\t\t\ttable.Append([]string{job.ID, job.Status(), job.LastRunStatus()})\n\t\t\t}\n\t\t\ttable.Render()\n\n\t\t\treturn nil\n\t\t},\n\t}\n\tcmd.Flags().BoolVar(&jsonOutput, \"json\", false, \"Print in json format\")\n\tcmd.Flags().BoolVarP(&quietOutput, \"quiet\", \"q\", false, \"Print only IDs of listed jobs\")\n\treturn cmd\n}", "func NewListCommand(banzaiCli cli.Cli) *cobra.Command {\n\toptions := listOptions{}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List secrets\",\n\t\tArgs: cobra.NoArgs,\n\t\tAliases: []string{\"l\", \"ls\"},\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\toptions.format, _ = cmd.Flags().GetString(\"output\")\n\t\t\trunList(banzaiCli, options)\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\n\tflags.StringVarP(&options.secretType, \"type\", \"t\", \"\", \"Filter list to the given type\")\n\n\treturn cmd\n}", "func executeListCmd(t *gotesting.T, stdout io.Writer, args []string, wrapper *stubRunWrapper) subcommands.ExitStatus {\n\ttd := testutil.TempDir(t)\n\tdefer os.RemoveAll(td)\n\n\tcmd := newListCmd(stdout, td)\n\tcmd.wrapper = wrapper\n\tflags := flag.NewFlagSet(\"\", flag.ContinueOnError)\n\tcmd.SetFlags(flags)\n\tif err := flags.Parse(args); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tflags.Set(\"build\", \"false\") // DeriveDefaults fails if -build=true and bundle dirs are missing\n\treturn cmd.Execute(context.Background(), flags)\n}", "func NewListCommandWithEnv(env *commoncli.Env) cli.Command {\n\treturn util.AdaptCommand(env, &listCommand{env: env})\n}", "func ListBuilds(client *azuredevops.Client, opts ListOptions, w io.Writer) error {\n\tbuildDefOpts := azuredevops.BuildDefinitionsListOptions{Path: \"\\\\\" + viper.GetString(\"AZURE_DEVOPS_TEAM\")}\n\tdefinitions, err := client.BuildDefinitions.List(&buildDefOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresults := make(chan azuredevops.Build)\n\tvar wg sync.WaitGroup\n\twg.Add(len(definitions))\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(results)\n\t}()\n\n\tfor _, definition := range definitions {\n\t\tgo func(definition azuredevops.BuildDefinition) {\n\t\t\tdefer wg.Done()\n\n\t\t\tfor _, branchName := range strings.Split(opts.Branches, \",\") {\n\t\t\t\tbuilds, err := getBuildsForBranch(client, definition.ID, branchName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintf(w, \"unable to get builds for definition %s: %v\", definition.Name, err)\n\t\t\t\t}\n\t\t\t\tif len(builds) > 0 {\n\t\t\t\t\tresults <- builds[0]\n\t\t\t\t}\n\t\t\t}\n\t\t}(definition)\n\t}\n\n\tvar builds []azuredevops.Build\n\tfor result := range results {\n\t\tbuilds = append(builds, result)\n\t}\n\n\tsort.Slice(builds, func(i, j int) bool { return builds[i].Definition.Name < builds[j].Definition.Name })\n\n\t// renderAzureDevOpsBuilds(builds, len(builds), \".*\")\n\ttr := tabwriter.NewWriter(w, 0, 0, 1, ' ', tabwriter.FilterHTML)\n\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\t%s\\n\", \"\", \"Name\", \"Branch\", \"Build\", \"Finished\")\n\tfor index := 0; index < len(builds); index++ {\n\t\tbuild := builds[index]\n\t\tname := build.Definition.Name\n\t\tresult := build.Result\n\t\tstatus := build.Status\n\t\tbuildNo := build.BuildNumber\n\t\tbranch := build.Branch\n\n\t\t// Deal with date formatting for the finish time\n\t\tfinish, err := time.Parse(time.RFC3339, builds[index].FinishTime)\n\t\tfinishAt := finish.Format(ui.AppDateTimeFormat)\n\t\tif err != nil {\n\t\t\tfinishAt = builds[index].FinishTime\n\t\t}\n\n\t\t// Filter on branches\n\t\tmatched, _ := regexp.MatchString(\".*\"+opts.Branches+\".*\", branch)\n\t\tif matched == false {\n\t\t\tcontinue\n\t\t}\n\n\t\tif status == \"inProgress\" {\n\t\t\tresult = ui.AppProgress\n\t\t} else if status == \"notStarted\" {\n\t\t\tresult = ui.AppPending\n\t\t} else {\n\t\t\tif result == \"failed\" {\n\t\t\t\tresult = ui.AppFailure\n\t\t\t} else {\n\t\t\t\tresult = ui.AppSuccess\n\t\t\t}\n\t\t}\n\n\t\tfmt.Fprintf(tr, \"%s \\t%s\\t%s\\t%s\\t%s\\n\", result, name, branch, buildNo, finishAt)\n\t}\n\n\ttr.Flush()\n\n\treturn nil\n}", "func NewListCmd(f *cmdutil.Factory) *ListCmd {\n\tccmd := &ListCmd{\n\t\tfactory: f,\n\t}\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Get configuration collection\",\n\t\tLong: `Get a collection of configuration (managedObjects) based on filter parameters`,\n\t\tExample: heredoc.Doc(`\n$ c8y configuration list\nGet a list of configuration files\n `),\n\t\tPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nil\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\thandler := c8yquerycmd.NewInventoryQueryRunner(\n\t\t\t\tcmd,\n\t\t\t\targs,\n\t\t\t\tccmd.factory,\n\t\t\t\tflags.WithC8YQueryFixedString(\"(type eq 'c8y_ConfigurationDump')\"),\n\t\t\t\tflags.WithC8YQueryFormat(\"name\", \"(name eq '%s')\"),\n\t\t\t\tflags.WithC8YQueryFormat(\"deviceType\", \"(c8y_Filter.type eq '%s')\"),\n\t\t\t\tflags.WithC8YQueryFormat(\"description\", \"(description eq '%s')\"),\n\t\t\t)\n\t\t\treturn handler()\n\t\t},\n\t}\n\n\tcmd.SilenceUsage = true\n\n\tcmd.Flags().String(\"name\", \"\", \"Configuration name filter\")\n\tcmd.Flags().String(\"description\", \"\", \"Configuration description filter\")\n\tcmd.Flags().String(\"deviceType\", \"\", \"Configuration device type filter\")\n\n\tcompletion.WithOptions(\n\t\tcmd,\n\t)\n\n\tflags.WithOptions(\n\t\tcmd,\n\t\tflags.WithCommonCumulocityQueryOptions(),\n\t\tflags.WithExtendedPipelineSupport(\"query\", \"query\", false, \"c8y_DeviceQueryString\"),\n\t\tflags.WithCollectionProperty(\"managedObjects\"),\n\t)\n\n\t// Required flags\n\n\tccmd.SubCommand = subcommand.NewSubCommand(cmd)\n\n\treturn ccmd\n}", "func newManifestListCmd(manifestParams *manifestParameters) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List manifests from a repository\",\n\t\tLong: newManifestListCmdLongMessage,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tregistryName, err := manifestParams.GetRegistryName()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tloginURL := api.LoginURL(registryName)\n\t\t\t// An acrClient is created to make the http requests to the registry.\n\t\t\tacrClient, err := api.GetAcrCLIClientWithAuth(loginURL, manifestParams.username, manifestParams.password, manifestParams.configs)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tctx := context.Background()\n\t\t\terr = listManifests(ctx, acrClient, loginURL, manifestParams.repoName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn cmd\n}", "func NewCreateListCommand(list string) *CreateListCommand {\n\tcommand := new(CreateListCommand)\n\n\tcommand.definition = \"goboom <list>\"\n\tcommand.description = \"Creates the specified list.\"\n\tcommand.List = list\n\n\treturn command\n}", "func newVersionCommand() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Prints version information\",\n\t\tRunE: func(c *cobra.Command, args []string) error {\n\t\t\treturn versionTemplate.Execute(os.Stdout, build.GetInfo())\n\t\t},\n\t}\n}", "func NewListBoardsCommand(client trello.API) *cobra.Command {\n\tvar opts ListBoardOptions\n\n\tcmd := &cobra.Command{\n\t\tUse: \"boards\",\n\t\tShort: \"List all the boards\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts.refs = args\n\t\t\treturn DisplayBoards(client, opts, os.Stdout)\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.BoolVar(&opts.ShowClosed, \"show-closed\", false, \"Display closed boards?\")\n\n\treturn cmd\n}", "func NewCmdGetBuildLogs(commonOpts *opts.CommonOptions) *cobra.Command {\n\toptions := &GetBuildLogsOptions{\n\t\tGetOptions: GetOptions{\n\t\t\tCommonOptions: commonOpts,\n\t\t},\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"log [flags]\",\n\t\tShort: \"Display a build log\",\n\t\tLong: get_build_log_long,\n\t\tExample: get_build_log_example,\n\t\tAliases: []string{\"logs\"},\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\toptions.Cmd = cmd\n\t\t\toptions.Args = args\n\t\t\terr := options.Run()\n\t\t\thelper.CheckErr(err)\n\t\t},\n\t}\n\tcmd.Flags().BoolVarP(&options.Tail, \"tail\", \"t\", true, \"Tails the build log to the current terminal\")\n\tcmd.Flags().BoolVarP(&options.Wait, \"wait\", \"w\", false, \"Waits for the build to start before failing\")\n\tcmd.Flags().BoolVarP(&options.FailIfPodFails, \"fail-with-pod\", \"\", false, \"Return an error if the pod fails\")\n\tcmd.Flags().DurationVarP(&options.WaitForPipelineDuration, \"wait-duration\", \"d\", time.Minute*5, \"Timeout period waiting for the given pipeline to be created\")\n\tcmd.Flags().BoolVarP(&options.BuildFilter.Pending, \"pending\", \"p\", false, \"Only display logs which are currently pending to choose from if no build name is supplied\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Filter, \"filter\", \"f\", \"\", \"Filters all the available jobs by those that contain the given text\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Owner, \"owner\", \"o\", \"\", \"Filters the owner (person/organisation) of the repository\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Repository, \"repo\", \"r\", \"\", \"Filters the build repository\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Branch, \"branch\", \"\", \"\", \"Filters the branch\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Build, \"build\", \"\", \"\", \"The build number to view\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Pod, \"pod\", \"\", \"\", \"The pod name to view\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.GitURL, \"giturl\", \"g\", \"\", \"The git URL to filter on. If you specify a link to a github repository or PR we can filter the query of build pods accordingly\")\n\tcmd.Flags().StringVarP(&options.BuildFilter.Context, \"context\", \"\", \"\", \"Filters the context of the build\")\n\tcmd.Flags().BoolVarP(&options.CurrentFolder, \"current\", \"c\", false, \"Display logs using current folder as repo name, and parent folder as owner\")\n\toptions.AddBaseFlags(cmd)\n\n\treturn cmd\n}", "func NewTriggerListCommand(p *commands.KnParams) *cobra.Command {\n\ttriggerListFlags := flags.NewListPrintFlags(TriggerListHandlers)\n\n\ttriggerListCommand := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List triggers\",\n\t\tAliases: []string{\"ls\"},\n\t\tExample: `\n # List all triggers\n kn trigger list\n\n # List all triggers in JSON output format\n kn trigger list -o json`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tnamespace, err := p.GetNamespace(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tclient, err := p.NewEventingClient(namespace)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttriggerList, err := client.ListTriggers(cmd.Context())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !triggerListFlags.GenericPrintFlags.OutputFlagSpecified() && len(triggerList.Items) == 0 {\n\t\t\t\tfmt.Fprintf(cmd.OutOrStdout(), \"No triggers found.\\n\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// empty namespace indicates all-namespaces flag is specified\n\t\t\tif namespace == \"\" {\n\t\t\t\ttriggerListFlags.EnsureWithNamespace()\n\t\t\t}\n\n\t\t\terr = triggerListFlags.Print(triggerList, cmd.OutOrStdout())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tcommands.AddNamespaceFlags(triggerListCommand.Flags(), true)\n\ttriggerListFlags.AddFlags(triggerListCommand)\n\treturn triggerListCommand\n}", "func NewRevisionListCommand(p *commands.KnParams) *cobra.Command {\n\trevisionListFlags := flags.NewListPrintFlags(RevisionListHandlers)\n\n\trevisionListCommand := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List revisions\",\n\t\tAliases: []string{\"ls\"},\n\t\tLong: \"List revisions for a given service.\",\n\t\tExample: `\n # List all revisions\n kn revision list\n\n # List revisions for a service 'svc1' in namespace 'myapp'\n kn revision list -s svc1 -n myapp\n\n # List all revisions in JSON output format\n kn revision list -o json\n\n # List revision 'web'\n kn revision list web`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tnamespace, err := p.GetNamespace(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tclient, err := p.NewServingClient(namespace)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Create list filters\n\t\t\tvar params []clientservingv1.ListConfig\n\t\t\tparams, err = appendServiceFilter(params, client, cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tparams, err = appendRevisionNameFilter(params, args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Query for list with filters\n\t\t\trevisionList, err := client.ListRevisions(cmd.Context(), params...)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Stop if nothing found\n\t\t\tif !revisionListFlags.GenericPrintFlags.OutputFlagSpecified() && len(revisionList.Items) == 0 {\n\t\t\t\tfmt.Fprintf(cmd.OutOrStdout(), \"No revisions found.\\n\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// Add namespace column if no namespace is given (i.e. \"--all-namespaces\" option is given)\n\t\t\tif namespace == \"\" {\n\t\t\t\trevisionListFlags.EnsureWithNamespace()\n\t\t\t}\n\n\t\t\t// Only add temporary annotations if human readable output is requested\n\t\t\tif !revisionListFlags.GenericPrintFlags.OutputFlagSpecified() {\n\t\t\t\terr = enrichRevisionAnnotationsWithServiceData(cmd.Context(), p.NewServingClient, revisionList)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Sort revisions by namespace, service, generation (in this order)\n\t\t\tsortRevisions(revisionList)\n\n\t\t\t// Print out infos via printer framework\n\t\t\treturn revisionListFlags.Print(revisionList, cmd.OutOrStdout())\n\t\t},\n\t}\n\tcommands.AddNamespaceFlags(revisionListCommand.Flags(), true)\n\trevisionListFlags.AddFlags(revisionListCommand)\n\trevisionListCommand.Flags().StringVarP(&serviceNameFilter, \"service\", \"s\", \"\", \"Service name\")\n\n\treturn revisionListCommand\n}", "func ListCommand() cli.Command {\n\treturn cli.Command{\n\t\tName: \"list\",\n\t\tAliases: []string{\"l\"},\n\t\tUsage: \"List all invoices.\",\n\t\tDescription: \"Gets all records of database and lists them.\",\n\t\tAction: listAction,\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"format,f\",\n\t\t\t\tUsage: `list format; \n\tformats: (defualt is \"simple\")\n\t\t\t\"simple\" (or \"s\") \"brief\" (or \"b\"), \"pretty(or \"p\")\"`,\n\t\t\t},\n\t\t},\n\t}\n}", "func NewListCmd(f *cmdutil.Factory) *cobra.Command {\n\to := &ListOptions{\n\t\tIOStreams: f.IOStreams,\n\t\tRepository: f.Repository,\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tAliases: []string{\"ls\"},\n\t\tShort: \"List available skeletons\",\n\t\tLong: cmdutil.LongDesc(`\n\t\t\tLists all skeletons available in the configured repositories.`),\n\t\tExample: cmdutil.Examples(`\n\t\t\t# List skeletons only from the \"myrepo\" repository\n\t\t\tkickoff skeleton list --repository myrepo`),\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn o.Run()\n\t\t},\n\t}\n\n\tcmdutil.AddOutputFlag(cmd, &o.Output, \"table\", \"wide\", \"name\")\n\tcmdutil.AddRepositoryFlag(cmd, f, &o.RepoNames)\n\n\treturn cmd\n}", "func newListCmd(clientFn func() (*fic.ServiceClient, error), out io.Writer) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List ports\",\n\t\tExample: \"fic ports list\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclient, err := clientFn()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"creating FIC client: %w\", err)\n\t\t\t}\n\n\t\t\tpages, err := ports.List(client, nil).AllPages()\n\t\t\tif err != nil {\n\t\t\t\tvar e *json.UnmarshalTypeError\n\t\t\t\tif errors.As(err, &e) {\n\t\t\t\t\treturn fmt.Errorf(\"extracting ports from API response: %w\", err)\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"calling List ports API: %w\", err)\n\t\t\t}\n\n\t\t\tps, _ := ports.ExtractPorts(pages)\n\n\t\t\tt := utils.NewTabby(out)\n\t\t\tt.AddHeader(\"id\", \"name\", \"operationStatus\", \"isActivated\", \"vlanRanges\", \"tenantID\", \"switchName\",\n\t\t\t\t\"portType\", \"location\", \"area\")\n\t\t\tfor _, p := range ps {\n\t\t\t\tt.AddLine(p.ID, p.Name, p.OperationStatus, p.IsActivated, p.VLANRanges, p.TenantID, p.SwitchName,\n\t\t\t\t\tp.PortType, p.Location, p.Area)\n\t\t\t}\n\t\t\tt.Print()\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn cmd\n}", "func MachineListCommand(c *cli.Context, log logging.Logger, _ string) (int, error) {\n\topts := &machine.ListOptions{\n\t\tLog: log.New(\"machine:list\"),\n\t}\n\n\tinfos, err := machine.List(opts)\n\tif err != nil {\n\t\treturn 1, err\n\t}\n\n\ttabFormatter(os.Stdout, infos)\n\treturn 0, nil\n}", "func ProjectListFactory() (cli.Command, error) {\n\tcomm, err := newCommand(\"nerd project list\", \"List all your projects.\", \"\", nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create command\")\n\t}\n\tcmd := &ProjectList{\n\t\tcommand: comm,\n\t}\n\tcmd.runFunc = cmd.DoRun\n\n\treturn cmd, nil\n}", "func (w *Command) List() error {\n\tfmt.Println(\"Available bugs and their target versions:\")\n\treturn util.PrintList(w.NewGit, util.FixType, w.Short)\n}", "func (v *varnishClient) BuildCommand() (string, []string) {\n\targList := []string{\"-j\"}\n\targList = append(argList, \"-n\", v.cfg.CacheDir)\n\n\tcommand := varnishStat\n\tif v.cfg.ExecDir != \"\" {\n\t\tcommand = filepath.Join(v.cfg.ExecDir, command)\n\t}\n\treturn command, argList\n}", "func ListBuilds(db *sql.DB, builds chan<- BuildMetadata, componentID string) error {\n\tdefer close(builds)\n\n\tvar rows *sql.Rows\n\tvar err error\n\tif componentID != \"\" {\n\t\trows, err = db.Query(selectBuildsByComponentID, componentID)\n\t} else {\n\t\trows, err = db.Query(selectBuilds)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\n\tvar id, rowComponentID string\n\tvar createdAt int64\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&id, &rowComponentID, &createdAt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuilds <- BuildMetadata{\n\t\t\tID: id,\n\t\t\tComponentID: rowComponentID,\n\t\t\tCreatedAt: time.Unix(createdAt, 0),\n\t\t}\n\t}\n\n\treturn nil\n}", "func newVersion() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"show build version\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tfmt.Println(version)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn cmd\n}", "func (t Plan) BuildCommand() []string {\n\t// detailed exit code needed to better parse the plan\n\tcommand := []string{\"plan\", \"-detailed-exitcode\"}\n\n\tif t.CompactWarnings {\n\t\tcommand = append(command, \"-compact-warnings\")\n\t}\n\n\tif t.Destroy {\n\t\tcommand = append(command, \"-destroy\")\n\t}\n\n\tif !t.Input {\n\t\tcommand = append(command, \"-input=false\")\n\t}\n\n\tif t.LockTimeout.String() != \"0s\" {\n\t\tcommand = append(command, \"-lock-timeout=\"+t.LockTimeout.String())\n\t}\n\n\tif t.NoColor {\n\t\tcommand = append(command, \"-no-color\")\n\t}\n\n\tif t.Out != \"\" {\n\t\tcommand = append(command, \"-out=\"+t.Out)\n\t}\n\n\tif t.Parallelism != 10 {\n\t\tcommand = append(command, fmt.Sprintf(\"-parallelism=%d\", t.Parallelism))\n\t}\n\n\tif !t.Refresh {\n\t\tcommand = append(command, \"-refresh=false\")\n\t}\n\n\tif t.State != \"\" {\n\t\tcommand = append(command, \"-state=\"+t.State)\n\t}\n\n\tif !t.Targets.Empty() {\n\t\tfor _, v := range t.Targets.Options {\n\t\t\tcommand = append(command, \"-target=\"+v)\n\t\t}\n\t}\n\n\tif !t.Vars.Empty() {\n\t\tfor _, v := range t.Vars.Options {\n\t\t\tcommand = append(command, \"-var '\"+v+\"'\")\n\t\t}\n\t}\n\n\tif !t.VarFiles.Empty() {\n\t\tfor _, v := range t.VarFiles.Options {\n\t\t\tcommand = append(command, \"-var-file=\"+v)\n\t\t}\n\t}\n\n\treturn command\n}", "func listRun(cmd *cobra.Command, args []string) {\n\t\n\t// Items are read in using ReadItems; an example of stepwise refinement and procedural abstraction.\n\titems, err := todo.ReadItems(dataFile)\n\n\tvar data [][]string\n\n\t// Selection statement run to check if the To-Do list is empty\n\tif len(items) == 0 {\n\t\tlog.Println(\"No To-Do's in Your List - use the create command to get started!\")\n\t\treturn\n\t}\n\n\t// Selection statement run to check if there was an error from reading the data\n\tif err != nil {\n\t\tlog.Printf(\"%v\", err)\n\t} \n\n\t// Calls Sort method created in todo.go; an example of stepwise refinement\n\ttodo.Sort(items)\n\n\t// Iterative statement that appends all of the To-Dos in the list to a String array\n\t// Sequential statements are run within the FOR-EACH loop\n\tfor _, i := range items {\n\t\tvar temp []string\n\t\ttemp = append(temp, i.Label())\n\t\ttemp = append(temp, i.PrettyDone())\n\t\ttemp = append(temp, i.PrettyPrint())\n\t\ttemp = append(temp, i.Text)\n\t\tdata = append(data, temp)\n\t}\n\n\t\n\t/*\n\tSets the parameters for the To-Do list displayed as a table to the user. \n\tControls the appearence of the GUI.\n\t*/\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetHeader([]string {\"Position\", \"Done?\", \"Priority\", \"Task\"})\n\n\ttable.SetHeaderColor(tablewriter.Colors{tablewriter.Bold, tablewriter.BgHiBlueColor},\n\t\ttablewriter.Colors{tablewriter.FgWhiteColor, tablewriter.Bold, tablewriter.BgHiBlueColor},\n\t\ttablewriter.Colors{tablewriter.BgHiBlueColor, tablewriter.FgWhiteColor},\n\t\ttablewriter.Colors{tablewriter.BgHiBlueColor, tablewriter.FgWhiteColor})\n\n\ttable.SetColumnColor(tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiCyanColor},\n\t\ttablewriter.Colors{tablewriter.Bold, tablewriter.FgHiRedColor},\n\t\ttablewriter.Colors{tablewriter.Bold, tablewriter.FgHiMagentaColor},\n\t\ttablewriter.Colors{tablewriter.Bold, tablewriter.FgBlackColor})\n\n\tw := tabwriter.NewWriter(os.Stdout, 3, 0, 1, ' ', 0)\n\n\t// Iterative statement that appends all To-Do items marked done based on the condition of if either the --all or --done flag is active.\n\tfor p, i := range data {\n\t\tif allFlag || items[p].Done == doneFlag {\n\t\t\ttable.Append(i)\n\t\t}\n\t}\n\n\t// Renders the table\n\ttable.Render()\n\n\t// Flushes the writer\n\tw.Flush()\n\n}", "func newCmdClusterList(ctx api.Context) *cobra.Command {\n\tvar attachedOnly bool\n\tvar jsonOutput bool\n\tvar names bool\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List the clusters configured and the ones linked to the current cluster\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif names {\n\t\t\t\tclusters, err := ctx.Clusters()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tfor _, cluster := range clusters {\n\t\t\t\t\tfmt.Fprintln(ctx.Out(), cluster.Name())\n\t\t\t\t\tfmt.Fprintln(ctx.Out(), cluster.ID())\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tvar filters []lister.Filter\n\t\t\tif attachedOnly {\n\t\t\t\tfilters = append(filters, lister.AttachedOnly())\n\t\t\t} else {\n\t\t\t\tfilters = append(filters, lister.Linked())\n\t\t\t}\n\n\t\t\tconfigManager, err := ctx.ConfigManager()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\titems := lister.New(configManager, ctx.Logger()).List(filters...)\n\t\t\tif attachedOnly && len(items) == 0 {\n\t\t\t\treturn errors.New(\"no cluster is attached. Please run `dcos cluster attach <cluster-name>`\")\n\t\t\t}\n\n\t\t\tif jsonOutput {\n\t\t\t\tenc := json.NewEncoder(ctx.Out())\n\t\t\t\tenc.SetIndent(\"\", \" \")\n\t\t\t\treturn enc.Encode(items)\n\t\t\t}\n\n\t\t\ttable := cli.NewTable(ctx.Out(), []string{\"\", \"NAME\", \"ID\", \"STATUS\", \"VERSION\", \"URL\"})\n\t\t\tfor _, item := range items {\n\t\t\t\tvar attached string\n\t\t\t\tif item.Attached {\n\t\t\t\t\tattached = \"*\"\n\t\t\t\t}\n\t\t\t\ttable.Append([]string{attached, item.Name, item.ID, item.Status, item.Version, item.URL})\n\t\t\t}\n\t\t\ttable.Render()\n\n\t\t\treturn nil\n\t\t},\n\t}\n\tcmd.Flags().BoolVar(&attachedOnly, \"attached\", false, \"returns attached cluster only\")\n\tcmd.Flags().BoolVar(&jsonOutput, \"json\", false, \"returns clusters in json format\")\n\tcmd.Flags().BoolVar(&names, \"names\", false, \"print out a list of cluster names and IDs\")\n\tcmd.Flags().MarkHidden(\"names\")\n\treturn cmd\n}", "func NewBuild(\n\tui cli.Ui,\n\tgocmd gocmd.Command,\n\tworkspace deptfile.Workspacer,\n\ttoolcacher toolcacher.Cacher,\n) cli.Command {\n\treturn &buildCommand{\n\t\tf: newBuildFlagSet(),\n\t\tui: ui,\n\t\tgocmd: gocmd,\n\t\tworkspace: workspace,\n\t\ttoolcacher: toolcacher,\n\t}\n}", "func NewListCmd(f *cmdutil.Factory) *ListCmd {\n\tccmd := &ListCmd{\n\t\tfactory: f,\n\t}\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Get managed object collection\",\n\t\tLong: `Get a collection of managedObjects based on filter parameters`,\n\t\tExample: heredoc.Doc(`\n$ c8y inventory list\nGet a list of managed objects\n\n$ c8y inventory list --ids 1111,2222\nGet a list of managed objects by ids\n\n$ echo 'myType' | c8y inventory list\nSearch by type using pipeline. piped input will be mapped to type parameter\n\n$ c8y inventory get --id 1234 | c8y inventory list\nGet managed objects which have the same type as the managed object id=1234. piped input will be mapped to type parameter\n `),\n\t\tPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nil\n\t\t},\n\t\tRunE: ccmd.RunE,\n\t}\n\n\tcmd.SilenceUsage = true\n\n\tcmd.Flags().StringSlice(\"ids\", []string{\"\"}, \"List of ids.\")\n\tcmd.Flags().String(\"type\", \"\", \"ManagedObject type. (accepts pipeline)\")\n\tcmd.Flags().String(\"fragmentType\", \"\", \"ManagedObject fragment type.\")\n\tcmd.Flags().String(\"text\", \"\", \"managed objects containing a text value starting with the given text (placeholder {text}). Text value is any alphanumeric string starting with a latin letter (A-Z or a-z).\")\n\tcmd.Flags().Bool(\"withParents\", false, \"include a flat list of all parents and grandparents of the given object\")\n\tcmd.Flags().Bool(\"skipChildrenNames\", false, \"Don't include the child devices names in the response. This can improve the API response because the names don't need to be retrieved\")\n\n\tcompletion.WithOptions(\n\t\tcmd,\n\t)\n\n\tflags.WithOptions(\n\t\tcmd,\n\n\t\tflags.WithExtendedPipelineSupport(\"type\", \"type\", false, \"type\"),\n\t\tflags.WithCollectionProperty(\"managedObjects\"),\n\t)\n\n\t// Required flags\n\n\tccmd.SubCommand = subcommand.NewSubCommand(cmd)\n\n\treturn ccmd\n}", "func NewCommandList() *CommandList {\n\tlist := new(CommandList)\n\tlist.commands = []Command{}\n\treturn list\n}", "func BuildCommand(c *cli.Context) error {\n\n\tprod := getProduction(c)\n\n\tbuild, err := client.Build(prod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintMsg(messagedef.MsgBuildSuccess, prod, build.FeedAliasURL)\n\treturn nil\n}", "func newStatus() *cobra.Command {\n\tvar cluster []string\n\tvar timeout time.Duration\n\n\tcmd := &cobra.Command{\n\t\tUse: \"status\",\n\t\tShort: \"display cluster nodes.\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\t\tdefer cancel()\n\t\t\treturn clusterShow(ctx, &globalKeys, cluster...)\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.DurationVarP(&timeout, \"timeout\", \"t\", time.Second*60, \"time to wait for connection to complete\")\n\tflags.StringSliceVarP(&cluster, \"cluster\", \"c\", clusterList(), \"addresses of existing cluster nodes\")\n\n\treturn cmd\n}", "func buildCLICommands() []cli.Command {\n\treturn []cli.Command{\n\t\t{\n\t\t\tName: \"run\",\n\t\t\tUsage: \"runs your test suites\",\n\t\t\tAction: runAction,\n\t\t},\n\t\t{\n\t\t\tName: \"verify\",\n\t\t\tUsage: \"verify an api-check file\",\n\t\t\tAction: verifyAction,\n\t\t},\n\t\t{\n\t\t\tName: \"generate\",\n\t\t\tAliases: []string{\"gen\"},\n\t\t\tUsage: \"generate a skeleton api-check file\",\n\t\t\tAction: generateAction,\n\t\t},\n\t}\n}", "func NewCommandImageList() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tArgs: cobra.NoArgs,\n\t\tShort: \"Display Docker image on registry\",\n\t\tLong: `Display Docker image list on private registry`,\n\t\tRun: imgListMain,\n\t}\n\n\t//set local flag\n\tutils.AddImageFlag(cmd)\n\n\t//add subcommand\n\treturn cmd\n}", "func (client *BuildServiceClient) listBuildsCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, options *BuildServiceClientListBuildsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter serviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serviceName}\", url.PathEscape(serviceName))\n\tif buildServiceName == \"\" {\n\t\treturn nil, errors.New(\"parameter buildServiceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{buildServiceName}\", url.PathEscape(buildServiceName))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func NewBuildCommand(reportLocation string, containerized bool) *BuildCommand {\n\tcmd := &BuildCommand{\n\t\tCommand: Command{\n\t\t\treportLocation: reportLocation,\n\t\t\tVersion: OVBuildCommand, //build command 'results' version (report and artifacts)\n\t\t\tType: command.Build,\n\t\t\tState: command.StateUnknown,\n\t\t},\n\t}\n\n\tcmd.Command.init(containerized)\n\treturn cmd\n}", "func getBuildList(build model.Build, cs *cloudbuild.Service) model.Build {\n\n\tprojectId := build.ProjectID\n\trespBuildList, err := cs.Projects.Builds.List(projectId).Do()\n\tif err != nil {\n\t\tfmt.Printf(\"error: \" + err.Error())\n\t}\n\tfor i := 0; i < len(respBuildList.Builds); i++ {\n\t\t//fmt.Println(respBuildList.Builds[i].SourceProvenance.ResolvedRepoSource.CommitSha)\n\t\tif respBuildList.Builds[i].SourceProvenance.ResolvedRepoSource.CommitSha == build.CommitID {\n\t\t\tbuild.BuildID = respBuildList.Builds[i].Id\n\t\t\tbuild.BuildStatus = respBuildList.Builds[i].Status\n\t\t\tbuild.ImageID = respBuildList.Builds[i].Artifacts.Images[0]\n\t\t\treturn build\n\t\t}\n\t}\n\tfmt.Println(\"Build Details Not Found\")\n\tbuild.BuildID = \"0\"\n\treturn build\n}", "func ListCommand(c *cli.Context, log logging.Logger, _ string) int {\n\tif len(c.Args()) != 0 {\n\t\tcli.ShowCommandHelp(c, \"list\")\n\t\treturn 1\n\t}\n\n\tshowAll := c.Bool(\"all\")\n\n\tk, err := klient.CreateKlientWithDefaultOpts()\n\tif err != nil {\n\t\tlog.Error(\"Error creating klient client. err:%s\", err)\n\t\tfmt.Println(defaultHealthChecker.CheckAllFailureOrMessagef(GenericInternalError))\n\t\treturn 1\n\t}\n\n\tif err := k.Dial(); err != nil {\n\t\tlog.Error(\"Error dialing klient client. err:%s\", err)\n\t\tfmt.Println(defaultHealthChecker.CheckAllFailureOrMessagef(GenericInternalError))\n\t\treturn 1\n\t}\n\n\tinfos, err := getListOfMachines(k)\n\tif err != nil {\n\t\tlog.Error(\"Error listing machines. err:%s\", err)\n\t\tfmt.Println(getListErrRes(err, defaultHealthChecker))\n\t\treturn 1\n\t}\n\n\t// Sort our infos\n\tsort.Sort(infos)\n\n\t// Filter out infos for listing and json.\n\tfor i := 0; i < len(infos); i++ {\n\t\tinfo := &infos[i]\n\n\t\tonlineRecently := time.Since(info.OnlineAt) <= 24*time.Hour\n\t\thasMounts := len(info.Mounts) > 0\n\t\t// Do not show machines that have been offline for more than 24h,\n\t\t// but only if the machine doesn't have any mounts and we aren't using the --all\n\t\t// flag.\n\t\tif !hasMounts && !showAll && !onlineRecently {\n\t\t\t// Remove this element from the slice, because we're not showing it as\n\t\t\t// described above.\n\t\t\tinfos = append(infos[:i], infos[i+1:]...)\n\t\t\t// Decrement the index, since we're removing the item from the slice.\n\t\t\ti--\n\t\t\tcontinue\n\t\t}\n\n\t\t// For a more clear UX, replace the team name of the default Koding team,\n\t\t// with Koding.com\n\t\tfor i, team := range info.Teams {\n\t\t\tif team == \"Koding\" {\n\t\t\t\tinfo.Teams[i] = \"koding.com\"\n\t\t\t}\n\t\t}\n\n\t\tswitch info.MachineStatus {\n\t\tcase machine.MachineOffline:\n\t\t\tinfo.MachineStatusName = \"offline\"\n\t\tcase machine.MachineOnline:\n\t\t\tinfo.MachineStatusName = \"online\"\n\t\tcase machine.MachineDisconnected:\n\t\t\tinfo.MachineStatusName = \"disconnected\"\n\t\tcase machine.MachineConnected:\n\t\t\tinfo.MachineStatusName = \"connected\"\n\t\tcase machine.MachineError:\n\t\t\tinfo.MachineStatusName = \"error\"\n\t\tcase machine.MachineRemounting:\n\t\t\tinfo.MachineStatusName = \"remounting\"\n\t\tdefault:\n\t\t\tinfo.MachineStatusName = \"unknown\"\n\t\t}\n\t}\n\n\tif c.Bool(\"json\") {\n\t\tjsonBytes, err := json.MarshalIndent(infos, \"\", \" \")\n\t\tif err != nil {\n\t\t\tlog.Error(\"Marshalling infos to json failed. err:%s\", err)\n\t\t\tfmt.Println(GenericInternalError)\n\t\t\treturn 1\n\t\t}\n\n\t\tfmt.Println(string(jsonBytes))\n\t\treturn 0\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)\n\tfmt.Fprintf(w, \"\\tTEAM\\tLABEL\\tIP\\tALIAS\\tSTATUS\\tMOUNTED PATHS\\n\")\n\tfor i, info := range infos {\n\t\t// Join multiple teams into a single identifier\n\t\tteam := strings.Join(info.Teams, \",\")\n\n\t\tvar formattedMount string\n\t\tif len(info.Mounts) > 0 {\n\t\t\tformattedMount += fmt.Sprintf(\n\t\t\t\t\"%s -> %s\",\n\t\t\t\tshortenPath(info.Mounts[0].LocalPath),\n\t\t\t\tshortenPath(info.Mounts[0].RemotePath),\n\t\t\t)\n\t\t}\n\n\t\t// Currently we are displaying the status message over the formattedMount,\n\t\t// if it exists.\n\t\tif info.StatusMessage != \"\" {\n\t\t\tformattedMount = info.StatusMessage\n\t\t}\n\n\t\tfmt.Fprintf(w, \" %d.\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\",\n\t\t\ti+1, team, info.MachineLabel, info.IP, info.VMName, info.MachineStatusName,\n\t\t\tformattedMount,\n\t\t)\n\t}\n\tw.Flush()\n\n\treturn 0\n}", "func addNewBuilds(ctx context.Context, activationInfo specificActivationInfo, v *Version, p *Project,\n\ttasks TaskVariantPairs, syncAtEndOpts patch.SyncAtEndOptions, projectRef *ProjectRef, generatedBy string) ([]string, error) {\n\n\ttaskIdTables, err := getTaskIdTables(v, p, tasks, projectRef.Identifier)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to make task ID table\")\n\t}\n\n\tnewBuildIds := make([]string, 0)\n\tnewActivatedTaskIds := make([]string, 0)\n\tnewBuildStatuses := make([]VersionBuildStatus, 0)\n\n\texistingBuilds, err := build.Find(build.ByVersion(v.Id).WithFields(build.BuildVariantKey, build.IdKey))\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tvariantsProcessed := map[string]bool{}\n\tfor _, b := range existingBuilds {\n\t\tvariantsProcessed[b.BuildVariant] = true\n\t}\n\n\tcreateTime, err := getTaskCreateTime(p.Identifier, v)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"can't get create time for tasks\")\n\t}\n\tbatchTimeCatcher := grip.NewBasicCatcher()\n\tfor _, pair := range tasks.ExecTasks {\n\t\tif _, ok := variantsProcessed[pair.Variant]; ok { // skip variant that was already processed\n\t\t\tcontinue\n\t\t}\n\t\tvariantsProcessed[pair.Variant] = true\n\t\t// Extract the unique set of task names for the variant we're about to create\n\t\ttaskNames := tasks.ExecTasks.TaskNames(pair.Variant)\n\t\tdisplayNames := tasks.DisplayTasks.TaskNames(pair.Variant)\n\t\tactivateVariant := !activationInfo.variantHasSpecificActivation(pair.Variant)\n\t\tbuildArgs := BuildCreateArgs{\n\t\t\tProject: *p,\n\t\t\tVersion: *v,\n\t\t\tTaskIDs: taskIdTables,\n\t\t\tBuildName: pair.Variant,\n\t\t\tActivateBuild: activateVariant,\n\t\t\tTaskNames: taskNames,\n\t\t\tDisplayNames: displayNames,\n\t\t\tActivationInfo: activationInfo,\n\t\t\tGeneratedBy: generatedBy,\n\t\t\tTaskCreateTime: createTime,\n\t\t\tSyncAtEndOpts: syncAtEndOpts,\n\t\t\tProjectIdentifier: projectRef.Identifier,\n\t\t}\n\n\t\tgrip.Info(message.Fields{\n\t\t\t\"op\": \"creating build for version\",\n\t\t\t\"variant\": pair.Variant,\n\t\t\t\"activated\": activateVariant,\n\t\t\t\"version\": v.Id,\n\t\t})\n\t\tbuild, tasks, err := CreateBuildFromVersionNoInsert(buildArgs)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t\tif len(tasks) == 0 {\n\t\t\tgrip.Info(message.Fields{\n\t\t\t\t\"op\": \"skipping empty build for version\",\n\t\t\t\t\"variant\": pair.Variant,\n\t\t\t\t\"activated\": activateVariant,\n\t\t\t\t\"version\": v.Id,\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\n\t\tif err = build.Insert(); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"error inserting build %s\", build.Id)\n\t\t}\n\t\tif err = tasks.InsertUnordered(ctx); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"error inserting tasks for build %s\", build.Id)\n\t\t}\n\t\tnewBuildIds = append(newBuildIds, build.Id)\n\n\t\tbatchTimeTasksToIds := map[string]string{}\n\t\tfor _, t := range tasks {\n\t\t\tif t.Activated {\n\t\t\t\tnewActivatedTaskIds = append(newActivatedTaskIds, t.Id)\n\t\t\t}\n\t\t\tif activationInfo.taskHasSpecificActivation(t.BuildVariant, t.DisplayName) {\n\t\t\t\tbatchTimeTasksToIds[t.DisplayName] = t.Id\n\t\t\t}\n\t\t}\n\n\t\tvar activateVariantAt time.Time\n\t\tbatchTimeTaskStatuses := []BatchTimeTaskStatus{}\n\t\tif !activateVariant {\n\t\t\tactivateVariantAt, err = projectRef.GetActivationTimeForVariant(p.FindBuildVariant(pair.Variant))\n\t\t\tbatchTimeCatcher.Add(errors.Wrapf(err, \"unable to get activation time for variant '%s'\", pair.Variant))\n\t\t}\n\t\tfor taskName, id := range batchTimeTasksToIds {\n\t\t\tactivateTaskAt, err := projectRef.GetActivationTimeForTask(p.FindTaskForVariant(taskName, pair.Variant))\n\t\t\tbatchTimeCatcher.Add(errors.Wrapf(err, \"unable to get activation time for task '%s' (variant '%s')\", taskName, pair.Variant))\n\t\t\tbatchTimeTaskStatuses = append(batchTimeTaskStatuses, BatchTimeTaskStatus{\n\t\t\t\tTaskId: id,\n\t\t\t\tTaskName: taskName,\n\t\t\t\tActivationStatus: ActivationStatus{\n\t\t\t\t\tActivateAt: activateTaskAt,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tnewBuildStatuses = append(newBuildStatuses,\n\t\t\tVersionBuildStatus{\n\t\t\t\tBuildVariant: pair.Variant,\n\t\t\t\tBuildId: build.Id,\n\t\t\t\tBatchTimeTasks: batchTimeTaskStatuses,\n\t\t\t\tActivationStatus: ActivationStatus{\n\t\t\t\t\tActivated: activateVariant,\n\t\t\t\t\tActivateAt: activateVariantAt,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\n\tgrip.Error(message.WrapError(batchTimeCatcher.Resolve(), message.Fields{\n\t\t\"message\": \"unable to get all activation times\",\n\t\t\"runner\": \"addNewBuilds\",\n\t\t\"version\": v.Id,\n\t}))\n\n\treturn newActivatedTaskIds, errors.WithStack(VersionUpdateOne(\n\t\tbson.M{VersionIdKey: v.Id},\n\t\tbson.M{\n\t\t\t\"$push\": bson.M{\n\t\t\t\tVersionBuildIdsKey: bson.M{\"$each\": newBuildIds},\n\t\t\t\tVersionBuildVariantsKey: bson.M{\"$each\": newBuildStatuses},\n\t\t\t},\n\t\t},\n\t))\n}", "func registerCommandList(progname string) {\n\tlog.Printf(\"Entering repo::registerCommandList(%s)\", progname)\n\tdefer log.Println(\"Exiting repo::registerCommandList\")\n\n\tcmdOptions.listCmd = flag.NewFlagSet(progname+\" list\", flag.PanicOnError)\n\n\tcmdOptions.listCmd.StringVar(\n\t\t&cmdOptions.productVersion,\n\t\t\"product-version\",\n\t\t\"\",\n\t\t\"Version that a software should be compatibile with.\"+\n\t\t\t\" (I.e., product-version)\",\n\t)\n\tcmdOptions.listCmd.StringVar(\n\t\t&cmdOptions.softwareName,\n\t\t\"filename\",\n\t\t\"\",\n\t\t\"File name of the software.\",\n\t)\n\tcmdOptions.listCmd.StringVar(\n\t\t&cmdOptions.softwareRepo,\n\t\t\"repo\",\n\t\tSoftwareRepoPath,\n\t\t\"Path of the software repository.\",\n\t)\n\tcmdOptions.listCmd.StringVar(\n\t\t&cmdOptions.softwareType,\n\t\t\"type\",\n\t\t\"\",\n\t\t\"Type of the software.\",\n\t)\n\toutput.RegisterCommandOptions(cmdOptions.listCmd,\n\t\tmap[string]string{\"output-format\": \"yaml\"})\n}", "func MakeCommand(globalParamsGetter func() GlobalParams) *cobra.Command {\n\tcliParams := &cliParams{}\n\n\tworkloadListCommand := &cobra.Command{\n\t\tUse: \"workload-list\",\n\t\tShort: \"Print the workload content of a running agent\",\n\t\tLong: ``,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tglobalParams := globalParamsGetter()\n\n\t\t\tcliParams.GlobalParams = globalParams\n\n\t\t\treturn fxutil.OneShot(workloadList,\n\t\t\t\tfx.Supply(cliParams),\n\t\t\t\tfx.Supply(core.BundleParams{\n\t\t\t\t\tConfigParams: config.NewAgentParamsWithoutSecrets(\n\t\t\t\t\t\tglobalParams.ConfFilePath,\n\t\t\t\t\t\tconfig.WithConfigName(globalParams.ConfigName),\n\t\t\t\t\t),\n\t\t\t\t\tLogParams: log.LogForOneShot(globalParams.LoggerName, \"off\", true)}),\n\t\t\t\tcore.Bundle,\n\t\t\t)\n\t\t},\n\t}\n\n\tworkloadListCommand.Flags().BoolVarP(&cliParams.verboseList, \"verbose\", \"v\", false, \"print out a full dump of the workload store\")\n\n\treturn workloadListCommand\n}", "func New(b BuildInfo) *Command {\n\tfs := flag.NewFlagSet(\"changelog\", flag.ExitOnError)\n\n\treturn &Command{\n\t\tfs: fs,\n\t\tb: b,\n\t\tfile: fs.String(fileOptName, dfltChangelogFile, \"changelog file name\"),\n\t\tdebug: fs.Bool(debugOptName, false, \"log debug information\"),\n\t\ttoStdOut: fs.Bool(stdOutOptName, false, \"output changelog to stdout instead to file\"),\n\t\thistory: fs.Bool(historyOptName, false, \"create history of old versions tags (output is always stdout)\"),\n\t\tignore: fs.Bool(ignoreOptName, false, \"ignore parsing errors of invalid (not conventional) commit messages\"),\n\t\tsinceTag: fs.String(sinceTagOptName, \"\", fmt.Sprintf(\"in combination with -%s: if a tag is specified, the changelog will be created from that tag on\", historyOptName)),\n\t\tinitConfig: fs.Bool(initDfltConfigOptName, false, fmt.Sprintf(\"initialize a default changelog configuration '%s'\", config.FileName)),\n\t\tnoPrompt: fs.Bool(noPromptOptName, false, \"do not prompt for next version\"),\n\t\tversion: fs.Bool(versionOptName, false, \"show program version information\"),\n\t\tnum: fs.Int(numOptName, 0, fmt.Sprintf(\"in combination with -%s: the number of tags to go back\", historyOptName)),\n\t}\n}", "func (st *buildStatus) distTestList() (names []distTestName, remoteErr, err error) {\n\tworkDir, err := st.bc.WorkDir(st.ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"distTestList, WorkDir: %v\", err)\n\t\treturn\n\t}\n\tgoroot := st.conf.FilePathJoin(workDir, \"go\")\n\n\targs := []string{\"tool\", \"dist\", \"test\", \"--no-rebuild\", \"--list\"}\n\tif st.conf.IsRace() {\n\t\targs = append(args, \"--race\")\n\t}\n\tif st.conf.CompileOnly {\n\t\targs = append(args, \"--compile-only\")\n\t}\n\tvar buf bytes.Buffer\n\tremoteErr, err = st.bc.Exec(st.ctx, \"./go/bin/go\", buildlet.ExecOpts{\n\t\tOutput: &buf,\n\t\tExtraEnv: append(st.conf.Env(), \"GOROOT=\"+goroot),\n\t\tOnStartExec: func() { st.LogEventTime(\"discovering_tests\") },\n\t\tPath: []string{st.conf.FilePathJoin(\"$WORKDIR\", \"go\", \"bin\"), \"$PATH\"},\n\t\tArgs: args,\n\t})\n\tif remoteErr != nil {\n\t\tremoteErr = fmt.Errorf(\"Remote error: %v, %s\", remoteErr, buf.Bytes())\n\t\terr = nil\n\t\treturn\n\t}\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Exec error: %v, %s\", err, buf.Bytes())\n\t\treturn\n\t}\n\t// To avoid needing to update all the existing dist test adjust policies,\n\t// it's easier to remap new dist test names in \"<pkg>[:<variant>]\" format\n\t// to ones used in Go 1.20 and prior. Do that for now.\n\tfor _, test := range go120DistTestNames(strings.Fields(buf.String())) {\n\t\tisNormalTry := st.isTry() && !st.isSlowBot()\n\t\tif !st.conf.ShouldRunDistTest(test.Old, isNormalTry) {\n\t\t\tcontinue\n\t\t}\n\t\tnames = append(names, test)\n\t}\n\treturn names, nil, nil\n}", "func NewCmdControllerBuild(commonOpts *opts.CommonOptions) *cobra.Command {\n\toptions := &ControllerBuildOptions{\n\t\tControllerOptions: ControllerOptions{\n\t\t\tCommonOptions: commonOpts,\n\t\t},\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"build\",\n\t\tShort: \"Runs the build controller\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\toptions.Cmd = cmd\n\t\t\toptions.Args = args\n\t\t\terr := options.Run()\n\t\t\thelper.CheckErr(err)\n\t\t},\n\t\tAliases: []string{\"builds\"},\n\t}\n\n\tcmd.Flags().StringVarP(&options.Namespace, \"namespace\", \"n\", \"\", \"The namespace to watch or defaults to the current namespace\")\n\tcmd.Flags().BoolVarP(&options.InitGitCredentials, \"git-credentials\", \"\", false, \"If enable then lets run the 'jx step git credentials' step to initialise git credentials\")\n\tcmd.Flags().BoolVarP(&options.FailIfNoGitProvider, \"fail-on-git-provider-error\", \"\", false, \"If enable then lets terminate quickly if we cannot create a git provider\")\n\n\t// optional git reporting flags\n\tcmd.Flags().StringVarP(&options.TargetURLTemplate, \"target-url-template\", \"\", \"\", \"The Go template for generating the target URL of pipeline logs/views if git reporting is enabled. If unspecified, a default will be used based on `--job-url-base`.\")\n\tcmd.Flags().BoolVarP(&options.GitReporting, \"git-reporting\", \"\", false, \"If enabled then lets report pipeline success/failures to the git provider. Note this is purely tactical until we can do this natively inside tekton\")\n\tcmd.Flags().StringVarP(&options.JobURLBase, \"job-url-base\", \"\", \"\", \"The base URL, such as 'https://dashboard.jenkins-x.live', for generating the target URL for pipeline logs if git reporting is enabled.\")\n\treturn cmd\n}", "func listCommandFunc(cmd *cobra.Command, args []string) {\n\turl := fmt.Sprintf(\"http://%s%s\", Global.Endpoints, proxy.APIProxies)\n\tcli := &http.Client{}\n\trsp, err := cli.Get(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t} else {\n\t\tdefer rsp.Body.Close()\n\t\tdata, err := ioutil.ReadAll(rsp.Body)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t} else {\n\t\t\tfmt.Printf(\"%s\\n\", data)\n\t\t}\n\t}\n}", "func NewCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Returns a list of device profiles\",\n\t\tLong: `Returns the list of device profiles currently in the core-metadata database.`,\n\t\tRunE: listHandler,\n\t}\n\treturn cmd\n}", "func NewConfigPluginListCmd(opt *common.CommonOption) (cmd *cobra.Command) {\n\tconfigPluginListCmd := configPluginListCmd{\n\t\tCommonOption: opt,\n\t}\n\n\tcmd = &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"list all installed plugins\",\n\t\tLong: \"list all installed plugins\",\n\t\tRunE: configPluginListCmd.RunE,\n\t\tAnnotations: map[string]string{\n\t\t\tcommon.Since: common.VersionSince0028,\n\t\t},\n\t}\n\n\tconfigPluginListCmd.SetFlagWithHeaders(cmd, \"Use,Version,DownloadLink\")\n\treturn\n}", "func NewListCmd(f *cmdutil.Factory) *ListCmd {\n\tccmd := &ListCmd{\n\t\tfactory: f,\n\t}\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List smart group collection\",\n\t\tLong: `Get a collection of smart groups based on filter parameters`,\n\t\tExample: heredoc.Doc(`\n\t\t\t$ c8y smartgroups list\n\t\t\tGet a list of smart groups\n\n\t\t\t$ c8y smartgroups list --name \"myText*\"\n\t\t\tGet a list of smart groups with the names starting with 'myText'\n\n\t\t\t$ c8y smartgroups list --name \"myText*\" | c8y devices list\n\t\t\tGet a list of smart groups with their names starting with \"myText\", then get the devices from the smart groups\n `),\n\t\tPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nil\n\t\t},\n\t\tRunE: ccmd.RunE,\n\t}\n\n\tcmd.SilenceUsage = true\n\n\tcmd.Flags().String(\"name\", \"\", \"Filter by name\")\n\tcmd.Flags().String(\"fragmentType\", \"\", \"Filter by fragment type\")\n\tcmd.Flags().String(\"owner\", \"\", \"Filter by owner\")\n\tcmd.Flags().String(\"deviceQuery\", \"\", \"Filter by device query\")\n\tcmd.Flags().String(\"query\", \"\", \"Additional query filter (accepts pipeline)\")\n\tcmd.Flags().String(\"queryTemplate\", \"\", \"String template to be used when applying the given query. Use %s to reference the query/pipeline input\")\n\tcmd.Flags().String(\"orderBy\", \"name\", \"Order by. e.g. _id asc or name asc or creationTime.date desc\")\n\tcmd.Flags().Bool(\"onlyInvisible\", false, \"Only include invisible smart groups\")\n\tcmd.Flags().Bool(\"onlyVisible\", false, \"Only include visible smart groups\")\n\tcmd.Flags().Bool(\"withParents\", false, \"Include a flat list of all parents and grandparents of the given object\")\n\n\tflags.WithOptions(\n\t\tcmd,\n\t\tflags.WithExtendedPipelineSupport(\"query\", \"query\", false, \"c8y_DeviceQueryString\"),\n\t)\n\n\t// Required flags\n\tccmd.SubCommand = subcommand.NewSubCommand(cmd)\n\n\treturn ccmd\n}", "func NewPluginListCommand(p *commands.KnParams) *cobra.Command {\n\tpluginFlags := PluginFlags{\n\t\tIOStreams: genericclioptions.IOStreams{\n\t\t\tIn: os.Stdin,\n\t\t\tOut: os.Stdout,\n\t\t\tErrOut: os.Stderr,\n\t\t},\n\t}\n\n\tpluginListCommand := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List all visible plugin executables\",\n\t\tLong: `List all visible plugin executables.\n\nAvailable plugin files are those that are:\n- executable\n- begin with \"kn-\n- anywhere on the path specified in Kn's config pluginDir variable, which:\n * can be overridden with the --plugin-dir flag`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\terr := pluginFlags.complete(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = pluginFlags.run()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tAddPluginFlags(pluginListCommand)\n\tBindPluginsFlagToViper(pluginListCommand)\n\n\tpluginFlags.AddPluginFlags(pluginListCommand)\n\n\treturn pluginListCommand\n}", "func newToDoList() toDoList {\n\treturn toDoList{}\n}", "func newListCmd(out io.Writer, errOut io.Writer) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Lists various entities managed by the Ziti Edge Controller\",\n\t\tLong: \"Lists various entities managed by the Ziti Edge Controller\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\terr := cmd.Help()\n\t\t\tcmdhelper.CheckErr(err)\n\t\t},\n\t}\n\n\tnewOptions := func() *edgeOptions {\n\t\treturn &edgeOptions{\n\t\t\tCommonOptions: common.CommonOptions{Out: out, Err: errOut},\n\t\t}\n\t}\n\n\tcmd.AddCommand(newListCmdForEntityType(\"api-sessions\", runListApiSessions, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"cas\", runListCAs, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"config-types\", runListConfigTypes, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"configs\", runListConfigs, newOptions()))\n\tcmd.AddCommand(newListEdgeRoutersCmd(newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"edge-router-policies\", runListEdgeRouterPolicies, newOptions(), \"erps\"))\n\tcmd.AddCommand(newListCmdForEntityType(\"terminators\", runListTerminators, newOptions()))\n\tcmd.AddCommand(newListIdentitiesCmd(newOptions()))\n\tcmd.AddCommand(newListServicesCmd(newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"service-edge-router-policies\", runListServiceEdgeRouterPolices, newOptions(), \"serps\"))\n\tcmd.AddCommand(newListCmdForEntityType(\"service-policies\", runListServicePolices, newOptions(), \"sps\"))\n\tcmd.AddCommand(newListCmdForEntityType(\"sessions\", runListSessions, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"transit-routers\", runListTransitRouters, newOptions()))\n\n\tcmd.AddCommand(newListCmdForEntityType(\"edge-router-role-attributes\", runListEdgeRouterRoleAttributes, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"identity-role-attributes\", runListIdentityRoleAttributes, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"service-role-attributes\", runListServiceRoleAttributes, newOptions()))\n\n\tcmd.AddCommand(newListCmdForEntityType(\"posture-checks\", runListPostureChecks, newOptions()))\n\tcmd.AddCommand(newListCmdForEntityType(\"posture-check-types\", runListPostureCheckTypes, newOptions()))\n\n\tconfigTypeListRootCmd := newEntityListRootCmd(\"config-type\")\n\tconfigTypeListRootCmd.AddCommand(newSubListCmdForEntityType(\"config-type\", \"configs\", outputConfigs, newOptions()))\n\n\tedgeRouterListRootCmd := newEntityListRootCmd(\"edge-router\", \"er\")\n\tedgeRouterListRootCmd.AddCommand(newSubListCmdForEntityType(\"edge-routers\", \"edge-router-policies\", outputEdgeRouterPolicies, newOptions()))\n\tedgeRouterListRootCmd.AddCommand(newSubListCmdForEntityType(\"edge-routers\", \"service-edge-router-policies\", outputServiceEdgeRouterPolicies, newOptions()))\n\tedgeRouterListRootCmd.AddCommand(newSubListCmdForEntityType(\"edge-routers\", \"identities\", outputIdentities, newOptions()))\n\tedgeRouterListRootCmd.AddCommand(newSubListCmdForEntityType(\"edge-routers\", \"services\", outputServices, newOptions()))\n\n\tedgeRouterPolicyListRootCmd := newEntityListRootCmd(\"edge-router-policy\", \"erp\")\n\tedgeRouterPolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"edge-router-policies\", \"edge-routers\", outputEdgeRouters, newOptions()))\n\tedgeRouterPolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"edge-router-policies\", \"identities\", outputIdentities, newOptions()))\n\n\tidentityListRootCmd := newEntityListRootCmd(\"identity\")\n\tidentityListRootCmd.AddCommand(newSubListCmdForEntityType(\"identities\", \"edge-router-policies\", outputEdgeRouterPolicies, newOptions()))\n\tidentityListRootCmd.AddCommand(newSubListCmdForEntityType(\"identities\", \"edge-routers\", outputEdgeRouters, newOptions()))\n\tidentityListRootCmd.AddCommand(newSubListCmdForEntityType(\"identities\", \"service-policies\", outputServicePolicies, newOptions()))\n\tidentityListRootCmd.AddCommand(newSubListCmdForEntityType(\"identities\", \"services\", outputServices, newOptions()))\n\tidentityListRootCmd.AddCommand(newSubListCmdForEntityType(\"identities\", \"service-configs\", outputServiceConfigs, newOptions()))\n\n\tserviceListRootCmd := newEntityListRootCmd(\"service\")\n\tserviceListRootCmd.AddCommand(newSubListCmdForEntityType(\"services\", \"configs\", outputConfigs, newOptions()))\n\tserviceListRootCmd.AddCommand(newSubListCmdForEntityType(\"services\", \"service-policies\", outputServicePolicies, newOptions()))\n\tserviceListRootCmd.AddCommand(newSubListCmdForEntityType(\"services\", \"service-edge-router-policies\", outputServiceEdgeRouterPolicies, newOptions()))\n\tserviceListRootCmd.AddCommand(newSubListCmdForEntityType(\"services\", \"terminators\", outputTerminators, newOptions()))\n\tserviceListRootCmd.AddCommand(newSubListCmdForEntityType(\"services\", \"identities\", outputIdentities, newOptions()))\n\tserviceListRootCmd.AddCommand(newSubListCmdForEntityType(\"services\", \"edge-routers\", outputEdgeRouters, newOptions()))\n\n\tserviceEdgeRouterPolicyListRootCmd := newEntityListRootCmd(\"service-edge-router-policy\", \"serp\")\n\tserviceEdgeRouterPolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"service-edge-router-policies\", \"services\", outputServices, newOptions()))\n\tserviceEdgeRouterPolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"service-edge-router-policies\", \"edge-routers\", outputEdgeRouters, newOptions()))\n\n\tservicePolicyListRootCmd := newEntityListRootCmd(\"service-policy\", \"sp\")\n\tservicePolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"service-policies\", \"services\", outputServices, newOptions()))\n\tservicePolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"service-policies\", \"identities\", outputIdentities, newOptions()))\n\tservicePolicyListRootCmd.AddCommand(newSubListCmdForEntityType(\"service-policies\", \"posture-checks\", outputPostureChecks, newOptions()))\n\n\tcmd.AddCommand(newListCmdForEntityType(\"summary\", runListSummary, newOptions()))\n\n\tcmd.AddCommand(configTypeListRootCmd,\n\t\tedgeRouterListRootCmd,\n\t\tedgeRouterPolicyListRootCmd,\n\t\tidentityListRootCmd,\n\t\tserviceEdgeRouterPolicyListRootCmd,\n\t\tserviceListRootCmd,\n\t\tservicePolicyListRootCmd,\n\t)\n\n\treturn cmd\n}", "func (c *CodeShipProvider) GetBuildsList(uuid string) ([]Build, error) {\n\tres, _, err := c.API.ListBuilds(c.Context, uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar builds []Build\n\tfor _, build := range res.Builds {\n\t\tcommitMessage := build.CommitMessage\n\t\tif len(commitMessage) > 70 {\n\t\t\tcommitMessage = build.CommitMessage[:70]\n\t\t}\n\n\t\tstatus := fmt.Sprintf(\"[%s](fg-cyan)\", build.Status)\n\t\tif strings.Contains(build.Status, \"success\") {\n\t\t\tstatus = fmt.Sprintf(\"[%s](fg-green)\", build.Status)\n\t\t}\n\t\tif strings.Contains(build.Status, \"error\") {\n\t\t\tstatus = fmt.Sprintf(\"[%s](fg-red)\", \"failed\")\n\t\t}\n\n\t\tbuilds = append(builds, Build{\n\t\t\tStartedAt: build.AllocatedAt.Format(\"02/01/06 03:04:05\"),\n\t\t\tFinishedAt: build.FinishedAt.Format(\"02/01/06 03:04:05\"),\n\t\t\tCommitMessage: commitMessage,\n\t\t\tStatus: status,\n\t\t\tUsername: build.Username,\n\t\t})\n\t}\n\n\treturn builds, nil\n}", "func NewCredentialListCommand(io ui.IO, newClient newClientFunc) *CredentialListCommand {\n\treturn &CredentialListCommand{\n\t\tio: io,\n\t\tnewClient: newClient,\n\t}\n}", "func (c *Cluster) buildCommand(command []string, verbose bool) []string {\n\toptions := []string{}\n\tif c.KubeconfigFile != \"\" {\n\t\toptions = append(options, \"--kubeconfig\", c.KubeconfigFile)\n\t}\n\tif c.Context.ContextName != \"\" {\n\t\toptions = append(options, \"--context\", c.Context.ContextName)\n\t}\n\toptions = append(options, command...)\n\treturn options\n}", "func main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"golist\"\n\tapp.Usage = \"List Go project resources (built with Go ???)\"\n\tapp.Version = \"0.0.1\"\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringSliceFlag{\"ignore-dir, d\", nil, \"Directory to ignore\", \"\", false},\n\t\tcli.StringSliceFlag{\"ignore-tree, t\", nil, \"Directory tree to ignore\", \"\", false},\n\t\tcli.StringSliceFlag{\"ignore-regex, r\", nil, \"Regex specified files/dirs to ignore\", \"\", false},\n\t\tcli.StringFlag{\"package-path\", \"\", \"Package entry point\", \"\", nil, false},\n\t\tcli.BoolFlag{\"all-deps\", \"List imported packages including stdlib\", \"\", nil, false},\n\t\tcli.BoolFlag{\"provided\", \"List provided packages\", \"\", nil, false},\n\t\tcli.BoolFlag{\"imported\", \"List imported packages\", \"\", nil, false},\n\t\tcli.BoolFlag{\"skip-self\", \"Skip imported packages with the same --package-path\", \"\", nil, false},\n\t\tcli.BoolFlag{\"tests\", \"Apply the listing options over tests\", \"\", nil, false},\n\t\tcli.BoolFlag{\"show-main\", \"Including main files in listings\", \"\", nil, false},\n\t\tcli.BoolFlag{\"to-install\", \"List all resources recognized as essential part of the Go project\", \"\", nil, false},\n\t\tcli.StringSliceFlag{\"include-extension, e\", nil, \"Include all files with the extension in the recognized resources, e.g. .proto, .tmpl\", \"\", false},\n\t\tcli.BoolFlag{\"json\", \"Output as JSON artefact\", \"\", nil, false},\n\t}\n\n\tapp.Action = func(c *cli.Context) error {\n\n\t\tif c.String(\"package-path\") == \"\" {\n\t\t\treturn fmt.Errorf(\"--package-path is not set\")\n\t\t}\n\n\t\tif !c.Bool(\"provided\") && !c.Bool(\"imported\") && !c.Bool(\"to-install\") && !c.Bool(\"json\") {\n\t\t\treturn fmt.Errorf(\"At least one of --provided, --imported, --to-install or --json must be set\")\n\t\t}\n\n\t\tignore := &util.Ignore{}\n\n\t\tfor _, dir := range c.StringSlice(\"ignore-tree\") {\n\t\t\t// skip all ignored dirs that are prefixes of the package-path\n\t\t\tif strings.HasPrefix(c.String(\"package-path\"), dir) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tignore.Trees = append(ignore.Trees, dir)\n\t\t}\n\n\t\tfor _, dir := range c.StringSlice(\"ignore-dir\") {\n\t\t\t// skip all ignored dirs that are prefixes of the package-path\n\t\t\tif strings.HasPrefix(c.String(\"package-path\"), dir) && c.String(\"package-path\") != dir {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tignore.Dirs = append(ignore.Dirs, dir)\n\t\t}\n\n\t\tfor _, dir := range c.StringSlice(\"ignore-regex\") {\n\t\t\tignore.Regexes = append(ignore.Regexes, regexp.MustCompile(dir))\n\t\t}\n\n\t\tcollector := util.NewPackageInfoCollector(ignore, c.StringSlice(\"include-extension\"))\n\t\tif err := collector.CollectPackageInfos(c.String(\"package-path\")); err != nil {\n\t\t\treturn err\n\n\t\t}\n\n\t\tif c.Bool(\"json\") {\n\t\t\t// Collect everything\n\t\t\tartifact, _ := collector.BuildArtifact()\n\t\t\tstr, _ := json.Marshal(artifact)\n\t\t\tfmt.Printf(\"%v\\n\", string(str))\n\t\t\treturn nil\n\t\t}\n\n\t\tif c.Bool(\"provided\") {\n\t\t\tpkgs, err := collector.BuildPackageTree(c.Bool(\"show-main\"), c.Bool(\"tests\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsort.Strings(pkgs)\n\t\t\tfor _, item := range pkgs {\n\t\t\t\tfmt.Println(item)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tif c.Bool(\"imported\") {\n\t\t\tpkgs, err := collector.CollectProjectDeps(c.Bool(\"all-deps\"), c.Bool(\"skip-self\"), c.Bool(\"tests\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsort.Strings(pkgs)\n\t\t\tfor _, item := range pkgs {\n\t\t\t\tfmt.Println(item)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tif c.Bool(\"to-install\") {\n\t\t\tpkgs, err := collector.CollectInstalledResources()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsort.Strings(pkgs)\n\t\t\tfor _, item := range pkgs {\n\t\t\t\tfmt.Println(item)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif err := app.Run(os.Args); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n}", "func CommandList() error {\n\tcommon.LogInfo2Quiet(\"My Apps\")\n\tapps, err := common.DokkuApps()\n\tif err != nil {\n\t\tcommon.LogWarn(err.Error())\n\t\treturn nil\n\t}\n\n\tfor _, appName := range apps {\n\t\tcommon.Log(appName)\n\t}\n\n\treturn nil\n}", "func List(ctx *cli.Context) error {\n\tm := task.NewFileManager()\n\ttasks := m.GetAllOpenTasks()\n\n\ttasks = sortTasks(ctx.String(\"sort\"), tasks)\n\n\tfor _, v := range tasks {\n\t\tfmt.Println(v.String())\n\t}\n\treturn nil\n}", "func TestCmdList(t *testing.T) {\n\tassert := asrt.New(t)\n\torigDir, _ := os.Getwd()\n\n\tsite := TestSites[0]\n\terr := os.Chdir(site.Dir)\n\n\tglobalconfig.DdevGlobalConfig.SimpleFormatting = true\n\t_ = globalconfig.WriteGlobalConfig(globalconfig.DdevGlobalConfig)\n\n\tt.Cleanup(func() {\n\t\terr = os.Chdir(origDir)\n\t\tassert.NoError(err)\n\t\tglobalconfig.DdevGlobalConfig.SimpleFormatting = false\n\t\t_ = globalconfig.WriteGlobalConfig(globalconfig.DdevGlobalConfig)\n\t})\n\t// This gratuitous ddev start -a repopulates the ~/.ddev/global_config.yaml\n\t// project list, which has been damaged by other tests which use\n\t// direct app techniques.\n\t_, err = exec.RunHostCommand(DdevBin, \"start\", \"-a\", \"-y\")\n\tassert.NoError(err)\n\n\t// Execute \"ddev list\" and harvest plain text output.\n\tout, err := exec.RunHostCommand(DdevBin, \"list\", \"-W\")\n\tassert.NoError(err, \"error running ddev list: %v output=%s\", out)\n\n\t// Execute \"ddev list -j\" and harvest the json output\n\tjsonOut, err := exec.RunHostCommand(DdevBin, \"list\", \"-j\")\n\tassert.NoError(err, \"error running ddev list -j: %v, output=%s\", jsonOut)\n\n\tsiteList := getTestingSitesFromList(t, jsonOut)\n\tassert.Equal(len(TestSites), len(siteList), \"didn't find expected number of sites in list: %v\", siteList)\n\n\tfor _, v := range TestSites {\n\t\tapp, err := ddevapp.GetActiveApp(v.Name)\n\t\tassert.NoError(err)\n\n\t\t// Look for standard items in the regular ddev list output\n\t\tassert.Contains(string(out), v.Name)\n\t\ttestURL := app.GetHTTPSURL()\n\t\tif globalconfig.GetCAROOT() == \"\" {\n\t\t\ttestURL = app.GetHTTPURL()\n\t\t}\n\t\tassert.Contains(string(out), testURL)\n\t\tassert.Contains(string(out), app.GetType())\n\t\tassert.Contains(string(out), ddevapp.RenderHomeRootedDir(app.GetAppRoot()))\n\n\t\t// Look through list results in json for this site.\n\t\tfound := false\n\t\tfor _, listitem := range siteList {\n\t\t\titem, ok := listitem.(map[string]interface{})\n\t\t\tassert.True(ok)\n\t\t\t// Check to see that we can find our item\n\t\t\tif item[\"name\"] == v.Name {\n\t\t\t\tfound = true\n\t\t\t\tassert.Equal(app.GetHTTPURL(), item[\"httpurl\"])\n\t\t\t\tassert.Equal(app.GetHTTPSURL(), item[\"httpsurl\"])\n\t\t\t\tassert.Equal(app.Name, item[\"name\"])\n\t\t\t\tassert.Equal(app.GetType(), item[\"type\"])\n\t\t\t\tassert.EqualValues(ddevapp.RenderHomeRootedDir(app.GetAppRoot()), item[\"shortroot\"])\n\t\t\t\tassert.EqualValues(app.GetAppRoot(), item[\"approot\"])\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tassert.True(found, \"Failed to find project %s in ddev list -j\", v.Name)\n\n\t}\n\n\t// Now filter the list by the type of the first running test app\n\tjsonOut, err = exec.RunHostCommand(DdevBin, \"list\", \"-j\", \"--type\", TestSites[0].Type)\n\tassert.NoError(err, \"error running ddev list: %v output=%s\", err, out)\n\tsiteList = getTestingSitesFromList(t, jsonOut)\n\tassert.GreaterOrEqual(len(siteList), 1)\n\n\t// Now filter the list by a not existing type\n\tjsonOut, err = exec.RunHostCommand(DdevBin, \"list\", \"-j\", \"--type\", \"not-existing-type\")\n\tassert.NoError(err, \"error running ddev list: %v output=%s\", err, out)\n\tsiteList = getTestingSitesFromList(t, jsonOut)\n\tassert.Equal(0, len(siteList))\n\n\t// Stop the first app\n\tout, err = exec.RunHostCommand(DdevBin, \"stop\", TestSites[0].Name)\n\tassert.NoError(err, \"error running ddev stop %v: %v output=%s\", TestSites[0].Name, err, out)\n\n\t// Execute \"ddev list\" and harvest json output.\n\t// Now there should be one less active project in list\n\tjsonOut, err = exec.RunHostCommand(DdevBin, \"list\", \"-jA\", \"-W\")\n\tassert.NoError(err, \"error running ddev list: %v output=%s\", err, jsonOut)\n\n\tsiteList = getTestingSitesFromList(t, jsonOut)\n\tassert.Equal(len(TestSites)-1, len(siteList))\n\n\t// Now list without -A, make sure we show all projects\n\tjsonOut, err = exec.RunHostCommand(DdevBin, \"list\", \"-j\")\n\tassert.NoError(err, \"error running ddev list: %v output=%s\", err, out)\n\tsiteList = getTestingSitesFromList(t, jsonOut)\n\tassert.Equal(len(TestSites), len(siteList))\n\n\t// Leave firstApp running for other tests\n\tout, err = exec.RunHostCommand(DdevBin, \"start\", \"-y\", TestSites[0].Name)\n\tassert.NoError(err, \"error running ddev start: %v output=%s\", err, out)\n}", "func NewCommand() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"The version of matryoshka\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tfmt.Println(BuildCommit)\n\t\t\treturn nil\n\t\t},\n\t}\n}", "func newVersionCommands(globalOpts *globalOptions) *cobra.Command {\n\toptions := &versionOptions{\n\t\tglobalOptions: globalOpts,\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Print the CLI version information\",\n\t\tLong: versionDesc,\n\t\tExample: versionExample,\n\t\tArgs: cobra.ExactArgs(0),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn options.run()\n\t\t},\n\t}\n\n\toptions.addVersionFlags(cmd)\n\n\treturn cmd\n}", "func newWatchCommand(c *cli.Context) (Command, error) {\n\trepo, err := newRepositoryRequestInfo(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &watchCommand{repo: repo, jsonPaths: c.StringSlice(\"jsonpath\"), streaming: c.Bool(\"streaming\")}, nil\n}", "func NewTasksCommand() *cobra.Command {\n\tcommand := &cobra.Command{\n\t\tUse: \"tasks\",\n\t\tShort: \"Task related option\",\n\t\tLong: \"Task related option, e.g. list tasks\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmd.Usage()\n\t\t},\n\t}\n\n\tcommand.AddCommand(listTasksCommand())\n\n\treturn command\n}", "func NewCommand(ctx api.Context) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"node\",\n\t\tShort: \"Display DC/OS node information\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\t_, ok := ctx.EnvLookup(cli.EnvStrictDeprecations)\n\t\t\tif !ok {\n\t\t\t\tctx.Deprecated(\"Getting the list of nodes from `dcos node` is deprecated. Please use `dcos node list`.\")\n\t\t\t\tlistCmd := newCmdNodeList(ctx)\n\t\t\t\t// Execute by default would use os.Args[1:], which is everything after `dcos ...`.\n\t\t\t\t// We need all command line arguments after `dcos node ...`.\n\t\t\t\tlistCmd.SetArgs(ctx.Args()[2:])\n\t\t\t\tlistCmd.SilenceErrors = true\n\t\t\t\tlistCmd.SilenceUsage = true\n\t\t\t\treturn listCmd.Execute()\n\t\t\t}\n\t\t\treturn cmd.Help()\n\t\t},\n\t}\n\tcmd.Flags().Bool(\"json\", false, \"Print in json format\")\n\tcmd.Flags().StringArray(\"field\", nil, \"Name of extra field to include in the output of `dcos node`. Can be repeated multiple times to add several fields.\")\n\n\tcmd.AddCommand(\n\t\tnewCmdNodeDecommission(ctx),\n\t\tnewCmdNodeDiagnostics(ctx),\n\t\tnewCmdNodeDNS(ctx),\n\t\tnewCmdNodeList(ctx),\n\t\tnewCmdNodeListComponents(ctx),\n\t\tnewCmdNodeLog(ctx),\n\t\tnewCmdNodeMetrics(ctx),\n\t\tnewCmdNodeSSH(ctx),\n\t)\n\treturn cmd\n}", "func (cli *bkCli) projectList(quietList bool) error {\n\n\tt := time.Now()\n\n\tprojects, err := cli.listProjects()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif quietList {\n\t\tfor _, proj := range projects {\n\t\t\tfmt.Printf(\"%-36s\\n\", *proj.ID)\n\t\t}\n\t\treturn nil // we are done\n\t}\n\n\ttb := table.New(projectColumns)\n\tvals := make(map[string]interface{})\n\n\tfor _, proj := range projects {\n\t\tif proj.FeaturedBuild != nil {\n\t\t\tfb := proj.FeaturedBuild\n\t\t\tvals = utils.ToMap(projectColumns, []interface{}{*proj.ID, *proj.Name, *fb.Number, toString(fb.Branch), toString(fb.Message), toString(fb.State), valString(fb.FinishedAt)})\n\t\t} else {\n\t\t\tvals = utils.ToMap(projectColumns, []interface{}{*proj.ID, *proj.Name, 0, \"\", \"\", \"\", \"\"})\n\t\t}\n\t\ttb.AddRow(vals)\n\t}\n\ttb.Markdown = true\n\ttb.Print()\n\n\tfmt.Printf(\"\\nTime taken: %s\\n\", time.Now().Sub(t))\n\n\treturn err\n}", "func NewVersionCommand(version string, buildDate string, out io.Writer) *cobra.Command {\n\tversionCmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"display the current version\",\n\t\tLong: \"display the current version\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Fprintf(out, \"Primes Worker:\\n\")\n\t\t\tfmt.Fprintf(out, \" Version: %s\\n\", version)\n\t\t\tfmt.Fprintf(out, \" Built: %s\\n\", buildDate)\n\t\t\tfmt.Fprintf(out, \" Go Version: %s\\n\", runtime.Version())\n\t\t},\n\t}\n\n\treturn versionCmd\n}", "func NewIOCStreamListCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tAliases: []string{\"il\"},\n\t\tUse: \"list\",\n\t\tShort: \"List IoCs from notifications\",\n\t\tExample: iocStreamListCmdExamples,\n\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tp, err := NewPrinter(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn p.PrintCollection(vt.URL(\"ioc_stream\"))\n\t\t},\n\t}\n\n\taddIncludeExcludeFlags(cmd.Flags())\n\taddIDOnlyFlag(cmd.Flags())\n\taddFilterFlag(cmd.Flags())\n\taddLimitFlag(cmd.Flags())\n\taddCursorFlag(cmd.Flags())\n\n\treturn cmd\n}", "func buildQueue(c *cli.Context) error {\n\n\tclient, err := newClient(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuilds, err := client.BuildQueue()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(builds) == 0 {\n\t\tfmt.Println(\"there are no pending or running builds\")\n\t\treturn nil\n\t}\n\n\ttmpl, err := template.New(\"_\").Parse(c.String(\"format\") + \"\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, build := range builds {\n\t\ttmpl.Execute(os.Stdout, build)\n\t}\n\treturn nil\n}", "func (o ClusterBuildStrategySpecBuildStepsOutput) Command() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildSteps) []string { return v.Command }).(pulumi.StringArrayOutput)\n}", "func NewBuildCommand() *Command {\n\treturn &Command{\n\t\tGetManifest: model.GetManifestV2,\n\t\tBuilder: &build.OktetoBuilder{},\n\t\tRegistry: registry.NewOktetoRegistry(okteto.Config{}),\n\t}\n}", "func NewVersionCommand(streams genericclioptions.IOStreams) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Print the version information for kubectl trace\",\n\t\tRunE: func(c *cobra.Command, args []string) error {\n\t\t\tfmt.Fprintln(streams.Out, version.String())\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn cmd\n}", "func List(ctx *cli.Context) error {\n\targs := &listArgs{}\n\targs.Parse(ctx)\n\n\tmanager := yata.NewTaskManager()\n\ttasks, err := manager.GetAll()\n\thandleError(err)\n\n\tif args.showTags {\n\t\treturn displayTags(tasks)\n\t}\n\n\ttasks = yata.FilterTasks(tasks, func(t yata.Task) bool {\n\t\treturn (args.tag == \"\" || sliceContains(t.Tags, args.tag)) &&\n\t\t\t(args.description == \"\" || strings.Contains(t.Description, args.description)) &&\n\t\t\t(args.all || !t.Completed)\n\t})\n\n\tsortTasks(args.sort, &tasks)\n\n\tfor _, v := range tasks {\n\t\tstringer := yata.NewTaskStringer(v, taskStringer(args.format))\n\t\tswitch v.Priority {\n\t\tcase yata.LowPriority:\n\t\t\tyata.PrintlnColor(\"cyan+h\", stringer.String())\n\t\tcase yata.HighPriority:\n\t\t\tyata.PrintlnColor(\"red+h\", stringer.String())\n\t\tdefault:\n\t\t\tyata.Println(stringer.String())\n\t\t}\n\t}\n\n\treturn nil\n}", "func newCoverageList(name string) *CoverageList {\n\treturn &CoverageList{\n\t\tCoverage: &Coverage{Name: name},\n\t\tGroup: []Coverage{},\n\t}\n}", "func NewCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Version for apisix-mesh-agent\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Println(version.String())\n\t\t},\n\t}\n\treturn cmd\n}", "func (*ListCmd) Name() string { return \"list\" }", "func cmdListReleases(ccmd *cobra.Command, args []string) {\n\taplSvc := apl.NewClient()\n\toutput := runListCommand(&releaseParams, aplSvc.Releases.List)\n\tif output != nil {\n\t\tfields := []string{\"ID\", \"StackID\", \"Version\", \"CreatedTime\"}\n\t\tprintTableResultsCustom(output.([]apl.Release), fields)\n\t}\n}", "func RunGoList(cwd string, goExec string) (*GoListCmd, error) {\n\t/*\tcmd, err := GetGoExecutable()\n\t\tif err != nil {\n\t\t\tlog.Error().Err(err).Msg(\"`which go` failed\")\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdefer cmd.ReadCloser().Close()\n\t\tbuf := new(bytes.Buffer)\n\t\tbuf.ReadFrom(cmd.ReadCloser())\n\t\ts := strings.TrimSpace(buf.String())\n\t\tlog.Info().Msg(\"Found go executable \" + s)\n\n\t\t// Wait for the `go list` command to complete.\n\t\t//if err := cmd.Wait(); err != nil {\n\t\t//\treturn nil, fmt.Errorf(\"%v: `go list` failed, use `go mod tidy` to known more\", err)\n\t\t//}\n\t*/\n\tgoList := exec.Command(goExec, \"list\", \"-json\", \"-deps\", \"-mod=readonly\", \"./...\")\n\tgoList.Dir = cwd\n\toutput, err := goList.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = goList.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &GoListCmd{cmd: goList, output: output}, nil\n}", "func (c *Client) BuildListRequest(ctx context.Context, v interface{}) (*http.Request, error) {\n\tu := &url.URL{Scheme: c.scheme, Host: c.host, Path: ListLogPath()}\n\treq, err := http.NewRequest(\"POST\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, goahttp.ErrInvalidURL(\"log\", \"list\", u.String(), err)\n\t}\n\tif ctx != nil {\n\t\treq = req.WithContext(ctx)\n\t}\n\n\treturn req, nil\n}", "func buildCommand() *command {\n\n\tres := &command{\n\t\tType: \"\",\n\t\tArgs: make([]string,0),\n\t}\n\tvar tmpCount = 0\n\n\tfor _, p := range os.Args {\n\t\t// Remove the empty args (I have no idea why they appear)\n\t\tpTrim := strings.Trim(p, \" \")\n\t\tif pTrim != \"\" {\n\t\t\tif tmpCount==1 {\n\t\t\t\tres.Type = pTrim\n\t\t\t} else if tmpCount > 1 {\n\t\t\t\tres.Args = append(res.Args, pTrim)\n\t\t\t}\n\t\t\ttmpCount += 1\n\t\t}\n\n\t}\n\treturn res\n}", "func newLogsCommand(dockerCli *command.DockerCli) *cobra.Command {\n\tvar opts logsOptions\n\n\tcmd := &cobra.Command{\n\t\tUse: \"logs [OPTIONS] SERVICE|TASK\",\n\t\tShort: \"Fetch the logs of a service or task\",\n\t\tArgs: cli.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts.target = args[0]\n\t\t\treturn runLogs(dockerCli, &opts)\n\t\t},\n\t\tTags: map[string]string{\"version\": \"1.29\"},\n\t}\n\n\tflags := cmd.Flags()\n\t// options specific to service logs\n\tflags.BoolVar(&opts.noResolve, \"no-resolve\", false, \"Do not map IDs to Names in output\")\n\tflags.BoolVar(&opts.noTrunc, \"no-trunc\", false, \"Do not truncate output\")\n\tflags.BoolVar(&opts.noTaskIDs, \"no-task-ids\", false, \"Do not include task IDs in output\")\n\t// options identical to container logs\n\tflags.BoolVarP(&opts.follow, \"follow\", \"f\", false, \"Follow log output\")\n\tflags.StringVar(&opts.since, \"since\", \"\", \"Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)\")\n\tflags.BoolVarP(&opts.timestamps, \"timestamps\", \"t\", false, \"Show timestamps\")\n\tflags.StringVar(&opts.tail, \"tail\", \"all\", \"Number of lines to show from the end of the logs\")\n\treturn cmd\n}", "func (r *ConfigAuditReportReconciler) buildCommand(workloadInfo string) string {\n\tworkloadInfos := strings.Split(workloadInfo, \"|\")\n\tworkloadType := workloadInfos[0]\n\tworkloadName := workloadInfos[1]\n\n\treturn \"starboard -n \" + r.NamespaceWatched + \" get report \" + workloadType + \"/\" + workloadName + \" > \" + buildReportName(workloadType, workloadName)\n}", "func List(g *types.Cmd) {\n\tg.AddOptions(\"list\")\n}", "func NewVersionCommand() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Prints out build version information\",\n\t\tLong: \"Prints out build version information\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Printf(`Version: %v\nGitRevision: %v\nGolangVersion: %v\n`,\n\t\t\t\tversion.VelaVersion,\n\t\t\t\tversion.GitRevision,\n\t\t\t\truntime.Version())\n\t\t},\n\t\tAnnotations: map[string]string{\n\t\t\ttypes.TagCommandType: types.TypePlugin,\n\t\t},\n\t}\n}" ]
[ "0.7019383", "0.6365712", "0.62861466", "0.62341", "0.61762345", "0.61427575", "0.61323035", "0.6077577", "0.5928921", "0.5884531", "0.5867837", "0.58048195", "0.57902944", "0.5639388", "0.56278795", "0.5610364", "0.5604566", "0.5572504", "0.5563013", "0.5516337", "0.5463784", "0.53819853", "0.5374539", "0.5358723", "0.5335075", "0.5335038", "0.53340995", "0.5330123", "0.53161705", "0.53125745", "0.53116715", "0.5279986", "0.5258267", "0.52562475", "0.52452123", "0.5242123", "0.52360404", "0.522759", "0.51760197", "0.5172501", "0.51219815", "0.5116296", "0.51076245", "0.50990605", "0.5092991", "0.5085276", "0.5081948", "0.50472045", "0.50470734", "0.5016907", "0.50108117", "0.4986524", "0.49763098", "0.4968389", "0.49600077", "0.4940333", "0.49158987", "0.49150267", "0.49126428", "0.49066848", "0.49010822", "0.48973688", "0.48954648", "0.48804632", "0.48656738", "0.48655567", "0.48426756", "0.4831766", "0.48285446", "0.48267525", "0.48182085", "0.48180008", "0.48157522", "0.48048842", "0.4797872", "0.47942373", "0.47834358", "0.4781776", "0.47800523", "0.4774863", "0.4770705", "0.47676185", "0.47654304", "0.47442225", "0.47384718", "0.47345516", "0.47259223", "0.4700326", "0.46934322", "0.4691185", "0.46907145", "0.46883285", "0.46854192", "0.4680708", "0.46730512", "0.46463877", "0.4645619", "0.46405783", "0.46384573", "0.46337977" ]
0.8401678
0
ListBuilds will display a list of builds
func ListBuilds(client *travis.Client, w io.Writer) error { filterBranch := "master" opt := &travis.RepositoryListOptions{Member: viper.GetString("TRAVIS_CI_OWNER"), Active: true} repos, _, err := client.Repositories.Find(opt) if err != nil { return err } tr := tabwriter.NewWriter(w, 0, 0, 1, ' ', tabwriter.FilterHTML) fmt.Fprintf(tr, "%s\t%s\t%s\t%s\n", "", "Name", "Branch", "Finished") for _, repo := range repos { // Trying to remove the items that are not really running in Travis CI // Assume there is a better way to do this? if repo.LastBuildState == "" { continue } for _, branchName := range strings.Split(filterBranch, ",") { branch, _, err := client.Branches.GetFromSlug(repo.Slug, branchName) if err != nil { return err } finish, err := time.Parse(time.RFC3339, branch.FinishedAt) finishAt := finish.Format(ui.AppDateTimeFormat) if err != nil { finishAt = branch.FinishedAt } result := "" if branch.State == "failed" { result = ui.AppFailure } else if branch.State == "started" { result = ui.AppProgress } else { result = ui.AppSuccess } fmt.Fprintf(tr, "%s \t%s\t%s\t%s\n", result, repo.Slug, branchName, finishAt) } } tr.Flush() return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b Build) List(c *gin.Context) {\n\tproject := c.DefaultQuery(\"project\", \"\")\n\tpublic := c.DefaultQuery(\"public\", \"\")\n\tbuilds := []models.Build{}\n\tvar err error\n\n\tif public == \"true\" {\n\t\tbuilds, err = b.publicBuilds()\n\t} else {\n\t\tbuilds, err = b.userBuilds(c, project)\n\t}\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\tsugar.InternalError(c, err)\n\t\treturn\n\t}\n\n\tsugar.SuccessResponse(c, 200, builds)\n}", "func ListBuilds(db *sql.DB, builds chan<- BuildMetadata, componentID string) error {\n\tdefer close(builds)\n\n\tvar rows *sql.Rows\n\tvar err error\n\tif componentID != \"\" {\n\t\trows, err = db.Query(selectBuildsByComponentID, componentID)\n\t} else {\n\t\trows, err = db.Query(selectBuilds)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\n\tvar id, rowComponentID string\n\tvar createdAt int64\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&id, &rowComponentID, &createdAt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuilds <- BuildMetadata{\n\t\t\tID: id,\n\t\t\tComponentID: rowComponentID,\n\t\t\tCreatedAt: time.Unix(createdAt, 0),\n\t\t}\n\t}\n\n\treturn nil\n}", "func ListBuilds(client *azuredevops.Client, opts ListOptions, w io.Writer) error {\n\tbuildDefOpts := azuredevops.BuildDefinitionsListOptions{Path: \"\\\\\" + viper.GetString(\"AZURE_DEVOPS_TEAM\")}\n\tdefinitions, err := client.BuildDefinitions.List(&buildDefOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresults := make(chan azuredevops.Build)\n\tvar wg sync.WaitGroup\n\twg.Add(len(definitions))\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(results)\n\t}()\n\n\tfor _, definition := range definitions {\n\t\tgo func(definition azuredevops.BuildDefinition) {\n\t\t\tdefer wg.Done()\n\n\t\t\tfor _, branchName := range strings.Split(opts.Branches, \",\") {\n\t\t\t\tbuilds, err := getBuildsForBranch(client, definition.ID, branchName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintf(w, \"unable to get builds for definition %s: %v\", definition.Name, err)\n\t\t\t\t}\n\t\t\t\tif len(builds) > 0 {\n\t\t\t\t\tresults <- builds[0]\n\t\t\t\t}\n\t\t\t}\n\t\t}(definition)\n\t}\n\n\tvar builds []azuredevops.Build\n\tfor result := range results {\n\t\tbuilds = append(builds, result)\n\t}\n\n\tsort.Slice(builds, func(i, j int) bool { return builds[i].Definition.Name < builds[j].Definition.Name })\n\n\t// renderAzureDevOpsBuilds(builds, len(builds), \".*\")\n\ttr := tabwriter.NewWriter(w, 0, 0, 1, ' ', tabwriter.FilterHTML)\n\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\t%s\\n\", \"\", \"Name\", \"Branch\", \"Build\", \"Finished\")\n\tfor index := 0; index < len(builds); index++ {\n\t\tbuild := builds[index]\n\t\tname := build.Definition.Name\n\t\tresult := build.Result\n\t\tstatus := build.Status\n\t\tbuildNo := build.BuildNumber\n\t\tbranch := build.Branch\n\n\t\t// Deal with date formatting for the finish time\n\t\tfinish, err := time.Parse(time.RFC3339, builds[index].FinishTime)\n\t\tfinishAt := finish.Format(ui.AppDateTimeFormat)\n\t\tif err != nil {\n\t\t\tfinishAt = builds[index].FinishTime\n\t\t}\n\n\t\t// Filter on branches\n\t\tmatched, _ := regexp.MatchString(\".*\"+opts.Branches+\".*\", branch)\n\t\tif matched == false {\n\t\t\tcontinue\n\t\t}\n\n\t\tif status == \"inProgress\" {\n\t\t\tresult = ui.AppProgress\n\t\t} else if status == \"notStarted\" {\n\t\t\tresult = ui.AppPending\n\t\t} else {\n\t\t\tif result == \"failed\" {\n\t\t\t\tresult = ui.AppFailure\n\t\t\t} else {\n\t\t\t\tresult = ui.AppSuccess\n\t\t\t}\n\t\t}\n\n\t\tfmt.Fprintf(tr, \"%s \\t%s\\t%s\\t%s\\t%s\\n\", result, name, branch, buildNo, finishAt)\n\t}\n\n\ttr.Flush()\n\n\treturn nil\n}", "func (c OSClientBuildClient) List(namespace string, opts kapi.ListOptions) (*buildapi.BuildList, error) {\n\treturn c.Client.Builds(namespace).List(opts)\n}", "func buildList(c *cli.Context) error {\n\trepo := c.Args().First()\n\towner, name, err := parseRepo(repo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := newClient(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuilds, err := client.BuildList(owner, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmpl, err := template.New(\"_\").Parse(c.String(\"format\") + \"\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbranch := c.String(\"branch\")\n\tevent := c.String(\"event\")\n\tstatus := c.String(\"status\")\n\tlimit := c.Int(\"limit\")\n\n\tvar count int\n\tfor _, build := range builds {\n\t\tif count >= limit {\n\t\t\tbreak\n\t\t}\n\t\tif branch != \"\" && build.Branch != branch {\n\t\t\tcontinue\n\t\t}\n\t\tif event != \"\" && build.Event != event {\n\t\t\tcontinue\n\t\t}\n\t\tif status != \"\" && build.Status != status {\n\t\t\tcontinue\n\t\t}\n\t\ttmpl.Execute(os.Stdout, build)\n\t\tcount++\n\t}\n\treturn nil\n}", "func BuildsList(quietList bool) error {\n\tcli, err := newBkCli()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cli.buildList(quietList)\n}", "func (cli *bkCli) buildList(quietList bool) error {\n\n\tvar (\n\t\tbuilds []bk.Build\n\t\terr error\n\t)\n\n\tt := time.Now()\n\n\tprojects, err := cli.listProjects()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// did we locate a project\n\tproject := git.LocateProject(projects)\n\n\tif project != nil {\n\t\tfmt.Printf(\"Listing for project = %s\\n\\n\", *project.Name)\n\n\t\torg := extractOrg(*project.URL)\n\n\t\tbuilds, _, err = cli.client.Builds.ListByProject(org, *project.Slug, nil)\n\n\t} else {\n\t\tutils.Check(fmt.Errorf(\"Failed to locate the buildkite project using git.\")) // TODO tidy this up\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif quietList {\n\t\tfor _, build := range builds {\n\t\t\tfmt.Printf(\"%-36s\\n\", *build.ID)\n\t\t}\n\t\treturn nil // we are done\n\t}\n\n\ttb := table.New(buildColumns)\n\n\tfor _, build := range builds {\n\t\tvals := utils.ToMap(buildColumns, []interface{}{*build.Project.Name, *build.Number, *build.Branch, *build.Message, *build.State, *build.Commit})\n\t\ttb.AddRow(vals)\n\t}\n\n\ttb.Markdown = true\n\ttb.Print()\n\n\tfmt.Printf(\"\\nTime taken: %s\\n\", time.Now().Sub(t))\n\n\treturn nil\n}", "func BuildList(builds ...buildapi.Build) buildapi.BuildList {\n\treturn buildapi.BuildList{\n\t\tItems: builds,\n\t}\n}", "func (c *CodeShipProvider) GetBuildsList(uuid string) ([]Build, error) {\n\tres, _, err := c.API.ListBuilds(c.Context, uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar builds []Build\n\tfor _, build := range res.Builds {\n\t\tcommitMessage := build.CommitMessage\n\t\tif len(commitMessage) > 70 {\n\t\t\tcommitMessage = build.CommitMessage[:70]\n\t\t}\n\n\t\tstatus := fmt.Sprintf(\"[%s](fg-cyan)\", build.Status)\n\t\tif strings.Contains(build.Status, \"success\") {\n\t\t\tstatus = fmt.Sprintf(\"[%s](fg-green)\", build.Status)\n\t\t}\n\t\tif strings.Contains(build.Status, \"error\") {\n\t\t\tstatus = fmt.Sprintf(\"[%s](fg-red)\", \"failed\")\n\t\t}\n\n\t\tbuilds = append(builds, Build{\n\t\t\tStartedAt: build.AllocatedAt.Format(\"02/01/06 03:04:05\"),\n\t\t\tFinishedAt: build.FinishedAt.Format(\"02/01/06 03:04:05\"),\n\t\t\tCommitMessage: commitMessage,\n\t\t\tStatus: status,\n\t\t\tUsername: build.Username,\n\t\t})\n\t}\n\n\treturn builds, nil\n}", "func (d Dashboard) drawBuilds(bounds rect) error {\n\n\tnumberOfBuilds := len(d.builds)\n\tlayout, err := layoutGridForScreen(size{30, 5}, numberOfBuilds, 1,\n\t\tbounds)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := 0; i < numberOfBuilds; i++ {\n\t\tbox := layout.boxes[i]\n\t\td.drawBuildState(d.builds[i], box)\n\t}\n\treturn nil\n}", "func ListBuildings(queryAPI api.QueryAPI, relTime string) []map[string]interface{} {\n\tvar queryBuidler strings.Builder\n\n\tlistBuildingTemp.Execute(&queryBuidler, relTime)\n\tquery := queryBuidler.String()\n\tlog.Println(query)\n\treturn ExecuteQuery(queryAPI, query)\n}", "func getBuilds(c context.Context, masterName, builderName string) ([]*resp.BuildRef, error) {\n\tresult := []*resp.BuildRef{}\n\tbs, err := model.GetBuilds(c, []model.BuildRoot{\n\t\tmodel.GetBuildRoot(c, masterName, builderName)}, 25)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, b := range bs[0] {\n\t\tmb := &resp.MiloBuild{\n\t\t\tSummary: resp.BuildComponent{\n\t\t\t\tStarted: b.ExecutionTime.Format(time.RFC3339),\n\t\t\t\t// TODO(hinoka/martiniss): Also get the real finished time and duration.\n\t\t\t\tFinished: b.ExecutionTime.Format(time.RFC3339),\n\t\t\t\tStatus: func(status string) resp.Status {\n\t\t\t\t\tswitch status {\n\t\t\t\t\tcase \"SUCCESS\":\n\t\t\t\t\t\treturn resp.Success\n\t\t\t\t\tcase \"FAILURE\":\n\t\t\t\t\t\treturn resp.Failure\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t// TODO(hinoka): Also implement the other status types.\n\t\t\t\t\t\treturn resp.InfraFailure\n\t\t\t\t\t}\n\t\t\t\t}(b.UserStatus),\n\t\t\t\t// TODO(martiniss): Implement summary text.\n\t\t\t\tText: []string{\"Coming Soon....\"},\n\t\t\t},\n\t\t\t// TODO(hinoka/martiniss): Also get the repo so it's a real sourcestamp so\n\t\t\t// that the commit can be linkable.\n\t\t\tSourceStamp: &resp.SourceStamp{\n\t\t\t\tCommit: resp.Commit{\n\t\t\t\t\tRevision: b.Revisions[0].Digest,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tresult = append(result, &resp.BuildRef{\n\t\t\tURL: func(url string) string {\n\t\t\t\tr, err := regexp.Compile(\".*/builds/(\\\\d+)/.*\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\treturn r.FindStringSubmatch(url)[1]\n\t\t\t}(b.BuildLogKey),\n\t\t\tBuild: mb,\n\t\t})\n\t}\n\treturn result, nil\n}", "func GetBuilds() ([]Build, error) {\n\turl := fmt.Sprintf(\"https://%s.visualstudio.com/%s/_apis/build/builds?api-version=5.0-preview.4\", TenantName, ProjectName)\n\tbody, err := rest.Get(url, accessToken)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar builds buildList\n\tif err := json.Unmarshal(body, &builds); err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to unmarshal Build JSON, %v\", err)\n\t}\n\n\tlog.Printf(\"Received %v builds\", builds.Count)\n\treturn builds.Value, nil\n}", "func getBuildList(build model.Build, cs *cloudbuild.Service) model.Build {\n\n\tprojectId := build.ProjectID\n\trespBuildList, err := cs.Projects.Builds.List(projectId).Do()\n\tif err != nil {\n\t\tfmt.Printf(\"error: \" + err.Error())\n\t}\n\tfor i := 0; i < len(respBuildList.Builds); i++ {\n\t\t//fmt.Println(respBuildList.Builds[i].SourceProvenance.ResolvedRepoSource.CommitSha)\n\t\tif respBuildList.Builds[i].SourceProvenance.ResolvedRepoSource.CommitSha == build.CommitID {\n\t\t\tbuild.BuildID = respBuildList.Builds[i].Id\n\t\t\tbuild.BuildStatus = respBuildList.Builds[i].Status\n\t\t\tbuild.ImageID = respBuildList.Builds[i].Artifacts.Images[0]\n\t\t\treturn build\n\t\t}\n\t}\n\tfmt.Println(\"Build Details Not Found\")\n\tbuild.BuildID = \"0\"\n\treturn build\n}", "func getBuilds(\n\tc context.Context, masterName, builderName string, finished bool, limit int, cursor *datastore.Cursor) (\n\t[]*resp.BuildSummary, *datastore.Cursor, error) {\n\n\t// TODO(hinoka): Builder specific structs.\n\tresult := []*resp.BuildSummary{}\n\tq := datastore.NewQuery(\"buildbotBuild\")\n\tq = q.Eq(\"finished\", finished)\n\tq = q.Eq(\"master\", masterName)\n\tq = q.Eq(\"builder\", builderName)\n\tq = q.Order(\"-number\")\n\tif cursor != nil {\n\t\tq = q.Start(*cursor)\n\t}\n\tbuildbots, nextCursor, err := runBuildsQuery(c, q, int32(limit))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfor _, b := range buildbots {\n\t\tresult = append(result, getBuildSummary(b))\n\t}\n\treturn result, nextCursor, nil\n}", "func ListBuildSummaries(settings *playfab.Settings, postData *ListBuildSummariesRequestModel, entityToken string) (*ListBuildSummariesResponseModel, 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/ListBuildSummaries\", \"X-EntityToken\", entityToken)\n if err != nil {\n return nil, err\n }\n \n result := &ListBuildSummariesResponseModel{}\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 (c Builds) Index() revel.Result {\n\tvar rbuilds []models.BuildedPackage\n\tvar builds []models.BuildedPackage\n\n\twhere := \"pushed='false' AND is_blocked_to_push='false'\"\n\n\tcurrentUser := connected(c.RenderArgs, c.Session)\n\tif currentUser != nil {\n\t\tif currentUser.UserGroup < models.GroupPusher {\n\t\t\tvar owner models.Owner\n\t\t\tctx := dbgorm.Db.First(&owner, \"owner_name=?\", currentUser.UserName)\n\t\t\tif ctx.Error == nil {\n\t\t\t\twhere = fmt.Sprintf(\"%s AND owner_id='%d'\", where, owner.ID)\n\t\t\t} else {\n\t\t\t\twhere = fmt.Sprintf(\"%s AND owner_id=-1\", where)\n\t\t\t\tc.Flash.Error(\"Not found owner with name: %s\", currentUser.UserName)\n\t\t\t}\n\t\t}\n\t}\n\tdbgorm.Db.Order(\"build_id DESC\", true).Find(&rbuilds, where)\n\n\tfor _, build := range rbuilds {\n\t\tdbgorm.Db.Model(&build).Related(&build.BuildPackage, \"BuildPackage\")\n\t\tdbgorm.Db.Model(&build).Related(&build.Owner, \"Owner\")\n\t\tdbgorm.Db.Model(&build).Related(&build.User, \"PushUser\")\n\t\tdbgorm.Db.Model(&build).Related(&build.PushRepoType, \"PushRepoType\")\n\t\tbuilds = append(builds, build)\n\t}\n\n\tvar branches []models.RepoType\n\tdbgorm.Db.Order(\"rt_name ASC\", true).Find(&branches)\n\n\treturn c.Render(builds, currentUser, branches)\n}", "func ExecuteBuilds(kubeAccess KubeAccess, namingCfg NamingConfig, buildCfg BuildConfig, count int) ([]Result, error) {\n\n\tvar errors = make(chan error, count)\n\tvar wg sync.WaitGroup\n\twg.Add(count)\n\n\tvar buildResults = make([]Result, count)\n\tfor i := 0; i < count; i++ {\n\t\tgo func(idx int) {\n\t\t\tdefer wg.Done()\n\n\t\t\tnamespace, name := createNamespaceAndName(namingCfg, buildCfg, idx)\n\n\t\t\tbuildSpec, err := createBuildSpec(name, buildCfg)\n\t\t\tif err != nil {\n\t\t\t\terrors <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tbuildAnnotations := createBuildAnnotations(buildCfg)\n\n\t\t\tresult, err := registerSingleBuild(\n\t\t\t\tkubeAccess,\n\t\t\t\tnamespace,\n\t\t\t\tname,\n\t\t\t\t*buildSpec,\n\t\t\t\tbuildAnnotations,\n\t\t\t\tGenerateServiceAccount(buildCfg.GenerateServiceAccount),\n\t\t\t\tSkipDelete(buildCfg.SkipDelete),\n\t\t\t)\n\n\t\t\tif err != nil {\n\t\t\t\terrors <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tbuildResults[idx] = *result\n\t\t}(i)\n\t}\n\n\twg.Wait()\n\tclose(errors)\n\n\treturn buildResults, wrapErrorChanResults(errors, \"failed to execute buildruns\")\n}", "func (a *Client) ServeAllBuilds(params *ServeAllBuildsParams, authInfo runtime.ClientAuthInfoWriter) (*ServeAllBuildsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewServeAllBuildsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"serveAllBuilds\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/app/rest/builds\",\n\t\tProducesMediaTypes: []string{\"application/json\", \"application/xml\", \"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/xml\", \"text/plain\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ServeAllBuildsReader{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.(*ServeAllBuildsOK), nil\n\n}", "func getBuilds(c *config, ch chan Build) {\n\tjobs := []string{}\n\tnumbers := []int{}\n\tb := Build{}\n\n\tfor {\n\t\tjobs = listJobs(c)\n\n\t\tfor _, job := range jobs {\n\t\t\tnumbers = listBuildNumbers(c, job) // []int\n\n\t\t\tfor _, num := range numbers {\n\t\t\t\t_, b = getBuild(c, job, num) // (int, Build)\n\t\t\t\tch <- b\n\t\t\t}\n\t\t}\n\t\tsleep(c.Common.Interval)\n\t}\n}", "func listBuildNumbers(c *config, job string) []int {\n\tbuilds := BuildNums{}\n\tresult := []int{}\n\n\turl := fmt.Sprintf(jobURL, c.Jenkins.Url, job)\n\tcode, b := jenkinsGet(url, c.Jenkins.User, c.Jenkins.Password, c.Jenkins.Verify)\n\n\tif code != 200 {\n\t\tlog.Printf(\"List builds: response code: %d\", code)\n\t\treturn result\n\t}\n\n\terr := json.Unmarshal(b, &builds)\n\tlogFatal(\"List builds: json\", err)\n\n\tfor _, build := range builds.Builds {\n\t\tresult = append(result, build.Number)\n\t}\n\n\treturn result\n}", "func (client *BuildServiceClient) listBuildsCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, options *BuildServiceClientListBuildsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter serviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serviceName}\", url.PathEscape(serviceName))\n\tif buildServiceName == \"\" {\n\t\treturn nil, errors.New(\"parameter buildServiceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{buildServiceName}\", url.PathEscape(buildServiceName))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func GetConsoleBuilds(\n\tc context.Context, builders []resp.BuilderRef, commits []string) (\n\t[][]*resp.ConsoleBuild, error) {\n\n\tresults := make([][]*resp.ConsoleBuild, len(commits))\n\tfor i := range results {\n\t\tresults[i] = make([]*resp.ConsoleBuild, len(builders))\n\t}\n\t// HACK(hinoka): This fetches 25 full builds and then filters them. Replace this\n\t// with something more reasonable.\n\t// This is kind of a hack but it's okay for now.\n\terr := parallel.FanOutIn(func(taskC chan<- func() error) {\n\t\tfor i, builder := range builders {\n\t\t\ti := i\n\t\t\tbuilder := builder\n\t\t\tbuilderComponents := strings.SplitN(builder.Name, \"/\", 2)\n\t\t\tif len(builderComponents) != 2 {\n\t\t\t\ttaskC <- func() error {\n\t\t\t\t\treturn fmt.Errorf(\"%s is an invalid builder name\", builder.Name)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tmaster := builderComponents[0]\n\t\t\tbuilderName := builderComponents[1]\n\t\t\ttaskC <- func() error {\n\t\t\t\tt1 := clock.Now(c)\n\t\t\t\tbuilds, err := getFullBuilds(c, master, builderName, true)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tt2 := clock.Now(c)\n\t\t\t\tvar currentStatus *model.Status\n\t\t\t\tfor j, commit := range commits {\n\t\t\t\t\tfor _, build := range builds {\n\t\t\t\t\t\tif build.Sourcestamp.Revision == commit {\n\t\t\t\t\t\t\tresults[j][i] = &resp.ConsoleBuild{\n\t\t\t\t\t\t\t\tLink: resp.NewLink(\n\t\t\t\t\t\t\t\t\tstrings.Join(build.Text, \" \"),\n\t\t\t\t\t\t\t\t\tfmt.Sprintf(\"/buildbot/%s/%s/%d\", master, builderName, build.Number),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tStatus: build.toStatus(),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcurrentStatus = &results[j][i].Status\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif currentStatus != nil && results[j][i] == nil {\n\t\t\t\t\t\tresults[j][i] = &resp.ConsoleBuild{Status: *currentStatus}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlog.Debugf(c,\n\t\t\t\t\t\"Builder %s took %s to query, %s to compute.\", builderName,\n\t\t\t\t\tt2.Sub(t1), clock.Since(c, t2))\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t})\n\treturn results, err\n}", "func FmtBuilds(builds []*types.Repository, log *xlog.Logger) {\n\t//detail,err := s.Codehost.Detail.GetCodehostDetail(build.JobCtx.Builds)\n\tfor _, repo := range builds {\n\t\tcId := repo.CodehostID\n\t\tif cId == 0 {\n\t\t\tlog.Error(\"codehostID can't be empty\")\n\t\t\treturn\n\t\t}\n\t\topt := &codehost.CodeHostOption{\n\t\t\tCodeHostID: cId,\n\t\t}\n\t\tdetail, err := codehost.GetCodeHostInfo(opt)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t\trepo.Source = detail.Type\n\t\trepo.OauthToken = detail.AccessToken\n\t\trepo.Address = detail.Address\n\t}\n}", "func (as *AnnotationsService) ListByBuild(org string, pipeline string, build string, opt *AnnotationListOptions) ([]Annotation, *Response, error) {\n\tvar u string\n\n\tu = fmt.Sprintf(\"v2/organizations/%s/pipelines/%s/builds/%s/annotations\", org, pipeline, build)\n\tu, err := addOptions(u, opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := as.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tannotations := new([]Annotation)\n\tresp, err := as.client.Do(req, annotations)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn *annotations, resp, err\n}", "func (client *BuildServiceClient) listBuildsHandleResponse(resp *http.Response) (BuildServiceClientListBuildsResponse, error) {\n\tresult := BuildServiceClientListBuildsResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.BuildCollection); err != nil {\n\t\treturn BuildServiceClientListBuildsResponse{}, err\n\t}\n\treturn result, nil\n}", "func cmdListReleases(ccmd *cobra.Command, args []string) {\n\taplSvc := apl.NewClient()\n\toutput := runListCommand(&releaseParams, aplSvc.Releases.List)\n\tif output != nil {\n\t\tfields := []string{\"ID\", \"StackID\", \"Version\", \"CreatedTime\"}\n\t\tprintTableResultsCustom(output.([]apl.Release), fields)\n\t}\n}", "func (c *rethinkClient) watchBuilds() error {\n\tcursor, err := r.Table(buildTable).Changes().Run(c.session)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\tvar model BuildModel\n\t\t// TODO: use channel and cursor.Listen instead?\n\t\t// TODO: check if new or updated or deleted\n\t\t// i.e. newValue != nil, oldValue != nil\n\t\tfor cursor.Next(&model) {\n\t\t\tbuild.Enqueue(&build.Build{\n\t\t\t// TODO: fill this in\n\t\t\t})\n\t\t}\n\t}()\n\treturn nil\n}", "func (a *Client) ListTriggerRecentBuilds(params *ListTriggerRecentBuildsParams, authInfo runtime.ClientAuthInfoWriter) (*ListTriggerRecentBuildsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListTriggerRecentBuildsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"listTriggerRecentBuilds\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/repository/{repository}/trigger/{trigger_uuid}/builds\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListTriggerRecentBuildsReader{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.(*ListTriggerRecentBuildsOK)\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 listTriggerRecentBuilds: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *Client) SearchBuilds(ctx context.Context, in *bbpb.SearchBuildsRequest, opts ...grpc.CallOption) (*bbpb.SearchBuildsResponse, error) {\n\tif in.GetPredicate() != nil {\n\t\tvar notSupportedPredicates []string\n\t\tin.GetPredicate().ProtoReflect().Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {\n\t\t\tif v.IsValid() && !supportedPredicates.Has(string(fd.Name())) {\n\t\t\t\tnotSupportedPredicates = append(notSupportedPredicates, string(fd.Name()))\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\tif len(notSupportedPredicates) > 0 {\n\t\t\treturn nil, status.Errorf(codes.InvalidArgument, \"predicates [%s] are not supported\", strings.Join(notSupportedPredicates, \", \"))\n\t\t}\n\t}\n\tvar lastReturnedBuildID int64\n\tif token := in.GetPageToken(); token != \"\" {\n\t\tvar err error\n\t\tlastReturnedBuildID, err = strconv.ParseInt(token, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid token %q, expecting a build ID\", token)\n\t\t}\n\t}\n\tcandidates := make([]*bbpb.Build, 0, len(c.fa.buildStore))\n\tc.fa.iterBuildStore(func(build *bbpb.Build) {\n\t\tcandidates = append(candidates, build)\n\t})\n\tsort.Slice(candidates, func(i, j int) bool {\n\t\treturn candidates[i].Id < candidates[j].Id\n\t})\n\tpageSize := in.GetPageSize()\n\tif pageSize == 0 {\n\t\tpageSize = defaultSearchPageSize\n\t}\n\tresBuilds := make([]*bbpb.Build, 0, pageSize)\n\tfor _, b := range candidates {\n\t\tif c.shouldIncludeBuild(b, in.GetPredicate(), lastReturnedBuildID) {\n\t\t\tif err := applyMask(b, in.GetMask()); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresBuilds = append(resBuilds, b)\n\t\t\tif len(resBuilds) == int(pageSize) {\n\t\t\t\treturn &bbpb.SearchBuildsResponse{\n\t\t\t\t\tBuilds: resBuilds,\n\t\t\t\t\tNextPageToken: strconv.FormatInt(b.Id, 10),\n\t\t\t\t}, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn &bbpb.SearchBuildsResponse{Builds: resBuilds}, nil\n}", "func (c *Client) Builds(namespace string) BuildInterface {\n\treturn &Builds{ns: namespace, host: c.host, token: c.token, restClient: c.restClient}\n}", "func BuildConfigBuilds(c buildlister.BuildLister, namespace, name string, filterFunc buildFilter) ([]*buildapi.Build, error) {\n\tresult, err := c.Builds(namespace).List(BuildConfigSelector(name))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif filterFunc == nil {\n\t\treturn result, nil\n\t}\n\tvar filteredList []*buildapi.Build\n\tfor _, b := range result {\n\t\tif filterFunc(b) {\n\t\t\tfilteredList = append(filteredList, b)\n\t\t}\n\t}\n\treturn filteredList, nil\n}", "func GetBuilds(client *circleci.Client, b github.Branch) (builds []*circleci.Build, err error) {\n\tif b.Account == \"\" {\n\t\terr = errors.New(\"Cannot get builds for empty branch\")\n\t\treturn\n\t}\n\n\treturn client.ListRecentBuildsForProject(\n\t\tb.Account,\n\t\tb.Repo,\n\t\tb.Branch,\n\t\t\"\",\n\t\t-1,\n\t\t0,\n\t)\n}", "func (c *Client) List() ([]*release.Release, error) {\n\tlist := action.NewList(c.actionConfig)\n\treturn list.Run()\n}", "func (c *client) List() ([]Buildpack, error) {\n\tcfg, err := c.fetchConfig()\n\tif err != nil || cfg == nil {\n\t\treturn nil, err\n\t}\n\n\tvar order struct {\n\t\tBuildpacks []Buildpack `json:\"buildpacks\"`\n\t}\n\tif err := json.NewDecoder(strings.NewReader(cfg.Config.Labels[metadataLabel])).Decode(&order); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn order.Buildpacks, nil\n}", "func (client *BuildServiceClient) NewListBuildsPager(resourceGroupName string, serviceName string, buildServiceName string, options *BuildServiceClientListBuildsOptions) *runtime.Pager[BuildServiceClientListBuildsResponse] {\n\treturn runtime.NewPager(runtime.PagingHandler[BuildServiceClientListBuildsResponse]{\n\t\tMore: func(page BuildServiceClientListBuildsResponse) bool {\n\t\t\treturn page.NextLink != nil && len(*page.NextLink) > 0\n\t\t},\n\t\tFetcher: func(ctx context.Context, page *BuildServiceClientListBuildsResponse) (BuildServiceClientListBuildsResponse, error) {\n\t\t\tvar req *policy.Request\n\t\t\tvar err error\n\t\t\tif page == nil {\n\t\t\t\treq, err = client.listBuildsCreateRequest(ctx, resourceGroupName, serviceName, buildServiceName, options)\n\t\t\t} else {\n\t\t\t\treq, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn BuildServiceClientListBuildsResponse{}, err\n\t\t\t}\n\t\t\tresp, err := client.internal.Pipeline().Do(req)\n\t\t\tif err != nil {\n\t\t\t\treturn BuildServiceClientListBuildsResponse{}, err\n\t\t\t}\n\t\t\tif !runtime.HasStatusCode(resp, http.StatusOK) {\n\t\t\t\treturn BuildServiceClientListBuildsResponse{}, runtime.NewResponseError(resp)\n\t\t\t}\n\t\t\treturn client.listBuildsHandleResponse(resp)\n\t\t},\n\t})\n}", "func (c *ci) ListJobs(refreshResult, buildResult bool) *format.ListResponse {\n\n\tjs := make([]*format.Job, 0, len(c.jobs))\n\tfor _, j := range c.jobs {\n\t\tjs = append(js, j.Status(refreshResult, buildResult))\n\t}\n\n\treturn &format.ListResponse{\n\t\tJobs: js,\n\t}\n}", "func (c *ci) ListJobs(refreshResult, buildResult bool) *format.ListResponse {\n\n\t//make and fill the slice\n\tjs := make([]*format.Job, 0, len(c.jobs))\n\tfor _, j := range c.jobs {\n\t\tjs = append(js, j.Status(refreshResult, buildResult))\n\t}\n\n\treturn &format.ListResponse{\n\t\tJobs: js,\n\t}\n}", "func ListVersion(w http.ResponseWriter, r *http.Request) {\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\tv := version.Model{\n\t\tRelease: version.Release,\n\t\tCommit: version.Commit,\n\t\tBuildTime: version.BuildTime,\n\t\tGO: version.GO,\n\t\tCompiler: version.Compiler,\n\t\tOS: version.OS,\n\t\tArch: version.Arch,\n\t}\n\n\toutput, err := json.MarshalIndent(v, \"\", \" \")\n\tif err != nil {\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\trespondOK(w, output)\n\n}", "func BuildPackageList(d *http.Response) PackageList {\n\tpkgs := PackageList{}\n\tjson.NewDecoder(d.Body).Decode(&pkgs)\n\tdefer d.Body.Close()\n\n\treturn pkgs\n\n}", "func (s *service) GetProjectBuilds(project *brigademodel.Project, desc bool) ([]*brigademodel.Build, error) {\n\tpr, err := s.client.GetProject(project.ID)\n\tif err != nil {\n\t\treturn []*brigademodel.Build{}, err\n\t}\n\n\tbuilds, err := s.client.GetProjectBuilds(pr)\n\tif err != nil {\n\t\treturn []*brigademodel.Build{}, err\n\t}\n\n\tres := make([]*brigademodel.Build, len(builds))\n\tfor i, build := range builds {\n\t\tbl := brigademodel.Build(*build)\n\t\tres[i] = &bl\n\t}\n\n\t// TODO: Should we improve the sorting algorithm?\n\t// Make a first sort by ID so in equality of time always is the same order on every case.\n\t// Doesn't matter the order at all is for consistency when start time is the same.\n\tsort.SliceStable(res, func(i, j int) bool {\n\t\treturn res[i].ID < res[j].ID\n\t})\n\n\t// Split phantom jobs and builds.\n\tphantomBs := []*brigademodel.Build{}\n\tgoodBs := []*brigademodel.Build{}\n\tfor _, b := range res {\n\t\tb := b\n\t\tif b.Worker == nil {\n\t\t\tphantomBs = append(phantomBs, b)\n\t\t} else {\n\t\t\tgoodBs = append(goodBs, b)\n\t\t}\n\t}\n\n\t// Order builds in descending order (last ones first).\n\tsort.SliceStable(goodBs, func(i, j int) bool {\n\t\tif desc {\n\t\t\treturn goodBs[i].Worker.StartTime.After(goodBs[j].Worker.StartTime)\n\t\t}\n\t\treturn goodBs[i].Worker.StartTime.Before(goodBs[j].Worker.StartTime)\n\t})\n\n\t// Append phantom to the end.\n\tfor _, pb := range phantomBs {\n\t\tpb := pb\n\t\tgoodBs = append(goodBs, pb)\n\t}\n\n\treturn goodBs, nil\n}", "func (c *Client) List(p ListParameters) ([]Release, error) {\n\tresponse, err := c.client.ListReleases(p.Options()...) // TODO Paging.\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tvar releases []Release\n\tif response != nil && response.Releases != nil {\n\t\tfor _, item := range response.Releases {\n\t\t\treleases = append(releases, *(fromHelm(item)))\n\t\t}\n\t}\n\treturn releases, nil\n}", "func ListProductionsCommand(c *cli.Context) error {\n\n\tl, err := client.Productions()\n\tif err != nil {\n\t\tprintError(c, err)\n\t\treturn nil\n\t}\n\n\tif len(l.Productions) == 0 {\n\t\tfmt.Println(\"No shows to list.\")\n\t} else {\n\t\tfmt.Println(productionListing(\"GUID\", \"NAME\", \"TITLE\", false))\n\t\tfor _, details := range l.Productions {\n\t\t\tif details.GUID == client.GUID {\n\t\t\t\tfmt.Println(productionListing(details.GUID, details.Name, details.Title, true))\n\t\t\t} else {\n\t\t\t\tfmt.Println(productionListing(details.GUID, details.Name, details.Title, false))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func getFullBuilds(c context.Context, masterName, builderName string, finished bool) ([]*buildbotBuild, error) {\n\t// TODO(hinoka): Builder specific structs.\n\tq := ds.NewQuery(\"buildbotBuild\")\n\tq = q.Eq(\"finished\", finished)\n\tq = q.Eq(\"master\", masterName)\n\tq = q.Eq(\"builder\", builderName)\n\tq = q.Order(\"-number\")\n\tq.Finalize()\n\t// Ignore the cursor, we don't need it.\n\tbuildbots, _, err := runBuildsQuery(c, q, 25)\n\treturn buildbots, err\n}", "func (r *Router) LoadProjectBuildList(projectID string) {\n\tr.projectBuildListPage.BeforeLoad()\n\tr.projectBuildListPage.Refresh(projectID)\n\tr.pages.SwitchToPage(ProjectBuildListPageName)\n}", "func (a *Client) ListBuildTriggers(params *ListBuildTriggersParams, authInfo runtime.ClientAuthInfoWriter) (*ListBuildTriggersOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListBuildTriggersParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"listBuildTriggers\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/repository/{repository}/trigger/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListBuildTriggersReader{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.(*ListBuildTriggersOK)\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 listBuildTriggers: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (r *Router) LoadBuildJobList(projectID, buildID string) {\n\tr.buildJobListPage.BeforeLoad()\n\tr.buildJobListPage.Refresh(projectID, buildID)\n\tr.pages.SwitchToPage(BuildJobListPageName)\n}", "func ListJobs(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 countDefault int32\n\tcount := &countDefault\n\terr = flags.ParseFlag(cmd.Flags(), \"count\", &count)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"count\": ` + err.Error())\n\t}\n\tvar filter string\n\terr = flags.ParseFlag(cmd.Flags(), \"filter\", &filter)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"filter\": ` + err.Error())\n\t}\n\tvar status model.SearchStatus\n\terr = flags.ParseFlag(cmd.Flags(), \"status\", &status)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"status\": ` + err.Error())\n\t}\n\t// Form query params\n\tgenerated_query := model.ListJobsQueryParams{}\n\tgenerated_query.Count = count\n\tgenerated_query.Filter = filter\n\tgenerated_query.Status = status\n\n\t// Silence Usage\n\tcmd.SilenceUsage = true\n\n\tresp, err := client.SearchService.ListJobs(&generated_query)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjsonx.Pprint(cmd, resp)\n\treturn nil\n}", "func runBuildsQuery(c context.Context, q *datastore.Query, limit int32) (\n\t[]*buildbotBuild, *datastore.Cursor, error) {\n\n\tif limit != 0 {\n\t\tq = q.Limit(limit)\n\t}\n\tbuilds := make([]*buildbotBuild, 0, limit)\n\tvar nextCursor *datastore.Cursor\n\terr := getBuildQueryBatcher(c).Run(\n\t\tc, q, func(build *buildbotBuild, getCursor datastore.CursorCB) error {\n\t\t\tbuilds = append(builds, build)\n\t\t\ttmpCursor, err := getCursor()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnextCursor = &tmpCursor\n\t\t\treturn nil\n\t\t})\n\treturn builds, nextCursor, err\n}", "func GetBuildings() ([]accessors.Building, error) {\n\tlog.Printf(\"getting all buildings...\")\n\turl := os.Getenv(\"CONFIGURATION_DATABASE_MICROSERVICE_ADDRESS\") + \"/buildings\"\n\tlog.Printf(url)\n\tvar buildings []accessors.Building\n\terr := GetData(url, &buildings)\n\n\treturn buildings, err\n}", "func List(c echo.Context) error {\n\tvar b [3]*Board\n\tb[0] = &Board {\n\t\tName: \"Jon\",\n\t\tDescription: \"this is jon board\",\n\t}\n\tb[1] = &Board {\n\t\tName: \"Doe\",\n\t\tDescription: \"this is doe board\",\n\t}\n\tb[2] = &Board {\n\t\tName: \"Tiger\",\n\t\tDescription: \"this is tiger board\",\n\t}\n\treturn c.JSONPretty(http.StatusOK, b, \" \")\n}", "func (hc *Actions) ListReleases() ([]api.Stack, error) {\n\tactList := action.NewList(hc.Config)\n\treleases, err := actList.Run()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := []api.Stack{}\n\tfor _, rel := range releases {\n\t\tresult = append(result, api.Stack{\n\t\t\tID: rel.Name,\n\t\t\tName: rel.Name,\n\t\t\tStatus: string(rel.Info.Status),\n\t\t})\n\t}\n\treturn result, nil\n}", "func list_versions(w rest.ResponseWriter, r *rest.Request) {\n\tarch := r.PathParam(\"arch\")\n\tversions := []string{\"nightly\", \"beta\", \"stable\"}\n\t// get the numbered versions available\n\tdb_directories := get_directories(cache_instance, db, arch)\n\tfor _, dir := range db_directories {\n\t\tversion_path := strings.Split(dir.Path, \"/\")\n\t\tversion := version_path[len(version_path)-1]\n\t\tif version != \"snapshots\" {\n\t\t\tversions = append(versions, version)\n\t\t}\n\t}\n\t// Filter things folders we don't want in the versions out\n\n\tw.WriteJson(versions)\n}", "func ListProductionsCommand(c *cli.Context) error {\n\tl, err := client.Productions()\n\tif err != nil {\n\t\tprintError(c, err)\n\t\treturn nil\n\t}\n\n\tif len(l.Productions) == 0 {\n\t\tfmt.Println(messagedef.MsgNoProductionsFound)\n\t} else {\n\t\tfmt.Println(productionListing(\"ID\", \"NAME\", \"TITLE\", false))\n\t\tfor _, details := range l.Productions {\n\t\t\tif details.GUID == client.DefaultProduction() {\n\t\t\t\tfmt.Println(productionListing(details.GUID, details.Name, details.Title, true))\n\t\t\t} else {\n\t\t\t\tfmt.Println(productionListing(details.GUID, details.Name, details.Title, false))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewAdoBuildListCommand(client *azuredevops.Client) *cobra.Command {\n\tvar opts ListOptions\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List all the builds\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts.flags = args\n\t\t\treturn ListBuilds(client, opts, os.Stdout)\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.StringVar(&opts.Branches, \"branches\", \"master\", \"Which branches should be displayed\")\n\n\treturn cmd\n}", "func (*ListBuildsRequest) Descriptor() ([]byte, []int) {\n\treturn file_versions_v1_versions_proto_rawDescGZIP(), []int{12}\n}", "func (*ListBuildsResponse) Descriptor() ([]byte, []int) {\n\treturn file_versions_v1_versions_proto_rawDescGZIP(), []int{13}\n}", "func (c Cache) Builds() Path {\n\treturn c.Join(\"builds\")\n}", "func (a *Client) DeleteBuilds(params *DeleteBuildsParams, authInfo runtime.ClientAuthInfoWriter) error {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteBuildsParams()\n\t}\n\n\t_, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"deleteBuilds\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/app/rest/builds\",\n\t\tProducesMediaTypes: []string{\"application/json\", \"application/xml\", \"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/xml\", \"text/plain\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &DeleteBuildsReader{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 err\n\t}\n\treturn nil\n\n}", "func getCurrentBuilds(master *buildbotMaster, builderName string) []*resp.BuildRef {\n\tb := master.Builders[builderName]\n\tresults := make([]*resp.BuildRef, len(b.Currentbuilds))\n\tbMap := createRunningBuildMap(master)\n\tfor i, bn := range b.Currentbuilds {\n\t\tresults[i] = getCurrentBuild(bMap, builderName, bn)\n\t}\n\treturn results\n}", "func (handler *Handler) BuildGetAllHandler(w http.ResponseWriter, r *http.Request) {\n\n\tbuilds, err := data.BuildGetAll()\n\n\tif err != nil {\n\t\trespondWithError(w, err.Error(), http.StatusInternalServerError)\n\t}\n\n\trespondWithJSON(w, http.StatusOK, builds)\n}", "func (client *BuildServiceClient) listBuildResultsCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, options *BuildServiceClientListBuildResultsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds/{buildName}/results\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter serviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serviceName}\", url.PathEscape(serviceName))\n\tif buildServiceName == \"\" {\n\t\treturn nil, errors.New(\"parameter buildServiceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{buildServiceName}\", url.PathEscape(buildServiceName))\n\tif buildName == \"\" {\n\t\treturn nil, errors.New(\"parameter buildName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{buildName}\", url.PathEscape(buildName))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (c *Client) BuildListRequest(ctx context.Context, v interface{}) (*http.Request, error) {\n\tu := &url.URL{Scheme: c.scheme, Host: c.host, Path: ListBlogPath()}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, goahttp.ErrInvalidURL(\"blog\", \"list\", u.String(), err)\n\t}\n\tif ctx != nil {\n\t\treq = req.WithContext(ctx)\n\t}\n\n\treturn req, nil\n}", "func List(params map[string]string) ([]RPMInfo, error) {\n\tlog.Printf(\"Entering repo::List(%v)\", params)\n\tdefer log.Println(\"Exiting repo::List\")\n\n\tproductVersion := params[\"productVersion\"]\n\n\tvar info []RPMInfo\n\n\tfiles, err := listRepo(params)\n\tif err != nil {\n\t\treturn info, err\n\t}\n\n\tinfo, err = ListRPMFilesInfo(files, productVersion)\n\tif err != nil {\n\t\treturn info, err\n\t}\n\n\toutput.Write(info)\n\n\treturn info, nil\n}", "func ListJobs(cmd CmdInterface) {\n\tqueue, err := store.FindQueueBySlug(cmd.Parts[1], cmd.User.CurrentGroup, false)\n\tif err != nil {\n\t\tReturnError(cmd, err.Error())\n\t\treturn\n\t}\n\n\trawJSON, _ := json.Marshal(queue.Jobs)\n\tReturnString(cmd, string(rawJSON))\n}", "func (c *ProjectService) List() ([]Project, *http.Response, error) {\n\tresponse := new(projectListResponse)\n\tapiError := new(APIError)\n\tresp, err := c.sling.New().Get(\"\").Receive(response, apiError)\n\treturn response.Results, resp, relevantError(err, *apiError)\n}", "func buildQueue(c *cli.Context) error {\n\n\tclient, err := newClient(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuilds, err := client.BuildQueue()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(builds) == 0 {\n\t\tfmt.Println(\"there are no pending or running builds\")\n\t\treturn nil\n\t}\n\n\ttmpl, err := template.New(\"_\").Parse(c.String(\"format\") + \"\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, build := range builds {\n\t\ttmpl.Execute(os.Stdout, build)\n\t}\n\treturn nil\n}", "func (cli *bkCli) projectList(quietList bool) error {\n\n\tt := time.Now()\n\n\tprojects, err := cli.listProjects()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif quietList {\n\t\tfor _, proj := range projects {\n\t\t\tfmt.Printf(\"%-36s\\n\", *proj.ID)\n\t\t}\n\t\treturn nil // we are done\n\t}\n\n\ttb := table.New(projectColumns)\n\tvals := make(map[string]interface{})\n\n\tfor _, proj := range projects {\n\t\tif proj.FeaturedBuild != nil {\n\t\t\tfb := proj.FeaturedBuild\n\t\t\tvals = utils.ToMap(projectColumns, []interface{}{*proj.ID, *proj.Name, *fb.Number, toString(fb.Branch), toString(fb.Message), toString(fb.State), valString(fb.FinishedAt)})\n\t\t} else {\n\t\t\tvals = utils.ToMap(projectColumns, []interface{}{*proj.ID, *proj.Name, 0, \"\", \"\", \"\", \"\"})\n\t\t}\n\t\ttb.AddRow(vals)\n\t}\n\ttb.Markdown = true\n\ttb.Print()\n\n\tfmt.Printf(\"\\nTime taken: %s\\n\", time.Now().Sub(t))\n\n\treturn err\n}", "func listJobs(w io.Writer, projectID string) error {\n\t// projectID := \"my-project-id\"\n\t// jobID := \"my-job-id\"\n\tctx := context.Background()\n\n\tclient, err := bigquery.NewClient(ctx, projectID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"bigquery.NewClient: %w\", err)\n\t}\n\tdefer client.Close()\n\n\tit := client.Jobs(ctx)\n\t// List up to 10 jobs to demonstrate iteration.\n\tfor i := 0; i < 10; i++ {\n\t\tj, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tstate := \"Unknown\"\n\t\tswitch j.LastStatus().State {\n\t\tcase bigquery.Pending:\n\t\t\tstate = \"Pending\"\n\t\tcase bigquery.Running:\n\t\t\tstate = \"Running\"\n\t\tcase bigquery.Done:\n\t\t\tstate = \"Done\"\n\t\t}\n\t\tfmt.Fprintf(w, \"Job %s in state %s\\n\", j.ID(), state)\n\t}\n\treturn nil\n}", "func (d *remoteDB) GetBuildsFromDateRange(start, end time.Time) ([]*Build, error) {\n\treq := &rpc.GetBuildsFromDateRangeRequest{\n\t\tStart: start.Format(time.RFC3339),\n\t\tEnd: end.Format(time.RFC3339),\n\t}\n\tresp, err := d.client.GetBuildsFromDateRange(context.Background(), req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trv := make([]*Build, 0, len(resp.Builds))\n\tfor _, build := range resp.Builds {\n\t\tvar b Build\n\t\tif err := gob.NewDecoder(bytes.NewBuffer(build.Build)).Decode(&b); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb.fixup()\n\t\trv = append(rv, &b)\n\t}\n\treturn rv, nil\n}", "func (w *Command) List() error {\n\tfmt.Println(\"Available bugs and their target versions:\")\n\treturn util.PrintList(w.NewGit, util.FixType, w.Short)\n}", "func (s *DashboardsService) List(ctx context.Context, organizationSlug string, params *ListCursorParams) ([]*Dashboard, *Response, error) {\n\tu := fmt.Sprintf(\"0/organizations/%v/dashboards/\", organizationSlug)\n\tu, err := addQuery(u, params)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar dashboards []*Dashboard\n\tresp, err := s.client.Do(ctx, req, &dashboards)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn dashboards, resp, nil\n}", "func (c *WorkItemBoardsController) List(ctx *app.ListWorkItemBoardsContext) error {\n\n\tvar boards []*workitem.Board\n\terr := application.Transactional(c.db, func(appl application.Application) error {\n\t\tlist, err := appl.Boards().List(ctx, ctx.SpaceTemplateID)\n\t\tif err != nil {\n\t\t\treturn errs.WithStack(err)\n\t\t}\n\t\tboards = list\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn jsonapi.JSONErrorResponse(ctx, err)\n\t}\n\tres := &app.WorkItemBoardList{\n\t\tData: make([]*app.WorkItemBoardData, len(boards)),\n\t\tLinks: &app.WorkItemBoardLinks{\n\t\t\tSelf: rest.AbsoluteURL(ctx.Request, app.SpaceTemplateHref(ctx.SpaceTemplateID)) + \"/\" + APIWorkItemBoards,\n\t\t},\n\t}\n\tfor i, board := range boards {\n\t\tres.Data[i] = ConvertBoardFromModel(ctx.Request, *board)\n\t\tfor _, column := range board.Columns {\n\t\t\tres.Included = append(res.Included, ConvertColumnsFromModel(ctx.Request, column))\n\t\t}\n\t}\n\treturn ctx.OK(res)\n}", "func BCList(bcs ...buildapi.BuildConfig) buildapi.BuildConfigList {\n\treturn buildapi.BuildConfigList{\n\t\tItems: bcs,\n\t}\n}", "func ListJobs(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\t// error handling\n\t\t\tErrorLog(fmt.Sprintf(\"Web list jobs Error: %s\\n\", err))\n\t\t\terrMsg := fmt.Sprintf(\"Error: %s\", err)\n\t\t\thttp.Error(w, errMsg, http.StatusInternalServerError)\n\t\t\tAccessLog(r, http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tif r.Method == \"GET\" {\n\t\tif !isLogin(r) {\n\t\t\tLogin(w, r)\n\t\t\treturn\n\t\t}\n\t\tret := JobsOutPut{}\n\t\tApiUrl := fmt.Sprintf(\"%s/jobs\", WEB.ApiUrl)\n\t\tretJson, err := HttpGet(ApiUrl, nil, BASIC_AUTH.User, BASIC_AUTH.Pass)\n\t\terr = json.Unmarshal(retJson, &ret)\n\t\tCheckErr(err)\n\t\t//ErrorLog(ret)\n\t\tif ret.Status != \"OK\" {\n\t\t\tCheckErr(fmt.Errorf(\"%s\", ret.Status))\n\t\t}\n\n\t\tt, err := template.ParseFiles(WEB.TemplatePath+\"/listjobs.html\", WEB.TemplatePath+\"/header.html\", WEB.TemplatePath+\"/footer.html\")\n\t\tCheckErr(err)\n\t\t//err = templates.Execute(w, ret)\n\t\terr = t.Execute(w, ret)\n\t\tCheckErr(err)\n\n\t} else {\n\t\tCheckErr(fmt.Errorf(\"Sorry: Only Accept GET Method\"))\n\t}\n\tAccessLog(r, http.StatusOK)\n\treturn\n}", "func listJobs(c *config) []string {\n\turl := fmt.Sprintf(jobsURL, c.Jenkins.Url)\n\tcode, b := jenkinsGet(url, c.Jenkins.User, c.Jenkins.Password, c.Jenkins.Verify)\n\n\tif code != 200 {\n\t\tlog.Fatalf(\"List jobs: response code: %d\", code)\n\t}\n\n\tjobs := Jobs{}\n\tres := []string{}\n\n\te := json.Unmarshal(b, &jobs)\n\tlogFatal(\"List jobs: json\", e)\n\n\tfor _, j := range jobs.Jobs {\n\t\tres = append(res, j.Name)\n\t}\n\n\treturn res\n}", "func buildPipelineListCmd() *cobra.Command {\n\tvars := listPipelineVars{}\n\tcmd := &cobra.Command{\n\t\tUse: \"ls\",\n\t\tShort: \"Lists all the deployed pipelines in an application.\",\n\t\tExample: `\n Lists all the pipelines for the frontend application.\n /code $ copilot pipeline ls -a frontend`,\n\t\tRunE: runCmdE(func(cmd *cobra.Command, args []string) error {\n\t\t\topts, err := newListPipelinesOpts(vars)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := opts.Ask(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn opts.Execute()\n\t\t}),\n\t}\n\n\tcmd.Flags().StringVarP(&vars.appName, appFlag, appFlagShort, tryReadingAppName(), appFlagDescription)\n\tcmd.Flags().BoolVar(&vars.shouldOutputJSON, jsonFlag, false, jsonFlagDescription)\n\treturn cmd\n}", "func (s *workspaces) List(ctx context.Context, organization string, options *WorkspaceListOptions) (*WorkspaceList, error) {\n\tif !validStringID(&organization) {\n\t\treturn nil, ErrInvalidOrg\n\t}\n\tif err := options.valid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := fmt.Sprintf(\"organizations/%s/workspaces\", url.QueryEscape(organization))\n\treq, err := s.client.NewRequest(\"GET\", u, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twl := &WorkspaceList{}\n\terr = req.Do(ctx, wl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn wl, nil\n}", "func LogsList(number string) error {\n\tcli, err := newBkCli()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cli.tailLogs(number)\n}", "func getRelatedBuilds(c context.Context, now *timestamppb.Timestamp, client buildbucketpb.BuildsClient, b *buildbucketpb.Build) ([]*ui.Build, error) {\n\tvar bs []string\n\tfor _, buildset := range protoutil.BuildSets(b) {\n\t\t// HACK(hinoka): Remove the commit/git/ buildsets because we know they're redundant\n\t\t// with the commit/gitiles/ buildsets, and we don't need to ask Buildbucket twice.\n\t\tif strings.HasPrefix(buildset, \"commit/git/\") {\n\t\t\tcontinue\n\t\t}\n\t\tbs = append(bs, buildset)\n\t}\n\tif len(bs) == 0 {\n\t\t// No buildset? No builds.\n\t\treturn nil, nil\n\t}\n\n\t// Do the search request.\n\t// Use multiple requests instead of a single batch request.\n\t// A single large request is CPU bound to a single GAE instance on the buildbucket side.\n\t// Multiple requests allows the use of multiple GAE instances, therefore more parallelism.\n\tresps := make([]*buildbucketpb.SearchBuildsResponse, len(bs))\n\tif err := parallel.WorkPool(8, func(ch chan<- func() error) {\n\t\tfor i, buildset := range bs {\n\t\t\ti := i\n\t\t\tbuildset := buildset\n\t\t\tch <- func() (err error) {\n\t\t\t\tlogging.Debugf(c, \"Searching for %s (%d)\", buildset, i)\n\t\t\t\tresps[i], err = client.SearchBuilds(c, searchBuildset(buildset, summaryBuildsMask))\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Dedupe builds.\n\t// It's possible since we've made multiple requests that we got back the same builds\n\t// multiple times.\n\tseen := map[int64]bool{} // set of build IDs.\n\tresult := []*ui.Build{}\n\tfor _, resp := range resps {\n\t\tfor _, rb := range resp.GetBuilds() {\n\t\t\tif seen[rb.Id] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tseen[rb.Id] = true\n\t\t\tresult = append(result, &ui.Build{\n\t\t\t\tBuild: rb,\n\t\t\t\tNow: now,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Sort builds by ID.\n\tsort.Slice(result, func(i, j int) bool { return result[i].Id < result[j].Id })\n\n\treturn result, nil\n}", "func ListReleases(ctx *context.APIContext) {\n\t// swagger:operation GET /repos/{owner}/{repo}/releases repository repoListReleases\n\t// ---\n\t// summary: List a repo's releases\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: draft\n\t// in: query\n\t// description: filter (exclude / include) drafts, if you dont have repo write access none will show\n\t// type: boolean\n\t// - name: pre-release\n\t// in: query\n\t// description: filter (exclude / include) pre-releases\n\t// type: boolean\n\t// - name: per_page\n\t// in: query\n\t// description: page size of results, deprecated - use limit\n\t// type: integer\n\t// deprecated: true\n\t// - name: page\n\t// in: query\n\t// description: page number of results to return (1-based)\n\t// type: integer\n\t// - name: limit\n\t// in: query\n\t// description: page size of results\n\t// type: integer\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/ReleaseList\"\n\tlistOptions := utils.GetListOptions(ctx)\n\tif listOptions.PageSize == 0 && ctx.FormInt(\"per_page\") != 0 {\n\t\tlistOptions.PageSize = ctx.FormInt(\"per_page\")\n\t}\n\n\topts := repo_model.FindReleasesOptions{\n\t\tListOptions: listOptions,\n\t\tIncludeDrafts: ctx.Repo.AccessMode >= perm.AccessModeWrite || ctx.Repo.UnitAccessMode(unit.TypeReleases) >= perm.AccessModeWrite,\n\t\tIncludeTags: false,\n\t\tIsDraft: ctx.FormOptionalBool(\"draft\"),\n\t\tIsPreRelease: ctx.FormOptionalBool(\"pre-release\"),\n\t}\n\n\treleases, err := repo_model.GetReleasesByRepoID(ctx, ctx.Repo.Repository.ID, opts)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetReleasesByRepoID\", err)\n\t\treturn\n\t}\n\trels := make([]*api.Release, len(releases))\n\tfor i, release := range releases {\n\t\tif err := release.LoadAttributes(ctx); err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"LoadAttributes\", err)\n\t\t\treturn\n\t\t}\n\t\trels[i] = convert.ToAPIRelease(ctx, ctx.Repo.Repository, release)\n\t}\n\n\tfilteredCount, err := repo_model.CountReleasesByRepoID(ctx.Repo.Repository.ID, opts)\n\tif err != nil {\n\t\tctx.InternalServerError(err)\n\t\treturn\n\t}\n\n\tctx.SetLinkHeader(int(filteredCount), listOptions.PageSize)\n\tctx.SetTotalCountHeader(filteredCount)\n\tctx.JSON(http.StatusOK, rels)\n}", "func (g Gitlab) List(ctx context.Context) ([]string, error) {\n\tclient, err := gitlab.NewClient(\n\t\tg.Token,\n\t\tgitlab.WithBaseURL(g.URL),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"List: %w\", err)\n\t}\n\n\t// TODO: pagination\n\trepos, resp, err := client.Projects.ListProjects(\n\t\t&gitlab.ListProjectsOptions{\n\t\t\tVisibility: gitlab.Visibility(gitlab.PrivateVisibility),\n\t\t},\n\t\tgitlab.WithContext(ctx),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"List: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar res []string\n\tfor _, r := range repos {\n\t\tres = append(res, r.SSHURLToRepo)\n\t}\n\n\treturn res, nil\n}", "func (s *adminRuns) List(ctx context.Context, options *AdminRunsListOptions) (*AdminRunsList, error) {\n\tif err := options.valid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := \"admin/runs\"\n\treq, err := s.client.NewRequest(\"GET\", u, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trl := &AdminRunsList{}\n\terr = req.Do(ctx, rl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rl, nil\n}", "func runList(cmd *cobra.Command, args []string) error {\n\tverb := \"GET\"\n\turl := \"/v1/query\"\n\n\tresp, err := web.Request(cmd, verb, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.Printf(\"\\n%s\\n\\n\", resp)\n\treturn nil\n}", "func (b ShapeValueBuilder) BuildList(name, memName string, ref *ShapeRef, v []interface{}) string {\n\tret := \"\"\n\n\tif len(v) == 0 || ref == nil {\n\t\treturn \"\"\n\t}\n\n\tpassRef := &ref.Shape.MemberRef\n\tret += fmt.Sprintf(\"%s: %s {\\n\", memName, b.GoType(ref, false))\n\tret += b.buildListElements(passRef, v)\n\tret += \"},\\n\"\n\treturn ret\n}", "func ListBoardCommand(ctx *cli.Context) error {\n\tworkspaceID := ctx.String(\"workspace-id\")\n\tif workspaceID == \"\" {\n\t\treturn fmt.Errorf(\"invalid workpace-id value of %s\", workspaceID)\n\t}\n\n\trepositoryID := ctx.Uint(\"repository-id\")\n\tif repositoryID == 0 {\n\t\treturn fmt.Errorf(\"invalid repository-id value of %d\", repositoryID)\n\t}\n\turl := fmt.Sprintf(\n\t\t\"%s/p2/workspaces/%s/repositories/%d/board\",\n\t\tctx.String(\"base-url\"),\n\t\tworkspaceID,\n\t\trepositoryID,\n\t)\n\tlogrus.WithField(\"url\", url).Debug(\"Sending list board request\")\n\n\ttoken, err := GetZenHubToken()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient := http.Client{\n\t\tTransport: &AuthenticationTransport{\n\t\t\ttransport: http.DefaultTransport,\n\t\t\tauthenticationToken: token,\n\t\t},\n\t}\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to list board: %w\", err)\n\t}\n\n\tif err := ErrorFromStatusCode(resp.StatusCode); err != nil {\n\t\treturn fmt.Errorf(\"failed to list board: %w\", err)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read body of list board response\")\n\t}\n\tdefer resp.Body.Close()\n\tfmt.Println(string(body))\n\n\treturn nil\n}", "func (r *Runsc) List(context context.Context) ([]*runc.Container, error) {\n\tdata, stderr, err := cmdOutput(r.command(context, \"list\", \"--format=json\"), false)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %s\", err, stderr)\n\t}\n\tvar out []*runc.Container\n\tif err := json.Unmarshal(data, &out); err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func repoList(w http.ResponseWriter, r *http.Request) {}", "func List() *cobra.Command {\n\tvar yamlOutput bool\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List your active cloud native development environments\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn list(yamlOutput)\n\t\t},\n\t}\n\tcmd.Flags().BoolVarP(&yamlOutput, \"yaml\", \"y\", false, \"yaml output\")\n\treturn cmd\n}", "func List(ctx context.Context, client *selvpcclient.ServiceClient) ([]*Project, *selvpcclient.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, resourceURL}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\treturn nil, responseResult, responseResult.Err\n\t}\n\n\t// Extract projects from the response body.\n\tvar result struct {\n\t\tProjects []*Project `json:\"projects\"`\n\t}\n\terr = responseResult.ExtractResult(&result)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn result.Projects, responseResult, nil\n}", "func List(cfg *types.Chain33Config, db dbm.Lister, stateDB dbm.KV, param *gt.QueryGameListByStatusAndAddr) (types.Message, error) {\n\treturn QueryGameListByPage(cfg, db, stateDB, param)\n}", "func (cr APIContractRepository) List(ctx context.Context, projectID uint, clusterID uint) ([]*models.APIContractRevision, error) {\n\tvar confs []*models.APIContractRevision\n\n\tif clusterID == 0 {\n\t\ttx := cr.db.Where(\"project_id = ?\", projectID).Find(&confs).Order(\"created_at desc\")\n\t\tif tx.Error != nil {\n\t\t\treturn nil, tx.Error\n\t\t}\n\t\treturn confs, nil\n\t}\n\ttx := cr.db.Where(\"project_id = ? and cluster_id = ?\", projectID, clusterID).Find(&confs).Order(\"created_at desc\")\n\tif tx.Error != nil {\n\t\treturn nil, tx.Error\n\t}\n\n\treturn confs, nil\n}", "func GetBuildRecords(toolchainID string, appName string) (interface{}, error) {\n\turl := getDlmsService() + \"/v3/toolchainids/\" + toolchainID + \"/buildartifacts/\" + url.PathEscape(appName) + \"/builds\"\n\t//url := getDlmsService() + \"/v3/toolchainids/\" + toolchainID + \"/builds\"\n\n\tstatusCode, body, reqerr := httpRequest(\"GET\", url, nil)\n\tif reqerr != nil {\n\t\treturn nil, errors.New(\"Failed to get build records Error: \" + reqerr.Error())\n\t}\n\tif statusCode != 200 {\n\t\treturn nil, errors.New(\"Failed to get build records \" + fmt.Sprintf(\"statusCode %v\", statusCode) + \" Error: \" + fmt.Sprintf(\"body: %v\", body))\n\t}\n\treturn body, nil\n}", "func (client DeploymentsClient) List(ctx context.Context, resourceGroupName string, serviceName string, appName string, version []string) (result DeploymentResourceCollectionPage, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/DeploymentsClient.List\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.drc.Response.Response != nil {\n\t\t\t\tsc = result.drc.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tresult.fn = client.listNextResults\n\treq, err := client.ListPreparer(ctx, resourceGroupName, serviceName, appName, version)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.DeploymentsClient\", \"List\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListSender(req)\n\tif err != nil {\n\t\tresult.drc.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.DeploymentsClient\", \"List\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult.drc, err = client.ListResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.DeploymentsClient\", \"List\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\tif result.drc.hasNextLink() && result.drc.IsEmpty() {\n\t\terr = result.NextWithContext(ctx)\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *BuildVariablesService) ListBuildVariables(pid interface{}, options ...OptionFunc) ([]*BuildVariable, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects/%s/variables\", url.QueryEscape(project))\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar v []*BuildVariable\n\tresp, err := s.client.Do(req, &v)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn v, resp, err\n}", "func (r *Repository) ListRuns(_ context.Context, req controlplane.ListRequest) (runs []*adagio.Run, err error) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tfor _, state := range r.runs {\n\t\truns = append(runs, state.run)\n\t}\n\n\tsort.Slice(runs, func(i, j int) bool {\n\t\treturn runs[i].Id > runs[j].Id\n\t})\n\n\tif req.Start != nil || req.Finish != nil {\n\t\tvar (\n\t\t\tmin int\n\t\t\tmax = len(runs)\n\t\t\tminSet, maxSet bool\n\t\t\tstart, _ = time.Parse(time.RFC3339, runs[min].CreatedAt)\n\t\t)\n\n\t\tfinish, terr := time.Parse(time.RFC3339, runs[max-1].CreatedAt)\n\t\tif terr != nil {\n\t\t\tfinish = time.Unix(0, math.MaxInt64)\n\t\t}\n\n\t\tif req.Start != nil {\n\t\t\tstart = *req.Start\n\t\t}\n\n\t\tif req.Finish != nil {\n\t\t\tfinish = *req.Finish\n\t\t}\n\n\t\tif start.Before(finish) {\n\t\t\t// start must be > finish as time descending\n\t\t\truns = nil\n\t\t\treturn\n\t\t}\n\n\t\tfor i, run := range runs {\n\t\t\tcreatedAt, err := time.Parse(time.RFC3339Nano, run.CreatedAt)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !minSet && (createdAt.Before(start) || createdAt == start) {\n\t\t\t\tminSet = true\n\t\t\t\tmin = i\n\t\t\t}\n\n\t\t\tif !maxSet && (createdAt.Before(finish) || createdAt == finish) {\n\t\t\t\tmaxSet = true\n\t\t\t\tmax = i + 1\n\t\t\t}\n\t\t}\n\n\t\truns = runs[min:max]\n\t}\n\n\tif limit := req.Limit; limit != nil {\n\t\truns = runs[:int(*limit)]\n\t}\n\n\treturn\n}", "func (s *service) GetBuildJobs(BuildID string, desc bool) ([]*brigademodel.Job, error) {\n\tbl, err := s.client.GetBuild(BuildID)\n\tif err != nil {\n\t\treturn []*brigademodel.Job{}, err\n\t}\n\n\tjobs, err := s.client.GetBuildJobs(bl)\n\tif err != nil {\n\t\treturn []*brigademodel.Job{}, err\n\t}\n\tres := make([]*brigademodel.Job, len(jobs))\n\tfor i, job := range jobs {\n\t\tj := brigademodel.Job(*job)\n\t\tres[i] = &j\n\t}\n\n\t// TODO: Should we improve the sorting algorithm?\n\t// Make a first sort by ID so in equality of time always is the same order on every case.\n\t// Doesn't matter the order at all is for consistency when start time is the same.\n\tsort.SliceStable(res, func(i, j int) bool {\n\t\treturn res[i].ID < res[j].ID\n\t})\n\n\t// Order jobs in ascending order (first ones first).\n\tsort.SliceStable(res, func(i, j int) bool {\n\t\tif desc {\n\t\t\treturn res[i].StartTime.After(res[j].StartTime)\n\t\t}\n\t\treturn res[i].StartTime.Before(res[j].StartTime)\n\t})\n\n\treturn res, nil\n}", "func (c Builds) Get(id int) revel.Result {\n\treturn c.Redirect(\"/\")\n}", "func (ps *ProjectsPG) List(ctx context.Context, opt *ProjectsListOptions, customerId string) ([]api.Project, error) {\n\tif opt == nil {\n\t\topt = &ProjectsListOptions{}\n\t}\n\n\tconds := ListNameLikeSQL(opt.NameLikeOptions)\n\tconds = append(conds, sqlf.Sprintf(\"customer_id = %s\", customerId))\n\n\tqry := sqlf.Sprintf(\"WHERE %s ORDER BY id ASC %s\", sqlf.Join(conds, \"AND\"), opt.LimitOffset.SQL())\n\n\treturn ps.getBySQL(ctx, qry.Query(sqlf.PostgresBindVar), qry.Args()...)\n}", "func (svc *ServiceContext) GetArchivesList(c *gin.Context) {\n\ttype Archives struct {\n\t\tDisplay string `json:\"displayDate\"`\n\t\tInternal string `json:\"internalDate\"`\n\t}\n\tvar data []Archives\n\tq := svc.DB.NewQuery(`select distinct DATE_FORMAT(submitted_at,'%M %Y') display, DATE_FORMAT(submitted_at,'%Y-%m') as internal\n\t\t from submissions where public=1 order by submitted_at desc`)\n\terr := q.All(&data)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: Unable to get archives list: %s\", err.Error())\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, data)\n}" ]
[ "0.82053334", "0.80467856", "0.7970842", "0.7654507", "0.7466744", "0.74304396", "0.7397928", "0.69482076", "0.6844837", "0.67070955", "0.65804696", "0.64626217", "0.6430503", "0.64146525", "0.64016765", "0.63869685", "0.63159895", "0.6205155", "0.6189829", "0.61538106", "0.61388147", "0.61124563", "0.6095879", "0.60589707", "0.6034483", "0.6020381", "0.59758013", "0.5934943", "0.590552", "0.5869946", "0.58428836", "0.583927", "0.57933795", "0.57631266", "0.5742198", "0.5740876", "0.5719904", "0.5710332", "0.56916106", "0.56863964", "0.5601207", "0.55986756", "0.5559537", "0.5558939", "0.55521774", "0.55299395", "0.5519336", "0.5450006", "0.5448689", "0.5424206", "0.5422509", "0.54187757", "0.5387468", "0.53812474", "0.5380956", "0.5364764", "0.5363228", "0.5339517", "0.5316773", "0.5314047", "0.5313453", "0.53010076", "0.5300693", "0.5296936", "0.5253307", "0.52513576", "0.52337205", "0.5228493", "0.5225003", "0.5223109", "0.5210684", "0.51883966", "0.5186379", "0.5185727", "0.5180771", "0.51792055", "0.51309836", "0.5130771", "0.5121188", "0.51135445", "0.5090702", "0.5082985", "0.5082406", "0.5073906", "0.5070334", "0.5064299", "0.5060916", "0.505242", "0.5043195", "0.50062335", "0.5005074", "0.4989343", "0.49834827", "0.49784985", "0.49716026", "0.49712375", "0.4970256", "0.4965083", "0.49610612", "0.49573794" ]
0.7866787
3
Bind a `RunnableWithContext` to this runner. WARNING: invoking it when state is StateRunning may cause blocked.
func (s *DeterminationWithContext) Bind(ctx context.Context, runnable RunnableWithContext) *DeterminationWithContext { defer s.lock.Unlock() /*_*/ s.lock.Lock() s.rctx = ctx s.runn = runnable return s }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (tx *WriteTx) RunWithContext(ctx context.Context) error {\n\tif tx.err != nil {\n\t\treturn tx.err\n\t}\n\tinput, err := tx.input()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = retry(ctx, func() error {\n\t\tout, err := tx.db.client.TransactWriteItemsWithContext(ctx, input)\n\t\tif tx.cc != nil && out != nil {\n\t\t\tfor _, cc := range out.ConsumedCapacity {\n\t\t\t\taddConsumedCapacity(tx.cc, cc)\n\t\t\t}\n\t\t}\n\t\treturn err\n\t})\n\treturn err\n}", "func (r *Retry) RunWithContext(\n\tctx context.Context, funcToRetry func(context.Context) (interface{}, error),\n) (interface{}, error) {\n\t// create a random source which is used in setting the jitter\n\n\tattempts := 0\n\tfor {\n\t\t// run the function\n\t\tresult, err := funcToRetry(ctx)\n\t\t// no error, then we are done!\n\t\tif err == nil {\n\t\t\treturn result, nil\n\t\t}\n\t\t// max retries is reached return the error\n\t\tattempts++\n\t\tif attempts == r.maxTries {\n\t\t\treturn nil, err\n\t\t}\n\t\t// wait for the next duration or context canceled|time out, whichever comes first\n\t\tt := time.NewTimer(getNextBackoff(attempts, r.initialDelay, r.maxDelay))\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\t// nothing to be done as the timer is killed\n\t\tcase <-ctx.Done():\n\t\t\t// context cancelled, kill the timer if it is not killed, and return the last error\n\t\t\tif !t.Stop() {\n\t\t\t\t<-t.C\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t}\n}", "func (e *executor) RunWithContext(ctx context.Context, cmd *exec.Cmd) (string, error) {\n\tvar out bytes.Buffer\n\n\tprefix := color.BlueString(cmd.Args[0])\n\tlogger := e.logger.WithContext(log.ContextWithPrefix(prefix))\n\n\tcmd.Stdout = io.MultiWriter(&out, log.LineWriter(logger.Info))\n\tcmd.Stderr = io.MultiWriter(&out, log.LineWriter(logger.Error))\n\n\treturn e.run(ctx, &out, cmd)\n}", "func runWithContext(fun func(ctx context.Context) error) (context.CancelFunc, chan error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdefer close(done)\n\t\tdone <- fun(ctx)\n\t}()\n\n\treturn cancel, done\n}", "func RunWithContext(ctx context.Context, cmd *exec.Cmd) (string, error) {\n\treturn DefaultExecutor.RunWithContext(ctx, cmd)\n}", "func (ttl *UpdateTTL) RunWithContext(ctx context.Context) error {\n\tinput := ttl.input()\n\n\terr := retry(ctx, func() error {\n\t\t_, err := ttl.table.db.client.UpdateTimeToLiveWithContext(ctx, input)\n\t\treturn err\n\t})\n\treturn err\n}", "func (m *MinikubeRunner) RunWithContext(ctx context.Context, cmdStr string, wait ...bool) (string, string, error) {\n\tprofileArg := fmt.Sprintf(\"-p=%s \", m.Profile)\n\tcmdStr = profileArg + cmdStr\n\tcmdArgs := strings.Split(cmdStr, \" \")\n\tpath, _ := filepath.Abs(m.BinaryPath)\n\n\tcmd := exec.CommandContext(ctx, path, cmdArgs...)\n\tLogf(\"RunWithContext: %s\", cmd.Args)\n\treturn m.teeRun(cmd, wait...)\n}", "func (dtw *describeTTLWrap) RunWithContext(ctx aws.Context) (dynamo.TTLDescription, error) {\n\treturn dtw.describeTTL.RunWithContext(ctx)\n}", "func (p *Pipeline) RunWithContext(ctx context.Context, cancel context.CancelFunc) {\n\tif p.err != nil {\n\t\treturn\n\t}\n\tp.ctx, p.cancel = ctx, cancel\n\tdataSize := p.source.Prepare(p.ctx)\n\tfilteredSize := dataSize\n\tfor index := 0; index < len(p.nodes); {\n\t\tif p.nodes[index].Begin(p, index, &filteredSize) {\n\t\t\tindex++\n\t\t} else {\n\t\t\tp.nodes = append(p.nodes[:index], p.nodes[index+1:]...)\n\t\t}\n\t}\n\tif p.err != nil {\n\t\treturn\n\t}\n\tif len(p.nodes) > 0 {\n\t\tfor index := 0; index < len(p.nodes)-1; {\n\t\t\tif p.nodes[index].TryMerge(p.nodes[index+1]) {\n\t\t\t\tp.nodes = append(p.nodes[:index+1], p.nodes[index+2:]...)\n\t\t\t} else {\n\t\t\t\tindex++\n\t\t\t}\n\t\t}\n\t\tfor index := len(p.nodes) - 1; index >= 0; index-- {\n\t\t\tif _, ok := p.nodes[index].(*strictordnode); ok {\n\t\t\t\tfor index = index - 1; index >= 0; index-- {\n\t\t\t\t\tswitch node := p.nodes[index].(type) {\n\t\t\t\t\tcase *seqnode:\n\t\t\t\t\t\tnode.kind = Ordered\n\t\t\t\t\tcase *lparnode:\n\t\t\t\t\t\tnode.makeOrdered()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif dataSize < 0 {\n\t\t\tp.finalizeVariableBatchSize()\n\t\t\tfor seqNo, batchSize := 0, p.batchInc; p.source.Fetch(batchSize) > 0; seqNo, batchSize = seqNo+1, p.nextBatchSize(batchSize) {\n\t\t\t\tp.nodes[0].Feed(p, 0, seqNo, p.source.Data())\n\t\t\t\tif err := p.source.Err(); err != nil {\n\t\t\t\t\tp.SetErr(err)\n\t\t\t\t\treturn\n\t\t\t\t} else if p.Err() != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tbatchSize := ((dataSize - 1) / p.NofBatches(0)) + 1\n\t\t\tif batchSize == 0 {\n\t\t\t\tbatchSize = 1\n\t\t\t}\n\t\t\tfor seqNo := 0; p.source.Fetch(batchSize) > 0; seqNo++ {\n\t\t\t\tp.nodes[0].Feed(p, 0, seqNo, p.source.Data())\n\t\t\t\tif err := p.source.Err(); err != nil {\n\t\t\t\t\tp.SetErr(err)\n\t\t\t\t\treturn\n\t\t\t\t} else if p.Err() != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor _, node := range p.nodes {\n\t\tnode.End()\n\t}\n\tif p.err == nil {\n\t\tp.err = p.source.Err()\n\t}\n}", "func withContext(borrower ContextBorrower, worker Worker) Worker {\n\n\treturn func(t *T, _ Context) {\n\n\t\tif t.Failed() {\n\t\t\treturn\n\t\t}\n\n\t\tctx, release, err := borrower.Borrow()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s\", err)\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tdefer release()\n\t\tworkerRunner(nil, worker, t, ctx)\n\t}\n}", "func (h *Handler) BindContext(ctx context.Context, server core.Server) {\n\tswitch s := server.(type) {\n\tcase *http.Server:\n\t\ts.Handler = h\n\t\ts.BaseContext = func(l net.Listener) context.Context {\n\t\t\treturn ctx\n\t\t}\n\tcase *fasthttp.Server:\n\t\ts.Handler = h.ServeFastHTTP\n\t}\n}", "func (c *Consumer) ListenWithContext(ctx context.Context, fn MessageProcessor) {\n\tc.consume(ctx)\n\tvar wg sync.WaitGroup\n\tdefer wg.Wait()\n\n\tfor {\n\t\tmsg, ok := <-c.messages\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tc.Stats.AddDelivered(1)\n\t\t// For simplicity, did not do the pipe of death here. If POD is received, we may deliver a\n\t\t// couple more messages (especially since select is random in which channel is read from).\n\t\tc.concurrencySem <- empty{}\n\t\twg.Add(1)\n\t\tgo func(msg *Message) {\n\t\t\tdefer func() {\n\t\t\t\t<-c.concurrencySem\n\t\t\t}()\n\t\t\tstart := time.Now()\n\t\t\tfn(msg)\n\t\t\tc.Stats.UpdateProcessedDuration(time.Since(start))\n\t\t\tc.Stats.AddProcessed(1)\n\t\t\twg.Done()\n\t\t}(msg)\n\t}\n}", "func AddServantWithContext(v dispatch, f interface{}, obj string) {\n\taddServantCommon(v, f, obj, true)\n}", "func (p *Pipeline) RunWithContext(ctx context.Context, cancel context.CancelFunc) {\n\tif p.err != nil {\n\t\treturn\n\t}\n\tp.ctx, p.cancel = ctx, cancel\n\tdataSize := p.source.Prepare(p.ctx)\n\tfilteredSize := dataSize\n\tfor index := 0; index < len(p.nodes); {\n\t\tif p.nodes[index].Begin(p, index, &filteredSize) {\n\t\t\tindex++\n\t\t} else {\n\t\t\tp.nodes = append(p.nodes[:index], p.nodes[index+1:]...)\n\t\t}\n\t}\n\tif p.err != nil {\n\t\treturn\n\t}\n\tif len(p.nodes) > 0 {\n\t\tfor index := 0; index < len(p.nodes)-1; {\n\t\t\tif p.nodes[index].TryMerge(p.nodes[index+1]) {\n\t\t\t\tp.nodes = append(p.nodes[:index+1], p.nodes[index+2:]...)\n\t\t\t} else {\n\t\t\t\tindex++\n\t\t\t}\n\t\t}\n\t\tif dataSize < 0 {\n\t\t\tfor seqNo, batchSize := 0, batchInc; p.source.Fetch(batchSize) > 0; seqNo, batchSize = seqNo+1, nextBatchSize(batchSize) {\n\t\t\t\tp.nodes[0].Feed(p, 0, seqNo, p.source.Data())\n\t\t\t\tif err := p.source.Err(); err != nil {\n\t\t\t\t\tp.SetErr(err)\n\t\t\t\t\treturn\n\t\t\t\t} else if p.Err() != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tbatchSize := ((dataSize - 1) / p.NofBatches(0)) + 1\n\t\t\tif batchSize == 0 {\n\t\t\t\tbatchSize = 1\n\t\t\t}\n\t\t\tfor seqNo := 0; p.source.Fetch(batchSize) > 0; seqNo++ {\n\t\t\t\tp.nodes[0].Feed(p, 0, seqNo, p.source.Data())\n\t\t\t\tif err := p.source.Err(); err != nil {\n\t\t\t\t\tp.SetErr(err)\n\t\t\t\t\treturn\n\t\t\t\t} else if p.Err() != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor _, node := range p.nodes {\n\t\tnode.End()\n\t}\n}", "func (s *Stmt) BindContext(ctx context.Context, args ...interface{}) *Query {\n\treturn &Query{\n\t\tctx: ctx,\n\t\texecer: s.middleware(stmtExecer{s.stmt}),\n\t\tquery: s.sql,\n\t\targs: args,\n\t}\n}", "func NewServerWithContext(ctx context.Context) *Server {\n\treturn &Server{\n\t\tctx: ctx,\n\t\tmaxIdleConns: 1024,\n\t\terrHandler: ignoreErrorHandler,\n\t}\n}", "func (s *SizedWaitGroup) AddWithContext(ctx context.Context) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase s.current <- struct{}{}:\n\t\tbreak\n\t}\n\ts.wg.Add(1)\n\treturn nil\n}", "func CrtlnWithContext(ctx context.Context, args ...interface{}) {\n\ts := fmt.Sprintln(args...)\n\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\tcreticaldeps(hub.CaptureMessage, 3, s)\n\t\treturn\n\t}\n\n\tcreticaldeps(sentry.CaptureMessage, 3, s)\n}", "func (s *Supervisor) StartWithContext(ctx context.Context) {\n\tctx, cancel := context.WithCancel(ctx)\n\n\tgo func() {\n\t\t<-s.shutdown\n\t\ts.logger(Info, nil, \"supervisor ordered to shutdown\")\n\t\tcancel()\n\t}()\n\n\terrChan := make(chan error)\n\twg := sync.WaitGroup{}\n\tfor name := range s.processes {\n\t\twg.Add(1)\n\n\t\tprocess := s.processes[name]\n\t\tgo func() {\n\t\t\tdefer func() {\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\ts.logger(Warn, loggerData{\"cause\": err, \"name\": process.Name()}, \"runner terminated due a panic\")\n\t\t\t\t}\n\n\t\t\t\twg.Done()\n\t\t\t}()\n\t\t\tif err := process.Run(ctx); err != nil {\n\t\t\t\terrChan <- err\n\t\t\t}\n\t\t}()\n\t}\n\n\tgo func() {\n\t\tfor range errChan {\n\t\t\tswitch s.policy.Failure.Policy {\n\t\t\tcase shutdown:\n\t\t\t\ts.logger(Warn, nil, \"under configured failure policy, supervisor will shutdown\")\n\t\t\t\tcancel()\n\t\t\tcase ignore:\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Wait()\n}", "func BindContext(hndl http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tprint(\"Binding context\\n\")\n\t\tctx := OpenCtx(req)\n\t\tprint(\"BindContext: \", ctx, \"\\n\")\n\n\t\tdefer closeCtx(req)\n\t\thndl.ServeHTTP(w, req)\n\t})\n}", "func PerformWithContext(ctx context.Context, input *PerformInput) (*PerformOutput, error) {\n\toutput := make(chan *PerformOutput)\n\n\tnewCtx := withContext(ctx)\n\n\tgo run(newCtx, input, output)\n\n\tfor {\n\t\tselect {\n\t\tcase out := <-output:\n\t\t\treturn out, nil\n\t\tcase <-newCtx.Done():\n\t\t\treturn nil, newCtx.Err()\n\t\t}\n\t}\n}", "func (tx *GetTx) RunWithContext(ctx context.Context) error {\n\tinput, err := tx.input()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar resp *dynamodb.TransactGetItemsOutput\n\terr = retry(ctx, func() error {\n\t\tvar err error\n\t\tresp, err = tx.db.client.TransactGetItemsWithContext(ctx, input)\n\t\tif tx.cc != nil && resp != nil {\n\t\t\tfor _, cc := range resp.ConsumedCapacity {\n\t\t\t\taddConsumedCapacity(tx.cc, cc)\n\t\t\t}\n\t\t}\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isResponsesEmpty(resp.Responses) {\n\t\treturn ErrNotFound\n\t}\n\treturn tx.unmarshal(resp)\n}", "func CrtlfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\tcreticaldeps(hub.CaptureMessage, 3, format, args...)\n\t\treturn\n\t}\n\n\tcreticaldeps(sentry.CaptureMessage, 3, format, args...)\n}", "func RunContext(ctx context.Context, routine func(context.Context)) {\n\tdoRun(ctx, routine)\n}", "func (e *executor) RunSilentlyWithContext(ctx context.Context, cmd *exec.Cmd) (string, error) {\n\tvar buf bytes.Buffer\n\n\tcmd.Stdout = &buf\n\tcmd.Stderr = &buf\n\n\treturn e.run(ctx, &buf, cmd)\n}", "func RunContext(h http.Handler, ctx context.Context) {\n\tsrv := createServer(h)\n\tgo gracefullyShutDownOnSignal(srv, ctx)\n\tif err := srv.ListenAndServe(); err != http.ErrServerClosed {\n\t\tlog.Fatalf(\"Unable to to start server: %v\", err)\n\t}\n}", "func (s *DeterminationWithContext) Run() (err error) {\n\treturn s.run(s.prepare, s.booting, s.running, s.trigger, s.closing)\n}", "func WarnfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\twarndeps(hub.CaptureMessage, 3, format, args...)\n\t\treturn\n\t}\n\n\twarndeps(sentry.CaptureMessage, 3, format, args...)\n}", "func ExecuteWithContext(ctx context.Context, eval Evaluator) (interface{}, error) {\n\ttype Result struct {\n\t\tI interface{}\n\t\tE error\n\t}\n\tch := make(chan Result, 1)\n\tgo func() {\n\t\ti, e := eval(ctx)\n\t\tch <- Result{I: i, E: e}\n\t\tclose(ch)\n\t}()\n\tselect {\n\tcase r := <-ch:\n\t\treturn r.I, r.E\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\t}\n}", "func (d *DescribeTTL) RunWithContext(ctx context.Context) (TTLDescription, error) {\n\tinput := d.input()\n\n\tvar result *dynamodb.DescribeTimeToLiveOutput\n\terr := retry(ctx, func() error {\n\t\tvar err error\n\t\tresult, err = d.table.db.client.DescribeTimeToLiveWithContext(ctx, input)\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn TTLDescription{}, err\n\t}\n\n\tdesc := TTLDescription{\n\t\tStatus: TTLDisabled,\n\t}\n\tif result.TimeToLiveDescription.TimeToLiveStatus != nil {\n\t\tdesc.Status = TTLStatus(*result.TimeToLiveDescription.TimeToLiveStatus)\n\t}\n\tif result.TimeToLiveDescription.AttributeName != nil {\n\t\tdesc.Attribute = *result.TimeToLiveDescription.AttributeName\n\t}\n\treturn desc, nil\n}", "func (s *Service) BindContext(ctx context.Context, server Server) error {\n\tserverType := reflect.TypeOf(server)\n\tif value, ok := serverTypes.Load(serverType); ok {\n\t\tnames := value.([]string)\n\t\tfor _, name := range names {\n\t\t\ts.handlers[name].BindContext(ctx, server)\n\t\t}\n\t\treturn nil\n\t}\n\treturn UnsupportedServerTypeError{serverType}\n}", "func runWithContextCheck(ctx context.Context, action func(ctx context.Context) error) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\terr := action(ctx)\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\treturn err\n}", "func ExecuteWithContext(ctx context.Context, s string, obj interface{}, settings ...SettingsFunc) *exec.Cmd {\n\tr := DefaultRunner()\n\treturn r.ExecuteWithContext(ctx, s, obj, settings...)\n}", "func NewAgentRunEWithContext(initialize InitializeFunc, cmd *cobra.Command, ctx context.Context) func(cmd *cobra.Command, args []string) error {\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\tctx, cancel := context.WithCancel(ctx)\n\t\tdefer cancel()\n\n\t\tcfg, err := NewAgentConfig(cmd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsensuAgent, err := initialize(ctx, cfg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn sensuAgent.Run(ctx)\n\t}\n}", "func SetTimeoutWithContext(ctx context.Context, callback func(), delay time.Duration) func() {\n\tchildCtx, cancel := context.WithCancel(ctx)\n\ttimer := time.NewTimer(delay)\n\tgo func(f func()) {\n\t\tselect {\n\t\tcase <-childCtx.Done():\n\t\t\treturn\n\t\tcase <-timer.C:\n\t\t\tf()\n\t\t}\n\t}(callback)\n\treturn cancel\n}", "func bindContext(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(ContextABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func bindContext(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(ContextABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func bindContext(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(ContextABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func bindContext(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(ContextABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func runSonobuoyCommandWithContext(ctx context.Context, t *testing.T, args string) (error, bytes.Buffer, bytes.Buffer) {\n\tvar stdout, stderr bytes.Buffer\n\n\tcommand := exec.CommandContext(ctx, sonobuoy, strings.Fields(args)...)\n\tcommand.Stdout = &stdout\n\tcommand.Stderr = &stderr\n\n\tt.Logf(\"Running %q\\n\", command.String())\n\n\treturn command.Run(), stdout, stderr\n}", "func (obj *ConfigWriter) AddServantWithContext(imp impConfigWriterWithContext, objStr string) {\n\ttars.AddServantWithContext(obj, imp, objStr)\n}", "func (c *Context) Bind(out interface{}) error {\n\tif err := c.Context.Bind(out); err != nil {\n\t\tc.JSON400Msg(400, fmt.Sprintf(\"invalid request parameters, details: \\n%v\", err))\n\t\treturn err\n\t}\n\treturn nil\n}", "func RunSilentlyWithContext(ctx context.Context, cmd *exec.Cmd) (string, error) {\n\treturn DefaultExecutor.RunSilentlyWithContext(ctx, cmd)\n}", "func NewWithContext(ctx context.Context) (interfaces.AsyncWork, error) {\n\tctx, cancel := context.WithCancel(ctx)\n\n\taw := &asyncWorkImpl{\n\t\tqueue: queue.New(),\n\t\tqueueMutex: &sync.RWMutex{},\n\n\t\tctx: ctx,\n\t\tctxCancel: cancel,\n\n\t\tevent: syncevent.NewSyncEvent(false),\n\n\t\terrorChs: []chan error{},\n\t\terrorChsMutex: &sync.RWMutex{},\n\n\t\tlastExecutionMap: map[string]time.Time{},\n\t\tlastExecutionMapMutex: &sync.RWMutex{},\n\n\t\tthrottleLastMap: map[string]*jobImpl{},\n\t\tthrottleLastMapMutex: &sync.RWMutex{},\n\t}\n\n\treturn aw, nil\n}", "func (blk *Block) DrawWithContext(d Drawable, ctx DrawContext) error {\n\tblocks, _, err := d.GeneratePageBlocks(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(blocks) != 1 {\n\t\treturn errors.New(\"too many output blocks\")\n\t}\n\n\tfor _, newBlock := range blocks {\n\t\tif err := blk.mergeBlocks(newBlock); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func WarningfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\twarndeps(hub.CaptureMessage, 3, format, args...)\n\t\treturn\n\t}\n\n\twarndeps(sentry.CaptureMessage, 3, format, args...)\n}", "func (_obj *DataService) AddServantWithContext(imp _impDataServiceWithContext, obj string) {\n\ttars.AddServantWithContext(_obj, imp, obj)\n}", "func InfolnWithContext(ctx context.Context, args ...interface{}) {\n\ts := fmt.Sprintln(args...)\n\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\tinfodeps(hub.CaptureMessage, 3, s)\n\t\treturn\n\t}\n\n\tinfodeps(sentry.CaptureMessage, 3, s)\n}", "func ErrfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\terrdeps(hub.CaptureMessage, 3, format, args...)\n\t\treturn\n\t}\n\n\terrdeps(sentry.CaptureMessage, 3, format, args...)\n}", "func RawWithContext(ctx context.Context, cmd string, options ...types.Option) (string, error) {\n\treturn command(ctx, cmd, options...)\n}", "func (_obj *LacService) AddServantWithContext(imp _impLacServiceWithContext, obj string) {\n\ttars.AddServantWithContext(_obj, imp, obj)\n}", "func NewWithContext(ctx context.Context, workers, capacity int) (Interface, context.Context) {\n\tctx, cancel := context.WithCancel(ctx)\n\ti := &impl{\n\t\tcancel: cancel,\n\t\tworkCh: make(chan func() error, capacity),\n\t}\n\n\t// Start a go routine for each worker, which:\n\t// 1. reads off of the work channel,\n\t// 2. (optionally) sets the error as the result,\n\t// 3. marks work as done in our sync.WaitGroup.\n\tfor idx := 0; idx < workers; idx++ {\n\t\tgo func() {\n\t\t\tfor work := range i.workCh {\n\t\t\t\ti.exec(work)\n\t\t\t}\n\t\t}()\n\t}\n\treturn i, ctx\n}", "func retryWithContext(ctx context.Context, targetFunc retryableFunc, delay time.Duration) error {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t\tcontinueRetrying, err := targetFunc()\n\t\t\tif !continueRetrying {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttime.Sleep(delay) //delay between retries\n\t\t}\n\t}\n}", "func (c *Client) SubscribeRawWithContext(ctx context.Context, handler func(msg *Event)) error {\n\treturn c.SubscribeWithContext(ctx, \"\", handler)\n}", "func (mr *MockRDSAPIMockRecorder) ModifyDBSnapshotAttributeWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ModifyDBSnapshotAttributeWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).ModifyDBSnapshotAttributeWithContext), varargs...)\n}", "func (_obj *Apichannels) AddServantWithContext(imp _impApichannelsWithContext, obj string) {\n\ttars.AddServantWithContext(_obj, imp, obj)\n}", "func (bf *BuiltInFunc) Bind(instance *LoxInstance) Callable {\n\tbf.instance = instance\n\t// return itself.\n\treturn bf\n}", "func (_obj *Apilangpack) AddServantWithContext(imp _impApilangpackWithContext, obj string) {\n\ttars.AddServantWithContext(_obj, imp, obj)\n}", "func NewTickerWithContext(ctx context.Context, d time.Duration) *Ticker {\n\tt := NewTicker(d)\n\tif ctx.Done() != nil {\n\t\tgo func() {\n\t\t\t<-ctx.Done()\n\t\t\tt.Stop()\n\t\t}()\n\t}\n\treturn t\n}", "func (r *StreamingRuntime) ExecWithContext(\n\tctx context.Context,\n\tcontainerID string,\n\tcmd []string,\n\tin io.Reader,\n\tout, errw io.WriteCloser,\n\ttty bool,\n\tresize <-chan remotecommand.TerminalSize,\n\ttimeout time.Duration,\n) error {\n\tcontainer, err := libdocker.CheckContainerStatus(r.Client, containerID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn r.ExecHandler.ExecInContainer(\n\t\tctx,\n\t\tr.Client,\n\t\tcontainer,\n\t\tcmd,\n\t\tin,\n\t\tout,\n\t\terrw,\n\t\ttty,\n\t\tresize,\n\t\ttimeout,\n\t)\n}", "func (mr *MockRDSAPIMockRecorder) ModifyDBInstanceWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ModifyDBInstanceWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).ModifyDBInstanceWithContext), varargs...)\n}", "func ForWithContext(c context.Context, begin int, end int, f ForLoop) {\n\tlength := end - begin\n\n\tif length > 0 {\n\t\tctx, cacnel := context.WithCancel(c)\n\t\tgo doLoop(cacnel, begin, end, f)\n\t\t<-ctx.Done()\n\t}\n}", "func WithEvalContext[T any](ctx context.Context, state T, f func(ctx context.Context, state T) error) error {\r\n\t_, ok := ctxutil.Value(ctx, (*exprEvaluator)(nil)).(*exprEvaluator)\r\n\tif !ok {\r\n\t\teev := exprEvaluators.Get()\r\n\t\tdefer exprEvaluators.Put(eev)\r\n\t\tee := eev.(*exprEvaluator)\r\n\t\tctx = ctxutil.WithValue(ctx, ee.ContextKey(), eev)\r\n\t}\r\n\treturn f(ctx, state)\r\n}", "func PipeWithContext(\n\tctx context.Context,\n\tsamplesPerSecond uint,\n\tformat SampleFormat,\n) (PipeReader, PipeWriter) {\n\tctx, cancel := context.WithCancel(ctx)\n\tp := &pipe{\n\t\tcontext: ctx,\n\t\tcancel: cancel,\n\t\tformat: format,\n\t\tsamplesPerSecond: samplesPerSecond,\n\t\tsamplesCh: make(chan Samples),\n\t\treadSamplesCh: make(chan int),\n\t}\n\treturn p, p\n}", "func (ctx *Context) BindWith(obj interface{}, b binder.Binder) (err error) {\n\tif err = b.Bind(ctx.Request, obj); err != nil {\n\t\treturn\n\t}\n\tif validator := ctx.Validator; validator != nil {\n\t\treturn validator.ValidateStruct(obj)\n\t}\n\treturn\n}", "func (d *DefaultContext) Bind(value interface{}) error {\n\treturn binding.Exec(d.Request(), value)\n}", "func ListenContext(ctx context.Context, laddr net.Addr, raddr string, config *Config) (net.Listener, <-chan error, error) {\n\tlistener, err := net.Listen(laddr.Network(), laddr.String())\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"listen on %s://%s: %v\", laddr.Network(), laddr.String(), err)\n\t}\n\tlistenerConnsCh, _ := listenerConns(ctx, listener)\n\ttunnelConn := func(ctx context.Context) (net.Conn, <-chan error, error) {\n\t\treturn DialContext(ctx, raddr, config)\n\t}\n\terrCh := make(chan error, 1)\n\thandleListenerConn := func(listenerConn net.Conn) {\n\t\tctxConn, cancel := context.WithCancel(ctx)\n\t\tdefer listenerConn.Close()\n\t\tdefer cancel()\n\t\ttunnelConn, tunnelConnErrCh, err := tunnelConn(ctxConn)\n\t\tif err != nil {\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\t\tpipeDone := make(chan bool, 1)\n\t\tgo func() {\n\t\t\tconnpipe.Run(ctxConn, tunnelConn, listenerConn)\n\t\t\tpipeDone <- true\n\t\t}()\n\t\tselect {\n\t\tcase <-pipeDone:\n\t\t\treturn\n\t\tcase err, ok := <-tunnelConnErrCh:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terrCh <- err\n\t\tcase <-ctx.Done():\n\t\t\terrCh <- ctx.Err()\n\t\t}\n\t}\n\tgo func() {\n\t\tdefer listener.Close()\n\t\tdefer close(errCh)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\terrCh <- ctx.Err()\n\t\t\t\treturn\n\t\t\tcase listenerConn, ok := <-listenerConnsCh:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tgo handleListenerConn(listenerConn)\n\t\t\t}\n\t\t}\n\t}()\n\treturn listener, errCh, err\n}", "func (r RunFunc) Run(ctx context.Context) {\n\tr(ctx)\n}", "func (c *Client) PostWithContext(ctx context.Context, url string, reqBody, resType interface{}) error {\n\treturn c.CallAPIWithContext(ctx, \"POST\", url, reqBody, resType, true)\n}", "func (r *Reconciler) bind(\n\tlogger *log.Log,\n\tbm *ServiceBinder,\n\tsbrStatus *v1alpha1.ServiceBindingRequestStatus,\n) (\n\treconcile.Result,\n\terror,\n) {\n\tlogger = logger.WithName(\"bind\")\n\n\tlogger.Info(\"Binding applications with intermediary secret...\")\n\treturn bm.Bind()\n}", "func PrintfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\tprintdeps(hub.CaptureMessage, 3, fmt.Sprintf(format, args...))\n\t\treturn\n\t}\n\n\tprintdeps(sentry.CaptureMessage, 3, fmt.Sprintf(format, args...))\n}", "func NewWithContext(ctx context.Context, fn func() error) func() error {\n\treturn NewFactory(WithContext(ctx))(fn)\n}", "func WithRunActionsCtx(ctx context.Context, ra RunActionsCtx) context.Context {\n\treturn context.WithValue(ctx, runActionsCtxKey{}, ra)\n}", "func PanicfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\tpanicdeps(hub.CaptureMessage, 3, format, args...)\n\t\treturn\n\t}\n\n\tpanicdeps(sentry.CaptureMessage, 3, format, args...)\n}", "func Bind(req *http.Request) *http.Request {\n // Reuse context if already binded\n if _, ok := req.Context().Value(Key).(Store); ok {\n return req\n }\n // Create new context store\n ctx := context.WithValue(req.Context(), Key, Store{})\n return req.WithContext(ctx)\n}", "func (mr *MockRDSAPIMockRecorder) ModifyDBSubnetGroupWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ModifyDBSubnetGroupWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).ModifyDBSubnetGroupWithContext), varargs...)\n}", "func (m *Manager) Run(ctx context.Context, run func() error) (err error) {\n\t// Acquire mutex lock\n\tm.mux.Lock()\n\t// Defer the release of mutex lock\n\tdefer m.mux.Unlock()\n\t// Call internal run func\n\treturn m.run(ctx, run)\n}", "func (r *Retrier) RunContext(ctx context.Context, funcToRetry func(context.Context) error) error {\n\tmaxTries := r.maxTries\n\tinitialDelay := r.initialDelay\n\tmaxDelay := r.maxDelay\n\tif maxTries <= 0 {\n\t\tmaxTries = DefaultMaxTries\n\t}\n\tif initialDelay <= 0 {\n\t\tinitialDelay = DefaultInitialDelay\n\t}\n\tif maxDelay <= 0 {\n\t\tmaxDelay = DefaultMaxDelay\n\t}\n\trandSource := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tattempts := 0\n\tfor {\n\t\t// Attempt to run the function\n\t\terr := funcToRetry(ctx)\n\t\t// If there's no error, we're done!\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tattempts++\n\t\t// If we've just run our last attempt, return the error we got\n\t\tif attempts == maxTries {\n\t\t\treturn err\n\t\t}\n\n\t\t// Check if the error is a terminal error. If so, stop!\n\t\tswitch v := err.(type) {\n\t\tcase terminalError:\n\t\t\treturn v.e\n\t\t}\n\t\t// Otherwise wait for the next duration or until the context is done,\n\t\t// whichever comes first\n\t\tt := time.NewTimer(getnextBackoff(attempts, initialDelay, maxDelay, randSource))\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\t// duration elapsed, loop\n\t\tcase <-ctx.Done():\n\t\t\t// context cancelled, kill the timer if it hasn't fired, and return\n\t\t\t// the last error we got\n\t\t\tif !t.Stop() {\n\t\t\t\t<-t.C\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (s *Service) Bind(ctx context.Context, address string) error {\n\ts.mutex.Lock()\n\tif s.running {\n\t\ts.mutex.Unlock()\n\t\treturn fmt.Errorf(\"Init(): already running\")\n\t}\n\ts.mutex.Unlock()\n\n\ts.parseAddress(address)\n\n\terr := s.setListener(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (mr *MockRDSAPIMockRecorder) ModifyDBSnapshotWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ModifyDBSnapshotWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).ModifyDBSnapshotWithContext), varargs...)\n}", "func (p fullProvider) FetchDSNWithContext(_ context.Context, dsn string) (string, error) {\n\treturn p.FetchDSN(dsn)\n}", "func CreticalfWithContext(ctx context.Context, format string, args ...interface{}) {\n\tif hub := sentry.GetHubFromContext(ctx); hub != nil {\n\t\tcreticaldeps(hub.CaptureMessage, 3, format, args...)\n\t\treturn\n\t}\n\n\tcreticaldeps(sentry.CaptureMessage, 3, format, args...)\n}", "func AllWithContext(ctx context.Context, functions ...TaskFunc) {\n\tForWithContext(ctx, 0, len(functions), func(i int) {\n\t\tfunctions[i]()\n\t})\n}", "func (_m *EventBus) Run(ctx context.Context) {\n\t_m.Called(ctx)\n}", "func (o *LoggingBindParams) WithContext(ctx context.Context) *LoggingBindParams {\n\to.SetContext(ctx)\n\treturn o\n}", "func (c *icecontext) Bind(i interface{}) error {\n\treturn protocol.Unpack(c.Request().GetFormat(),\n\t\tc.Request().GetBody(), i)\n}", "func DoWithContext(ctx context.Context, do func(ctx context.Context) error, fallback func(err error)) (err error) {\n\terrorChannel := make(chan error)\n\tvar contextHasBeenDone = false\n\tgo func() {\n\t\terr := do(ctx)\n\t\tif contextHasBeenDone {\n\t\t\tif fallback != nil {\n\t\t\t\tfallback(err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\terrorChannel <- err\n\t}()\n\tselect {\n\tcase err = <-errorChannel:\n\t\treturn err\n\tcase <-ctx.Done():\n\t\tcontextHasBeenDone = true\n\t\treturn ctx.Err()\n\t}\n}", "func wrapContext(ctx context.Context, adapter Adapter) contextWrapper {\n\treturn contextWrapper{\n\t\tctx: context.WithValue(ctx, ctxKey, adapter),\n\t\tadapter: adapter,\n\t}\n}", "func (mr *MockRDSAPIMockRecorder) ModifyDBClusterSnapshotAttributeWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ModifyDBClusterSnapshotAttributeWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).ModifyDBClusterSnapshotAttributeWithContext), varargs...)\n}", "func WithRunner(runner func(context.Context) error) CollectorIntegrationConfig {\n\treturn func(i *CollectorIntegration) {\n\t\ti.runner = runner\n\t}\n}", "func (b ExponentialBackOff) RetryWithContext(ctx context.Context, operation func() error) error {\n\tb.Reset()\n\tfor {\n\t\terr := operation()\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t\tnext := b.NextBackOff()\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn fmt.Errorf(\"%v with last error: %v\", context.DeadlineExceeded, err)\n\t\tcase <-time.After(next):\n\t\t}\n\t}\n}", "func (API) Context(s *api.State, thread uint64) api.Context {\n\treturn nil\n}", "func ExecuteEWithContext(ctx context.Context, s string, obj interface{}, settings ...SettingsFunc) (*exec.Cmd, error) {\n\tr := DefaultRunner()\n\treturn r.ExecuteEWithContext(ctx, s, obj, settings...)\n}", "func (b *Builder) Run(r *Runner) {\n\tr.Run()\n\tb.mu.Lock()\n\tdelete(b.running, r)\n\tb.mu.Unlock()\n}", "func (mr *MockRDSAPIMockRecorder) WaitUntilDBSnapshotAvailableWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WaitUntilDBSnapshotAvailableWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).WaitUntilDBSnapshotAvailableWithContext), varargs...)\n}", "func (o *OutputState) ApplyIntPtrWithContext(ctx context.Context, applier interface{}) IntPtrOutput {\n\treturn o.ApplyTWithContext(ctx, applier).(IntPtrOutput)\n}", "func WrapContextForServer(ctx context.Context) context.Context {\n\tif v := ctx.Value(serverPayloadKey); v != nil {\n\t\treturn ctx\n\t}\n\n\treturn context.WithValue(ctx, serverPayloadKey, serverPayload{\n\t\tm: make(map[string]interface{}),\n\t})\n}", "func (mr *MockRDSAPIMockRecorder) WaitUntilDBInstanceAvailableWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WaitUntilDBInstanceAvailableWithContext\", reflect.TypeOf((*MockRDSAPI)(nil).WaitUntilDBInstanceAvailableWithContext), varargs...)\n}", "func (s *StubSentry) WrapContext(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, stubSentryKey, s)\n}", "func (m *MQTT) WriteWithContext(ctx context.Context, msg *message.Batch) error {\n\treturn m.Write(msg)\n}" ]
[ "0.6004581", "0.5999245", "0.59970725", "0.5727529", "0.56164736", "0.55119467", "0.5381095", "0.5210632", "0.52035266", "0.5194531", "0.5181738", "0.51611114", "0.5145714", "0.5078032", "0.50537634", "0.5029204", "0.5004192", "0.49929345", "0.4977733", "0.49630624", "0.49399602", "0.49342173", "0.49006084", "0.4874898", "0.48338205", "0.48226637", "0.4812495", "0.47725084", "0.4769671", "0.476642", "0.47219515", "0.47141433", "0.4713416", "0.47040948", "0.47017372", "0.46720192", "0.46720192", "0.46720192", "0.46720192", "0.46612304", "0.46570274", "0.46450475", "0.46406668", "0.4625494", "0.46254826", "0.46101275", "0.4588602", "0.45847958", "0.4562158", "0.45567486", "0.45388055", "0.4522944", "0.45094544", "0.45054305", "0.45026252", "0.44876415", "0.44576338", "0.44498038", "0.4422623", "0.4418043", "0.44168568", "0.44085318", "0.4408354", "0.4404763", "0.44005406", "0.43981755", "0.43907925", "0.4388614", "0.4370541", "0.43539342", "0.4341735", "0.43398854", "0.43278286", "0.4322912", "0.4317141", "0.4315656", "0.43132195", "0.42949426", "0.42782596", "0.42741978", "0.4269806", "0.4261499", "0.42593953", "0.42429602", "0.42428055", "0.42398685", "0.42390805", "0.4231867", "0.42297134", "0.42288148", "0.42276946", "0.42264536", "0.42249712", "0.4218942", "0.421638", "0.4215314", "0.4203425", "0.42011997", "0.41990155", "0.4190176" ]
0.7612144
0
State of this `Runner`.
func (s *DeterminationWithContext) State() State { return s.stat.get() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *task) State() State {\n\tv := atomic.LoadInt32(&t.state)\n\treturn State(v)\n}", "func (this *Job) State() int {\n\tanyRunningTasks := false\n\tfor _, task := range this.Tasks {\n\t\tif task.IsRunning() {\n\t\t\tanyRunningTasks = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn JobState(this.Started, this.Finished, this.Suspended, this.Error, anyRunningTasks)\n}", "func (ed *EvalDetails) State() interpreter.EvalState {\n\treturn ed.state\n}", "func (r *Stater) State(log lager.Logger, handle string) (state rundmc.State, err error) {\n\tlog = log.Session(\"state\", lager.Data{\"handle\": handle})\n\n\tlog.Debug(\"started\")\n\tdefer log.Debug(\"finished\")\n\n\tbuf := new(bytes.Buffer)\n\terr = r.runner.RunAndLog(log, func(logFile string) *exec.Cmd {\n\t\tcmd := r.runc.StateCommand(handle, logFile)\n\t\tcmd.Stdout = buf\n\t\treturn cmd\n\t})\n\tif err != nil {\n\t\treturn rundmc.State{}, fmt.Errorf(\"runc state: %s\", err)\n\t}\n\n\tif err := json.NewDecoder(buf).Decode(&state); err != nil {\n\t\tlog.Error(\"decode-state-failed\", err)\n\t\treturn rundmc.State{}, fmt.Errorf(\"runc state: %s\", err)\n\t}\n\n\treturn state, nil\n}", "func (m *Machine) State() State {\n\treturn m.currentState\n}", "func (a *Arena) State() game.State { return a.game }", "func (cb *Breaker) State() State {\n\tcb.mutex.Lock()\n\tdefer cb.mutex.Unlock()\n\n\tnow := time.Now()\n\tstate, _ := cb.currentState(now)\n\treturn state\n}", "func (c *Processor) RunState() RunState {\n\treturn c.runState\n}", "func (s *stateMachine) Run() (done bool) {\n\t// Multiplex external (Stop) messages and internal ones\n\ts.cmds = make(chan *Message)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase m := <-s.cl.Receive():\n\t\t\t\tif !m.Valid() {\n\t\t\t\t\tmetafora.Warnf(\"Ignoring invalid command: %q\", m)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tselect {\n\t\t\t\tcase s.cmds <- m:\n\t\t\t\tcase <-s.stopped:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-s.stopped:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Stop the command listener and internal message multiplexer when Run exits\n\tdefer func() {\n\t\ts.cl.Stop()\n\t\ts.stop()\n\t}()\n\n\ttid := s.task.ID()\n\n\t// Load the initial state\n\tstate, err := s.ss.Load(s.task)\n\tif err == ReleasableError {\n\t\t// A failure to load was reported by our provided loader, but the loader believed the failure\n\t\t// was retriable. In most cases this will be some type of network partition or communication error,\n\t\t// too many file handles, etc.\n\t\tmetafora.Errorf(\"task=%q could not load initial state but the task is retriable!\", tid)\n\t\ttime.Sleep(time.Second) //defer releasing the task so other nodes don't thunder herd retrying it.\n\t\treturn false\n\t} else if err != nil {\n\t\t// A failure to load the state for a task is *fatal* - the task will be\n\t\t// unscheduled and requires operator intervention to reschedule.\n\t\tmetafora.Errorf(\"task=%q could not load initial state. Marking done! Error: %v\", tid, err)\n\t\treturn true\n\t}\n\tif state == nil {\n\t\t// Note to StateStore implementors: This should not happen! Either state or\n\t\t// err must be non-nil. This code is simply to prevent a nil pointer panic.\n\t\tmetafora.Errorf(\"statestore %T returned nil state and err for task=%q - unscheduling\", s.ss, tid)\n\t\treturn true\n\t}\n\tif state.Code.Terminal() {\n\t\tmetafora.Warnf(\"task=%q in terminal state %s - exiting.\", tid, state.Code)\n\t\treturn true\n\t}\n\n\ts.setState(state) // for introspection/debugging\n\n\t// Main Statemachine Loop\n\tdone = false\n\tfor {\n\t\t// Enter State\n\t\tmetafora.Debugf(\"task=%q in state %s\", tid, state.Code)\n\t\tmsg := s.exec(state)\n\n\t\t// Apply Message\n\t\tnewstate, ok := apply(state, msg)\n\t\tif !ok {\n\t\t\tmetafora.Warnf(\"task=%q Invalid state transition=%q returned by task. Old state=%q msg.Err=%s\", tid, msg.Code, state.Code, msg.Err)\n\t\t\tmsg = ErrorMessage(msg.Err)\n\t\t\tif newstate, ok = apply(state, msg); !ok {\n\t\t\t\tmetafora.Errorf(\"task=%q Unable to transition to error state! Exiting with state=%q\", tid, state.Code)\n\t\t\t\treturn state.Code.Terminal()\n\t\t\t}\n\t\t}\n\n\t\tmetafora.Infof(\"task=%q transitioning %s --> %s --> %s\", tid, state, msg, newstate)\n\n\t\t// Save state - second part of logic probably should never happen\n\t\tif msg.Code != Release || (msg.Code == Release && (state.Code != newstate.Code || len(state.Errors) != len(newstate.Errors))) {\n\t\t\tif err := s.ss.Store(s.task, newstate); err != nil {\n\t\t\t\t// After upgrading to 1.25.5-gke.2000 we started experiencing the metadata server throwing POD_FINDER_IP_MISMATCH\n\t\t\t\t// errors resulting in failures authenticating to spanner. This panic will cause the pod to cyle\n\t\t\t\t// See https://github.com/lytics/lio/issues/30414\n\t\t\t\tif strings.Contains(err.Error(), \"spanner: code = \\\"Unauthenticated\\\"\") {\n\t\t\t\t\tmetafora.Errorf(\"task=%q Unable to persist state=%q due to failure to authenticate to spanner.\", tid, newstate.Code)\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\tmetafora.Errorf(\"task=%q Unable to persist state=%q. Continuing.\", tid, newstate.Code)\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\t// Set next state and loop if non-terminal\n\t\tstate = newstate\n\n\t\t// Expose the state for introspection\n\t\ts.setState(state)\n\n\t\t// Exit and unschedule task on terminal state.\n\t\tif state.Code.Terminal() {\n\t\t\treturn true\n\t\t}\n\n\t\t// Release messages indicate the task should exit but not unschedule.\n\t\tif msg.Code == Release {\n\t\t\treturn false\n\t\t}\n\n\t\t// Alternatively Stop() may have been called but the handler may not have\n\t\t// returned the Release message. Always exit if we've been told to Stop()\n\t\t// even if the handler has returned a different Message.\n\t\tselect {\n\t\tcase <-s.stopped:\n\t\t\treturn false\n\t\tdefault:\n\t\t}\n\t}\n}", "func (inst *Instancer) State() sd.Event {\n\treturn inst.cache.State()\n}", "func (r *VmwareMapper) RunningState() bool {\n\treturn false\n}", "func (r *remoteReplicator) State() *state {\n\treturn r.state.Load().(*state)\n}", "func GetCurrentState() {\n\n}", "func (ctl *taskController) State() *task.State {\n\treturn &ctl.state\n}", "func (r *RPCTaskReader) State() (tes.State, error) {\n\tt, err := r.client.GetTask(context.Background(), &tes.GetTaskRequest{\n\t\tId: r.taskID,\n\t\tView: tes.TaskView_MINIMAL,\n\t})\n\treturn t.GetState(), err\n}", "func (tp *ThreadPool) State() map[string]interface{} {\n\n\tgetIdsFromWorkerMap := func(m map[uint64]*ThreadPoolWorker) []uint64 {\n\t\tvar ret []uint64\n\t\tfor k := range m {\n\t\t\tret = append(ret, k)\n\t\t}\n\t\treturn ret\n\t}\n\n\ttp.workerMapLock.Lock()\n\tdefer tp.workerMapLock.Unlock()\n\n\treturn map[string]interface{}{\n\t\t\"TaskQueueSize\": tp.queue.Size(),\n\t\t\"TotalWorkerThreads\": getIdsFromWorkerMap(tp.workerMap),\n\t\t\"IdleWorkerThreads\": getIdsFromWorkerMap(tp.workerIdleMap),\n\t}\n}", "func (manager *Manager) State() string {\n\treturn manager.state\n}", "func (d delegate) LocalState(join bool) []byte { return nil }", "func (r *runtime) State() server.State {\n\treturn r.state\n}", "func (t *SmartTripper) State() State {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\n\treturn t.state\n}", "func (s *SketchLimiter) State() LoadState {\n\ts.m.RLock()\n\tdefer s.m.RUnlock()\n\treturn s.current\n}", "func (s *SketchLimiter) State() LoadState {\n\ts.m.RLock()\n\tdefer s.m.RUnlock()\n\treturn s.current\n}", "func (s *SketchLimiter) State() LoadState {\n\ts.m.RLock()\n\tdefer s.m.RUnlock()\n\treturn s.current\n}", "func State() (*db.Source, int, time.Time) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\treturn current, ingestDelaySeconds, nextIngest\n}", "func (r Request) State() interfaces.GameState { return r.state }", "func (r *IntCode) State() []int { return r.prog }", "func (e *dockerExec) setState(state execState, err error) {\n\te.mu.Lock()\n\te.State = state\n\te.err = err\n\te.cond.Broadcast()\n\te.mu.Unlock()\n}", "func (s *trialWorkloadSequencer) snapshotState() {\n\ts.LatestSnapshot = s.trialWorkloadSequencerState.deepCopy()\n\ts.LatestSnapshot.LatestSnapshot = nil\n}", "func (r *Ready) State() string {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\n\tselect {\n\tcase <-r.ch:\n\t\treturn \"unready\"\n\tdefault:\n\t\treturn \"ready\"\n\t}\n}", "func (w *StatusWorker) State() StatusWorkerState {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\n\treturn w.state\n}", "func (d *mlDelegate) LocalState(bool) []byte { return nil }", "func (sm *StateMachine) State() int {\n\treturn sm.state\n}", "func (m *Manager) Run() (State, InterfaceConfig, InterfaceStatus) {\n\tcount := 0\n\n\tstatus := InterfaceStatus{}\n\tconfig := InterfaceConfig{}\n\n\t// state machine for network manager\n\tfor {\n\t\tcount++\n\t\tif count > 10 {\n\t\t\tlog.Println(\"network state machine ran too many times\")\n\t\t\tif time.Since(m.stateStart) > time.Second*15 {\n\t\t\t\tlog.Println(\"Network: timeout: \", m.Desc())\n\t\t\t\tm.nextInterface()\n\t\t\t}\n\n\t\t\treturn m.state, config, status\n\t\t}\n\n\t\tif m.state != StateError {\n\t\t\tvar err error\n\t\t\tstatus, err = m.getStatus()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error getting interface status: \", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tswitch m.state {\n\t\tcase StateNotDetected:\n\t\t\t// give ourselves 15 seconds or so in detecting state\n\t\t\t// in case we just reset the devices\n\t\t\tif status.Detected {\n\t\t\t\tlog.Printf(\"Network: %v detected\\n\", m.Desc())\n\t\t\t\tm.setState(StateConfigure)\n\t\t\t\tcontinue\n\t\t\t} else if time.Since(m.stateStart) > time.Second*15 {\n\t\t\t\tlog.Println(\"Network: timeout detecting: \", m.Desc())\n\t\t\t\tm.nextInterface()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tcase StateConfigure:\n\t\t\ttry := 0\n\t\t\tfor ; try < 3; try++ {\n\t\t\t\tif try > 0 {\n\t\t\t\t\tlog.Println(\"Trying again ...\")\n\t\t\t\t}\n\t\t\t\tvar err error\n\t\t\t\tconfig, err = m.configure()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error configuring device: %v: %v\\n\",\n\t\t\t\t\t\tm.Desc(), err)\n\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif try < 3 {\n\t\t\t\tm.setState(StateConnecting)\n\t\t\t} else {\n\t\t\t\tlog.Println(\"giving up configuring device: \", m.Desc())\n\t\t\t\tm.nextInterface()\n\t\t\t}\n\n\t\tcase StateConnecting:\n\t\t\tif status.Connected {\n\t\t\t\tlog.Printf(\"Network: %v connected\\n\", m.Desc())\n\t\t\t\tm.setState(StateConnected)\n\t\t\t} else {\n\t\t\t\tif time.Since(m.stateStart) > time.Minute {\n\t\t\t\t\tlog.Println(\"Network: timeout connecting: \", m.Desc())\n\t\t\t\t\tm.nextInterface()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// try again to connect\n\t\t\t\terr := m.connect()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Error connecting: \", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase StateConnected:\n\t\t\tif !status.Connected {\n\t\t\t\t// try to reconnect\n\t\t\t\tm.setState(StateConnecting)\n\t\t\t}\n\n\t\tcase StateError:\n\t\t\tif time.Since(m.stateStart) > time.Minute {\n\t\t\t\tlog.Println(\"Network: reset and try again ...\")\n\t\t\t\tm.Reset()\n\t\t\t\tm.setState(StateNotDetected)\n\t\t\t}\n\t\t}\n\n\t\t// if we want to re-run state machine, must execute continue above\n\t\tbreak\n\t}\n\n\treturn m.state, config, status\n}", "func (r *DynamoDBTaskReader) State() (tes.State, error) {\n\tt, err := r.client.GetTask(context.Background(), &tes.GetTaskRequest{\n\t\tId: r.taskID,\n\t\tView: tes.TaskView_MINIMAL,\n\t})\n\treturn t.GetState(), err\n}", "func (state JenkinsRunState) String() string {\n\treturn string(state)\n}", "func (evpool *EvidencePool) State() State {\n\tevpool.mtx.Lock()\n\tdefer evpool.mtx.Unlock()\n\treturn evpool.state\n}", "func (f *Machine) State() uint8 {\n\treturn f.state\n}", "func (e HybridKFEstimate) State() *mat64.Vector {\n\treturn e.state\n}", "func (o LakeOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Lake) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (job *Job) State() chan string {\n\treturn job.stateChan\n}", "func (state *State) Running() bool {\n\treturn *(*uint32)(state) == 1\n}", "func (rb *TrainedModelDeploymentAllocationStatusBuilder) State(state deploymentallocationstate.DeploymentAllocationState) *TrainedModelDeploymentAllocationStatusBuilder {\n\trb.v.State = state\n\treturn rb\n}", "func (d *Execution_Data) State() Execution_State {\n\tif d != nil {\n\t\tswitch d.ExecutionType.(type) {\n\t\tcase *Execution_Data_Scheduling_:\n\t\t\treturn Execution_SCHEDULING\n\t\tcase *Execution_Data_Running_:\n\t\t\treturn Execution_RUNNING\n\t\tcase *Execution_Data_Stopping_:\n\t\t\treturn Execution_STOPPING\n\t\tcase *Execution_Data_Finished_:\n\t\t\treturn Execution_FINISHED\n\t\tcase *Execution_Data_AbnormalFinish:\n\t\t\treturn Execution_ABNORMAL_FINISHED\n\t\t}\n\t}\n\treturn Execution_SCHEDULING\n}", "func (e *dockerExec) getState() (execState, error) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\treturn e.State, e.err\n}", "func (ed *Editor) State() *types.State {\n\treturn &ed.state\n}", "func (ts *TaskService) State(ctx context.Context, req *taskAPI.StateRequest) (*taskAPI.StateResponse, error) {\n\tdefer logPanicAndDie(log.G(ctx))\n\n\tlog.G(ctx).WithFields(logrus.Fields{\"id\": req.ID, \"exec_id\": req.ExecID}).Debug(\"state\")\n\ttask, err := ts.taskManager.Task(req.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx = namespaces.WithNamespace(ctx, defaultNamespace)\n\tresp, err := task.State(ctx, req)\n\tif err != nil {\n\t\tlog.G(ctx).WithError(err).Error(\"state failed\")\n\t\treturn nil, err\n\t}\n\n\tlog.G(ctx).WithFields(logrus.Fields{\n\t\t\"id\": resp.ID,\n\t\t\"bundle\": resp.Bundle,\n\t\t\"pid\": resp.Pid,\n\t\t\"status\": resp.Status,\n\t}).Debug(\"state succeeded\")\n\treturn resp, nil\n}", "func (r *Runner) AssertState() {\n\tr.T.Helper()\n\n\t// Assert counts.\n\tassertNumCommands(r.T, r.CustomMap, len(r.LearnDataMap))\n\tassertNumGists(r.T, r.Gist, r.GistsCount)\n\tassertNumDiscordMessages(r.T, r.DiscordSession, r.DiscordMessagesCount)\n\tassertVote(r.T, r.UTCClock, r.VoteMap, r.ActiveVoteDataMap)\n\n\t// Assert command map state.\n\tfor _, learn := range r.LearnDataMap {\n\t\tassertCommand(r.T, r.CustomMap, learn.Call, learn.Response)\n\t}\n}", "func (h *Harness) State() *gmon.Ganglia {\n\taddr := fmt.Sprintf(\"%s:%d\", localhostIP, h.port)\n\tganglia, err := gmon.RemoteRead(\"tcp\", addr)\n\tif err != nil {\n\t\th.t.Fatal(err)\n\t}\n\treturn ganglia\n}", "func (r *RecordStream) Running() bool { return r.state == running }", "func (rb *DatafeedsRecordBuilder) State(state datafeedstate.DatafeedState) *DatafeedsRecordBuilder {\n\trb.v.State = &state\n\treturn rb\n}", "func (o KafkaMirrorMakerOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KafkaMirrorMaker) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (pool *Pool) State() (state PoolState, err error) {\n\tif pool.list == nil {\n\t\terr = errors.New(msgPoolIsNil)\n\t} else {\n\t\tstate = PoolState(C.zpool_read_state(pool.list.zph))\n\t}\n\treturn\n}", "func (o WorkerPoolOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *WorkerPool) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (l *RelayDriver) State() bool {\n\treturn l.high\n}", "func (e *Event) State() *state.State {\n\treturn e.state\n}", "func (nm *NodeMonitor) State() *models.MonitorStatus {\n\tnm.mutex.RLock()\n\tstate := nm.state\n\tnm.mutex.RUnlock()\n\treturn state\n}", "func (s *ExternalAgentRunningState) Name() string {\n\treturn AgentRunningStateName\n}", "func idle() State_t {\n\t\n}", "func (r *Runsc) State(context context.Context, id string) (*runc.Container, error) {\n\tdata, stderr, err := cmdOutput(r.command(context, \"state\", id), false)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %s\", err, stderr)\n\t}\n\tvar c runc.Container\n\tif err := json.Unmarshal(data, &c); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}", "func (e *localfileExec) setState(state execState, err error) {\n\te.mu.Lock()\n\te.state = state\n\te.err = err\n\te.cond.Broadcast()\n\te.mu.Unlock()\n}", "func (m *mover) State() string {\n\treturn m.game.State\n}", "func (nm *NodeMonitor) State() *models.MonitorStatus {\n\tnm.Mutex.RLock()\n\tstate := nm.state\n\tnm.Mutex.RUnlock()\n\treturn state\n}", "func (h *StabNode) State() **linkedlist.State {\n\treturn &h.state\n}", "func (se *StateEngine) State() *state.State {\n\treturn se.state\n}", "func (r *Runner) Name() string { return RunnerName }", "func (p *Process) State() State {\n\tstatus, err := p.Status()\n\tif err != nil {\n\t\treturn StateUnknown\n\t}\n\treturn status.State\n}", "func (self Source) State() State {\n\treturn State(self.Geti(AlSourceState))\n}", "func (m *MockqueueTask) State() task.State {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"State\")\n\tret0, _ := ret[0].(task.State)\n\treturn ret0\n}", "func (cli *Client) State() State {\n\treturn State(cli.ref.Get(\"readyState\").Int())\n}", "func (r *Runner) SetState(state RunnerState) {\n\tr.state = state\n\tswitch r.state {\n\tcase Idle:\n\t\tr.animation.Play(\"Idle\")\n\tcase Running:\n\t\tr.animation.Play(\"Run\")\n\t}\n}", "func (cracker *Firecracker) State() (InstanceState, error) {\n\tresp, err := cracker.client.R().\n\t\tSetHeader(\"Accept\", \"application/json\").\n\t\tSetResult(&instanceInfo{}).\n\t\tSetError(&apiError{}).\n\t\tGet(\"/\")\n\n\tif err != nil {\n\t\treturn Uninitialized, err\n\t}\n\n\tif err = cracker.responseError(resp); err != nil {\n\t\treturn Uninitialized, err\n\t}\n\n\tif info, ok := resp.Result().(*instanceInfo); ok {\n\t\tcracker.id = info.ID\n\t\treturn info.State, nil\n\t}\n\n\treturn Uninitialized, errInvalidServerResponse\n}", "func (p *Producer) State() ProducerState {\n\treturn p.state\n}", "func (r *Runner) Reset() {\n\tif !r.usedNew {\n\t\tpanic(\"use interp.New to construct a Runner\")\n\t}\n\t// reset the internal state\n\t*r = Runner{\n\t\tEnv: r.Env,\n\t\tDir: r.Dir,\n\t\tParams: r.Params,\n\t\tStdin: r.Stdin,\n\t\tStdout: r.Stdout,\n\t\tStderr: r.Stderr,\n\t\tExec: r.Exec,\n\t\tOpen: r.Open,\n\t\tKillTimeout: r.KillTimeout,\n\n\t\t// emptied below, to reuse the space\n\t\tVars: r.Vars,\n\t\tcmdVars: r.cmdVars,\n\t\tdirStack: r.dirStack[:0],\n\t\tusedNew: r.usedNew,\n\t}\n\tif r.Vars == nil {\n\t\tr.Vars = make(map[string]Variable)\n\t} else {\n\t\tfor k := range r.Vars {\n\t\t\tdelete(r.Vars, k)\n\t\t}\n\t}\n\tif r.cmdVars == nil {\n\t\tr.cmdVars = make(map[string]string)\n\t} else {\n\t\tfor k := range r.cmdVars {\n\t\t\tdelete(r.cmdVars, k)\n\t\t}\n\t}\n\tif _, ok := r.Env.Get(\"HOME\"); !ok {\n\t\tu, _ := user.Current()\n\t\tr.Vars[\"HOME\"] = Variable{Value: StringVal(u.HomeDir)}\n\t}\n\tr.Vars[\"PWD\"] = Variable{Value: StringVal(r.Dir)}\n\tr.Vars[\"IFS\"] = Variable{Value: StringVal(\" \\t\\n\")}\n\tr.ifsUpdated()\n\tr.Vars[\"OPTIND\"] = Variable{Value: StringVal(\"1\")}\n\n\tif runtime.GOOS == \"windows\" {\n\t\t// convert $PATH to a unix path list\n\t\tpath, _ := r.Env.Get(\"PATH\")\n\t\tpath = strings.Join(filepath.SplitList(path), \":\")\n\t\tr.Vars[\"PATH\"] = Variable{Value: StringVal(path)}\n\t}\n\n\tr.dirStack = append(r.dirStack, r.Dir)\n\tif r.Exec == nil {\n\t\tr.Exec = DefaultExec\n\t}\n\tif r.Open == nil {\n\t\tr.Open = DefaultOpen\n\t}\n\tif r.KillTimeout == 0 {\n\t\tr.KillTimeout = 2 * time.Second\n\t}\n\tr.didReset = true\n}", "func (q *Queen) Run() {\n\n\tlog.L.Debugf(\"Obtaining a run lock for %v\", q.config.ID)\n\n\t//wait for the lock\n\tq.runMutex.Lock()\n\tq.State = running\n\n\tdefer func() {\n\t\tq.runMutex.Unlock()\n\t\tq.LastRun = time.Now()\n\t}()\n\n\tlog.L.Infof(\"Starting run of %v.\", q.config.ID)\n\n\t//before we get the info from the store, we need to have the caterpillar\n\tcat, err := caterpillar.GetCaterpillar(q.config.Type)\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't get the caterpillar %v.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.State = errorwaiting\n\t\tq.LastError = err.Error()\n\t\treturn\n\t}\n\n\t//Register the info struct so it'll come back with an assertable type in the interface that was written.\n\tcat.RegisterGobStructs()\n\n\t//get the information from the store\n\tinfo, err := store.GetInfo(q.config.ID)\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't get information for caterpillar %v from info store. Returning.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\tlog.L.Debugf(\"State before run: %v\", info)\n\n\t//get the feeder, from that we can get the number of events.\n\tfeed, err := feeder.GetFeeder(q.config, info.LastEventTime)\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't get feeder for %v from info store. Returning.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\n\tcount, err := feed.GetCount()\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't get event count from feeder for %v from info store. Returning.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\n\t//Run the caterpillar - this should block until the cateprillar is done chewing through the data.\n\tstate, err := cat.Run(q.config.ID, count, info, q.nydusChannel, q.config, feed.StartFeeding)\n\tif err != nil {\n\t\tlog.L.Error(err.Addf(\"There was an error running caterpillar %v: %v\", q.config.ID, err.Error()))\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\n\tlog.L.Debugf(\"State after run; %v\", state)\n\n\terr = store.PutInfo(q.config.ID, state)\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't store information for caterpillar %v to info store. Returning.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\n\tq.LastError = \"\"\n\tq.State = donewaiting\n\n}", "func (rc *Ctx) State() State {\n\treturn rc.state\n}", "func (w *Warp) State(\n\tctx context.Context,\n) warp.State {\n\tw.mutex.Lock()\n\tdefer w.mutex.Unlock()\n\tstate := warp.State{\n\t\tWarp: w.token,\n\t\tWindowSize: w.windowSize,\n\t\tUsers: map[string]warp.User{},\n\t}\n\n\tstate.Users[w.host.session.session.User] = w.host.User(ctx)\n\n\tfor token, user := range w.clients {\n\t\tstate.Users[token] = user.User(ctx)\n\t}\n\n\treturn state\n}", "func setup(t *testing.T, tid string) (*embedded.StateStore, Commander, metafora.Handler, chan bool) {\n\tt.Parallel()\n\tss := embedded.NewStateStore().(*embedded.StateStore)\n\t_ = ss.Store(task(tid), &State{Code: Runnable})\n\t<-ss.Stored // pop initial state out\n\tcmdr := embedded.NewCommander()\n\tcmdlistener := cmdr.NewListener(tid)\n\tsm := New(task(tid), testhandler, ss, cmdlistener, nil)\n\tdone := make(chan bool)\n\tgo func() { done <- sm.Run() }()\n\treturn ss, cmdr, sm, done\n}", "func (ts *TaskService) State(requestCtx context.Context, req *taskAPI.StateRequest) (*taskAPI.StateResponse, error) {\n\tdefer logPanicAndDie(log.G(requestCtx))\n\tlog.G(requestCtx).WithFields(logrus.Fields{\"id\": req.ID, \"exec_id\": req.ExecID}).Debug(\"state\")\n\n\tresp, err := ts.runcService.State(requestCtx, req)\n\tif err != nil {\n\t\tlog.G(requestCtx).WithError(err).Error(\"state failed\")\n\t\treturn nil, err\n\t}\n\n\tlog.G(requestCtx).WithFields(logrus.Fields{\n\t\t\"id\": resp.ID,\n\t\t\"bundle\": resp.Bundle,\n\t\t\"pid\": resp.Pid,\n\t\t\"status\": resp.Status,\n\t}).Debug(\"state succeeded\")\n\treturn resp, nil\n}", "func (e *localfileExec) getState() (execState, error) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\treturn e.state, e.err\n}", "func (e *engine) Run(ctx context.Context, spec *Spec, step *Step, output io.Writer) (*State, error) {\n state := &State{\n\t\tExitCode: 0,\n\t\tExited: true,\n\t\tOOMKilled: false,\n\t}\n\n\treturn state, nil\n}", "func (s *server) State() string {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\treturn s.state\n}", "func (i ImmExamplesState) IsState() {}", "func (s *StanServer) State() State {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn s.state\n}", "func(decorator *ProcessDecorator) changeState() string {\n\treturn \"state of process changed from down to up\"\n}", "func running() bool {\n\treturn runCalled.Load() != 0\n}", "func (s *Store) State() State {\n\treturn s.state\n}", "func (ws *workingSet) State(s interface{}, opts ...protocol.StateOption) (uint64, error) {\n\t_stateDBMtc.WithLabelValues(\"get\").Inc()\n\tcfg, err := processOptions(opts...)\n\tif err != nil {\n\t\treturn ws.height, err\n\t}\n\tvalue, err := ws.store.Get(cfg.Namespace, cfg.Key)\n\tif err != nil {\n\t\treturn ws.height, err\n\t}\n\treturn ws.height, state.Deserialize(s, value)\n}", "func (c *Conn) State() State {\n\treturn c.state\n}", "func (i *Incarnation) State() string {\n\treturn string(i.status.State.Current)\n}", "func (p *Pool) Running() int {\n\treturn int(atomic.LoadInt32(&p.running))\n}", "func (s *StateMgr) State(n State) State {\n\treturn s.current\n}", "func (p AMQPClient) State() chan bool {\n\treturn p.stateUpdates\n}", "func (o JobStatusOutput) State() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.State }).(pulumi.StringPtrOutput)\n}", "func (l *Lexer) run() {\n\tfor state := l.state; state != nil; {\n\t\tstate = state(l)\n\t}\n\tclose(l.items)\n}", "func (r *Raft) State() RaftState {\n\treturn r.getState()\n}", "func (w *World) State() State {\n\treturn State{World: w, L: w.l}\n}", "func (ctl *taskController) populateState() {\n\tctl.state = task.State{\n\t\tStatus: ctl.saved.Status,\n\t\tViewURL: ctl.saved.ViewURL,\n\t\tTaskData: append([]byte(nil), ctl.saved.TaskData...), // copy\n\t}\n}", "func (o AgentPoolOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AgentPool) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (c *Context) State() *iavl.MutableTree {\n\tif c.IsCheckOnly() {\n\t\treturn c.state.CheckTxTree()\n\t}\n\treturn c.state.DeliverTxTree()\n}", "func (s *Server) State() State {\n\ts.mu.RLock()\n\tst := s.state\n\ts.mu.RUnlock()\n\treturn st\n}" ]
[ "0.6165869", "0.614897", "0.6057116", "0.60031307", "0.59669775", "0.59290916", "0.59237635", "0.59144264", "0.5868559", "0.58162314", "0.579526", "0.5783789", "0.57044184", "0.5702006", "0.56892705", "0.5654448", "0.56457466", "0.5645388", "0.56394327", "0.56268454", "0.5624164", "0.5624164", "0.5624164", "0.5616515", "0.5608381", "0.55825317", "0.5572715", "0.55379665", "0.55329794", "0.5525853", "0.55192876", "0.5487665", "0.54876065", "0.5486269", "0.5474479", "0.5470038", "0.5454213", "0.542991", "0.5424572", "0.5424005", "0.541435", "0.5396288", "0.5392957", "0.53711104", "0.53613263", "0.5357939", "0.5352489", "0.5340562", "0.5338385", "0.5335296", "0.5328749", "0.5327978", "0.53247356", "0.53228945", "0.53125095", "0.53012085", "0.5288946", "0.5282861", "0.52791274", "0.5253886", "0.5244894", "0.52444077", "0.52440345", "0.5243501", "0.5239303", "0.52381784", "0.5226069", "0.5216113", "0.5210817", "0.5206526", "0.5201348", "0.5188859", "0.51840234", "0.51783526", "0.5178198", "0.515594", "0.51542675", "0.5145417", "0.5145412", "0.5143523", "0.5139663", "0.51335084", "0.5132124", "0.51203763", "0.51197666", "0.511836", "0.5104163", "0.5101602", "0.5097462", "0.5086234", "0.5079826", "0.50767386", "0.50674903", "0.5067411", "0.50654614", "0.5057755", "0.5057725", "0.5054794", "0.50510967", "0.5042056" ]
0.5167171
75
Run this `Runner`. Caller will be blocked until error happens or `Close` is called.
func (s *DeterminationWithContext) Run() (err error) { return s.run(s.prepare, s.booting, s.running, s.trigger, s.closing) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Runner) Run(ctx context.Context) error {\n\treturn errors.New(\"not implemented\")\n}", "func (e *Executor) Run() { e.loop() }", "func (b *Builder) Run(r *Runner) {\n\tr.Run()\n\tb.mu.Lock()\n\tdelete(b.running, r)\n\tb.mu.Unlock()\n}", "func (r *Runner) Run() {\n\tif err := os.MkdirAll(r.Dir, 0700); err != nil {\n\t\tr.setError(err)\n\t\treturn\n\t}\n\tdefer r.Cleanup()\n\tif flags.Verbose {\n\t\tfmt.Printf(\"Run %s %s\\n\", r.Binary, strings.Join(r.Args, \" \"))\n\t}\n\n\tvar stdout, stderr bytes.Buffer\n\tr.Cmd.Dir = r.Dir\n\tr.Cmd.Stdout = &stdout\n\tr.Cmd.Stderr = &stderr\n\n\tdefer func() {\n\t\tr.Stdout = stdout.Bytes()\n\t\tr.Stderr = stderr.Bytes()\n\t\tif !r.Preserve || r.Error() == nil {\n\t\t\treturn\n\t\t}\n\t\tif err := writefile(filepath.Join(r.Dir, \"stdout\"), r.Stdout); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t}\n\t\tif err := writefile(filepath.Join(r.Dir, \"stderr\"), r.Stderr); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t}\n\t}()\n\n\tr.mu.Lock()\n\t// r.err will not be nil if we tried to kill ourselves off\n\tif r.err == nil {\n\t\tr.err = r.Cmd.Start()\n\t\tif r.err == nil {\n\t\t\tgo func() {\n\t\t\t\tr.errCh <- r.Cmd.Wait()\n\t\t\t\tclose(r.errCh)\n\t\t\t}()\n\t\t} else {\n\t\t\tclose(r.errCh)\n\t\t}\n\t}\n\terr := r.err\n\tr.mu.Unlock()\n\tif err != nil {\n\t\treturn\n\t}\n\tt := time.NewTimer(r.Timeout)\n\tdefer t.Stop()\n\tr.Wait(t, killSignals)\n}", "func (t *Test) Run() error {\n\treturn t.Wrap(t.run)\n}", "func (m *Manager) Run(ctx context.Context, run func() error) (err error) {\n\t// Acquire mutex lock\n\tm.mux.Lock()\n\t// Defer the release of mutex lock\n\tdefer m.mux.Unlock()\n\t// Call internal run func\n\treturn m.run(ctx, run)\n}", "func (m *Manager) Run() {\n\tgo func() {\n\t\tif err := m.Start(context.Background()); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n}", "func (a *Application) Run() error {\n\t<-a.quit\n\treturn nil\n}", "func (c *client) Run(ctx context.Context) (err error) {\n\terr = c.Conn.Run(ctx)\n\treturn\n}", "func (tr *TestRunner) Run() {\n\ttr.pg.Run() // Start running the PortGroup and underlying Ports in goroutines\n\tgo tr.run()\n}", "func (m *Manager) Run(ctx context.Context) error {\n\t// start log broadcaster\n\t_ = utils.Pool.Submit(func() { m.logBroadcaster.run(ctx) })\n\n\t// initWorkloadStatus container\n\tif err := m.initWorkloadStatus(ctx); err != nil {\n\t\treturn err\n\t}\n\n\t// start status watcher\n\t_ = utils.Pool.Submit(func() { m.monitor(ctx) })\n\n\t// start health check\n\t_ = utils.Pool.Submit(func() { m.healthCheck(ctx) })\n\n\t// wait for signal\n\t<-ctx.Done()\n\tlog.WithFunc(\"Run\").Info(ctx, \"exiting\")\n\treturn nil\n}", "func (s *Session) Run() {\n\tgo s.run()\n}", "func (jr *joinReader) Run(wg *sync.WaitGroup) {\n\terr := jr.mainLoop()\n\tjr.output.Close(err)\n\tif wg != nil {\n\t\twg.Done()\n\t}\n}", "func Run() {\n\trun()\n}", "func (a *MockAgent) Run() {\n\tfor {\n\t\t<-a.Input // consume message to unblock Sender\n\t}\n}", "func (bg *Backgrounder) Run(f Handler) {\n\tbg.count++\n\tgo func() {\n\t\tbg.pipe <- process{Error: f()}\n\t}()\n}", "func (s *Service) Run() {\n\ts.acceptConnection()\n}", "func Run(s options.Options, stopCh <-chan struct{}) error {\n\terr := NonBlockingRun(s, stopCh)\n\tif err != nil {\n\t\treturn err\n\t}\n\t<-stopCh\n\treturn nil\n}", "func (a *Application) Run() {\n\tstartCtx, cancel := context.WithTimeout(context.Background(), a.lifecycleTimeout)\n\tdefer cancel()\n\n\tdone, err := a.Start(startCtx)\n\tif err != nil {\n\t\ta.errorHandler.Handle(err)\n\t\treturn\n\t}\n\n\tr := <-done\n\n\t// The application stopped because of an error\n\tif err, ok := r.(error); ok || err != nil {\n\t\ta.errorHandler.Handle(err)\n\t} else if sig, ok := r.(os.Signal); ok { // The application stopped because of an os signal\n\t\tlevel.Info(a.logger).Log(\"msg\", fmt.Sprintf(\"captured %v signal\", sig))\n\t}\n\n\tshutdownCtx, cancel := context.WithTimeout(context.Background(), a.lifecycleTimeout)\n\tdefer cancel()\n\n\tif err := a.Shutdown(shutdownCtx); err != nil {\n\t\ta.errorHandler.Handle(err)\n\t}\n}", "func (m *Manager) Run() error {\n\tif m.running == false {\n\t\tif err := m.Start(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tgo func() {\n\t\t// Wait until we get shutdown signal\n\t\t<-m.signals\n\n\t\t// Stop the waiter\n\t\tm.wait.Done()\n\t}()\n\n\t// Make sure we wait until we get signals\n\tm.wait.Add(1)\n\tm.wait.Wait()\n\n\t// Stop all bots and return\n\tm.Stop()\n\treturn nil\n}", "func Run() {\n\tsrc.ReadConfig(\"config.json\")\n\terr := src.InitDatabase(\"./\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\terr = src.ReminderInit(\"./\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tsrc.Start()\n\n\t<-make(chan struct{})\n\tdefer src.RemindClient.Close()\n\tdefer src.DB.Client.Close()\n}", "func (r *Runner) Run(request *workflow.RunRequest) (err error) {\n\tr.request = request\n\tr.context = r.manager.NewContext(toolbox.NewContext())\n\t//init shared session\n\texec.TerminalSessions(r.context)\n\texec.SetDefaultTarget(r.context, nil)\n\tselenium.Sessions(r.context)\n\n\tr.report = &ReportSummaryEvent{}\n\tr.context.CLIEnabled = true\n\tr.filter = request.EventFilter\n\tif len(r.filter) == 0 {\n\t\tr.filter = DefaultFilter()\n\t}\n\tdefer func() {\n\t\tr.onCallerEnd()\n\t\tif r.err != nil {\n\t\t\terr = r.err\n\t\t}\n\t\tif !request.Interactive {\n\t\t\tr.context.Close()\n\t\t}\n\t\tif r.hasValidationFailures || err != nil {\n\t\t\tOnError(1)\n\t\t}\n\t}()\n\tr.context.SetListener(r.AsListener())\n\trequest.Async = true\n\tvar response = &workflow.RunResponse{}\n\terr = endly.Run(r.context, request, response)\n\tr.onCallerStart()\n\tif err != nil {\n\t\tr.context.Publish(msg.NewErrorEvent(err.Error()))\n\t\treturn err\n\t}\n\tr.context.Wait.Wait()\n\treturn err\n}", "func (c *Chain) Run(ctx context.Context, options [][]string, input io.Reader, output io.Writer) error {\n\tvar currentReader = input\n\n\t// cancel everything when something goes wrong\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tdone := make(chan error, len(c.runnables))\n\n\t// kick of runnables and chain via io.Pipe\n\tfor i := 0; i < len(c.runnables); i++ {\n\t\tvar opts []string\n\t\tif i < len(options) {\n\t\t\topts = options[i]\n\t\t}\n\t\tcurrentReader = runChained(ctx, c.runnables[i], opts, currentReader, done)\n\t}\n\n\t// shovel last output to the output of this runnable\n\tgo func() {\n\t\t_, err := io.Copy(output, currentReader)\n\t\tdone <- err\n\t}()\n\n\t// wait for everything to finish\n\tfor i := 0; i < len(c.runnables)+1; i++ {\n\t\terr := <-done\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Client) Run() (err error) {\n\t// boot\n\tif err = c.boot(); err != nil {\n\t\treturn\n\t}\n\n\t// read loop\n\tgo c.tunReadLoop()\n\t// write loop\n\tgo c.connReadLoop()\n\n\t// wait both loop done\n\t<-c.done\n\t<-c.done\n\n\treturn\n}", "func (this *Connection) run() {\n\tgo this.routineMain()\n}", "func (i *IRC) Run() error {\n\t// ensure that if the socket chan was marked as closed, we clean it up\n\tselect {\n\tcase <-i.socketDoneChan:\n\tdefault:\n\t}\n\n\tif err := i.Connect(); err != nil {\n\t\tif !errors.Is(err, ErrorIRCAlreadyConnected) {\n\t\t\ti.Connected.Set(false)\n\t\t}\n\n\t\treturn err\n\t}\n\n\tpingCtx, cancel := context.WithCancel(context.Background())\n\tgo i.pingLoop(pingCtx)\n\n\tdefer func() {\n\t\t// clean up\n\t\tcancel()\n\t\ti.lastPong.Set(time.Time{})\n\t\ti.lag.Set(time.Duration(0))\n\t\t_ = i.socket.Close()\n\t\ti.Connected.Set(false)\n\t}()\n\n\tselect {\n\tcase e := <-i.RawEvents.WaitForChan(\"ERROR\"):\n\t\tif !i.StopRequested.Get() {\n\t\t\treturn fmt.Errorf(\"IRC server sent us an ERROR line: %s\", strings.Join(event2RawEvent(e).Line.Params, \" \"))\n\t\t}\n\tcase <-i.socketDoneChan:\n\t\treturn fmt.Errorf(\"IRC socket closed\")\n\t}\n\n\treturn nil\n}", "func (f *Flow) Run(opts Opts) error {\n\tctx := opts.Context\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\treturn newExecution(f, opts.Logger, opts.ProgressReporter, opts.ErrorCleaner, opts.ErrorContext).run(ctx)\n}", "func Run(ctx context.Context, client *guardian.Client, config Config) (err error) {\n\tif config.Icon == nil {\n\t\tconfig.Icon = leaseui.DefaultIcon()\n\t}\n\n\trunner, err := New(client, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn runner.Run(ctx)\n\n\t/*\n\t\tg, ctx := errgroup.WithContext(ctx)\n\n\t\trun := func() error {\n\t\t\trunner, err := New(client, config)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn runner.Run(ctx)\n\t\t}\n\n\t\tg.Go(run)\n\t\tg.Go(run)\n\n\t\treturn g.Wait()\n\t*/\n}", "func (c *Client) Run() {\n\tlog.Infof(\"Checking permission for: %s\", c.config.outputDir)\n\tif !c.checkWritable() {\n\t\tlog.Panicf(\"No write permission on directory: %s\", c.config.outputDir)\n\t\tos.Exit(1)\n\t}\n\n\tlog.Info(\"Starting collecting URLs..\")\n\tc.collectUrlsFromIndex()\n\tlog.Infof(\"Total files found: %d, Total directories found: %d\", len(c.files), len(c.directories))\n\tlog.Info(\"Creating the same directory structure..\")\n\tc.createDirectories()\n\tlog.Info(\"Preparing for downloads..\")\n\tc.start()\n\tlog.Info(\"Done.\")\n}", "func (app *App) Run() {\n\tif err := app.Start(Timeout(DefaultTimeout)); err != nil {\n\t\tapp.logger.Fatalf(\"ERROR\\t\\tFailed to start: %v\", err)\n\t}\n\n\tapp.logger.PrintSignal(<-app.Done())\n\n\tif err := app.Stop(Timeout(DefaultTimeout)); err != nil {\n\t\tapp.logger.Fatalf(\"ERROR\\t\\tFailed to stop cleanly: %v\", err)\n\t}\n}", "func (m *Monitor) Run(ctx context.Context) error {\n\treturn m.dialer.Dial(ctx, func(ctx context.Context, dctx *system.DialContext) error {\n\t\t// Note readiness on first successful init.\n\t\tm.readyOnce.Do(func() { close(m.readyC) })\n\t\tm.logf(\"initialized, monitoring from %s\", dctx.IP)\n\n\t\t// Monitor until an error occurs, reinitializing under certain\n\t\t// circumstances.\n\t\terr := m.monitor(ctx, dctx.Conn)\n\t\tswitch {\n\t\tcase errors.Is(err, context.Canceled):\n\t\t\t// Intentional shutdown.\n\t\t\treturn nil\n\t\tcase err == nil:\n\t\t\tpanic(\"corerad: monitor must never return nil error\")\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t})\n}", "func (b *AdapterBase) Run(stopCh <-chan struct{}) error {\n\tserver, err := b.Server()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn server.GenericAPIServer.PrepareRun().Run(stopCh)\n}", "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 (p *Pool) Run(t *tomb.Tomb) error {\n\treturn p.inner.run(t)\n}", "func (r *Retrier) Run(work func() error) error {\n\treturn r.RunCtx(context.Background(), func(ctx context.Context) error {\n\t\t// never use ctx\n\t\treturn work()\n\t})\n}", "func (e *Engine) Run() {\n\tif err := e.backend.Start(e.callback); err != nil {\n\t\te.errors <- err\n\t}\n\t<-e.stop\n\n\tif err := e.backend.Stop(); err != nil {\n\t\te.stop <- err\n\t\treturn\n\t}\n\te.stop <- e.graph.Close()\n}", "func (m *mockRunner) Run(probe *Probe) {\n\tm.RunFn(probe)\n}", "func Run(run func()) {\n\t// Note: Initializing global `callQueue`. This is potentially unsafe, as `callQueue` might\n\t// have been already initialized.\n\t// TODO(yarcat): Decide whether we should panic at this point or do something else.\n\tcallQueue = make(chan func())\n\n\ttasks := make(chan func())\n\tdone := make(chan struct{})\n\tgo transferTasks(tasks, done)\n\n\tgo func() {\n\t\trun()\n\t\tclose(done) // `close` broadcasts it to all receivers.\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase f := <-tasks:\n\t\t\tf()\n\t\tcase <-done:\n\t\t\treturn\n\t\t}\n\t}\n}", "func Run(m *testing.M, opts ...RunOption) {\n\t// Run tests in a separate function such that we can use deferred statements and still\n\t// (indirectly) call `os.Exit()` in case the test setup failed.\n\tif err := func() error {\n\t\tvar cfg runConfig\n\t\tfor _, opt := range opts {\n\t\t\topt(&cfg)\n\t\t}\n\n\t\tdefer mustHaveNoChildProcess()\n\t\tif !cfg.disableGoroutineChecks {\n\t\t\tdefer mustHaveNoGoroutines()\n\t\t}\n\n\t\tcleanup, err := configure()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"test configuration: %w\", err)\n\t\t}\n\t\tdefer cleanup()\n\n\t\tif cfg.setup != nil {\n\t\t\tif err := cfg.setup(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"error calling setup function: %w\", err)\n\t\t\t}\n\t\t}\n\n\t\tm.Run()\n\n\t\treturn nil\n\t}(); err != nil {\n\t\tfmt.Printf(\"%s\", err)\n\t\tos.Exit(1)\n\t}\n}", "func (t *testSystem) Run(core bool) func() {\n\tfor _, b := range t.backends {\n\t\tif core {\n\t\t\tb.engine.Start() // start Istanbul core\n\t\t}\n\t}\n\n\tgo t.listen()\n\tcloser := func() { t.stop(core) }\n\treturn closer\n}", "func Run(args []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) int {\n\tif err := run(args, stdin, stdout, stderr); err != nil {\n\t\tmessage := err.Error()\n\t\tif message == \"\" {\n\t\t\tmessage = \"unexpected error\"\n\t\t}\n\t\t_, _ = fmt.Fprintln(stderr, message)\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (r *Runner) Run(in io.Reader, out io.Writer) error {\n\tname, _ := detectType(r.fileName)\n\tdef := languageDefs[r.ft]\n\n\texec := ContainerExec{\n\t\tContainer: r.container,\n\t\tCmd: expandTemplate(def.RunCommand, r.fileName, name),\n\t\tIn: in,\n\t\tOut: out,\n\t}\n\n\texec.Run()\n\tcancelTimer := exec.StartKillTimer(r.timeLimit)\n\n\terr := <-exec.ExitC\n\tif err == ErrTimeLimit {\n\t\tr.container.Run()\n\t}\n\tcancelTimer <- true\n\treturn err\n}", "func (c *Copier) Run() {\n\tc.closed = make(chan struct{})\n\tgo c.logfile.ReadLogs(ReadConfig{Follow: true, Since: c.since, Tail: 0}, c.reader)\n\tgo c.copySrc()\n}", "func (b *Builder) Run() error {\n\tdefer b.Cleanup()\n\tlogrus.Debug(b.Options)\n\n\tfor _, s := range b.steps {\n\t\terr := s()\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tos.Chdir(b.Root)\n\t}\n\treturn nil\n}", "func (m *Manager) Run() error {\n\tfor range m.ctx.Done() {\n\t\tm.cancelDiscoverers()\n\t\treturn m.ctx.Err()\n\t}\n\treturn nil\n}", "func (client *AMIClient) Run() {\n\tgo func() {\n\t\tfor {\n\t\t\tdata, err := readMessage(client.bufReader)\n\t\t\tif err != nil {\n\t\t\t\tswitch err {\n\t\t\t\tcase syscall.ECONNABORTED:\n\t\t\t\t\tfallthrough\n\t\t\t\tcase syscall.ECONNRESET:\n\t\t\t\t\tfallthrough\n\t\t\t\tcase syscall.ECONNREFUSED:\n\t\t\t\t\tfallthrough\n\t\t\t\tcase io.EOF:\n\t\t\t\t\tclient.NetError <- err\n\t\t\t\t\t<-client.waitNewConnection\n\t\t\t\tdefault:\n\t\t\t\t\tclient.Error <- err\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ev, err := newEvent(data); err != nil {\n\t\t\t\tif err != errNotEvent {\n\t\t\t\t\tclient.Error <- err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tclient.Events <- ev\n\t\t\t}\n\n\t\t\tif response, err := newResponse(data); err == nil {\n\t\t\t\tclient.notifyResponse(response)\n\t\t\t}\n\n\t\t}\n\t}()\n}", "func (r SortedRunner) Close() error {\n\treturn nil\n}", "func (r *serverOneDotOne) Run() {\n\tr.state = RstateRunning\n\n\t// event handling is a NOP in this model\n\trxcallback := func(ev EventInterface) int {\n\t\tassert(r == ev.GetTarget())\n\t\tlog(LogVV, \"proc-ed\", ev.String())\n\t\treturn 0\n\t}\n\n\tgo func() {\n\t\tfor r.state == RstateRunning {\n\t\t\tr.receiveEnqueue()\n\t\t\ttime.Sleep(time.Microsecond)\n\t\t\tr.processPendingEvents(rxcallback)\n\t\t}\n\t}()\n}", "func (r *Room) Run() {\n\n\tgo r.EventDespatcher.RunEventLoop()\n\tr.logger.Info(\"cmp\", \"Room\", \"method\", \"Run\", \"msg\", fmt.Sprintf(\"%s Room running\", r.Name))\n}", "func (rnr *Runner) Run(args map[string]interface{}) (err error) {\n\n\trnr.Log.Debug(\"** Run **\")\n\n\t// signal channel\n\tsigChan := make(chan os.Signal, 1)\n\tsignal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)\n\n\t// run HTTP server\n\tgo func() {\n\t\trnr.Log.Debug(\"** Running HTTP server process **\")\n\t\terr = rnr.RunHTTPFunc(args)\n\t\tif err != nil {\n\t\t\trnr.Log.Error(\"Failed run server >%v<\", err)\n\t\t\tsigChan <- syscall.SIGTERM\n\t\t}\n\t\trnr.Log.Debug(\"** HTTP server process ended **\")\n\t}()\n\n\t// run daemon server\n\tgo func() {\n\t\trnr.Log.Debug(\"** Running daemon process **\")\n\t\terr = rnr.RunDaemonFunc(args)\n\t\tif err != nil {\n\t\t\trnr.Log.Error(\"Failed run daemon >%v<\", err)\n\t\t\tsigChan <- syscall.SIGTERM\n\t\t}\n\t\trnr.Log.Debug(\"** Daemon process ended **\")\n\t}()\n\n\t// wait\n\tsig := <-sigChan\n\n\tvar m runtime.MemStats\n\truntime.ReadMemStats(&m)\n\n\tbToMb := func(b uint64) uint64 {\n\t\treturn b / 1024 / 1024\n\t}\n\n\terr = fmt.Errorf(\"Received SIG >%v< Mem Alloc >%d MiB< TotalAlloc >%d MiB< Sys >%d MiB< NumGC >%d<\",\n\t\tsig,\n\t\tbToMb(m.Alloc),\n\t\tbToMb(m.TotalAlloc),\n\t\tbToMb(m.Sys),\n\t\tm.NumGC,\n\t)\n\n\trnr.Log.Warn(\">%v<\", err)\n\n\treturn err\n}", "func (a *Agent) Run() {\n\tagent.RegisterAPIValidator(a.validateAPI)\n\tagent.OnConfigChange(a.onConfigChange)\n\n\tgo a.discoveryLoop()\n\tgo a.publishLoop()\n\n\tselect {\n\tcase <-a.stopAgent:\n\t\tlog.Info(\"Received request to kill agent\")\n\t\ta.stopDiscovery <- true\n\t\ta.stopPublish <- true\n\t\treturn\n\t}\n}", "func (p *Pump) Run() {\n\tgo p.run()\n}", "func (p *Processor) Run(ctx context.Context) error {\n\terr := p.runImpl(ctx)\n\n\t// the context is the proper way to close down the Run() loop, so it's not\n\t// an error and doesn't need to be returned.\n\tif ctx.Err() != nil {\n\t\treturn nil\n\t}\n\n\treturn err\n}", "func (b *Boomer) Run() {\n\tb.results = make(chan *result, b.N)\n\n\ttotalRequests = 0\n\trequestCountChan = make(chan int)\n\tquit = make(chan bool)\n\n\tstart := time.Now()\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\n\n\tgo func() {\n\t\t<-c\n\t\tfmt.Print(\"quit\\n\")\n\t\t// TODO(jbd): Progress bar should not be finalized.\n\t\tnewReport(b.N, b.results, b.Output, time.Now().Sub(start)).finalize()\n\n\t\tclose(requestCountChan)\n\t\tos.Exit(1)\n\t}()\n\tgo showProgress(b.C) // sunny\n\n\tif b.EnableEngineIo {\n\t\tgo b.readConsole()\n\t\tb.clients = make([]*engineioclient2.Client, b.C)\n\t\tb.startTimes = make([]time.Time, b.C)\n\t\tb.durations = make([]time.Duration, b.C)\n\t}\n\tb.runWorkers()\n\n\tfmt.Printf(\"Finished %d requests\\n\\n\", totalRequests)\n\tclose(requestCountChan)\n\n\tnewReport(b.N, b.results, b.Output, time.Now().Sub(start)).finalize()\n\tclose(b.results)\n\t//<-quit\n}", "func (s *Server) Run() error {\n\tpath := fmt.Sprintf(\"%s:%d\", s.host, s.port)\n\tlog.Printf(\"Starting %s server on: %s\", s.protocol, path)\n\n\tlistener, err := net.Listen(s.protocol, path)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// I usually use helper function, but don't want to call it only once.\n\tdefer func() {\n\t\tif err := listener.Close(); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}() // dont want to loose possible error\n\n\t// Pass context for the graceful shutdown.\n\t// It's not relevant in this lab (and it could be done far better),\n\t// but it's the best practice in go to use ctx\n\ts.handleConnections(s.handleCancel(), listener)\n\n\treturn nil\n}", "func (il *inputLoop) Run(ctx context.Context) error {\n\tdefer close(il.execQueue)\n\tg, lctx := errgroup.WithContext(ctx)\n\tif len(il.spec.Inputs) > 0 {\n\t\t// Watch inputs\n\t\tfor _, tis := range il.spec.Inputs {\n\t\t\ttis := tis // Bring in scope\n\t\t\tstats := il.statistics.InputByName(tis.Name)\n\t\t\tg.Go(func() error {\n\t\t\t\treturn il.watchInput(lctx, il.spec.SnapshotPolicy, tis, stats)\n\t\t\t})\n\t\t}\n\t}\n\tif il.spec.HasLaunchPolicyCustom() {\n\t\t// Custom launch policy, run executor all the time\n\t\tg.Go(func() error {\n\t\t\treturn il.runExecWithCustomLaunchPolicy(lctx)\n\t\t})\n\t}\n\tg.Go(func() error {\n\t\treturn il.processExecQueue(lctx)\n\t})\n\tif err := g.Wait(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (cli *CLI) Run(args []string) int {\n\n\tc, err := cli.setup(args)\n\tif err != nil {\n\t\tlogging.Error(\"unable to parse configuration: %v\", err)\n\t\treturn ExitCodeParseConfigError\n\t}\n\n\t// Set the logging level for the logger.\n\tlogging.SetLevel(c.LogLevel)\n\n\t// Initialize telemetry if this was configured by the user.\n\tif c.Telemetry.StatsdAddress != \"\" {\n\t\tsink, statsErr := metrics.NewStatsdSink(c.Telemetry.StatsdAddress)\n\t\tif statsErr != nil {\n\t\t\tlogging.Error(\"unable to setup telemetry correctly: %v\", statsErr)\n\t\t\treturn ExitCodeTelemtryError\n\t\t}\n\t\tmetrics.NewGlobal(metrics.DefaultConfig(\"replicator\"), sink)\n\t}\n\n\t// Create the initial runner with the merged configuration parameters.\n\trunner, err := NewRunner(c)\n\tif err != nil {\n\t\treturn ExitCodeRunnerError\n\t}\n\n\tlogging.Debug(\"running version %v\", version.Get())\n\tgo runner.Start()\n\n\tsignalCh := make(chan os.Signal, 1)\n\tsignal.Notify(signalCh,\n\t\tsyscall.SIGHUP,\n\t\tsyscall.SIGINT,\n\t\tsyscall.SIGTERM,\n\t\tsyscall.SIGQUIT,\n\t)\n\n\tfor {\n\t\tselect {\n\t\tcase s := <-signalCh:\n\t\t\tswitch s {\n\t\t\tcase syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:\n\t\t\t\trunner.Stop()\n\t\t\t\treturn ExitCodeInterrupt\n\n\t\t\tcase syscall.SIGHUP:\n\t\t\t\trunner.Stop()\n\n\t\t\t\t// Reload the configuration in order to make proper use of SIGHUP.\n\t\t\t\tc, err := cli.setup(args)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn ExitCodeParseConfigError\n\t\t\t\t}\n\n\t\t\t\t// Setup a new runner with the new configuration.\n\t\t\t\trunner, err = NewRunner(c)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn ExitCodeRunnerError\n\t\t\t\t}\n\n\t\t\t\tgo runner.Start()\n\t\t\t}\n\t\t}\n\t}\n}", "func (w *WorkerManager) Run(ctx context.Context, filename string) {\n\tstats.StartTimer()\n\n\tdefer w.close()\n\n\tvar r io.ReadCloser\n\tvar err error\n\n\tif filename == \"-\" {\n\t\tr = os.Stdin\n\t} else {\n\t\tr, err = os.Open(filename)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer r.Close()\n\t}\n\n\tw.produceWithScanner(ctx, r)\n}", "func (p *Pipeline) Run() {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tp.RunWithContext(ctx, cancel)\n}", "func (p *Pipeline) Run() {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tp.RunWithContext(ctx, cancel)\n}", "func (self *Server) Run(quit chan int) {\n\n\t//takes in raw events and push the onto channel\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\n\t\t\tcase e <- RawEventIn:\n\t\t\t\t{\n\t\t\t\t\terr := CheckMsgAuth(e)\n\t\t\t\t\tif err == nil {\n\n\t\t\t\t\t\te.EventResponse <- \"error invalid message\"\n\t\t\t\t\t\tbreak //ignore messages that are invalid\n\t\t\t\t\t\t//return error to event channel\n\t\t\t\t\t}\n\t\t\t\t\terr = self.RawEventToEvent(e) //push onto event loops\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//main:\n\n\t}()\n}", "func (c *XDSClient) Run(ctx context.Context) error {\n\terr := c.run(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.handleRecv()\n}", "func (b *RunStep) Run(state quantum.StateBag) error {\n\trunner := state.Get(\"runner\").(quantum.Runner)\n\tconn := state.Get(\"conn\").(quantum.AgentConn)\n\toutCh := conn.Logs()\n\tsigCh := conn.Signals()\n\n\tif b.Command == \"\" {\n\t\tcommandRaw, ok := state.GetOk(\"command\")\n\t\tif ok {\n\t\t\tb.Command = commandRaw.(string)\n\t\t}\n\t}\n\n\tlog.Printf(\"Running command: %v\", b.Command)\n\n\terr := runner.Run(b.Command, outCh, sigCh)\n\tif err != nil {\n\t\treturn errors.New(\"Cmd: \" + b.Command + \" failed: \" + err.Error())\n\t}\n\treturn nil\n}", "func (n *Ncd) Run() {\n\tn._start()\n}", "func (r *Router) Run(ctx context.Context) (err error) {\n\tif r.isRunning {\n\t\treturn errors.New(\"router is already running\")\n\t}\n\tr.isRunning = true\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tr.logger.Debug(\"Loading plugins\", nil)\n\tfor _, plugin := range r.plugins {\n\t\tif err := plugin(r); err != nil {\n\t\t\treturn errors.Wrapf(err, \"cannot initialize plugin %v\", plugin)\n\t\t}\n\t}\n\n\tif err := r.RunHandlers(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tclose(r.running)\n\n\tgo r.closeWhenAllHandlersStopped(ctx)\n\n\t<-r.closingInProgressCh\n\tcancel()\n\n\tr.logger.Info(\"Waiting for messages\", watermill.LogFields{\n\t\t\"timeout\": r.config.CloseTimeout,\n\t})\n\n\t<-r.closedCh\n\n\tr.logger.Info(\"All messages processed\", nil)\n\n\treturn nil\n}", "func Run() {\n\tl := logrus.WithField(\"component\", \"main\")\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer l.Info(\"Done.\")\n\n\t// handle termination signals\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals, unix.SIGTERM, unix.SIGINT)\n\tgo func() {\n\t\ts := <-signals\n\t\tsignal.Stop(signals)\n\t\tl.Warnf(\"Got %s, shutting down...\", unix.SignalName(s.(unix.Signal)))\n\t\tcancel()\n\t}()\n\n\tfor {\n\t\tcfg, configFilepath, err := config.Get(l)\n\t\tif err != nil {\n\t\t\tl.Fatalf(\"Failed to load configuration: %s.\", err)\n\t\t}\n\t\tconfig.ConfigureLogger(cfg)\n\t\tl.Debugf(\"Loaded configuration: %+v\", cfg)\n\n\t\trun(ctx, cfg, configFilepath)\n\n\t\tif ctx.Err() != nil {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (d *Downloader) Run(log *logrus.Entry) error {\n\tlog = log.WithField(\"app\", AppName)\n\n\t// Init the app\n\td.InitStart(log)\n\n\tlog.Debug(\"downloader started\")\n\td.event = make(chan struct{}, 1)\n\n\tif d.config.Downloader.LaunchAtStartup {\n\t\tlog.Debug(\"initial downloader launch\")\n\t\td.event <- struct{}{}\n\t}\n\n\t// Start the scheduler\n\td.Wg.Add(1)\n\tgo func() {\n\t\tdefer d.Wg.Done()\n\t\td.scheduler(log)\n\t}()\n\n\t// Start the downloader\n\tvar err error\n\td.Wg.Add(1)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\terr = subapp.ErrPanicRecovered\n\t\t\t\td.Stop(log)\n\t\t\t}\n\n\t\t\td.Wg.Done()\n\t\t}()\n\t\td.downloader(log)\n\t}()\n\n\tdefer log.Debug(\"downloader stopped\")\n\n\td.Wg.Wait()\n\n\treturn err\n}", "func (t *Task) Run() {\n\t// println(\"run step\", t.Step.Id, \"task\", t.Id)\n\tt.Step.Function(t)\n\tfor _, out := range t.Outputs {\n\t\tout.WriteChan.Close()\n\t}\n\t// println(\"stop step\", t.Step.Id, \"task\", t.Id)\n}", "func (c *Client) Run() error {\n\tc.generateClientID()\n\n\tlistener, err := net.Listen(\"tcp\", c.ListenAddr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to listen on %s: %s\", c.ListenAddr, err)\n\t}\n\n\tfmt.Println(\"Listening for incoming SOCKS connection...\")\n\t// accept local connections and tunnel them\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Accept Err:\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Println(\"new SOCKS conn\", conn.RemoteAddr().String())\n\n\t\tif !c.connected.IsSet() {\n\t\t\terr = c.connect()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Failed to connect to tunnel host:\", err)\n\t\t\t\tconn.Close()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// start watcher which closes when canceled\n\t\t\tgo c.watchCancel()\n\n\t\t\tc.connected.Set(true)\n\t\t}\n\n\t\tgo c.tunnelConn(conn)\n\t}\n}", "func (runnable *MockRunnable) Run() error {\n\targs := runnable.Called()\n\treturn args.Error(0)\n}", "func (a *API) Run() error {\n\treturn a.e.Start(a.addr)\n}", "func (s *Server) Run() error {\n\tfor {\n\t\tconn, err := s.ln.Accept()\n\t\tif err != nil {\n\t\t\toperr, ok := err.(*net.OpError)\n\t\t\tif !ok {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif operr.Temporary() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tgo s.handleConnection(conn)\n\t}\n}", "func (n *NetImpl) Run(shutdownSignal <-chan struct{}) {\n\tgo n.connectOutboundLoop()\n\tgo n.connectInboundLoop()\n\n\t<-shutdownSignal\n\n\tn.log.Info(\"Closing all connections with peers...\")\n\tn.closeAll()\n\tn.log.Info(\"Closing all connections with peers... done\")\n}", "func (j *Job) Run() {\n\tleftRunningTimes := j.times.Add(-1)\n\tif leftRunningTimes < 0 {\n\t\tj.status.Set(StatusClosed)\n\t\treturn\n\t}\n\t// This means it does not limit the running times.\n\t// I know it's ugly, but it is surely high performance for running times limit.\n\tif leftRunningTimes < 2000000000 && leftRunningTimes > 1000000000 {\n\t\tj.times.Set(math.MaxInt32)\n\t}\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tif err != panicExit {\n\t\t\t\t\tpanic(err)\n\t\t\t\t} else {\n\t\t\t\t\tj.Close()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif j.Status() == StatusRunning {\n\t\t\t\tj.SetStatus(StatusReady)\n\t\t\t}\n\t\t}()\n\t\tj.job()\n\t}()\n}", "func (d *Downloads) Run() {\n\tfor {\n\t\tselect {\n\t\tcase performer := <-d.performers:\n\t\t\tgo d.start(performer)\n\t\tcase <-d.quit:\n\t\t\td.close()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *ClientState) Run() error {\n\ts.DetermineInitialMasters()\n\tdefer s.closeRedisConnections()\n\tif err := s.Connect(); err != nil {\n\t\treturn err\n\t}\n\tif err := VerifyMasterFileString(s.GetConfig().RedisMasterFile); err != nil {\n\t\treturn err\n\t}\n\tif err := s.SendClientStarted(); err != nil {\n\t\treturn err\n\t}\n\tif s.opts.ConsulClient != nil {\n\t\tvar err error\n\t\ts.configChanges, err = s.opts.ConsulClient.WatchConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\ts.configChanges = make(chan consul.Env)\n\t}\n\tgo s.Reader()\n\ts.Writer()\n\treturn nil\n}", "func Run() {\n\tgo listen()\n}", "func (bot *Bot) Run() {\n\tbot.ircConn.Loop()\n}", "func (mts *metadataTestSender) Run(wg *sync.WaitGroup) {\n\tif mts.out.output == nil {\n\t\tpanic(\"metadataTestSender output not initialized for emitting rows\")\n\t}\n\tRun(mts.flowCtx.Ctx, mts, mts.out.output)\n\tif wg != nil {\n\t\twg.Done()\n\t}\n}", "func (s *Server) Run() {\n\ts.Config.set()\n\tfor {\n\t\tconn, err := s.Listener.Accept()\n\t\tif err != nil {\n\t\t\ts.Config.ErrorLog(\"fail to accept new connection: %s\", err)\n\t\t}\n\t\tgo s.handleConn(conn)\n\t}\n}", "func (s *Server) Run(ctx context.Context, callback func(context.Context) error) error {\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\t// TODO(sajjadm): Add Export here when implemented and explain it in the function comment.\n\tif err := s.Start(ctx); err != nil {\n\t\treturn err\n\t}\n\tdefer s.Close()\n\n\tdone := make(chan error)\n\tgo func() {\n\t\tdone <- callback(ctx)\n\t}()\n\n\tselect {\n\tcase err := <-s.errC:\n\t\tcancel()\n\t\t<-done\n\t\treturn err\n\tcase err := <-done:\n\t\treturn err\n\t}\n}", "func (uc *UseCase) Run(r *Runner) (err error) {\n\tuc.runner = r\n\t// Start with a fresh memory cache as each run is separate from any other.\n\tuc.memory = map[string]interface{}{}\n\tpath := uc.Filepath\n\tif !r.NoColor {\n\t\tif 80 <= len(path) {\n\t\t\tpath = underline + path + normal\n\t\t} else {\n\t\t\tpath = underline + path + strings.Repeat(\" \", (80-len(path))) + normal\n\t\t}\n\t}\n\tif 0 < len(uc.Comment) {\n\t\tr.Log(aComment, \"\\n%s\\n%s\\n\", path, uc.Comment)\n\t} else {\n\t\tr.Log(aComment, \"\\n%s\\n\", path)\n\t}\n\tfor _, step := range uc.Steps {\n\t\tif err == nil {\n\t\t\terr = step.Execute(uc)\n\t\t} else if step.Always {\n\t\t\t_ = step.Execute(uc)\n\t\t}\n\t}\n\treturn\n}", "func (c *Coordinator) Run(ctx context.Context) error {\n\tc.logEntry.Info(\"Starting\")\n\terr := c.run(ctx)\n\tc.logEntry.Info(\"Waiting for games to stop...\")\n\tc.gamesWG.Wait()\n\tc.logEntry.Info(\"Stopped\")\n\treturn err\n}", "func (o Options) Run(ctx context.Context, cfg client.Config) error {\n\tc, err := client.New(cfg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating client: %w\", err)\n\t}\n\n\teg, ctx := errgroup.WithContext(ctx)\n\n\tfor i := 0; i < o.Amount; i++ {\n\t\teg.Go(func() error {\n\t\t\tfor ctx.Err() == nil {\n\t\t\t\treq, err := http.NewRequestWithContext(ctx, \"POST\", o.URL.String(), slowRandromReader{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"creating request: %w\", err)\n\t\t\t\t}\n\n\t\t\t\tresp, err := c.Do(req)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"sending request: %w\", err)\n\t\t\t\t}\n\t\t\t\tdefer resp.Body.Close()\n\n\t\t\t\tif _, err := io.ReadAll(resp.Body); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"draining body: %w\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\treturn eg.Wait()\n}", "func Run(ctx context.Context, p *beam.Pipeline) error {\n\t_, err := beam.Run(ctx, getRunner(), p)\n\treturn err\n}", "func (s *Spinner) Run(ctx context.Context) error {\n\ts.push(ctx, NewEvent(s, EventRunRequested, nil))\n\n\tcmdCtx, cancel := context.WithTimeout(ctx, s.timeout)\n\tdefer cancel()\n\n\tlogger := s.step.logger\n\n\t// add this spinner to the context for the log writers\n\tctx = context.WithValue(ctx, CtxSpinner, s)\n\n\toutChannel := NewLogWriter(ctx, logger, logrus.DebugLevel)\n\terrChannel := NewLogWriter(ctx, logger, logrus.ErrorLevel)\n\n\tlogger.WithField(FldStep, s.Name).Tracef(\"Running %s with %s\", s.cmd, s.args)\n\n\tcmd := exec.CommandContext(cmdCtx, s.cmd, s.args...)\n\tcmd.Stderr = errChannel\n\tcmd.Stdout = outChannel\n\tenvs := os.Environ()\n\tfor _, env := range s.env {\n\t\tenvs = append(envs, env)\n\t}\n\n\tcmd.Env = envs\n\tcmd.Dir = s.workdir\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\ts.push(ctx, NewEvent(s, EventRunError, nil))\n\n\t\treturn err\n\t}\n\n\ts.push(ctx, NewEvent(s, EventRunStarted, nil))\n\n\tif err := cmd.Wait(); err != nil {\n\t\tif cmdCtx.Err() == context.DeadlineExceeded {\n\t\t\ts.push(ctx, NewEvent(s, EventRunTimeout, nil))\n\n\t\t\treturn fmt.Errorf(\"Timed out after %s\", s.timeout)\n\t\t}\n\n\t\tif exitErr, ok := err.(*exec.ExitError); ok {\n\t\t\t// The program has exited with an exit code != 0\n\t\t\tif status, ok := exitErr.Sys().(syscall.WaitStatus); ok {\n\t\t\t\ts.push(ctx, NewEvent(s, EventRunFail, status))\n\t\t\t\treturn exitErr\n\t\t\t}\n\t\t} else {\n\t\t\t// wait error\n\t\t\ts.push(ctx, NewEvent(s, EventRunWaitError, s))\n\n\t\t\treturn exitErr\n\t\t}\n\t}\n\n\ts.push(ctx, NewEvent(s, EventRunSuccess, nil))\n\n\treturn nil\n}", "func (i *IRC) Run() {\n\ti.wg.Add(1)\n\tgo func() {\n\t\tdefer i.wg.Done()\n\t\ti.conn.Loop()\n\t}()\n}", "func (srv *Server) Run() <-chan error {\n\terrs := make(chan error)\n\n\tgo func() {\n\t\tdefer close(errs)\n\t\tif err := srv.ListenAndServe(); err != nil {\n\t\t\terrs <- err\n\t\t}\n\t}()\n\n\treturn errs\n}", "func (c *SystemdCheck) Run() error {\n\tsender, err := c.GetSender()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn, err := c.connect(sender)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.stats.CloseConn(conn)\n\n\tc.submitVersion(conn)\n\tc.submitSystemdState(sender, conn)\n\n\terr = c.submitMetrics(sender, conn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsender.Commit()\n\n\treturn nil\n}", "func (r *gatewayOneDotOne) Run() {\n\tr.state = RstateRunning\n\n\tgo func() {\n\t\tfor r.state == RstateRunning {\n\t\t\tr.send()\n\t\t\ttime.Sleep(time.Microsecond * 100)\n\t\t}\n\t\tr.closeTxChannels()\n\t}()\n}", "func (execution *Execution) Run() error {\n\terr := execution.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = execution.Wait()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (rc *Controller) Run(ctx context.Context) error {\n\topts := []func(context.Context) error{\n\t\trc.setGlobalVariables,\n\t\trc.restoreSchema,\n\t\trc.preCheckRequirements,\n\t\trc.initCheckpoint,\n\t\trc.importTables,\n\t\trc.fullCompact,\n\t\trc.cleanCheckpoints,\n\t}\n\n\ttask := log.FromContext(ctx).Begin(zap.InfoLevel, \"the whole procedure\")\n\n\tvar err error\n\tfinished := false\noutside:\n\tfor i, process := range opts {\n\t\terr = process(ctx)\n\t\tif i == len(opts)-1 {\n\t\t\tfinished = true\n\t\t}\n\t\tlogger := task.With(zap.Int(\"step\", i), log.ShortError(err))\n\n\t\tswitch {\n\t\tcase err == nil:\n\t\tcase log.IsContextCanceledError(err):\n\t\t\tlogger.Info(\"task canceled\")\n\t\t\tbreak outside\n\t\tdefault:\n\t\t\tlogger.Error(\"run failed\")\n\t\t\tbreak outside // ps : not continue\n\t\t}\n\t}\n\n\t// if process is cancelled, should make sure checkpoints are written to db.\n\tif !finished {\n\t\trc.waitCheckpointFinish()\n\t}\n\n\ttask.End(zap.ErrorLevel, err)\n\trc.errorMgr.LogErrorDetails()\n\trc.errorSummaries.emitLog()\n\n\treturn errors.Trace(err)\n}", "func (r *Runner) Run(ctx context.Context, node syntax.Node) error {\n\tif !r.didReset {\n\t\tr.Reset()\n\t}\n\tr.err = nil\n\tr.filename = \"\"\n\tswitch x := node.(type) {\n\tcase *syntax.File:\n\t\tr.filename = x.Name\n\t\tr.stmts(ctx, x.StmtList)\n\tcase *syntax.Stmt:\n\t\tr.stmt(ctx, x)\n\tcase syntax.Command:\n\t\tr.cmd(ctx, x)\n\tdefault:\n\t\treturn fmt.Errorf(\"Node can only be File, Stmt, or Command: %T\", x)\n\t}\n\tif r.exit > 0 {\n\t\tr.setErr(ExitStatus(r.exit))\n\t}\n\treturn r.err\n}", "func (action *Action) Run(service string, cli kt.CliInterface, options *options.DaemonOptions) error {\n\tch := SetUpCloseHandler(cli, options, \"run\")\n\trun(service, cli, options)\n\t<-ch\n\treturn nil\n}", "func (c *Client) Run() {\n\tctx, cancel := context.WithCancel(context.Background())\n\t// TODO: Possibly switch these to prioritize select statements\n\t// to handle case where backupper returns an error\n\t// https://stackoverflow.com/questions/46200343/force-priority-of-go-select-statement/46202533#46202533\n\tgo func() {\n\t\tc.Backupper.Run(ctx)\n\t}()\n\n\tgo func() {\n\t\tfor msg := range c.Conn.Read() {\n\t\t\tc.Broadcaster.Broadcast() <- &broker.Message{Payload: msg}\n\n\t\t\tc.Backupper.Hold(msg)\n\t\t}\n\t\tc.Broadcaster.Unregister() <- c.Receive // shutdown the client because the connection was closed\n\t}()\n\n\tgo func() {\n\t\tfor bmsg := range c.Receive {\n\t\t\tc.Conn.Write() <- bmsg.Payload.(*Message)\n\t\t}\n\t\tcancel()\n\t}()\n}", "func (s *Sampler) Run() {\n\tgo func() {\n\t\tdefer watchdog.LogOnPanic()\n\t\ts.Backend.Run()\n\t}()\n\ts.RunAdjustScoring()\n}", "func (s *Server) Run() {\n\tfor {\n\t\tconn, err := s.l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Accept error: %v\\n\", err)\n\t\t} else {\n\t\t\tgo s.handlerConn(conn)\n\t\t}\n\t}\n}", "func (r *Reader) run() {\n\tdefer r.cancel()\n\tdefer close(r.done)\n\tdefer r.stmt.Close()\n\n\tvar err error\n\n\tfor err == nil {\n\t\terr = r.tick()\n\t}\n\n\tif err != context.Canceled {\n\t\tr.done <- err\n\t}\n}", "func (r *ProblemRunner) Run() error {\n\tr.problems = map[uint64]Problem{}\n\tr.evaluators = map[uint64]Evaluator{}\n\n\tif err := r.castProblemSpec(); err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\tdoContinue, err := r.runOnce()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !doContinue {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}", "func (w Watcher) Run(stopCh <-chan struct{}) {\n\tfmt.Println(\"client/run:Running\")\n\tgo w.controller.Run(stopCh)\n}", "func (s *HttpServer) Run() {\n\n\tgo s.httpServer()\n\t<-s.quitChan\n}" ]
[ "0.69904256", "0.6832305", "0.6797363", "0.66353744", "0.65243745", "0.6519319", "0.6473249", "0.63717395", "0.6355448", "0.6291291", "0.62721133", "0.625664", "0.6250894", "0.62359995", "0.6224739", "0.61857235", "0.6171192", "0.6163286", "0.614711", "0.61339176", "0.6131875", "0.61293787", "0.6124126", "0.61210525", "0.61198807", "0.6118933", "0.60843706", "0.6077154", "0.60701936", "0.60649633", "0.60593504", "0.60558003", "0.60556436", "0.6054978", "0.6041262", "0.60241723", "0.6016003", "0.5998901", "0.59927183", "0.5973371", "0.59574455", "0.59570414", "0.5956031", "0.5950277", "0.5947567", "0.59471536", "0.59334844", "0.59291214", "0.5923277", "0.59172326", "0.5914489", "0.5906692", "0.5900211", "0.5896232", "0.58917665", "0.589009", "0.5889124", "0.58876806", "0.58839244", "0.58839244", "0.58835036", "0.58742183", "0.58734107", "0.58733857", "0.58609545", "0.58588636", "0.5851516", "0.58506477", "0.58479583", "0.5847131", "0.5839245", "0.5836368", "0.58236736", "0.5822395", "0.58201295", "0.58096415", "0.5804301", "0.58027256", "0.58018005", "0.5799465", "0.5795059", "0.57908404", "0.57875067", "0.5786611", "0.5784194", "0.57835186", "0.5782702", "0.5778267", "0.5776678", "0.57755274", "0.57690203", "0.5763817", "0.576069", "0.57597625", "0.5757954", "0.574888", "0.574494", "0.5744615", "0.57430565", "0.5742467", "0.5739541" ]
0.0
-1
WhileRunning do something if it is running. It provides a context o check if it stops.
func (s *DeterminationWithContext) WhileRunning(do func(context.Context) error) error { return s.whilerunning(func() error { select { case <-s.sctx.Done(): return ErrRunnerIsClosing default: return do(s.sctx) } }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Manager) WaitUntilRunning() {\n\tfor {\n\t\tm.mu.Lock()\n\n\t\tif m.ctx != nil {\n\t\t\tm.mu.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\tstarted := m.started\n\t\tm.mu.Unlock()\n\n\t\t// Block until we have been started.\n\t\t<-started\n\t}\n}", "func (s *Stopwatch) isRunning() bool {\n\treturn !s.refTime.IsZero()\n}", "func (w *watcher) checkLoop(ctx context.Context) {\n\tfor atomic.LoadInt32(&w.state) == isRunning {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tw.Close()\n\t\t\tw.dispose()\n\t\t\treturn\n\t\tdefault:\n\t\t\tw.check(ctx)\n\t\t\ttime.Sleep(w.interval)\n\t\t}\n\t}\n}", "func (w *worker) isRunning() bool {\n\treturn atomic.LoadInt32(&w.running) == 1\n}", "func (f *flushDaemon) isRunning() bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\treturn f.stopC != nil\n}", "func runWhileFilesystemLives(f func() error, label string, filesystemId string, errorBackoff, successBackoff time.Duration) {\n\tdeathChan := make(chan interface{})\n\tdeathObserver.Subscribe(filesystemId, deathChan)\n\tstillAlive := true\n\tfor stillAlive {\n\t\tselect {\n\t\tcase _ = <-deathChan:\n\t\t\tstillAlive = false\n\t\tdefault:\n\t\t\terr := f()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\n\t\t\t\t\t\"Error in runWhileFilesystemLives(%s@%s), retrying in %s: %s\",\n\t\t\t\t\tlabel, filesystemId, errorBackoff, err)\n\t\t\t\ttime.Sleep(errorBackoff)\n\t\t\t} else {\n\t\t\t\ttime.Sleep(successBackoff)\n\t\t\t}\n\t\t}\n\t}\n\tdeathObserver.Unsubscribe(filesystemId, deathChan)\n}", "func (m *WebsocketRoutineManager) IsRunning() bool {\n\tif m == nil {\n\t\treturn false\n\t}\n\treturn atomic.LoadInt32(&m.state) == readyState\n}", "func (p *adapter) Running() bool {\n\tif p.cmd == nil || p.cmd.Process == nil || p.cmd.Process.Pid == 0 || p.state() != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func running() bool {\n\treturn runCalled.Load() != 0\n}", "func (i *info) IsRunning() bool {\n\t_, ok := i.driver.activeContainers[i.ID]\n\treturn ok\n}", "func (b *Backtest) IsRunning() (ret bool) {\n\treturn b.running\n}", "func (b *base) IsRunning() bool {\n\treturn b.isRunning\n}", "func (h *Module) IsRunning()bool{\n\treturn h.running\n}", "func (p *AbstractRunProvider) IsRunning() bool {\n\treturn p.running\n}", "func (s *Stopwatch) IsRunning() bool {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\treturn s.isRunning()\n}", "func (t *task) IsRunning() bool {\n\treturn t.running\n}", "func (folderWatcher *FolderWatcher) IsRunning() bool {\n\treturn folderWatcher.running\n}", "func isRunning(on_node, operation, rcCode string) bool {\n\treturn on_node != \"\" && (operation == \"start\" || (operation == \"monitor\" && rcCode == \"0\"))\n}", "func (sc *ConditionsScraper) Running() bool {\n\treturn sc.running\n}", "func (s *Scanner) IsRunning() bool {\n\treturn s.state == running\n}", "func (p *procBase) Running() bool {\n\treturn p.cmd != nil\n}", "func (r *Router) IsRunning() bool {\n\tselect {\n\tcase <-r.running:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (ss sservice) IsRunning(status string) bool {\n\tre := regexp.MustCompile(`is running`)\n\treturn re.Match([]byte(status))\n}", "func (r *Runner) IsRunning(id string) bool {\n\tr.rw.RLock()\n\tdefer r.rw.RUnlock()\n\t_, ok := r.jobsCancel[id]\n\n\treturn ok\n}", "func (i *Interval) IsRunning() bool {\n\treturn i.latch.IsRunning()\n}", "func (pb *PhilosopherBase) Runnable() bool {\n\treturn pb.State != philstate.Stopped\n}", "func (m *DataHistoryManager) IsRunning() bool {\n\tif m == nil {\n\t\treturn false\n\t}\n\treturn atomic.LoadInt32(&m.started) == 1\n}", "func (m *DataHistoryManager) IsRunning() bool {\n\tif m == nil {\n\t\treturn false\n\t}\n\treturn atomic.LoadInt32(&m.started) == 1\n}", "func (bc *BotCommand) isRunning() bool {\n\tbc.Lock()\n\tdefer bc.Unlock()\n\treturn bc.running\n}", "func (m *ntpManager) IsRunning() bool {\n\tif m == nil {\n\t\treturn false\n\t}\n\treturn atomic.LoadInt32(&m.started) == 1\n}", "func (a *Recorder) IsRunning() bool {\n\treturn atomic.LoadUint32(&a.isRunning) != 0\n}", "func (tr *TestRunner) isStopped() bool {\n\tselect {\n\tcase <-tr.stop:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func checkForExit(ctx context.Context, client *docker.Client, containerID string) error {\n\tticker := time.NewTicker(2 * time.Second)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tinspectCtx, cancelInspect := xcontext.KeepAlive(ctx, 30*time.Second)\n\t\tisRunning, err := IsRunning(inspectCtx, client, containerID)\n\t\tcancelInspect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !isRunning {\n\t\t\toutput := new(strings.Builder)\n\t\t\tclient.Logs(docker.LogsOptions{\n\t\t\t\tContext: ctx,\n\t\t\t\tContainer: containerID,\n\t\t\t\tStdout: true,\n\t\t\t\tStderr: true,\n\t\t\t\tOutputStream: output,\n\t\t\t\tErrorStream: output,\n\t\t\t})\n\t\t\tif output.Len() == 0 {\n\t\t\t\treturn fmt.Errorf(\"container %s stopped running\", containerID)\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"container %s stopped running:\\n%s\", containerID, strings.TrimSuffix(output.String(), \"\\n\"))\n\t\t}\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (s *Server) IsRunning() bool { return s.running }", "func (e *executor) isRunning(file string) *runInfo {\n\te.mRun.Lock()\n\tdefer e.mRun.Unlock()\n\treturn e.running[file]\n}", "func (c *Consumer) IsRunning() bool {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\treturn c.running\n}", "func (dw *DoWhileTaskBehavior) evaluateCondition(ctx model.TaskContext, condition expression.Expr) (evalResult model.EvalResult, err error) {\n\tif t, ok := ctx.(*instance.TaskInst); ok {\n\t\tresult, err := condition.Eval(getScope(ctx, t))\n\t\tif err != nil {\n\t\t\treturn model.EvalFail, err\n\t\t}\n\t\tif result.(bool) {\n\t\t\tdelay := ctx.Task().LoopConfig().Delay()\n\t\t\tif delay > 0 {\n\t\t\t\tctx.FlowLogger().Infof(\"Dowhile Task[%s] execution delaying for %d milliseconds...\", ctx.Task().ID(), delay)\n\t\t\t\ttime.Sleep(time.Duration(delay) * time.Millisecond)\n\t\t\t}\n\t\t\tctx.FlowLogger().Infof(\"Task[%s] repeating as doWhile condition evaluated to true\", ctx.Task().ID())\n\t\t\treturn model.EvalRepeat, nil\n\t\t}\n\t\tctx.FlowLogger().Infof(\"Task[%s] doWhile condition evaluated to false\", ctx.Task().ID())\n\t}\n\treturn model.EvalDone, nil\n}", "func (l *List) IsRunning() bool {\n\treturn l.list.IsRunning()\n}", "func (p *Poller) IsStopped() bool {\n\treturn p.isStopped\n}", "func (i *Inbound) IsRunning() bool {\n\treturn i.once.IsRunning()\n}", "func (i *Intel8080) Running() bool {\n\treturn !i.halted\n}", "func WaitUntilRunning(service Service, timeout time.Duration) error {\n\treturn WaitUntil(service, true, timeout)\n}", "func (n *Ncd) IsRunning() bool {\n\treturn n.rtconf.Running\n}", "func (b *Build) IsRunning() bool {\n\treturn (b.Status == StatusStarted || b.Status == StatusEnqueue)\n}", "func LoopContext(ctx context.Context, interval time.Duration, loopFn, cleanupFn func()) {\n\tdefer cleanupFn()\n\n\tfor !ContextDone(ctx) {\n\t\tloopFn()\n\t\tif !DelayContext(ctx, interval) {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (t *DeferredRecordingTaskImpl) IsRunning() bool {\n\treturn t.task.IsRunning()\n}", "func (s *SegmentUpdateWorker) IsRunning() bool {\n\treturn s.lifecycle.IsRunning()\n}", "func (scheduler *Scheduler) IsRunning() bool {\n\treturn atomic.LoadInt32(&scheduler.isRunning) == 1\n}", "func (nl *Logger) Running() bool {\n\tnl.mu.Lock()\n\tdefer nl.mu.Unlock()\n\treturn nl.logger != nil\n}", "func (c *TestController) IsRunning(id TestID) bool {\n\treturn c.lookupJob(id) != nil\n}", "func (n *notifier) serviceLoop() {\n\tn.lock.Lock()\n\tdefer n.lock.Unlock()\n\tfor {\n\t\tfor n.desired == n.current {\n\t\t\tn.cond.Wait()\n\t\t}\n\t\tif n.current != n.id && n.desired == n.id {\n\t\t\tn.service.Validate(n.desired, n.current)\n\t\t\tn.service.Start()\n\t\t} else if n.current == n.id && n.desired != n.id {\n\t\t\tn.service.Stop()\n\t\t}\n\t\tn.current = n.desired\n\t}\n}", "func (s *Service) Running() bool {\n\tif m := s.mgr; m == nil {\n\t\treturn false\n\t} else {\n\t\tm.lock()\n\t\trv := s.running && !s.stopping\n\t\tm.unlock()\n\t\treturn rv\n\t}\n}", "func (m *Monitor) run(ctx context.Context) {\n\tdefer close(m.stopCh)\n\tdefer close(m.events)\n\tdefer m.log.Info(\"event loop stopped\")\n\tf := filters.NewArgs()\n\tf.Add(\"event\", \"start\")\n\tf.Add(\"event\", \"die\")\n\toptions := types.EventsOptions{Filters: f}\n\tfor {\n\t\terr := func() error {\n\t\t\tm.log.Info(\"processing existing containers\")\n\t\t\tif err := m.processContainers(ctx); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.log.Info(\"starting event loop\")\n\t\t\tmsgChan, errChan := m.client.Events(ctx, options)\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase msg := <-msgChan:\n\t\t\t\t\tif err := m.processMessage(ctx, msg); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\tcase err := <-errChan:\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tif err == context.Canceled {\n\t\t\treturn\n\t\t}\n\t\tm.log.Error(err)\n\t\tm.log.Info(\"reconnecting in 30 seconds\")\n\t\tselect {\n\t\tcase <-time.After(30 * time.Second):\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c Container) IsRunning() bool {\n\treturn c.containerInfo.State.Running\n}", "func (c *D) IsRunning() bool {\n\tif c.cmd == nil {\n\t\treturn false\n\t}\n\tif c.cmd.Process == nil {\n\t\treturn false\n\t}\n\tprocess, err := ps.FindProcess(c.cmd.Process.Pid)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif process == nil && err == nil {\n\t\t// not found\n\t\treturn false\n\t}\n\treturn true\n}", "func (app *frame) IsStopped() bool {\n\treturn app.isStopped\n}", "func (c *Consumer) loop() {\n\tvar stop bool\n\tfor !stop {\n\t\tselect {\n\t\tcase <-c.status: // ...\n\t\tcase <-c.pause: // ...\n\t\tcase <-c.resume: // ...\n\t\tcase <-c.stop: // ...\n\t\tcase resp := <-c.pausedQuery: // ...\n\t\tcase <-c.exit:\n\t\t\tstop = true\n\t\t}\n\t}\n}", "func (s *scheduler) IsRunning() bool {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\treturn s.isRunning\n}", "func (s *server) Running() bool {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\treturn (s.state != Stopped && s.state != Initialized)\n}", "func (jbobject *TaskContext) RunningLocally() bool {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"runningLocally\", javabind.Boolean)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(bool)\n}", "func IsRunning() bool {\n\treturn defaultDaemon.IsRunning()\n}", "func (h *EventHandler) Run() {\n\tticker := time.NewTicker(2 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif !h.needHandle || h.isDoing {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\th.needHandle = false\n\t\t\th.isDoing = true\n\t\t\t// if has error\n\t\t\tif h.doHandle() {\n\t\t\t\th.needHandle = true\n\t\t\t\ttime.Sleep(2 * time.Second)\n\t\t\t}\n\t\t\th.isDoing = false\n\t\tcase <-h.ctx.Done():\n\t\t\tblog.Infof(\"EventHandler for %s run loop exit\", h.lbID)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *Streamer) IsRunning() bool {\n\ts.mu.Lock()\n\tisRunning := s.state == stateRunning\n\ts.mu.Unlock()\n\n\treturn isRunning\n}", "func skipIfStillRunning(name string, t Task) Task {\n\tvar ch = make(chan struct{}, 1)\n\tch <- struct{}{}\n\n\treturn TaskFunc(func() {\n\t\tselect {\n\t\tcase v := <-ch:\n\t\t\tt.Run()\n\t\t\tch <- v\n\t\tdefault:\n\t\t\tlog.Warn(\"scheduler: skipping task\").String(\"name\", name).Log()\n\t\t}\n\t})\n}", "func (c *cephStatusChecker) checkCephStatus(stopCh chan struct{}) {\n\t// check the status immediately before starting the loop\n\tc.checkStatus()\n\n\tfor {\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\tlogger.Infof(\"Stopping monitoring of ceph status\")\n\t\t\treturn\n\n\t\tcase <-time.After(c.interval):\n\t\t\tc.checkStatus()\n\t\t}\n\t}\n}", "func (m *Manager) Run(ctx context.Context) error {\n\ts := <-m.status\n\tswitch s {\n\tcase StatusShutdown:\n\t\tm.status <- s\n\t\treturn ErrShutdown\n\tcase StatusUnknown:\n\t\t// ok\n\tdefault:\n\t\tm.status <- s\n\t\treturn ErrAlreadyStarted\n\t}\n\n\tstartCtx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tm.startupCancel = cancel\n\tstartupFunc := m.startupFunc\n\tm.status <- StatusStarting\n\n\tif startupFunc != nil {\n\t\tm.startupErr = startupFunc(startCtx)\n\t}\n\tcancel()\n\n\ts = <-m.status\n\n\tswitch s {\n\tcase StatusShutdown:\n\t\tm.status <- s\n\t\t// no error on shutdown while starting\n\t\treturn nil\n\tcase StatusStarting:\n\t\tif m.startupErr != nil {\n\t\t\tm.status <- s\n\t\t\tclose(m.startupDone)\n\t\t\treturn m.startupErr\n\t\t}\n\t\t// ok\n\tdefault:\n\t\tm.status <- s\n\t\tpanic(\"unexpected lifecycle state\")\n\t}\n\n\tctx, m.runCancel = context.WithCancel(ctx)\n\tclose(m.startupDone)\n\tm.status <- StatusReady\n\n\terr := m.runFunc(ctx)\n\tclose(m.runDone)\n\t<-m.shutdownDone\n\treturn err\n}", "func (transmuxer *Transmuxer) IsRunning() bool {\n\treturn transmuxer.running\n}", "func (s *status) stopping() error { return s.set(\"stopping\", \"STOPPING=1\") }", "func (o *Outbound) IsRunning() bool {\n\treturn o.once.IsRunning()\n}", "func (wf *Workflow) IsRunning() bool {\n\treturn wf.running\n}", "func IsWatchRunning() error {\n\t// This is connecting locally and it is very unlikely watch is overloaded,\n\t// set the timeout *super* short to make it easier on the users when they\n\t// forgot to start watch.\n\twithTimeout, _ := context.WithTimeout(context.TODO(), 100*time.Millisecond)\n\n\tconn, err := grpc.DialContext(\n\t\twithTimeout,\n\t\tfmt.Sprintf(\"127.0.0.1:%d\", viper.GetInt(\"port\")),\n\t\t[]grpc.DialOption{\n\t\t\tgrpc.WithBlock(),\n\t\t\tgrpc.WithInsecure(),\n\t\t}...)\n\n\tif err != nil {\n\t\t// The assumption is that the only real error here is because watch isn't\n\t\t// running\n\t\tlog.Debug(err)\n\t\treturn errWatchNotRunning\n\t}\n\n\tclient := pb.NewKsyncClient(conn)\n\talive, err := client.IsAlive(context.Background(), &empty.Empty{})\n\tif err != nil {\n\t\tlog.Debug(err)\n\t\treturn errWatchNotResponding\n\t}\n\n\tif !alive.Alive {\n\t\treturn errSyncthingNotRunning\n\t}\n\n\tif err := conn.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *WhileStmt) isDone(env *Env) (done bool) { //todo\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tswitch e.(type) { // error type case\n\t\t\tcase ContinueErr:\n\t\t\t\tdone = false\n\t\t\t\treturn\n\t\t\tcase BreakErr:\n\t\t\t\tdone = true\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tpanic(e)\n\t\t\t}\n\t\t}\n\t}()\n\tfor isTruthy(s.condition.eval(env)) {\n\t\ts.body.execute(env)\n\t}\n\treturn true\n}", "func (e *Engine) Running() bool {\n\treturn e.running\n}", "func (o *ChannelOutbound) IsRunning() bool {\n\treturn o.once.IsRunning()\n}", "func Stop() {\n\tstopRunning <- true\n\n}", "func (s *TimeSwitch) Run(stopCh <-chan struct{}) {\n\tfor {\n\t\tselect {\n\t\tcase <-s.Clock.After(s.secondsUntilNextMinute()):\n\t\t\ts.check()\n\t\tcase <-stopCh:\n\t\t\tlog.Info(\"shutting down time switch\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (sw *streamWatcher) stopping() bool {\n\tsw.Lock()\n\tdefer sw.Unlock()\n\treturn sw.stopped\n}", "func (w *WatchManager) run() {\n\tw.pollUpdatesInWasp() // initial pull from WASP\n\trunning := true\n\tfor running {\n\t\tselect {\n\t\tcase <-time.After(1 * time.Minute):\n\t\t\tw.pollUpdatesInWasp()\n\n\t\tcase <-w.stopChannel:\n\t\t\trunning = false\n\t\t}\n\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func (s *Session) IsRunning() bool {\n\tstatus, err := s.status()\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn status == \"Running\"\n}", "func (jbobject *TaskContext) IsRunningLocally() bool {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"isRunningLocally\", javabind.Boolean)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(bool)\n}", "func (t ResolvedPipelineRunTask) IsRunning() bool {\n\tif t.IsCustomTask() {\n\t\tif t.Run == nil {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tif t.TaskRun == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn !t.IsSuccessful() && !t.IsFailure() && !t.IsCancelled()\n}", "func (j *JournalTailer) IsRunning() bool {\n\tj.mu.RLock()\n\tdefer j.mu.RUnlock()\n\treturn j.running\n}", "func (s *Stopper) IsStopped() <-chan struct{} {\n\tif s == nil {\n\t\treturn nil\n\t}\n\treturn s.stopped\n}", "func (s *Stopper) IsStopped() <-chan struct{} {\n\tif s == nil {\n\t\treturn nil\n\t}\n\treturn s.stopped\n}", "func (e *BackgroundTask) Run(m libkb.MetaContext) (err error) {\n\tdefer m.Trace(e.Name(), &err)()\n\n\t// use a new background context with a saved cancel function\n\tvar cancel func()\n\tm, cancel = m.BackgroundWithCancel()\n\n\te.Lock()\n\tdefer e.Unlock()\n\n\te.shutdownFunc = cancel\n\tif e.shutdown {\n\t\t// Shutdown before started\n\t\tcancel()\n\t\te.meta(\"early-shutdown\")\n\t\treturn nil\n\t}\n\n\t// start the loop and return\n\tgo func() {\n\t\terr := e.loop(m)\n\t\tif err != nil {\n\t\t\te.log(m, \"loop error: %s\", err)\n\t\t}\n\t\tcancel()\n\t\te.meta(\"loop-exit\")\n\t}()\n\n\treturn nil\n}", "func (s *GrpcServer) IsRunning() bool {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\treturn s.running\n}", "func (p *Provider) CheckStopped() {\n\tp.t.Helper()\n\n\tif !p.stopped {\n\t\tp.t.Fatal(\"provider is not stopped\")\n\t}\n}", "func (c *ContextCollector) Run() {\n\tif !c.Running {\n\t\tc.StopChan = make(chan bool)\n\t\tc.StopCounterChan = make(chan bool)\n\t\tc.StoppedCounterChan = make(chan bool)\n\t\tgo c.runCounter()\n\t\tc.Running = true\n\t}\n}", "func (timer *Timer) IsRunning() bool {\n\tif timer == nil {\n\t\treturn false\n\t}\n\n\treturn timer.running\n}", "func (s *Stopwatch) active() bool {\n\treturn s.stop.IsZero()\n}", "func (s *OpenHackSimulator) IsRunning() bool {\n\ts.isRunningMutex.Lock()\n\tdefer s.isRunningMutex.Unlock()\n\treturn s.isRunning\n}", "func (s *Scheduler) Running() bool {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\treturn s.running\n}", "func (w *worker) stop() {\n\tatomic.StoreInt32(&w.running, 0)\n}", "func (s *Server) stopRunning() bool {\n\ts.rl.Lock()\n\tdefer s.rl.Unlock()\n\treturn s.doClose\n}", "func sleepUntilCtxDone(d time.Duration, ctx context.Context) (abort bool) {\n\tif ctx == nil {\n\t\ttime.Sleep(d)\n\t\treturn false\n\t}\n\n\tselect {\n\tcase <-time.After(d):\n\t\treturn false\n\tcase <-ctx.Done():\n\t\treturn true\n\t}\n}", "func running(args ...string) (found bool) {\n found = false\n cmd := exec.Command(\"docker\", \"ps\", \"--no-trunc\")\n\n stdout, err := cmd.StdoutPipe()\n if err != nil {\n logger.Log(fmt.Sprintln(err))\n }\n\n _, err = cmd.StderrPipe()\n if err != nil {\n logger.Log(fmt.Sprintln(err))\n }\n\n err = cmd.Start()\n if err != nil {\n logger.Log(fmt.Sprintln(err))\n }\n\n buf := new(bytes.Buffer)\n buf.ReadFrom(stdout)\n s := buf.String()\n\n cmd.Wait()\n\n for _, id := range pids() {\n if len(id) > 0 && !found {\n found = strings.Contains(s, id[:5])\n }\n }\n\n return\n}", "func (b *T) Run(name string, f func(t *T)) bool {\n\tsuccess := true\n\tif b.tracker.Active() {\n\t\tsuccess = success && b.t.Run(name, func(t *testing.T) {\n\t\t\tf(&T{t, t, b.tracker.SubTracker()})\n\t\t})\n\t}\n\treturn success\n}", "func isStepRunning(index int, stageSteps []v1.CoreActivityStep) bool {\n\tif len(stageSteps) > 0 {\n\t\tpreviousStep := stageSteps[index-1]\n\t\treturn previousStep.CompletedTimestamp != nil\n\t}\n\treturn true\n}", "func (m *TimerMutation) IsRunning() (r bool, exists bool) {\n\tv := m._IsRunning\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (o *observer) run(ctx context.Context) error {\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\twg := sync.WaitGroup{}\n\n\t// Run healthcheck loop\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\to.runHealthcheckLoopFn(ctx)\n\t}()\n\n\t// Continuously sync worker pods\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\to.syncWorkerPodsFn(ctx)\n\t}()\n\n\t// Continuously sync job pods\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\to.syncJobPodsFn(ctx)\n\t}()\n\n\t// Wait for an error or a completed context\n\tvar err error\n\tselect {\n\t// In essence, this comprises the Observer's \"healthcheck\" logic.\n\t// Whenever we receive an error on this channel, we cancel the context and\n\t// shut down. E.g., if one loop fails, everything fails.\n\t// This includes:\n\t// 1. an error pinging the Brigade API server endpoint\n\t// (Observer <-> API comms)\n\t// 2. an error pinging the K8s API server endpoint\n\t// (Observer <-> K8s comms)\n\t//\n\t// Note: Currently, errors updating or cleaning up worker or job statuses\n\t// are handled by o.errFn, which currently simply logs the error\n\tcase err = <-o.errCh:\n\t\tcancel() // Shut it all down\n\tcase <-ctx.Done():\n\t\terr = ctx.Err()\n\t}\n\n\t// Adapt wg to a channel that can be used in a select\n\tdoneCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(doneCh)\n\t\twg.Wait()\n\t}()\n\n\tselect {\n\tcase <-doneCh:\n\tcase <-time.After(3 * time.Second):\n\t\t// Probably doesn't matter that this is hardcoded. Relatively speaking, 3\n\t\t// seconds is a lot of time for things to wrap up.\n\t}\n\n\treturn err\n}" ]
[ "0.622798", "0.61385405", "0.6091839", "0.5883035", "0.58240783", "0.57762426", "0.56919473", "0.5631193", "0.56184846", "0.5609338", "0.5568484", "0.55551463", "0.5537527", "0.55302274", "0.5524895", "0.5518544", "0.549713", "0.544841", "0.54235667", "0.5421718", "0.53941876", "0.5375202", "0.5368934", "0.53635347", "0.53493935", "0.53449667", "0.53417933", "0.53417933", "0.5337958", "0.5304802", "0.52992415", "0.52891773", "0.5262416", "0.5259816", "0.52530366", "0.52466345", "0.52401537", "0.5235107", "0.52290845", "0.5221592", "0.52213985", "0.5207853", "0.5184785", "0.51645744", "0.5163141", "0.51541877", "0.51534766", "0.51524717", "0.51341546", "0.51315475", "0.5126247", "0.5121419", "0.5118825", "0.5111056", "0.5090381", "0.508878", "0.5088245", "0.50843483", "0.5083389", "0.5079202", "0.5056837", "0.505399", "0.50512284", "0.50496376", "0.50486255", "0.50470626", "0.5033762", "0.5019976", "0.5001165", "0.49986905", "0.4993433", "0.49842313", "0.49789205", "0.4971221", "0.49712038", "0.49629048", "0.49608135", "0.4945123", "0.49306354", "0.49115154", "0.49101612", "0.49047863", "0.48982757", "0.48982757", "0.4896024", "0.489523", "0.48806238", "0.48796958", "0.48782972", "0.4862897", "0.48609594", "0.485429", "0.48416066", "0.48380643", "0.483792", "0.4828252", "0.48274276", "0.48058105", "0.4805196", "0.47942477" ]
0.7218582
0
CloseAsync sends a signal to close this runner asynchronously. This is a nonblock version of `Close`. Only an `ErrUnexpectedState` with a `StateStopped` may be returned.
func (s *DeterminationWithContext) CloseAsync() error { return s.closeasync(s.trigger) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Retry) CloseAsync() {\n\tif atomic.CompareAndSwapInt32(&r.running, 1, 0) {\n\t\tclose(r.closeChan)\n\t}\n}", "func (o *Switch) CloseAsync() {\n\to.close()\n}", "func (t *TestProcessor) CloseAsync() {\n\tprintln(\"Closing async\")\n}", "func (r *ReadUntil) CloseAsync() {\n\tr.shutSig.CloseAtLeisure()\n}", "func (z *ZMQ4) CloseAsync() {\n\tif atomic.CompareAndSwapInt32(&z.running, 1, 0) {\n\t\tclose(z.closeChan)\n\t}\n}", "func (p *AsyncBundleUnacks) CloseAsync() {\n\tp.r.CloseAsync()\n}", "func (k *Kafka) CloseAsync() {\n\tif atomic.CompareAndSwapInt32(&k.running, 1, 0) {\n\t\tclose(k.closeChan)\n\t}\n}", "func (m mockProc) CloseAsync() {\n\t// Do nothing as our processor doesn't require resource cleanup.\n}", "func (b *Bloblang) CloseAsync() {\n\tif b.timer != nil {\n\t\tb.timer.Stop()\n\t}\n}", "func (m *MQTT) CloseAsync() {\n\tgo func() {\n\t\tm.connMut.Lock()\n\t\tif m.client != nil {\n\t\t\tm.client.Disconnect(0)\n\t\t\tm.client = nil\n\t\t}\n\t\tm.connMut.Unlock()\n\t}()\n}", "func (a *Async) Close() {\n\ta.quit <- true\n\t// wait for watcher quit\n\t<-a.quit\n}", "func (s *SQL) CloseAsync() {\n\ts.closeOnce.Do(func() {\n\t\tclose(s.closeChan)\n\t})\n}", "func (p CustomProcessor) CloseAsync() {\n\t// Do nothing as our processor doesn't require resource cleanup.\n}", "func (p SplitToBatch) CloseAsync() {\n\t// Do nothing as our processor doesn't require resource cleanup.\n}", "func (r *Resource) CloseAsync() {\n}", "func (r *Resource) CloseAsync() {\n}", "func (aio *AsyncIO) Close() error {\n\tif aio.ioctx == 0 {\n\t\treturn ErrNotInit\n\t}\n\n\t// send to signal to stop wait\n\taio.close <- struct{}{}\n\t<-aio.close\n\n\tif aio.close != nil {\n\t\tclose(aio.close)\n\t}\n\tif aio.trigger != nil {\n\t\tclose(aio.trigger)\n\t}\n\n\t// destroy async IO context\n\taio.ioctx.Destroy()\n\taio.ioctx = 0\n\n\t// close file descriptor\n\tif err := aio.fd.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (d *Detector) RunAsync() chan (error) {\n\tgo func() {\n\t\tdefer close(d.c)\n\t\tif err := d.Run(); err != nil {\n\t\t\t// Return the error to the calling thread\n\t\t\td.c <- err\n\t\t}\n\t}()\n\treturn d.c\n}", "func (_m *AsyncBR) Close(ctx context.Context) {\n\t_m.Called(ctx)\n}", "func (c *Context) CancelAsync() (err int) {\n\treturn int(C.rtlsdr_cancel_async((*C.rtlsdr_dev_t)(c.dev)))\n}", "func (p *ProcessField) CloseAsync() {\n\tfor _, c := range p.children {\n\t\tc.CloseAsync()\n\t}\n}", "func (m *geo) CloseAsync() {\n\tm.geoip2DB.Close()\n}", "func (p *asyncPipeline) Close() {\n\tclose(p.chDie)\n\t<-p.chExit\n}", "func (_m *MockCompletableFuture[T]) HandleAsync(_a0 func(T, error)) {\n\t_m.Called(_a0)\n}", "func (rr *RtcpReceiver) Close() {\n\trr.events <- rtcpReceiverEventTerminate{}\n\t<-rr.done\n}", "func (t *FuchsiaTester) Close() error {\n\tif err := t.delegate.Close(); err != nil {\n\t\treturn fmt.Errorf(\"failed to close delegate ssh runner: %v\", err)\n\t}\n\treturn nil\n}", "func (cm *ConnectionManager) LeaveAsync() *utils.AsyncResult {\n\tresult := utils.NewAsyncResult()\n\tgo func() {\n\t\tdefer rpanic.PanicRecover(\"LeaveAsync\")\n\t\t_, err := cm.Leave(true)\n\t\tresult.Result <- err\n\t}()\n\treturn result\n}", "func (g *GRPC) AwaitTermination() error {\n\tsign := make(chan os.Signal, 1)\n\tsignal.Notify(sign, syscall.SIGINT, syscall.SIGTERM)\n\t<-sign\n\n\tg.GracefulStop()\n\treturn g.listener.Close()\n}", "func (_e *MockCompletableFuture_Expecter[T]) HandleAsync(_a0 interface{}) *MockCompletableFuture_HandleAsync_Call[T] {\n\treturn &MockCompletableFuture_HandleAsync_Call[T]{Call: _e.mock.On(\"HandleAsync\", _a0)}\n}", "func Close(ctx context.Context, tconn *chrome.TestConn, appID string) error {\n\treturn tconn.Call(ctx, nil, `tast.promisify(chrome.autotestPrivate.closeApp)`, appID)\n}", "func (m *Monitor) RunAsync() chan error {\n\tklog.V(5).Info(\"starting leader elect bit\")\n\tgo func() {\n\t\tdefer close(m.c)\n\t\tif err := m.runLeaderElect(); err != nil {\n\t\t\t// Return the error to the calling thread\n\t\t\tm.c <- err\n\t\t}\n\t}()\n\tklog.V(5).Info(\"starting leader elect bit started\")\n\treturn m.c\n}", "func (server *Server) RunAsync(callback func(errors.Error)) errors.Error {\n\tserver.asyncServer = &http.Server{Addr: server.config.ListenAddress, Handler: server.engine}\n\tvar returnErr errors.Error\n\tgo func() {\n\t\tserver.notifyBeginServing()\n\t\terr := server.asyncServer.ListenAndServe()\n\t\tif err != nil {\n\t\t\tif err == http.ErrServerClosed {\n\t\t\t\treturnErr = ErrGraceShutdown.Make()\n\t\t\t} else {\n\t\t\t\treturnErr = ErrServeFailed.Make().Cause(err)\n\t\t\t}\n\t\t}\n\t\tserver.notifyStopServing()\n\t\tif callback != nil {\n\t\t\tcallback(returnErr)\n\t\t}\n\t}()\n\ttime.Sleep(100 * time.Millisecond)\n\treturn returnErr\n}", "func (monitor *TaskMonitor) Shutdown() error {\n\t// Close the events channel\n\tclose(monitor.EventsChannel)\n\n\t// Will close() the deliveries channel\n\tif err := monitor.channel.Cancel(monitor.consumerTag, true); err != nil {\n\t\treturn fmt.Errorf(\"failed to cancel monitor: %s\", err)\n\t}\n\n\tif err := monitor.connection.Close(); err != nil {\n\t\treturn fmt.Errorf(\"error closing AMQP connection: %s\", err)\n\t}\n\n\tdefer log.Printf(\"shutdown AMQP OK\")\n\n\t// Wait for handle() to exit\n\treturn <-monitor.done\n}", "func syncClose(done chan chan struct{}) {\n\tch := make(chan struct{}, 0)\n\tdone <- ch\n\t<-ch\n}", "func (p *AbstractRunProvider) Close() error {\n\tp.SetRunning(false)\n\treturn nil\n}", "func (t *TestProcessor) WaitForClose(timeout time.Duration) error {\n\tprintln(\"Waiting for close\")\n\treturn nil\n}", "func TestRTCPeerConnection_Close(t *testing.T) {\n\t// Limit runtime in case of deadlocks\n\tlim := test.TimeOut(time.Second * 20)\n\tdefer lim.Stop()\n\n\treport := test.CheckRoutines(t)\n\tdefer report()\n\n\tpcOffer, pcAnswer, err := newPair()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tawaitSetup := make(chan struct{})\n\tpcAnswer.OnDataChannel(func(d *RTCDataChannel) {\n\t\tclose(awaitSetup)\n\t})\n\n\t_, err = pcOffer.CreateDataChannel(\"data\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = signalPair(pcOffer, pcAnswer)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t<-awaitSetup\n\n\terr = pcOffer.Close()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = pcAnswer.Close()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (this *ThreadCtl) MarkStopAsync() {\n\tgo func() {\n\t\tthis.signalChan <- \"stop\"\n\t}()\n}", "func (s *Slave) RunInShellAsync(query string, sudo bool) chan string {\n\tch := make(chan string)\n\n\tgo func() {\n\t\trc, err := NewRemoteConnection(s)\n\t\tif err != nil {\n\t\t\tch <- \"error: \" + err.Error()\n\t\t\treturn\n\t\t}\n\n\t\tch <- rc.RunInShell(query, sudo)\n\t}()\n\n\treturn ch\n}", "func (f *Function) RemoveInstanceAsync() {\n\tlogger := log.WithFields(log.Fields{\"fID\": f.fID})\n\n\tlogger.Debug(\"Removing instance (async)\")\n\n\tgo func() {\n\t\terr := orch.StopSingleVM(context.Background(), f.vmID)\n\t\tif err != nil {\n\t\t\tlog.Warn(err)\n\t\t}\n\t}()\n}", "func (c *Channel) Close() (result *utils.AsyncResult) {\n\tif c.State != channeltype.StateOpened {\n\t\tlog.Warn(fmt.Sprintf(\"try to close channel %s,but it's state is %s\", utils.HPex(c.ChannelIdentifier.ChannelIdentifier), c.State))\n\t}\n\tif c.State == channeltype.StateClosed ||\n\t\tc.State == channeltype.StateSettled {\n\t\tresult = utils.NewAsyncResult()\n\t\tresult.Result <- fmt.Errorf(\"channel %s already closed or settled\", utils.HPex(c.ChannelIdentifier.ChannelIdentifier))\n\t\treturn\n\t}\n\t/*\n\t\t在关闭的过程中崩溃了,或者关闭 tx 失败了,这些都可能发生.所以不能因为 state 不对,就不允许 close\n\t\t标记的目的是为了阻止继续接受或者发起交易.\n\t*/\n\tc.State = channeltype.StateClosing\n\tbp := c.PartnerState.BalanceProofState\n\tresult = c.ExternState.Close(bp)\n\treturn\n}", "func (p *AsyncBundleUnacks) WaitForClose(tout time.Duration) error {\n\treturn p.r.WaitForClose(tout)\n}", "func (mock *CloudMock) Shutdown() {\n\tif err := mock.conn.Close(); err != nil {\n\t\tlog.Fatalf(\"failed to close connection: %s\", err)\n\t}\n\tmock.grpcServer.GracefulStop()\n}", "func TestRelayRejectsDuringClose(t *testing.T) {\n\topts := testutils.NewOpts().\n\t\tSetRelayOnly().\n\t\tSetCheckFramePooling().\n\t\tAddLogFilter(\"Failed to relay frame.\", 1, \"error\", \"incoming connection is not active: connectionStartClose\")\n\ttestutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {\n\t\tgotCall := make(chan struct{})\n\t\tblock := make(chan struct{})\n\n\t\ttestutils.RegisterEcho(ts.Server(), func() {\n\t\t\tclose(gotCall)\n\t\t\t<-block\n\t\t})\n\n\t\tclient := ts.NewClient(nil)\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\ttestutils.AssertEcho(t, client, ts.HostPort(), ts.ServiceName())\n\t\t}()\n\n\t\t<-gotCall\n\t\t// Close the relay so that it stops accepting more calls.\n\t\tts.Relay().Close()\n\t\terr := testutils.CallEcho(client, ts.HostPort(), ts.ServiceName(), nil)\n\t\trequire.Error(t, err, \"Expect call to fail after relay is shutdown\")\n\t\tassert.Contains(t, err.Error(), \"incoming connection is not active\")\n\t\tclose(block)\n\t\twg.Wait()\n\n\t\t// We have a successful call that ran in the goroutine\n\t\t// and a failed call that we just checked the error on.\n\t\tcalls := relaytest.NewMockStats()\n\t\tcalls.Add(client.PeerInfo().ServiceName, ts.ServiceName(), \"echo\").\n\t\t\tSucceeded().End()\n\t\tcalls.Add(client.PeerInfo().ServiceName, ts.ServiceName(), \"echo\").\n\t\t\t// No peer is set since we rejected the call before selecting one.\n\t\t\tFailed(\"relay-client-conn-inactive\").End()\n\t\tts.AssertRelayStats(calls)\n\t})\n}", "func (cli *OpsGenieAlertV2Client) Close(req alertsv2.CloseRequest) (*AsyncRequestResponse, error) {\n\treturn cli.sendAsyncPostRequest(&req)\n}", "func (a *AzureBlobStorage) CloseAsync() {\n}", "func (m *mockTCPEndpoint) Close() {\n\tm.impl.Close()\n\tm.notifyDone <- struct{}{}\n}", "func (m mockProc) WaitForClose(timeout time.Duration) error {\n\t// Do nothing as our processor doesn't require resource cleanup.\n\treturn nil\n}", "func (m *mockStream) Close() {\n\tclose(m.recvChan)\n\tclose(m.sendChan)\n}", "func (a *Application) AwaitSignal() {\n\tc := make(chan os.Signal, 1)\n\tsignal.Reset(syscall.SIGTERM, syscall.SIGINT)\n\tsignal.Notify(c, syscall.SIGTERM, syscall.SIGINT)\n\n\ts := <-c\n\ta.logger.Info(\"receive a signal\", zap.String(\"signal\", s.String()))\n\tif a.httpServer != nil {\n\t\tif err := a.httpServer.Stop(); err != nil {\n\t\t\ta.logger.Warn(\"stop http server error\", zap.Error(err))\n\t\t}\n\t}\n\tif a.grpcServer != nil {\n\t\tif err := a.grpcServer.Stop(); err != nil {\n\t\t\ta.logger.Warn(\"stop grpc server error\", zap.Error(err))\n\t\t}\n\t}\n\n\tos.Exit(0)\n}", "func (al *AsyncLogger) Close() (resultErr error) {\n\tal.closed.Store(true)\n\n\tif err := al.writer.Close(); err != nil {\n\t\treturn fmt.Errorf(\"Error closing writer: %v\", err)\n\t}\n\treturn nil\n}", "func (s *session) Close(e error) error {\n\ts.close(e, false)\n\t<-s.runClosed\n\treturn nil\n}", "func (c *TimeoutChan) Close() {\n\tclose(c.in)\n\tc.pushCtrl.Wait()\n\tclose(c.closePush)\n\tc.popCtrl.Wait()\n\tclose(c.out)\n\tclose(c.resumePush)\n\tclose(c.resumePop)\n\tclose(c.reschedule)\n}", "func (ac *azureClient) DeleteAsync(ctx context.Context, resourceGroupName, vmssName, instanceID string) (*infrav1.Future, error) {\n\tctx, _, done := tele.StartSpanWithLogger(ctx, \"scalesetvms.azureClient.DeleteAsync\")\n\tdefer done()\n\n\tfuture, err := ac.scalesetvms.Delete(ctx, resourceGroupName, vmssName, instanceID, ptr.To(false))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed deleting vmss named %q\", vmssName)\n\t}\n\n\treturn converters.SDKToFuture(&future, infrav1.DeleteFuture, serviceName, instanceID, resourceGroupName)\n}", "func (s *Session) Close() error {\n\ts.Watch(map[string]bool{\"enable\": false})\n\tclose(s.done)\n\treturn s.socket.Close()\n}", "func (t *T) Close() (err error) {\n\tif t.cb != nil {\n\t\terr = t.cb(t.n, t.block)\n\t}\n\t*t = T{}\n\treturn err\n}", "func async(fn func() error) <-chan error {\n\terrChan := make(chan error, 0)\n\tgo func() {\n\t\tselect {\n\t\tcase errChan <- fn():\n\t\tdefault:\n\t\t}\n\n\t\tclose(errChan)\n\t}()\n\n\treturn errChan\n}", "func (m *Mock) Close() {\n\tlog.Printf(\"Closing mock %p\\n\", m)\n\tif m.cmd != nil && m.cmd.Process != nil {\n\t\tif err := m.cmd.Process.Kill(); err != nil {\n\t\t\tlog.Printf(\"Error killing process: %v\", err)\n\t\t\treturn\n\t\t}\n\t\t_, err := m.cmd.Process.Wait()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error waiting for process to end: %v\", err)\n\t\t\treturn\n\t\t}\n\t}\n\tif m.conn != nil {\n\t\tif err := m.conn.Close(); err != nil {\n\t\t\tlog.Printf(\"Error closing connection: %v\", err)\n\t\t}\n\t}\n\tm.EntryPort = 0\n}", "func (b *Backend) Close() {\n\t// wait all handler coroutine finish\n\tgateway.waitGroup.Wait()\n\t// close all channel\n\tclose(gateway.notifyMacChan)\n}", "func (c *Mock) Close() { c.Closed = true }", "func (ngw *NatGateways) deleteAsync(wg *sync.WaitGroup, errChan chan error, ngwID *string) {\n\tdefer wg.Done()\n\n\tinput := &ec2.DeleteNatGatewayInput{NatGatewayId: ngwID}\n\t_, err := ngw.Client.DeleteNatGateway(input)\n\n\t// Record status of this resource\n\te := report.Entry{\n\t\tIdentifier: aws.StringValue(ngwID),\n\t\tResourceType: \"NAT Gateway\",\n\t\tError: err,\n\t}\n\treport.Record(e)\n\n\terrChan <- err\n}", "func (r *Receiver) Close() error { return nil }", "func (c *TimeoutChan) Shutdown() {\n\tclose(c.in)\n\tc.pushCtrl.Shutdown()\n\tclose(c.closePush)\n\tc.popCtrl.Shutdown()\n\tclose(c.out)\n\tclose(c.resumePush)\n\tclose(c.resumePop)\n\tclose(c.reschedule)\n}", "func (sm *stateMachine) Close() error {\n\tif sm.running.CAS(true, false) {\n\t\tdefer func() {\n\t\t\tsm.cancel()\n\t\t}()\n\n\t\tsm.discovery.Close()\n\n\t\tsm.logger.Info(\"state machine stop successfully\",\n\t\t\tlogger.String(\"type\", sm.stateMachineType.String()))\n\t}\n\treturn nil\n}", "func (p CustomProcessor) WaitForClose(timeout time.Duration) error {\n\t// Do nothing as our processor doesn't require resource cleanup.\n\treturn nil\n}", "func ServeAsync(port int, closing chan bool, acceptHandler OnAccept) error {\n\tl, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tserver := new(Server)\n\tserver.Closing = closing\n\tserver.OnAccept = acceptHandler\n\tgo server.Serve(l)\n\treturn nil\n}", "func TestClose(t *testing.T) {\n\tmockTr := new(mockTTransport)\n\ttr := NewTFramedTransport(mockTr)\n\tmockTr.On(\"Close\").Return(nil)\n\n\tassert.Nil(t, tr.Close())\n\tmockTr.AssertExpectations(t)\n}", "func (s *Server) Close() {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tgo func(ctx context.Context) {\n\t\t<-ctx.Done()\n\t\tif ctx.Err() == context.Canceled {\n\t\t\treturn\n\t\t} else if ctx.Err() == context.DeadlineExceeded {\n\t\t\tpanic(\"Timeout while stopping traefik, killing instance ✝\")\n\t\t}\n\t}(ctx)\n\tclose(s.stopChan)\n\n\tcancel()\n}", "func (e *Exclusive) CallAfterAsync(key interface{}, value func() (interface{}, error), wait time.Duration) <-chan *ExclusiveOutcome {\n\treturn e.CallWithOptions(ExclusiveKey(key), ExclusiveValue(value), ExclusiveWait(wait))\n}", "func (c *Channel) Close() error {\n\treturn c.exit(false)\n}", "func (l *remoteLoggingClient) Close() error {\n\tl.stream.CloseSend()\n\t<-l.doneCh\n\tif l.runErr != nil {\n\t\treturn errors.Wrap(l.runErr, \"remote logging background routine failed\")\n\t}\n\treturn nil\n}", "func (e *endpoint) Close() {\n\t// Tell dispatch goroutine to stop, then write to the eventfd so that\n\t// it wakes up in case it's sleeping.\n\tatomic.StoreUint32(&e.stopRequested, 1)\n\tsyscall.Write(e.rx.eventFD, []byte{1, 0, 0, 0, 0, 0, 0, 0})\n\n\t// Cleanup the queues inline if the worker hasn't started yet; we also\n\t// know it won't start from now on because stopRequested is set to 1.\n\te.mu.Lock()\n\tworkerPresent := e.workerStarted\n\te.mu.Unlock()\n\n\tif !workerPresent {\n\t\te.tx.cleanup()\n\t\te.rx.cleanup()\n\t}\n}", "func (s *SignalFx) Close() error {\n\ts.ctx.Done()\n\ts.client = nil\n\tclose(s.done)\n\ts.wg.Wait()\n\treturn nil\n}", "func (c *Chrome) Close() error {\n\tc.eg.Go(func() error { return errStopped })\n\tif e := c.eg.Wait(); e != errStopped {\n\t\treturn e\n\t}\n\treturn nil\n}", "func (c *Mock) Close() {\n\tc.FakeClose()\n}", "func (s *Slave) RunScriptAsync(scriptpath string, deviceEnv map[string]string) (chan string, error) {\n\trc, err := NewRemoteConnection(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvs := GetGlobalEnvs()\n\tfor k, v := range deviceEnv {\n\t\tenvs[k] = v\n\t}\n\n\treturn rc.RunScript(scriptpath, envs)\n}", "func (m *MQTT) WaitForClose(timeout time.Duration) error {\n\treturn nil\n}", "func CloseAsyncPipeline() {\n\tfor _, pool := range asyncPipelinePools {\n\t\tfor _, pipeline := range pool.pipelines {\n\t\t\tpipeline.Close()\n\t\t}\n\t}\n\tasyncPipelinePools = nil\n}", "func (c *RawConnectionMock) Close() error {\n\targs := c.Called()\n\treturn args.Error(0)\n}", "func (r *Raft) Close() {\n\tr.logger.Debugf(\"closing raft\")\n\n\tclose(r.closeChannel)\n\t<-r.runFinishedChannel\n}", "func QuietlyClose(c io.Closer) {\n\t_ = c.Close()\n}", "func (_m *AsyncBR) Cancel() {\n\t_m.Called()\n}", "func Close() {\n\tapp.producer.AsyncClose()\n}", "func (s *Signal) Close() {\n\tclose(s.channel)\n}", "func (q *QueuedOutput) Close() error {\n\tq.ctxCancel()\n\treturn nil\n}", "func (s socket) Close() error {\n\ts.done <- true\n\treturn nil\n}", "func (r *RegisterMonitor) Close() error {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tfor {\n\t\tswitch r.runState {\n\t\tcase registerStateIdle:\n\t\t\t// Idle so just set it to stopped and return. We notify\n\t\t\t// the condition variable in case others are waiting.\n\t\t\tr.runState = registerStateStopped\n\t\t\tr.cond.Broadcast()\n\t\t\treturn nil\n\n\t\tcase registerStateRunning:\n\t\t\t// Set the state to stopping and broadcast to all waiters,\n\t\t\t// since Run is sitting on cond.Wait.\n\t\t\tr.runState = registerStateStopping\n\t\t\tr.cond.Broadcast()\n\t\t\tr.cond.Wait() // Wait on the stopping event\n\n\t\tcase registerStateStopping:\n\t\t\t// Still stopping, wait...\n\t\t\tr.cond.Wait()\n\n\t\tcase registerStateStopped:\n\t\t\t// Stopped, target state reached\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (_e *MockTestTransportInstance_Expecter) Close() *MockTestTransportInstance_Close_Call {\n\treturn &MockTestTransportInstance_Close_Call{Call: _e.mock.On(\"Close\")}\n}", "func (it *RandomBeaconDkgSeedTimedOutIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (nopBroadcaster) SendAsync(Message) error { return nil }", "func (c *Client) PostAsync(request graphql.PostRequest, callback func(*graphql.Response, error)) (context.CancelFunc, error) {\n\theader, err := c.setupHeaders(request)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\tcb := func(g *graphql.Response, err error) {\n\t\tc.sleepIfNeeded(request)\n\t\tcallback(g, err)\n\t}\n\treturn c.graphQLAPI.PostAsync(header, request, cb)\n}", "func (e *Exclusive) CallAsync(key interface{}, value func() (interface{}, error)) <-chan *ExclusiveOutcome {\n\treturn e.CallAfterAsync(key, value, 0)\n}", "func (c *Channel) Close() {\n\tclose(c.done)\n\tc.sharedDone()\n}", "func (_m *Socket) Close() {\n\t_m.Called()\n}", "func (ch *Channel) Close() {}", "func (cli *FakeDatabaseClient) RunRMANAsync(ctx context.Context, in *dbdpb.RunRMANAsyncRequest, opts ...grpc.CallOption) (*lropb.Operation, error) {\n\tpanic(\"implement me\")\n}", "func (impl *Impl) SetAsync() error {\n\timpl.forever = true\n\treturn impl.buffer.SetAsync()\n}", "func (c *InterfaceStateUpdater) Close() error {\n\tc.cancel()\n\tc.wg.Wait()\n\n\tif c.vppNotifSubs != nil {\n\t\tif err := c.vppNotifSubs.Unsubscribe(); err != nil {\n\t\t\treturn errors.Errorf(\"failed to unsubscribe interface state notification on close: %v\", err)\n\t\t}\n\t}\n\tif c.vppCountersSubs != nil {\n\t\tif err := c.vppCountersSubs.Unsubscribe(); err != nil {\n\t\t\treturn errors.Errorf(\"failed to unsubscribe interface state counters on close: %v\", err)\n\t\t}\n\t}\n\tif c.vppCombinedCountersSubs != nil {\n\t\tif err := c.vppCombinedCountersSubs.Unsubscribe(); err != nil {\n\t\t\treturn errors.Errorf(\"failed to unsubscribe interface state combined counters on close: %v\", err)\n\t\t}\n\t}\n\n\tif err := safeclose.Close(c.vppCh, c.notifChan); err != nil {\n\t\treturn errors.Errorf(\"failed to safe close interface state: %v\", err)\n\t}\n\n\treturn nil\n}", "func (l *AsyncPoolLogger) Shutdown() chan struct{} {\n\tshutdownCompletedChan := make(chan struct{}, 1)\n\n\tgo func() {\n\t\tl.active = false\n\t\tduration := 100 * time.Millisecond\n\t\tfor {\n\t\t\tif len(l.logsQueue) <= 0 {\n\t\t\t\tclose(l.logsQueue)\n\n\t\t\t\tfor i := 0; i < l.workerNum; i++ {\n\t\t\t\t\t<-l.stoppedChan\n\t\t\t\t}\n\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ttime.Sleep(duration)\n\t\t}\n\t\tshutdownCompletedChan <- notifier\n\t}()\n\n\treturn shutdownCompletedChan\n}", "func TestCloseAfterEOF(t *testing.T) {\n\tmaybeSkipIntegrationTest(t)\n\n\ts, err := NewSession()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create session: %v\", err)\n\t}\n\tdefer s.Close()\n\n\tif err := s.Subscribe(\"log\"); err != nil {\n\t\tt.Fatalf(\"Failed to subscribe to event: %v\", err)\n\t}\n\n\terr = exec.Command(\"systemctl\", \"stop\", \"strongswan\").Run()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to stop strongswan: %v\", err)\n\t}\n\tdefer func() {\n\t\terr := exec.Command(\"systemctl\", \"start\", \"strongswan\").Run()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to restart strongswan: %v\", err)\n\t\t}\n\t}()\n}" ]
[ "0.68786585", "0.6547746", "0.6543886", "0.63452035", "0.6333746", "0.6276764", "0.61466765", "0.6040728", "0.5954821", "0.5851878", "0.5822685", "0.57749647", "0.5627606", "0.5361624", "0.5353209", "0.5353209", "0.5328969", "0.49306536", "0.48934168", "0.48741895", "0.4690705", "0.4655894", "0.46341115", "0.45809442", "0.4538347", "0.45344806", "0.45204645", "0.45026934", "0.44923636", "0.44583508", "0.44567487", "0.44544697", "0.44196984", "0.44152933", "0.43523258", "0.43505102", "0.43236503", "0.43070456", "0.42803967", "0.42620376", "0.4235389", "0.42269745", "0.42262635", "0.42079362", "0.42071557", "0.41826418", "0.41793215", "0.41730678", "0.41520748", "0.41412207", "0.41217425", "0.41104662", "0.4109002", "0.41004798", "0.4096951", "0.4086603", "0.4066808", "0.40641722", "0.40616715", "0.40462554", "0.40340385", "0.39882454", "0.3975213", "0.39643776", "0.39555988", "0.39555898", "0.39532337", "0.39490733", "0.39479274", "0.39460617", "0.39448678", "0.3941509", "0.39402586", "0.39386493", "0.3919378", "0.39156574", "0.3914031", "0.39058137", "0.39055678", "0.38974264", "0.3895675", "0.38924572", "0.389152", "0.38903406", "0.38845855", "0.38823098", "0.38798323", "0.38791293", "0.38749772", "0.38648367", "0.3857351", "0.3855163", "0.3852794", "0.38516334", "0.3846262", "0.38350683", "0.3832434", "0.3826892", "0.38204232", "0.3812743" ]
0.60688484
7
Close this DeterminationWithContext and wait until stop running. Using it in `WhileRunning` will cause deadlock. Please use `CloseAsync()` instead.
func (s *DeterminationWithContext) Close() error { return s.close(s.trigger) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *DeterminationWithContext) CloseAsync() error {\n\treturn s.closeasync(s.trigger)\n}", "func (s *DeterminationWithContext) Run() (err error) {\n\treturn s.run(s.prepare, s.booting, s.running, s.trigger, s.closing)\n}", "func (s *DeterminationWithContext) WhileRunning(do func(context.Context) error) error {\n\treturn s.whilerunning(func() error {\n\t\tselect {\n\t\tcase <-s.sctx.Done():\n\t\t\treturn ErrRunnerIsClosing\n\t\tdefault:\n\t\t\treturn do(s.sctx)\n\t\t}\n\t})\n}", "func (node *DataNode) Stop() error {\n\tnode.stopOnce.Do(func() {\n\t\tnode.cancel()\n\t\t// https://github.com/milvus-io/milvus/issues/12282\n\t\tnode.UpdateStateCode(commonpb.StateCode_Abnormal)\n\t\tnode.flowgraphManager.close()\n\n\t\tnode.eventManagerMap.Range(func(_ string, m *channelEventManager) bool {\n\t\t\tm.Close()\n\t\t\treturn true\n\t\t})\n\n\t\tif node.allocator != nil {\n\t\t\tlog.Info(\"close id allocator\", zap.String(\"role\", typeutil.DataNodeRole))\n\t\t\tnode.allocator.Close()\n\t\t}\n\n\t\tif node.closer != nil {\n\t\t\tnode.closer.Close()\n\t\t}\n\n\t\tif node.session != nil {\n\t\t\tnode.session.Stop()\n\t\t}\n\n\t\tnode.wg.Wait()\n\t})\n\treturn nil\n}", "func (o *Switch) CloseAsync() {\n\to.close()\n}", "func (h *handler) shutdown(ctx context.Context) {\n\tdefer func() {\n\t\tif h.onStopped != nil {\n\t\t\tgo h.onStopped()\n\t\t}\n\n\t\th.totalClosingTime = h.clock.Time().Sub(h.startClosingTime)\n\t\tclose(h.closed)\n\t}()\n\n\t// shutdown may be called during Start, so we populate the start closing\n\t// time here in case Stop was never called.\n\tif h.startClosingTime.IsZero() {\n\t\th.startClosingTime = h.clock.Time()\n\t}\n\n\tstate := h.ctx.State.Get()\n\tengine, ok := h.engineManager.Get(state.Type).Get(state.State)\n\tif !ok {\n\t\th.ctx.Log.Error(\"failed fetching current engine during shutdown\",\n\t\t\tzap.Stringer(\"type\", state.Type),\n\t\t\tzap.Stringer(\"state\", state.State),\n\t\t)\n\t\treturn\n\t}\n\n\tif err := engine.Shutdown(ctx); err != nil {\n\t\th.ctx.Log.Error(\"failed while shutting down the chain\",\n\t\t\tzap.Error(err),\n\t\t)\n\t}\n}", "func (sm *stateMachine) Close() error {\n\tif sm.running.CAS(true, false) {\n\t\tdefer func() {\n\t\t\tsm.cancel()\n\t\t}()\n\n\t\tsm.discovery.Close()\n\n\t\tsm.logger.Info(\"state machine stop successfully\",\n\t\t\tlogger.String(\"type\", sm.stateMachineType.String()))\n\t}\n\treturn nil\n}", "func runWithContext(fun func(ctx context.Context) error) (context.CancelFunc, chan error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdefer close(done)\n\t\tdone <- fun(ctx)\n\t}()\n\n\treturn cancel, done\n}", "func (g *Gatekeeper) Close() error {\n\treturn g.hd.Stop()\n}", "func (c *Context) Stop() {\n\tlog.Printf(\"[WARN] terraform: Stop called, initiating interrupt sequence\")\n\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\t// If we're running, then stop\n\tif c.runContextCancel != nil {\n\t\tlog.Printf(\"[WARN] terraform: run context exists, stopping\")\n\n\t\t// Tell the hook we want to stop\n\t\tc.sh.Stop()\n\n\t\t// Stop the context\n\t\tc.runContextCancel()\n\t\tc.runContextCancel = nil\n\t}\n\n\t// Grab the condition var before we exit\n\tif cond := c.runCond; cond != nil {\n\t\tcond.Wait()\n\t}\n\n\tlog.Printf(\"[WARN] terraform: stop complete\")\n}", "func (h *handler) Stop(ctx context.Context) {\n\th.closeOnce.Do(func() {\n\t\th.startClosingTime = h.clock.Time()\n\n\t\t// Must hold the locks here to ensure there's no race condition in where\n\t\t// we check the value of [h.closing] after the call to [Signal].\n\t\th.syncMessageQueue.Shutdown()\n\t\th.asyncMessageQueue.Shutdown()\n\t\tclose(h.closingChan)\n\n\t\t// TODO: switch this to use a [context.Context] with a cancel function.\n\t\t//\n\t\t// Don't process any more bootstrap messages. If a dispatcher is\n\t\t// processing a bootstrap message, stop. We do this because if we\n\t\t// didn't, and the engine was in the middle of executing state\n\t\t// transitions during bootstrapping, we wouldn't be able to grab\n\t\t// [h.ctx.Lock] until the engine finished executing state transitions,\n\t\t// which may take a long time. As a result, the router would time out on\n\t\t// shutting down this chain.\n\t\tstate := h.ctx.State.Get()\n\t\tbootstrapper, ok := h.engineManager.Get(state.Type).Get(snow.Bootstrapping)\n\t\tif !ok {\n\t\t\th.ctx.Log.Error(\"bootstrapping engine doesn't exists\",\n\t\t\t\tzap.Stringer(\"type\", state.Type),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tbootstrapper.Halt(ctx)\n\t})\n}", "func (m mockProc) CloseAsync() {\n\t// Do nothing as our processor doesn't require resource cleanup.\n}", "func (p *AbstractRunProvider) Close() error {\n\tp.SetRunning(false)\n\treturn nil\n}", "func (h *Handler) WithContext(ctx context.Context) {\n\tgo func() {\n\t\t<-ctx.Done()\n\t\th.terminating = true\n\t}()\n}", "func (f *fakeAppReconcileWatcher) Stop() {\n\tclose(f.ch)\n}", "func (f *Filler) Terminate(err error) {\n\tf.closeo.Do(func() {\n\t\tf.drop(err)\n\t\tclose(f.closeq)\n\t})\n}", "func (h *EventHandler) Stop() {\n\th.ctx.Done()\n}", "func (m *manager) Stop(hive.HookContext) error {\n\tif m.workerpool != nil {\n\t\tif err := m.workerpool.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\treturn nil\n}", "func (t *Tree) GracefulShutdown(ctx context.Context) error {\n\tif ctx == nil {\n\t\treturn ErrMissingContext\n\t}\n\tif t.gracefulCancel == nil {\n\t\treturn ErrTreeNotRunning\n\t}\n\tt.init()\n\tif err := t.err(); err != nil {\n\t\treturn ErrTreeNotRunning\n\t}\n\tselect {\n\tcase <-t.stopped:\n\t\treturn ErrTreeNotRunning\n\tdefault:\n\t}\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(done)\n\t\tt.semaphore.Lock()\n\t\tdefer t.semaphore.Unlock()\n\t\tfor i := len(t.childrenOrder) - 1; i >= 0; i-- {\n\t\t\tif ctx.Err() != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tprocName := t.childrenOrder[i]\n\t\t\tt.children[procName].state.setFailed()\n\t\t\tt.children[procName].state.stop()\n\t\t}\n\t}()\n\tselect {\n\tcase <-ctx.Done():\n\t\tt.gracefulCancel()\n\t\treturn ctx.Err()\n\tcase <-done:\n\t\tt.gracefulCancel()\n\t\treturn nil\n\t}\n}", "func (s *Stopper) Stop(ctx context.Context) {\n\ts.mu.Lock()\n\tstopCalled := s.mu.stopping\n\ts.mu.stopping = true\n\ts.mu.Unlock()\n\n\tif stopCalled {\n\t\t// Wait for the concurrent Stop() to complete.\n\t\t<-s.stopped\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\ts.Recover(ctx)\n\t\tunregister(s)\n\t\tclose(s.stopped)\n\t}()\n\n\t// Don't bother doing stuff cleanly if we're panicking, that would likely\n\t// block. Instead, best effort only. This cleans up the stack traces,\n\t// avoids stalls and helps some tests in `./cli` finish cleanly (where\n\t// panics happen on purpose).\n\tif r := recover(); r != nil {\n\t\tgo s.Quiesce(ctx)\n\t\ts.mu.Lock()\n\t\tfor _, c := range s.mu.closers {\n\t\t\tgo c.Close()\n\t\t}\n\t\ts.mu.Unlock()\n\t\tpanic(r)\n\t}\n\n\ts.Quiesce(ctx)\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfor _, c := range s.mu.closers {\n\t\tc.Close()\n\t}\n}", "func (s *Server) Close() {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tgo func(ctx context.Context) {\n\t\t<-ctx.Done()\n\t\tif ctx.Err() == context.Canceled {\n\t\t\treturn\n\t\t} else if ctx.Err() == context.DeadlineExceeded {\n\t\t\tpanic(\"Timeout while stopping traefik, killing instance ✝\")\n\t\t}\n\t}(ctx)\n\tclose(s.stopChan)\n\n\tcancel()\n}", "func Shutdown(ctx context.Context, code int) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tcancelFn()\n\tif _, ok := ctx.Deadline(); ok {\n\t\t<-ctx.Done()\n\t}\n}", "func (aio *AsyncIO) Close() error {\n\tif aio.ioctx == 0 {\n\t\treturn ErrNotInit\n\t}\n\n\t// send to signal to stop wait\n\taio.close <- struct{}{}\n\t<-aio.close\n\n\tif aio.close != nil {\n\t\tclose(aio.close)\n\t}\n\tif aio.trigger != nil {\n\t\tclose(aio.trigger)\n\t}\n\n\t// destroy async IO context\n\taio.ioctx.Destroy()\n\taio.ioctx = 0\n\n\t// close file descriptor\n\tif err := aio.fd.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func closeDependency(ctx context.Context, n int, wg *sync.WaitGroup) {\n\ttime.Sleep((time.Duration(rand.Intn(10) * 25)) * time.Millisecond)\n\tfmt.Printf(\"[%d] closed\\n\", n)\n\twg.Done() // decrements the WaitGroup counter by one, same as wg.Add(-1) // HL\n}", "func makeContext(c context.Context) (context.Context, context.CancelFunc, <-chan struct{}) {\n\texit := make(chan os.Signal, 1)\n\tnotif := make(chan struct{})\n\n\tsignal.Notify(exit, os.Interrupt, syscall.SIGTERM)\n\n\tctx, cancel := context.WithCancel(c)\n\n\tgo func() {\n\t\tselect {\n\t\tcase <-c.Done():\n\t\tcase <-exit:\n\t\t}\n\n\t\tlog.Println(\"attempting to shut down gracefully...\")\n\t\tclose(notif)\n\n\t\t// A second signal will cause the manager to exit forcefully\n\t\t<-exit\n\t\tlog.Println(\"exiting forcefully...\")\n\t\tos.Exit(1)\n\t}()\n\n\treturn ctx, cancel, notif\n}", "func (i *Ingester) Close() error {\n\t// Stop the internal Go routines.\n\tclose(i.doneCh)\n\n\t// Close the liveness.\n\ti.eventProcessMetrics.liveness.Close()\n\n\t// Give straggling operations time to complete before we close the ingestion store.\n\ttime.Sleep(1 * time.Second)\n\n\t// Note: This does not seem to shut down gRPC related goroutines.\n\tif i.ingestionStore != nil {\n\t\treturn i.ingestionStore.Close()\n\t}\n\treturn nil\n}", "func (r *ReadUntil) CloseAsync() {\n\tr.shutSig.CloseAtLeisure()\n}", "func (p CustomProcessor) CloseAsync() {\n\t// Do nothing as our processor doesn't require resource cleanup.\n}", "func WaitForWithContext(\n\tctx context.Context,\n\tminTimeout, maxTimeout, defaultTimeout time.Duration,\n\tperiod time.Duration,\n\tf func() (bool, error),\n) error {\n\tvar timeout time.Duration\n\n\t// Check if the caller provided a deadline\n\td, ok := ctx.Deadline()\n\tif !ok {\n\t\ttimeout = defaultTimeout\n\t} else {\n\t\ttimeout = d.Sub(time.Now())\n\n\t\t// Determine if it is too short or too long\n\t\tif timeout < minTimeout || timeout > maxTimeout {\n\t\t\treturn status.Errorf(codes.InvalidArgument,\n\t\t\t\t\"Deadline must be between %v and %v; was: %v\", minTimeout, maxTimeout, timeout)\n\t\t}\n\t}\n\n\treturn WaitFor(timeout, period, f)\n}", "func (w *Worker) Close() {\n\tw.Lock()\n\tdefer w.Unlock()\n\n\tif w.closed.Get() == closedTrue {\n\t\tw.l.Warn(\"already closed\")\n\t\treturn\n\t}\n\n\t// cancel status output ticker and wait for return\n\tw.cancel()\n\tw.wg.Wait()\n\n\t// close all sub tasks\n\tw.subTaskHolder.closeAllSubTasks()\n\n\t// close relay\n\tw.relayHolder.Close()\n\n\t// close purger\n\tw.relayPurger.Close()\n\n\t// close task status checker\n\tif w.cfg.Checker.CheckEnable {\n\t\tw.taskStatusChecker.Close()\n\t}\n\n\t// close meta\n\tw.meta.Close()\n\n\t// close kv db\n\tif w.db != nil {\n\t\tw.db.Close()\n\t}\n\n\t// close tracer\n\tif w.tracer.Enable() {\n\t\tw.tracer.Stop()\n\t}\n\n\tw.closed.Set(closedTrue)\n}", "func (it *RandomBeaconDkgSeedTimedOutIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func lifetimeContext(logger *logrus.Logger) context.Context {\n\tctx, cancel := context.WithCancel(context.Background())\n\tstopSigs := []os.Signal{os.Interrupt, os.Kill, syscall.SIGTERM}\n\tstopCh := make(chan os.Signal, len(stopSigs))\n\tsignal.Notify(stopCh, stopSigs...)\n\tgo func() {\n\t\t<-stopCh\n\t\tlogger.Info(\"Caught interrupt, shutting down\")\n\t\tcancel()\n\t\t<-stopCh\n\t\tlogger.Fatal(\"Caught second interrupt, force closing\")\n\t}()\n\treturn ctx\n}", "func (p *fakeProvider) Close() {\n\tp.Distributor.Stop()\n}", "func (m mockProc) WaitForClose(timeout time.Duration) error {\n\t// Do nothing as our processor doesn't require resource cleanup.\n\treturn nil\n}", "func (d *ConsulDiscovery) Close() {\r\n\tclose(d.stopCh)\r\n}", "func (p CustomProcessor) WaitForClose(timeout time.Duration) error {\n\t// Do nothing as our processor doesn't require resource cleanup.\n\treturn nil\n}", "func (r *EtcdResolver) Stop() {\n\tr.Close()\n}", "func pollWithContext(ctx context.Context, timeout time.Duration, pollFn func() (success bool, err error)) error {\n\tstart := time.Now()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn context.Canceled\n\t\tcase <-time.After(500 * time.Millisecond):\n\t\t\tsuccess, err := pollFn()\n\t\t\tif err != nil || success {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif time.Since(start) > timeout {\n\t\t\t\treturn ErrTimeout\n\t\t\t}\n\t\t}\n\t}\n}", "func (r *runtime) Stop() {\n\tr.logger.Info(\"stopping broker server...\")\n\tdefer r.cancel()\n\n\tr.Shutdown()\n\n\tif r.httpServer != nil {\n\t\tr.logger.Info(\"stopping http server...\")\n\t\tif err := r.httpServer.Close(r.ctx); err != nil {\n\t\t\tr.logger.Error(\"shutdown http server error\", logger.Error(err))\n\t\t} else {\n\t\t\tr.logger.Info(\"stopped http server successfully\")\n\t\t}\n\t}\n\n\t// close registry, deregister broker node from active list\n\tif r.registry != nil {\n\t\tr.logger.Info(\"closing discovery-registry...\")\n\t\tif err := r.registry.Deregister(r.node); err != nil {\n\t\t\tr.logger.Error(\"unregister broker node error\", logger.Error(err))\n\t\t}\n\t\tif err := r.registry.Close(); err != nil {\n\t\t\tr.logger.Error(\"unregister broker node error\", logger.Error(err))\n\t\t} else {\n\t\t\tr.logger.Info(\"closed discovery-registry successfully\")\n\t\t}\n\t}\n\n\tif r.master != nil {\n\t\tr.logger.Info(\"stopping master...\")\n\t\tr.master.Stop()\n\t}\n\n\tif r.stateMachineFactory != nil {\n\t\tr.stateMachineFactory.Stop()\n\t}\n\n\tif r.repo != nil {\n\t\tr.logger.Info(\"closing state repo...\")\n\t\tif err := r.repo.Close(); err != nil {\n\t\t\tr.logger.Error(\"close state repo error, when broker stop\", logger.Error(err))\n\t\t} else {\n\t\t\tr.logger.Info(\"closed state repo successfully\")\n\t\t}\n\t}\n\tif r.stateMgr != nil {\n\t\tr.stateMgr.Close()\n\t}\n\tif r.srv.channelManager != nil {\n\t\tr.logger.Info(\"closing write channel manager...\")\n\t\tr.srv.channelManager.Close()\n\t\tr.logger.Info(\"closed write channel successfully\")\n\t}\n\n\tif r.factory.connectionMgr != nil {\n\t\tif err := r.factory.connectionMgr.Close(); err != nil {\n\t\t\tr.logger.Error(\"close connection manager error, when broker stop\", logger.Error(err))\n\t\t} else {\n\t\t\tr.logger.Info(\"closed connection manager successfully\")\n\t\t}\n\t}\n\tr.logger.Info(\"close connections successfully\")\n\n\t// finally, shutdown rpc server\n\tif r.grpcServer != nil {\n\t\tr.logger.Info(\"stopping grpc server...\")\n\t\tr.grpcServer.Stop()\n\t\tr.logger.Info(\"stopped grpc server successfully\")\n\t}\n\n\tr.state = server.Terminated\n\tr.logger.Info(\"stopped broker server successfully\")\n}", "func WaitWithContext(ctx context.Context, cmd *exec.Cmd) error {\n\tproc, err := process.NewProcess(int32(cmd.Process.Pid))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tisRunning, err := proc.IsRunning()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdone := ctx.Done()\n\tfor isRunning {\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t\tisRunning, err = proc.IsRunning()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t} else if isRunning {\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn cmd.Wait()\n}", "func (zc *Coordinator) Stop() error {\n\tzc.Log.Info(\"stopping\")\n\n\t// This will close the event channel, closing the mainLoop\n\tzc.App.Zookeeper.Close()\n\tzc.running.Wait()\n\n\treturn nil\n}", "func (t *TestProcessor) CloseAsync() {\n\tprintln(\"Closing async\")\n}", "func (_m *AsyncBR) Close(ctx context.Context) {\n\t_m.Called(ctx)\n}", "func NBContextClosed(ctx context.Context) bool {\n\tclosed := false\n\tselect {\n\tcase <-ctx.Done():\n\t\tclosed = true\n\tdefault:\n\t\t//Empty default to disable blocking\n\t}\n\treturn closed\n}", "func (m *Manager) Shutdown(ctx context.Context) error {\n\tinitShutdown := func() {\n\t\tctx, m.shutdownCancel = context.WithCancel(ctx)\n\t\tm.status <- StatusShutdown\n\t}\n\n\tvar isRunning bool\n\ts := <-m.status\n\tswitch s {\n\tcase StatusShutdown:\n\t\tm.status <- s\n\t\tselect {\n\t\tcase <-m.shutdownDone:\n\t\tcase <-ctx.Done():\n\t\t\t// if we timeout before the existing call, cancel it's context\n\t\t\tm.shutdownCancel()\n\t\t\t<-m.shutdownDone\n\t\t}\n\t\treturn m.shutdownErr\n\tcase StatusStarting:\n\t\tm.startupCancel()\n\t\tclose(m.pauseStart)\n\t\tinitShutdown()\n\t\t<-m.startupDone\n\tcase StatusUnknown:\n\t\tinitShutdown()\n\t\tclose(m.pauseStart)\n\t\tclose(m.shutdownDone)\n\t\treturn nil\n\tcase StatusPausing:\n\t\tisRunning = true\n\t\tm.pauseCancel()\n\t\tinitShutdown()\n\t\t<-m.pauseDone\n\tcase StatusReady:\n\t\tclose(m.pauseStart)\n\t\tfallthrough\n\tcase StatusPaused:\n\t\tisRunning = true\n\t\tinitShutdown()\n\t}\n\n\tdefer close(m.shutdownDone)\n\tdefer m.shutdownCancel()\n\n\terr := m.shutdownFunc(ctx)\n\n\tif isRunning {\n\t\tm.runCancel()\n\t\t<-m.runDone\n\t}\n\n\treturn err\n}", "func (e *endpoint) Close() {\n\t// Tell dispatch goroutine to stop, then write to the eventfd so that\n\t// it wakes up in case it's sleeping.\n\tatomic.StoreUint32(&e.stopRequested, 1)\n\tsyscall.Write(e.rx.eventFD, []byte{1, 0, 0, 0, 0, 0, 0, 0})\n\n\t// Cleanup the queues inline if the worker hasn't started yet; we also\n\t// know it won't start from now on because stopRequested is set to 1.\n\te.mu.Lock()\n\tworkerPresent := e.workerStarted\n\te.mu.Unlock()\n\n\tif !workerPresent {\n\t\te.tx.cleanup()\n\t\te.rx.cleanup()\n\t}\n}", "func (svc *Service) Close(ctx context.Context) error {\n\ttimeout := svc.Config.GracefulShutdownTimeout\n\tlog.Event(ctx, \"commencing graceful shutdown\", log.Data{\"graceful_shutdown_timeout\": timeout}, log.INFO)\n\tctx, cancel := context.WithTimeout(ctx, timeout)\n\n\t// track shutown gracefully closes up\n\tvar hasShutdownError bool\n\n\tgo func() {\n\t\tdefer cancel()\n\n\t\t// stop healthcheck, as it depends on everything else\n\t\tif svc.ServiceList.HealthCheck {\n\t\t\tsvc.HealthCheck.Stop()\n\t\t}\n\n\t\t// stop any incoming requests before closing any outbound connections\n\t\tif err := svc.Server.Shutdown(ctx); err != nil {\n\t\t\tlog.Event(ctx, \"failed to shutdown http server\", log.Error(err), log.ERROR)\n\t\t\thasShutdownError = true\n\t\t}\n\n\t\t// TODO: Close other dependencies, in the expected order\n\t}()\n\n\t// wait for shutdown success (via cancel) or failure (timeout)\n\t<-ctx.Done()\n\n\t// timeout expired\n\tif ctx.Err() == context.DeadlineExceeded {\n\t\tlog.Event(ctx, \"shutdown timed out\", log.ERROR, log.Error(ctx.Err()))\n\t\treturn ctx.Err()\n\t}\n\n\t// other error\n\tif hasShutdownError {\n\t\terr := errors.New(\"failed to shutdown gracefully\")\n\t\tlog.Event(ctx, \"failed to shutdown gracefully \", log.ERROR, log.Error(err))\n\t\treturn err\n\t}\n\n\tlog.Event(ctx, \"graceful shutdown was successful\", log.INFO)\n\treturn nil\n}", "func (t *Task) Stopping() <-chan struct{} {\n\treturn t.ctx.Done()\n}", "func (d *etcdResolver) Close() {\n\td.cancel()\n\td.wg.Wait()\n\td.t.Stop()\n}", "func (c *Context) Stop() {\n\tc.stopChannel <- struct{}{}\n}", "func (s *Server) Close() {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\n\tgo func(ctx context.Context) {\n\t\t<-ctx.Done()\n\t\tif errors.Is(ctx.Err(), context.Canceled) {\n\t\t\treturn\n\t\t} else if errors.Is(ctx.Err(), context.DeadlineExceeded) {\n\t\t\tpanic(\"Timeout while stopping traefik, killing instance ✝\")\n\t\t}\n\t}(ctx)\n\n\tstopMetricsClients()\n\n\ts.routinesPool.Stop()\n\n\tsignal.Stop(s.signals)\n\tclose(s.signals)\n\n\tclose(s.stopChan)\n\n\ts.chainBuilder.Close()\n\n\tcancel()\n}", "func (ft *fakeTraverser) Shutdown(ctx context.Context) {}", "func (p SplitToBatch) CloseAsync() {\n\t// Do nothing as our processor doesn't require resource cleanup.\n}", "func (t *Tracer) Close() {\n\tif t.workerStopCh == nil {\n\t\treturn\n\t}\n\t// Tell the worker to stop and wait for it to finish up.\n\tclose(t.workerStopCh)\n\tt.workerWait.Wait()\n\tt.workerStopCh = nil\n}", "func (svc *Service) Close(ctx context.Context) error {\n\ttimeout := svc.cfg.GracefulShutdownTimeout\n\tlog.Event(ctx, \"commencing graceful shutdown\", log.Data{\"graceful_shutdown_timeout\": timeout}, log.INFO)\n\tctx, cancel := context.WithTimeout(ctx, timeout)\n\thasShutdownError := false\n\n\t// Gracefully shutdown the application closing any open resources.\n\tgo func() {\n\t\tdefer cancel()\n\n\t\t// stop healthcheck, as it depends on everything else\n\t\tif svc.healthCheck != nil {\n\t\t\tsvc.healthCheck.Stop()\n\t\t}\n\n\t\t// stop any incoming requests\n\t\tif svc.server != nil {\n\t\t\tif err := svc.server.Shutdown(ctx); err != nil {\n\t\t\t\tlog.Event(ctx, \"failed to shutdown http server\", log.ERROR, log.Error(err))\n\t\t\t\thasShutdownError = true\n\t\t\t}\n\t\t}\n\n\t\t// Close MongoDB (if it exists)\n\t\tif svc.mongoDataStore != nil {\n\t\t\tlog.Event(ctx, \"closing mongo data store\", log.INFO)\n\t\t\tif err := svc.mongoDataStore.Close(ctx); err != nil {\n\t\t\t\tlog.Event(ctx, \"unable to close mongo data store\", log.ERROR, log.Error(err))\n\t\t\t\thasShutdownError = true\n\t\t\t}\n\t\t}\n\n\t\t// Close Data Baker Kafka Producer (it if exists)\n\t\tif svc.dataBakerProducer != nil {\n\t\t\tlog.Event(ctx, \"closing data baker producer\", log.INFO)\n\t\t\tif err := svc.dataBakerProducer.Close(ctx); err != nil {\n\t\t\t\tlog.Event(ctx, \"unable to close data baker producer\", log.ERROR, log.Error(err))\n\t\t\t\thasShutdownError = true\n\t\t\t}\n\t\t}\n\n\t\t// Close Direct Kafka Producer (if it exists)\n\t\tif svc.inputFileAvailableProducer != nil {\n\t\t\tlog.Event(ctx, \"closing direct producer\", log.INFO)\n\t\t\tif err := svc.inputFileAvailableProducer.Close(ctx); err != nil {\n\t\t\t\tlog.Event(ctx, \"unable to close direct producer\", log.ERROR, log.Error(err))\n\t\t\t\thasShutdownError = true\n\t\t\t}\n\t\t}\n\t}()\n\n\t// wait for shutdown success (via cancel) or failure (timeout)\n\t<-ctx.Done()\n\n\t// timeout expired\n\tif ctx.Err() == context.DeadlineExceeded {\n\t\tlog.Event(ctx, \"shutdown timed out\", log.ERROR, log.Error(ctx.Err()))\n\t\treturn ctx.Err()\n\t}\n\n\t// other error\n\tif hasShutdownError {\n\t\terr := errors.New(\"failed to shutdown gracefully\")\n\t\tlog.Event(ctx, \"failed to shutdown gracefully \", log.ERROR, log.Error(err))\n\t\treturn err\n\t}\n\n\tlog.Event(ctx, \"graceful shutdown was successful\", log.INFO)\n\treturn nil\n}", "func (r *Resource) CloseAsync() {\n}", "func (r *Resource) CloseAsync() {\n}", "func (z *ZMQ4) CloseAsync() {\n\tif atomic.CompareAndSwapInt32(&z.running, 1, 0) {\n\t\tclose(z.closeChan)\n\t}\n}", "func (sc *StateCheckpoint) Close() {\n\tsc.ctx = nil\n}", "func (k *Kafka) CloseAsync() {\n\tif atomic.CompareAndSwapInt32(&k.running, 1, 0) {\n\t\tclose(k.closeChan)\n\t}\n}", "func (hc *LegacyHealthCheckImpl) Close() error {\n\thc.mu.Lock()\n\tfor _, th := range hc.addrToHealth {\n\t\tth.cancelFunc()\n\t}\n\thc.addrToHealth = nil\n\t// Release the lock early or a pending checkHealthCheckTimeout\n\t// cannot get a read lock on it.\n\thc.mu.Unlock()\n\n\t// Wait for the checkHealthCheckTimeout Go routine and each Go\n\t// routine per tablet.\n\thc.connsWG.Wait()\n\n\treturn nil\n}", "func (it *LoggerDepositSubTreeReadyIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func Close() {\n\tif App.WatchEnabled && !App.CmdMode {\n\t\tchannelExchangeCommands(LevelCritical, command{Action: \"DONE\"})\n\t}\n}", "func (b *Bloblang) CloseAsync() {\n\tif b.timer != nil {\n\t\tb.timer.Stop()\n\t}\n}", "func (e *endpoint) Close() {\n\t// Tell dispatch goroutine to stop, then write to the eventfd so that\n\t// it wakes up in case it's sleeping.\n\te.stopRequested.Store(1)\n\te.rx.eventFD.Notify()\n\n\t// Cleanup the queues inline if the worker hasn't started yet; we also\n\t// know it won't start from now on because stopRequested is set to 1.\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\tworkerPresent := e.workerStarted\n\n\tif !workerPresent {\n\t\te.tx.cleanup()\n\t\te.rx.cleanup()\n\t}\n}", "func (r *etcdBuilder) Close() {\n\tr.etcdWatcher.Close()\n\tr.waitGroup.Wait()\n}", "func (ctx *ResourceContext) SafeClose() {\n}", "func (v *PeriodicView) Close() error {\n\tv.mu.Lock()\n\tdefer v.mu.Unlock()\n\n\tif !v.closed && v.running {\n\t\tv.taskRunner.Stop()\n\t}\n\tv.closed = true\n\treturn nil\n}", "func (t *ViewBufferManager) Close() {\n\tif t.stopCurrentTask == nil {\n\t\treturn\n\t}\n\n\tc := make(chan struct{})\n\n\tgo utils.Safe(func() {\n\t\tt.stopCurrentTask()\n\t\tc <- struct{}{}\n\t})\n\n\tselect {\n\tcase <-c:\n\t\treturn\n\tcase <-time.After(3 * time.Second):\n\t\tfmt.Println(\"cannot kill child process\")\n\t}\n}", "func (t *TimeLimit) Close() {\n\t// Close the wrapped environment\n\tt.wrapped.Close()\n\n\t// Close this environment\n\tt.Environment.Close()\n}", "func (c *Chrome) doClose() error {\n\t<-c.ctx.Done()\n\n\tif c.cmd.Process == nil {\n\t\treturn nil\n\t}\n\n\t// sigint\n\tif e := c.cmd.Process.Signal(syscall.SIGINT); e != nil {\n\t\treturn e\n\t}\n\n\t// wait until the command exits\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- c.cmd.Wait()\n\t}()\n\n\tselect {\n\tcase err := <-done:\n\t\treturn err\n\tcase <-time.After(5 * time.Second):\n\t\tif c.cmd.Process == nil {\n\t\t\treturn nil\n\t\t}\n\t\t// kill after the context elapsed\n\t\tc.cmd.Process.Signal(syscall.SIGKILL)\n\t\tselect {\n\t\tcase err := <-done:\n\t\t\treturn err\n\t\tcase <-time.After(10 * time.Second):\n\t\t\treturn errors.New(\"couldn't kill process after 10s\")\n\t\t}\n\t}\n}", "func (p SplitToBatch) WaitForClose(timeout time.Duration) error {\n\t// Do nothing as our processor doesn't require resource cleanup.\n\treturn nil\n}", "func (s *service) Close() (err error) {\n\ts.ctxCancel()\n\treturn nil\n}", "func (this *Manager) Close(tuner gopi.DVBTuner) error {\n\ttuner_ := this.getTunerForId(tuner.Id())\n\tif tuner_ == nil {\n\t\treturn gopi.ErrNotFound.WithPrefix(\"Close\")\n\t}\n\n\t// Dispose of tuner (stop watching, closing filters, etc)\n\tif err := tuner_.Dispose(this.FilePoll); err != nil {\n\t\treturn err\n\t}\n\n\t// Delete context\n\tthis.RWMutex.Lock()\n\tdefer this.RWMutex.Unlock()\n\tdelete(this.context, tuner_)\n\n\t// Return success\n\treturn nil\n}", "func (it *SmartchefEmergencyWithdrawIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (h *Harness) Stop() {\n\tfin := make(chan struct{})\n\tgo func() {\n\t\tdefer close(fin)\n\t\tif err := h.Client.Close(); err != nil {\n\t\t\th.t.Fatal(err)\n\t\t}\n\n\t\tif err := h.cmd.Process.Kill(); err != nil {\n\t\t\th.t.Fatal(err)\n\t\t}\n\n\t\tif err := os.Remove(h.configPath); err != nil {\n\t\t\th.t.Fatal(err)\n\t\t}\n\t}()\n\tselect {\n\tcase <-fin:\n\tcase <-time.After(h.StopTimeout):\n\t}\n}", "func (a *Async) Close() {\n\ta.quit <- true\n\t// wait for watcher quit\n\t<-a.quit\n}", "func (p *keventloop) Close() {\n\tclose(p.done)\n}", "func waitForShutdown(ctx context.Context, service *PortService, logger *logrus.Logger) {\n\t<-ctx.Done()\n\tservice.grpcServer.GracefulStop()\n\tlogger.Infoln(\"grpc service stopped\")\n\tservice.dbSession.Close()\n\tlogger.Infoln(\"db session closed\")\n}", "func (p *asyncPipeline) Close() {\n\tclose(p.chDie)\n\t<-p.chExit\n}", "func (c *Context) Close() (err int) {\n\treturn int(C.rtlsdr_close((*C.rtlsdr_dev_t)(c.dev)))\n}", "func LoopClosed(ctx context.Context, p *Protocol, ld routing.LoopData) error {\n\tif err := p.WritePacket(PacketLoopClosed, ld); err != nil {\n\t\treturn err\n\t}\n\treturn readAndDecodePacketWithTimeout(ctx, p, nil)\n}", "func (h *Handler) shutdown() {\n\th.ctx.Lock.Lock()\n\tdefer h.ctx.Lock.Unlock()\n\n\tstartTime := h.clock.Time()\n\tif err := h.engine.Shutdown(); err != nil {\n\t\th.ctx.Log.Error(\"Error while shutting down the chain: %s\", err)\n\t}\n\tif h.onCloseF != nil {\n\t\tgo h.onCloseF()\n\t}\n\tendTime := h.clock.Time()\n\th.metrics.shutdown.Observe(float64(endTime.Sub(startTime)))\n\tclose(h.closed)\n}", "func (l *Ledger) Stop(ctx context.Context) error {\n\treturn nil\n}", "func (mgr *manager) step_Terminated() mgr_step {\n\t// Let others see us as done. yayy!\n\tmgr.doneFuse.Fire()\n\t// We've finally stopped selecting. We're done. We're out.\n\t// No other goroutines alive should have reach to this channel, so we can close it.\n\tclose(mgr.ctrlChan_childDone)\n\t// It's over. No more step functions to call.\n\treturn nil\n}", "func (r *ReconciliationLoop) Shutdown() error {\n\tr.done <- true\n\n\tdefer func() {\n\t\terr := r.listener.Close()\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Cold not close the loop client: %v\", err)\n\t\t}\n\t}()\n\treturn nil\n}", "func (it *RandomBeaconDkgTimedOutIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (d *DynamicSelect) shutDown() {\n\tif r := recover(); r != nil {\n\t\tlog.Printf(\"Recovered from panic in main DynamicSelect: %v\\n\", r)\n\t\tlog.Println(\"Attempting normal shutdown.\")\n\t}\n\n\t// just making sure.\n\td.killHeard = true\n\td.alive = false\n\td.running = false\n\tclose(d.done)\n\n\t// Tell the outside world we're done.\n\td.onKillAction()\n\n\t// Handle outstanding requests / a flood of closed messages.\n\tgo d.drainChannels()\n\n\t// Wait for internal listeners to halt.\n\td.listenerWG.Wait()\n\n\t// Make it painfully clear to the GC.\n\tclose(d.aggregator)\n\tclose(d.priorityAggregator)\n\tclose(d.onClose)\n}", "func (s *Context) Stop() error {\n\tclose(s.stop)\n\ts.wg.Wait()\n\n\tzmq.AuthStop()\n\n\tif err := s.pulls.Close(); err != nil {\n\t\tlog.Printf(\"Failed to close PULL socket: %s\\n\", err)\n\t}\n\n\tif err := s.pushs.Close(); err != nil {\n\t\tlog.Printf(\"Failed to close PUSH socket: %s\\n\", err)\n\t}\n\treturn nil\n}", "func (p *literalProcessor) stop() { syncClose(p.done) }", "func (h *HealthCheck) Close() {\n\th.metricTicker.Stop()\n}", "func (h *Harness) Close() error {\n\th.t.Helper()\n\tif recErr := recover(); recErr != nil {\n\t\tdefer panic(recErr)\n\t}\n\th.dumpDB() // early as possible\n\n\th.tw.WaitAndAssert(h.t)\n\th.slack.WaitAndAssert()\n\th.email.WaitAndAssert()\n\n\th.mx.Lock()\n\th.closing = true\n\th.mx.Unlock()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\tdefer cancel()\n\terr := h.backend.Shutdown(ctx)\n\tif err != nil {\n\t\th.t.Error(\"failed to shutdown backend cleanly:\", err)\n\t}\n\th.backendLogs.Close()\n\n\th.slackS.Close()\n\th.twS.Close()\n\n\th.tw.Close()\n\n\th.pgTime.Close()\n\n\tconn, err := pgx.Connect(ctx, DBURL(\"\"))\n\tif err != nil {\n\t\th.t.Error(\"failed to connect to DB:\", err)\n\t}\n\tdefer conn.Close(ctx)\n\t_, err = conn.Exec(ctx, \"drop database \"+sqlutil.QuoteID(h.dbName))\n\tif err != nil {\n\t\th.t.Errorf(\"failed to drop database '%s': %v\", h.dbName, err)\n\t}\n\n\treturn nil\n}", "func (it *FlopperKickIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (w *watcher) checkLoop(ctx context.Context) {\n\tfor atomic.LoadInt32(&w.state) == isRunning {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tw.Close()\n\t\t\tw.dispose()\n\t\t\treturn\n\t\tdefault:\n\t\t\tw.check(ctx)\n\t\t\ttime.Sleep(w.interval)\n\t\t}\n\t}\n}", "func (b *BtcdFeeEstimator) Stop() error {\n\tb.btcdConn.Shutdown()\n\n\treturn nil\n}", "func (s *Service) Close() error {\n\tif wait, err := func() (bool, error) {\n\t\ts.mu.Lock()\n\t\tdefer s.mu.Unlock()\n\n\t\tif s.closed() {\n\t\t\treturn false, nil // Already closed.\n\t\t}\n\t\tclose(s.done)\n\n\t\t// Close the listeners.\n\t\tif err := s.ln.Close(); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif err := s.httpln.Close(); err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif s.batcher != nil {\n\t\t\ts.batcher.Stop()\n\t\t}\n\t\treturn true, nil\n\t}(); err != nil {\n\t\treturn err\n\t} else if !wait {\n\t\treturn nil\n\t}\n\ts.wg.Wait()\n\n\ts.mu.Lock()\n\ts.done = nil\n\ts.mu.Unlock()\n\n\treturn nil\n}", "func (c *context) Done() <-chan struct{} {\n\treturn c.parent.Done()\n}", "func main() {\n\tlog.Println(\"begin main...\")\n\tparentCtx, cancelParent := context.WithCancel(context.Background())\n\n\tchildTimeoutCtx, _ := context.WithTimeout(parentCtx, time.Second*10)\n\n\ttime.AfterFunc(time.Second*2, func() {\n\t\tlog.Println(\"Cancel parent context after 2s\")\n\t\tcancelParent()\n\t})\n\n\tselect {\n\tcase <-childTimeoutCtx.Done():\n\t\tlog.Println(\"Child context done! Normally this will called after Child ctx timeout (10s)\")\n\t}\n\n\t// cancelParent()\n\t// for i:=0;i<15 ;i++ {\n\t// \tfmt.Println(\"...\")\n\t// \ttime.Sleep(time.Second)\n\t// }\n}", "func (q *QueuedOutput) Close() error {\n\tq.ctxCancel()\n\treturn nil\n}", "func (s *BaseLittleDuckListener) ExitCte(ctx *CteContext) {}" ]
[ "0.5852757", "0.52932596", "0.5185775", "0.4858248", "0.48176065", "0.47810063", "0.4778499", "0.47632846", "0.47588742", "0.47494122", "0.47453672", "0.47408634", "0.471754", "0.47167784", "0.4708157", "0.4693535", "0.46701324", "0.46656507", "0.46643656", "0.46549073", "0.4653664", "0.46485317", "0.46451575", "0.4642967", "0.46232352", "0.46222505", "0.4622091", "0.45990673", "0.45977628", "0.4591234", "0.459117", "0.45859212", "0.45858967", "0.45716417", "0.4567512", "0.45663148", "0.4565068", "0.45591545", "0.45523974", "0.45433474", "0.4539468", "0.45323384", "0.45290232", "0.45274282", "0.45273224", "0.44991413", "0.4494546", "0.4487312", "0.4483141", "0.4477183", "0.4475565", "0.44721147", "0.44613278", "0.4460791", "0.4438945", "0.44377872", "0.44377872", "0.44239733", "0.4421196", "0.44097507", "0.4405968", "0.44029438", "0.43930495", "0.4385969", "0.43820095", "0.43782842", "0.43745977", "0.43709233", "0.4370696", "0.43684852", "0.43580213", "0.43538678", "0.43428716", "0.4342557", "0.4337856", "0.4334506", "0.43310082", "0.4329313", "0.43268695", "0.4321156", "0.43200654", "0.43168676", "0.43149242", "0.43129787", "0.43119508", "0.4305824", "0.42982465", "0.42957267", "0.4291203", "0.42903236", "0.4288689", "0.4282972", "0.4282481", "0.42805865", "0.42738232", "0.42732772", "0.42729285", "0.4271579", "0.42705345", "0.42684597" ]
0.6293567
0
RecordReqDuration records the duration of given operation in metrics system
func (pr PrometheusRecorder) RecordReqDuration(jenkinsService, operation string, code int, elapsedTime float64) { reportRequestDuration(jenkinsService, operation, code, elapsedTime) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func recordDuration(name string, hostname string, path string, method string, duration float64) {\n\trequestDurations.WithLabelValues(name, hostname, path, method).Observe(duration)\n}", "func (me *Metrics) RecordRequestTime(labels Labels, length time.Duration) {\n\t// Only record times for successful requests, as we don't have labels to screen out bad requests.\n\tif labels.RequestStatus == RequestStatusOK {\n\t\tme.RequestTimer.Update(length)\n\t}\n}", "func PromAddRequestDuration(sc int, m string, d time.Duration) {\n\tRequestDuration.With(prometheus.Labels{\"code\": fmt.Sprintf(\"%v\", sc), \"method\": m}).Set(d.Seconds())\n}", "func (me *Metrics) RecordRequest(labels Labels) {\n\tme.RequestStatuses[labels.RType][labels.RequestStatus].Mark(1)\n\tif labels.Source == DemandApp {\n\t\tme.AppRequestMeter.Mark(1)\n\t} else {\n\t\tif labels.CookieFlag == CookieFlagNo {\n\t\t\t// NOTE: Old behavior was log me.AMPNoCookieMeter here for AMP requests.\n\t\t\t// AMP is still new and OpenRTB does not do this, so changing to match\n\t\t\t// OpenRTB endpoint\n\t\t\tme.NoCookieMeter.Mark(1)\n\t\t}\n\t}\n\n\t// Handle the account metrics now.\n\tam := me.getAccountMetrics(labels.PubID)\n\tam.requestMeter.Mark(1)\n}", "func recordRequest(name string, hostname string, path string, method string) {\n\trequestsProcessed.WithLabelValues(name, hostname, path, method).Inc()\n}", "func observeRequestSimDuration(jobName string, extJobID uuid.UUID, vrfVersion vrfcommon.Version, pendingReqs []pendingRequest) {\n\tnow := time.Now().UTC()\n\tfor _, request := range pendingReqs {\n\t\t// First time around lastTry will be zero because the request has not been\n\t\t// simulated yet. It will be updated every time the request is simulated (in the event\n\t\t// the request is simulated multiple times, due to it being underfunded).\n\t\tif request.lastTry.IsZero() {\n\t\t\tvrfcommon.MetricTimeUntilInitialSim.\n\t\t\t\tWithLabelValues(jobName, extJobID.String(), string(vrfVersion)).\n\t\t\t\tObserve(float64(now.Sub(request.utcTimestamp)))\n\t\t} else {\n\t\t\tvrfcommon.MetricTimeBetweenSims.\n\t\t\t\tWithLabelValues(jobName, extJobID.String(), string(vrfVersion)).\n\t\t\t\tObserve(float64(now.Sub(request.lastTry)))\n\t\t}\n\t}\n}", "func (m *metricsReporter) ReportRequest(_ context.Context, startTime time.Time, action string, err error) {\n\tm.requestDurationMetric.With(kitmetrics.Field{Key: \"action\", Value: action}).Observe(time.Since(startTime))\n\tm.requestCounterMetric.With(kitmetrics.Field{Key: \"action\", Value: action}).Add(1)\n\tif err != nil {\n\t\tm.errorCounterMetric.With(kitmetrics.Field{Key: \"action\", Value: action}).Add(1)\n\t}\n}", "func (m *MetricsProvider) AddOperationTime(value time.Duration) {\n}", "func ReportLibRequestMetric(system, handler, method, status string, started time.Time) {\n\trequestsTotalLib.WithLabelValues(system, handler, method, status).Inc()\n\trequestLatencyLib.WithLabelValues(system, handler, method, status).Observe(time.Since(started).Seconds())\n}", "func RecordKMSOperationLatency(providerName, methodName string, duration time.Duration, err error) {\n\tKMSOperationsLatencyMetric.WithLabelValues(providerName, methodName, getErrorCode(err)).Observe(duration.Seconds())\n}", "func BenchmarkRecordReqCommand(b *testing.B) {\n\tw := newWorker()\n\n\tregister := &registerViewReq{views: []*View{view}, err: make(chan error, 1)}\n\tregister.handleCommand(w)\n\tif err := <-register.err; err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tconst tagCount = 10\n\tctxs := make([]context.Context, 0, tagCount)\n\tfor i := 0; i < tagCount; i++ {\n\t\tctx, _ := tag.New(context.Background(),\n\t\t\ttag.Upsert(k1, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k2, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k3, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k4, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k5, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k6, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k7, fmt.Sprintf(\"v%d\", i)),\n\t\t\ttag.Upsert(k8, fmt.Sprintf(\"v%d\", i)),\n\t\t)\n\t\tctxs = append(ctxs, ctx)\n\t}\n\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\trecord := &recordReq{\n\t\t\tms: []stats.Measurement{\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t\tm.M(1),\n\t\t\t},\n\t\t\ttm: tag.FromContext(ctxs[i%len(ctxs)]),\n\t\t}\n\t\trecord.handleCommand(w)\n\t}\n}", "func (tr *customTransport) Duration() time.Duration {\n\treturn tr.reqEnd.Sub(tr.reqStart)\n}", "func RecordLatency(seconds float64) RecordOption {\n\treturn func(r *RecordStream) {\n\t\tr.createRequest.BufferFragSize = uint32(seconds*float64(r.createRequest.Rate)) * uint32(r.createRequest.Channels) * uint32(r.bytesPerSample)\n\t\tr.createRequest.BufferMaxLength = 2 * r.createRequest.BufferFragSize\n\t\tr.createRequest.AdjustLatency = true\n\t}\n}", "func ReportAPIRequestMetric(handler, method, status string, started time.Time) {\n\trequestsTotalAPI.WithLabelValues(handler, method, status).Inc()\n\trequestLatencyAPI.WithLabelValues(handler, method, status).Observe(time.Since(started).Seconds())\n}", "func (*Client) RequestDuration() map[float64]float64 {\n\trequestDuration.Write(m)\n\tresult := make(map[float64]float64, len(m.Summary.Quantile))\n\tfor _, v := range m.Summary.Quantile {\n\t\tresult[*v.Quantile] = *v.Value\n\t}\n\n\treturn result\n}", "func RecordVolumeOperationMetric(pluginName, opName string, timeTaken float64, err error) {\n\tif pluginName == \"\" {\n\t\tpluginName = \"N/A\"\n\t}\n\tif err != nil {\n\t\tvolumeOperationErrorsMetric.WithLabelValues(pluginName, opName).Inc()\n\t\treturn\n\t}\n\tvolumeOperationMetric.WithLabelValues(pluginName, opName).Observe(timeTaken)\n}", "func (dc *deviceContext) computeTime(req *Request) time.Duration {\n\trequestDuration := time.Duration(0)\n\n\tswitch req.Type {\n\t// Handle metadata requests, plus metadata requests that have been factored out because we\n\t// need separate handling for them.\n\tcase MetadataRequest, CloseRequest:\n\t\trequestDuration = dc.deviceConfig.MetadataOpTime\n\tcase AllocateRequest:\n\t\trequestDuration = dc.computeSeekTime(req) + dc.deviceConfig.AllocateTime(req.Size)\n\tcase ReadRequest:\n\t\trequestDuration = dc.computeSeekTime(req) + dc.deviceConfig.ReadTime(req.Size)\n\tcase WriteRequest:\n\t\tswitch dc.deviceConfig.WriteStrategy {\n\t\tcase slowfs.FastWrite:\n\t\t\t// Leave at 0 seconds.\n\t\tcase slowfs.SimulateWrite:\n\t\t\trequestDuration = dc.computeSeekTime(req) + dc.deviceConfig.WriteTime(req.Size)\n\t\t}\n\tcase FsyncRequest:\n\t\tswitch dc.deviceConfig.FsyncStrategy {\n\t\tcase slowfs.DumbFsync:\n\t\t\trequestDuration = dc.deviceConfig.SeekTime * 10\n\t\tcase slowfs.WriteBackCachedFsync:\n\t\t\trequestDuration = dc.deviceConfig.SeekTime + dc.deviceConfig.WriteTime(dc.writeBackCache.getUnwrittenBytes(req.Path))\n\t\t}\n\tdefault:\n\t\tdc.logger.Printf(\"unknown request type for %+v\\n\", req)\n\t}\n\n\treturn latestTime(dc.busyUntil, req.Timestamp).Add(requestDuration).Sub(req.Timestamp)\n}", "func (nsc *NilConsumerStatsCollector) UpdateGetRecordsDuration(time.Duration) {}", "func TimeLog(nextHandler http.Handler) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// log.Debugf(\"Request received : %v\", r)\n\t\tstart := time.Now()\n\n\t\t// make the call\n\t\tv := capturewriter.CaptureWriter{ResponseWriter: w, StatusCode: 0}\n\t\tctx := context.Background()\n\t\tnextHandler.ServeHTTP(&v, r.WithContext(ctx))\n\n\t\t// Stop timer\n\t\tend := time.Now()\n\n\t\tgo func() {\n\t\t\tlatency := end.Sub(start)\n\t\t\treq++\n\t\t\tavgLatency = avgLatency + ((int64(latency) - avgLatency) / req)\n\t\t\t// log.Debugf(\"Request handled successfully: %v\", v.GetStatusCode())\n\t\t\tvar statusCode = v.GetStatusCode()\n\n\t\t\tpath := r.URL.Path\n\t\t\thost := r.Host\n\t\t\treferer := r.Header.Get(\"Referer\")\n\t\t\tclientIP := r.RemoteAddr\n\t\t\tmethod := r.Method\n\n\t\t\tlog.Infow(fmt.Sprintf(\"|%d| %10v %s\", statusCode, time.Duration(latency), path),\n\t\t\t\t\"statusCode\", statusCode,\n\t\t\t\t\"request\", req,\n\t\t\t\t\"latency\", time.Duration(latency),\n\t\t\t\t\"avgLatency\", time.Duration(avgLatency),\n\t\t\t\t\"ipPort\", clientIP,\n\t\t\t\t\"method\", method,\n\t\t\t\t\"host\", host,\n\t\t\t\t\"path\", path,\n\t\t\t\t\"referer\", referer,\n\t\t\t)\n\t\t}()\n\n\t}\n}", "func TrackRequest(method string, uri string) *DurationTrace {\n\ttraces := make([]*DurationTrace, 0)\n\n\tif traceListeners != nil {\n\t\tfor _, tl := range traceListeners {\n\t\t\ttraces = append(traces, (*tl).TrackRequest(method, uri))\n\t\t}\n\t}\n\n\tdt := newAggregateDurationTrace(traces)\n\treturn &dt\n}", "func (m *Measurement) Record(name string, duration time.Duration) {\n\tr := m.Result(name)\n\tr.Durations = append(r.Durations, duration)\n}", "func (r *Recorder) Record(ctx context.Context, outDir string) error {\n\tvs, err := r.timeline.StopRecording(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to stop timeline\")\n\t}\n\n\tpv := perf.NewValues()\n\ttimeElapsed := time.Since(r.startTime)\n\tpv.Set(perf.Metric{\n\t\tName: \"Recorder.ElapsedTime\",\n\t\tUnit: \"s\",\n\t\tDirection: perf.SmallerIsBetter,\n\t}, float64(timeElapsed.Seconds()))\n\tpv.Merge(vs)\n\n\treturn pv.Save(outDir)\n}", "func (r *Reporter) ReportIMDSOperationDuration(operation string, duration time.Duration) error {\n\treturn r.ReportOperation(operation, ImdsOperationsDurationM.M(duration.Seconds()))\n}", "func Record(ctx context.Context, ms ...Measurement) {\n\treq := &recordReq{\n\t\tnow: time.Now(),\n\t\ttm: tag.FromContext(ctx),\n\t\tms: ms,\n\t}\n\tdefaultWorker.c <- req\n}", "func (t *testMetricsBackend) AddDuration(l metricsLabels, f float64) {\n\tt.Lock()\n\tt.durations[l] = append(t.durations[l], f)\n\tt.Unlock()\n}", "func (nsc *NilConsumerStatsCollector) UpdateGetRecordsReadResponseDuration(time.Duration) {}", "func (s Broker) TimingDuration(name string, duration time.Duration) {\n\ttimeMillis := int(duration.Nanoseconds() / 1000000)\n\ts.Timing(name, timeMillis)\n}", "func testOperationDurationMetric(t *testing.T, reporter *Reporter, m *stats.Float64Measure) {\n\tminimumDuration := float64(2)\n\tmaximumDuration := float64(4)\n\ttestOperationKey := \"test\"\n\terr := reporter.ReportOperation(testOperationKey, m.M(minimumDuration))\n\tif err != nil {\n\t\tt.Errorf(\"Error when reporting metrics: %v from %v\", err, m.Name())\n\t}\n\terr = reporter.ReportOperation(testOperationKey, m.M(maximumDuration))\n\tif err != nil {\n\t\tt.Errorf(\"Error when reporting metrics: %v from %v\", err, m.Name())\n\t}\n\n\trow, err := view.RetrieveData(m.Name())\n\tif err != nil {\n\t\tt.Errorf(\"Error when retrieving data: %v from %v\", err, m.Name())\n\t}\n\n\tduration, ok := row[0].Data.(*view.DistributionData)\n\tif !ok {\n\t\tt.Error(\"DistributionData missing\")\n\t}\n\n\ttag := row[0].Tags[0]\n\tif tag.Key.Name() != operationTypeKey.Name() && tag.Value != testOperationKey {\n\t\tt.Errorf(\"Tag does not match for %v\", operationTypeKey.Name())\n\t}\n\tif duration.Min != minimumDuration {\n\t\tt.Errorf(\"Metric: %v - Expected %v, got %v. \", m.Name(), duration.Min, minimumDuration)\n\t}\n\tif duration.Max != maximumDuration {\n\t\tt.Errorf(\"Metric: %v - Expected %v, got %v. \", m.Name(), duration.Max, maximumDuration)\n\t}\n}", "func (me *Metrics) RecordPrebidCacheRequestTime(success bool, length time.Duration) {\n\tif success {\n\t\tme.PrebidCacheRequestTimerSuccess.Update(length)\n\t} else {\n\t\tme.PrebidCacheRequestTimerError.Update(length)\n\t}\n}", "func requestMetrics(l *log.Logger) service {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tstart := time.Now()\n\t\t\th.ServeHTTP(w, r)\n\t\t\tl.Printf(\"%s request to %s took %vns.\", r.Method, r.URL.Path, time.Since(start).Nanoseconds())\n\t\t})\n\t}\n}", "func RecordControllerPolicyExecTime(timer *Timer, op OperationKind, hadError bool) {\n\tif op == CreateOp {\n\t\ttimer.stopAndRecordExecTimeWithError(addPolicyExecTime, hadError)\n\t} else {\n\t\ttimer.stopAndRecordCRUDExecTime(controllerPolicyExecTime, op, hadError)\n\t}\n}", "func (client PrimitiveClient) PutDurationResponder(resp *http.Response) (result autorest.Response, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByClosing())\n result.Response = resp\n return\n}", "func Timing(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\t\tnext.ServeHTTP(w, r)\n\t\td := time.Since(start)\n\t\tlogrus.WithField(\"duration\", d).\n\t\t\tWithField(\"request_id\", GetRequestID(r.Context())).\n\t\t\tDebug(\"Request timing\")\n\t})\n}", "func recordGCDuration(duration time.Duration) {\n\tstorage.PromGCDurationMilliseconds.Observe(float64(duration.Nanoseconds()) / float64(time.Millisecond))\n}", "func RequestTimer(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\t\tdefer func() {\n\t\t\tmillis := int64((time.Now().Sub(start)) / time.Millisecond)\n\t\t\tlog.Printf(\"severity=INFO RequestId=%v, Duration_ms=%v\", context.MustGetRequestId(r), millis)\n\t\t}()\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func InstrumentRoundTripperDuration(obs prometheus.ObserverVec, next http.RoundTripper) promhttp.RoundTripperFunc {\n\treturn promhttp.RoundTripperFunc(func(r *http.Request) (*http.Response, error) {\n\t\tstart := time.Now()\n\t\tresp, err := next.RoundTrip(r)\n\t\tif err == nil {\n\t\t\tobs.With(\n\t\t\t\tprometheus.Labels{\n\t\t\t\t\t\"code\": resp.Status,\n\t\t\t\t\t\"method\": r.Method,\n\t\t\t\t\t\"host\": r.URL.Host,\n\t\t\t\t},\n\t\t\t).Observe(time.Since(start).Seconds())\n\t\t}\n\t\treturn resp, err\n\t})\n}", "func (r *receiveMessageRequestRecorder) Record(req *sqs.ReceiveMessageInput) {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tr.requests = append(r.requests, req)\n}", "func (c *Prometheus) TrackRequest(r *http.Request, t timer.Timer, success bool) Client {\n\tb := bucket.NewHTTPRequest(c.httpRequestSection, r, success, c.httpMetricCallback, c.unicode)\n\tmetric := b.Metric()\n\tmetricTotal := b.MetricTotal()\n\n\tmetric = strings.Replace(metric, \"-.\", \"\", -1)\n\tmetric = strings.Replace(metric, \".-\", \"\", -1)\n\tmetric = strings.Replace(metric, \"-\", \"\", -1)\n\tmetric = strings.Replace(metric, \".\", \"_\", -1)\n\n\tmetricTotal = strings.Replace(metricTotal, \"-.\", \"\", -1)\n\tmetricTotal = strings.Replace(metricTotal, \".-\", \"\", -1)\n\tmetricTotal = strings.Replace(metricTotal, \"-\", \"\", -1)\n\tmetricTotal = strings.Replace(metricTotal, \".\", \"_\", -1)\n\n\tmetricInc := c.getIncrementer(metric)\n\tmetricTotalInc := c.getIncrementer(metricTotal)\n\n\tlabels := map[string]string{\"success\": strconv.FormatBool(success), \"action\": r.Method}\n\n\tmetric = c.prepareMetric(metric)\n\tmetricTotal = c.prepareMetric(metricTotal)\n\tmetricInc.Increment(metric, labels)\n\tmetricTotalInc.Increment(metricTotal, labels)\n\n\treturn c\n}", "func (m *MockMetricsProvider) ObserveHTTPRequestDuration(method, handler, statusCode string, elapsed float64) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"ObserveHTTPRequestDuration\", method, handler, statusCode, elapsed)\n}", "func sendLatency(\n\tscope tally.Scope,\n\ttable, operation string,\n\td time.Duration,\n) {\n\ts := scope.Tagged(map[string]string{\n\t\t\"table\": table,\n\t\t\"operation\": operation,\n\t})\n\ts.Timer(\"execute_latency\").Record(d)\n}", "func StatRequest(rpc string, errcode string, inTime, outTime time.Time) int64 {\n\treqCounter.With(prometheus.Labels{\n\t\t\"rpc\": rpc,\n\t\t\"errcode\": errcode,\n\t}).Inc()\n\n\tcost := toMSTimestamp(outTime) - toMSTimestamp(inTime)\n\trespTimeSummary.With(prometheus.Labels{\"rpc\": rpc}).Observe(float64(cost))\n\n\treturn cost\n}", "func (i *TelemetryStorage) RecordLatency(method string, latency time.Duration) {\n\tbucket := constants.Bucket(latency.Milliseconds())\n\tswitch method {\n\tcase constants.Treatment:\n\t\ti.latencies.treatment.Incr(bucket)\n\tcase constants.Treatments:\n\t\ti.latencies.treatments.Incr(bucket)\n\tcase constants.TreatmentWithConfig:\n\t\ti.latencies.treatmentWithConfig.Incr(bucket)\n\tcase constants.TreatmentsWithConfig:\n\t\ti.latencies.treatmentsWithConfig.Incr(bucket)\n\tcase constants.Track:\n\t\ti.latencies.track.Incr(bucket)\n\t}\n}", "func (r *RedisStorage) CountRequest(key string, requestTs time.Time, windowDuration time.Duration) (*WindowInfo, error) {\n\tcn := r.p.Get()\n\tdefer cn.Close()\n\n\tredisKey := r.getRedisKey(key)\n\tcn.Send(\"MULTI\")\n\tcn.Send(\"HINCRBY\", redisKey, noCallsField, 1)\n\tcn.Send(\"HSETNX\", redisKey, windowStartField, requestTs.UnixNano())\n\tcn.Send(\"HGET\", redisKey, windowStartField)\n\n\tvalues, err := redis.Values(cn.Do(\"EXEC\"))\n\tif err != nil {\n\t\t// in case of error happen, try to delete the key\n\t\tr.deleteKey(redisKey, cn)\n\t\treturn nil, err\n\t}\n\n\tcalls, _ := redis.Int(values[0], nil)\n\tsetStartTimeSuccess, _ := redis.Bool(values[1], nil)\n\tstartTs, _ := redis.Int64(values[2], nil)\n\n\t// if start time is set, it means the rate limit does not exist, hence set expiry time\n\tif setStartTimeSuccess {\n\t\t_, err = cn.Do(\"PEXPIREAT\", redisKey, r.keyExpiredAtInMilliSeconds(requestTs, windowDuration))\n\t\tif err != nil {\n\t\t\t// in case of error happen, try to delete the key\n\t\t\tr.deleteKey(redisKey, cn)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tinfo := &WindowInfo{\n\t\tCalls: calls,\n\t\tStartTimestamp: time.Unix(0, startTs),\n\t}\n\n\treturn info, nil\n}", "func requestSize(req *logging.WriteLogEntriesRequest) (int, error) {\n\tb, err := json.Marshal(req)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(b), nil\n}", "func (d TestSink) Timing(c *telemetry.Context, stat string, value float64) {\n\td[stat] = TestMetric{\"Timing\", value, c.Tags()}\n}", "func (c *Client) Duration(stat string, duration time.Duration, rate float64) error {\n\treturn c.send(stat, rate, \"%d|ms\", millisecond(duration))\n}", "func (c *Stats) RecordRes(_time uint64, method string, worker_id int) {\n\tif _stats_use_channel {\n\t\tc.C_response <- _time\n\t} else {\n\t\tatomic.AddUint64(&c.totalResp, STAT_BATCH_SIZE)\n\t\tatomic.AddUint64(&c.totalRespTime, _time)\n\t}\n\n\t// if longer that 200ms, it is a slow response\n\tif _time > slowThreshold*1000000 {\n\t\tatomic.AddUint64(&c.totalResSlow, 1)\n\t}\n\n\t// record percentile\n\t//c.mu.Lock()\n\t//c.quants.Insert(float64(_time))\n\t//c.mu.Unlock()\n}", "func ReqLogger(rw *http.ResponseWriter, responseStatus *int, URL *url.URL, Method string, start *time.Time) {\n\tif *responseStatus != 200 && *responseStatus != 308 {\n\t\t(*rw).WriteHeader(*responseStatus)\n\t}\n\tlog.Printf(\"%s %s %d %s\\n\", Method, URL, *responseStatus, time.Since(*start))\n}", "func Record(h http.Handler, method, url string, headers map[string]string, payload string) *httptest.ResponseRecorder {\n\t// prepare body\n\tvar body io.Reader\n\tif payload != \"\" {\n\t\tbody = strings.NewReader(payload)\n\t}\n\n\t// create request and recorder\n\tr := httptest.NewRequest(method, url, body)\n\tw := httptest.NewRecorder()\n\n\t// set headers\n\tfor k, v := range headers {\n\t\tr.Header.Set(k, v)\n\t}\n\n\t// call handler\n\th.ServeHTTP(w, r)\n\n\treturn w\n}", "func (b *Benchttp) SendDuration(d time.Duration) *Report {\n\tb.targetDuration = d\n\treturn b.do()\n}", "func (sw *Stopwatch) Record() time.Duration {\n\td := sw.Elapsed()\n\tsw.timer.record(d)\n\treturn d\n}", "func (l *LogRequest) SetDuration(duration int64) {\n\tl.Duration = duration\n}", "func (client PrimitiveClient) PutDurationSender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (zr *ZRequest) Duration() time.Duration {\n\tif zr.endTime.IsZero() {\n\t\treturn 0\n\t}\n\treturn zr.endTime.Sub(zr.startTime)\n}", "func (c *Client) RecordRequest(peerID peer.ID, req *RecordRequest) (interface{}, error) {\n\tif req == nil {\n\t\treq = &RecordRequest{\n\t\t\tRecordName: defaultRecordName,\n\t\t\tUserName: defaultRecordUserName,\n\t\t}\n\t}\n\tmarshaledData, err := json.Marshal(&req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.GenerateStreamAndWrite(\n\t\tcontext.Background(), peerID, \"record-request\", c.IPFSAPI, marshaledData,\n\t)\n}", "func (m *MetricsProvider) ProcessDIDTime(value time.Duration) {\n}", "func (manager *Manager) RecordTime(t interface{}) {\n\tmanager.metaWG.Add(1)\n\tmanager.metadata.timings <- t\n}", "func (h *HTTP) Timing(stat string, delta int64) error {\n\treadable := time.Duration(delta).String()\n\n\th.Lock()\n\th.json.SetP(delta, stat)\n\th.json.SetP(readable, stat+\"_readable\")\n\th.Unlock()\n\treturn nil\n}", "func (lgr logger) RequestEnd(act string, startAt time.Time, status *int, errMsg *string) {\n\tlgr.client.Sugar().Infow(\"http_request\",\n\t\t\"action\", act,\n\t\t\"status_code\", status,\n\t\t\"error_message\", errMsg,\n\t\t\"created_at\", startAt.Unix(),\n\t\t\"response_time\", fmt.Sprintf(\"%.4f\", time.Since(startAt).Seconds()))\n}", "func incrRequestStatDelta() {\n\tStatMu.Mutex.Lock()\n\n\t// increment the requests counter\n\t*(StatMu.InstanceStat.Requests) = *(StatMu.InstanceStat.Requests) + uint64(1)\n\tStatMu.Mutex.Unlock()\n\n}", "func calculateDuration(r *record) time.Duration {\n\tdateFormat := \"2006-01-0215:04:05\"\n\n\tstart, err := time.Parse(dateFormat, r.date+r.startTime)\n\tcheckErr(err)\n\n\tend, err := time.Parse(dateFormat, r.date+r.endTime)\n\tcheckErr(err)\n\n\tpause, err := time.ParseDuration(r.pause)\n\tcheckErr(err)\n\n\treturn end.Sub(start) - pause\n}", "func (me *Metrics) RecordOverheadTime(overhead OverheadType, length time.Duration) {\n\tme.OverheadTimer[overhead].Update(length)\n}", "func (client PrimitiveClient) GetDurationResponder(resp *http.Response) (result DurationWrapper, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n}", "func keyDuration(oid int64) string {\n\treturn _keyDuration + strconv.FormatInt(oid, 10)\n}", "func main() {\n\tinitFlag()\n\n\tts := status.NewTimerStatus()\n\tts.SetTimerDump(time.Duration(duration)*time.Second, func() {\n\t\tb := bytes.NewBuffer([]byte{})\n\t\tts.DumpCount(b)\n\t\tfmt.Printf(\"%v\\n\", string(b.Bytes()))\n\t})\n\n\tvar wg sync.WaitGroup\n\tfor c := 0; c < concurrence; c++ {\n\t\tgo request(&wg, ts)\n\t\twg.Add(1)\n\t}\n\n\twg.Wait()\n}", "func logEndOfRequest(\n\tr *stdhttp.Request,\n\tduration time.Duration,\n\tmw mutil.WriterProxy,\n) {\n\tl := log.Ctx(r.Context()).WithFields(log.F{\n\t\t\"subsys\": \"http\",\n\t\t\"path\": r.URL.String(),\n\t\t\"method\": r.Method,\n\t\t\"status\": mw.Status(),\n\t\t\"bytes\": mw.BytesWritten(),\n\t\t\"duration\": duration,\n\t})\n\tif routeContext := chi.RouteContext(r.Context()); routeContext != nil {\n\t\tl = l.WithField(\"route\", routeContext.RoutePattern())\n\t}\n\tl.Info(\"finished request\")\n}", "func (r *ApacheLogRecord) formattedTimeRequest() (string, string) {\n\treturn r.time.Format(timeFormat), fmt.Sprintf(requestFormat, r.method, r.uri, r.protocol)\n}", "func (r *Reporter) Timing(metricName string, value time.Duration, tags metrics.Tags) error {\n\treturn nil\n}", "func decodeReq(req logql.QueryParams) ([]*labels.Matcher, model.Time, model.Time, error) {\n\texpr, err := req.LogSelector()\n\tif err != nil {\n\t\treturn nil, 0, 0, err\n\t}\n\n\tmatchers := expr.Matchers()\n\tnameLabelMatcher, err := labels.NewMatcher(labels.MatchEqual, labels.MetricName, \"logs\")\n\tif err != nil {\n\t\treturn nil, 0, 0, err\n\t}\n\tmatchers = append(matchers, nameLabelMatcher)\n\tif err != nil {\n\t\treturn nil, 0, 0, err\n\t}\n\tmatchers, err = injectShardLabel(req.GetShards(), matchers)\n\tif err != nil {\n\t\treturn nil, 0, 0, err\n\t}\n\tfrom, through := util.RoundToMilliseconds(req.GetStart(), req.GetEnd())\n\treturn matchers, from, through, nil\n}", "func (nsc *NilConsumerStatsCollector) UpdateGetRecordsUnmarshalDuration(time.Duration) {}", "func (nsc *NilConsumerStatsCollector) AddGetRecordsTimeout(int) {}", "func (client PrimitiveClient) GetDurationSender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func (r RecordTTL) Duration() time.Duration {\n\treturn (time.Second * time.Duration(int(r)))\n}", "func MetricMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tt := metrics.NewTimer(serverRequestDuration.WithLabels(c.Request.URL.Path))\n\t\tdefer t.ObserveDuration()\n\t\tc.Next()\n\t}\n}", "func (om OperationMetric) Duration() time.Duration {\n\tif om.Start.IsZero() {\n\t\treturn 0\n\t}\n\treturn om.End.Time.Sub(om.Start.Time)\n}", "func (p *Prometheus) ObserveDurationResourceAddEventProcessedSuccess(handler string, start time.Time) {\n\td := p.getDuration(start)\n\tp.processedSucDuration.WithLabelValues(handler, addEventType).Observe(d.Seconds())\n}", "func UpdateDuration(label FunctionLabel, duration time.Duration) {\n\t// TODO(maciekpytel): remove second condition if we manage to get\n\t// asynchronous node drain\n\tif duration > LogLongDurationThreshold && label != ScaleDown {\n\t\tklog.V(4).Infof(\"Function %s took %v to complete\", label, duration)\n\t}\n\tfunctionDuration.WithLabelValues(string(label)).Observe(duration.Seconds())\n\tfunctionDurationSummary.WithLabelValues(string(label)).Observe(duration.Seconds())\n}", "func (o QuotaLimitResponseOutput) Duration() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QuotaLimitResponse) string { return v.Duration }).(pulumi.StringOutput)\n}", "func (me *Metrics) RecordAdapterRequest(labels AdapterLabels) {\n\tam, ok := me.AdapterMetrics[labels.Adapter]\n\tif !ok {\n\t\tglog.Errorf(\"Trying to run adapter metrics on %s: adapter metrics not found\", string(labels.Adapter))\n\t\treturn\n\t}\n\n\taam, ok := me.getAccountMetrics(labels.PubID).adapterMetrics[labels.Adapter]\n\tswitch labels.AdapterBids {\n\tcase AdapterBidNone:\n\t\tam.NoBidMeter.Mark(1)\n\t\tif ok {\n\t\t\taam.NoBidMeter.Mark(1)\n\t\t}\n\tcase AdapterBidPresent:\n\t\tam.GotBidsMeter.Mark(1)\n\t\tif ok {\n\t\t\taam.GotBidsMeter.Mark(1)\n\t\t}\n\tdefault:\n\t\tglog.Warningf(\"No go-metrics logged for AdapterBids value: %s\", labels.AdapterBids)\n\t}\n\tfor errType := range labels.AdapterErrors {\n\t\tam.ErrorMeters[errType].Mark(1)\n\t}\n\n\tif labels.CookieFlag == CookieFlagNo {\n\t\tam.NoCookieMeter.Mark(1)\n\t}\n}", "func RegisterDuration(key string, def time.Duration, description string) onion.Int {\n\tsetDescription(key, description)\n\treturn o.RegisterDuration(key, def)\n}", "func (tcr *TestCaseReporter) Duration() time.Duration {\n\tif tcr.startTime.IsZero() || tcr.endTime.IsZero() {\n\t\treturn 0\n\t}\n\n\treturn tcr.endTime.Sub(tcr.startTime)\n}", "func (c *volumeSeriesRequestCmd) makeRecord(o *models.VolumeSeriesRequest, now time.Time) map[string]string {\n\tvar cluster string\n\tif cn, ok := c.clusters[string(o.ClusterID)]; ok { // assume map\n\t\tcluster = cn.name\n\t} else {\n\t\tcluster = string(o.ClusterID)\n\t}\n\tvar node string\n\tif cn, ok := c.nodes[string(o.NodeID)]; ok { // assume map\n\t\tnode = cn.name\n\t} else {\n\t\tnode = string(o.NodeID)\n\t}\n\tobj := string(o.VolumeSeriesID)\n\tif util.Contains(o.RequestedOperations, common.VolReqOpCGCreateSnapshot) {\n\t\tobj = string(o.ConsistencyGroupID)\n\t}\n\tif util.Contains(o.RequestedOperations, common.VolReqOpAllocateCapacity) {\n\t\tobj = string(o.ServicePlanAllocationID)\n\t}\n\tpct := \"\"\n\tif o.Progress != nil {\n\t\tpct = fmt.Sprintf(\"%d%%\", swag.Int32Value(o.Progress.PercentComplete))\n\t}\n\tvar tDur string\n\tif util.Contains(terminalVolumeSeriesRequestStates, o.VolumeSeriesRequestState) {\n\t\ttDur = fmt.Sprintf(\"%s\", time.Time(o.Meta.TimeModified).Sub(time.Time(o.Meta.TimeCreated)).Round(time.Millisecond))\n\t\tpct = \"\"\n\t} else {\n\t\tc.activeReq = true\n\t\ttDur = fmt.Sprintf(\"%s\", now.Sub(time.Time(o.Meta.TimeCreated)).Round(time.Second))\n\t}\n\treturn map[string]string{\n\t\thCluster: cluster,\n\t\thCompleteBy: time.Time(o.CompleteByTime).Format(time.RFC3339),\n\t\thID: string(o.Meta.ID),\n\t\thNode: node,\n\t\thRequestState: o.VolumeSeriesRequestState,\n\t\thRequestedOperations: strings.Join(o.RequestedOperations, \", \"),\n\t\thTimeCreated: time.Time(o.Meta.TimeCreated).Format(time.RFC3339),\n\t\thTimeModified: time.Time(o.Meta.TimeModified).Format(time.RFC3339),\n\t\thVsID: string(o.VolumeSeriesID),\n\t\thTimeDuration: tDur,\n\t\thObjectID: obj,\n\t\thProgress: pct,\n\t}\n}", "func (s *Stats) record(rpcStats stats.RPCStats) {\n\tswitch v := rpcStats.(type) {\n\tcase *stats.InHeader:\n\t\ts.Lock()\n\t\tatomic.AddInt64(&s.respSize, int64(v.WireLength))\n\t\ts.respHeaders = v.Header.Copy()\n\t\ts.Unlock()\n\tcase *stats.InPayload:\n\t\tatomic.AddInt64(&s.respSize, int64(v.WireLength))\n\tcase *stats.InTrailer:\n\t\tatomic.AddInt64(&s.respSize, int64(v.WireLength))\n\t\ts.Lock()\n\t\ts.respTrailers = v.Trailer.Copy()\n\t\ts.Unlock()\n\tcase *stats.OutHeader:\n\t\t// No wire length.\n\t\ts.Lock()\n\t\ts.reqHeaders = v.Header.Copy()\n\t\ts.fullMethod = v.FullMethod\n\t\ts.Unlock()\n\tcase *stats.OutPayload:\n\t\tatomic.AddInt64(&s.reqSize, int64(v.WireLength))\n\tcase *stats.OutTrailer:\n\t\tatomic.AddInt64(&s.reqSize, int64(v.WireLength))\n\tcase *stats.End:\n\t\ts.Duration = v.EndTime.Sub(v.BeginTime)\n\t}\n}", "func (s *service) reqHandler(endpoint *Endpoint, req *request) {\n\tstart := time.Now()\n\tendpoint.Handler.Handle(req)\n\ts.m.Lock()\n\tendpoint.stats.NumRequests++\n\tendpoint.stats.ProcessingTime += time.Since(start)\n\tavgProcessingTime := endpoint.stats.ProcessingTime.Nanoseconds() / int64(endpoint.stats.NumRequests)\n\tendpoint.stats.AverageProcessingTime = time.Duration(avgProcessingTime)\n\n\tif req.respondError != nil {\n\t\tendpoint.stats.NumErrors++\n\t\tendpoint.stats.LastError = req.respondError.Error()\n\t}\n\ts.m.Unlock()\n}", "func (s *DevStat) AddSentDuration(start time.Time, duration time.Duration) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\t//only register the first start time on concurrent mode\n\tif s.Counters[BackEndSentStartTime] == 0 {\n\t\ts.Counters[BackEndSentStartTime] = start.Unix()\n\t}\n\ts.Counters[BackEndSentDuration] = s.Counters[BackEndSentDuration].(float64) + duration.Seconds()\n}", "func (c *LoggerClient) Timing(name string, value time.Duration) {\n\tc.print(\"Timing\", name, value, value)\n}", "func MetricsMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tt := time.Now()\n\n\t\t// Call next to jump into the next handler.\n\t\tc.Next()\n\n\t\ttook := time.Since(t).String()\n\n\t\tlog.\n\t\t\tWith(\n\t\t\t\tzap.String(\"path\", c.Request.RequestURI),\n\t\t\t\tzap.String(\"took\", took),\n\t\t\t).\n\t\t\tDebug(\"request end\")\n\t}\n}", "func tickTimeHandler(duration string) http.HandlerFunc {\n\treturn func(respWriter http.ResponseWriter, request *http.Request) {\n\t\trespWriter.Write([]byte(duration))\n\t}\n}", "func (e *RuntimeStat) Record(d time.Duration, rowNum int) {\n\tatomic.AddInt32(&e.loop, 1)\n\tatomic.AddInt64(&e.consume, int64(d))\n\tatomic.AddInt64(&e.rows, int64(rowNum))\n}", "func (mr *MockMetricsProviderMockRecorder) ObserveHTTPRequestDuration(method, handler, statusCode, elapsed interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ObserveHTTPRequestDuration\", reflect.TypeOf((*MockMetricsProvider)(nil).ObserveHTTPRequestDuration), method, handler, statusCode, elapsed)\n}", "func LogRequest(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t// Start timer\n\t\tstart := time.Now()\n\n\t\t// Add a requestID field to logger\n\t\tuid, _ := ulid.NewFromTime(start)\n\t\tl := log.With(zap.String(\"requestID\", uid.String()))\n\t\t// Add logger to context\n\t\tctx := context.WithValue(r.Context(), requestIDKey, l)\n\t\t// Request with this new context.\n\t\tr = r.WithContext(ctx)\n\n\t\t// wrap the ResponseWriter\n\t\tlw := &basicWriter{ResponseWriter: w}\n\n\t\t// Get the real IP even behind a proxy\n\t\trealIP := r.Header.Get(http.CanonicalHeaderKey(\"X-Forwarded-For\"))\n\t\tif realIP == \"\" {\n\t\t\t// if no content in header \"X-Forwarded-For\", get \"X-Real-IP\"\n\t\t\tif xrip := r.Header.Get(http.CanonicalHeaderKey(\"X-Real-IP\")); xrip != \"\" {\n\t\t\t\trealIP = xrip\n\t\t\t} else {\n\t\t\t\trealIP = r.RemoteAddr\n\t\t\t}\n\t\t}\n\n\t\t// Process request\n\t\tnext.ServeHTTP(lw, r)\n\t\tlw.maybeWriteHeader()\n\n\t\t// Stop timer\n\t\tend := time.Now()\n\t\tlatency := end.Sub(start)\n\t\tstatusCode := lw.Status()\n\n\t\tl.Info(\"request\",\n\t\t\tzap.String(\"method\", r.Method),\n\t\t\tzap.String(\"url\", r.RequestURI),\n\t\t\tzap.Int(\"code\", statusCode),\n\t\t\tzap.String(\"clientIP\", realIP),\n\t\t\tzap.Int(\"bytes\", lw.bytes),\n\t\t\tzap.Int64(\"duration\", int64(latency)/int64(time.Microsecond)),\n\t\t)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func SendProcessMetrics() {\n\n c := h.NewClient(ip, port)\n\n processMetrics := s.ProcessMeasurement{\n TimeSlice: timeSlice,\n CpuUsed: cpu,\n MemUsed: mem,\n }\n\n\n path := fmt.Sprintf(\"/v1/metrics/nodes/%s/process/%s/\", nodeName, processName)\n req, _ := c.NewRequest(\"POST\", path, processMetrics)\n\n\n var processMeasurement s.ProcessMeasurement\n\n c.Do(req, &processMeasurement)\n\n\n //fmt.Printf(\"PROCESS MEASUREMENT SENT: %s\\n\", u.PrettyPrint(processMeasurement))\n\n}", "func (m Metric) AddMethodDuration() {\n\tif m.startTime.Equal(time.Time{}) {\n\t\tpanic(\"not initialised method\")\n\t}\n\n\tdur := time.Now().Sub(m.startTime)\n\tm.backend.AddMethodDuration(m.asset, m.methodName, dur)\n}", "func record(ctx context.Context, ms ...stats.Measurement) {\n\tstats.Record(ctx, ms...)\n}", "func (c *Client) Duration(name string, duration time.Duration) error {\n\treturn c.Histogram(name, millisecond(duration))\n}", "func (recorder *ReqRecorder) CloseAfter(dur time.Duration) {\n\tgo func() {\n\t\t<-time.NewTimer(dur).C\n\t\trecorder.Close()\n\t}()\n}", "func (r *Reporter) ReportCloudProviderOperationDuration(operation string, duration time.Duration) error {\n\treturn r.ReportOperation(operation, CloudProviderOperationsDurationM.M(duration.Seconds()))\n}", "func Durations(statsd io.Writer, key string, interval time.Duration, next http.Handler) http.Handler {\n\t// buffered - reporting is concurrent with the handler\n\tdurations := make(chan time.Duration, 1)\n\tgo reportDurations(statsd, key, time.Tick(interval), durations)\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\t\tnext.ServeHTTP(w, r)\n\t\tdurations <- time.Now().Sub(start)\n\t})\n}", "func (c *MockedHTTPContext) Duration() time.Duration {\n\tif c.MockedDuration != nil {\n\t\treturn c.MockedDuration()\n\t}\n\treturn 0\n}", "func (s *Sample) AddSize(t time.Duration, size int64) *Sample {\n\tatomic.AddInt64(&s.Count, 1)\n\n\tp1 := float64(s.TimeSleep) * 0.01\n\tp10 := float64(s.TimeSleep) * 0.10\n\tp50 := float64(s.TimeSleep) / 2\n\tp97 := float64(s.TimeSleep) * 0.97\n\tp99 := float64(s.TimeSleep) * 0.99\n\n\ts.Lock()\n\tif t.Seconds() <= p1 {\n\t\ts.MetricReqSec.P1++\n\t\ts.MetricBodySize.P1 = size\n\t} else if t.Seconds() > p1 && t.Seconds() <= p10 {\n\t\tif s.MetricReqSec.P10 == 0 {\n\t\t\ts.MetricReqSec.P10 = s.MetricReqSec.P1\n\t\t}\n\t\ts.MetricReqSec.P10++\n\t\ts.MetricBodySize.P10 = size\n\t} else if t.Seconds() > p10 && t.Seconds() <= p50 {\n\t\tif s.MetricReqSec.P50 == 0 {\n\t\t\ts.MetricReqSec.P50 = s.MetricReqSec.P10\n\t\t}\n\t\ts.MetricReqSec.P50++\n\t\ts.MetricBodySize.P50 = size\n\t} else if t.Seconds() > p50 && t.Seconds() <= p97 {\n\t\tif s.MetricReqSec.P50 == 0 {\n\t\t\ts.MetricReqSec.P97 = s.MetricReqSec.P50\n\t\t}\n\t\ts.MetricReqSec.P97++\n\t\ts.MetricBodySize.P97 = size\n\t} else if t.Seconds() > p97 && t.Seconds() <= p99 {\n\t\tif s.MetricReqSec.P99 == 0 {\n\t\t\ts.MetricReqSec.P99 = s.MetricReqSec.P97\n\t\t}\n\t\ts.MetricReqSec.P99++\n\t\ts.MetricBodySize.P99 = size\n\t}\n\ts.Unlock()\n\n\treturn s\n}" ]
[ "0.7509087", "0.6741319", "0.6448921", "0.601776", "0.58529365", "0.5823079", "0.573807", "0.5685555", "0.5597103", "0.5575818", "0.5555443", "0.55546105", "0.5551546", "0.5550965", "0.54829746", "0.54797477", "0.54717624", "0.5451511", "0.5430681", "0.5402279", "0.5385498", "0.5377787", "0.53304756", "0.53281516", "0.5317965", "0.5272165", "0.5253002", "0.5242636", "0.5233388", "0.5230767", "0.52152526", "0.52083653", "0.5202938", "0.5197928", "0.5194526", "0.51936924", "0.5159126", "0.5136083", "0.51281834", "0.5119417", "0.5098883", "0.50976866", "0.5070719", "0.5068659", "0.50644505", "0.5064108", "0.5023322", "0.50129795", "0.50084126", "0.49975514", "0.49836764", "0.49755657", "0.49568585", "0.49339178", "0.49257052", "0.4923151", "0.49154618", "0.49136826", "0.49042365", "0.48974466", "0.48961392", "0.48869568", "0.48820713", "0.48789236", "0.48781618", "0.4873461", "0.48733985", "0.48703533", "0.4858786", "0.4848095", "0.48364103", "0.48281088", "0.48268193", "0.48108876", "0.48069996", "0.48002437", "0.47964936", "0.4794554", "0.47922572", "0.4782552", "0.47766417", "0.47728422", "0.47690332", "0.47645664", "0.47587913", "0.47578958", "0.4753405", "0.47462896", "0.47443977", "0.4741586", "0.47077897", "0.4700519", "0.4699927", "0.46984392", "0.46982118", "0.4693301", "0.46869275", "0.46868104", "0.4682211", "0.46795297" ]
0.83944345
0
Generates a random, 64bit token, encoded as base62.
func GenToken() (string, error) { var data [64]byte if _, err := io.ReadFull(rand.Reader, data[:]); err != nil { return "", err } return basex.Base62StdEncoding.EncodeToString(data[:]), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TokenB64(n int) string {\n\tif n < 1 {\n\t\treturn \"\"\n\t}\n\trand.Seed(time.Now().UTC().UnixNano())\n\tbts := make([]byte, n)\n\trand.Read(bts)\n\treturn base64.StdEncoding.EncodeToString(bts)\n}", "func randToken() string {\n\tba := make([]byte, 32)\n\trand.Read(ba)\n\treturn base64.StdEncoding.EncodeToString(ba)\n\n}", "func randToken() string {\n\tb := make([]byte, 32)\n\trand.Read(b)\n\treturn base64.StdEncoding.EncodeToString(b)\n}", "func randToken() string {\n\tb := make([]byte, 32)\n\trand.Read(b)\n\treturn base64.StdEncoding.EncodeToString(b)\n}", "func generateToken() (string, time.Time) {\n now := time.Now();\n\n randData := make([]byte, TOKEN_RANDOM_BYTE_LEN);\n rand.Read(randData);\n\n timeBinary := make([]byte, 8);\n binary.LittleEndian.PutUint64(timeBinary, uint64(now.UnixNano() / 1000));\n\n tokenData := bytes.Join([][]byte{timeBinary, randData}, []byte{});\n\n return base64.URLEncoding.EncodeToString(tokenData), now;\n}", "func randToken() string {\n\trand.Seed(time.Now().UnixNano())\n\tb := make([]byte, 16)\n\trand.Read(b)\n\treturn fmt.Sprintf(\"%x\", b)\n}", "func Generate() []byte {\n\tt := make([]byte, TOKEN_SIZE)\n\n\t//32-64 is pure random...\n\trand.Read(t[32:])\n\n\thash := createHash(t[32:])\n\n\t//\tlogx.D(\"hash:\", base64.URLEncoding.EncodeToString(hash))\n\n\t//copy hash protection to first 32bytes\n\tcopy(t[0:32], hash)\n\n\t//\tlogx.D(\"token:\", base64.URLEncoding.EncodeToString(t))\n\n\treturn t\n}", "func generateToken() string {\n\tcharset := \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\trand.Seed(time.Now().UnixNano())\n\n\tchars := make([]byte, tokenLength)\n for i := range chars {\n chars[i] = charset[rand.Intn(len(charset))]\n }\n\n\tmsg := string(chars)\n\tfmt.Println(msg)\n\treturn msg\n}", "func generateRandomToken() string {\n\tsleep()\n\trandomBytes := generateRandomBytes()\n\treturn base64.StdEncoding.EncodeToString(randomBytes)\n}", "func NewUuid62() string {\n return ConvertUp(NewUuid(), base62alphabet)\n}", "func randToken(i int) string {\n\tb := make([]byte, i)\n\trand.Read(b)\n\treturn base64.StdEncoding.EncodeToString(b)\n}", "func getToken(length int) string {\n randomBytes := make([]byte, 32)\n _, err := rand.Read(randomBytes)\n if err != nil {\n panic(err)\n }\n return base64.StdEncoding.EncodeToString(randomBytes)[:length]\n}", "func generateSessionToken() string {\n\treturn strconv.FormatInt(rand.Int63(), 16)\n}", "func GenToken() string {\n\tb := make([]byte, 16)\n\trand.Read(b)\n\treturn fmt.Sprintf(\"%x\", b)\n}", "func Base62(n int) string { return String(n, Base62Chars) }", "func GenerateToken() string {\n\trand.Seed(time.Now().UnixNano())\n\tletters := []rune(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n\ttokenBytes := make([]rune, 16)\n\tfor i := range tokenBytes {\n\t\ttokenBytes[i] = letters[rand.Intn(len(letters))]\n\t}\n\treturn string(tokenBytes)\n}", "func randomToken(n int) string {\n\t// buffer to store n bytes\n\tb := make([]byte, n)\n\n\t// read random bytes based on size of b\n\t_, err := rand.Read(b)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t// convert buffer to URL friendly string\n\treturn base64.URLEncoding.EncodeToString(b)\n}", "func GenerateToken() (string, error) {\n\tb := make([]byte, 8)\n\n\tif _, err := rand.Read(b); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%x\", b), nil\n}", "func GenerateToken() (string, error) {\n\t// Minimum token size is 24, max is 36\n\treader := rand.Reader\n\tmax := big.NewInt(int64(MaxTokenSize - MinTokenSize))\n\tmin := big.NewInt(int64(MinTokenSize))\n\n\ttokenSize, err := rand.Int(reader, max)\n\n\tif err != nil {\n\t\tlog.Print(\"[!] Failed to generate a password size\\n\")\n\t}\n\n\ttokenSize.Add(tokenSize, min)\n\n\tvar letters = []rune(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%^&*()=_+[]{};,.<>/?\")\n\n\tb := make([]rune, tokenSize.Int64())\n\tfor i := range b {\n\t\tnewRand, _ := rand.Int(reader, big.NewInt(int64(len(letters))))\n\t\tb[i] = letters[newRand.Int64()]\n\t}\n\n\treturn string(b), nil\n}", "func generateSessionToken() string {\n\t// DO NOT USE THIS IN PRODUCTION\n\treturn strconv.FormatInt(rand.Int63(), 16)\n}", "func RandToken() string {\n\tb := make([]byte, 16)\n\t_, _ = rand.Read(b)\n\treturn fmt.Sprintf(\"%x\", b)\n}", "func GenerateBase64(length int) string {\n\tbase := new(big.Int)\n\tbase.SetString(\"64\", 10)\n\n\tbase64 := \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_\"\n\ttempKey := \"\"\n\tfor i := 0; i < length; i++ {\n\t\tindex, _ := rand.Int(rand.Reader, base)\n\t\ttempKey += string(base64[int(index.Int64())])\n\t}\n\treturn tempKey\n}", "func (t *Token) gen(tl TokenLifetime) (string, error) {\n\tif timeutil.Now().Before(t.NextAt.Time) {\n\t\treturn \"\", ErrTooManyTokens\n\t}\n\n\tv := uniuri.NewLenChars(uniuri.StdLen, _tokenChars)\n\n\th, err := bcrypt.GenerateFromPassword([]byte(v), bcrypt.DefaultCost)\n\tif err != nil {\n\t\t// unlikely to happen\n\t\treturn \"\", err\n\t}\n\n\tt.ExpiresAt = null.TimeFrom(timeutil.Now().Add(tl.Interval))\n\tt.NextAt = null.TimeFrom(timeutil.Now().Add(tl.Cooldown))\n\tt.Hash = h\n\n\treturn v, nil\n}", "func GenerateToken() string {\n\tb := make([]byte, 30)\n\trand.Read(b)\n\n\tfmt.Println(\"hey\")\n\treturn fmt.Sprintf(\"%x\", b)\n}", "func Base62String(length int) string {\n\treturn generateString(length, base62Alphabet)\n}", "func GenToken(id uint) string {\n\tjwt_token := jwt.New(jwt.GetSigningMethod(\"HS256\"))\n\t// Set some claims\n\tjwt_token.Claims = jwt.MapClaims{\n\t\t\"id\": id,\n\t\t\"exp\": time.Now().Add(time.Hour * 24).Unix(),\n\t}\n\t// Sign and get the complete encoded token as a string\n\ttoken, _ := jwt_token.SignedString([]byte(NBSecretPassword))\n\treturn token\n}", "func Uint64() uint64 { return globalRand.Uint64() }", "func Uint64() uint64 { return globalRand.Uint64() }", "func Uint64() uint64 { return globalRand.Uint64() }", "func GenerateToken() string {\n\tb := make([]byte, 16) // 16-byte token\n\trand.Read(b)\n\treturn fmt.Sprintf(\"%x\", b)\n}", "func GenerateSecretToken() string {\n\t// 128 bits of entropy are enough to resist any online attack:\n\tvar buf [16]byte\n\trand.Read(buf[:])\n\t// 26 ASCII characters, should be fine for most purposes\n\treturn B32Encoder.EncodeToString(buf[:])\n}", "func getRandomSecretToken() []byte {\n\tb := make([]byte, 20)\n\tfor i := 0; i < 20; {\n\t\tidx := int(src.Int63() & tokenIdxMask)\n\t\tif idx < len(tokenBytes) {\n\t\t\tb[i] = tokenBytes[idx]\n\t\t\ti++\n\t\t}\n\t}\n\treturn b\n}", "func generateHotpToken(secret string, t uint64) (pass string) {\n\t// make sure to trim whitespace and transform to uppercase\n\tsecret = strings.TrimSpace(strings.ToUpper(secret))\n\tsecretAsBytes, _ := base32.StdEncoding.DecodeString(secret)\n\n\tbuffer := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(buffer, t)\n\n\t// TODO: make use of dynamic algorithms\n\thash := sha1.New\n\tmac := hmac.New(hash, secretAsBytes)\n\tmac.Write(buffer)\n\th := mac.Sum(nil)\n\toffset := (h[19] & 15)\n\n\tvar header uint32\n\treader := bytes.NewReader(h[offset : offset+4])\n\terr := binary.Read(reader, binary.BigEndian, &header)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\th12 := (int(header) & 0x7fffffff) % 1000000\n\totp := int(h12)\n\n\treturn padleft0(otp, 6)\n}", "func GenerateToken(length int) string {\n\tb := make([]byte, length)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Int63()%int64(len(letterBytes))]\n\t}\n\treturn string(b)\n}", "func GenerateToken() (token string, err error) {\n\tb := make([]byte, 8)\n\t_, err = rand.Read(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn hex.EncodeToString(b), nil\n}", "func GenSessionKey() string {\n\n b := make([]byte, 16)\n\n t := time.Now().Unix()\n tmpid := uint16(atomic.AddUint32(&uuid, 1))\n\n b[0] = byte(255)\n b[1] = byte(0)\n b[2] = byte(tmpid)\n b[3] = byte(tmpid >> 8)\n\n b[4] = byte(t)\n b[5] = byte(t >> 8)\n b[6] = byte(t >> 16)\n b[7] = byte(t >> 24)\n\n c, _ := rc4.NewCipher([]byte{0x0c, b[2], b[3], b[0]})\n c.XORKeyStream(b[8:], b[:8])\n\n guid := fmt.Sprintf(\"%x-%x-%x-%x-%x\", b[:4], b[4:6], b[6:8], b[8:12], b[12:])\n h := md5.New()\n io.WriteString(h, guid)\n io.WriteString(h, MD5key)\n\n return fmt.Sprintf(\"%x-%x-%x-%x-%x--%x\", b[:4], b[4:6], b[6:8], b[8:12], b[12:], h.Sum(nil))\n}", "func NewRandomToken(length int) ([]byte, error) {\n\tl := big.NewInt(int64(len(randomCharSet)))\n\n\tresult := make([]byte, length, length)\n\tfor i := 0; i < length; i++ {\n\t\tn, err := rand.Int(rand.Reader, l)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[i] = randomCharSet[n.Int64()]\n\t}\n\treturn result, nil\n}", "func generateNewToken(hashed_usr string) string {\n\t//generate random string\n\ttoken := GenerateRandomString()\n\tSaveToken(hashed_usr, token)\n\treturn token\n}", "func generateSecretKey() (string, error) {\n\tkey := make([]byte, 10)\n\n\t_, err := rand.Read(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn base32.StdEncoding.EncodeToString(key), nil\n}", "func GenerateId() []byte {\n\tt := make([]byte, TOKEN_ID_SIZE)\n\n\t//32-64 is pure random...\n\trand.Read(t)\n\n\treturn t\n}", "func GenerateRandomToken() (string, error) {\n\tb := make([]byte, 32)\n\t_, err := rand.Read(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.URLEncoding.EncodeToString(b), err\n}", "func New64() hash.Hash64 { return New64WithSeed(0) }", "func (client *RedisClient) GenerateToken(userID string) (string, error) {\n\tid := uuid.NewV4()\n\texp := time.Duration(600 * time.Second) // 10 minutes\n\n\terr := client.redisdb.Set(id.String(), userID, exp).Err()\n\treturn id.String(), err\n}", "func base62(b byte) byte {\n\tif b < 10 {\n\t\treturn byte('0' + b)\n\t} else if b < 36 {\n\t\treturn byte('a' - 10 + b)\n\t} else if b < 62 {\n\t\treturn byte('A' - 36 + b)\n\t}\n\tpanic(\"integer out of range for base 62 encode\")\n}", "func GenerateToken(uname string) string {\r\n return Md5String(fmt.Sprintf(\"%s:%d\", uname, rand.Intn(999999)))\r\n}", "func randomKey() string {\n\tvar buffer bytes.Buffer\n\tpossibles := \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"\n\tfor i := 0; i < 64; i++ {\n\t\tbuffer.Write([]byte{possibles[rand.Intn(len(possibles))]})\n\t}\n\treturn buffer.String()\n}", "func generateSessionID() string {\n\tb := make([]byte, randomSessionByteCount)\n\t_, err := randRead(b)\n\tif err != nil {\n\t\t// Only possible if randRead fails to read len(b) bytes.\n\t\tpanic(err)\n\t}\n\t// RawURLEncoding does not pad encoded string with \"=\".\n\treturn base64.RawURLEncoding.EncodeToString(b)\n}", "func RandomUint64() uint64 {\n\treturn rand.Uint64()\n}", "func RandomUint64() (randInt uint64) {\n\trandomBytes := make([]byte, 8)\n\trand.Read(randomBytes)\n\treturn siaencoding.DecUint64(randomBytes)\n}", "func Base64(n int) string { return String(n, Base64Chars) }", "func RandToken() (int, string, error) {\n\tb := make([]byte, 32)\n\t_, e := rand.Read(b)\n\tif e != nil {\n\t\treturn 500, \"\", errors.New(\"Error in generating random token\")\n\t}\n\treturn 200, base64.StdEncoding.EncodeToString(b), nil\n}", "func getUniqueToken() string {\n\tb := make([]rune, TokenLength)\n\tfor i := range b {\n\t\tb[i] = alphabet[rand.Intn(len(alphabet))]\n\t}\n\treturn string(b)\n}", "func randUint64(rand cipher.Stream) uint64 {\n\tb := random.Bits(64, false, rand)\n\treturn binary.BigEndian.Uint64(b)\n}", "func randToken() string {\n\ttok := \"/\"\n\tfor strings.Contains(tok, \"/\") {\n\t\tb := make([]byte, 32)\n\t\trand.Read(b)\n\t\ttok = base64.StdEncoding.EncodeToString(b)\n\t}\n\treturn tok\n}", "func randomUint64(t *testing.T) uint64 {\n\tbigInt, err := rand.Int(rand.Reader, new(big.Int).SetUint64(math.MaxUint64))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn bigInt.Uint64()\n}", "func generatePseudoRand() string {\n\talphanum := \"0123456789abcdefghigklmnopqrst\"\n\tvar bytes = make([]byte, 10)\n\trand.Read(bytes)\n\tfor i, b := range bytes {\n\t\tbytes[i] = alphanum[b%byte(len(alphanum))]\n\t}\n\treturn string(bytes)\n}", "func generateEmailToken() (string, error) {\n\trandBytes, err := scrypt.GenerateRandomBytes(32)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.URLEncoding.EncodeToString(randBytes), nil\n}", "func GenerateRandomString(s int) (string) {\n b := GenerateRandomBytes(s)\n return base64.URLEncoding.EncodeToString(b)\n}", "func generatePrivKey() []byte {\n\tpriv := make([]byte, 32)\n\ts := rand.NewSource(time.Now().UnixNano())\n\tr := rand.New(s)\n\tfor i := 0; i < 31; i++ {\n\t\tpriv[i] = byte(r.Intn(256))\n\t}\n\treturn priv\n}", "func GenNonce() string {\n\treturn fmt.Sprintf(\"%d%8d\", time.Now().Unix(), rand.Intn(100000000))\n}", "func GenerateRandomB64String(n int) (string, error) {\n\tb := make([]byte, n)\n\n\t_, err := rand.Read(b)\n\n\t// If less than n bytes are read, an error is returned\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn base64.URLEncoding.EncodeToString(b), nil\n}", "func generateSessionId(n int) string {\n\n\tvar src = rand.NewSource(time.Now().UnixNano())\n\n\t// session id will be just a time it was created\n\tb := make([]byte, n)\n\n\t// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!\n\tfor i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {\n\t\tif remain == 0 {\n\t\t\tcache, remain = src.Int63(), letterIdxMax\n\t\t}\n\t\tif idx := int(cache & letterIdxMask); idx < len(letterBytes) {\n\t\t\tb[i] = letterBytes[idx]\n\t\t\ti--\n\t\t}\n\t\tcache >>= letterIdxBits\n\t\tremain--\n\t}\n\n\treturn string(b)\n}", "func GenerateToken(key []byte, digest Digest) (string, string) {\n\tt := rand.RandomString(32)\n\treturn t, Sign(key, digest, []byte(t))\n}", "func GenerateToken(dictionary []rune, size int) string {\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tb := make([]rune, size)\n\tfor i := range b {\n\t\tb[i] = dictionary[rand.Intn(len(dictionary))]\n\t}\n\treturn string(b)\n}", "func generateRandomBytes() []byte {\n\tbytes := make([]byte, TOKEN_LENGTH)\n\t_, err := rand.Read(bytes)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tlog.Fatal()\n\t}\n\treturn bytes\n}", "func generateNonce() string {\n\tnow := time.Now().UnixNano() / int64(time.Millisecond)\n\treturn strconv.FormatInt(now, 10)\n}", "func genUUID() string {\n\tuuid := make([]byte, 16)\n\tn, err := rand.Read(uuid)\n\tif n != len(uuid) || err != nil {\n\t\treturn strconv.FormatInt(time.Now().UnixNano(), 10)\n\t}\n\t// TODO: verify the two lines implement RFC 4122 correctly\n\tuuid[8] = 0x80 // variant bits see page 5\n\tuuid[4] = 0x40 // version 4 Pseudo Random, see page 7\n\n\treturn hex.EncodeToString(uuid)\n}", "func RandomKey() string {\n\tk := make([]byte, 12)\n\tfor bytes := 0; bytes < len(k); {\n\t\tn, err := rand.Read(k[bytes:])\n\t\tif err != nil {\n\t\t\tpanic(\"rand.Read() failed\")\n\t\t}\n\t\tbytes += n\n\t}\n\treturn base64.StdEncoding.EncodeToString(k)\n}", "func createNonce() string {\n\tnonceLen := 42 // taken from their example\n\tsrc := []byte(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ09123456789\")\n\n\trslt := make([]byte, nonceLen)\n\tfor i := 0; i < nonceLen; i++ {\n\t\trslt[i] = src[rand.Intn(len(src))]\n\t}\n\n\treturn string(rslt)\n}", "func _() string {\n\trand.Seed(time.Now().UnixNano())\n\tchars := []rune(\"ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ\" +\n\t\t\"abcdefghijklmnopqrstuvwxyzåäö\" +\n\t\t\"0123456789\")\n\tlength := 12\n\tvar b strings.Builder\n\tfor i := 0; i < length; i++ {\n\t\tb.WriteRune(chars[rand.Intn(len(chars))])\n\t}\n\treturn b.String()\n}", "func GenerateKey(n int) (string, error) {\n\tbuf := make([]byte, n)\n\t_, err := rand.Read(buf)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.URLEncoding.EncodeToString(buf), nil\n\n}", "func mustGenSessionToken() []byte {\n\tvar b [32]byte\n\t_, err := rand.Read(b[:])\n\tif err != nil {\n\t\t// out of entropy...\n\t\tpanic(err)\n\t}\n\n\treturn chainhash.HashB(b[:])\n}", "func RandUint64() uint64 {\n\tb := RandBytes(8)\n\treturn binary.BigEndian.Uint64(b)\n}", "func genSessionID() (string, error) {\n\tbytes := make([]byte, 16)\n\tif _, err := rand.Read(bytes); err != nil {\n\t\treturn \"\", err\n\t}\n\tid := make([]byte, hex.EncodedLen(len(bytes)))\n\thex.Encode(id, bytes)\n\treturn string(id), nil\n}", "func GenerateToken(str string) string {\n\thash, err := bcrypt.GenerateFromPassword([]byte(str), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn base64.StdEncoding.EncodeToString(hash)\n}", "func GenerateToken() string {\n\tuuid := uuid.NewV4()\n\treturn hex.EncodeToString(uuid.Bytes())\n}", "func Uint64() uint64 {\n\treturn uint64(rand.Int63n(math.MaxInt64))\n}", "func RandomID(n int) string {\n\trnd := rndGen.GetRand()\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = alphaNumerics[FastRand()%alphaNumericsLength]\n\t}\n\trndGen.PutRand(rnd)\n\treturn ByteToStr(b)\n}", "func encodeBase62(clearText string) string {\n\tvar bigInt big.Int\n\treturn noPad62Encoding.EncodeBigInt(bigInt.SetBytes([]byte(clearText)))\n}", "func RandomUint64() uint64 {\n\tbuf := make([]byte, 8)\n\t_, err := rand.Read(buf)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn binary.LittleEndian.Uint64(buf)\n}", "func GenerateToken(name string, cost int) string {\n\thash, err := bcrypt.GenerateFromPassword([]byte(name), cost)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to generate a random token: %v\", err)\n\t}\n\treturn base64.StdEncoding.EncodeToString(hash)\n}", "func GenerateSecretKey() string {\n\tvar buf [32]byte\n\trand.Read(buf[:])\n\treturn base64.RawURLEncoding.EncodeToString(buf[:])\n}", "func newID() string {\n\tvar b [8]byte\n\t_, err := rand.Read(b[:])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn fmt.Sprintf(\"%x\", b[:])\n}", "func generate(length int) (string, error) {\n\trb := make([]byte, length)\n\n\t_, err := rand.Read(rb)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn base64.RawURLEncoding.EncodeToString(rb), nil\n}", "func randUInt64() uint64 {\n\tbits := rand.Uint32() % 64\n\tif bits == 0 {\n\t\treturn 0\n\t}\n\tn := uint64(1 << (bits - 1))\n\tn += uint64(rand.Int63()) & ((1 << (bits - 1)) - 1)\n\treturn n\n}", "func keygen() (string, string) {\n priv, _ := config.GenerateRandomBytes(32)\n addr := config.PrivateToAddress(priv)\n return \"0x\"+addr, fmt.Sprintf(\"%x\", priv)\n}", "func GenerateToken() (string, int64, error) {\n\tnow := time.Now()\n\tnow = now.UTC()\n\n\texpiration := now.Add(TokenLifespan).Unix()\n\tclaims := &jwt.StandardClaims{\n\t\tIssuer: \"auth.evanmoncuso.com\",\n\t\tAudience: \"*\",\n\t\tExpiresAt: expiration,\n\t\tIssuedAt: now.Unix(),\n\t}\n\n\ttoken := jwt.NewWithClaims(SigningMethod, claims)\n\ttokenString, err := token.SignedString(TokenSecret)\n\n\treturn tokenString, expiration, err\n}", "func TestRandomUint64(t *testing.T) {\n\ttries := 1 << 8 // 2^8\n\twatermark := uint64(1 << 56) // 2^56\n\tmaxHits := 5\n\tbadRNG := \"The random number generator on this system is clearly \" +\n\t\t\"terrible since we got %d values less than %d in %d runs \" +\n\t\t\"when only %d was expected\"\n\n\tnumHits := 0\n\tfor i := 0; i < tries; i++ {\n\t\tnonce, err := RandomUint64()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"RandomUint64 iteration %d failed - err %v\",\n\t\t\t\ti, err)\n\t\t\treturn\n\t\t}\n\t\tif nonce < watermark {\n\t\t\tnumHits++\n\t\t}\n\t\tif numHits > maxHits {\n\t\t\tstr := fmt.Sprintf(badRNG, numHits, watermark, tries, maxHits)\n\t\t\tt.Errorf(\"Random Uint64 iteration %d failed - %v %v\", i,\n\t\t\t\tstr, numHits)\n\t\t\treturn\n\t\t}\n\t}\n}", "func newRandomID(n int) string {\n\trand.Seed(UTCNow().UnixNano())\n\tsid := make([]rune, n)\n\tfor i := range sid {\n\t\tsid[i] = letters[rand.Intn(len(letters))]\n\t}\n\treturn string(sid)\n}", "func Gen(pwd string) string {\n\tsalt := strconv.FormatInt(time.Now().UnixNano()%9000+1000, 10)\n\treturn Base64Encode(Sha256(Md5(pwd)+salt) + salt)\n}", "func GenerateToken(secret []byte, aud, sub string) (string, error) {\n\n\ttok := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.RegisteredClaims{\n\t\tIssuer: TokenIssuer,\n\t\tAudience: []string{aud},\n\t\tSubject: sub,\n\t\tIssuedAt: jwt.NewNumericDate(time.Now()),\n\t\tNotBefore: jwt.NewNumericDate(time.Now().Add(-15 * time.Minute)),\n\t})\n\n\treturn tok.SignedString(secret)\n}", "func (s *session) newID() (interface{}, error) {\n\tvar b [32]byte\n\t_, err := rand.Read(b[:])\n\treturn hex.EncodeToString(b[:]), err\n}", "func newRandomID(n int) string {\n\trand.Seed(time.Now().UTC().UnixNano())\n\tsid := make([]rune, n)\n\tfor i := range sid {\n\t\tsid[i] = letters[rand.Intn(len(letters))]\n\t}\n\treturn string(sid)\n}", "func (e Aes128CtsHmacSha256128) RandomToKey(b []byte) []byte {\n\treturn rfc8009.RandomToKey(b)\n}", "func (c *HMACStrategy) Generate() (string, string, error) {\n\tif len(c.GlobalSecret) < minimumSecretLength/2 {\n\t\treturn \"\", \"\", errors.New(\"Secret is not strong enough\")\n\t}\n\n\tif c.AuthCodeEntropy < minimumEntropy {\n\t\tc.AuthCodeEntropy = minimumEntropy\n\t}\n\n\t// When creating secrets not intended for usage by human users (e.g.,\n\t// client secrets or token handles), the authorization server should\n\t// include a reasonable level of entropy in order to mitigate the risk\n\t// of guessing attacks. The token value should be >=128 bits long and\n\t// constructed from a cryptographically strong random or pseudo-random\n\t// number sequence (see [RFC4086] for best current practice) generated\n\t// by the authorization server.\n\tkey, err := RandomBytes(c.AuthCodeEntropy)\n\tif err != nil {\n\t\treturn \"\", \"\", errors.WithStack(err)\n\t}\n\n\tif len(key) < c.AuthCodeEntropy {\n\t\treturn \"\", \"\", errors.New(\"Could not read enough random data for key generation\")\n\t}\n\n\tuseSecret := append([]byte{}, c.GlobalSecret...)\n\tmac := hmac.New(sha256.New, useSecret)\n\t_, err = mac.Write(key)\n\tif err != nil {\n\t\treturn \"\", \"\", errors.WithStack(err)\n\t}\n\n\tsignature := mac.Sum([]byte{})\n\tencodedSignature := b64.EncodeToString(signature)\n\tencodedToken := fmt.Sprintf(\"%s.%s\", b64.EncodeToString(key), encodedSignature)\n\treturn encodedToken, encodedSignature, nil\n}", "func generatePassword() string {\n\tletters := []byte(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n\tb := make([]byte, randomPasswordLength)\n\tfor i := range b {\n\t\tb[i] = letters[rand.Int63()%int64(len(letters))]\n\t}\n\treturn string(b)\n}", "func generateAuthCode(key []byte, t uint64) string {\n\tt /= 30 // converting time for any reason\n\ttb := make([]byte, 8) // 00 00 00 00 00 00 00 00\n\tbinary.BigEndian.PutUint64(tb, t) // 00 00 00 00 xx xx xx xx\n\n\t// evaluate hash code for `tb` by key\n\tmac := hmac.New(sha1.New, key)\n\tmac.Write(tb)\n\thashcode := mac.Sum(nil)\n\n\t// last 4 bits provide initial position\n\t// len(hashcode) = 20 bytes\n\tstart := hashcode[19] & 0xf\n\n\t// extract 4 bytes at `start` and drop first bit\n\tfc32 := binary.BigEndian.Uint32(hashcode[start : start+4])\n\tfc32 &= 1<<31 - 1\n\tfullcode := int(fc32)\n\n\t// generate auth code\n\tcode := make([]byte, 5)\n\tfor i := range code {\n\t\tcode[i] = codeChars[fullcode%codeCharsLen]\n\t\tfullcode /= codeCharsLen\n\t}\n\n\treturn string(code[:])\n}", "func Token() string {\n\tb := make([]byte, 20)\n\trand.Read(b)\n\treturn fmt.Sprintf(\"%x\", b)\n}", "func GenToken() (token string, err error) {\n\ttoken, err = getRandString(tokenBytes)\n\treturn\n}", "func Token() (string, error) {\n\treturn generate(32)\n}" ]
[ "0.71865994", "0.6750421", "0.67401165", "0.67401165", "0.66797066", "0.66131717", "0.65611285", "0.65567636", "0.65222335", "0.650689", "0.64505213", "0.641281", "0.63893825", "0.6360658", "0.63373137", "0.6330806", "0.63270384", "0.6306842", "0.6298314", "0.6294659", "0.62931234", "0.627302", "0.62552255", "0.6232675", "0.62269765", "0.62129545", "0.61645174", "0.61645174", "0.61645174", "0.6143017", "0.6129044", "0.6123358", "0.6036966", "0.6021254", "0.5975159", "0.59738797", "0.5961827", "0.5955564", "0.5953521", "0.5938051", "0.59298015", "0.58964837", "0.58886236", "0.5878417", "0.58740455", "0.58712065", "0.5851269", "0.58377695", "0.5823216", "0.58204854", "0.5779771", "0.5775645", "0.57682335", "0.57551306", "0.57427084", "0.57349443", "0.573282", "0.57313865", "0.572388", "0.5723489", "0.5718405", "0.56976444", "0.5667891", "0.56530255", "0.5646626", "0.5608532", "0.5607635", "0.5579303", "0.5575018", "0.5574222", "0.55709195", "0.5563654", "0.5563437", "0.5552228", "0.5539007", "0.5533248", "0.55284256", "0.55223185", "0.55192804", "0.55019456", "0.5500728", "0.5489733", "0.5483489", "0.5476779", "0.54646635", "0.5462457", "0.5456341", "0.54535276", "0.5449102", "0.5447693", "0.5446138", "0.5445304", "0.5441002", "0.54290587", "0.5418064", "0.54143494", "0.5406921", "0.5403091", "0.539463", "0.53865826" ]
0.6891487
1
NewList instantiates a new list and sets the default values.
func NewList()(*List) { m := &List{ BaseItem: *NewBaseItem(), } odataTypeValue := "#microsoft.graph.list"; m.SetOdataType(&odataTypeValue); return m }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New() *List {\n\t// new returns a pointer to a List with all variables set to 0 value\n\treturn new(List).Init()\n}", "func NewList(vs ...Value) Value {\n\treturn StrictPrepend(vs, EmptyList)\n}", "func NewList() List {\n\treturn make(List, 0)\n}", "func NewList() List {\n\treturn List{}\n}", "func New() *List { return new(List).Init() }", "func newList(vert bool, width, height float32) *List {\n\n\tli := new(List)\n\tli.initialize(vert, width, height)\n\treturn li\n}", "func NewList() List {\n\tl := List{}\n\tl.Set = make(map[string]int)\n\treturn l\n}", "func NewList() *Lista{\n\treturn &Lista{nil, nil, 0}\n}", "func NewList(vs ...Value) List {\n\treturn List{&vs}\n}", "func NewList(list uint32, mode uint32) {\n\tsyscall.Syscall(gpNewList, 2, uintptr(list), uintptr(mode), 0)\n}", "func New() *List {\n\treturn &List{size: 0}\n}", "func NewList(s string) *List {\n\treturn &List{\n\t\t&ListItem{\n\t\t\t0,\n\t\t\tTODO,\n\t\t\ts,\n\t\t\t[]*ListItem{},\n\t\t},\n\t}\n}", "func NewList() *list.List {\n\treturn list.New()\n}", "func NewList() *List {\n newObj := &List {\n counters : make(map[string]Counter),\n }\n\n return newObj\n}", "func newList(data interface{}) *List {\n\tnewL := new(List)\n\tnewL.Insert(data)\n\treturn newL\n}", "func New(vals ...interface{}) *List {\n\thead := list.New()\n\tfor _, v := range vals {\n\t\thead.PushBack(v)\n\t}\n\treturn &List{head}\n}", "func NewList() *List {\n\treturn &List{\n\t\tBox: tview.NewBox(),\n\t\ttextColor: tview.Styles.PrimaryTextColor,\n\t\tcurrentTextColor: tview.Styles.PrimitiveBackgroundColor,\n\t\tcurrentBackgroundColor: tview.Styles.PrimaryTextColor,\n\t}\n}", "func NewList() List {\n\treturn List{items: []string{}}\n}", "func New(values ...interface{}) *List {\n\tlist := &List{}\n\tif len(values) > 0 {\n\t\tlist.Add(values...)\n\t}\n\treturn list\n}", "func New(values ...interface{}) *List {\n\tlist := &List{}\n\tif len(values) > 0 {\n\t\tlist.Add(values)\n\t}\n\treturn list\n}", "func New() *LList {\n\tvar l LList\n\tl.size = 0\n\treturn &l\n}", "func New() *List {\n\treturn &List{}\n}", "func New() *List {\n\treturn &List{}\n}", "func New() *List {\n return &List{size:0}\n}", "func NewList(args ...interface{}) *List {\n\tl := &List{}\n\tfor _, v := range args {\n\t\tl.PushBack(v)\n\t}\n\treturn l\n}", "func NewList(cfg *Configuration) *List {\n\treturn &List{\n\t\tStateMask: ListExecuted,\n\t\tcfg: cfg,\n\t}\n}", "func New() *List {\n\treturn &List{nil, nil, 0, sync.RWMutex{}}\n}", "func NewList() *List {\n\treturn new(List).Init()\n}", "func NewList(val interface{}) *List {\n\treturn &List{\n\t\tval: val,\n\t}\n}", "func NewList(initial []W) UpdatableList {\n\tul := &updatableList{}\n\tul.Update(initial)\n\treturn ul\n}", "func NewList(args ...interface{}) *List {\n\tl := List{}\n\tfor _, data := range args {\n\t\tl.PushBack(data)\n\t}\n\treturn &l\n}", "func NewList(vs ...Value) *List {\n\tacc := EmptyList\n\tfor _, v := range vs {\n\t\tacc = acc.Append(v)\n\t}\n\treturn acc\n}", "func NewList(data Source, name string, index int) *List {\n\treturn &List{Data: data, name: name, copyIndexes: []int{index}}\n}", "func NewList() *List {\n\treturn &List{}\n}", "func NewList() *List {\n\treturn &List{}\n}", "func New() *List {\n\treturn &List{\n\t\tfront: nil,\n\t\tlen: 0,\n\t}\n\n}", "func NewList() *List {\n\tl := List{\n\t\tpostings: make(map[uint64]*Posting),\n\t}\n\treturn &l\n}", "func NewList(v ...Value) List {\n\tr := emptyList\n\tfor i := len(v) - 1; i >= 0; i-- {\n\t\tr = &list{\n\t\t\tfirst: v[i],\n\t\t\trest: r,\n\t\t\tcount: r.count + 1,\n\t\t}\n\t}\n\treturn r\n}", "func NewList(listType string) *List {\n\tl := new(List)\n\tl.Element = NewElement(listType)\n\tl.Items = make(ListItems, 0)\n\treturn l\n}", "func NewList(name string) *List {\n\treturn &List{\n\t\tname: name,\n\t\tentries: make([]interface{}, 0, 1),\n\t}\n}", "func NewList(elems ...interface{}) *List {\n\tl := List{}\n\tfor _, elem := range elems {\n\t\tl.PushBack(elem)\n\t}\n\n\treturn &l\n}", "func New(maxlevel int, cmpFn CompareFn) *List {\n\treturn NewCustom(maxlevel, DefaultProbability, cmpFn, time.Now().Unix())\n}", "func newList() *List {\n\tl := &List{\n\t\tch: make(chan sh.QData),\n\t}\n\treturn l\n}", "func NewList(first Term, rest ...Term) NonEmptyList {\n\treturn append(NonEmptyList{first}, rest...)\n}", "func NewList(length int) *PyList {\n\tptr := C.PyList_New(C.long(length))\n\tif ptr != nil {\n\t\treturn &PyList{PyObject{ptr}}\n\t}\n\n\treturn nil\n}", "func NewList(e Type, i *debug.Information) List {\n\treturn List{e, i}\n}", "func NewList(val []byte, ttl int) List {\n\tvar it item\n\tit.SetTTL(ttl)\n\tll := list.New()\n\tll.PushFront(val)\n\n\treturn List{it, ll}\n}", "func NewList(list uint32, mode uint32) {\n\tC.glowNewList(gpNewList, (C.GLuint)(list), (C.GLenum)(mode))\n}", "func NewList() *list {\n\treturn &list{\n\t\thead: &node{next: nil, prev: nil},\n\t\ttail: &node{next: nil, prev: nil},\n\t}\n}", "func NewList(elements ...interface{}) *List {\n\tl := &List{}\n\n\tfor _, el := range elements {\n\t\tl.PushBack(el)\n\t}\n\n\treturn l\n}", "func NewList(client *secretsapi.Client, p listPrimeable) *List {\n\treturn &List{\n\t\tsecretsClient: client,\n\t\tout: p.Output(),\n\t\tproj: p.Project(),\n\t}\n}", "func (e *exprHelper) NewList(elems ...ast.Expr) ast.Expr {\n\treturn e.exprFactory.NewList(e.nextMacroID(), elems, []int32{})\n}", "func NewListValue() *ListValue {\n\treturn &ListValue{\n\t\tEntries: []*DynValue{},\n\t}\n}", "func NewList(g ...Getter) *List {\n\tlist := &List{\n\t\tlist: g,\n\t}\n\tlist.GetProxy = NewGetProxy(list) // self\n\treturn list\n}", "func NewListForTesting(name string, entries []interface{}) *List {\n\treturn &List{\n\t\tname: name,\n\t\tentries: entries,\n\t}\n}", "func NewList(valType Type, vals ...Item) *List {\n\treturn &List{\n\t\tvalue: vals,\n\t\tvalType: valType,\n\t}\n}", "func NewList(capacity int) *List {\n\tif capacity < 0 {\n\t\tpanic(\"negative capacity\")\n\t}\n\n\tpids := make([]ID, capacity)\n\tfor i := 0; i < capacity; i++ {\n\t\tpids[i] = ID(i)\n\t}\n\n\treturn &List{\n\t\tentities: make([]*Entity, capacity+1), // + 1 due to the 'highest' variable\n\n\t\tlowest: -1,\n\t\thighest: -1,\n\n\t\tavailableIDs: pids,\n\t}\n}", "func New() *TList {\n\treturn &TList{list: list.New(), mux: &sync.RWMutex{}}\n}", "func New(size int) *List {\n\treturn &List{data: make([]string, size)}\n}", "func New(name string, options []string) *List {\n\tlist := &List{}\n\n\tlist.name = name\n\tlist.options = options\n\tlist.Index = 0\n\n\tlist.Cursor = &curse.Cursor{}\n\n\tlist.SetColors(DefaultColors)\n\tlist.SetPrint(fmt.Print)\n\tlist.SetChooser(\" ❯ \")\n\tlist.SetIndent(3)\n\n\treturn list\n}", "func MustNewList(typeDef ListTypeDefinition) List {\n\tl, err := NewList(typeDef)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn l\n}", "func NewList(parent sparta.Widget, name string, rect image.Rectangle) *List {\n\tl := &List{\n\t\tname: name,\n\t\tparent: parent,\n\t\tgeometry: rect,\n\t\tback: backColor,\n\t\tfore: foreColor,\n\t\ttarget: parent,\n\t}\n\tsparta.NewWindow(l)\n\tl.scroll = NewScroll(l, \"list\"+name+\"Scroll\", 0, 0, Vertical, image.Rect(rect.Dx()-10, 0, rect.Dx(), rect.Dy()))\n\treturn l\n}", "func NewList(storage storageInterface) *List {\n\treturn &List{storage: storage}\n}", "func NewList(list uint32, mode uint32) {\n C.glowNewList(gpNewList, (C.GLuint)(list), (C.GLenum)(mode))\n}", "func NewList(compare Compare) *SkipList {\n\thead := &Node{\n\t\tnext: make([]*Node, maxLevel),\n\t}\n\treturn &SkipList{\n\t\tlen: 0,\n\t\tlevel: 0,\n\t\tcompare: compare,\n\t\theader: head,\n\t}\n}", "func NewList(name string, heuristics int) *LinkedList {\n\treturn &LinkedList{\n\t\tname: name,\n\t\theuristics: heuristics, // distance from node to target/goal.\n\t}\n}", "func MustNewListOf(elementTypeDef TypeDefinition) List {\n\treturn MustNewList(ListOf(elementTypeDef))\n}", "func NewList(values []interface{}) *List {\n\tvar items []Item\n\tlist := List{Len: len(values)}\n\tfor i := 0; i < list.Len; i++ {\n\t\titem := Item{Value: values[i]}\n\t\tif i > 0 {\n\t\t\t// i - 1 should reference to previous el before append\n\t\t\titem.Prev = &items[i-1]\n\t\t\titems[i-1].Next = &item\n\t\t}\n\t\titems = append(items, item)\n\t}\n\tif len(items) == 0 {\n\t\treturn &list\n\t}\n\tlist.First = &items[0]\n\tlist.Last = &items[len(items)-1]\n\treturn &list\n}", "func newList(rowType reflect.Type) []*Info {\n\tvar list columnList\n\tvar state = stateT{}\n\tlist.addFields(rowType, state)\n\treturn list\n}", "func NewListValue(list []interface{}) ListValue {\n\treturn ListValue(list)\n}", "func NewList(kubeClient kubernetes.Interface, appConfig config.Config, items ...v1.Ingress) *List {\n\treturn &List{\n\t\tkubeClient: kubeClient,\n\t\tappConfig: appConfig,\n\t\titems: items,\n\t}\n}", "func NewList(typeDef ListTypeDefinition) (List, error) {\n\tt, err := newTypeImpl(&listTypeCreator{\n\t\ttypeDef: typeDef,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn t.(List), nil\n}", "func newListFormulaArg(l []formulaArg) formulaArg {\n\treturn formulaArg{Type: ArgList, List: l}\n}", "func NewConfList(path string, defaultList []string) *ConfList {\n\tr := &ConfList{\n\t\tpath: path,\n\t}\n\tr.update()\n\tif len(r.data) == 0 {\n\t\tr.data = defaultList\n\t}\n\treturn r\n}", "func NewCustom_List(s *capnp.Segment, sz int32) (Custom_List, error) {\n\tl, err := capnp.NewCompositeList(s, capnp.ObjectSize{DataSize: 24, PointerCount: 1}, sz)\n\treturn Custom_List{l}, err\n}", "func NewListSized(n int) *List {\n\tl := &List{}\n\tif n != 0 {\n\t\tl.Items = make([]Object, n)\n\t}\n\treturn l\n}", "func New() *ListBuffer {\n\tbuf := new(ListBuffer)\n\tbuf.Init()\n\treturn buf\n}", "func New(less LessFunc) *List {\n\treturn &List{\n\t\tless: less,\n\t\tzero: El{h: MaxHeight, more: make([]*El, MaxHeight-FixedHeight)},\n\t\tup: make([]**El, MaxHeight),\n\t\tautoreuse: true,\n\t}\n}", "func InitList() *List {\n\t// Init the head node\n\theadNode := &Node{\n\t\tKey: \"\",\n\t\tValue: \"\",\n\t\tTTL: -1,\n\t\tCreatedAt: time.Now().Unix(),\n\t\tPrev: nil,\n\t\tNext: nil,\n\t}\n\n\t// Init the tail node\n\ttailNode := &Node{\n\t\tKey: \"\",\n\t\tValue: \"\",\n\t\tTTL: -1,\n\t\tCreatedAt: time.Now().Unix(),\n\t\tPrev: nil,\n\t\tNext: nil,\n\t}\n\n\t// Init the doubly-linked list\n\tlist := &List{\n\t\tHead: headNode,\n\t\tTail: tailNode,\n\t\tSize: int32(0),\n\t}\n\n\t// Set correct pointers for head and tail nodes.1\n\tlist.Head.Next = list.Tail\n\tlist.Tail.Prev = list.Head\n\n\treturn list\n}", "func New(stk *stack.Stack) *VList {\n\tr := new(VList)\n\tr.value = *stk\n\treturn r\n}", "func New(isupport *isupport.ISupport) *List {\n\treturn &List{\n\t\tisupport: isupport,\n\t\tusers: make([]*User, 0, 64),\n\t\tindex: make(map[string]*User, 64),\n\t\tautosort: true,\n\t}\n}", "func NewListOf(elementTypeDef TypeDefinition) (List, error) {\n\treturn NewList(ListOf(elementTypeDef))\n}", "func newListMetrics() *listMetrics {\n\treturn new(listMetrics)\n}", "func NewList(slice []Unit) List {\n\treturn unitlist{slice}\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 NewExampleList(data []Example, count int32) *ExampleList {\n\treturn &ExampleList{\n\t\tData: data,\n\t\tCount: count,\n\t}\n}", "func NewListWithCapacity(n int) *List {\n\tl := &List{}\n\tif n != 0 {\n\t\tl.Items = make([]Object, 0, n)\n\t}\n\treturn l\n}", "func NewIntList() *IntList {\n // -111 for no good reason. FIXME(david)?\n f := newIntListNode(nil, nil, -111)\n l := newIntListNode(f, nil, -111)\n f.next = l\n return &IntList{ first: f,\n last: l,\n }\n}", "func newObjectList() *ObjectList {\n\treturn &ObjectList{\n\t\tObjectIDs: make([]int, 0, 200),\n\t}\n}", "func New(elems ...interface{}) List {\n\tl := Mzero()\n\tfor _, elem := range elems {\n\t\tl = Cons(elem, l)\n\t}\n\treturn Reverse(l)\n}", "func NewFromList(list []types.VType) *VList {\n\tr := new(VList)\n\tr.value = list\n\treturn r\n}", "func newIDList(p *idElementPool) *idList {\n\tl := &idList{Pool: p}\n\treturn l.Init()\n}", "func NewListOptions(opts ...ListOption) ListOptions {\n\toptions := ListOptions{\n\t\tDomain: DefaultDomain,\n\t\tContext: context.Background(),\n\t}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\treturn options\n}", "func NewListValue(list []interface{}) *ListValue {\n\tres := &ListValue{\n\t\tlist: list,\n\t}\n\n\tres.bytes, _ = packAnyArray(list)\n\n\treturn res\n}", "func NewListImpl(g *GlobalImpl, b *ListOptions) *ListImpl {\n\treturn &ListImpl{\n\t\tGlobalImpl: g,\n\t\tListOptions: b,\n\t}\n}", "func newList(ctx TransactionContextInterface) *list {\n\t stateList := new(ledgerapi.StateList)\n\t stateList.Ctx = ctx\n\t stateList.Class = \"Asset\"\n\t stateList.Deserialize = func(bytes []byte, state ledgerapi.StateInterface) error {\n\t\t return Deserialize(bytes, state.(*Asset))\n\t }\n \n\t list := new(list)\n\t list.stateList = stateList\n \n\t return list\n }", "func newToDoList() toDoList {\n\treturn toDoList{}\n}", "func MakeList(fields []Field) List {\n\t// TODO: optimize to reduce allocations.\n\tvar list List\n\tfor _, f := range fields {\n\t\tlist = list.Set(f)\n\t}\n\treturn list\n}", "func (l *List) Init() {\r\n\tl.list = list.New()\r\n}", "func InitializeList(uninitializedList *List, itemSize uint64) {\n uninitializedList.itemSize = itemSize;\n uninitializedList.capacity = 16; //Allocate 16 items by default\n uninitializedList.baseAddress = Alloc(uninitializedList.capacity * uninitializedList.itemSize);\n uninitializedList.itemCount = 0; //Reset item count (to zero)\n}" ]
[ "0.79136246", "0.78035533", "0.77620363", "0.775962", "0.7705582", "0.7686803", "0.7679327", "0.75430304", "0.75349677", "0.7452575", "0.7435865", "0.7435628", "0.7392671", "0.7382111", "0.737879", "0.73784304", "0.736477", "0.7362613", "0.73597026", "0.73436475", "0.7342709", "0.7314093", "0.7314093", "0.7312446", "0.7300071", "0.7295601", "0.7271859", "0.72592014", "0.7257601", "0.72486335", "0.72463906", "0.72175413", "0.7164117", "0.7160281", "0.7160281", "0.71486163", "0.71209615", "0.7115307", "0.70867133", "0.70845115", "0.7068175", "0.7065826", "0.70412385", "0.70391726", "0.7019575", "0.7017439", "0.6958979", "0.695527", "0.69472784", "0.6914234", "0.6913073", "0.6911801", "0.69080365", "0.68785053", "0.6869326", "0.68601394", "0.6851454", "0.6826033", "0.6820674", "0.6807149", "0.6801817", "0.6800693", "0.6774334", "0.6718849", "0.6685606", "0.6675114", "0.6667218", "0.6659143", "0.660426", "0.6603524", "0.653775", "0.6526871", "0.6520907", "0.6446393", "0.6426162", "0.6414647", "0.63987595", "0.63794696", "0.63610834", "0.6351107", "0.63484496", "0.6347074", "0.6344709", "0.6337791", "0.63249475", "0.63244706", "0.63150686", "0.6298819", "0.6295676", "0.6279929", "0.6271416", "0.6236191", "0.62255627", "0.62184614", "0.6204457", "0.61727273", "0.61528337", "0.61407435", "0.61286265", "0.61257696" ]
0.72837466
26
CreateListFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateListFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) { return NewList(), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateBrowserSiteListFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewBrowserSiteList(), nil\n}", "func CreateSharepointIdsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSharepointIds(), nil\n}", "func CreateVulnerabilityFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewVulnerability(), nil\n}", "func CreateDetectionRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDetectionRule(), nil\n}", "func CreateDeviceCategoryFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceCategory(), nil\n}", "func CreateIosDeviceFeaturesConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewIosDeviceFeaturesConfiguration(), nil\n}", "func CreateCloudCommunicationsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCloudCommunications(), nil\n}", "func CreateSiteCollectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSiteCollection(), nil\n}", "func CreateWin32LobAppRegistryRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppRegistryRule(), nil\n}", "func CreateSetFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSet(), nil\n}", "func CreateWin32LobAppRegistryDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppRegistryDetection(), nil\n}", "func CreateDeviceCompliancePolicyPolicySetItemFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceCompliancePolicyPolicySetItem(), nil\n}", "func CreateSchemaFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSchema(), nil\n}", "func CreatePlannerFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewPlanner(), nil\n}", "func CreateRoleDefinitionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.deviceAndAppManagementRoleDefinition\":\n return NewDeviceAndAppManagementRoleDefinition(), nil\n }\n }\n }\n }\n return NewRoleDefinition(), nil\n}", "func CreateDriveFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDrive(), nil\n}", "func CreateDirectoryFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDirectory(), nil\n}", "func CreateGroupFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewGroup(), nil\n}", "func CreatePolicyRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.networkaccess.forwardingRule\":\n return NewForwardingRule(), nil\n case \"#microsoft.graph.networkaccess.m365ForwardingRule\":\n return NewM365ForwardingRule(), nil\n case \"#microsoft.graph.networkaccess.privateAccessForwardingRule\":\n return NewPrivateAccessForwardingRule(), nil\n }\n }\n }\n }\n return NewPolicyRule(), nil\n}", "func CreateItemFacetFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.educationalActivity\":\n return NewEducationalActivity(), nil\n case \"#microsoft.graph.itemAddress\":\n return NewItemAddress(), nil\n case \"#microsoft.graph.itemEmail\":\n return NewItemEmail(), nil\n case \"#microsoft.graph.itemPatent\":\n return NewItemPatent(), nil\n case \"#microsoft.graph.itemPhone\":\n return NewItemPhone(), nil\n case \"#microsoft.graph.itemPublication\":\n return NewItemPublication(), nil\n case \"#microsoft.graph.languageProficiency\":\n return NewLanguageProficiency(), nil\n case \"#microsoft.graph.personAnnotation\":\n return NewPersonAnnotation(), nil\n case \"#microsoft.graph.personAnnualEvent\":\n return NewPersonAnnualEvent(), nil\n case \"#microsoft.graph.personAward\":\n return NewPersonAward(), nil\n case \"#microsoft.graph.personCertification\":\n return NewPersonCertification(), nil\n case \"#microsoft.graph.personInterest\":\n return NewPersonInterest(), nil\n case \"#microsoft.graph.personName\":\n return NewPersonName(), nil\n case \"#microsoft.graph.personResponsibility\":\n return NewPersonResponsibility(), nil\n case \"#microsoft.graph.personWebsite\":\n return NewPersonWebsite(), nil\n case \"#microsoft.graph.projectParticipation\":\n return NewProjectParticipation(), nil\n case \"#microsoft.graph.skillProficiency\":\n return NewSkillProficiency(), nil\n case \"#microsoft.graph.userAccountInformation\":\n return NewUserAccountInformation(), nil\n case \"#microsoft.graph.webAccount\":\n return NewWebAccount(), nil\n case \"#microsoft.graph.workPosition\":\n return NewWorkPosition(), nil\n }\n }\n }\n }\n return NewItemFacet(), nil\n}", "func CreateIosDeviceTypeFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewIosDeviceType(), nil\n}", "func CreateScheduleItemFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewScheduleItem(), nil\n}", "func CreateSearchAlterationOptionsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSearchAlterationOptions(), nil\n}", "func CreateWindowsInformationProtectionDeviceRegistrationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsInformationProtectionDeviceRegistration(), nil\n}", "func CreateVppTokenFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewVppToken(), nil\n}", "func CreateRegistryKeyStateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewRegistryKeyState(), nil\n}", "func CreateConditionalAccessDeviceStatesFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewConditionalAccessDeviceStates(), nil\n}", "func CreateBusinessScenarioPlannerFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewBusinessScenarioPlanner(), nil\n}", "func CreateDomainSecurityProfileCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDomainSecurityProfileCollectionResponse(), nil\n}", "func CreateDeviceManagementIntentDeviceStateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementIntentDeviceState(), nil\n}", "func CreateMessageRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMessageRule(), nil\n}", "func CreateHeadersFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewHeaders(), nil\n}", "func CreateApplicationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewApplication(), nil\n}", "func CreateDomainCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDomainCollectionResponse(), nil\n}", "func CreateAndroidCustomConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAndroidCustomConfiguration(), nil\n}", "func CreateDeviceManagementSettingsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementSettings(), nil\n}", "func CreateDeviceManagementConfigurationPolicyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementConfigurationPolicy(), nil\n}", "func CreateSettingFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSetting(), nil\n}", "func CreateGroupPolicyDefinitionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewGroupPolicyDefinition(), nil\n}", "func CreateSchemaExtensionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSchemaExtension(), nil\n}", "func CreateTemplateParameterFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewTemplateParameter(), nil\n}", "func CreateRecurrenceRangeFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewRecurrenceRange(), nil\n}", "func CreateVpnConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.androidDeviceOwnerVpnConfiguration\":\n return NewAndroidDeviceOwnerVpnConfiguration(), nil\n }\n }\n }\n }\n return NewVpnConfiguration(), nil\n}", "func CreatePrinterCreateOperationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewPrinterCreateOperation(), nil\n}", "func CreatePrinterCreateOperationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewPrinterCreateOperation(), nil\n}", "func CreateDeviceManagementSettingDependencyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementSettingDependency(), nil\n}", "func CreatePrinterDefaultsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewPrinterDefaults(), nil\n}", "func CreateDeviceAndAppManagementAssignmentFilterFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.payloadCompatibleAssignmentFilter\":\n return NewPayloadCompatibleAssignmentFilter(), nil\n }\n }\n }\n }\n return NewDeviceAndAppManagementAssignmentFilter(), nil\n}", "func CreateDeviceCompliancePolicyCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceCompliancePolicyCollectionResponse(), nil\n}", "func CreateTeamworkActivePeripheralsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewTeamworkActivePeripherals(), nil\n}", "func CreateConnectedOrganizationMembersFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewConnectedOrganizationMembers(), nil\n}", "func CreateTargetManagerFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewTargetManager(), nil\n}", "func CreateWebPartDataFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWebPartData(), nil\n}", "func CreateMeetingParticipantsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMeetingParticipants(), nil\n}", "func CreateProtectGroupFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewProtectGroup(), nil\n}", "func CreateDiscoveredSensitiveTypeFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDiscoveredSensitiveType(), nil\n}", "func CreateManagementTemplateStepFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewManagementTemplateStep(), nil\n}", "func CreateRecurrencePatternFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewRecurrencePattern(), nil\n}", "func CreateWin32LobAppFileSystemDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppFileSystemDetection(), nil\n}", "func CreateAndroidLobAppFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAndroidLobApp(), nil\n}", "func CreateMediaFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMedia(), nil\n}", "func CreateUserFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewUser(), nil\n}", "func CreateOnPremisesExtensionAttributesFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewOnPremisesExtensionAttributes(), nil\n}", "func CreateCommunicationsIdentitySetFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCommunicationsIdentitySet(), nil\n}", "func CreateWorkforceIntegrationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWorkforceIntegration(), nil\n}", "func CreateWorkbookFilterFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWorkbookFilter(), nil\n}", "func CreateWin32LobAppProductCodeDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppProductCodeDetection(), nil\n}", "func CreateReportsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewReports(), nil\n}", "func CreateSearchBucketFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSearchBucket(), nil\n}", "func CreateSmsLogRowFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSmsLogRow(), nil\n}", "func CreateSubCategoryTemplateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSubCategoryTemplate(), nil\n}", "func CreateFederatedTokenValidationPolicyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewFederatedTokenValidationPolicy(), nil\n}", "func CreateBookingBusinessFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewBookingBusiness(), nil\n}", "func CreateDeviceManagementConfigurationSettingGroupDefinitionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.deviceManagementConfigurationSettingGroupCollectionDefinition\":\n return NewDeviceManagementConfigurationSettingGroupCollectionDefinition(), nil\n }\n }\n }\n }\n return NewDeviceManagementConfigurationSettingGroupDefinition(), nil\n}", "func CreateUserExperienceAnalyticsDeviceStartupHistoryFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewUserExperienceAnalyticsDeviceStartupHistory(), nil\n}", "func CreateOpenTypeExtensionCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewOpenTypeExtensionCollectionResponse(), nil\n}", "func CreateAuthenticationCombinationConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.fido2CombinationConfiguration\":\n return NewFido2CombinationConfiguration(), nil\n }\n }\n }\n }\n return NewAuthenticationCombinationConfiguration(), nil\n}", "func CreateCatalogContentFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCatalogContent(), nil\n}", "func CreateAttachmentItemFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAttachmentItem(), nil\n}", "func CreateMalwareFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMalware(), nil\n}", "func CreateReminderFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewReminder(), nil\n}", "func CreateUpdateAllowedCombinationsResultFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewUpdateAllowedCombinationsResult(), nil\n}", "func CreateDirectorySettingFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDirectorySetting(), nil\n}", "func CreateKeyValueFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewKeyValue(), nil\n}", "func CreateManagedDeviceComplianceCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewManagedDeviceComplianceCollectionResponse(), nil\n}", "func CreateRelatedContactFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewRelatedContact(), nil\n}", "func CreateDeviceManagementConfigurationSettingDefinitionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.deviceManagementConfigurationChoiceSettingCollectionDefinition\":\n return NewDeviceManagementConfigurationChoiceSettingCollectionDefinition(), nil\n case \"#microsoft.graph.deviceManagementConfigurationChoiceSettingDefinition\":\n return NewDeviceManagementConfigurationChoiceSettingDefinition(), nil\n case \"#microsoft.graph.deviceManagementConfigurationRedirectSettingDefinition\":\n return NewDeviceManagementConfigurationRedirectSettingDefinition(), nil\n case \"#microsoft.graph.deviceManagementConfigurationSettingGroupCollectionDefinition\":\n return NewDeviceManagementConfigurationSettingGroupCollectionDefinition(), nil\n case \"#microsoft.graph.deviceManagementConfigurationSettingGroupDefinition\":\n return NewDeviceManagementConfigurationSettingGroupDefinition(), nil\n case \"#microsoft.graph.deviceManagementConfigurationSimpleSettingCollectionDefinition\":\n return NewDeviceManagementConfigurationSimpleSettingCollectionDefinition(), nil\n case \"#microsoft.graph.deviceManagementConfigurationSimpleSettingDefinition\":\n return NewDeviceManagementConfigurationSimpleSettingDefinition(), nil\n }\n }\n }\n }\n return NewDeviceManagementConfigurationSettingDefinition(), nil\n}", "func CreateIosCustomConfigurationCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewIosCustomConfigurationCollectionResponse(), nil\n}", "func CreateCommsNotificationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCommsNotification(), nil\n}", "func CreateGovernancePolicyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewGovernancePolicy(), nil\n}", "func CreateCreatePostRequestBodyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCreatePostRequestBody(), nil\n}", "func CreateCalendarGroupFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCalendarGroup(), nil\n}", "func CreateFileDataConnectorFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.industryData.azureDataLakeConnector\":\n return NewAzureDataLakeConnector(), nil\n }\n }\n }\n }\n return NewFileDataConnector(), nil\n}", "func CreateMessageSecurityStateCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMessageSecurityStateCollectionResponse(), nil\n}", "func CreateEntitlementManagementSettingsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewEntitlementManagementSettings(), nil\n}", "func CreateConnectorStatusDetailsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewConnectorStatusDetails(), nil\n}", "func CreateAttributeSetFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAttributeSet(), nil\n}", "func CreateDeviceManagementConfigurationSettingFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementConfigurationSetting(), nil\n}", "func CreateDeviceComplianceScriptDeviceStateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceComplianceScriptDeviceState(), nil\n}", "func CreateBusinessFlowCollectionResponseFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewBusinessFlowCollectionResponse(), nil\n}" ]
[ "0.7130501", "0.65420735", "0.6469803", "0.63655806", "0.62998223", "0.62049437", "0.61957437", "0.61202574", "0.61152625", "0.6078244", "0.6048618", "0.60275096", "0.601459", "0.59926915", "0.596089", "0.59600526", "0.5952939", "0.59473586", "0.59227026", "0.59070474", "0.58590144", "0.5850004", "0.5829843", "0.5820803", "0.5817381", "0.5793375", "0.5789015", "0.57866937", "0.57807994", "0.575407", "0.5753894", "0.57476324", "0.57454354", "0.5743987", "0.57437134", "0.5741936", "0.5731635", "0.5717699", "0.571719", "0.5714152", "0.5693347", "0.56809604", "0.56743646", "0.56736016", "0.56736016", "0.5669824", "0.56679684", "0.5666755", "0.56599194", "0.56526804", "0.5643918", "0.5643824", "0.56372964", "0.5636759", "0.56349", "0.56322676", "0.56302387", "0.56196856", "0.5613785", "0.56066513", "0.56049615", "0.5604105", "0.5590915", "0.5588215", "0.5581597", "0.5580076", "0.5575741", "0.5574731", "0.5573298", "0.55705905", "0.55693966", "0.5568692", "0.5564955", "0.55610335", "0.5555037", "0.5549514", "0.55431557", "0.5540566", "0.5531157", "0.55211085", "0.5519989", "0.55188525", "0.5514902", "0.5511952", "0.55002797", "0.54991436", "0.5494518", "0.5491884", "0.5488574", "0.5486759", "0.5486097", "0.54837155", "0.54818016", "0.54793787", "0.5476269", "0.54755056", "0.54741645", "0.54715306", "0.5460713", "0.5459562" ]
0.85900795
0
GetColumns gets the columns property value. The collection of field definitions for this list.
func (m *List) GetColumns()([]ColumnDefinitionable) { return m.columns }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Model) GetColumns() []Column {\n\treturn m.Columns\n}", "func (fmd *FakeMysqlDaemon) GetColumns(ctx context.Context, dbName, table string) ([]*querypb.Field, []string, error) {\n\treturn []*querypb.Field{}, []string{}, nil\n}", "func (c *Client) GetColumns(sheetID string) (cols []Column, err error) {\n\tpath := fmt.Sprintf(\"sheets/%v/columns\", sheetID)\n\n\tbody, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer body.Close()\n\n\tvar resp PaginatedResponse\n\t//TODO: need generic handling and ability to read from pages to get all datc... eventually\n\tdec := json.NewDecoder(body)\n\tif err = dec.Decode(&resp); err != nil {\n\t\tlog.Fatalf(\"Failed to decode: %v\\n\", err)\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(resp.Data, &cols); err != nil {\n\t\tlog.Fatalf(\"Failed to decode data: %v\\n\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func (o *TelemetryDruidScanRequestAllOf) GetColumns() []string {\n\tif o == nil || o.Columns == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn o.Columns\n}", "func (qi *QueryIterator) GetColumns() ([]string, error) {\n\tif qi.schema == nil {\n\t\treturn nil, errors.New(\"Failed to get table schema\")\n\t}\n\tvar result = make([]string, 0)\n\tfor _, field := range qi.schema.Fields {\n\t\tresult = append(result, field.Name)\n\t}\n\treturn result, nil\n}", "func (d *dbBase) GetColumns(ctx context.Context, db dbQuerier, table string) (map[string][3]string, error) {\n\tcolumns := make(map[string][3]string)\n\tquery := d.ins.ShowColumnsQuery(table)\n\trows, err := db.QueryContext(ctx, query)\n\tif err != nil {\n\t\treturn columns, err\n\t}\n\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tname string\n\t\t\ttyp string\n\t\t\tnull string\n\t\t)\n\t\terr := rows.Scan(&name, &typ, &null)\n\t\tif err != nil {\n\t\t\treturn columns, err\n\t\t}\n\t\tcolumns[name] = [3]string{name, typ, null}\n\t}\n\n\treturn columns, nil\n}", "func (_m *RepositoryMock) GetColumns() []string {\n\tret := _m.Called()\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func() []string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (d *dnfEventPrizeDao) GetColumns(prefix ...string) string {\n\tdata := gconv.MapStrStr(d.Columns)\n\treturn helper.FormatSelectColumn(data, prefix...)\n}", "func (c *Client) GetColumns(dbTableName string) (columns []string, err error) {\n\ttype describeTable struct {\n\t\tData []map[string]string `json:\"data\"`\n\t}\n\n\tvar desc describeTable\n\n\terr = c.Do(http.MethodGet, nil, \"applicaiton/json\", &desc, \"/?query=DESCRIBE%%20%s%%20FORMAT%%20JSON\", dbTableName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get describe of %s: %v\", dbTableName, err)\n\t}\n\n\tfor _, column := range desc.Data {\n\t\tfor key, value := range column {\n\t\t\tif key == \"name\" {\n\t\t\t\tcolumns = append(columns, value)\n\t\t\t}\n\t\t}\n\t}\n\treturn columns, nil\n}", "func (d *maxCountChannelDao) GetColumns(prefix ...string) string {\n\tdata := gconv.MapStrStr(d.Columns)\n\treturn helper.FormatSelectColumn(data, prefix...)\n}", "func (d *tmpCharacDao) GetColumns(prefix ...string) string {\n\tdata := gconv.MapStrStr(d.Columns)\n\treturn helper.FormatSelectColumn(data, prefix...)\n}", "func (o *SummaryResponse) GetColumns() SummaryColumnResponse {\n\tif o == nil || o.Columns == nil {\n\t\tvar ret SummaryColumnResponse\n\t\treturn ret\n\t}\n\treturn *o.Columns\n}", "func GetColumns(tmap *gorp.TableMap) (columns []string) {\n\n\tfor index, _ := range tmap.Columns {\n\t\tcolumns = append(columns, tmap.Columns[index].ColumnName)\n\t}\n\treturn columns\n}", "func (d Dataset) GetColumns(a *config.AppContext) ([]models.Node, error) {\n\tds := models.Dataset(d)\n\treturn ds.GetColumns(a.Db)\n}", "func (r *result) Columns() []string {\n\treturn r.columns\n}", "func (qr *QueryResponse) Columns() []ColumnItem {\n\treturn qr.ColumnList\n}", "func (*__tbl_iba_servers) GetColumns() []string {\n\treturn []string{\"id\", \"name\", \"zex\", \"stort\", \"comment\"}\n}", "func (*__tbl_nodes) GetColumns() []string {\n\treturn []string{\"id\", \"parent_id\", \"description\", \"comment\", \"meta\", \"full_name\", \"directory_id\", \"signal_id\", \"created_at\", \"updated_at\", \"acl\"}\n}", "func (dao *SysConfigDao) Columns() SysConfigColumns {\n\treturn dao.columns\n}", "func (s *DbRecorder) Columns(includeKeys bool) []string {\n\treturn s.colList(includeKeys, false)\n}", "func (o *InlineResponse20075Stats) GetColumns() InlineResponse20075StatsColumns {\n\tif o == nil || o.Columns == nil {\n\t\tvar ret InlineResponse20075StatsColumns\n\t\treturn ret\n\t}\n\treturn *o.Columns\n}", "func (dao *PagesDao) Columns() PagesColumns {\n\treturn dao.columns\n}", "func (d *badUserDao) GetColumns(prefix ...string) string {\n\tdata := gconv.MapStrStr(d.Columns)\n\treturn helper.FormatSelectColumn(data, prefix...)\n}", "func (q Query) Columns() []string {\n\treturn q.columns\n}", "func (ts *STableSpec) Columns() []IColumnSpec {\n\tif ts._columns == nil {\n\t\tval := reflect.Indirect(reflect.New(ts.structType))\n\t\tts.struct2TableSpec(val)\n\t}\n\treturn ts._columns\n}", "func (r *filter) Columns() []string {\n\treturn r.input.Columns()\n}", "func (m *matrix) GetColumns() int {\n\treturn m.cols\n}", "func (cr *callResult) Columns() []string {\n\tif cr._columns == nil {\n\t\tnumField := len(cr.outputFields)\n\t\tcr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tcr._columns[i] = cr.outputFields[i].Name()\n\t\t}\n\t}\n\treturn cr._columns\n}", "func (cr *callResult) Columns() []string {\n\tif cr._columns == nil {\n\t\tnumField := len(cr.outputFields)\n\t\tcr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tcr._columns[i] = cr.outputFields[i].Name()\n\t\t}\n\t}\n\treturn cr._columns\n}", "func (qr *queryResult) Columns() []string {\n\tif qr._columns == nil {\n\t\tnumField := len(qr.fields)\n\t\tqr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tqr._columns[i] = qr.fields[i].Name()\n\t\t}\n\t}\n\treturn qr._columns\n}", "func (qr *queryResult) Columns() []string {\n\tif qr._columns == nil {\n\t\tnumField := len(qr.fields)\n\t\tqr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tqr._columns[i] = qr.fields[i].Name()\n\t\t}\n\t}\n\treturn qr._columns\n}", "func (r *Reader) Columns() []Column {\n\treturn r.cols\n}", "func (b *Blueprint) GetAddedColumns() []*ColumnDefinition {\n\treturn b.columns\n}", "func (t Table) Columns() []*Column {\n\treturn t.columns\n}", "func (db *DB) Columns(table string) ([]string, error) {\n\tif err := db.db.RLock(); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer db.db.RUnlock()\n\n\ts, err := db.db.Schema(table)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cols []string\n\tfor _, c := range s.Columns {\n\t\tcols = append(cols, c.Column)\n\t}\n\treturn cols, nil\n}", "func (ref *UIElement) Columns() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(ColumnsAttribute)\n}", "func Columns() *ColumnsType {\n\ttable := qbColumnsTable\n\treturn &ColumnsType{\n\t\tqbColumnsFColumnName.Copy(&table),\n\t\tqbColumnsFTableSchema.Copy(&table),\n\t\tqbColumnsFTableName.Copy(&table),\n\t\tqbColumnsFCharacterMaximumLength.Copy(&table),\n\t\t&table,\n\t}\n}", "func (cq *CypherQuery) Columns() []string {\n\treturn cq.cr.Columns\n}", "func (fw *FileWriter) Columns() []*Column {\n\treturn fw.schemaWriter.Columns()\n}", "func (r *rows) Columns() (c []string) {\n\tif trace {\n\t\tdefer func() {\n\t\t\ttracer(r, \"Columns(): %v\", c)\n\t\t}()\n\t}\n\treturn r.columns\n}", "func (c *Conn) GetColumns(schemaName, tableName string) ([]db.Column, error) {\n\tif schemaCache == nil {\n\t\tschemaCache = make(map[string][]db.Column)\n\t}\n\tif _, ok := schemaCache[schemaName+\".\"+tableName]; ok {\n\t\tfor i := range schemaCache[schemaName+\".\"+tableName] {\n\t\t\tschemaCache[schemaName+\".\"+tableName][i].Value = nil\n\t\t}\n\t\treturn schemaCache[schemaName+\".\"+tableName], nil\n\t}\n\tcols := []db.Column{}\n\tvar col db.Column\n\tvar field, tp, null, key, def, extra interface{}\n\tquery := \"show columns from \" + schemaName + \".\" + tableName\n\trows, err := c.conn.Query(query)\n\tif err != nil {\n\t\treturn cols, err\n\t}\n\tdefer rows.Close()\n\tif err == nil && rows != nil {\n\t\tfor rows.Next() {\n\t\t\trows.Scan(&field, &tp, &null, &key, &def, &extra)\n\t\t\tcol = db.Column{\n\t\t\t\tName: db.Interface2string(field, false),\n\t\t\t\tDefaultValue: db.Interface2string(def, false),\n\t\t\t}\n\t\t\tif db.Interface2string(key, false) == \"PRI\" {\n\t\t\t\tcol.PrimaryKey = true\n\t\t\t} else {\n\t\t\t\tcol.PrimaryKey = false\n\t\t\t}\n\t\t\tif db.Interface2string(null, false) == \"YES\" {\n\t\t\t\tcol.Nullable = true\n\t\t\t} else {\n\t\t\t\tcol.Nullable = false\n\t\t\t}\n\t\t\tif db.Interface2string(extra, false) == \"auto_increment\" {\n\t\t\t\tcol.AutoIncrement = true\n\t\t\t} else {\n\t\t\t\tcol.AutoIncrement = false\n\t\t\t}\n\t\t\tcol.Type, col.Length = mapDataType(db.Interface2string(tp, false))\n\t\t\tcols = append(cols, col)\n\t\t}\n\t}\n\n\tschemaCache[schemaName+\".\"+tableName] = cols\n\treturn cols, nil\n}", "func (dao *ConfigAuditProcessDao) Columns() ConfigAuditProcessColumns {\n\treturn dao.columns\n}", "func (r *Iter_UServ_UpdateNameToFoo) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (o ServiceBusQueueOutputDataSourceResponseOutput) PropertyColumns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceBusQueueOutputDataSourceResponse) []string { return v.PropertyColumns }).(pulumi.StringArrayOutput)\n}", "func (k *CustomResourceKind) Columns() []*printer.TableColumn {\n\tif k.Spec == nil {\n\t\treturn nil\n\t}\n\n\treturn []*printer.TableColumn{\n\t\t{\n\t\t\tName: \"JSONSchema\",\n\t\t\tValue: k.Spec.JSONSchema,\n\t\t},\n\t}\n}", "func (i *PermissionIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (s *DbRecorder) colList(withKeys bool, omitNil bool) []string {\n\tnames := make([]string, 0, len(s.fields))\n\n\tvar ar reflect.Value\n\tif omitNil {\n\t\tar = reflect.Indirect(reflect.ValueOf(s.record))\n\t}\n\n\tfor _, field := range s.fields {\n\t\tif !withKeys && field.isKey {\n\t\t\tcontinue\n\t\t}\n\t\tif omitNil {\n\t\t\tf := ar.FieldByName(field.name)\n\t\t\tif f.Kind() == reflect.Ptr && f.IsNil() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tnames = append(names, field.column)\n\t}\n\n\treturn names\n}", "func (c *GithubClient) columns(projectId int64) ([]Column, error) {\n\tu := fmt.Sprintf(\"/projects/%v/columns\", projectId)\n\treq, err := c.client.NewRequest(\"GET\", u, nil)\n\treq.Header.Set(\"Accept\", mediaTypeProjectsPreview)\n\tvar columns []Column\n\t_, err = c.client.Do(c.ctx, req, &columns)\n\treturn columns, err\n}", "func (c *cassandraConnector) Get(\n\tctx context.Context,\n\te *base.Definition,\n\tkeyCols []base.Column,\n\tcolNamesToRead ...string,\n) ([]base.Column, error) {\n\tif len(colNamesToRead) == 0 {\n\t\tcolNamesToRead = e.GetColumnsToRead()\n\t}\n\n\tq, err := c.buildSelectQuery(ctx, e, keyCols, colNamesToRead)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// build a result row\n\tresult := buildResultRow(e, colNamesToRead)\n\n\tif err := q.Scan(result...); err != nil {\n\t\tif err == gocql.ErrNotFound {\n\t\t\terr = yarpcerrors.NotFoundErrorf(err.Error())\n\t\t}\n\t\tsendCounters(c.executeFailScope, e.Name, get, err)\n\t\treturn nil, err\n\t}\n\n\tsendLatency(c.scope, e.Name, get, time.Duration(q.Latency()))\n\tsendCounters(c.executeSuccessScope, e.Name, get, nil)\n\n\t// translate the read result into a row ([]base.Column)\n\treturn getRowFromResult(e, colNamesToRead, result), nil\n}", "func (o ServiceBusQueueOutputDataSourceOutput) PropertyColumns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceBusQueueOutputDataSource) []string { return v.PropertyColumns }).(pulumi.StringArrayOutput)\n}", "func (o CassandraSchemaOutput) Columns() ColumnArrayOutput {\n\treturn o.ApplyT(func(v CassandraSchema) []Column { return v.Columns }).(ColumnArrayOutput)\n}", "func (r *Iter_UServ_GetAllUsers) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (c *client) GetProjectColumns(org string, projectID int) ([]ProjectColumn, error) {\n\tdurationLogger := c.log(\"GetProjectColumns\", projectID)\n\tdefer durationLogger()\n\n\tpath := fmt.Sprintf(\"/projects/%d/columns\", projectID)\n\tvar projectColumns []ProjectColumn\n\terr := c.readPaginatedResults(\n\t\tpath,\n\t\t\"application/vnd.github.inertia-preview+json\",\n\t\torg,\n\t\tfunc() interface{} {\n\t\t\treturn &[]ProjectColumn{}\n\t\t},\n\t\tfunc(obj interface{}) {\n\t\t\tprojectColumns = append(projectColumns, *(obj.(*[]ProjectColumn))...)\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn projectColumns, nil\n}", "func (i *GroupIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (m *MacroEvaluator) GetFields() []Field {\n\tfields := make([]Field, len(m.FieldValues))\n\ti := 0\n\tfor key := range m.FieldValues {\n\t\tfields[i] = key\n\t\ti++\n\t}\n\treturn fields\n}", "func (i *UserIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (r *Iter_UServ_CreateUsersTable) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (r *Iter_UServ_Drop) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (vt *perfSchemaTable) Cols() []*table.Column {\n\treturn vt.cols\n}", "func (r *rows) Columns() []string {\n\treturn r.parent.columns\n}", "func getAllSchemaColumns(t *testing.T) *schema.ColCollection {\n\tcolColl, err := schema.NewColCollection(\n\t\tschema.NewColumn(\"id\", 0, types.IntKind, true),\n\t\tschema.NewColumn(\"first\", 1, types.StringKind, false),\n\t\tschema.NewColumn(\"last\", 2, types.StringKind, false),\n\t\tschema.NewColumn(\"is_married\", 3, types.BoolKind, false),\n\t\tschema.NewColumn(\"age\", 4, types.IntKind, false),\n\t\tschema.NewColumn(\"rating\", 5, types.FloatKind, false),\n\t\tschema.NewColumn(\"uuid\", 6, types.UUIDKind, false),\n\t\tschema.NewColumn(\"num_episodes\", 7, types.UintKind, false),\n\t\tschema.NewColumn(\"id\", 8, types.IntKind, true),\n\t\tschema.NewColumn(\"name\", 9, types.StringKind, false),\n\t\tschema.NewColumn(\"air_date\", 10, types.IntKind, false),\n\t\tschema.NewColumn(\"rating\", 11, types.FloatKind, false),\n\t\tschema.NewColumn(\"character_id\", 12, types.IntKind, true),\n\t\tschema.NewColumn(\"episode_id\", 13, types.IntKind, true),\n\t\tschema.NewColumn(\"comments\", 14, types.StringKind, false),\n\t)\n\n\trequire.NoError(t, err)\n\treturn colColl\n}", "func (m *List) SetColumns(value []ColumnDefinitionable)() {\n m.columns = value\n}", "func (i *UserGroupsIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (r *Iter_UServ_GetFriends) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (o DataSetGeoSpatialColumnGroupPtrOutput) Columns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *DataSetGeoSpatialColumnGroup) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Columns\n\t}).(pulumi.StringArrayOutput)\n}", "func (s *DbRecorder) colValLists(withKeys, withAutos bool) (columns []string, values []interface{}) {\n\tar := reflect.Indirect(reflect.ValueOf(s.record))\n\n\tfor _, field := range s.fields {\n\n\t\tswitch {\n\t\tcase !withKeys && field.isKey:\n\t\t\tcontinue\n\t\tcase !withAutos && field.isAuto:\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get the value of the field we are going to store.\n\t\tf := ar.FieldByName(field.name)\n\t\tvar v reflect.Value\n\t\tif f.Kind() == reflect.Ptr {\n\t\t\tif f.IsNil() {\n\t\t\t\t// nothing to store\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// no indirection: the field is already a reference to its value\n\t\t\tv = f\n\t\t} else {\n\t\t\t// get the value pointed to by the field\n\t\t\tv = reflect.Indirect(f)\n\t\t}\n\n\t\tvalues = append(values, v.Interface())\n\t\tcolumns = append(columns, field.column)\n\t}\n\n\treturn\n}", "func (o DataSetGeoSpatialColumnGroupOutput) Columns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v DataSetGeoSpatialColumnGroup) []string { return v.Columns }).(pulumi.StringArrayOutput)\n}", "func (t *NodesTable) Columns() []table.ColumnDefinition {\n\treturn t.columns\n}", "func (i *UserPermissionsIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (r *boltRows) Columns() []string {\n\tfieldsInt, ok := r.metadata[\"fields\"]\n\tif !ok {\n\t\treturn []string{}\n\t}\n\n\tfields, ok := fieldsInt.([]interface{})\n\tif !ok {\n\t\tlog.Errorf(\"Unrecognized fields from success message: %#v\", fieldsInt)\n\t\treturn []string{}\n\t}\n\n\tfieldsStr := make([]string, len(fields))\n\tfor i, f := range fields {\n\t\tif fieldsStr[i], ok = f.(string); !ok {\n\t\t\tlog.Errorf(\"Unrecognized fields from success message: %#v\", fieldsInt)\n\t\t\treturn []string{}\n\t\t}\n\t}\n\treturn fieldsStr\n}", "func (i *GroupPermissionsIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (ei *Engine) getColumns(e mysql.BinlogEvent) (msgs []*pbmysql.Event, err error) {\n\ttID := e.TableID(ei.getFormat())\n\n\tif ei.tm[tID] == nil {\n\t\treturn\n\t}\n\tvar rows mysql.Rows\n\tif rows, err = e.Rows(ei.getFormat(), ei.tm[tID]); err != nil {\n\t\treturn\n\t}\n\n\tif e.IsWriteRows() {\n\t\tmsgs, err = ei.getInsertColumns(e, rows, tID)\n\t} else if e.IsUpdateRows() {\n\t\tmsgs, err = ei.getUpdateColumns(e, rows, tID)\n\t} else if e.IsDeleteRows() {\n\t\tmsgs, err = ei.getDeleteColumns(e, rows, tID)\n\t} else {\n\t\terr = fmt.Errorf(\"unsupport type\")\n\t}\n\tfor _, msg := range msgs {\n\t\tmsg.NanoTimestamp = time.Now().UnixNano()\n\t\tmsg.Schema = ei.tm[tID].Database\n\t\tmsg.Table = ei.tm[tID].Name\n\t}\n\n\treturn\n}", "func (m *Macro) GetFields() []Field {\n\tfields := m.evaluator.GetFields()\n\n\tfor _, macro := range m.Opts.MacroStore.List() {\n\t\tfields = append(fields, macro.evaluator.GetFields()...)\n\t}\n\n\treturn fields\n}", "func (o CassandraSchemaPtrOutput) Columns() ColumnArrayOutput {\n\treturn o.ApplyT(func(v *CassandraSchema) []Column {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Columns\n\t}).(ColumnArrayOutput)\n}", "func (r *Iter_UServ_SelectUserById) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (r *Iter_UServ_InsertUsers) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (c MethodsCollection) FieldsGet() pFieldsGet {\n\treturn pFieldsGet{\n\t\tMethod: c.MustGet(\"FieldsGet\"),\n\t}\n}", "func (o ServiceBusTopicOutputDataSourceResponseOutput) PropertyColumns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceBusTopicOutputDataSourceResponse) []string { return v.PropertyColumns }).(pulumi.StringArrayOutput)\n}", "func (rows *Rows) Columns() []string {\n\tcolInfo := rows.resultSet.ResultSetMetadata.ColumnInfo\n\tcolumns := make([]string, len(colInfo))\n\tfor i, col := range colInfo {\n\t\tcolumns[i] = *col.Name\n\t}\n\treturn columns\n}", "func (r *QueryResult) Columns() []string {\n\tnames := make([]string, r.metadata.ColumnCount())\n\tcols := r.metadata.Columns()\n\tfor i := 0; i < len(names); i++ {\n\t\tnames[i] = cols[i].Name()\n\t}\n\treturn names\n}", "func (s *Simplex) getColumn(pivotColumn int) []float64 {\n\tvar columnValues []float64\n\tfor i := 0; i < s.RowsSize; i++ {\n\t\tcolumnValues = append(columnValues, s.Tableau[i][pivotColumn])\n\t}\n\treturn columnValues\n}", "func(h ColumnHandler)Columns(initialColumn string, howManyColumns uint) []string {\n\tvar (\n\t\ta []string\n\t\tc= initialColumn\n\t)\n\n\ta = append(a, c)\n\n\tfor i := uint(0); i < howManyColumns-1; i++ {\n\t\tc = h.NextColumn(c, 0)\n\n\t\tif c!=\"\" {\n\t\t\ta = append(a, c)\n\t\t}\n\t}\n\n\treturn a\n}", "func (o ServiceBusTopicOutputDataSourceOutput) PropertyColumns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceBusTopicOutputDataSource) []string { return v.PropertyColumns }).(pulumi.StringArrayOutput)\n}", "func BenchmarkGetColumns(b *testing.B) {\n\tdbc := csdb.MustConnectTest()\n\tdefer dbc.Close()\n\tsess := dbc.NewSession()\n\tvar err error\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tbenchmarkGetColumns, err = csdb.GetColumns(sess, \"eav_attribute\")\n\t\tif err != nil {\n\t\t\tb.Error(err)\n\t\t}\n\t}\n\thashHave, err := benchmarkGetColumns.Hash()\n\tif err != nil {\n\t\tb.Error(err)\n\t}\n\tif 0 != bytes.Compare(hashHave, benchmarkGetColumnsHashWant) {\n\t\tb.Errorf(\"\\nHave %#v\\nWant %#v\\n\", hashHave, benchmarkGetColumnsHashWant)\n\t}\n\t//\tb.Log(benchmarkGetColumns.GoString())\n}", "func (t *BoundedTable) Cols() []*table.Column {\n\treturn t.Columns\n}", "func (v *templateTableType) Columns() []string {\n\treturn []string{\n\t\t\"id\",\n\t\t\"title\",\n\t\t\"description\",\n\t\t\"type\",\n\t\t\"note\",\n\t\t\"coach_id\",\n\t\t\"place_id\",\n\t\t\"weekday\",\n\t\t\"start_time\",\n\t\t\"duration\",\n\t\t\"created_at\",\n\t\t\"updated_at\",\n\t}\n}", "func (p *HbaseClient) GetColumnDescriptors(tableName Text) (r map[string]*ColumnDescriptor, err error) {\n\tif err = p.sendGetColumnDescriptors(tableName); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetColumnDescriptors()\n}", "func (r RowData) Columns() []string {\n\ttmp := []string{}\n\tfor colName := range r {\n\t\ttmp = append(tmp, colName)\n\t}\n\n\treturn tmp\n}", "func (v *IconView) GetColumns() int {\n\treturn int(C.gtk_icon_view_get_columns(v.native()))\n}", "func (d *Dense) Columns() int {\n\treturn d.columns\n}", "func (a *Client) EmployeesByIDColumnsGet(params *EmployeesByIDColumnsGetParams, authInfo runtime.ClientAuthInfoWriter) (*EmployeesByIDColumnsGetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewEmployeesByIDColumnsGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"EmployeesByIdColumnsGet\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/employees/{id}/columns\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &EmployeesByIDColumnsGetReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*EmployeesByIDColumnsGetOK), nil\n\n}", "func (v *permutationTableType) Columns() []string {\n\treturn []string{\"uuid\", \"data\"}\n}", "func (fn *formulaFuncs) COLUMNS(argsList *list.List) formulaArg {\n\tif argsList.Len() != 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"COLUMNS requires 1 argument\")\n\t}\n\tmin, max := calcColumnsMinMax(argsList)\n\tif max == MaxColumns {\n\t\treturn newNumberFormulaArg(float64(MaxColumns))\n\t}\n\tresult := max - min + 1\n\tif max == min {\n\t\tif min == 0 {\n\t\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"invalid reference\")\n\t\t}\n\t\treturn newNumberFormulaArg(float64(1))\n\t}\n\treturn newNumberFormulaArg(float64(result))\n}", "func (o CassandraSchemaResponseOutput) Columns() ColumnResponseArrayOutput {\n\treturn o.ApplyT(func(v CassandraSchemaResponse) []ColumnResponse { return v.Columns }).(ColumnResponseArrayOutput)\n}", "func (view *CrosstabView) Columns() ([]string, error) {\n\tif view.err != nil {\n\t\treturn nil, view.err\n\t}\n\tcols := make([]string, len(view.hkeys)+1)\n\tcols[0] = view.v\n\tfor i := 0; i < len(view.hkeys); i++ {\n\t\tcols[i+1] = view.hkeys[i].v\n\t}\n\treturn cols, nil\n}", "func (t *tableCommon) Cols() []*table.Column {\n\ttrace_util_0.Count(_tables_00000, 45)\n\tif len(t.publicColumns) > 0 {\n\t\ttrace_util_0.Count(_tables_00000, 48)\n\t\treturn t.publicColumns\n\t}\n\ttrace_util_0.Count(_tables_00000, 46)\n\tpublicColumns := make([]*table.Column, len(t.Columns))\n\tmaxOffset := -1\n\tfor _, col := range t.Columns {\n\t\ttrace_util_0.Count(_tables_00000, 49)\n\t\tif col.State != model.StatePublic {\n\t\t\ttrace_util_0.Count(_tables_00000, 51)\n\t\t\tcontinue\n\t\t}\n\t\ttrace_util_0.Count(_tables_00000, 50)\n\t\tpublicColumns[col.Offset] = col\n\t\tif maxOffset < col.Offset {\n\t\t\ttrace_util_0.Count(_tables_00000, 52)\n\t\t\tmaxOffset = col.Offset\n\t\t}\n\t}\n\ttrace_util_0.Count(_tables_00000, 47)\n\treturn publicColumns[0 : maxOffset+1]\n}", "func (sheet *SheetData) GetColumn(col int) []interface{} {\n\t//We need to transpose the data\n\tcolData := make([]interface{}, 0)\n\n\t//March over each row\n\tfor r := range sheet.Values {\n\t\t//If it has the column add it\n\t\tif len(sheet.Values[r]) > col+1 {\n\t\t\tcolData = append(colData, sheet.Values[r][col])\n\t\t}\n\n\t}\n\n\treturn colData\n}", "func (v Chunk) Cols() []flux.ColMeta {\n\treturn v.buf.Columns\n}", "func (m *ItemItemsItemWorkbookTablesWorkbookTableItemRequestBuilder) Columns()(*ItemItemsItemWorkbookTablesItemColumnsRequestBuilder) {\n return NewItemItemsItemWorkbookTablesItemColumnsRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (v *nicerButSlowerFilmListViewType) Columns() []string {\n\treturn []string{\n\t\t\"FID\",\n\t\t\"title\",\n\t\t\"description\",\n\t\t\"category\",\n\t\t\"price\",\n\t\t\"length\",\n\t\t\"rating\",\n\t\t\"actors\",\n\t}\n}" ]
[ "0.6995068", "0.6583713", "0.65590763", "0.6495269", "0.64883107", "0.63101625", "0.6274126", "0.6241689", "0.6212528", "0.6161865", "0.605871", "0.60496694", "0.6028404", "0.6013853", "0.599702", "0.5981092", "0.5973022", "0.5952178", "0.59382784", "0.5925666", "0.58940035", "0.5876905", "0.5861102", "0.58309436", "0.58063185", "0.579757", "0.57902", "0.5779666", "0.5779666", "0.5775891", "0.5775891", "0.57582045", "0.57420623", "0.5713454", "0.5708836", "0.5707396", "0.5706023", "0.5688588", "0.5687705", "0.56782436", "0.5572095", "0.5556475", "0.55517423", "0.5550844", "0.5507536", "0.54948115", "0.54923207", "0.5486347", "0.54764575", "0.5473337", "0.54645526", "0.54634976", "0.5462874", "0.54387087", "0.54302114", "0.54188484", "0.5417897", "0.541193", "0.5411222", "0.5403322", "0.5400279", "0.5393521", "0.5384458", "0.53830826", "0.53649503", "0.5359747", "0.5353298", "0.5323515", "0.53227854", "0.53173023", "0.53159213", "0.53100526", "0.5308569", "0.5306849", "0.5302087", "0.5286391", "0.52672833", "0.5250041", "0.5214074", "0.52134746", "0.5207467", "0.51946646", "0.5186772", "0.5184677", "0.51822585", "0.51739913", "0.51714134", "0.51712656", "0.516204", "0.5159912", "0.5153459", "0.5142394", "0.51365924", "0.5117269", "0.51093125", "0.51082766", "0.5101523", "0.5083754", "0.5083262", "0.50775415" ]
0.76532036
0
GetContentTypes gets the contentTypes property value. The collection of content types present in this list.
func (m *List) GetContentTypes()([]ContentTypeable) { return m.contentTypes }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *LastMileAccelerationOptions) GetContentTypes() []string {\n\tif o == nil || o.ContentTypes == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.ContentTypes\n}", "func (m *List) SetContentTypes(value []ContentTypeable)() {\n m.contentTypes = value\n}", "func (set *ContentTypeSet) Types() (types []ContentType) {\n\tif set == nil || len(set.set) == 0 {\n\t\treturn []ContentType{}\n\t}\n\treturn append(make([]ContentType, 0, len(set.set)), set.set...)\n}", "func (o *LastMileAccelerationOptions) SetContentTypes(v []string) {\n\to.ContentTypes = &v\n}", "func (ht HTMLContentTypeBinder) ContentTypes() []string {\n\treturn []string{\n\t\t\"application/html\",\n\t\t\"text/html\",\n\t\t\"application/x-www-form-urlencoded\",\n\t\t\"html\",\n\t}\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) ContentTypes(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"contentTypes\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (ycp *YamlContentParser) ContentTypes() []string {\n\treturn []string{\"text/x-yaml\", \"application/yaml\", \"text/yaml\", \"application/x-yaml\"}\n}", "func (m *SiteItemRequestBuilder) ContentTypes()(*ItemContentTypesRequestBuilder) {\n return NewItemContentTypesRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypes(contentTypes *string) {\n\to.ContentTypes = contentTypes\n}", "func ContentTypes(types []string, blacklist bool) Option {\n\treturn func(c *config) error {\n\t\tc.contentTypes = []parsedContentType{}\n\t\tfor _, v := range types {\n\t\t\tmediaType, params, err := mime.ParseMediaType(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.contentTypes = append(c.contentTypes, parsedContentType{mediaType, params})\n\t\t}\n\t\tc.blacklist = blacklist\n\t\treturn nil\n\t}\n}", "func (m *ItemSitesSiteItemRequestBuilder) ContentTypes()(*ItemSitesItemContentTypesRequestBuilder) {\n return NewItemSitesItemContentTypesRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func ContentTypes(contentTypes ...string) Option {\n\treturn ArrayOpt(\"content_types\", contentTypes...)\n}", "func (_AccessIndexor *AccessIndexorCaller) ContentTypes(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _AccessIndexor.contract.Call(opts, &out, \"contentTypes\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (_BaseContentSpace *BaseContentSpaceCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseContentSpace.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_Container *ContainerCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Container.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_BaseLibrary *BaseLibraryCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseLibrary.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (m *Gzip) GetContentType() []string {\n\tif m != nil {\n\t\treturn m.ContentType\n\t}\n\treturn nil\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIe(contentTypesIe *string) {\n\to.ContentTypesIe = contentTypesIe\n}", "func SetOfContentTypes(types ...ContentType) *ContentTypeSet {\n\tif len(types) == 0 {\n\t\treturn nil\n\t}\n\tset := &ContentTypeSet{\n\t\tset: make([]ContentType, 0, len(types)),\n\t\tpos: -1,\n\t}\nallTypes:\n\tfor _, t := range types {\n\t\t// Let's make sure we have not seen this type before.\n\t\tfor _, tt := range set.set {\n\t\t\tif tt == t {\n\t\t\t\t// Don't add it to the set, already exists\n\t\t\t\tcontinue allTypes\n\t\t\t}\n\t\t}\n\t\tset.set = append(set.set, t)\n\t}\n\tif len(set.set) == 0 {\n\t\treturn nil\n\t}\n\treturn set\n}", "func (sf SearchFilter) GetTypes() []string {\n\tret := funk.Keys(sf.Types).([]string)\n\tsort.Strings(ret)\n\treturn ret\n}", "func (o *LastMileAccelerationOptions) HasContentTypes() bool {\n\tif o != nil && o.ContentTypes != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (s *ChannelSpecification) SetSupportedContentTypes(v []*string) *ChannelSpecification {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (s *InferenceSpecification) SetSupportedContentTypes(v []*string) *InferenceSpecification {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (o *GetMessagesAllOf) GetContentType() interface{} {\n\tif o == nil {\n\t\tvar ret interface{}\n\t\treturn ret\n\t}\n\treturn o.ContentType\n}", "func (a *Client) GetSchemaTypes(params *GetSchemaTypesParams) (*GetSchemaTypesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSchemaTypesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getSchemaTypes\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/schemas/types\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetSchemaTypesReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetSchemaTypesOK), nil\n\n}", "func (o *SchemaDefinitionRestDto) GetTypes() map[string]SchemaType {\n\tif o == nil || o.Types == nil {\n\t\tvar ret map[string]SchemaType\n\t\treturn ret\n\t}\n\treturn *o.Types\n}", "func (s *ServerConnection) ContentFilterGetContentApplicationList() (ContentApplicationList, error) {\n\tdata, err := s.CallRaw(\"ContentFilter.getContentApplicationList\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcategories := struct {\n\t\tResult struct {\n\t\t\tCategories ContentApplicationList `json:\"categories\"`\n\t\t} `json:\"result\"`\n\t}{}\n\terr = json.Unmarshal(data, &categories)\n\treturn categories.Result.Categories, err\n}", "func (s *RecommendationJobPayloadConfig) SetSupportedContentTypes(v []*string) *RecommendationJobPayloadConfig {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (o *PluginConfigInterface) GetTypes() []PluginInterfaceType {\n\tif o == nil {\n\t\tvar ret []PluginInterfaceType\n\t\treturn ret\n\t}\n\n\treturn o.Types\n}", "func (s *AdditionalInferenceSpecificationDefinition) SetSupportedContentTypes(v []*string) *AdditionalInferenceSpecificationDefinition {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (o GetInstanceTypesResultOutput) Types() GetInstanceTypesTypeArrayOutput {\n\treturn o.ApplyT(func(v GetInstanceTypesResult) []GetInstanceTypesType { return v.Types }).(GetInstanceTypesTypeArrayOutput)\n}", "func ListTypes(c echo.Context) error {\n\tlogger.Info.Info(\"Preparing to list types\")\n\tresult := new(struct {\n\t\tData interface{} `json:\"data\"`\n\t\tTotal int `json:\"total\"`\n\t})\n\ttypes, total, err := controller.ListTypes()\n\tif err != nil {\n\t\tlogger.Error.Error(\"Error while list of types\", err)\n\t\treturn echo.NewHTTPError(http.StatusNotAcceptable, \"Error while list of types\")\n\t}\n\tresult.Data = types\n\tresult.Total = total\n\tlogger.Success.Info(\"Types listed successfully\")\n\treturn c.JSON(http.StatusOK, result)\n}", "func (o *LastMileAccelerationOptions) GetContentTypesOk() (*[]string, bool) {\n\tif o == nil || o.ContentTypes == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ContentTypes, true\n}", "func NewContentTypeSet(types ...string) *ContentTypeSet {\n\tif len(types) == 0 {\n\t\treturn nil\n\t}\n\tset := &ContentTypeSet{\n\t\tset: make([]ContentType, 0, len(types)),\n\t\tpos: -1,\n\t}\nallTypes:\n\tfor _, t := range types {\n\t\tmediaType, _, err := mime.ParseMediaType(t)\n\t\tif err != nil {\n\t\t\t// skip types that can not be parsed\n\t\t\tcontinue\n\t\t}\n\t\t// Let's make sure we have not seen this type before.\n\t\tfor _, tt := range set.set {\n\t\t\tif tt == ContentType(mediaType) {\n\t\t\t\t// Don't add it to the set, already exists\n\t\t\t\tcontinue allTypes\n\t\t\t}\n\t\t}\n\t\tset.set = append(set.set, ContentType(mediaType))\n\t}\n\tif len(set.set) == 0 {\n\t\treturn nil\n\t}\n\treturn set\n}", "func (o GetDomainNameEndpointConfigurationOutput) Types() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetDomainNameEndpointConfiguration) []string { return v.Types }).(pulumi.StringArrayOutput)\n}", "func (o *MicrosoftGraphListItem) GetContentType() AnyOfmicrosoftGraphContentTypeInfo {\n\tif o == nil || o.ContentType == nil {\n\t\tvar ret AnyOfmicrosoftGraphContentTypeInfo\n\t\treturn ret\n\t}\n\treturn *o.ContentType\n}", "func (s *CaptureContentTypeHeader) SetCsvContentTypes(v []*string) *CaptureContentTypeHeader {\n\ts.CsvContentTypes = v\n\treturn s\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) GetContentTypesLength(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"getContentTypesLength\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (aft AllowedFileTypes) Contents() []string {\n\treturn aft\n}", "func (a *Client) GetSchemaTypes(params *GetSchemaTypesParams) (*GetSchemaTypesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSchemaTypesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getSchemaTypes\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/schemas/types\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetSchemaTypesReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetSchemaTypesOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for getSchemaTypes: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func UtteranceContentType_Values() []string {\n\treturn []string{\n\t\tUtteranceContentTypePlainText,\n\t\tUtteranceContentTypeCustomPayload,\n\t\tUtteranceContentTypeSsml,\n\t\tUtteranceContentTypeImageResponseCard,\n\t}\n}", "func getContentInfoList() ([]content.Info, error) {\n\tinfos := make([]content.Info, 0)\n\twalkFn := func(info content.Info) error {\n\t\tinfos = append(infos, info)\n\t\treturn nil\n\t}\n\tif err := contentStore.Walk(ctrdCtx, walkFn); err != nil {\n\t\treturn nil, fmt.Errorf(\"getContentInfoList: Exception while getting content list. %s\", err.Error())\n\t}\n\treturn infos, nil\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIc(contentTypesIc *string) {\n\to.ContentTypesIc = contentTypesIc\n}", "func PossibleContentTypes(firstByte byte) (ct ContentTypeOptions) {\n\tif firstByte == 0 {\n\t\treturn 0\n\t}\n\n\tswitch {\n\tcase firstByte < '\\t' /* 9 */ :\n\t\t// not a text\n\t\tif firstByte&^maskWireType == 0 {\n\t\t\treturn 0\n\t\t}\n\tcase firstByte >= legalUtf8:\n\t\tct |= ContentOptionText\n\tcase firstByte < illegalUtf8FirstByte:\n\t\tct |= ContentOptionText\n\t}\n\n\tswitch WireType(firstByte & maskWireType) {\n\tcase WireVarint:\n\t\tif ct&ContentOptionText == 0 && firstByte >= illegalUtf8FirstByte {\n\t\t\tct |= ContentOptionNotation\n\t\t}\n\t\tct |= ContentOptionMessage\n\tcase WireFixed64, WireBytes, WireFixed32, WireStartGroup:\n\t\tct |= ContentOptionMessage\n\tcase WireEndGroup:\n\t\tif ct&ContentOptionText == 0 {\n\t\t\tct |= ContentOptionNotation\n\t\t}\n\t}\n\treturn ct\n}", "func (*AccountSetContentSettingsRequest) TypeName() string {\n\treturn \"account.setContentSettings\"\n}", "func (o *MicrosoftGraphWorkbookComment) GetContentType() string {\n\tif o == nil || o.ContentType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ContentType\n}", "func (ContentMuxType) Values() []ContentMuxType {\n\treturn []ContentMuxType{\n\t\t\"ContentOnly\",\n\t}\n}", "func (o *BranchingModelSettings) GetBranchTypes() []BranchingModelSettingsBranchTypes {\n\tif o == nil || o.BranchTypes == nil {\n\t\tvar ret []BranchingModelSettingsBranchTypes\n\t\treturn ret\n\t}\n\treturn *o.BranchTypes\n}", "func GetTypes(c echo.Context) error {\n\tvar types []db.Types\n\n\tif err := config.DB.Find(&types).Error; err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, err.Error())\n\t}\n\treturn c.JSON(http.StatusOK, map[string]interface{}{\n\t\t\"message\": \"Berhasil Menampilkan Semua Tipe Smartphone\",\n\t\t\"types\": types,\n\t})\n}", "func HubContentType_Values() []string {\n\treturn []string{\n\t\tHubContentTypeModel,\n\t\tHubContentTypeNotebook,\n\t}\n}", "func (o *InlineResponse20049Post) GetContentType() string {\n\tif o == nil || o.ContentType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ContentType\n}", "func (o *InlineResponse200115) GetContentType() string {\n\tif o == nil || o.ContentType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ContentType\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) GetContentTypesLength(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"getContentTypesLength\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func GetTypes(path string, excludeFilesRegexp *regexp.Regexp, excludeTypesRegexp *regexp.Regexp) (types []*TypeInfo, err error) {\n\tfiles, err := FindFiles(path, excludeFilesRegexp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !strings.HasSuffix(path, \"/\") {\n\t\tpath += \"/\"\n\t}\n\n\tfor _, file := range files {\n\t\tfileData, err := parser.ParseFile(token.NewFileSet(), path+file.Name(), nil, 0)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfileTypes, err := GetTypesFromFile(fileData, excludeTypesRegexp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttypes = append(types, fileTypes...)\n\t}\n\n\treturn types, nil\n}", "func (d *ceph) MigrationTypes(contentType ContentType, refresh bool, copySnapshots bool) []migration.Type {\n\tvar rsyncFeatures []string\n\n\t// Do not pass compression argument to rsync if the associated\n\t// config key, that is rsync.compression, is set to false.\n\tif shared.IsFalse(d.Config()[\"rsync.compression\"]) {\n\t\trsyncFeatures = []string{\"xattrs\", \"delete\", \"bidirectional\"}\n\t} else {\n\t\trsyncFeatures = []string{\"xattrs\", \"delete\", \"compress\", \"bidirectional\"}\n\t}\n\n\tif refresh {\n\t\tvar transportType migration.MigrationFSType\n\n\t\tif IsContentBlock(contentType) {\n\t\t\ttransportType = migration.MigrationFSType_BLOCK_AND_RSYNC\n\t\t} else {\n\t\t\ttransportType = migration.MigrationFSType_RSYNC\n\t\t}\n\n\t\treturn []migration.Type{\n\t\t\t{\n\t\t\t\tFSType: transportType,\n\t\t\t\tFeatures: rsyncFeatures,\n\t\t\t},\n\t\t}\n\t}\n\n\tif contentType == ContentTypeBlock {\n\t\treturn []migration.Type{\n\t\t\t{\n\t\t\t\tFSType: migration.MigrationFSType_RBD,\n\t\t\t},\n\t\t\t{\n\t\t\t\tFSType: migration.MigrationFSType_BLOCK_AND_RSYNC,\n\t\t\t\tFeatures: rsyncFeatures,\n\t\t\t},\n\t\t}\n\t}\n\n\treturn []migration.Type{\n\t\t{\n\t\t\tFSType: migration.MigrationFSType_RBD,\n\t\t},\n\t\t{\n\t\t\tFSType: migration.MigrationFSType_RSYNC,\n\t\t\tFeatures: rsyncFeatures,\n\t\t},\n\t}\n}", "func (resource *ResourceType) SchemeTypes(name TypeName) []TypeName {\n\treturn []TypeName{\n\t\tname,\n\t\tresource.makeResourceListTypeName(name),\n\t}\n}", "func (o *ExtrasSavedFiltersListParams) WithContentTypes(contentTypes *string) *ExtrasSavedFiltersListParams {\n\to.SetContentTypes(contentTypes)\n\treturn o\n}", "func (p *Plugin) GetTypes() []types.PluginInterfaceType {\n\tp.mu.RLock()\n\tdefer p.mu.RUnlock()\n\n\treturn p.PluginObj.Config.Interface.Types\n}", "func Parse(data string) (ContentTypeList, error) {\n\ttypes := make(ContentTypeList, 0, 1)\n\n\tfor _, entry := range parseList(data) {\n\t\tt, err := ParseSingle(entry)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif t != nil {\n\t\t\ttypes = append(types, t)\n\t\t}\n\t}\n\n\treturn types, nil\n\n}", "func (config *Config) ContentType() ContentType {\n\treturn config.contentType\n}", "func GetTypeFields(typeFileContents []byte) (ContentType, error) {\n\n\tvar contentType ContentType\n\tcontentType.Fields = map[string]string{}\n\n\t// Use empty interface to store JSON field values of unknown primitive type.\n\tvar unknownValues map[string]interface{}\n\t// Put JSON key/values into the map of unknown primitives.\n\terr := json.Unmarshal(typeFileContents, &unknownValues)\n\tif err != nil {\n\t\treturn contentType, fmt.Errorf(\"\\nUnable to read content because: %w\", err)\n\t}\n\tfor field, unknownValue := range unknownValues {\n\t\t// isString will be set to true if the value is a string (vs array, obj, etc).\n\t\t_, isString := unknownValue.(string)\n\t\tif isString {\n\t\t\t// Convert the empty interface into a string that can be stored in ContentType struct.\n\t\t\tcontentType.Fields[field] = fmt.Sprintf(\"%v\", unknownValue)\n\t\t}\n\t}\n\n\treturn contentType, nil\n}", "func (client *Client) ListCatalogItemTypes(req *Request) (*Response, error) {\n\treturn client.Execute(&Request{\n\t\tMethod: \"GET\",\n\t\tPath: ServiceCatalogTypesPath,\n\t\tQueryParams: req.QueryParams,\n\t\tResult: &ListCatalogItemTypesResult{},\n\t})\n}", "func (RestController *RestController) GetDataTypes(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tdataTypes := RestController.databaseController.ListDataTypes()\n\tjsonBytes, err := json.Marshal(*dataTypes)\n\tif err == nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tfmt.Fprintf(w, \"%s\", jsonBytes)\n\t} else {\n\t\tmsg := fmt.Sprintf(\"An error occurred during marshaling of list of data types: %s\\n\", err)\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tw.WriteHeader(500)\n\t\tfmt.Fprintf(w, \"%s\", msg)\n\t\tconfiguration.Error.Printf(msg)\n\t}\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIsw(contentTypesIsw *string) {\n\to.ContentTypesIsw = contentTypesIsw\n}", "func (client *ClientImpl) GetProcessWorkItemTypes(ctx context.Context, args GetProcessWorkItemTypesArgs) (*[]ProcessWorkItemType, error) {\n\trouteValues := make(map[string]string)\n\tif args.ProcessId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.ProcessId\"}\n\t}\n\trouteValues[\"processId\"] = (*args.ProcessId).String()\n\n\tqueryParams := url.Values{}\n\tif args.Expand != nil {\n\t\tqueryParams.Add(\"$expand\", string(*args.Expand))\n\t}\n\tlocationId, _ := uuid.Parse(\"e2e9d1a6-432d-4062-8870-bfcb8c324ad7\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"6.0-preview.2\", routeValues, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []ProcessWorkItemType\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (obj *Doc) GetContentLibraries(ctx context.Context) (*ContentLibraryList, error) {\n\tresult := &struct {\n\t\tList *ContentLibraryList `json:\"qList\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetContentLibraries\", result)\n\treturn result.List, err\n}", "func (a *Client) GetUniverseTypes(params *GetUniverseTypesParams) (*GetUniverseTypesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetUniverseTypesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get_universe_types\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/universe/types/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetUniverseTypesReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetUniverseTypesOK), nil\n\n}", "func (o *MicrosoftGraphListItem) SetContentType(v AnyOfmicrosoftGraphContentTypeInfo) {\n\to.ContentType = &v\n}", "func (s *Channel) SetContentType(v string) *Channel {\n\ts.ContentType = &v\n\treturn s\n}", "func (o *SoftwarerepositoryCategoryMapper) GetTagTypes() []string {\n\tif o == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn o.TagTypes\n}", "func (_AccessIndexor *AccessIndexorCaller) GetContentTypesLength(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _AccessIndexor.contract.Call(opts, &out, \"getContentTypesLength\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (ts *TypeSet) Types() map[string]Type {\n\tts.RLock()\n\tdefer ts.RUnlock()\n\n\tout := map[string]Type{}\n\tfor k, v := range ts.types {\n\t\tout[k] = v\n\t}\n\treturn out\n}", "func (HubContentType) Values() []HubContentType {\n\treturn []HubContentType{\n\t\t\"Model\",\n\t\t\"Notebook\",\n\t}\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesNisw(contentTypesNisw *string) {\n\to.ContentTypesNisw = contentTypesNisw\n}", "func (o *MicrosoftGraphWorkbookComment) SetContentType(v string) {\n\to.ContentType = &v\n}", "func GetFieldTypes() []types.FieldTypes {\n\tvar fieldTypeArray []types.FieldTypes\n\tfor key := range types.FieldTypesEnum_value {\n\t\tfieldTypeArray = append(fieldTypeArray, types.FieldTypes{Name: key})\n\t}\n\treturn fieldTypeArray\n}", "func (s *AutoMLChannel) SetContentType(v string) *AutoMLChannel {\n\ts.ContentType = &v\n\treturn s\n}", "func NotificationContentType_Values() []string {\n\treturn []string{\n\t\tNotificationContentTypePlainText,\n\t}\n}", "func (c *CreativesListCall) Types(types ...string) *CreativesListCall {\n\tc.urlParams_.SetMulti(\"types\", append([]string{}, types...))\n\treturn c\n}", "func (json Json) getContentType() (contentType string) {\n\treturn json.contentType\n}", "func GetType() ([]Type, error) {\n\tvar types []Type\n\tstmt, err := mysql.DBConn().Prepare(\"select * from types\")\n\tif err != nil {\n\t\treturn types, utils.ServerError\n\t}\n\n\tdefer stmt.Close()\n\trows, err := stmt.Query()\n\tif err != nil {\n\t\treturn types, utils.ServerError\n\t}\n\n\tfor rows.Next() {\n\t\tt := Type{}\n\t\terr := rows.Scan(&t.ID, &t.Name)\n\t\tif err != nil {\n\t\t\treturn types, utils.ServerError\n\t\t}\n\t\ttypes = append(types, t)\n\t}\n\treturn types, nil\n}", "func (d *cephobject) MigrationTypes(contentType ContentType, refresh bool, copySnapshots bool) []migration.Type {\n\treturn nil\n}", "func (o DomainNameEndpointConfigurationOutput) Types() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DomainNameEndpointConfiguration) string { return v.Types }).(pulumi.StringOutput)\n}", "func (o *BranchingModel) GetBranchTypes() []BranchingModelBranchTypes {\n\tif o == nil || o.BranchTypes == nil {\n\t\tvar ret []BranchingModelBranchTypes\n\t\treturn ret\n\t}\n\treturn *o.BranchTypes\n}", "func (s *Style) Types() []TokenType {\n\tdedupe := map[TokenType]bool{}\n\tfor tt := range s.entries {\n\t\tdedupe[tt] = true\n\t}\n\tif s.parent != nil {\n\t\tfor _, tt := range s.parent.Types() {\n\t\t\tdedupe[tt] = true\n\t\t}\n\t}\n\tout := make([]TokenType, 0, len(dedupe))\n\tfor tt := range dedupe {\n\t\tout = append(out, tt)\n\t}\n\treturn out\n}", "func (s *UtteranceBotResponse) SetContentType(v string) *UtteranceBotResponse {\n\ts.ContentType = &v\n\treturn s\n}", "func (a *API) AssetTypes(ctx context.Context) (*AssetTypesResult, error) {\n\tres := &AssetTypesResult{}\n\t_, err := a.get(ctx, assets, nil, res)\n\n\treturn res, err\n}", "func (s *QueryFilters) SetTypes(v []*string) *QueryFilters {\n\ts.Types = v\n\treturn s\n}", "func (m *SiteItemRequestBuilder) ContentTypesById(id string)(*ItemContentTypesContentTypeItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"contentType%2Did\"] = id\n }\n return NewItemContentTypesContentTypeItemRequestBuilderInternal(urlTplParams, m.requestAdapter)\n}", "func (o *GetContentSourcesUsingGETParams) SetContentType(contentType *string) {\n\to.ContentType = contentType\n}", "func (m *TestMod) AllowedTypes() base.MessageType {\n\treturn m.allowedTypes\n}", "func (m *SchemaExtension) GetTargetTypes()([]string) {\n val, err := m.GetBackingStore().Get(\"targetTypes\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesn(contentTypesn *string) {\n\to.ContentTypesn = contentTypesn\n}", "func (me *TContentType) Walk() (err error) {\n\tif fn := WalkHandlers.TContentType; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_TextchoiceContentTypeschema_Text_XsdtString_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_ListchoiceContentTypeschema_List_TxsdContentTypeChoiceList_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_FormattedContentchoiceContentTypeschema_FormattedContent_XsdtString_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_BinarychoiceContentTypeschema_Binary_TBinaryContentType_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_ApplicationchoiceContentTypeschema_Application_TApplicationContentType_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_EmbeddedBinarychoiceContentTypeschema_EmbeddedBinary_TEmbeddedBinaryContentType_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElems_TitlechoiceContentTypeschema_Title_XsdtString_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (s *MetricsSource) SetContentType(v string) *MetricsSource {\n\ts.ContentType = &v\n\treturn s\n}", "func (o *MicrosoftGraphListItem) HasContentType() bool {\n\tif o != nil && o.ContentType != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s *AutoMLJobChannel) SetContentType(v string) *AutoMLJobChannel {\n\ts.ContentType = &v\n\treturn s\n}", "func (cr *ContactReceiver) GetContactTypes() error {\n\terr := database.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstmt, err := database.DB.Prepare(getContactTypesByReceiver)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\tvar ct ContactType\n\tres, err := stmt.Query(cr.ID)\n\tfor res.Next() {\n\t\terr = res.Scan(&ct.ID, &ct.Name, &ct.ShowOnWebsite, &ct.BrandID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcr.ContactTypes = append(cr.ContactTypes, ct)\n\t}\n\tdefer res.Close()\n\treturn err\n}", "func (_BaseContentSpace *BaseContentSpaceCaller) ContentTypesLength(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseContentSpace.contract.Call(opts, &out, \"contentTypesLength\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}" ]
[ "0.77380264", "0.7120515", "0.6951072", "0.683847", "0.6325658", "0.63171864", "0.62789446", "0.61402726", "0.6130467", "0.6012503", "0.5989417", "0.5985794", "0.59765583", "0.58592784", "0.56957906", "0.56474996", "0.5573628", "0.5445044", "0.5442282", "0.54262537", "0.54202455", "0.53830886", "0.5322562", "0.52157044", "0.52118427", "0.5201793", "0.5201748", "0.5186983", "0.5169693", "0.51183057", "0.51110417", "0.5100947", "0.507782", "0.5071021", "0.5056867", "0.50218326", "0.49885827", "0.4945979", "0.49403155", "0.49033895", "0.48936868", "0.4885376", "0.48610204", "0.48594972", "0.48497996", "0.48405424", "0.48319465", "0.48103294", "0.48094308", "0.48085505", "0.47819787", "0.47773618", "0.4770419", "0.47585413", "0.4745482", "0.47426748", "0.4738846", "0.47296554", "0.47095704", "0.470481", "0.46928164", "0.46920532", "0.4680611", "0.4664239", "0.46605065", "0.4660471", "0.46474847", "0.46292517", "0.46251974", "0.46190205", "0.46178302", "0.46144947", "0.46049443", "0.46025896", "0.46010235", "0.45990118", "0.45884725", "0.458654", "0.45862278", "0.4571762", "0.45659468", "0.45529622", "0.45528245", "0.4537807", "0.45362216", "0.45354912", "0.45351994", "0.45338088", "0.45318073", "0.45306662", "0.45194697", "0.4517363", "0.4514074", "0.45019433", "0.4499135", "0.4498523", "0.44984573", "0.44949898", "0.44936714", "0.4488536" ]
0.79392874
0
GetDisplayName gets the displayName property value. The displayable title of the list.
func (m *List) GetDisplayName()(*string) { return m.displayName }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *DeviceClient) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *RoleWithAccess) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (m *DeviceAndAppManagementAssignmentFilter) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *MicrosoftGraphAppIdentity) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *SchemaDefinitionRestDto) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *MicrosoftGraphModifiedProperty) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (u *User) GetDisplayName() string {\n\treturn u.DisplayName\n}", "func (o *MicrosoftGraphEducationSchool) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (s UserSet) DisplayName() string {\n\tres, _ := s.RecordCollection.Get(models.NewFieldName(\"DisplayName\", \"display_name\")).(string)\n\treturn res\n}", "func (o *RoleAssignment) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (m *BrowserSiteList) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *User) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *User) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *Tier) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (m *User) GetDisplayName()(*string) {\n return m.displayName\n}", "func (u *User) GetDisplayName() string {\n\treturn u.displayName\n}", "func (o *MailFolder) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *MicrosoftGraphMailSearchFolder) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (m *List) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (o *MicrosoftGraphEducationUser) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (o *MicrosoftGraphSharedPcConfiguration) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (m *IdentityProviderBase) GetDisplayName()(*string) {\n return m.displayName\n}", "func (o *SubscriptionRegistration) GetDisplayName() (value string, ok bool) {\n\tok = o != nil && o.bitmap_&4 != 0\n\tif ok {\n\t\tvalue = o.displayName\n\t}\n\treturn\n}", "func (m *RPCRegistrationRequest) GetDisplayName() string {\n\tif m != nil && m.DisplayName != nil {\n\t\treturn *m.DisplayName\n\t}\n\treturn \"\"\n}", "func (m *Group) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *RoleDefinition) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *DeviceCategory) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *RelatedContact) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (a *Action) GetDisplayName() string {\n\tif setting.UI.DefaultShowFullName {\n\t\ttrimmedFullName := strings.TrimSpace(a.GetActFullName())\n\t\tif len(trimmedFullName) > 0 {\n\t\t\treturn trimmedFullName\n\t\t}\n\t}\n\treturn a.ShortActUserName()\n}", "func (m *RemoteAssistancePartner) GetDisplayName()(*string) {\n return m.displayName\n}", "func (o *MicrosoftGraphWindows10CompliancePolicy) GetDisplayName() string {\n\tif o == nil || o.DisplayName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DisplayName\n}", "func (m *WorkforceIntegration) GetDisplayName()(*string) {\n return m.displayName\n}", "func (u *User) GetDisplayName() string {\n\tif u.DisplayName != \"\" {\n\t\treturn u.DisplayName\n\t}\n\treturn u.Username\n}", "func (m *IndustryDataRunActivity) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *EducationAssignment) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *MessageRule) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *TelecomExpenseManagementPartner) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *BookingNamedEntity) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *TeamworkTag) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o ContactListTopicOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ContactListTopic) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *ConditionalAccessPolicy) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (d UserData) DisplayName() string {\n\tval := d.ModelData.Get(models.NewFieldName(\"DisplayName\", \"display_name\"))\n\tif !d.Has(models.NewFieldName(\"DisplayName\", \"display_name\")) {\n\t\treturn *new(string)\n\t}\n\treturn val.(string)\n}", "func (c FieldsCollection) DisplayName() *models.Field {\n\treturn c.MustGet(\"DisplayName\")\n}", "func (a *Action) GetDisplayNameTitle() string {\n\tif setting.UI.DefaultShowFullName {\n\t\treturn a.ShortActUserName()\n\t}\n\treturn a.GetActFullName()\n}", "func (o AllowlistCustomAlertRuleResponseOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AllowlistCustomAlertRuleResponse) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *NamedLocation) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *Setting) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *GroupPolicyDefinition) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *AccessPackage) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *IdentityUserFlowAttributeAssignment) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *AccessPackageCatalog) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *DirectorySetting) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *ManagementTemplateStep) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *DeviceManagementConfigurationSettingDefinition) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *CreatePostRequestBody) GetDisplayName()(*string) {\n return m.displayName\n}", "func (m *TemplateParameter) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *ProfileCardAnnotation) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *CloudPcAuditEvent) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *PrintConnector) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *ManagedAppPolicy) GetDisplayName()(*string) {\n return m.displayName\n}", "func (o LookupContactResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupContactResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (u *User) DisplayName() string {\n\tif len(u.FullName) > 0 {\n\t\treturn u.FullName\n\t}\n\treturn u.Name\n}", "func (m *Application) GetDisplayName()(*string) {\n return m.displayName\n}", "func (o DenylistCustomAlertRuleResponseOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DenylistCustomAlertRuleResponse) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o MonitoredResourceDescriptorResponseOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MonitoredResourceDescriptorResponse) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *WorkforceIntegration) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (o UserOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *User) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *BookingBusiness) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o LookupEntryResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupEntryResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *CloudPcConnection) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *SchemaDefinitionRestDto) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (m *RoleDefinition) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (o LogDescriptorResponseOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LogDescriptorResponse) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o LookupIntentResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupIntentResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *EducationAssignment) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (o LookupOrganizationResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOrganizationResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o *DisplayInfo) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (o SourceOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Source) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o LookupPipelineResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupPipelineResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o MonitoredResourceDescriptorOutput) DisplayName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MonitoredResourceDescriptor) *string { return v.DisplayName }).(pulumi.StringPtrOutput)\n}", "func (o *RoleAssignment) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (o UserOutput) DisplayName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *User) pulumi.StringPtrOutput { return v.DisplayName }).(pulumi.StringPtrOutput)\n}", "func (o DatastoreOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Datastore) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (s *Experiment) SetDisplayName(v string) *Experiment {\n\ts.DisplayName = &v\n\treturn s\n}", "func (o ClientOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Client) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *AdministrativeUnit) GetDisplayName()(*string) {\n return m.displayName\n}", "func (o LookupConnectivityTestResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupConnectivityTestResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o ConversationModelOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ConversationModel) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (m *ProgramControl) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o LakeOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Lake) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o ConnectorOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Connector) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o ServicePrincipalOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ServicePrincipal) pulumi.StringOutput { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o LogDescriptorOutput) DisplayName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LogDescriptor) *string { return v.DisplayName }).(pulumi.StringPtrOutput)\n}", "func (m *PaymentTerm) GetDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"displayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o LookupProxyConfigResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupProxyConfigResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}", "func (o *DeviceClient) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (o ScheduledQueryRulesAlertV2Output) DisplayName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScheduledQueryRulesAlertV2) pulumi.StringPtrOutput { return v.DisplayName }).(pulumi.StringPtrOutput)\n}", "func (m *RemoteAssistancePartner) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (s *Trial) SetDisplayName(v string) *Trial {\n\ts.DisplayName = &v\n\treturn s\n}", "func (o LookupClientConnectorServiceResultOutput) DisplayName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupClientConnectorServiceResult) string { return v.DisplayName }).(pulumi.StringOutput)\n}" ]
[ "0.7741837", "0.7733561", "0.74696445", "0.7466271", "0.74494886", "0.7443389", "0.74368083", "0.7429317", "0.7401814", "0.74005044", "0.73881435", "0.73865306", "0.73865306", "0.7367366", "0.7334453", "0.73278743", "0.73046476", "0.72927064", "0.727479", "0.7256103", "0.7253778", "0.72264194", "0.72171676", "0.7202448", "0.7190159", "0.7189942", "0.7188653", "0.71860635", "0.71804476", "0.7167179", "0.71669805", "0.7156371", "0.7152575", "0.70977217", "0.7095738", "0.709168", "0.70711035", "0.70694554", "0.7044781", "0.7041599", "0.7041483", "0.7037661", "0.70190793", "0.70137143", "0.6995211", "0.69807136", "0.69609255", "0.6959646", "0.6948451", "0.69426906", "0.6938619", "0.6928187", "0.69278234", "0.69031054", "0.68859935", "0.68759745", "0.6870766", "0.68683976", "0.68404967", "0.68258405", "0.68212444", "0.68084913", "0.67975485", "0.67929995", "0.6791627", "0.6769298", "0.67669773", "0.6763644", "0.67256206", "0.67189884", "0.66953516", "0.6687927", "0.6662133", "0.6659929", "0.6650593", "0.66394836", "0.66361016", "0.66268826", "0.66252136", "0.66114944", "0.6610825", "0.66049004", "0.6602177", "0.6595578", "0.65955216", "0.65916485", "0.65746367", "0.65688705", "0.6568414", "0.6568287", "0.6567559", "0.6562745", "0.655484", "0.6554218", "0.6550082", "0.6549063", "0.65408725", "0.6538555", "0.65375483", "0.6524655" ]
0.83683056
0
GetDrive gets the drive property value. Only present on document libraries. Allows access to the list as a [drive][] resource with [driveItems][driveItem].
func (m *List) GetDrive()(Driveable) { return m.drive }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *Block) GetDrive(ctx context.Context) (drive dbus.ObjectPath, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceBlock, \"Drive\").Store(&drive)\n\treturn\n}", "func (m *Group) GetDrive()(Driveable) {\n return m.drive\n}", "func (m *User) GetDrive()(Driveable) {\n return m.drive\n}", "func (o *User) GetDrive() Drive {\n\tif o == nil || o.Drive == nil {\n\t\tvar ret Drive\n\t\treturn ret\n\t}\n\treturn *o.Drive\n}", "func (m *Drive) GetDriveType()(*string) {\n return m.driveType\n}", "func GetDrive() (*drive.Service, *oauth2.Token) {\n\ttoken := getToken(GetOAuthConfig())\n\tsrv, err := drive.NewService(context.Background(), option.WithHTTPClient(GetOAuthConfig().Client(context.Background(), token)))\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve Drive client: %v\", err)\n\t}\n\n\treturn srv, token\n}", "func (o *User) GetDrive() AnyOfmicrosoftGraphDrive {\n\tif o == nil || o.Drive == nil {\n\t\tvar ret AnyOfmicrosoftGraphDrive\n\t\treturn ret\n\t}\n\treturn *o.Drive\n}", "func (ref FileView) Drive() resource.ID {\n\treturn ref.drive\n}", "func (repo Repository) Drive(driveID resource.ID) drivestream.DriveReference {\n\treturn Drive{\n\t\tdb: repo.db,\n\t\tdrive: driveID,\n\t}\n}", "func (o *MicrosoftGraphItemReference) GetDriveId() string {\n\tif o == nil || o.DriveId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveId\n}", "func (o *MicrosoftGraphItemReference) GetDriveType() string {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveType\n}", "func (o *StorageFlexUtilVirtualDrive) GetDriveType() string {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveType\n}", "func (a *HyperflexApiService) GetHyperflexDriveList(ctx context.Context) ApiGetHyperflexDriveListRequest {\n\treturn ApiGetHyperflexDriveListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (m *User) GetDrives()([]Driveable) {\n return m.drives\n}", "func (m *GraphBaseServiceClient) Drive()(*i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.DriveRequestBuilder) {\n return i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.NewDriveRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Drive()(*i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.DriveRequestBuilder) {\n return i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.NewDriveRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (device *DCV2Bricklet) GetDriveMode() (mode DriveMode, err error) {\n\tvar buf bytes.Buffer\n\n\tresultBytes, err := device.device.Get(uint8(FunctionGetDriveMode), buf.Bytes())\n\tif err != nil {\n\t\treturn mode, err\n\t}\n\tif len(resultBytes) > 0 {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(resultBytes)\n\n\t\tif header.Length != 9 {\n\t\t\treturn mode, fmt.Errorf(\"Received packet of unexpected size %d, instead of %d\", header.Length, 9)\n\t\t}\n\n\t\tif header.ErrorCode != 0 {\n\t\t\treturn mode, DeviceError(header.ErrorCode)\n\t\t}\n\n\t\tresultBuf := bytes.NewBuffer(resultBytes[8:])\n\t\tbinary.Read(resultBuf, binary.LittleEndian, &mode)\n\n\t}\n\n\treturn mode, nil\n}", "func (m *Group) GetDrives()([]Driveable) {\n return m.drives\n}", "func (o *StorageFlexUtilVirtualDrive) GetVirtualDrive() string {\n\tif o == nil || o.VirtualDrive == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.VirtualDrive\n}", "func (o *StorageFlexFlashVirtualDrive) GetDriveScope() string {\n\tif o == nil || o.DriveScope == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveScope\n}", "func (h *stubDriveHandler) GetDrives() []models.Drive {\n\treturn h.drives\n}", "func (m *List) SetDrive(value Driveable)() {\n m.drive = value\n}", "func (d *portworx) GetDriveSet(n *node.Node) (*torpedovolume.DriveSet, error) {\n\tout, err := d.nodeDriver.RunCommandWithNoRetry(*n, fmt.Sprintf(pxctlCloudDriveInspect, d.getPxctlPath(*n), n.VolDriverNodeID), node.ConnectionOpts{\n\t\tTimeout: crashDriverTimeout,\n\t\tTimeBeforeRetry: defaultRetryInterval,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error when inspecting drive sets for node ID [%s] using PXCTL, Err: %v\", n.VolDriverNodeID, err)\n\t}\n\tvar driveSetInspect torpedovolume.DriveSet\n\terr = json.Unmarshal([]byte(out), &driveSetInspect)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal drive set inspect, Err: %v\", err)\n\t}\n\treturn &driveSetInspect, nil\n}", "func (m *Drive) GetList()(Listable) {\n return m.list\n}", "func (o *StoragePhysicalDisk) GetDriveFirmware() string {\n\tif o == nil || o.DriveFirmware == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveFirmware\n}", "func (o *User) GetDrives() []Drive {\n\tif o == nil || o.Drives == nil {\n\t\tvar ret []Drive\n\t\treturn ret\n\t}\n\treturn o.Drives\n}", "func (o *MicrosoftGraphListItem) GetDriveItem() AnyOfmicrosoftGraphDriveItem {\n\tif o == nil || o.DriveItem == nil {\n\t\tvar ret AnyOfmicrosoftGraphDriveItem\n\t\treturn ret\n\t}\n\treturn *o.DriveItem\n}", "func (o *StoragePhysicalDiskAllOf) GetDriveFirmware() string {\n\tif o == nil || o.DriveFirmware == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveFirmware\n}", "func (o *VirtualizationIweClusterAllOf) GetDriveType() string {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveType\n}", "func (o *User) GetDrives() []MicrosoftGraphDrive {\n\tif o == nil || o.Drives == nil {\n\t\tvar ret []MicrosoftGraphDrive\n\t\treturn ret\n\t}\n\treturn *o.Drives\n}", "func (o *User) GetDriveOk() (*Drive, bool) {\n\tif o == nil || o.Drive == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Drive, true\n}", "func (o *StorageFlexFlashVirtualDrive) GetVirtualDrive() string {\n\tif o == nil || o.VirtualDrive == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.VirtualDrive\n}", "func (o *User) SetDrive(v AnyOfmicrosoftGraphDrive) {\n\to.Drive = &v\n}", "func (m *Group) SetDrive(value Driveable)() {\n m.drive = value\n}", "func (g Graph) GetDrives(w http.ResponseWriter, r *http.Request) {\n\tg.getDrives(w, r, false)\n}", "func (o *Drive) GetSerial(ctx context.Context) (serial string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Serial\").Store(&serial)\n\treturn\n}", "func (g Graph) GetSingleDrive(w http.ResponseWriter, r *http.Request) {\n\tdriveID, _ := url.PathUnescape(chi.URLParam(r, \"driveID\"))\n\tif driveID == \"\" {\n\t\terr := fmt.Errorf(\"no valid space id retrieved\")\n\t\tg.logger.Err(err)\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tg.logger.Info().Str(\"driveID\", driveID).Msg(\"Calling GetSingleDrive\")\n\tctx := r.Context()\n\n\tfilters := []*storageprovider.ListStorageSpacesRequest_Filter{listStorageSpacesIDFilter(driveID)}\n\tres, err := g.ListStorageSpacesWithFilters(ctx, filters, true)\n\tswitch {\n\tcase err != nil:\n\t\tg.logger.Error().Err(err).Msg(ListStorageSpacesTransportErr)\n\t\terrorcode.ServiceNotAvailable.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\tcase res.Status.Code != cs3rpc.Code_CODE_OK:\n\t\tif res.Status.Code == cs3rpc.Code_CODE_NOT_FOUND {\n\t\t\t// the client is doing a lookup for a specific space, therefore we need to return\n\t\t\t// not found to the caller\n\t\t\tg.logger.Error().Str(\"driveID\", driveID).Msg(fmt.Sprintf(NoSpaceFoundMessage, driveID))\n\t\t\terrorcode.ItemNotFound.Render(w, r, http.StatusNotFound, fmt.Sprintf(NoSpaceFoundMessage, driveID))\n\t\t\treturn\n\t\t}\n\t\tg.logger.Error().Err(err).Msg(ListStorageSpacesReturnsErr)\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, res.Status.Message)\n\t\treturn\n\t}\n\n\twdu, err := url.Parse(g.config.Spaces.WebDavBase + g.config.Spaces.WebDavPath)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error parsing url\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tspaces, err := g.formatDrives(ctx, wdu, res.StorageSpaces)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error encoding response\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tswitch num := len(spaces); {\n\tcase num == 0:\n\t\tg.logger.Error().Str(\"driveID\", driveID).Msg(\"no space found\")\n\t\terrorcode.ItemNotFound.Render(w, r, http.StatusNotFound, fmt.Sprintf(NoSpaceFoundMessage, driveID))\n\t\treturn\n\tcase num == 1:\n\t\trender.Status(r, http.StatusOK)\n\t\trender.JSON(w, r, spaces[0])\n\tdefault:\n\t\tg.logger.Error().Int(\"number\", num).Msg(\"expected to find a single space but found more\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, \"expected to find a single space but found more\")\n\t\treturn\n\t}\n}", "func GetDriveState(client *http.Client, token *Token, id int) (*DriveState, error) {\n\tresJson, err := GetRequest(client, token, fmt.Sprintf(DriveStateURL, id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar res DriveStateResponse\n\terr = json.Unmarshal(resJson, &res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &(res.Response), nil\n}", "func (m *User) SetDrive(value Driveable)() {\n m.drive = value\n}", "func (o *User) GetDriveOk() (AnyOfmicrosoftGraphDrive, bool) {\n\tif o == nil || o.Drive == nil {\n\t\tvar ret AnyOfmicrosoftGraphDrive\n\t\treturn ret, false\n\t}\n\treturn *o.Drive, true\n}", "func (o *Drive) GetVendor(ctx context.Context) (vendor string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Vendor\").Store(&vendor)\n\treturn\n}", "func (o *StorageFlexUtilVirtualDrive) GetDriveStatus() string {\n\tif o == nil || o.DriveStatus == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveStatus\n}", "func (o *Drive) GetMedia(ctx context.Context) (media string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Media\").Store(&media)\n\treturn\n}", "func (o *Drive) GetId(ctx context.Context) (id string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Id\").Store(&id)\n\treturn\n}", "func NewDrive()(*Drive) {\n m := &Drive{\n BaseItem: *NewBaseItem(),\n }\n odataTypeValue := \"#microsoft.graph.drive\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func (a *HyperflexApiService) GetHyperflexDriveByMoid(ctx context.Context, moid string) ApiGetHyperflexDriveByMoidRequest {\n\treturn ApiGetHyperflexDriveByMoidRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (o *StorageFlexFlashVirtualDrive) GetDriveStatus() string {\n\tif o == nil || o.DriveStatus == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveStatus\n}", "func (m *Drive) GetRoot()(DriveItemable) {\n return m.root\n}", "func (c *Conn) GetDriveState(id int) (*DriveState, error) {\n\tif c.accessToken == \"\" {\n\t\treturn nil, fmt.Errorf(\"%w\", ErrMissingAccessToken)\n\t}\n\n\ttype response struct {\n\t\tResponse DriveState `json:\"response\"`\n\t}\n\n\tvar respBody response\n\n\terr := c.doRequest(http.MethodGet, fmt.Sprintf(\"/api/1/vehicles/%d/data_request/drive_state\", id), nil, &respBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &respBody.Response, nil\n}", "func (o *Drive) GetCanPowerOff(ctx context.Context) (canPowerOff bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"CanPowerOff\").Store(&canPowerOff)\n\treturn\n}", "func getDriveFile(path string) (*drive.File, error) {\n\tparent, err := getFileById(\"root\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get Drive root directory: %v\", err)\n\t}\n\n\tdirs := strings.Split(path, \"/\")\n\t// Walk through the directories in the path in turn.\n\tfor _, dir := range dirs {\n\t\tif dir == \"\" {\n\t\t\t// The first string in the split is \"\" if the\n\t\t\t// path starts with a '/'.\n\t\t\tcontinue\n\t\t}\n\n\t\tquery := fmt.Sprintf(\"title='%s' and '%s' in parents and trashed=false\",\n\t\t\tdir, parent.Id)\n\t\tfiles := runDriveQuery(query)\n\n\t\tif len(files) == 0 {\n\t\t\treturn nil, fileNotFoundError{\n\t\t\t\tpath: path,\n\t\t\t}\n\t\t} else if len(files) > 1 {\n\t\t\treturn nil, fmt.Errorf(\"%s: multiple files found\", path)\n\t\t} else {\n\t\t\tparent = files[0]\n\t\t}\n\t}\n\treturn parent, nil\n}", "func (m *Drive) GetQuota()(Quotaable) {\n return m.quota\n}", "func (o *User) SetDrive(v Drive) {\n\to.Drive = &v\n}", "func (o *Drive) GetRevision(ctx context.Context) (revision string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Revision\").Store(&revision)\n\treturn\n}", "func (m *SiteItemRequestBuilder) Drive()(*ItemDriveRequestBuilder) {\n return NewItemDriveRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func (o *StoragePhysicalDisk) GetDriveState() string {\n\tif o == nil || o.DriveState == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveState\n}", "func (o *Drive) GetConfiguration(ctx context.Context) (configuration map[string]dbus.Variant, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Configuration\").Store(&configuration)\n\treturn\n}", "func (o *Drive) GetModel(ctx context.Context) (model string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Model\").Store(&model)\n\treturn\n}", "func (o *Drive) GetEjectable(ctx context.Context) (ejectable bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Ejectable\").Store(&ejectable)\n\treturn\n}", "func (o *Drive) GetOptical(ctx context.Context) (optical bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Optical\").Store(&optical)\n\treturn\n}", "func (o *StoragePhysicalDiskAllOf) GetDriveState() string {\n\tif o == nil || o.DriveState == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveState\n}", "func NewDrive(object dbus.BusObject) *Drive {\n\treturn &Drive{object}\n}", "func (v Vehicle) DriveState() (*DriveState, error) {\n\tstateRequest, err := fetchState(\"/drive_state\", v.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn stateRequest.Response.DriveState, nil\n}", "func (m *Drive) GetItems()([]DriveItemable) {\n return m.items\n}", "func (s *GDrive) Type() string {\n\treturn \"gdrive\"\n}", "func (o *Drive) GetWWN(ctx context.Context) (wWN string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"WWN\").Store(&wWN)\n\treturn\n}", "func (g Graph) getDrives(w http.ResponseWriter, r *http.Request, unrestricted bool) {\n\tsanitizedPath := strings.TrimPrefix(r.URL.Path, \"/graph/v1.0/\")\n\t// Parse the request with odata parser\n\todataReq, err := godata.ParseRequest(r.Context(), sanitizedPath, r.URL.Query())\n\tif err != nil {\n\t\tg.logger.Err(err).Interface(\"query\", r.URL.Query()).Msg(\"query error\")\n\t\terrorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tg.logger.Debug().\n\t\tInterface(\"query\", r.URL.Query()).\n\t\tBool(\"unrestricted\", unrestricted).\n\t\tMsg(\"Calling getDrives\")\n\tctx := r.Context()\n\n\tfilters, err := generateCs3Filters(odataReq)\n\tif err != nil {\n\t\tg.logger.Err(err).Interface(\"query\", r.URL.Query()).Msg(\"query error\")\n\t\terrorcode.NotSupported.Render(w, r, http.StatusNotImplemented, err.Error())\n\t\treturn\n\t}\n\tres, err := g.ListStorageSpacesWithFilters(ctx, filters, unrestricted)\n\tswitch {\n\tcase err != nil:\n\t\tg.logger.Error().Err(err).Msg(ListStorageSpacesTransportErr)\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\tcase res.Status.Code != cs3rpc.Code_CODE_OK:\n\t\tif res.Status.Code == cs3rpc.Code_CODE_NOT_FOUND {\n\t\t\t// return an empty list\n\t\t\trender.Status(r, http.StatusOK)\n\t\t\trender.JSON(w, r, &listResponse{})\n\t\t\treturn\n\t\t}\n\t\tg.logger.Error().Err(err).Msg(ListStorageSpacesReturnsErr)\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, res.Status.Message)\n\t\treturn\n\t}\n\n\twdu, err := url.Parse(g.config.Spaces.WebDavBase + g.config.Spaces.WebDavPath)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error parsing url\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tspaces, err := g.formatDrives(ctx, wdu, res.StorageSpaces)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error encoding response as json\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tspaces, err = sortSpaces(odataReq, spaces)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error sorting the spaces list\")\n\t\terrorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\trender.Status(r, http.StatusOK)\n\trender.JSON(w, r, &listResponse{Value: spaces})\n}", "func (m *Drive) GetSystem()(SystemFacetable) {\n return m.system\n}", "func (o *Drive) GetSize(ctx context.Context) (size uint64, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Size\").Store(&size)\n\treturn\n}", "func (o *Drive) GetSortKey(ctx context.Context) (sortKey string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"SortKey\").Store(&sortKey)\n\treturn\n}", "func (d *portworx) GetDriver() (*v1.StorageCluster, error) {\n\t// TODO: Need to implement it for Daemonset deployment as well, right now its only for StorageCluster\n\tstcList, err := pxOperator.ListStorageClusters(d.namespace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed get StorageCluster list from namespace [%s], Err: %v\", d.namespace, err)\n\t}\n\n\tstc, err := pxOperator.GetStorageCluster(stcList.Items[0].Name, stcList.Items[0].Namespace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get StorageCluster [%s] from namespace [%s], Err: %v\", stcList.Items[0].Name, stcList.Items[0].Namespace, err.Error())\n\t}\n\n\treturn stc, nil\n}", "func (m *ItemDriveItemRequestBuilder) Get(ctx context.Context, requestConfiguration *ItemDriveItemRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DriveItemable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.BaseRequestBuilder.RequestAdapter.Send(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateDriveItemFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DriveItemable), nil\n}", "func (o *MicrosoftGraphItemReference) GetDriveTypeOk() (string, bool) {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.DriveType, true\n}", "func (o *Drive) GetConnectionBus(ctx context.Context) (connectionBus string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"ConnectionBus\").Store(&connectionBus)\n\treturn\n}", "func (m *Drive) SetDriveType(value *string)() {\n m.driveType = value\n}", "func getGDriveClient(ctx context.Context, config *oauth2.Config, localConfigPath string, logger *log.Logger) *http.Client {\n\ttokenFile := filepath.Join(localConfigPath, gDriveTokenJSONFile)\n\ttok, err := gDriveTokenFromFile(tokenFile)\n\tif err != nil {\n\t\ttok = getGDriveTokenFromWeb(ctx, config, logger)\n\t\tsaveGDriveToken(tokenFile, tok, logger)\n\t}\n\n\treturn config.Client(ctx, tok)\n}", "func (o *MicrosoftGraphItemReference) SetDriveId(v string) {\n\to.DriveId = &v\n}", "func (obj *Global) GetLogicalDriveStrings(ctx context.Context) ([]*DriveInfo, error) {\n\tresult := &struct {\n\t\tDrives []*DriveInfo `json:\"qDrives\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetLogicalDriveStrings\", result)\n\treturn result.Drives, err\n}", "func (o *VirtualizationIweClusterAllOf) SetDriveType(v string) {\n\to.DriveType = &v\n}", "func (m *ItemSitesSiteItemRequestBuilder) Drive()(*ItemSitesItemDriveRequestBuilder) {\n return NewItemSitesItemDriveRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (o *MicrosoftGraphItemReference) SetDriveType(v string) {\n\to.DriveType = &v\n}", "func OpenDrive() *OpenDriveOptions {\n\treturn &OpenDriveOptions{}\n}", "func (c *FakePortalDocumentClient) Get(ctx context.Context, partitionkey string, id string, options *Options) (*pkg.PortalDocument, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\tif c.err != nil {\n\t\treturn nil, c.err\n\t}\n\n\tportalDocument, exists := c.portalDocuments[id]\n\tif !exists {\n\t\treturn nil, &Error{StatusCode: http.StatusNotFound}\n\t}\n\n\treturn c.decodePortalDocument(portalDocument)\n}", "func (c *Client) GetEndpoint() error {\n\treq, err := http.NewRequest(\"GET\", \"https://drive.amazonaws.com/drive/v1/account/endpoint\", nil)\n\treq.Header.Add(\"Authorization\", \"Bearer \"+c.config.AccessToken)\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.Status != \"200 OK\" {\n\t\treturn errors.New(\"Unsuccessful response for getting endpoint\")\n\t}\n\n\tdec := json.NewDecoder(resp.Body)\n\tvar ep endpointStruct\n\tif err := dec.Decode(&ep); err != nil {\n\t\tpanic(err)\n\t}\n\n\tc.config.ContentUrl = ep.ContentUrl\n\tc.config.MetaDataUrl = ep.MetaDataUrl\n\n\treturn nil\n}", "func (o *Drive) GetRemovable(ctx context.Context) (removable bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Removable\").Store(&removable)\n\treturn\n}", "func (a *HyperflexApiService) GetHyperflexDriveListExecute(r ApiGetHyperflexDriveListRequest) (*HyperflexDriveResponse, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *HyperflexDriveResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"HyperflexApiService.GetHyperflexDriveList\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/hyperflex/Drives\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\tif r.filter != nil {\n\t\tlocalVarQueryParams.Add(\"$filter\", parameterToString(*r.filter, \"\"))\n\t}\n\tif r.orderby != nil {\n\t\tlocalVarQueryParams.Add(\"$orderby\", parameterToString(*r.orderby, \"\"))\n\t}\n\tif r.top != nil {\n\t\tlocalVarQueryParams.Add(\"$top\", parameterToString(*r.top, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"$skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.select_ != nil {\n\t\tlocalVarQueryParams.Add(\"$select\", parameterToString(*r.select_, \"\"))\n\t}\n\tif r.expand != nil {\n\t\tlocalVarQueryParams.Add(\"$expand\", parameterToString(*r.expand, \"\"))\n\t}\n\tif r.apply != nil {\n\t\tlocalVarQueryParams.Add(\"$apply\", parameterToString(*r.apply, \"\"))\n\t}\n\tif r.count != nil {\n\t\tlocalVarQueryParams.Add(\"$count\", parameterToString(*r.count, \"\"))\n\t}\n\tif r.inlinecount != nil {\n\t\tlocalVarQueryParams.Add(\"$inlinecount\", parameterToString(*r.inlinecount, \"\"))\n\t}\n\tif r.at != nil {\n\t\tlocalVarQueryParams.Add(\"at\", parameterToString(*r.at, \"\"))\n\t}\n\tif r.tags != nil {\n\t\tlocalVarQueryParams.Add(\"tags\", parameterToString(*r.tags, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"text/csv\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tvar v Error\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (m *Drive) GetSpecial()([]DriveItemable) {\n return m.special\n}", "func (d *DriveDB) get(key []byte, item interface{}) error {\n\tdata, err := d.db.Get(key, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn decode(data, item)\n}", "func ExportDrive(conn *dbus.Conn, path dbus.ObjectPath, v Driveer) error {\n\treturn conn.ExportSubtreeMethodTable(map[string]interface{}{\n\t\t\"Eject\": v.Eject,\n\t\t\"SetConfiguration\": v.SetConfiguration,\n\t\t\"PowerOff\": v.PowerOff,\n\t}, path, InterfaceDrive)\n}", "func (a *PhonebookAccess1) GetFolder() (string, error) {\n\tv, err := a.GetProperty(\"Folder\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn v.Value().(string), nil\n}", "func (b *Dirs) Get(parentInode uint64, name string) (*wirefs.Dirent, error) {\n\tkey := dirKey(parentInode, name)\n\tbuf := b.b.Get(key)\n\tif buf == nil {\n\t\treturn nil, fuse.ENOENT\n\t}\n\n\tvar de wirefs.Dirent\n\tif err := proto.Unmarshal(buf, &de); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &de, nil\n}", "func (obj *Global) GetLogicalDriveStringsRaw(ctx context.Context) (json.RawMessage, error) {\n\tresult := &struct {\n\t\tDrives json.RawMessage `json:\"qDrives\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetLogicalDriveStrings\", result)\n\treturn result.Drives, err\n}", "func WatchDrive(client *Client, env *util.Env) {\n\tpull := func() {\n\t\tUpdateMenu(client, env)\n\t}\n\tutil.SetInterval(pull, time.Duration(env.CFG.Frequency)*time.Millisecond)\n\tpull()\n}", "func (o *StorageFlexUtilVirtualDrive) GetDriveTypeOk() (*string, bool) {\n\tif o == nil || o.DriveType == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DriveType, true\n}", "func (o *StorageFlexUtilVirtualDrive) SetDriveType(v string) {\n\to.DriveType = &v\n}", "func (db *DriveDb) LookupDrive(ident []byte) DriveModel {\n\tvar model DriveModel\n\n\tfor _, d := range db.Drives {\n\t\t// Skip placeholder entry\n\t\tif strings.HasPrefix(d.Family, \"$Id\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif d.Family == \"DEFAULT\" {\n\t\t\tmodel = d\n\t\t\tcontinue\n\t\t}\n\n\t\tif d.CompiledRegexp.Match(ident) {\n\t\t\tmodel.Family = d.Family\n\t\t\tmodel.ModelRegex = d.ModelRegex\n\t\t\tmodel.FirmwareRegex = d.FirmwareRegex\n\t\t\tmodel.WarningMsg = d.WarningMsg\n\t\t\tmodel.CompiledRegexp = d.CompiledRegexp\n\n\t\t\tfor id, p := range d.Presets {\n\t\t\t\tif _, exists := model.Presets[id]; exists {\n\t\t\t\t\t// Some drives override the conv but don't specify a name, so copy it from default\n\t\t\t\t\tif p.Name == \"\" {\n\t\t\t\t\t\tp.Name = model.Presets[id].Name\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmodel.Presets[id] = AttrConv{Name: p.Name, Conv: p.Conv}\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn model\n}", "func (vc *client) GetFolder(folderPath string) (*object.Folder, error) {\n\tlog.Info(fmt.Sprintf(\"Getting Folder `%s`\", folderPath))\n\n\tfolder, err := vc.finder.Folder(vc.context, folderPath)\n\tif err != nil {\n\t\tlog.Error(err, fmt.Sprintf(\"Error getting Folder `%s`\", folderPath))\n\t\treturn nil, err\n\t}\n\n\treturn folder, nil\n}", "func (o *Drive) GetRotationRate(ctx context.Context) (rotationRate int32, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"RotationRate\").Store(&rotationRate)\n\treturn\n}", "func (o *StorageFlexUtilVirtualDrive) GetVirtualDriveOk() (*string, bool) {\n\tif o == nil || o.VirtualDrive == nil {\n\t\treturn nil, false\n\t}\n\treturn o.VirtualDrive, true\n}", "func (m *Group) SetDrives(value []Driveable)() {\n m.drives = value\n}" ]
[ "0.752509", "0.7201301", "0.7189572", "0.6953924", "0.6819783", "0.6769293", "0.6731472", "0.66618615", "0.64475167", "0.6344764", "0.62929523", "0.6108446", "0.5979537", "0.59536654", "0.59533954", "0.59533954", "0.5950644", "0.59289634", "0.5919691", "0.5914934", "0.58727837", "0.58614016", "0.5853273", "0.58063877", "0.5759239", "0.5758416", "0.57436424", "0.56726915", "0.5670783", "0.565167", "0.56311315", "0.56101346", "0.55522907", "0.54844135", "0.54787785", "0.5457151", "0.5452468", "0.5442821", "0.54427224", "0.5418745", "0.5397032", "0.5389707", "0.53705436", "0.53365797", "0.5324481", "0.52474856", "0.5244638", "0.5229101", "0.5204504", "0.51863736", "0.51784724", "0.516728", "0.5164186", "0.5151046", "0.5136681", "0.51233554", "0.5097034", "0.50905925", "0.5071097", "0.50152254", "0.50119287", "0.49807876", "0.49614117", "0.4950061", "0.49439022", "0.49433175", "0.49013692", "0.48973396", "0.48915872", "0.48713312", "0.4859178", "0.4857685", "0.4841138", "0.4833732", "0.48237687", "0.48180023", "0.47971362", "0.47902197", "0.47851872", "0.47847214", "0.4775776", "0.4769202", "0.47675654", "0.4756815", "0.47502545", "0.47432235", "0.47370827", "0.47281557", "0.47101766", "0.468065", "0.46544757", "0.46524018", "0.46389487", "0.46312544", "0.46141207", "0.46135443", "0.45991832", "0.45990306", "0.45976627", "0.4595486" ]
0.78761816
0
GetFieldDeserializers the deserialization information for the current model
func (m *List) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) { res := m.BaseItem.GetFieldDeserializers() res["columns"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateColumnDefinitionFromDiscriminatorValue , m.SetColumns) res["contentTypes"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateContentTypeFromDiscriminatorValue , m.SetContentTypes) res["displayName"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName) res["drive"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDriveFromDiscriminatorValue , m.SetDrive) res["items"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateListItemFromDiscriminatorValue , m.SetItems) res["list"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateListInfoFromDiscriminatorValue , m.SetList) res["operations"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateRichLongRunningOperationFromDiscriminatorValue , m.SetOperations) res["sharepointIds"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSharepointIdsFromDiscriminatorValue , m.SetSharepointIds) res["subscriptions"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateSubscriptionFromDiscriminatorValue , m.SetSubscriptions) res["system"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSystemFacetFromDiscriminatorValue , m.SetSystem) return res }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *AuthenticationMethod) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n return res\n}", "func (m *IdentityProviderBase) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n return res\n}", "func (m *Artifact) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n return res\n}", "func (m *IdentityCustomUserFlowAttribute) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.IdentityUserFlowAttribute.GetFieldDeserializers()\n return res\n}", "func (m *Store) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"defaultLanguageTag\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDefaultLanguageTag)\n res[\"groups\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateGroupFromDiscriminatorValue , m.SetGroups)\n res[\"languageTags\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetLanguageTags)\n res[\"sets\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateSetFromDiscriminatorValue , m.SetSets)\n return res\n}", "func (m *NamedLocation) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"modifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetModifiedDateTime)\n return res\n}", "func (m *Schema) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"baseType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetBaseType)\n res[\"properties\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreatePropertyFromDiscriminatorValue , m.SetProperties)\n return res\n}", "func (m *RemoteAssistancePartner) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"lastConnectionDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastConnectionDateTime)\n res[\"onboardingStatus\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseRemoteAssistanceOnboardingStatus , m.SetOnboardingStatus)\n res[\"onboardingUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnboardingUrl)\n return res\n}", "func (m *RoleDefinition) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"isBuiltIn\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsBuiltIn)\n res[\"roleAssignments\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateRoleAssignmentFromDiscriminatorValue , m.SetRoleAssignments)\n res[\"rolePermissions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateRolePermissionFromDiscriminatorValue , m.SetRolePermissions)\n return res\n}", "func (m *VppToken) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"appleId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAppleId)\n res[\"automaticallyUpdateApps\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetAutomaticallyUpdateApps)\n res[\"countryOrRegion\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCountryOrRegion)\n res[\"expirationDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetExpirationDateTime)\n res[\"lastModifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastModifiedDateTime)\n res[\"lastSyncDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastSyncDateTime)\n res[\"lastSyncStatus\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseVppTokenSyncStatus , m.SetLastSyncStatus)\n res[\"organizationName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOrganizationName)\n res[\"state\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseVppTokenState , m.SetState)\n res[\"token\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetToken)\n res[\"vppTokenAccountType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseVppTokenAccountType , m.SetVppTokenAccountType)\n return res\n}", "func (m *AuditLogRoot) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"directoryAudits\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryAuditFromDiscriminatorValue , m.SetDirectoryAudits)\n res[\"provisioning\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateProvisioningObjectSummaryFromDiscriminatorValue , m.SetProvisioning)\n res[\"signIns\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateSignInFromDiscriminatorValue , m.SetSignIns)\n return res\n}", "func (m *ItemFacet) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"allowedAudiences\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseAllowedAudiences)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAllowedAudiences(val.(*AllowedAudiences))\n }\n return nil\n }\n res[\"createdBy\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateIdentitySetFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCreatedBy(val.(IdentitySetable))\n }\n return nil\n }\n res[\"createdDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCreatedDateTime(val)\n }\n return nil\n }\n res[\"inference\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateInferenceDataFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetInference(val.(InferenceDataable))\n }\n return nil\n }\n res[\"isSearchable\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsSearchable(val)\n }\n return nil\n }\n res[\"lastModifiedBy\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateIdentitySetFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLastModifiedBy(val.(IdentitySetable))\n }\n return nil\n }\n res[\"lastModifiedDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLastModifiedDateTime(val)\n }\n return nil\n }\n res[\"source\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreatePersonDataSourcesFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSource(val.(PersonDataSourcesable))\n }\n return nil\n }\n return res\n}", "func (m *User) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.DirectoryObject.GetFieldDeserializers()\n res[\"aboutMe\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAboutMe)\n res[\"accountEnabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetAccountEnabled)\n res[\"activities\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateUserActivityFromDiscriminatorValue , m.SetActivities)\n res[\"ageGroup\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAgeGroup)\n res[\"agreementAcceptances\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAgreementAcceptanceFromDiscriminatorValue , m.SetAgreementAcceptances)\n res[\"appRoleAssignments\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAppRoleAssignmentFromDiscriminatorValue , m.SetAppRoleAssignments)\n res[\"assignedLicenses\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAssignedLicenseFromDiscriminatorValue , m.SetAssignedLicenses)\n res[\"assignedPlans\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAssignedPlanFromDiscriminatorValue , m.SetAssignedPlans)\n res[\"authentication\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateAuthenticationFromDiscriminatorValue , m.SetAuthentication)\n res[\"authorizationInfo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateAuthorizationInfoFromDiscriminatorValue , m.SetAuthorizationInfo)\n res[\"birthday\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetBirthday)\n res[\"businessPhones\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetBusinessPhones)\n res[\"calendar\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateCalendarFromDiscriminatorValue , m.SetCalendar)\n res[\"calendarGroups\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateCalendarGroupFromDiscriminatorValue , m.SetCalendarGroups)\n res[\"calendars\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateCalendarFromDiscriminatorValue , m.SetCalendars)\n res[\"calendarView\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEventFromDiscriminatorValue , m.SetCalendarView)\n res[\"chats\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateChatFromDiscriminatorValue , m.SetChats)\n res[\"city\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCity)\n res[\"companyName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCompanyName)\n res[\"consentProvidedForMinor\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetConsentProvidedForMinor)\n res[\"contactFolders\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateContactFolderFromDiscriminatorValue , m.SetContactFolders)\n res[\"contacts\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateContactFromDiscriminatorValue , m.SetContacts)\n res[\"country\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCountry)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"createdObjects\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetCreatedObjects)\n res[\"creationType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCreationType)\n res[\"department\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDepartment)\n res[\"deviceEnrollmentLimit\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetDeviceEnrollmentLimit)\n res[\"deviceManagementTroubleshootingEvents\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDeviceManagementTroubleshootingEventFromDiscriminatorValue , m.SetDeviceManagementTroubleshootingEvents)\n res[\"directReports\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetDirectReports)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"drive\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDriveFromDiscriminatorValue , m.SetDrive)\n res[\"drives\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDriveFromDiscriminatorValue , m.SetDrives)\n res[\"employeeHireDate\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetEmployeeHireDate)\n res[\"employeeId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetEmployeeId)\n res[\"employeeOrgData\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEmployeeOrgDataFromDiscriminatorValue , m.SetEmployeeOrgData)\n res[\"employeeType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetEmployeeType)\n res[\"events\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEventFromDiscriminatorValue , m.SetEvents)\n res[\"extensions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateExtensionFromDiscriminatorValue , m.SetExtensions)\n res[\"externalUserState\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetExternalUserState)\n res[\"externalUserStateChangeDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetExternalUserStateChangeDateTime)\n res[\"faxNumber\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetFaxNumber)\n res[\"followedSites\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateSiteFromDiscriminatorValue , m.SetFollowedSites)\n res[\"givenName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetGivenName)\n res[\"hireDate\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetHireDate)\n res[\"identities\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateObjectIdentityFromDiscriminatorValue , m.SetIdentities)\n res[\"imAddresses\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetImAddresses)\n res[\"inferenceClassification\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateInferenceClassificationFromDiscriminatorValue , m.SetInferenceClassification)\n res[\"insights\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateOfficeGraphInsightsFromDiscriminatorValue , m.SetInsights)\n res[\"interests\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetInterests)\n res[\"isResourceAccount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsResourceAccount)\n res[\"jobTitle\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetJobTitle)\n res[\"joinedTeams\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateTeamFromDiscriminatorValue , m.SetJoinedTeams)\n res[\"lastPasswordChangeDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastPasswordChangeDateTime)\n res[\"legalAgeGroupClassification\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetLegalAgeGroupClassification)\n res[\"licenseAssignmentStates\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateLicenseAssignmentStateFromDiscriminatorValue , m.SetLicenseAssignmentStates)\n res[\"licenseDetails\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateLicenseDetailsFromDiscriminatorValue , m.SetLicenseDetails)\n res[\"mail\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMail)\n res[\"mailboxSettings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateMailboxSettingsFromDiscriminatorValue , m.SetMailboxSettings)\n res[\"mailFolders\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateMailFolderFromDiscriminatorValue , m.SetMailFolders)\n res[\"mailNickname\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMailNickname)\n res[\"managedAppRegistrations\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateManagedAppRegistrationFromDiscriminatorValue , m.SetManagedAppRegistrations)\n res[\"managedDevices\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateManagedDeviceFromDiscriminatorValue , m.SetManagedDevices)\n res[\"manager\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDirectoryObjectFromDiscriminatorValue , m.SetManager)\n res[\"memberOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetMemberOf)\n res[\"messages\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateMessageFromDiscriminatorValue , m.SetMessages)\n res[\"mobilePhone\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMobilePhone)\n res[\"mySite\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMySite)\n res[\"oauth2PermissionGrants\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOAuth2PermissionGrantFromDiscriminatorValue , m.SetOauth2PermissionGrants)\n res[\"officeLocation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOfficeLocation)\n res[\"onenote\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateOnenoteFromDiscriminatorValue , m.SetOnenote)\n res[\"onlineMeetings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOnlineMeetingFromDiscriminatorValue , m.SetOnlineMeetings)\n res[\"onPremisesDistinguishedName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesDistinguishedName)\n res[\"onPremisesDomainName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesDomainName)\n res[\"onPremisesExtensionAttributes\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateOnPremisesExtensionAttributesFromDiscriminatorValue , m.SetOnPremisesExtensionAttributes)\n res[\"onPremisesImmutableId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesImmutableId)\n res[\"onPremisesLastSyncDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetOnPremisesLastSyncDateTime)\n res[\"onPremisesProvisioningErrors\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOnPremisesProvisioningErrorFromDiscriminatorValue , m.SetOnPremisesProvisioningErrors)\n res[\"onPremisesSamAccountName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesSamAccountName)\n res[\"onPremisesSecurityIdentifier\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesSecurityIdentifier)\n res[\"onPremisesSyncEnabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetOnPremisesSyncEnabled)\n res[\"onPremisesUserPrincipalName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesUserPrincipalName)\n res[\"otherMails\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetOtherMails)\n res[\"outlook\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateOutlookUserFromDiscriminatorValue , m.SetOutlook)\n res[\"ownedDevices\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetOwnedDevices)\n res[\"ownedObjects\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetOwnedObjects)\n res[\"passwordPolicies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPasswordPolicies)\n res[\"passwordProfile\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreatePasswordProfileFromDiscriminatorValue , m.SetPasswordProfile)\n res[\"pastProjects\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetPastProjects)\n res[\"people\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreatePersonFromDiscriminatorValue , m.SetPeople)\n res[\"photo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateProfilePhotoFromDiscriminatorValue , m.SetPhoto)\n res[\"photos\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateProfilePhotoFromDiscriminatorValue , m.SetPhotos)\n res[\"planner\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreatePlannerUserFromDiscriminatorValue , m.SetPlanner)\n res[\"postalCode\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPostalCode)\n res[\"preferredDataLocation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPreferredDataLocation)\n res[\"preferredLanguage\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPreferredLanguage)\n res[\"preferredName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPreferredName)\n res[\"presence\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreatePresenceFromDiscriminatorValue , m.SetPresence)\n res[\"provisionedPlans\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateProvisionedPlanFromDiscriminatorValue , m.SetProvisionedPlans)\n res[\"proxyAddresses\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetProxyAddresses)\n res[\"registeredDevices\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetRegisteredDevices)\n res[\"responsibilities\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetResponsibilities)\n res[\"schools\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetSchools)\n res[\"scopedRoleMemberOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateScopedRoleMembershipFromDiscriminatorValue , m.SetScopedRoleMemberOf)\n res[\"securityIdentifier\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSecurityIdentifier)\n res[\"settings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateUserSettingsFromDiscriminatorValue , m.SetSettings)\n res[\"showInAddressList\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetShowInAddressList)\n res[\"signInSessionsValidFromDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetSignInSessionsValidFromDateTime)\n res[\"skills\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetSkills)\n res[\"state\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetState)\n res[\"streetAddress\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetStreetAddress)\n res[\"surname\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSurname)\n res[\"teamwork\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateUserTeamworkFromDiscriminatorValue , m.SetTeamwork)\n res[\"todo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateTodoFromDiscriminatorValue , m.SetTodo)\n res[\"transitiveMemberOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetTransitiveMemberOf)\n res[\"usageLocation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUsageLocation)\n res[\"userPrincipalName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserPrincipalName)\n res[\"userType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserType)\n return res\n}", "func (m *Application) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.DirectoryObject.GetFieldDeserializers()\n res[\"addIns\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAddInFromDiscriminatorValue , m.SetAddIns)\n res[\"api\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateApiApplicationFromDiscriminatorValue , m.SetApi)\n res[\"appId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAppId)\n res[\"applicationTemplateId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetApplicationTemplateId)\n res[\"appRoles\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAppRoleFromDiscriminatorValue , m.SetAppRoles)\n res[\"certification\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateCertificationFromDiscriminatorValue , m.SetCertification)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"createdOnBehalfOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDirectoryObjectFromDiscriminatorValue , m.SetCreatedOnBehalfOf)\n res[\"defaultRedirectUri\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDefaultRedirectUri)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"disabledByMicrosoftStatus\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisabledByMicrosoftStatus)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"extensionProperties\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateExtensionPropertyFromDiscriminatorValue , m.SetExtensionProperties)\n res[\"federatedIdentityCredentials\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateFederatedIdentityCredentialFromDiscriminatorValue , m.SetFederatedIdentityCredentials)\n res[\"groupMembershipClaims\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetGroupMembershipClaims)\n res[\"homeRealmDiscoveryPolicies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateHomeRealmDiscoveryPolicyFromDiscriminatorValue , m.SetHomeRealmDiscoveryPolicies)\n res[\"identifierUris\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetIdentifierUris)\n res[\"info\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateInformationalUrlFromDiscriminatorValue , m.SetInfo)\n res[\"isDeviceOnlyAuthSupported\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsDeviceOnlyAuthSupported)\n res[\"isFallbackPublicClient\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsFallbackPublicClient)\n res[\"keyCredentials\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateKeyCredentialFromDiscriminatorValue , m.SetKeyCredentials)\n res[\"logo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetByteArrayValue(m.SetLogo)\n res[\"notes\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetNotes)\n res[\"oauth2RequirePostResponse\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetOauth2RequirePostResponse)\n res[\"optionalClaims\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateOptionalClaimsFromDiscriminatorValue , m.SetOptionalClaims)\n res[\"owners\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetOwners)\n res[\"parentalControlSettings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateParentalControlSettingsFromDiscriminatorValue , m.SetParentalControlSettings)\n res[\"passwordCredentials\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreatePasswordCredentialFromDiscriminatorValue , m.SetPasswordCredentials)\n res[\"publicClient\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreatePublicClientApplicationFromDiscriminatorValue , m.SetPublicClient)\n res[\"publisherDomain\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPublisherDomain)\n res[\"requiredResourceAccess\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateRequiredResourceAccessFromDiscriminatorValue , m.SetRequiredResourceAccess)\n res[\"samlMetadataUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSamlMetadataUrl)\n res[\"serviceManagementReference\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetServiceManagementReference)\n res[\"signInAudience\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSignInAudience)\n res[\"spa\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSpaApplicationFromDiscriminatorValue , m.SetSpa)\n res[\"tags\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetTags)\n res[\"tokenEncryptionKeyId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetTokenEncryptionKeyId)\n res[\"tokenIssuancePolicies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateTokenIssuancePolicyFromDiscriminatorValue , m.SetTokenIssuancePolicies)\n res[\"tokenLifetimePolicies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateTokenLifetimePolicyFromDiscriminatorValue , m.SetTokenLifetimePolicies)\n res[\"verifiedPublisher\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateVerifiedPublisherFromDiscriminatorValue , m.SetVerifiedPublisher)\n res[\"web\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateWebApplicationFromDiscriminatorValue , m.SetWeb)\n return res\n}", "func (m *Reports) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n return res\n}", "func (m *AttributeSet) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"maxAttributesPerSet\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetMaxAttributesPerSet(val)\n }\n return nil\n }\n return res\n}", "func (m *IosExpeditedCheckinConfiguration) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.AppleExpeditedCheckinConfigurationBase.GetFieldDeserializers()\n return res\n}", "func (m *LabelActionBase) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"name\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetName(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n return res\n}", "func (m *Planner) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"buckets\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreatePlannerBucketFromDiscriminatorValue , m.SetBuckets)\n res[\"plans\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreatePlannerPlanFromDiscriminatorValue , m.SetPlans)\n res[\"tasks\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreatePlannerTaskFromDiscriminatorValue , m.SetTasks)\n return res\n}", "func (m *SocialIdentityProvider) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.IdentityProviderBase.GetFieldDeserializers()\n res[\"clientId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetClientId)\n res[\"clientSecret\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetClientSecret)\n res[\"identityProviderType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetIdentityProviderType)\n return res\n}", "func (m *FileDataConnector) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.IndustryDataConnector.GetFieldDeserializers()\n return res\n}", "func (m *SubCategoryTemplate) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.FilePlanDescriptorTemplate.GetFieldDeserializers()\n return res\n}", "func (m *ChatMessage) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"attachments\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateChatMessageAttachmentFromDiscriminatorValue , m.SetAttachments)\n res[\"body\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateItemBodyFromDiscriminatorValue , m.SetBody)\n res[\"channelIdentity\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateChannelIdentityFromDiscriminatorValue , m.SetChannelIdentity)\n res[\"chatId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetChatId)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"deletedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetDeletedDateTime)\n res[\"etag\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetEtag)\n res[\"eventDetail\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEventMessageDetailFromDiscriminatorValue , m.SetEventDetail)\n res[\"from\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateChatMessageFromIdentitySetFromDiscriminatorValue , m.SetFrom)\n res[\"hostedContents\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateChatMessageHostedContentFromDiscriminatorValue , m.SetHostedContents)\n res[\"importance\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseChatMessageImportance , m.SetImportance)\n res[\"lastEditedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastEditedDateTime)\n res[\"lastModifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastModifiedDateTime)\n res[\"locale\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetLocale)\n res[\"mentions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateChatMessageMentionFromDiscriminatorValue , m.SetMentions)\n res[\"messageType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseChatMessageType , m.SetMessageType)\n res[\"policyViolation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateChatMessagePolicyViolationFromDiscriminatorValue , m.SetPolicyViolation)\n res[\"reactions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateChatMessageReactionFromDiscriminatorValue , m.SetReactions)\n res[\"replies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateChatMessageFromDiscriminatorValue , m.SetReplies)\n res[\"replyToId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetReplyToId)\n res[\"subject\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSubject)\n res[\"summary\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSummary)\n res[\"webUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetWebUrl)\n return res\n}", "func (m *Drive) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.BaseItem.GetFieldDeserializers()\n res[\"bundles\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDriveItemFromDiscriminatorValue , m.SetBundles)\n res[\"driveType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDriveType)\n res[\"following\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDriveItemFromDiscriminatorValue , m.SetFollowing)\n res[\"items\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDriveItemFromDiscriminatorValue , m.SetItems)\n res[\"list\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateListFromDiscriminatorValue , m.SetList)\n res[\"owner\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentitySetFromDiscriminatorValue , m.SetOwner)\n res[\"quota\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateQuotaFromDiscriminatorValue , m.SetQuota)\n res[\"root\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDriveItemFromDiscriminatorValue , m.SetRoot)\n res[\"sharePointIds\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSharepointIdsFromDiscriminatorValue , m.SetSharePointIds)\n res[\"special\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDriveItemFromDiscriminatorValue , m.SetSpecial)\n res[\"system\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSystemFacetFromDiscriminatorValue , m.SetSystem)\n return res\n}", "func (m *AndroidLobApp) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.MobileLobApp.GetFieldDeserializers()\n res[\"minimumSupportedOperatingSystem\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateAndroidMinimumOperatingSystemFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetMinimumSupportedOperatingSystem(val.(AndroidMinimumOperatingSystemable))\n }\n return nil\n }\n res[\"packageId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPackageId(val)\n }\n return nil\n }\n res[\"versionCode\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetVersionCode(val)\n }\n return nil\n }\n res[\"versionName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetVersionName(val)\n }\n return nil\n }\n return res\n}", "func (m *AgreementFile) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.AgreementFileProperties.GetFieldDeserializers()\n res[\"localizations\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAgreementFileLocalizationFromDiscriminatorValue , m.SetLocalizations)\n return res\n}", "func (m *ManagedAppPolicy) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"lastModifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastModifiedDateTime)\n res[\"version\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetVersion)\n return res\n}", "func (m *Malware) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n return res\n}", "func (m *EdgeHomeButtonHidden) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.EdgeHomeButtonConfiguration.GetFieldDeserializers()\n return res\n}", "func (m *Media) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"calleeDevice\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDeviceInfoFromDiscriminatorValue , m.SetCalleeDevice)\n res[\"calleeNetwork\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateNetworkInfoFromDiscriminatorValue , m.SetCalleeNetwork)\n res[\"callerDevice\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDeviceInfoFromDiscriminatorValue , m.SetCallerDevice)\n res[\"callerNetwork\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateNetworkInfoFromDiscriminatorValue , m.SetCallerNetwork)\n res[\"label\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetLabel)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"streams\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateMediaStreamFromDiscriminatorValue , m.SetStreams)\n return res\n}", "func (m *ServiceAnnouncement) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"healthOverviews\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateServiceHealthFromDiscriminatorValue , m.SetHealthOverviews)\n res[\"issues\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateServiceHealthIssueFromDiscriminatorValue , m.SetIssues)\n res[\"messages\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateServiceUpdateMessageFromDiscriminatorValue , m.SetMessages)\n return res\n}", "func (m *DeviceAndAppManagementAssignmentFilter) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"assignmentFilterManagementType\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseAssignmentFilterManagementType)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAssignmentFilterManagementType(val.(*AssignmentFilterManagementType))\n }\n return nil\n }\n res[\"createdDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCreatedDateTime(val)\n }\n return nil\n }\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"lastModifiedDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLastModifiedDateTime(val)\n }\n return nil\n }\n res[\"payloads\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreatePayloadByFilterFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]PayloadByFilterable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(PayloadByFilterable)\n }\n }\n m.SetPayloads(res)\n }\n return nil\n }\n res[\"platform\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseDevicePlatformType)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPlatform(val.(*DevicePlatformType))\n }\n return nil\n }\n res[\"roleScopeTags\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfPrimitiveValues(\"string\")\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]string, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = *(v.(*string))\n }\n }\n m.SetRoleScopeTags(res)\n }\n return nil\n }\n res[\"rule\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetRule(val)\n }\n return nil\n }\n return res\n}", "func (m *ConnectedOrganizationMembers) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.SubjectSet.GetFieldDeserializers()\n res[\"connectedOrganizationId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetConnectedOrganizationId)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n return res\n}", "func (m *ExternalConnection) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"configuration\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateConfigurationFromDiscriminatorValue , m.SetConfiguration)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"groups\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateExternalGroupFromDiscriminatorValue , m.SetGroups)\n res[\"items\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateExternalItemFromDiscriminatorValue , m.SetItems)\n res[\"name\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetName)\n res[\"operations\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateConnectionOperationFromDiscriminatorValue , m.SetOperations)\n res[\"schema\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSchemaFromDiscriminatorValue , m.SetSchema)\n res[\"state\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseConnectionState , m.SetState)\n return res\n}", "func (m *IdentityUserFlowAttributeAssignment) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"isOptional\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsOptional)\n res[\"requiresVerification\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetRequiresVerification)\n res[\"userAttribute\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentityUserFlowAttributeFromDiscriminatorValue , m.SetUserAttribute)\n res[\"userAttributeValues\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateUserAttributeValuesItemFromDiscriminatorValue , m.SetUserAttributeValues)\n res[\"userInputType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseIdentityUserFlowAttributeInputType , m.SetUserInputType)\n return res\n}", "func (m *AadUserConversationMember) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.ConversationMember.GetFieldDeserializers()\n res[\"email\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetEmail)\n res[\"tenantId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetTenantId)\n res[\"user\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateUserFromDiscriminatorValue , m.SetUser)\n res[\"userId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserId)\n return res\n}", "func (m *DirectoryAudit) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"activityDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetActivityDateTime)\n res[\"activityDisplayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetActivityDisplayName)\n res[\"additionalDetails\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateKeyValueFromDiscriminatorValue , m.SetAdditionalDetails)\n res[\"category\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCategory)\n res[\"correlationId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCorrelationId)\n res[\"initiatedBy\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateAuditActivityInitiatorFromDiscriminatorValue , m.SetInitiatedBy)\n res[\"loggedByService\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetLoggedByService)\n res[\"operationType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOperationType)\n res[\"result\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseOperationResult , m.SetResult)\n res[\"resultReason\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetResultReason)\n res[\"targetResources\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateTargetResourceFromDiscriminatorValue , m.SetTargetResources)\n return res\n}", "func (m *KeyValue) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"key\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetKey)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"value\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetValue)\n return res\n}", "func (m *ParentLabelDetails) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"color\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetColor(val)\n }\n return nil\n }\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"id\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetId(val)\n }\n return nil\n }\n res[\"isActive\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsActive(val)\n }\n return nil\n }\n res[\"name\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetName(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n res[\"parent\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateParentLabelDetailsFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetParent(val.(ParentLabelDetailsable))\n }\n return nil\n }\n res[\"sensitivity\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSensitivity(val)\n }\n return nil\n }\n res[\"tooltip\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetTooltip(val)\n }\n return nil\n }\n return res\n}", "func (m *IncomingContext) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"observedParticipantId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetObservedParticipantId)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"onBehalfOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentitySetFromDiscriminatorValue , m.SetOnBehalfOf)\n res[\"sourceParticipantId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSourceParticipantId)\n res[\"transferor\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentitySetFromDiscriminatorValue , m.SetTransferor)\n return res\n}", "func (m *Group) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.DirectoryObject.GetFieldDeserializers()\n res[\"acceptedSenders\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetAcceptedSenders)\n res[\"allowExternalSenders\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetAllowExternalSenders)\n res[\"appRoleAssignments\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAppRoleAssignmentFromDiscriminatorValue , m.SetAppRoleAssignments)\n res[\"assignedLabels\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAssignedLabelFromDiscriminatorValue , m.SetAssignedLabels)\n res[\"assignedLicenses\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAssignedLicenseFromDiscriminatorValue , m.SetAssignedLicenses)\n res[\"autoSubscribeNewMembers\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetAutoSubscribeNewMembers)\n res[\"calendar\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateCalendarFromDiscriminatorValue , m.SetCalendar)\n res[\"calendarView\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEventFromDiscriminatorValue , m.SetCalendarView)\n res[\"classification\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetClassification)\n res[\"conversations\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateConversationFromDiscriminatorValue , m.SetConversations)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"createdOnBehalfOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDirectoryObjectFromDiscriminatorValue , m.SetCreatedOnBehalfOf)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"drive\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDriveFromDiscriminatorValue , m.SetDrive)\n res[\"drives\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDriveFromDiscriminatorValue , m.SetDrives)\n res[\"events\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEventFromDiscriminatorValue , m.SetEvents)\n res[\"expirationDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetExpirationDateTime)\n res[\"extensions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateExtensionFromDiscriminatorValue , m.SetExtensions)\n res[\"groupLifecyclePolicies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateGroupLifecyclePolicyFromDiscriminatorValue , m.SetGroupLifecyclePolicies)\n res[\"groupTypes\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetGroupTypes)\n res[\"hasMembersWithLicenseErrors\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetHasMembersWithLicenseErrors)\n res[\"hideFromAddressLists\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetHideFromAddressLists)\n res[\"hideFromOutlookClients\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetHideFromOutlookClients)\n res[\"isArchived\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsArchived)\n res[\"isAssignableToRole\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsAssignableToRole)\n res[\"isSubscribedByMail\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsSubscribedByMail)\n res[\"licenseProcessingState\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateLicenseProcessingStateFromDiscriminatorValue , m.SetLicenseProcessingState)\n res[\"mail\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMail)\n res[\"mailEnabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetMailEnabled)\n res[\"mailNickname\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMailNickname)\n res[\"memberOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetMemberOf)\n res[\"members\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetMembers)\n res[\"membershipRule\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMembershipRule)\n res[\"membershipRuleProcessingState\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMembershipRuleProcessingState)\n res[\"membersWithLicenseErrors\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetMembersWithLicenseErrors)\n res[\"onenote\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateOnenoteFromDiscriminatorValue , m.SetOnenote)\n res[\"onPremisesDomainName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesDomainName)\n res[\"onPremisesLastSyncDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetOnPremisesLastSyncDateTime)\n res[\"onPremisesNetBiosName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesNetBiosName)\n res[\"onPremisesProvisioningErrors\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOnPremisesProvisioningErrorFromDiscriminatorValue , m.SetOnPremisesProvisioningErrors)\n res[\"onPremisesSamAccountName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesSamAccountName)\n res[\"onPremisesSecurityIdentifier\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesSecurityIdentifier)\n res[\"onPremisesSyncEnabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetOnPremisesSyncEnabled)\n res[\"owners\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetOwners)\n res[\"permissionGrants\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateResourceSpecificPermissionGrantFromDiscriminatorValue , m.SetPermissionGrants)\n res[\"photo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateProfilePhotoFromDiscriminatorValue , m.SetPhoto)\n res[\"photos\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateProfilePhotoFromDiscriminatorValue , m.SetPhotos)\n res[\"planner\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreatePlannerGroupFromDiscriminatorValue , m.SetPlanner)\n res[\"preferredDataLocation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPreferredDataLocation)\n res[\"preferredLanguage\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPreferredLanguage)\n res[\"proxyAddresses\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetProxyAddresses)\n res[\"rejectedSenders\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetRejectedSenders)\n res[\"renewedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetRenewedDateTime)\n res[\"securityEnabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetSecurityEnabled)\n res[\"securityIdentifier\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSecurityIdentifier)\n res[\"settings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateGroupSettingFromDiscriminatorValue , m.SetSettings)\n res[\"sites\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateSiteFromDiscriminatorValue , m.SetSites)\n res[\"team\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateTeamFromDiscriminatorValue , m.SetTeam)\n res[\"theme\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetTheme)\n res[\"threads\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateConversationThreadFromDiscriminatorValue , m.SetThreads)\n res[\"transitiveMemberOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetTransitiveMemberOf)\n res[\"transitiveMembers\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetTransitiveMembers)\n res[\"unseenCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetUnseenCount)\n res[\"visibility\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetVisibility)\n return res\n}", "func (m *IndustryDataRunActivity) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"activity\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateIndustryDataActivityFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetActivity(val.(IndustryDataActivityable))\n }\n return nil\n }\n res[\"blockingError\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.CreatePublicErrorFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetBlockingError(val.(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.PublicErrorable))\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"status\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseIndustryDataActivityStatus)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetStatus(val.(*IndustryDataActivityStatus))\n }\n return nil\n }\n return res\n}", "func (m *WorkbookPivotTable) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"name\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetName)\n res[\"worksheet\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateWorkbookWorksheetFromDiscriminatorValue , m.SetWorksheet)\n return res\n}", "func (m *MediaPrompt) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Prompt.GetFieldDeserializers()\n res[\"mediaInfo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateMediaInfoFromDiscriminatorValue , m.SetMediaInfo)\n return res\n}", "func (m *EdiscoverySearch) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Search.GetFieldDeserializers()\n res[\"additionalSources\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDataSourceFromDiscriminatorValue , m.SetAdditionalSources)\n res[\"addToReviewSetOperation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEdiscoveryAddToReviewSetOperationFromDiscriminatorValue , m.SetAddToReviewSetOperation)\n res[\"custodianSources\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDataSourceFromDiscriminatorValue , m.SetCustodianSources)\n res[\"dataSourceScopes\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseDataSourceScopes , m.SetDataSourceScopes)\n res[\"lastEstimateStatisticsOperation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEdiscoveryEstimateOperationFromDiscriminatorValue , m.SetLastEstimateStatisticsOperation)\n res[\"noncustodialSources\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEdiscoveryNoncustodialDataSourceFromDiscriminatorValue , m.SetNoncustodialSources)\n return res\n}", "func (m *Synchronization) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"jobs\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateSynchronizationJobFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]SynchronizationJobable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(SynchronizationJobable)\n }\n }\n m.SetJobs(res)\n }\n return nil\n }\n res[\"secrets\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateSynchronizationSecretKeyStringValuePairFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]SynchronizationSecretKeyStringValuePairable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(SynchronizationSecretKeyStringValuePairable)\n }\n }\n m.SetSecrets(res)\n }\n return nil\n }\n res[\"templates\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateSynchronizationTemplateFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]SynchronizationTemplateable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(SynchronizationTemplateable)\n }\n }\n m.SetTemplates(res)\n }\n return nil\n }\n return res\n}", "func (m *ThreatAssessmentResult) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"message\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMessage)\n res[\"resultType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseThreatAssessmentResultType , m.SetResultType)\n return res\n}", "func (m *EdgeSearchEngineCustom) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.EdgeSearchEngineBase.GetFieldDeserializers()\n res[\"edgeSearchEngineOpenSearchXmlUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetEdgeSearchEngineOpenSearchXmlUrl)\n return res\n}", "func (m *BookingBusiness) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"address\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreatePhysicalAddressFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAddress(val.(PhysicalAddressable))\n }\n return nil\n }\n res[\"appointments\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingAppointmentFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingAppointmentable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingAppointmentable)\n }\n }\n m.SetAppointments(res)\n }\n return nil\n }\n res[\"businessHours\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingWorkHoursFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingWorkHoursable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingWorkHoursable)\n }\n }\n m.SetBusinessHours(res)\n }\n return nil\n }\n res[\"businessType\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetBusinessType(val)\n }\n return nil\n }\n res[\"calendarView\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingAppointmentFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingAppointmentable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingAppointmentable)\n }\n }\n m.SetCalendarView(res)\n }\n return nil\n }\n res[\"customers\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingCustomerBaseFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingCustomerBaseable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingCustomerBaseable)\n }\n }\n m.SetCustomers(res)\n }\n return nil\n }\n res[\"customQuestions\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingCustomQuestionFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingCustomQuestionable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingCustomQuestionable)\n }\n }\n m.SetCustomQuestions(res)\n }\n return nil\n }\n res[\"defaultCurrencyIso\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDefaultCurrencyIso(val)\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"email\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetEmail(val)\n }\n return nil\n }\n res[\"isPublished\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsPublished(val)\n }\n return nil\n }\n res[\"languageTag\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLanguageTag(val)\n }\n return nil\n }\n res[\"phone\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPhone(val)\n }\n return nil\n }\n res[\"publicUrl\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPublicUrl(val)\n }\n return nil\n }\n res[\"schedulingPolicy\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateBookingSchedulingPolicyFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSchedulingPolicy(val.(BookingSchedulingPolicyable))\n }\n return nil\n }\n res[\"services\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingServiceFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingServiceable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingServiceable)\n }\n }\n m.SetServices(res)\n }\n return nil\n }\n res[\"staffMembers\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingStaffMemberBaseFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingStaffMemberBaseable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingStaffMemberBaseable)\n }\n }\n m.SetStaffMembers(res)\n }\n return nil\n }\n res[\"webSiteUrl\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetWebSiteUrl(val)\n }\n return nil\n }\n return res\n}", "func (m *FileAssessmentRequest) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.ThreatAssessmentRequest.GetFieldDeserializers()\n res[\"contentData\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetContentData)\n res[\"fileName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetFileName)\n return res\n}", "func (m *AuthenticationContext) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"detail\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseAuthenticationContextDetail)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDetail(val.(*AuthenticationContextDetail))\n }\n return nil\n }\n res[\"id\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetId(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n return res\n}", "func (m *RelatedContact) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"accessConsent\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAccessConsent(val)\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"emailAddress\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetEmailAddress(val)\n }\n return nil\n }\n res[\"mobilePhone\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetMobilePhone(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n res[\"relationship\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseContactRelationship)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetRelationship(val.(*ContactRelationship))\n }\n return nil\n }\n return res\n}", "func (m *MessageRule) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"actions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateMessageRuleActionsFromDiscriminatorValue , m.SetActions)\n res[\"conditions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateMessageRulePredicatesFromDiscriminatorValue , m.SetConditions)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"exceptions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateMessageRulePredicatesFromDiscriminatorValue , m.SetExceptions)\n res[\"hasError\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetHasError)\n res[\"isEnabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsEnabled)\n res[\"isReadOnly\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsReadOnly)\n res[\"sequence\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetSequence)\n return res\n}", "func (m *WindowsInformationProtectionAppLearningSummary) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"applicationName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetApplicationName)\n res[\"applicationType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseApplicationType , m.SetApplicationType)\n res[\"deviceCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetDeviceCount)\n return res\n}", "func (m *ManagementTemplateStep) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"acceptedVersion\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateManagementTemplateStepVersionFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAcceptedVersion(val.(ManagementTemplateStepVersionable))\n }\n return nil\n }\n res[\"category\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseManagementCategory)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCategory(val.(*ManagementCategory))\n }\n return nil\n }\n res[\"createdByUserId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCreatedByUserId(val)\n }\n return nil\n }\n res[\"createdDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCreatedDateTime(val)\n }\n return nil\n }\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"lastActionByUserId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLastActionByUserId(val)\n }\n return nil\n }\n res[\"lastActionDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLastActionDateTime(val)\n }\n return nil\n }\n res[\"managementTemplate\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateManagementTemplateFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetManagementTemplate(val.(ManagementTemplateable))\n }\n return nil\n }\n res[\"portalLink\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.CreateActionUrlFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPortalLink(val.(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.ActionUrlable))\n }\n return nil\n }\n res[\"priority\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPriority(val)\n }\n return nil\n }\n res[\"versions\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateManagementTemplateStepVersionFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]ManagementTemplateStepVersionable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(ManagementTemplateStepVersionable)\n }\n }\n m.SetVersions(res)\n }\n return nil\n }\n return res\n}", "func (m *ApplicationCollectionResponse) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.BaseCollectionPaginationCountResponse.GetFieldDeserializers()\n res[\"value\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateApplicationFromDiscriminatorValue , m.SetValue)\n return res\n}", "func (m *OutlookUser) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"masterCategories\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOutlookCategoryFromDiscriminatorValue , m.SetMasterCategories)\n return res\n}", "func (m *PrintConnector) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"appVersion\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAppVersion(val)\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"fullyQualifiedDomainName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetFullyQualifiedDomainName(val)\n }\n return nil\n }\n res[\"location\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreatePrinterLocationFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLocation(val.(PrinterLocationable))\n }\n return nil\n }\n res[\"operatingSystem\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOperatingSystem(val)\n }\n return nil\n }\n res[\"registeredDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetRegisteredDateTime(val)\n }\n return nil\n }\n return res\n}", "func (m *ManagedDeviceOverview) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"deviceExchangeAccessStateSummary\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDeviceExchangeAccessStateSummaryFromDiscriminatorValue , m.SetDeviceExchangeAccessStateSummary)\n res[\"deviceOperatingSystemSummary\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDeviceOperatingSystemSummaryFromDiscriminatorValue , m.SetDeviceOperatingSystemSummary)\n res[\"dualEnrolledDeviceCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetDualEnrolledDeviceCount)\n res[\"enrolledDeviceCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetEnrolledDeviceCount)\n res[\"mdmEnrolledCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetMdmEnrolledCount)\n return res\n}", "func (m *AttachmentItem) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"attachmentType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseAttachmentType , m.SetAttachmentType)\n res[\"contentId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetContentId)\n res[\"contentType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetContentType)\n res[\"isInline\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsInline)\n res[\"name\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetName)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"size\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt64Value(m.SetSize)\n return res\n}", "func (m *TargetManager) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.SubjectSet.GetFieldDeserializers()\n res[\"managerLevel\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetManagerLevel)\n return res\n}", "func (m *TeamworkConversationIdentity) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Identity.GetFieldDeserializers()\n res[\"conversationIdentityType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseTeamworkConversationIdentityType , m.SetConversationIdentityType)\n return res\n}", "func (m *SchemaExtension) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"owner\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOwner(val)\n }\n return nil\n }\n res[\"properties\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateExtensionSchemaPropertyFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]ExtensionSchemaPropertyable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(ExtensionSchemaPropertyable)\n }\n }\n m.SetProperties(res)\n }\n return nil\n }\n res[\"status\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetStatus(val)\n }\n return nil\n }\n res[\"targetTypes\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfPrimitiveValues(\"string\")\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]string, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = *(v.(*string))\n }\n }\n m.SetTargetTypes(res)\n }\n return nil\n }\n return res\n}", "func (m *AndroidCustomConfiguration) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.DeviceConfiguration.GetFieldDeserializers()\n res[\"omaSettings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOmaSettingFromDiscriminatorValue , m.SetOmaSettings)\n return res\n}", "func (m *AccessReviewSet) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"definitions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAccessReviewScheduleDefinitionFromDiscriminatorValue , m.SetDefinitions)\n res[\"historyDefinitions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAccessReviewHistoryDefinitionFromDiscriminatorValue , m.SetHistoryDefinitions)\n return res\n}", "func (m *AuthenticationListener) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"priority\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPriority(val)\n }\n return nil\n }\n res[\"sourceFilter\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateAuthenticationSourceFilterFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSourceFilter(val.(AuthenticationSourceFilterable))\n }\n return nil\n }\n return res\n}", "func (m *Vulnerability) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"activeExploitsObserved\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetActiveExploitsObserved(val)\n }\n return nil\n }\n res[\"articles\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateArticleFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]Articleable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(Articleable)\n }\n }\n m.SetArticles(res)\n }\n return nil\n }\n res[\"commonWeaknessEnumerationIds\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfPrimitiveValues(\"string\")\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]string, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = *(v.(*string))\n }\n }\n m.SetCommonWeaknessEnumerationIds(res)\n }\n return nil\n }\n res[\"components\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateVulnerabilityComponentFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]VulnerabilityComponentable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(VulnerabilityComponentable)\n }\n }\n m.SetComponents(res)\n }\n return nil\n }\n res[\"createdDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCreatedDateTime(val)\n }\n return nil\n }\n res[\"cvss2Summary\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateCvssSummaryFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCvss2Summary(val.(CvssSummaryable))\n }\n return nil\n }\n res[\"cvss3Summary\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateCvssSummaryFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCvss3Summary(val.(CvssSummaryable))\n }\n return nil\n }\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateFormattedContentFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val.(FormattedContentable))\n }\n return nil\n }\n res[\"exploits\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateHyperlinkFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]Hyperlinkable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(Hyperlinkable)\n }\n }\n m.SetExploits(res)\n }\n return nil\n }\n res[\"exploitsAvailable\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetExploitsAvailable(val)\n }\n return nil\n }\n res[\"hasChatter\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetHasChatter(val)\n }\n return nil\n }\n res[\"lastModifiedDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLastModifiedDateTime(val)\n }\n return nil\n }\n res[\"priorityScore\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPriorityScore(val)\n }\n return nil\n }\n res[\"publishedDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPublishedDateTime(val)\n }\n return nil\n }\n res[\"references\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateHyperlinkFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]Hyperlinkable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(Hyperlinkable)\n }\n }\n m.SetReferences(res)\n }\n return nil\n }\n res[\"remediation\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateFormattedContentFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetRemediation(val.(FormattedContentable))\n }\n return nil\n }\n res[\"severity\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseVulnerabilitySeverity)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSeverity(val.(*VulnerabilitySeverity))\n }\n return nil\n }\n return res\n}", "func (m *AccessPackageCatalog) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"accessPackages\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAccessPackageFromDiscriminatorValue , m.SetAccessPackages)\n res[\"catalogType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseAccessPackageCatalogType , m.SetCatalogType)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"isExternallyVisible\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsExternallyVisible)\n res[\"modifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetModifiedDateTime)\n res[\"state\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseAccessPackageCatalogState , m.SetState)\n return res\n}", "func (m *UserSettings) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"contributionToContentDiscoveryAsOrganizationDisabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetContributionToContentDiscoveryAsOrganizationDisabled)\n res[\"contributionToContentDiscoveryDisabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetContributionToContentDiscoveryDisabled)\n res[\"shiftPreferences\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateShiftPreferencesFromDiscriminatorValue , m.SetShiftPreferences)\n return res\n}", "func (m *SectionGroup) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.OnenoteEntityHierarchyModel.GetFieldDeserializers()\n res[\"parentNotebook\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateNotebookFromDiscriminatorValue , m.SetParentNotebook)\n res[\"parentSectionGroup\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSectionGroupFromDiscriminatorValue , m.SetParentSectionGroup)\n res[\"sectionGroups\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateSectionGroupFromDiscriminatorValue , m.SetSectionGroups)\n res[\"sectionGroupsUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSectionGroupsUrl)\n res[\"sections\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOnenoteSectionFromDiscriminatorValue , m.SetSections)\n res[\"sectionsUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSectionsUrl)\n return res\n}", "func (m *DiscoveredSensitiveType) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"classificationAttributes\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateClassificationAttributeFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]ClassificationAttributeable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(ClassificationAttributeable)\n }\n }\n m.SetClassificationAttributes(res)\n }\n return nil\n }\n res[\"confidence\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetConfidence(val)\n }\n return nil\n }\n res[\"count\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCount(val)\n }\n return nil\n }\n res[\"id\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetUUIDValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetId(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n return res\n}", "func (m *DomainCollectionResponse) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.BaseCollectionPaginationCountResponse.GetFieldDeserializers()\n res[\"value\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDomainFromDiscriminatorValue , m.SetValue)\n return res\n}", "func (m *CreatePostRequestBody) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"certificateSigningRequest\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreatePrintCertificateSigningRequestFromDiscriminatorValue , m.SetCertificateSigningRequest)\n res[\"connectorId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetConnectorId)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"hasPhysicalDevice\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetHasPhysicalDevice)\n res[\"manufacturer\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetManufacturer)\n res[\"model\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetModel)\n res[\"physicalDeviceId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPhysicalDeviceId)\n return res\n}", "func (m *BookingNamedEntity) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n return res\n}", "func (m *ApplicationSignInDetailedSummary) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"aggregatedEventDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAggregatedEventDateTime(val)\n }\n return nil\n }\n res[\"appDisplayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAppDisplayName(val)\n }\n return nil\n }\n res[\"appId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAppId(val)\n }\n return nil\n }\n res[\"signInCount\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt64Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSignInCount(val)\n }\n return nil\n }\n res[\"status\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateSignInStatusFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetStatus(val.(SignInStatusable))\n }\n return nil\n }\n return res\n}", "func (m *MicrosoftAuthenticatorAuthenticationMethodConfiguration) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.AuthenticationMethodConfiguration.GetFieldDeserializers()\n res[\"featureSettings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateMicrosoftAuthenticatorFeatureSettingsFromDiscriminatorValue , m.SetFeatureSettings)\n res[\"includeTargets\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateMicrosoftAuthenticatorAuthenticationMethodTargetFromDiscriminatorValue , m.SetIncludeTargets)\n return res\n}", "func (m *ExternalActivity) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"performedBy\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateIdentityFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPerformedBy(val.(Identityable))\n }\n return nil\n }\n res[\"startDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetStartDateTime(val)\n }\n return nil\n }\n res[\"type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseExternalActivityType)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetTypeEscaped(val.(*ExternalActivityType))\n }\n return nil\n }\n return res\n}", "func (m *WorkbookOperation) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"error\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateWorkbookOperationErrorFromDiscriminatorValue , m.SetError)\n res[\"resourceLocation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetResourceLocation)\n res[\"status\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseWorkbookOperationStatus , m.SetStatus)\n return res\n}", "func (m *DeviceCategory) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n return res\n}", "func (m *AccessPackage) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"accessPackagesIncompatibleWith\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAccessPackageFromDiscriminatorValue , m.SetAccessPackagesIncompatibleWith)\n res[\"assignmentPolicies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAccessPackageAssignmentPolicyFromDiscriminatorValue , m.SetAssignmentPolicies)\n res[\"catalog\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateAccessPackageCatalogFromDiscriminatorValue , m.SetCatalog)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"incompatibleAccessPackages\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAccessPackageFromDiscriminatorValue , m.SetIncompatibleAccessPackages)\n res[\"incompatibleGroups\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateGroupFromDiscriminatorValue , m.SetIncompatibleGroups)\n res[\"isHidden\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsHidden)\n res[\"modifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetModifiedDateTime)\n return res\n}", "func (m *MessageSecurityStateCollectionResponse) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.BaseCollectionPaginationCountResponse.GetFieldDeserializers()\n res[\"value\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateMessageSecurityStateFromDiscriminatorValue , m.SetValue)\n return res\n}", "func (m *RecurrencePattern) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"dayOfMonth\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetDayOfMonth)\n res[\"daysOfWeek\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfEnumValues(ParseDayOfWeek , m.SetDaysOfWeek)\n res[\"firstDayOfWeek\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseDayOfWeek , m.SetFirstDayOfWeek)\n res[\"index\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseWeekIndex , m.SetIndex)\n res[\"interval\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetInterval)\n res[\"month\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetMonth)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseRecurrencePatternType , m.SetType)\n return res\n}", "func (m *DeviceManagementSettingXmlConstraint) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.DeviceManagementConstraint.GetFieldDeserializers()\n return res\n}", "func (m *TeamworkApplicationIdentity) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Identity.GetFieldDeserializers()\n res[\"applicationIdentityType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseTeamworkApplicationIdentityType , m.SetApplicationIdentityType)\n return res\n}", "func (m *TeamSummary) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"guestsCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetGuestsCount)\n res[\"membersCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetMembersCount)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"ownersCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetOwnersCount)\n return res\n}", "func (m *AgreementAcceptance) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"agreementFileId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAgreementFileId)\n res[\"agreementId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAgreementId)\n res[\"deviceDisplayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDeviceDisplayName)\n res[\"deviceId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDeviceId)\n res[\"deviceOSType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDeviceOSType)\n res[\"deviceOSVersion\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDeviceOSVersion)\n res[\"expirationDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetExpirationDateTime)\n res[\"recordedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetRecordedDateTime)\n res[\"state\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseAgreementAcceptanceState , m.SetState)\n res[\"userDisplayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserDisplayName)\n res[\"userEmail\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserEmail)\n res[\"userId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserId)\n res[\"userPrincipalName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserPrincipalName)\n return res\n}", "func (m *EducationAssignment) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"addedStudentAction\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseEducationAddedStudentAction , m.SetAddedStudentAction)\n res[\"addToCalendarAction\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseEducationAddToCalendarOptions , m.SetAddToCalendarAction)\n res[\"allowLateSubmissions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetAllowLateSubmissions)\n res[\"allowStudentsToAddResourcesToSubmission\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetAllowStudentsToAddResourcesToSubmission)\n res[\"assignDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetAssignDateTime)\n res[\"assignedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetAssignedDateTime)\n res[\"assignTo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEducationAssignmentRecipientFromDiscriminatorValue , m.SetAssignTo)\n res[\"categories\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEducationCategoryFromDiscriminatorValue , m.SetCategories)\n res[\"classId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetClassId)\n res[\"closeDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCloseDateTime)\n res[\"createdBy\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentitySetFromDiscriminatorValue , m.SetCreatedBy)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"dueDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetDueDateTime)\n res[\"feedbackResourcesFolderUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetFeedbackResourcesFolderUrl)\n res[\"grading\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEducationAssignmentGradeTypeFromDiscriminatorValue , m.SetGrading)\n res[\"instructions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEducationItemBodyFromDiscriminatorValue , m.SetInstructions)\n res[\"lastModifiedBy\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentitySetFromDiscriminatorValue , m.SetLastModifiedBy)\n res[\"lastModifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastModifiedDateTime)\n res[\"notificationChannelUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetNotificationChannelUrl)\n res[\"resources\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEducationAssignmentResourceFromDiscriminatorValue , m.SetResources)\n res[\"resourcesFolderUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetResourcesFolderUrl)\n res[\"rubric\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEducationRubricFromDiscriminatorValue , m.SetRubric)\n res[\"status\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseEducationAssignmentStatus , m.SetStatus)\n res[\"submissions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEducationSubmissionFromDiscriminatorValue , m.SetSubmissions)\n res[\"webUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetWebUrl)\n return res\n}", "func (m *OnlineMeetingInfo) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"conferenceId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetConferenceId(val)\n }\n return nil\n }\n res[\"joinUrl\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetJoinUrl(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n res[\"phones\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreatePhoneFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]Phoneable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(Phoneable)\n }\n }\n m.SetPhones(res)\n }\n return nil\n }\n res[\"quickDial\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetQuickDial(val)\n }\n return nil\n }\n res[\"tollFreeNumbers\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfPrimitiveValues(\"string\")\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]string, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = *(v.(*string))\n }\n }\n m.SetTollFreeNumbers(res)\n }\n return nil\n }\n res[\"tollNumber\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetTollNumber(val)\n }\n return nil\n }\n return res\n}", "func (m *ThreatAssessmentRequest) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"category\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseThreatCategory , m.SetCategory)\n res[\"contentType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseThreatAssessmentContentType , m.SetContentType)\n res[\"createdBy\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentitySetFromDiscriminatorValue , m.SetCreatedBy)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"expectedAssessment\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseThreatExpectedAssessment , m.SetExpectedAssessment)\n res[\"requestSource\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseThreatAssessmentRequestSource , m.SetRequestSource)\n res[\"results\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateThreatAssessmentResultFromDiscriminatorValue , m.SetResults)\n res[\"status\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseThreatAssessmentStatus , m.SetStatus)\n return res\n}", "func (m *SharePostRequestBody) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"endDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetEndDateTime)\n res[\"notifyTeam\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetNotifyTeam)\n res[\"startDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetStartDateTime)\n return res\n}", "func (m *ZebraFotaArtifact) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"boardSupportPackageVersion\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetBoardSupportPackageVersion(val)\n }\n return nil\n }\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"deviceModel\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDeviceModel(val)\n }\n return nil\n }\n res[\"osVersion\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOsVersion(val)\n }\n return nil\n }\n res[\"patchVersion\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPatchVersion(val)\n }\n return nil\n }\n res[\"releaseNotesUrl\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetReleaseNotesUrl(val)\n }\n return nil\n }\n return res\n}", "func (m *Setting) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"jsonValue\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetJsonValue(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n res[\"overwriteAllowed\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOverwriteAllowed(val)\n }\n return nil\n }\n res[\"settingId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSettingId(val)\n }\n return nil\n }\n res[\"valueType\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseManagementParameterValueType)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetValueType(val.(*ManagementParameterValueType))\n }\n return nil\n }\n return res\n}", "func (m *ActionResultPart) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"error\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreatePublicErrorFromDiscriminatorValue , m.SetError)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n return res\n}", "func (m *EventMessageDetail) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n return res\n}", "func (m *SearchBucket) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"aggregationFilterToken\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAggregationFilterToken)\n res[\"count\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetCount)\n res[\"key\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetKey)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n return res\n}", "func (m *InternalDomainFederation) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.SamlOrWsFedProvider.GetFieldDeserializers()\n res[\"activeSignInUri\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetActiveSignInUri(val)\n }\n return nil\n }\n res[\"federatedIdpMfaBehavior\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseFederatedIdpMfaBehavior)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetFederatedIdpMfaBehavior(val.(*FederatedIdpMfaBehavior))\n }\n return nil\n }\n res[\"isSignedAuthenticationRequestRequired\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsSignedAuthenticationRequestRequired(val)\n }\n return nil\n }\n res[\"nextSigningCertificate\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetNextSigningCertificate(val)\n }\n return nil\n }\n res[\"promptLoginBehavior\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParsePromptLoginBehavior)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPromptLoginBehavior(val.(*PromptLoginBehavior))\n }\n return nil\n }\n res[\"signingCertificateUpdateStatus\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateSigningCertificateUpdateStatusFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSigningCertificateUpdateStatus(val.(SigningCertificateUpdateStatusable))\n }\n return nil\n }\n res[\"signOutUri\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSignOutUri(val)\n }\n return nil\n }\n return res\n}", "func (m *VirtualEndpoint) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"auditEvents\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcAuditEventFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcAuditEventable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcAuditEventable)\n }\n }\n m.SetAuditEvents(res)\n }\n return nil\n }\n res[\"bulkActions\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcBulkActionFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcBulkActionable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcBulkActionable)\n }\n }\n m.SetBulkActions(res)\n }\n return nil\n }\n res[\"cloudPCs\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPCFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPCable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPCable)\n }\n }\n m.SetCloudPCs(res)\n }\n return nil\n }\n res[\"crossCloudGovernmentOrganizationMapping\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateCloudPcCrossCloudGovernmentOrganizationMappingFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCrossCloudGovernmentOrganizationMapping(val.(CloudPcCrossCloudGovernmentOrganizationMappingable))\n }\n return nil\n }\n res[\"deviceImages\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcDeviceImageFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcDeviceImageable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcDeviceImageable)\n }\n }\n m.SetDeviceImages(res)\n }\n return nil\n }\n res[\"externalPartnerSettings\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcExternalPartnerSettingFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcExternalPartnerSettingable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcExternalPartnerSettingable)\n }\n }\n m.SetExternalPartnerSettings(res)\n }\n return nil\n }\n res[\"frontLineServicePlans\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcFrontLineServicePlanFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcFrontLineServicePlanable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcFrontLineServicePlanable)\n }\n }\n m.SetFrontLineServicePlans(res)\n }\n return nil\n }\n res[\"galleryImages\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcGalleryImageFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcGalleryImageable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcGalleryImageable)\n }\n }\n m.SetGalleryImages(res)\n }\n return nil\n }\n res[\"onPremisesConnections\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcOnPremisesConnectionFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcOnPremisesConnectionable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcOnPremisesConnectionable)\n }\n }\n m.SetOnPremisesConnections(res)\n }\n return nil\n }\n res[\"organizationSettings\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateCloudPcOrganizationSettingsFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOrganizationSettings(val.(CloudPcOrganizationSettingsable))\n }\n return nil\n }\n res[\"provisioningPolicies\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcProvisioningPolicyFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcProvisioningPolicyable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcProvisioningPolicyable)\n }\n }\n m.SetProvisioningPolicies(res)\n }\n return nil\n }\n res[\"reports\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateCloudPcReportsFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetReports(val.(CloudPcReportsable))\n }\n return nil\n }\n res[\"servicePlans\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcServicePlanFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcServicePlanable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcServicePlanable)\n }\n }\n m.SetServicePlans(res)\n }\n return nil\n }\n res[\"sharedUseServicePlans\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcSharedUseServicePlanFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcSharedUseServicePlanable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcSharedUseServicePlanable)\n }\n }\n m.SetSharedUseServicePlans(res)\n }\n return nil\n }\n res[\"snapshots\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcSnapshotFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcSnapshotable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcSnapshotable)\n }\n }\n m.SetSnapshots(res)\n }\n return nil\n }\n res[\"supportedRegions\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcSupportedRegionFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcSupportedRegionable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcSupportedRegionable)\n }\n }\n m.SetSupportedRegions(res)\n }\n return nil\n }\n res[\"userSettings\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcUserSettingFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcUserSettingable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcUserSettingable)\n }\n }\n m.SetUserSettings(res)\n }\n return nil\n }\n return res\n}", "func (m *RetentionLabelSettings) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"isContentUpdateAllowed\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsContentUpdateAllowed(val)\n }\n return nil\n }\n res[\"isDeleteAllowed\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsDeleteAllowed(val)\n }\n return nil\n }\n res[\"isLabelUpdateAllowed\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsLabelUpdateAllowed(val)\n }\n return nil\n }\n res[\"isMetadataUpdateAllowed\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsMetadataUpdateAllowed(val)\n }\n return nil\n }\n res[\"isRecordLocked\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsRecordLocked(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n return res\n}", "func (m *WorkforceIntegration) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.ChangeTrackedEntity.GetFieldDeserializers()\n res[\"apiVersion\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetApiVersion)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"encryption\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateWorkforceIntegrationEncryptionFromDiscriminatorValue , m.SetEncryption)\n res[\"isActive\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsActive)\n res[\"supportedEntities\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseWorkforceIntegrationSupportedEntities , m.SetSupportedEntities)\n res[\"url\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUrl)\n return res\n}", "func (m *ResponseStatus) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"response\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseResponseType , m.SetResponse)\n res[\"time\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetTime)\n return res\n}" ]
[ "0.7138905", "0.71287197", "0.7090122", "0.700706", "0.7002194", "0.6968013", "0.6934261", "0.68714935", "0.6712393", "0.6699971", "0.66959363", "0.6689326", "0.66878796", "0.66668355", "0.66515285", "0.661564", "0.6610947", "0.6606688", "0.6602702", "0.66005516", "0.6599443", "0.6582186", "0.65779525", "0.6575734", "0.6571306", "0.6559125", "0.65570784", "0.6553863", "0.65461546", "0.6545348", "0.65442055", "0.65392023", "0.65339893", "0.6533101", "0.65288997", "0.6523711", "0.6520873", "0.65189445", "0.6516919", "0.6515603", "0.651152", "0.65042514", "0.64859605", "0.6484928", "0.6480872", "0.64789414", "0.6477309", "0.647237", "0.6468562", "0.64574087", "0.64549494", "0.6454305", "0.64539504", "0.6450751", "0.6440468", "0.6439272", "0.64310914", "0.64281833", "0.64229864", "0.64206386", "0.64200157", "0.64184195", "0.6411872", "0.64112663", "0.64097106", "0.6406938", "0.640641", "0.6404795", "0.64000714", "0.63963974", "0.6396077", "0.63897246", "0.63861823", "0.63861823", "0.63845414", "0.6379596", "0.6375607", "0.6372314", "0.6367411", "0.63653004", "0.6364213", "0.6361379", "0.6355722", "0.63484395", "0.63392794", "0.6339262", "0.63360345", "0.633596", "0.63330334", "0.6331507", "0.63284504", "0.63201433", "0.6319735", "0.62959397", "0.62894285", "0.6284353", "0.6284197", "0.62711656", "0.6271031", "0.6270868" ]
0.6972001
5
GetItems gets the items property value. All items contained in the list.
func (m *List) GetItems()([]ListItemable) { return m.items }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (l *RestAPIList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func GetItems(c *gin.Context) {\n\tvar items []model.ItemJson\n\terr := util.DB.Table(\"items\").Find(&items).Error\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t} else {\n\t\tc.JSON(http.StatusOK, util.SuccessResponse(http.StatusOK, \"Success\", items))\n\t}\n}", "func (out Outlooky) GetItems(folder *ole.IDispatch) *ole.IDispatch {\n\titems, err := out.CallMethod(folder, \"Items\")\n\tutil.Catch(err, \"Failed retrieving items.\")\n\n\treturn items.ToIDispatch()\n}", "func (l *IntegrationList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (api *API) ItemsGet(params Params) (res Items, err error) {\n\tif _, present := params[\"output\"]; !present {\n\t\tparams[\"output\"] = \"extend\"\n\t}\n\tresponse, err := api.CallWithError(\"item.get\", params)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treflector.MapsToStructs2(response.Result.([]interface{}), &res, reflector.Strconv, \"json\")\n\treturn\n}", "func (l *AuthorizerList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (c *Client) GetItems(ctx context.Context, owner string) (Items, error) {\n\tresponse, err := c.sendRequest(ctx, owner, http.MethodGet, fmt.Sprintf(\"%s/%s\", c.storeBaseURL, c.bucket), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif response.Code != http.StatusOK {\n\t\tlevel.Error(c.getLogger(ctx)).Log(xlog.MessageKey(), \"Argus responded with non-200 response for GetItems request\",\n\t\t\t\"code\", response.Code, \"ErrorHeader\", response.ArgusErrorHeader)\n\t\treturn nil, fmt.Errorf(errStatusCodeFmt, response.Code, translateNonSuccessStatusCode(response.Code))\n\t}\n\n\tvar items Items\n\n\terr = json.Unmarshal(response.Body, &items)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"GetItems: %w: %s\", errJSONUnmarshal, err.Error())\n\t}\n\n\treturn items, nil\n}", "func (l *DeploymentList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *DomainNameList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *DocumentationVersionList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *ResourceList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *List) GetItems() []ListItem {\n\treturn l.items\n}", "func (l *StageList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *IntegrationResponseList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (m *MGOStore) GetItems() interface{} {\n\treturn m.items\n}", "func (l *DocumentationPartList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (c *Client) GetItems(id int) (Item, error) {\n\tc.defaultify()\n\tvar item Item\n\tresp, err := http.Get(fmt.Sprintf(\"%s/item/%d.json\", c.apiBase, id))\n\tif err != nil {\n\t\treturn item, err\n\t}\n\tdefer resp.Body.Close()\n\tdec := json.NewDecoder(resp.Body)\n\terr = dec.Decode(&item)\n\tif err != nil {\n\t\treturn item, err\n\t}\n\treturn item, nil\n}", "func GetItems(c *gin.Context) {\n\tvar items []models.Item\n\tif err := models.DB.Order(\"name\").Find(&items).Error; err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"Could not find items\"})\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"items\": items})\n}", "func GetItems(ctx *fasthttp.RequestCtx) {\n\tenc := json.NewEncoder(ctx)\n\titems := ReadItems()\n\tenc.Encode(&items)\n\tctx.SetStatusCode(fasthttp.StatusOK)\n}", "func (self *SearchJob) GetItems() (items []Item) {\n\tself.Mutex.Lock()\n\titems = self.Items\n\t//update last access time\n\tself.LastRead = time.Now()\n\t//write to the writer\n\tself.Items = make([]Item, 0)\n\tself.Mutex.Unlock()\n\tlog.Println(\"items:\",len(items))\n\treturn items\n}", "func (l *MethodList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *ModelList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *MethodResponseList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *GatewayResponseList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (s *GORMStore) GetItems() interface{} {\n\treturn s.items\n}", "func (l *APIKeyList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (us *ItemsUseCase) GetItems() ([]model.Item, *model.Error) {\n\treturn us.csvservice.GetItemsFromCSV()\n}", "func (db Database) GetItems() (*models.ItemList, error) {\n\tlist := &models.ItemList{}\n\n\trows, err := db.Conn.Query(\"SELECT * FROM items ORDER BY created_at desc;\")\n\tif err != nil {\n\t\treturn list, err\n\t}\n\n\tfor rows.Next() {\n\t\tvar item models.Item\n\n\t\tif err = rows.Scan(\n\t\t\t&item.ID,\n\t\t\t&item.Name,\n\t\t\t&item.Description,\n\t\t\t&item.Creation,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlist.Items = append(list.Items, item)\n\t}\n\n\treturn list, nil\n}", "func (m *ExternalConnection) GetItems()([]ExternalItemable) {\n return m.items\n}", "func (c *pricedCart) GetItems() []Item {\n\titems := make([]Item, len(c.items))\n\ti := 0\n\tfor _, item := range c.items {\n\t\titems[i] = *item\n\t\ti++\n\t}\n\treturn items\n}", "func (m *Drive) GetItems()([]DriveItemable) {\n return m.items\n}", "func getItems(w http.ResponseWriter, r *http.Request) {\n\titems, err := supermart.GetItems(r.Context(), r)\n\tif err != nil {\n\t\tutils.WriteErrorResponse(http.StatusInternalServerError, err, w)\n\t\treturn\n\t}\n\tutils.WriteResponse(http.StatusOK, items, w)\n}", "func (l *BasePathMappingList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (b *OGame) GetItems(celestialID ogame.CelestialID) ([]ogame.Item, error) {\n\treturn b.WithPriority(taskRunner.Normal).GetItems(celestialID)\n}", "func (l *VPCLinkList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func getItems(ctx context.Context, request events.APIGatewayProxyRequest,\n\tih *item.Handler) (events.APIGatewayProxyResponse, error) {\n\n\tvar list *item.List\n\n\tlist, err := ih.List(ctx, request.PathParameters[PathParamCategoryID])\n\tif err != nil {\n\t\treturn web.GetResponse(ctx, err.Error(), http.StatusInternalServerError)\n\t}\n\n\treturn web.GetResponse(ctx, list, http.StatusOK)\n}", "func (l *UsagePlanKeyList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (c *Cache) GetItems() map[string]*Item {\n\treturn c.items\n}", "func (o *Invoice) GetItems() []InvoiceItems {\n\tif o == nil || o.Items == nil {\n\t\tvar ret []InvoiceItems\n\t\treturn ret\n\t}\n\treturn o.Items\n}", "func (l *UsagePlanList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (l *RequestValidatorList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (c *Controller) GetItems() http.Handler {\n\treturn http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {\n\t\tu := utility.New(writer, req)\n\t\tsession := c.store.DB.Copy()\n\t\tdefer session.Close()\n\n\t\tvar items []Item\n\t\tcollection := session.DB(c.databaseName).C(ItemsCollection)\n\t\terr := collection.\n\t\t\tFind(nil).\n\t\t\tSelect(bson.M{\"_id\": 1, \"color\": 1, \"code\": 1, \"description\": 1, \"category\": 1}).\n\t\t\tSort(\"description\").\n\t\t\tAll(&items)\n\t\tif err != nil {\n\t\t\tc.logger.Error(err)\n\t\t\tu.WriteJSONError(\"verification failed\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tu.WriteJSON(items)\n\t})\n}", "func (ris *rssItems) getItems() []RssItem {\n\tris.RLock()\n\tdefer ris.RUnlock()\n\treturn ris.items\n}", "func (svc *svc) ListItems(ctx context.Context, query model.ItemQuery) ([]model.Item, int64, error) {\n\titems, err := svc.repo.ListItems(ctx, query)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\ttotal, err := svc.repo.CountItems(ctx, query)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn items, total, nil\n}", "func GetItems(filter interface{}) (GetItemResult, error) {\n\t// create connection to database\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\tc := newConnection(ctx)\n\tdefer c.clt.Disconnect(ctx)\n\n\tcursor, err := c.collection(itemCollection).Find(context.Background(), filter)\n\tif err == mongo.ErrNoDocuments {\n\t\treturn GetItemResult{\n\t\t\tGotItemCount: 0,\n\t\t\tData: nil,\n\t\t}, nil\n\t} else if err != nil {\n\t\treturn GetItemResult{}, err\n\t}\n\n\tvar res []bson.M\n\tif err = cursor.All(context.Background(), &res); err != nil {\n\t\treturn GetItemResult{}, err\n\t}\n\treturn GetItemResult{\n\t\tGotItemCount: int64(len(res)),\n\t\tData: res,\n\t}, nil\n}", "func (is *ItemServices) Items(ctx context.Context, limit, offset int) ([]entity.Item, []error) {\n\titms, errs := is.itemRepo.Items(ctx, limit, offset)\n\tif len(errs) > 0 {\n\t\treturn nil, errs\n\t}\n\treturn itms, errs\n}", "func (s *InventoryApiService) ListItems(w http.ResponseWriter) error {\n\tctx := context.Background()\n\tl, err := s.db.ListItems(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn EncodeJSONResponse(l, nil, w)\n}", "func GetItems(huntID int) ([]*models.Item, *response.Error) {\n\titemDBs, e := db.GetItemsWithHuntID(huntID)\n\tif itemDBs == nil {\n\t\treturn nil, e\n\t}\n\n\titems := make([]*models.Item, 0, len(itemDBs))\n\tfor _, itemDB := range itemDBs {\n\t\titem := models.Item{ItemDB: *itemDB}\n\t\titems = append(items, &item)\n\t}\n\n\treturn items, e\n}", "func (o *CreditBankEmploymentReport) GetItems() []CreditBankEmploymentItem {\n\tif o == nil {\n\t\tvar ret []CreditBankEmploymentItem\n\t\treturn ret\n\t}\n\n\treturn o.Items\n}", "func GetItems() (items []Item, err error) {\n\tdir, err := os.Open(rootPath)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfi, err := dir.Stat()\n\tif !fi.Mode().IsDir() {\n\t\tpanic(\"need directory\")\n\t}\n\n\tnames, err := dir.Readdirnames(0)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, name := range names {\n\t\titem, err := NewItem(name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\titems = append(items, item)\n\t}\n\n\tsort.Sort(sort.Reverse(byCreatedAt(items)))\n\n\treturn items, nil\n}", "func (o *AssetReport) GetItems() []AssetReportItem {\n\tif o == nil {\n\t\tvar ret []AssetReportItem\n\t\treturn ret\n\t}\n\n\treturn o.Items\n}", "func (c *M) Items() []*js.Object {\n\treturn c.items\n}", "func GetItems(da DataAccess, username string) (*ItemList, error) {\n\t// find the user and verify they exist\n\tuser, err := FindUserByName(da, username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// try to get their items\n\titems, err := da.GetItemsByUser(context.Background(), user.Id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// calculate net worth, asset total, liability total\n\tvar net, asset, liability int64\n\tfor i := range *items {\n\t\tif (*items)[i].Type == ItemTypeAsset {\n\t\t\tnet += (*items)[i].Value\n\t\t\tasset += (*items)[i].Value\n\t\t} else if (*items)[i].Type == ItemTypeLiability {\n\t\t\tnet -= (*items)[i].Value\n\t\t\tliability += (*items)[i].Value\n\t\t}\n\t}\n\n\treturn &ItemList{Username: username, Items: items, NetWorth: net, AssetTotal: asset, LiabilityTotal: liability}, nil\n}", "func (o TagsOutput) Items() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v Tags) []string { return v.Items }).(pulumi.StringArrayOutput)\n}", "func (o *MainSetStockStatusInput) GetItems() []MainStockItemState {\n\tif o == nil {\n\t\tvar ret []MainStockItemState\n\t\treturn ret\n\t}\n\n\treturn o.Items\n}", "func (o PersistentVolumeListOutput) Items() PersistentVolumeTypeArrayOutput {\n\treturn o.ApplyT(func(v *PersistentVolumeList) PersistentVolumeTypeArrayOutput { return v.Items }).(PersistentVolumeTypeArrayOutput)\n}", "func (d *Database) GetItems(\n\treq GetItemsRequest) (*GetItemsResponse, error) {\n\tvar err error\n\tresp := GetItemsResponse{\n\t\tItems: []*structs.Item{}}\n\n\tif !req.Unread && req.ReadAfter == nil && req.ReadBefore == nil {\n\t\tlog.Info(\"GetItems() called with empty request\")\n\t\treturn &resp, nil\n\t}\n\n\tif len(req.FeedIDs) != 0 && req.CategoryID != nil {\n\t\treturn nil, errors.New(\"Can't call GetItems for both feeds and a category\")\n\t}\n\n\tif req.Unread && len(req.FeedIDs) == 0 {\n\t\treturn nil, errors.New(\"Can't request unread except by feeds\")\n\t}\n\n\tif (req.ReadAfter != nil) && (req.ReadBefore != nil) {\n\t\treturn nil, errors.New(\"Must not specify both ReadBefore and ReadAfter\")\n\t}\n\n\tif req.ReadAfter != nil {\n\t\t*req.ReadAfter = req.ReadAfter.UTC().Truncate(time.Second)\n\t}\n\n\tif req.ReadBefore != nil {\n\t\t*req.ReadBefore = req.ReadBefore.UTC().Truncate(time.Second)\n\t}\n\n\td.lock.RLock()\n\tdefer d.lock.RUnlock()\n\n\tif err := d.checkClosed(); err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tif !req.IncludeFeeds {\n\t\tresp.Items, err = getItemsFor(d.db, req)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &resp, nil\n\t}\n\n\ttx, err := d.db.Begin()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tdefer tx.Rollback()\n\n\tresp.Items, err = getItemsFor(tx, req)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tif req.IncludeFeeds && req.FeedIDs != nil {\n\t\tresp.Feeds, err = getFeeds(tx, req.FeedIDs)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\ttx.Rollback()\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (o TagsResponseOutput) Items() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TagsResponse) []string { return v.Items }).(pulumi.StringArrayOutput)\n}", "func (r *CompanyItemsCollectionRequest) Get(ctx context.Context) ([]Item, error) {\n\treturn r.GetN(ctx, 0)\n}", "func (us *ItemsUseCase) GetItemsAPI(token string, query url.Values) ([]model.ApiItem, *model.Error) {\n\tnewItems, err := us.httpservice.GetItemAPI(token, query)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terrorSaveItem := us.csvservice.SaveItems(&newItems)\n\n\tif errorSaveItem != nil {\n\t\treturn nil, errorSaveItem\n\t}\n\n\treturn newItems, nil\n}", "func (r *MachinePoolsListResponse) GetItems() (value *MachinePoolList, ok bool) {\n\tok = r != nil && r.items != nil\n\tif ok {\n\t\tvalue = r.items\n\t}\n\treturn\n}", "func (b *Bag) Items() []Item {\n\treturn b.items\n}", "func (o MetadataOutput) Items() MetadataItemsItemArrayOutput {\n\treturn o.ApplyT(func(v Metadata) []MetadataItemsItem { return v.Items }).(MetadataItemsItemArrayOutput)\n}", "func (r *SubscriptionsListServerResponse) Items(value *SubscriptionList) *SubscriptionsListServerResponse {\n\tr.items = value\n\treturn r\n}", "func (o HorizontalPodAutoscalerListOutput) Items() HorizontalPodAutoscalerTypeArrayOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerList) HorizontalPodAutoscalerTypeArrayOutput { return v.Items }).(HorizontalPodAutoscalerTypeArrayOutput)\n}", "func (api *API) ItemsGetByApplicationID(id string) (res Items, err error) {\n\treturn api.ItemsGet(Params{\"applicationids\": id})\n}", "func (d *Dao) ItemList(ctx context.Context, params *model.SourceSearch) (itemsList []model.Items, err error) {\n\tquery := make(map[string]interface{})\n\tquery[\"pageNum\"] = params.PageNum\n\tquery[\"pageSize\"] = params.PageSize\n\tquery[\"shopId\"] = 0\n\tquery[\"keyword\"] = params.Keyword\n\tjsonQuery, _ := json.Marshal(query)\n\tresp, err := d.client.Post(d.c.URL.ItemSearch, \"application/json\", bytes.NewReader(jsonQuery))\n\tif err != nil {\n\t\tlog.Error(\"Request error(%v)\", err)\n\t\treturn\n\t}\n\tHTTPResponse := model.HTTPResponse{}\n\tbodyJSON, _ := ioutil.ReadAll(resp.Body)\n\tif err = json.Unmarshal(bodyJSON, &HTTPResponse); err != nil {\n\t\tlog.Error(\"json.Unmarshal error(%v)\", err)\n\t}\n\tif HTTPResponse.Code != 0 {\n\t\tlog.Error(\"Request (%s) search error(%v)\", d.c.URL.ItemSearch, err)\n\t\treturn\n\t}\n\titemsList = HTTPResponse.Data.List\n\treturn\n}", "func GetAllItems(w http.ResponseWriter, r *http.Request) {\r\n\titems, err := models.GetAllItems()\r\n\r\n\tif err != nil {\r\n\t\trespondWithError(w, http.StatusNotFound, \"Items could not be returned due to an error\")\r\n\t\treturn\r\n\t}\r\n\r\n\trespondWithJSON(w, http.StatusOK, items)\r\n}", "func (c *Container) Items(prefix string, cursor string, count int) ([]stow.Item, string, error) {\n\tquery := &storage.Query{Prefix: prefix}\n\tcall := c.Bucket().Objects(c.ctx, query)\n\n\tp := iterator.NewPager(call, count, cursor)\n\tvar results []*storage.ObjectAttrs\n\tnextPageToken, err := p.NextPage(&results)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tvar items []stow.Item\n\tfor _, item := range results {\n\t\ti, err := c.convertToStowItem(item)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\titems = append(items, i)\n\t}\n\n\treturn items, nextPageToken, nil\n}", "func (o *RoleListAllOf) GetItems() []Role {\n\tif o == nil || o.Items == nil {\n\t\tvar ret []Role\n\t\treturn ret\n\t}\n\treturn *o.Items\n}", "func (o HorizontalPodAutoscalerListTypeOutput) Items() HorizontalPodAutoscalerTypeArrayOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerListType) []HorizontalPodAutoscalerType { return v.Items }).(HorizontalPodAutoscalerTypeArrayOutput)\n}", "func (o HorizontalPodAutoscalerListTypeOutput) Items() HorizontalPodAutoscalerTypeArrayOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerListType) []HorizontalPodAutoscalerType { return v.Items }).(HorizontalPodAutoscalerTypeArrayOutput)\n}", "func (c *container) Items(prefix, cursor string, count int) ([]stow.Item, string, error) {\n\tvar entries []entry\n\tentries, cursor, err := c.getFolderItems([]entry{}, prefix, \"\", filepath.Join(c.location.config.basePath, c.name), cursor, count, false)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\t// Convert entries to []stow.Item\n\tsItems := make([]stow.Item, len(entries))\n\tfor i := range entries {\n\t\tsItems[i] = entries[i].item\n\t}\n\n\treturn sItems, cursor, nil\n}", "func (p *PaginationModel) ReadItems(v interface{}) error {\n\treturn json.Unmarshal(p.RawItems, v)\n}", "func (o TagsPtrOutput) Items() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Tags) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Items\n\t}).(pulumi.StringArrayOutput)\n}", "func (o IopingSpecVolumeVolumeSourceDownwardAPIOutput) Items() IopingSpecVolumeVolumeSourceDownwardAPIItemsArrayOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceDownwardAPI) []IopingSpecVolumeVolumeSourceDownwardAPIItems {\n\t\treturn v.Items\n\t}).(IopingSpecVolumeVolumeSourceDownwardAPIItemsArrayOutput)\n}", "func (o *WorkflowListResponse) GetItems() []Workflow {\n\tif o == nil {\n\t\tvar ret []Workflow\n\t\treturn ret\n\t}\n\n\treturn o.Items\n}", "func (o JobListTypeOutput) Items() JobTypeArrayOutput {\n\treturn o.ApplyT(func(v JobListType) []JobType { return v.Items }).(JobTypeArrayOutput)\n}", "func (oq *SortedQueue) Items() ItemList {\n\treturn oq.items\n}", "func (r *MachinePoolsListServerResponse) Items(value *MachinePoolList) *MachinePoolsListServerResponse {\n\tr.items = value\n\treturn r\n}", "func (c Caretaker) Items() []string {\n\tvar items []string\n\tfor k, _ := range c.o.data {\n\t\titems = append(items, k)\n\t}\n\n\treturn items\n}", "func (o *AclBindingListPage) GetItems() []AclBinding {\n\tif o == nil || o.Items == nil {\n\t\tvar ret []AclBinding\n\t\treturn ret\n\t}\n\treturn *o.Items\n}", "func (c *CaptureList) Items() []Capture {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\treturn c.items\n}", "func GetSelfItems() ([]Item, error) {\n\treq, _ := http.NewRequest(\"GET\", \"https://qiita.com/api/v2/authenticated_user/items\", nil)\n\tresbyte, err := DoRequest(req)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to DoRequest\")\n\t}\n\n\tvar items []Item\n\tif err := json.Unmarshal(resbyte, &items); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to unmarshal\")\n\t}\n\treturn items, nil\n}", "func (o TagsResponsePtrOutput) Items() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *TagsResponse) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Items\n\t}).(pulumi.StringArrayOutput)\n}", "func (c CacheReader) GetAllItems(ctx context.Context) ([]models.Item, error) {\n\tvar items []models.Item\n\n\terr := c.cache.Once(&cache.Item{\n\t\tKey: \"all\",\n\t\tValue: &items,\n\t\tTTL: c.cfg.CacheTimout,\n\t\tDo: func(*cache.Item) (interface{}, error) {\n\t\t\ti, err := c.reader.GetAllItems(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"cache\")\n\t\t\t}\n\t\t\treturn i, nil\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}", "func (m *statusTableDataModel) Items() interface{} {\n\treturn m.items\n}", "func (o *BatchCreateRoleAssignment) GetItems() []CreateRoleAssignment {\n\tif o == nil {\n\t\tvar ret []CreateRoleAssignment\n\t\treturn ret\n\t}\n\n\treturn o.Items\n}", "func (c *Chromium) GetAllItems() ([]data.Item, error) {\n\tvar items []data.Item\n\tfor item, choice := range chromiumItems {\n\t\tm, err := GetItemPath(c.profilePath, choice.mainFile)\n\t\tif err != nil {\n\t\t\tlogger.Debugf(\"%s find %s file failed, ERR:%s\", c.name, item, err)\n\t\t\tcontinue\n\t\t}\n\t\ti := choice.newItem(m, \"\")\n\t\tlogger.Debugf(\"%s find %s File Success\", c.name, item)\n\t\titems = append(items, i)\n\t}\n\treturn items, nil\n}", "func (l *LogItems) Items() []*LogItem {\n\tl.mx.RLock()\n\tdefer l.mx.RUnlock()\n\n\treturn l.items\n}", "func getItemList(r *http.Request, pb transactionPb.TransactionService) (proto.Message, error) {\n\tpbRequest := &transactionPb.ItemListReq{}\n\tpbResponse, err := pb.GetItemList(context.Background(), pbRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pbResponse, nil\n}", "func (res ItemsResource) List(w http.ResponseWriter, r *http.Request) {\n\trender.JSON(w, r, items)\n}", "func (b *Bag) QueryItems() *BagItemQuery {\n\treturn (&BagClient{config: b.config}).QueryItems(b)\n}", "func GetItemsHandler(db *sqlx.DB) gin.HandlerFunc {\n\treturn func (ctx *gin.Context) {\n\t\tcreatedBy, createdByExists := GetUserID(ctx)\n\t\tif !createdByExists {\n\t\t\tctx.String(http.StatusUnauthorized, \"User id not found in authorization token.\")\n\t\t\treturn\n\t\t}\n\n\t\tvar searchQuery ItemsGetQuery\n\t\tif err := ctx.ShouldBindQuery(&searchQuery); err != nil {\n\t\t\tctx.String(http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tquery := sq.Select(\"items.public_id, name, price, unit, created_at, updated_at\").From(\"items\")\n\n\t\tif createdBy != \"\" {\n\t\t\tquery = query.Join(\"users ON users.id = items.created_by\").Where(sq.Eq{\"users.public_id\": createdBy})\n\t\t}\n\n\t\tif searchQuery.Name != \"\" {\n\t\t\tquery = query.Where(\"items.name LIKE ?\", fmt.Sprint(\"%\", searchQuery.Name, \"%\"))\n\t\t}\n\n\t\tqueryString, queryStringArgs, err := query.ToSql()\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\titems := []Item{}\n\t\tif err := db.Select(&items, queryString, queryStringArgs...); err != nil {\n\t\t\tlog.Fatalln(err.Error())\n\t\t}\n\n\t\tctx.JSON(http.StatusOK, items)\n\t}\n}", "func (r *MachinePoolsListResponse) Items() *MachinePoolList {\n\tif r == nil {\n\t\treturn nil\n\t}\n\treturn r.items\n}", "func (db *DB) Items() *ItemIterator {\n\treturn &ItemIterator{db: db}\n}", "func (o FioSpecVolumeVolumeSourceDownwardAPIOutput) Items() FioSpecVolumeVolumeSourceDownwardAPIItemsArrayOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceDownwardAPI) []FioSpecVolumeVolumeSourceDownwardAPIItems {\n\t\treturn v.Items\n\t}).(FioSpecVolumeVolumeSourceDownwardAPIItemsArrayOutput)\n}", "func (b *CompanyRequestBuilder) Items() *CompanyItemsCollectionRequestBuilder {\n\tbb := &CompanyItemsCollectionRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.baseURL += \"/items\"\n\treturn bb\n}", "func GetList(c Context) {\n\tres, err := db.SelectAllItems()\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, res)\n}", "func (o *RoleListAllOf) SetItems(v []Role) {\n\to.Items = &v\n}" ]
[ "0.75478745", "0.744459", "0.7434444", "0.74341697", "0.7407838", "0.73677117", "0.73617125", "0.7360272", "0.7359669", "0.7346144", "0.7336508", "0.7334327", "0.73200595", "0.7295804", "0.72761357", "0.72758305", "0.72643614", "0.7261494", "0.72567713", "0.7251349", "0.7244536", "0.7231289", "0.71946055", "0.71710896", "0.71686697", "0.71456456", "0.71053827", "0.7077708", "0.70618194", "0.7054976", "0.70537543", "0.70506066", "0.7049282", "0.7012157", "0.70017946", "0.6981622", "0.6949256", "0.690125", "0.6893008", "0.6881061", "0.68801546", "0.68694264", "0.6771782", "0.67012346", "0.668106", "0.6644188", "0.6520586", "0.6488233", "0.6450608", "0.6412892", "0.6392377", "0.6323595", "0.63167125", "0.63130563", "0.6308038", "0.62881166", "0.62848985", "0.6244262", "0.62409115", "0.6201512", "0.61974305", "0.6171747", "0.6168615", "0.61513764", "0.6150155", "0.6116454", "0.6108938", "0.60923177", "0.6092114", "0.60891134", "0.60865134", "0.60865134", "0.6084561", "0.60669935", "0.60423964", "0.6040523", "0.60404915", "0.6014265", "0.60138816", "0.5999712", "0.5983943", "0.598288", "0.59575015", "0.59552836", "0.5951859", "0.5951611", "0.59365827", "0.5925251", "0.5916604", "0.58928686", "0.5886617", "0.58829796", "0.5882622", "0.58758473", "0.5870828", "0.5853358", "0.58398885", "0.5839663", "0.58359593", "0.58355755" ]
0.7805831
0
GetList gets the list property value. Provides additional details about the list.
func (m *List) GetList()(ListInfoable) { return m.list }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client *ClientImpl) GetList(ctx context.Context, args GetListArgs) (*PickList, error) {\n\trouteValues := make(map[string]string)\n\tif args.ListId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.ListId\"}\n\t}\n\trouteValues[\"listId\"] = (*args.ListId).String()\n\n\tlocationId, _ := uuid.Parse(\"01e15468-e27c-4e20-a974-bd957dcccebc\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"6.0-preview.1\", routeValues, nil, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue PickList\n\terr = client.Client.UnmarshalBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (l *Lists) GetList(id string) (*ListOutput, error) {\n\tif id == \"\" {\n\t\treturn nil, errors.New(\"goengage: id is required\")\n\t}\n\n\treq, err := l.client.newRequest(http.MethodGet, fmt.Sprintf(\"/lists/%v\", id), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar output ListOutput\n\terr = l.client.makeRequest(req, &output)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &output, err\n}", "func (p *Profile) ListGet() *queue.List {\n\treturn &p.List\n}", "func (a *alphaMock) GetList(ctx context.Context, in *alpha.GetListRequest, opts ...grpc.CallOption) (*alpha.List, error) {\n\t// TODO(#2716): Implement me!\n\treturn nil, errors.Errorf(\"Unimplemented -- GetList coming soon\")\n}", "func (n NestedInteger) GetList() []*NestedInteger {\n\tif n.single {\n\t\treturn nil\n\t} else {\n\t\tlist, _ := n.value.([]*NestedInteger)\n\t\treturn list\n\t}\n}", "func GetList(w http.ResponseWriter, r *http.Request) {\n\tlist, err := watchlist.GetWatchList(r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttpext.JSON(w, list)\n}", "func (c *Client) GetList(board *trello.Board, name string) (*trello.List, error) {\n\tlists, err := board.GetLists(trello.Defaults())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, list := range lists {\n\t\tif list.Name == name {\n\t\t\treturn list, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"could not find list %s on board %s\", name, board.Name)\n}", "func (n NestedInteger) GetList() []*NestedInteger {\n\treturn n.Ns\n}", "func (m *Drive) GetList()(Listable) {\n return m.list\n}", "func (c *Firewall) GetList() ([]string, error) {\n\tans := c.container()\n\treturn c.ns.Listing(util.Get, c.pather(), ans)\n}", "func GetList(c Context) {\n\tres, err := db.SelectAllItems()\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, res)\n}", "func (ctl *SaleCounterProductController) GetList() {\n\tviewType := ctl.Input().Get(\"view\")\n\tif viewType == \"\" || viewType == \"table\" {\n\t\tctl.Data[\"ViewType\"] = \"table\"\n\t}\n\tctl.PageAction = utils.MsgList\n\tctl.Data[\"tableId\"] = \"table-sale-counter-product\"\n\tctl.Layout = \"base/base_list_view.html\"\n\tctl.TplName = \"sale/sale_counter_product_list_search.html\"\n}", "func (m *Mongo) GetList(ctx context.Context) ([]ListItem, error) {\n\tcoll := m.C.Database(m.dbName).Collection(listCollection)\n\n\tcursor, err := coll.Find(ctx, bson.D{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar list []ListItem\n\n\tfor cursor.Next(ctx) {\n\t\tvar item ListItem\n\n\t\terr = cursor.Decode(&item)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlist = append(list, item)\n\t}\n\n\treturn list, nil\n}", "func (client *GroupMgmtClient) listGet(\n\tpath string,\n\tqueryParams map[string]string,\n\tparams *param.GetParams,\n) (interface{}, error) {\n\t// build the url\n\turl := fmt.Sprintf(\"%s/%s/detail\", client.URL, path)\n\n\tresponse, err := client.Client.R().\n\t\tSetQueryParams(queryParams).\n\t\tSetHeader(\"X-Auth-Token\", client.SessionToken).\n\t\tGet(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn processResponse(client, response, path, nil, params)\n}", "func getList(w io.Writer, r *http.Request) error {\n\tc := appengine.NewContext(r)\n\n\t// Get the list id from the URL.\n\tid := mux.Vars(r)[\"list\"]\n\n\t// Decode the obtained id into a datastore key.\n\tkey, err := datastore.DecodeKey(id)\n\tif err != nil {\n\t\treturn appErrorf(http.StatusBadRequest, \"invalid list id\")\n\t}\n\n\t// Fetch the list from the datastore.\n\tlist := &List{}\n\terr = datastore.Get(c, key, list)\n\tif err == datastore.ErrNoSuchEntity {\n\t\treturn appErrorf(http.StatusNotFound, \"list not found\")\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"fetch list: %v\", err)\n\t}\n\n\t// Set the ID field with the id from the request url and encode the list.\n\tlist.ID = id\n\treturn json.NewEncoder(w).Encode(&list)\n}", "func (c *FwRouter) GetList() ([]string, error) {\n\tresult, _ := c.versioning()\n\treturn c.ns.Listing(util.Get, c.xpath(nil), result)\n}", "func (this NestedInteger) GetList() []*NestedInteger {\n\treturn nil\n}", "func (this NestedInteger) GetList() []*NestedInteger {\n\treturn nil\n}", "func (c *Client) GetList(dir string) ([]string, error) {\n\tvar list []string\n\n\t// Prepare the URL\n\tURL := fmt.Sprintf(wpListURL, dir)\n\n\t// Make the Request\n\tresp, err := c.getRequest(URL)\n\tif err != nil {\n\t\treturn list, err\n\t}\n\n\t// Drain body and check Close error\n\tdefer drainAndClose(resp.Body, &err)\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tmatches := regexList.FindAllStringSubmatch(string(bytes), -1)\n\n\t// Add all matches to extension list\n\tfor _, match := range matches {\n\t\tlist = append(list, match[1])\n\t}\n\n\treturn list, err\n}", "func (s *Storage) GetList(key string) ([]string, error) {\n\titem := s.get(key)\n\tif item == nil {\n\t\treturn nil, nil\n\t}\n\n\tif list, ok := item.value.([]string); ok {\n\t\treturn list, nil\n\t}\n\n\treturn nil, newErrCustom(errWrongType)\n}", "func (c *CappedList) List() []string {\n\t// get size of list\n\tsize, err := c.client.LLen(c.name).Result()\n\tif err != nil {\n\t\tsetup.LogCommon(err).Error(\"Failed LLen\")\n\t} else if size > c.size {\n\t\t// sanity check that the list is not bigger than possible\n\t\tsetup.LogCommon(nil).WithField(\"size\", size).Error(\"Size is larger than expected\")\n\t}\n\n\t// get the elements\n\tout, err := c.client.LRange(c.name, 0, size-1).Result()\n\tif err != nil {\n\t\tsetup.LogCommon(err).Error(\"Failed LRange\")\n\t}\n\n\treturn out\n\n}", "func (item Item) GetList(name string) sugar.List {\n\tlist := sugar.List{}\n\n\tswitch item[name].(type) {\n\tcase []interface{}:\n\t\tlist = make(sugar.List, len(item[name].([]interface{})))\n\n\t\tfor k, _ := range item[name].([]interface{}) {\n\t\t\tlist[k] = item[name].([]interface{})[k]\n\t\t}\n\t}\n\n\treturn list\n}", "func (nls *NetworkListService) GetNetworkList(ListID string, opts ListNetworkListsOptions) (*AkamaiNetworkList, *ClientResponse, error) {\n\n\tapiURI := fmt.Sprintf(\"%s/%s?listType=%s&extended=%t&includeDeprecated=%t&includeElements=%t\",\n\t\tapiPaths[\"network_list\"],\n\t\tListID,\n\t\topts.TypeOflist,\n\t\topts.Extended,\n\t\topts.IncludeDeprecated,\n\t\topts.IncludeElements)\n\n\tvar k *AkamaiNetworkList\n\tresp, err := nls.client.NewRequest(\"GET\", apiURI, nil, &k)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn k, resp, err\n\n}", "func (o *ViewProjectActivePages) GetList() bool {\n\tif o == nil || o.List == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.List\n}", "func (h *Handle) optionGetList(f func(*C.alpm_handle_t) *C.alpm_list_t) (StringList, error) {\n\talpmList := f(h.ptr)\n\tgoList := StringList{(*list)(unsafe.Pointer(alpmList))}\n\n\tif alpmList == nil {\n\t\treturn goList, h.LastError()\n\t}\n\n\treturn goList, nil\n}", "func GetList(tx *sql.Tx) (list []Info, err error) {\n\tmapper := rlt.NewAccountMapper(tx)\n\trows, err := mapper.FindAccountAll()\n\tfor _, row := range rows {\n\t\tinfo := Info{}\n\t\tinfo.ID = row.ID\n\t\tinfo.Domain = row.Domain.String\n\t\tinfo.UserName = row.UserName\n\t\tinfo.DisplayName = row.DisplayName\n\t\tinfo.Email = row.Email\n\t\tlist = append(list, info) //数据写入\n\t}\n\treturn list, err\n}", "func GetList(path string) ([]string, error) {\n\tftpConn, err := connect()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer ftpConn.Quit()\n\tvar entries []string\n\tentries, err = ftpConn.NameList(path)\n\tif err != nil {\n\t\treturn entries, &FTPError{\n\t\t\tMessage: fmt.Sprintf(\"获取路径%s下文件列表失败\", path),\n\t\t\tOriginErr: err,\n\t\t}\n\t}\n\n\treturn entries, nil\n}", "func (obj *Global) GetDocList(ctx context.Context) ([]*DocListEntry, error) {\n\tresult := &struct {\n\t\tDocList []*DocListEntry `json:\"qDocList\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetDocList\", result)\n\treturn result.DocList, err\n}", "func (l *ArrayLister) List() ([]string, error) {\n\treturn l.Items, nil\n}", "func GetList(pattern string) ([]string, error) {\n\tconn := db.Pool.Get()\n\tdefer conn.Close()\n\n\treturn db.GetList(conn, pattern)\n}", "func (s *initServer) GetUserList(ctx context.Context, in *pb.UserListRequest) (*pb.UserListResponse, error) {\t\n\treturn userListTempl(ctx, in, \"userList:user\", false)\n}", "func (c *Client) List(ctx context.Context, p *ListPayload) (res *ListResult, err error) {\n\tvar ires interface{}\n\tires, err = c.ListEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(*ListResult), nil\n}", "func GetList(str string) []string {\n\tif str == \"\" {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(strings.Replace(str, \" \", \"\", -1), \",\")\n}", "func GetList(str, seperator string) ([]string, bool) {\n\tss := strings.Split(str, seperator)\n\tif len(ss) > 1 {\n\t\treturn ss, true\n\t}\n\treturn ss, false\n}", "func (f *StringList) Get() any {\n\tif f == nil {\n\t\treturn []string(nil)\n\t}\n\treturn *f\n}", "func GetUserList(w http.ResponseWriter, r *http.Request) {\n\n\tusers, err := user.GetUserList(r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttpext.SuccessDataAPI(w, \"Ok\", users)\n}", "func testList(t *testing.T) *List {\n\tc := testClient()\n\tc.BaseURL = mockResponse(\"lists\", \"list-api-example.json\").URL\n\tlist, err := c.GetList(\"4eea4ff\", Defaults())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn list\n}", "func (a *adapter) getList() []*net.IPNet {\n\treturn a.atomicList.Load().([]*net.IPNet)\n}", "func GetList(pageNumber, minRating int, sort, order string) ([]Movie, error) {\n\tv := url.Values{}\n\tv.Set(\"limit\", \"50\")\n\tv.Set(\"sort_by\", sort)\n\tv.Set(\"order_by\", order)\n\tv.Set(\"minimum_rating\", strconv.Itoa(minRating))\n\tv.Set(\"page\", strconv.Itoa(pageNumber))\n\tURL := fmt.Sprintf(\"%s/list_movies.json?%s\", APIEndpoint, v.Encode())\n\treturn getMovieList(URL)\n}", "func (c *ChargeClient) GetList(ctx context.Context, paymentID string) ([]Charge, error) {\n\tvar charges []Charge\n\tif err := c.Caller.Call(ctx, \"GET\", c.chargesPath(paymentID), nil, nil, &charges); err != nil {\n\t\treturn nil, err\n\t}\n\treturn charges, nil\n}", "func GetListUser(c *gin.Context) {\r\n\tvar usr []model.UserTemporary\r\n\tres := model.GetLUser(usr)\r\n\r\n\tutils.WrapAPIData(c, map[string]interface{}{\r\n\t\t\"Data\": res,\r\n\t}, http.StatusOK, \"success\")\r\n}", "func (om *OrderedMap) GetList() (kvList []KV) {\n\tfor idx := 0; idx < len(om.kvList); idx++ {\n\t\tif om.kvList[idx] != nil {\n\t\t\tkvList = append(kvList, *om.kvList[idx])\n\t\t}\n\t}\n\treturn\n}", "func (_m *Usecase) GetList(ctx context.Context, pocketId int) ([]activities.Domain, error) {\n\tret := _m.Called(ctx, pocketId)\n\n\tvar r0 []activities.Domain\n\tif rf, ok := ret.Get(0).(func(context.Context, int) []activities.Domain); ok {\n\t\tr0 = rf(ctx, pocketId)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]activities.Domain)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, int) error); ok {\n\t\tr1 = rf(ctx, pocketId)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (element *Element) List(value string) *Element {\n\treturn element.Attr(\"list\", value)\n}", "func (s *ResolutionService) GetList(ctx context.Context) ([]Resolution, *Response, error) {\n\tapiEndpoint := \"rest/api/2/resolution\"\n\treq, err := s.client.NewRequest(ctx, http.MethodGet, apiEndpoint, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresolutionList := []Resolution{}\n\tresp, err := s.client.Do(req, &resolutionList)\n\tif err != nil {\n\t\treturn nil, resp, NewJiraError(resp, err)\n\t}\n\treturn resolutionList, resp, nil\n}", "func (c *vaultLists) Get(name string, options v1.GetOptions) (result *v1alpha1.VaultList, err error) {\n\tresult = &v1alpha1.VaultList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"vaultlists\").\n\t\tName(name).\n\t\tVersionedParams(&options, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}", "func (m *publicUser) GetUserList(c *gin.Context) (int, interface{}) {\n\tuser := plugins.CurrentPlugin(c, m.config.LoginVersion)\n\tuserList, err := user.GetUserList(c, m.config.ConfigMap)\n\trspBody := metadata.LonginSystemUserListResult{}\n\tif nil != err {\n\t\trspBody.Code = common.CCErrCommHTTPDoRequestFailed\n\t\trspBody.ErrMsg = err.Error()\n\t\trspBody.Result = false\n\t}\n\trspBody.Result = true\n\trspBody.Data = userList\n\treturn 200, rspBody\n}", "func GetListStops(api goemt.IAPI, postData PostListStops) (listStops []ListStops, err error) {\n\tif postData == nil {\n\t\tpostData = PostListStops{}\n\t}\n\tvar data auxListStops\n\terr = postInfoToPlatform(api, endpointListStops, postData, &data)\n\tif err != nil {\n\t\treturn listStops, err\n\t}\n\treturn data.Data, nil\n}", "func (tmdb *TMDb) GetListInfo(id string) (*ListInfo, error) {\n\tvar listInfo ListInfo\n\turi := fmt.Sprintf(\"%s/list/%v?api_key=%s\", baseURL, id, tmdb.apiKey)\n\tresult, err := getTmdb(uri, &listInfo)\n\treturn result.(*ListInfo), err\n}", "func GetListOptions(ctx *context.APIContext) models.ListOptions {\n\treturn models.ListOptions{\n\t\tPage: ctx.QueryInt(\"page\"),\n\t\tPageSize: convert.ToCorrectPageSize(ctx.QueryInt(\"limit\")),\n\t}\n}", "func (obj *Doc) GetMediaList(ctx context.Context) (*MediaList, error) {\n\tresult := &struct {\n\t\tList *MediaList `json:\"qList\"`\n\t\tReturn bool `json:\"qReturn\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetMediaList\", result)\n\treturn result.List, err\n}", "func GetListMeta(obj interface{}) (*api.ListMeta, error) {\n\tswitch t := obj.(type) {\n\tcase ListMetaAccessor:\n\t\tif meta := t.GetListMeta(); meta != nil {\n\t\t\treturn meta, nil\n\t\t}\n\t}\n\treturn nil, errNotListObject\n}", "func GetList() []string {\n\tvar envList []string\n\tif config.UsingDB() {\n\t\tenvList = getEnvironmentList()\n\t} else {\n\t\tds := datastore.New()\n\t\tenvList = ds.GetList(\"env\")\n\t\tenvList = append(envList, \"_default\")\n\t}\n\treturn envList\n}", "func (o *GetListParams) WithListID(listID int64) *GetListParams {\n\to.SetListID(listID)\n\treturn o\n}", "func (a *API) List(path string) (*ListObject, error) {\n\tvar out struct {\n\t\tObjects []*ListObject\n\t}\n\terr := a.Request(\"ls\", path).Exec(context.Background(), &out)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(out.Objects) != 1 {\n\t\treturn nil, errors.New(\"bad response from server\")\n\t}\n\treturn out.Objects[0], nil\n}", "func (c *Dg) GetList() ([]string, error) {\n c.con.LogQuery(\"(get) list of device groups\")\n path := c.xpath(nil)\n return c.con.EntryListUsing(c.con.Get, path[:len(path) - 1])\n}", "func LoanGetList(l models.Loan, m *models.Message) {\n\tm.Code = http.StatusBadRequest\n\tif l.CodCollection <= 0 && l.CodClient <= 0 {\n\t\tm.Message = \"especifique cobro o cliente\"\n\t\treturn\n\t}\n\tls := []models.Loan{l}\n\tdb := configuration.GetConnection()\n\tdefer db.Close()\n\terr := getLoanList(&ls, db)\n\tif err != nil {\n\t\tm.Code = http.StatusBadRequest\n\t\tm.Message = \"no se encontro litado de prestamos\"\n\t\treturn\n\t}\n\tm.Code = http.StatusOK\n\tm.Message = \"lista de prestamos\"\n\tm.Data = ls\n}", "func (this NestedInteger) GetList() []*NestedInteger { panic(\"\") }", "func GetListMembersWithLists(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\r\n\tvar lists []List\r\n\r\n\tjson.NewDecoder(r.Body).Decode(&lists)\r\n\r\n\tvar listMembers = make([]ListMember, 0)\r\n\tfmt.Println(\"lists \", lists)\r\n\tfor _, list := range lists {\r\n\t\tvar listMemberArray []ListMember\r\n\t\tdb.Where(\"listID = ?\", list.UUID).Find(&listMemberArray)\r\n\t\tlistMembers = append(listMembers, listMemberArray...)\r\n\t}\r\n\tfmt.Println(\"listmembers \", listMembers)\r\n\tjson.NewEncoder(w).Encode(listMembers)\r\n}", "func (db *Mysql) GetLists(args *models.GetListsArgs, user *models.User) (*[]models.ListInfo, error) {\n\tvar lists []models.ListInfo\n\n\tteam, err := db.getTeamFromID(args.TeamID)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"func\": \"GetLists\",\n\t\t\t\"subFunc\": \"getTeamFromID\",\n\t\t\t\"userID\": user.ID,\n\t\t\t\"args\": *args,\n\t\t}).Error(err)\n\t\treturn nil, err\n\t}\n\n\tif team.AdminID != user.ID {\n\t\treturn nil, errors.New(\"User not admin of team\")\n\t}\n\n\terr = db.Client.Table(\"lists\").Joins(\"LEFT JOIN tasks on lists.id = tasks.list_id\").\n\t\tSelect(\"lists.*,\"+\n\t\t\t\"sum(case when complete = true AND tasks.archived = false then 1 else 0 end) as completed_tasks,\"+\n\t\t\t\"sum(case when complete = false AND tasks.archived = false then 1 else 0 end) as pending_tasks\").\n\t\tWhere(\"lists.archived = false AND lists.user_id = ? AND lists.team_id = ?\", user.ID, team.ID).\n\t\tGroup(\"lists.id\").\n\t\tFind(&lists).Error\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"func\": \"GetLists\",\n\t\t\t\"info\": \"retrieving list info\",\n\t\t\t\"userID\": user.ID,\n\t\t}).Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn &lists, nil\n}", "func (c *Variable) GetList(tmpl, ts string) ([]string, error) {\n c.con.LogQuery(\"(get) list of template variables\")\n path := c.xpath(tmpl, ts, nil)\n return c.con.EntryListUsing(c.con.Get, path[:len(path) - 1])\n}", "func (yp *YamlParser) getListValue() error {\n\t// Skip prefix token\n\typ.move(len(TkPreListValue))\n\n\tv, err := yp.parseValue(\"\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\typ.currentNode.ntype = NodeTypeList\n\typ.appendValue(v)\n\n\treturn nil\n}", "func ContactListGet() ([]ContactList, error) {\n\tvar contacts []ContactList\n\trows, err := pool.Query(context.Background(), `\n\t\tSELECT\n\t\t\tc.id,\n\t\t\tc.name,\n\t\t\tco.id AS company_id,\n\t\t\tco.name AS company_name,\n\t\t\tpo.name AS post_name,\n\t\t\tarray_agg(DISTINCT ph.phone) AS phones,\n\t\t\tarray_agg(DISTINCT f.phone) AS faxes\n\t\tFROM\n\t\t\tcontacts AS c\n\t\tLEFT JOIN\n\t\t\tcompanies AS co ON c.company_id = co.id\n\t\tLEFT JOIN\n\t\t\tposts AS po ON c.post_id = po.id\n\t\tLEFT JOIN\n\t\t\tphones AS ph ON c.id = ph.contact_id AND ph.fax = false\n\t\tLEFT JOIN\n\t\t\tphones AS f ON c.id = f.contact_id AND f.fax = true\n\t\tGROUP BY\n\t\t\tc.id,\n\t\t\tco.id,\n\t\t\tpo.name\n\t\tORDER BY\n\t\t\tname ASC\n\t`)\n\tif err != nil {\n\t\terrmsg(\"GetContactList Query\", err)\n\t}\n\tfor rows.Next() {\n\t\tvar contact ContactList\n\t\terr := rows.Scan(&contact.ID, &contact.Name, &contact.CompanyID, &contact.CompanyName,\n\t\t\t&contact.PostName, &contact.Phones, &contact.Faxes)\n\t\tif err != nil {\n\t\t\terrmsg(\"GetContactList Scan\", err)\n\t\t\treturn contacts, err\n\t\t}\n\t\tcontacts = append(contacts, contact)\n\t}\n\treturn contacts, rows.Err()\n}", "func (pl *PolledList) List() *pb.ListResponse { return pl.resp.Load().(*pb.ListResponse) }", "func (pl *PolledList) List() *pb.ListResponse { return pl.resp.Load().(*pb.ListResponse) }", "func (a *AccessListService) GetAccessList(ctx context.Context, name string) (*accesslist.AccessList, error) {\n\taccessList, err := a.svc.GetResource(ctx, name)\n\treturn accessList, trace.Wrap(err)\n}", "func (s Store) List() ([]string, error) {\n\treturn s.backingStore.List(ItemType)\n}", "func (m *SharepointIds) GetListId()(*string) {\n val, err := m.GetBackingStore().Get(\"listId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func GetProfileList(ctx context.Context) ([]*shill.Profile, error) {\n\tmanager, err := shill.NewManager(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed creating shill manager object\")\n\t}\n\t// Refresh the in-memory profile list.\n\tif _, err := manager.GetProperties(ctx); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed refreshing the in-memory profile list\")\n\t}\n\t// Get current profiles.\n\tprofiles, err := manager.Profiles(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed getting profile list\")\n\t}\n\treturn profiles, nil\n}", "func (Alert) GetList(ctx goctx.Context, userID uint) []dto.Alert {\n\talerts := context.DB(ctx).Table(\"alert\")\n\n\tvar res []dto.Alert\n\talerts.Where(\"user_id = ?\", userID).Find(&res)\n\n\treturn res\n}", "func (s *PriorityService) GetList(ctx context.Context) ([]Priority, *Response, error) {\n\tapiEndpoint := \"rest/api/2/priority\"\n\treq, err := s.client.NewRequest(ctx, http.MethodGet, apiEndpoint, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpriorityList := []Priority{}\n\tresp, err := s.client.Do(req, &priorityList)\n\tif err != nil {\n\t\treturn nil, resp, NewJiraError(resp, err)\n\t}\n\treturn priorityList, resp, nil\n}", "func (o *GetListParams) SetListID(listID int64) {\n\to.ListID = listID\n}", "func GetList(conn redis.Conn, pattern string) ([]string, error) {\n\treturn redis.Strings(conn.Do(\"KEYS\", pattern))\n}", "func (c *Contract) GetList(offset, limit int64) ([]Contract, error) {\n\tresult := new([]Contract)\n\terr := DBConn.Table(c.TableName()).Offset(offset).Limit(limit).Order(\"id asc\").Find(&result).Error\n\treturn *result, err\n}", "func (r *Readarr) GetImportList(importListID int64) (*ImportListOutput, error) {\n\treturn r.GetImportListContext(context.Background(), importListID)\n}", "func (s *Store) List() []string {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tls := make([]string, 0, len(s.ls))\n\tfor p := range s.ls {\n\t\tls = append(ls, p)\n\t}\n\n\treturn ls\n}", "func (s *Store) List() []string {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tls := make([]string, 0, len(s.ls))\n\tfor p := range s.ls {\n\t\tls = append(ls, p)\n\t}\n\n\treturn ls\n}", "func (a *Client) GetTokenList(params *GetTokenListParams) (*GetTokenListOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetTokenListParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getTokenList\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/asset/tokens\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetTokenListReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetTokenListOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for getTokenList: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (s Store) List() ([]string, error) {\n\treturn s.backingStore.List(ItemType, \"\")\n}", "func (c *cache) GetDeviceList() (devList []lava.DeviceList, err error) {\n\terr = c.updateDeviceList()\n\tdevList = c.deviceList.DeviceList\n\n\treturn\n}", "func (o *GetListParams) WithTimeout(timeout time.Duration) *GetListParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (b *ListBuilder) List() *CSPList {\n\treturn b.CspList\n}", "func (client Client) GetListResponder(resp *http.Response) (result VolumeInstanceListResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (l *list) Get() interface{} {\n\ttypeOf := reflect.TypeOf(l.t)\n\tsliceOf := reflect.SliceOf(typeOf)\n\tvar result = reflect.ValueOf(reflect.New(sliceOf).Interface()).Elem()\n\n\tl.ForEach(func(index int, el interface{}) {\n\t\tresult.Set(reflect.Append(result, reflect.ValueOf(el)))\n\t})\n\n\treturn result.Interface()\n}", "func (b *Base) GetSlotList(req *GetSlotListReq) (*GetSlotListResp, error) {\n\treturn nil, ErrFunctionNotSupported\n}", "func (client ListManagementTermListsClient) GetDetails(ctx context.Context, listID string) (result TermList, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListManagementTermListsClient.GetDetails\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.GetDetailsPreparer(ctx, listID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementTermListsClient\", \"GetDetails\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetDetailsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementTermListsClient\", \"GetDetails\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetDetailsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementTermListsClient\", \"GetDetails\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (s *SalesPriceListDetailsEndpoint) List(ctx context.Context, division int, all bool, o *api.ListOptions) ([]*SalesPriceListDetails, error) {\n\tvar entities []*SalesPriceListDetails\n\tu, _ := s.client.ResolvePathWithDivision(\"/api/v1/{division}/sales/SalesPriceListDetails\", division) // #nosec\n\tapi.AddListOptionsToURL(u, o)\n\n\tif all {\n\t\terr := s.client.ListRequestAndDoAll(ctx, u.String(), &entities)\n\t\treturn entities, err\n\t}\n\t_, _, err := s.client.NewRequestAndDo(ctx, \"GET\", u.String(), nil, &entities)\n\treturn entities, err\n}", "func (m *List) SetList(value ListInfoable)() {\n m.list = value\n}", "func (f *FeatureGateClient) GetFeatureList(ctx context.Context) (*corev1alpha2.FeatureList, error) {\n\tfeatures := &corev1alpha2.FeatureList{}\n\terr := f.crClient.List(ctx, features)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get features on cluster: %w\", err)\n\t}\n\treturn features, nil\n}", "func (obj *Global) GetStreamList(ctx context.Context) ([]*NxStreamListEntry, error) {\n\tresult := &struct {\n\t\tStreamList []*NxStreamListEntry `json:\"qStreamList\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetStreamList\", result)\n\treturn result.StreamList, err\n}", "func (a Accessor) GetSubscriptionList(service, servicePath string, subscriptions *[]Subscription) error {\n\treturn a.access(&AccessParameter{\n\t\tEpID: EntryPointIDs.Subscriptions,\n\t\tMethod: gohttp.HttpMethods.GET,\n\t\tService: service,\n\t\tServicePath: servicePath,\n\t\tPath: \"\",\n\t\tReceivedBody: subscriptions,\n\t})\n}", "func GetLists(ctx Context) {\n\titems, err := db.SelectAllItems()\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\tctx.JSON(http.StatusOK, items)\n}", "func GetSecretList(c *gin.Context) {\n\trepo := session.Repo(c)\n\tlist, err := Config.Services.Secrets.SecretList(repo)\n\tif err != nil {\n\t\tc.String(500, \"Error getting secret list. %s\", err)\n\t\treturn\n\t}\n\t// copy the secret detail to remove the sensitive\n\t// password and token fields.\n\tfor i, secret := range list {\n\t\tlist[i] = secret.Copy()\n\t}\n\tc.JSON(200, list)\n}", "func (obj *Global) GetDocListRaw(ctx context.Context) (json.RawMessage, error) {\n\tresult := &struct {\n\t\tDocList json.RawMessage `json:\"qDocList\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetDocList\", result)\n\treturn result.DocList, err\n}", "func (r *r) List() ([]*internal.Item, error) {\n\treturn nil, fmt.Errorf(\"not implemented yet\")\n}", "func (s *ServerConnection) MailingListsGet(query SearchQuery, domainId KId) (MlList, int, error) {\n\tquery = addMissedParametersToSearchQuery(query)\n\tparams := struct {\n\t\tQuery SearchQuery `json:\"query\"`\n\t\tDomainId KId `json:\"domainId\"`\n\t}{query, domainId}\n\tdata, err := s.CallRaw(\"MailingLists.get\", params)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tlist := struct {\n\t\tResult struct {\n\t\t\tList MlList `json:\"list\"`\n\t\t\tTotalItems int `json:\"totalItems\"`\n\t\t} `json:\"result\"`\n\t}{}\n\terr = json.Unmarshal(data, &list)\n\treturn list.Result.List, list.Result.TotalItems, err\n}", "func (r *FakeClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {\n\t// TODO (covariance) implement me!\n\tpanic(\"not implemented\")\n}", "func (c *Checklist) GetChecklist(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\tjson.NewEncoder(w).Encode(c.Items)\n}", "func (l *ToDoList) showList() []string {\n\treturn l.list\n}", "func (s *CallListsService) GetCallListDetails(params GetCallListDetailsParams) (*GetCallListDetailsReturn, *structure.VError, error) {\n\treq, err := s.client.NewRequest(\"POST\", \"GetCallListDetails\", params)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tresponse := &GetCallListDetailsReturn{}\n\tverr, err := s.client.MakeResponse(req, response)\n\tif verr != nil || err != nil {\n\t\treturn nil, verr, err\n\t}\n\treturn response, nil, nil\n}" ]
[ "0.7402214", "0.7211892", "0.7197566", "0.7090484", "0.7002887", "0.69607484", "0.69395965", "0.68194044", "0.6801362", "0.67747223", "0.6725991", "0.663443", "0.66022295", "0.6588623", "0.65876096", "0.65801454", "0.65714175", "0.65714175", "0.6566503", "0.6454622", "0.6409096", "0.62911844", "0.6214806", "0.61964786", "0.6189537", "0.61595297", "0.6131997", "0.6122757", "0.6096117", "0.60928833", "0.607829", "0.6032064", "0.6019856", "0.6009313", "0.59953886", "0.5995058", "0.59682524", "0.59586746", "0.5956028", "0.5946521", "0.59375024", "0.59360474", "0.5907806", "0.590699", "0.5904573", "0.5900708", "0.5887597", "0.58861136", "0.58836395", "0.58677685", "0.5859086", "0.58510494", "0.5848091", "0.5843247", "0.58289564", "0.58079445", "0.5795391", "0.57594067", "0.57368976", "0.5726731", "0.5726342", "0.5725025", "0.57040745", "0.56986004", "0.56986004", "0.56910485", "0.5686415", "0.5684947", "0.56814915", "0.56669605", "0.5662032", "0.56364954", "0.56356364", "0.5635325", "0.56235534", "0.5616956", "0.5616956", "0.5607719", "0.56061846", "0.5602275", "0.5587779", "0.55870914", "0.5584738", "0.5575373", "0.55726343", "0.5565984", "0.55541855", "0.55519086", "0.55456835", "0.5539817", "0.5537219", "0.552446", "0.55157477", "0.5508771", "0.5503025", "0.54980165", "0.54913", "0.5489442", "0.5485862", "0.54849756" ]
0.7468337
0
GetOperations gets the operations property value. The collection of longrunning operations on the list.
func (m *List) GetOperations()([]RichLongRunningOperationable) { return m.operations }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *Endpoint) GetOperations() []models.EndpointOperation {\n\treturn e.Operations\n}", "func GetOperations() ([]dtos.Operation, error) {\n\tvar ops []dtos.Operation\n\n\tresp, err := makeJSONRequest(\"GET\", apiURL+\"/operations\", http.NoBody)\n\tif err != nil {\n\t\treturn ops, errors.Append(err, ErrCannotConnect)\n\t}\n\n\tif err = evaluateResponseStatusCode(resp.StatusCode); err != nil {\n\t\treturn ops, err\n\t}\n\n\terr = readResponseBody(&ops, resp.Body)\n\n\treturn ops, err\n}", "func (m *Microservice) GetOperations(status string) (*c8y.OperationCollection, *c8y.Response, error) {\n\topt := &c8y.OperationCollectionOptions{\n\t\tStatus: status,\n\t\tAgentID: m.AgentID,\n\t\tPaginationOptions: c8y.PaginationOptions{\n\t\t\tPageSize: 5,\n\t\t\tWithTotalPages: false,\n\t\t},\n\t}\n\n\tdata, resp, err := m.Client.Operation.GetOperations(m.WithServiceUser(), opt)\n\treturn data, resp, err\n}", "func (c *jobsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v2/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (client BaseClient) ListOperations(ctx context.Context) (result Operations, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/BaseClient.ListOperations\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.ListOperationsPreparer(ctx)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"serialconsole.BaseClient\", \"ListOperations\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListOperationsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"serialconsole.BaseClient\", \"ListOperations\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.ListOperationsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"serialconsole.BaseClient\", \"ListOperations\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (c *tensorboardRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/ui/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (process *Process) GetOperations() []*Operation {\n\n\t// fields\n\tfieldList := \"operation.id, operation.content, operation.start, operation.end, operation.is_running, operation.current_task, operation.result\"\n\n\t// the query\n\tsql := \"SELECT \" + fieldList + \" FROM `operation` AS operation WHERE process=? ORDER BY operation.id DESC\"\n\n\trows, err := database.Connection.Query(sql, process.Action.ID)\n\tif err != nil {\n\t\tfmt.Println(\"Problem #7 when getting all the operations of the process: \")\n\t\tfmt.Println(err)\n\t}\n\n\tvar (\n\t\tlist []*Operation\n\t\tID, currentTaskID int\n\t\tstart, end int64\n\t\tisRunning bool\n\t\tcontent, isRunningString, result string\n\t\ttask *Task\n\t)\n\n\tfor rows.Next() {\n\t\trows.Scan(&ID, &content, &start, &end, &isRunningString, &currentTaskID, &result)\n\n\t\tisRunning, err = strconv.ParseBool(isRunningString)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t\tif isRunning {\n\t\t\ttask = NewTask(currentTaskID)\n\t\t}\n\n\t\tlist = append(list, &Operation{\n\t\t\tCurrentTask: task,\n\t\t\tAction: &Action{\n\t\t\t\tID: ID,\n\t\t\t\tIsRunning: isRunning,\n\t\t\t\tStart: start,\n\t\t\t\tEnd: end,\n\t\t\t\tContent: content,\n\t\t\t\tresult: result,\n\t\t\t},\n\t\t})\n\t}\n\treturn list\n}", "func (c *cloudChannelRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (c *Controller) GetOperations() []operation.Handler {\n\treturn c.handlers\n}", "func (c *Controller) GetOperations() []operation.Handler {\n\treturn c.handlers\n}", "func (r *SpanReader) GetOperations(ctx context.Context, service string) ([]string, error){\n\treturn r.cache.LoadOperations(service)\n}", "func (m *Workbook) GetOperations()([]WorkbookOperationable) {\n return m.operations\n}", "func (m *List) SetOperations(value []RichLongRunningOperationable)() {\n m.operations = value\n}", "func (m *ExternalConnection) GetOperations()([]ConnectionOperationable) {\n return m.operations\n}", "func (so *Operations) Operations() api.Operations {\n\treturn api.Operations(so)\n}", "func (reader *LogzioSpanReader) GetOperations(ctx context.Context, query spanstore.OperationQueryParameters) ([]spanstore.Operation, error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"GetOperations\")\n\tdefer span.Finish()\n\toperations, err := reader.serviceOperationStorage.getOperations(ctx, query.ServiceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result []spanstore.Operation\n\tfor _, operation := range operations {\n\t\tresult = append(result, spanstore.Operation{\n\t\t\tName: operation,\n\t\t})\n\t}\n\treturn result, err\n\n\n}", "func (c *workflowsServiceV2BetaRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v2beta/%v/operations\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (m *Master) GetOperations(session *gocql.Session, hostname string) ([]ops.Operation, error) {\n\tvar operations []ops.Operation\n\tvar description, scriptName string\n\tvar attributes map[string]string\n\tq := `SELECT description, script_name, attributes FROM operations where hostname = ?`\n\titer := session.Query(q, hostname).Iter()\n\tfor iter.Scan(&description, &scriptName, &attributes) {\n\t\to := ops.Operation{\n\t\t\tDescription: description,\n\t\t\tScriptName: scriptName,\n\t\t\tAttributes: attributes,\n\t\t}\n\t\toperations = append(operations, o)\n\t}\n\tif err := iter.Close(); err != nil {\n\t\treturn []ops.Operation{}, fmt.Errorf(\"error getting operations from DB: %v\", err)\n\t}\n\n\treturn operations, nil\n}", "func (c *CloudChannelClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (bq *InMemoryBuildQueue) ListOperations(ctx context.Context, request *buildqueuestate.ListOperationsRequest) (*buildqueuestate.ListOperationsResponse, error) {\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\t// Obtain operation names in sorted order.\n\tnameList := make([]string, 0, len(bq.operationsNameMap))\n\tfor name := range bq.operationsNameMap {\n\t\tnameList = append(nameList, name)\n\t}\n\tsort.Strings(nameList)\n\tpaginationInfo, endIndex := getPaginationInfo(len(nameList), request.PageSize, func(i int) bool {\n\t\treturn request.StartAfter == nil || nameList[i] > request.StartAfter.OperationName\n\t})\n\n\t// Extract status.\n\tnameListRegion := nameList[paginationInfo.StartIndex:endIndex]\n\toperations := make([]*buildqueuestate.OperationState, 0, len(nameListRegion))\n\tfor _, name := range nameListRegion {\n\t\to := bq.operationsNameMap[name]\n\t\toperations = append(operations, o.getOperationState(bq))\n\t}\n\treturn &buildqueuestate.ListOperationsResponse{\n\t\tOperations: operations,\n\t\tPaginationInfo: paginationInfo,\n\t}, nil\n}", "func (c *Client) ListOperations(ctx context.Context, params *ListOperationsInput, optFns ...func(*Options)) (*ListOperationsOutput, error) {\n\tif params == nil {\n\t\tparams = &ListOperationsInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListOperations\", params, optFns, addOperationListOperationsMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListOperationsOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (cli *FakeDatabaseClient) ListOperations(ctx context.Context, in *lropb.ListOperationsRequest, opts ...grpc.CallOption) (*lropb.ListOperationsResponse, error) {\n\tatomic.AddInt32(&cli.listOperationsCalledCnt, 1)\n\treturn nil, nil\n}", "func ListOperations() ([]*op.Operation, error) {\n\tmessage := protocol.NewRequestListMessage()\n\terr := channel.Broadcast(message)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc1 := make(chan *protocol.ResponseList)\n\n\tonResponse := func(response *protocol.ResponseList) {\n\t\tc1 <- response\n\t}\n\n\tbus.SubscribeOnce(string(message.RequestList.ID), onResponse)\n\n\tselect {\n\tcase res := <-c1:\n\t\tif res.Result == protocol.ResponseOk {\n\t\t\treturn res.Operations, nil\n\t\t}\n\n\t\treturn nil, errors.New(string(res.Message))\n\tcase <-time.After(10 * time.Second):\n\t\tbus.Unsubscribe(string(message.RequestList.ID), onResponse)\n\t\treturn nil, errors.New(\"timeout\")\n\t}\n}", "func (o NamedRuleWithOperationsPatchOutput) Operations() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v NamedRuleWithOperationsPatch) []string { return v.Operations }).(pulumi.StringArrayOutput)\n}", "func Operations() (string, error) {\n\treturn makeRequest(\"operations\")\n}", "func (c *TensorboardClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *JobsClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *WorkflowsServiceV2BetaClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *Client) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *Client) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (c *cloudChannelReportsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\tit := &OperationIterator{}\n\treq = proto.Clone(req).(*longrunningpb.ListOperationsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {\n\t\tresp := &longrunningpb.ListOperationsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v\", req.GetName())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetOperations(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (o NamedRuleWithOperationsOutput) Operations() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v NamedRuleWithOperations) []string { return v.Operations }).(pulumi.StringArrayOutput)\n}", "func (s *OperationNamesStorage) GetOperations(service string) ([]string, error) {\n\titer := s.session.Query(s.QueryStmt, service).Iter()\n\n\tvar operation string\n\tvar operations []string\n\tfor iter.Scan(&operation) {\n\t\toperations = append(operations, operation)\n\t}\n\tif err := iter.Close(); err != nil {\n\t\terr = errors.Wrap(err, \"Error reading operation_names from storage\")\n\t\treturn nil, err\n\t}\n\treturn operations, nil\n}", "func (r *OperationsService) List(name string) *OperationsListCall {\n\tc := &OperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *OperationsService) List(name string) *OperationsListCall {\n\tc := &OperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (c *PolicyBasedRoutingClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func (r *ManagedAppRegistrationOperationsCollectionRequest) Get(ctx context.Context) ([]ManagedAppOperation, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil)\n}", "func (db Db) GetOperations(portfolioID string, key string, value string, from string, to string) ([]models.Operation, error) {\n\tpid, err := primitive.ObjectIDFromHex(portfolioID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not decode portfolio Id (%s). Internal error : %s\", portfolioID, err)\n\t}\n\n\tfilter := bson.M{\"pid\": pid}\n\tand := []interface{}{}\n\thasParams := false\n\tif key != \"\" && value != \"\" {\n\t\tand = append(and, bson.M{key: value})\n\t\thasParams = true\n\t}\n\n\tif dtime, err := time.Parse(\"2006-01-02T15:04:05Z07:00\", from); err == nil {\n\t\tand = append(and, bson.M{\"time\": bson.M{\"$gte\": dtime}})\n\t\thasParams = true\n\t}\n\n\tif dtime, err := time.Parse(\"2006-01-02T15:04:05Z07:00\", to); err == nil {\n\t\tand = append(and, bson.M{\"time\": bson.M{\"$lte\": dtime}})\n\t\thasParams = true\n\t}\n\tif hasParams {\n\t\tand = append(and, filter)\n\t\tfilter = bson.M{\"$and\": and}\n\t}\n\n\tfindOptions := options.Find()\n\tfindOptions.SetSort(bson.M{\"time\": 1})\n\treturn db.getOperations(filter, findOptions)\n}", "func (client *ApplicationClient) ListOperations(options *ApplicationClientListOperationsOptions) *ApplicationClientListOperationsPager {\n\treturn &ApplicationClientListOperationsPager{\n\t\tclient: client,\n\t\trequester: func(ctx context.Context) (*policy.Request, error) {\n\t\t\treturn client.listOperationsCreateRequest(ctx, options)\n\t\t},\n\t\tadvancer: func(ctx context.Context, resp ApplicationClientListOperationsResponse) (*policy.Request, error) {\n\t\t\treturn runtime.NewRequest(ctx, http.MethodGet, *resp.OperationListResult.NextLink)\n\t\t},\n\t}\n}", "func (eClass *eClassImpl) GetEAllOperations() EList {\n\teClass.getInitializers().initEAllOperations()\n\treturn eClass.eAllOperations\n}", "func (eClass *eClassImpl) GetEOperations() EList {\n\tif eClass.eOperations == nil {\n\t\teClass.eOperations = eClass.getInitializers().initEOperations()\n\t}\n\treturn eClass.eOperations\n}", "func (dop *patchCollector) Operations() []OperationSpec {\n\treturn dop.patchOperations\n}", "func (om *OperationsManager) GetOperation(ctx context.Context) (*model.Operation, error) {\n\tom.mutex.Lock()\n\tdefer om.mutex.Unlock()\n\n\ttx, err := om.transact.Begin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer om.transact.RollbackUnlessCommitted(ctx, tx)\n\tctx = persistence.SaveToContext(ctx, tx)\n\n\toperations, err := om.opSvc.ListPriorityQueue(ctx, om.cfg.PriorityQueueLimit, om.opType)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"while fetching operations from priority queue with type %v \", om.opType)\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, operation := range operations {\n\t\top, err := om.tryToGetOperation(ctx, operation.ID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif op != nil {\n\t\t\treturn op, nil\n\t\t}\n\t}\n\treturn nil, apperrors.NewNoScheduledOperationsError()\n}", "func NewOperations() *Operations {\n\treturn &Operations{}\n}", "func (r *InspectOperationsService) List(name string) *InspectOperationsListCall {\n\tc := &InspectOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (c *CloudChannelReportsClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {\n\treturn c.internalClient.ListOperations(ctx, req, opts...)\n}", "func getOperations(props *spec.PathItem) map[string]*spec.Operation {\n\tops := map[string]*spec.Operation{\n\t\t\"DELETE\": props.Delete,\n\t\t\"GET\": props.Get,\n\t\t\"HEAD\": props.Head,\n\t\t\"OPTIONS\": props.Options,\n\t\t\"PATCH\": props.Patch,\n\t\t\"POST\": props.Post,\n\t\t\"PUT\": props.Put,\n\t}\n\n\t// Keep those != nil\n\tfor key, op := range ops {\n\t\tif op == nil {\n\t\t\tdelete(ops, key)\n\t\t}\n\t}\n\treturn ops\n}", "func GetAll() (result []Operation) {\n\tview(func(k, v []byte) {\n\t\top := &Operation{}\n\t\tboltdb.DecodeValue(v, op, cfg.DataEncoding)\n\t\tresult = append(result, *op)\n\t})\n\treturn\n}", "func (p *profileCache) ResourceOperations(profileName string, cmd string, method string) ([]models.ResourceOperation, errors.EdgeX) {\n\tp.mutex.RLock()\n\tdefer p.mutex.RUnlock()\n\n\tif err := p.verifyProfileExists(profileName); err != nil {\n\t\treturn nil, err\n\t}\n\n\trosMap, err := p.verifyResourceOperationsExists(method, profileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ok bool\n\tvar ros []models.ResourceOperation\n\tif ros, ok = rosMap[cmd]; !ok {\n\t\terrMsg := fmt.Sprintf(\"failed to find DeviceCommand %s in Profile %s\", cmd, profileName)\n\t\treturn nil, errors.NewCommonEdgeX(errors.KindEntityDoesNotExist, errMsg, nil)\n\t}\n\n\treturn ros, nil\n}", "func (m *ExternalConnection) SetOperations(value []ConnectionOperationable)() {\n m.operations = value\n}", "func (p *Postgres) Operations() []bindings.OperationKind {\n\treturn []bindings.OperationKind{\n\t\texecOperation,\n\t\tqueryOperation,\n\t\tcloseOperation,\n\t}\n}", "func (client BaseClient) ListOperationsResponder(resp *http.Response) (result Operations, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (o *StoragePhysicalDisk) GetBackgroundOperations() string {\n\tif o == nil || o.BackgroundOperations == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.BackgroundOperations\n}", "func (op *OperationRequest) SetOperationsEndpoint() *OperationRequest {\n\treturn op.setEndpoint(\"operations\")\n}", "func (client BaseClient) GetAllOperations(ctx context.Context, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (result SetObject, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/BaseClient.GetAllOperations\")\n defer func() {\n sc := -1\n if result.Response.Response != nil {\n sc = result.Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.GetAllOperationsPreparer(ctx, xMsRequestid, xMsCorrelationid)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetAllOperations\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.GetAllOperationsSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetAllOperations\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.GetAllOperationsResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetAllOperations\", resp, \"Failure responding to request\")\n }\n\n return\n }", "func (b *ManagedAppRegistrationRequestBuilder) Operations() *ManagedAppRegistrationOperationsCollectionRequestBuilder {\n\tbb := &ManagedAppRegistrationOperationsCollectionRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.baseURL += \"/operations\"\n\treturn bb\n}", "func ToOperations(operations []operation.Operation) ([]*api.Operation, error) {\n\tvar pbOperations []*api.Operation\n\n\tfor _, o := range operations {\n\t\tpbOperation := &api.Operation{}\n\t\tvar err error\n\t\tswitch op := o.(type) {\n\t\tcase *operation.Set:\n\t\t\tpbOperation.Body, err = toSet(op)\n\t\tcase *operation.Add:\n\t\t\tpbOperation.Body, err = toAdd(op)\n\t\tcase *operation.Move:\n\t\t\tpbOperation.Body, err = toMove(op)\n\t\tcase *operation.Remove:\n\t\t\tpbOperation.Body, err = toRemove(op)\n\t\tcase *operation.Edit:\n\t\t\tpbOperation.Body, err = toEdit(op)\n\t\tcase *operation.Select:\n\t\t\tpbOperation.Body, err = toSelect(op)\n\t\tcase *operation.RichEdit:\n\t\t\tpbOperation.Body, err = toRichEdit(op)\n\t\tcase *operation.Style:\n\t\t\tpbOperation.Body, err = toStyle(op)\n\t\tcase *operation.Increase:\n\t\t\tpbOperation.Body, err = toIncrease(op)\n\t\tdefault:\n\t\t\treturn nil, ErrUnsupportedOperation\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpbOperations = append(pbOperations, pbOperation)\n\t}\n\n\treturn pbOperations, nil\n}", "func (m *Workbook) SetOperations(value []WorkbookOperationable)() {\n m.operations = value\n}", "func (handler *NullHandler) Operations() api_operation.Operations {\n\tops := api_operation.New_SimpleOperations()\n\n\t// Add Null config operations\n\tops.Add(api_operation.Operation(&NullConfigReadersOperation{}))\n\tops.Add(api_operation.Operation(&NullConfigWritersOperation{}))\n\t// Add Null setting operations\n\tops.Add(api_operation.Operation(&NullSettingGetOperation{}))\n\tops.Add(api_operation.Operation(&NullSettingSetOperation{}))\n\t// Add Null command operations\n\tops.Add(api_operation.Operation(&NullCommandListOperation{}))\n\tops.Add(api_operation.Operation(&NullCommandExecOperation{}))\n\t// Add Null documentation operations\n\tops.Add(api_operation.Operation(&NullDocumentTopicListOperation{}))\n\tops.Add(api_operation.Operation(&NullDocumentTopicGetOperation{}))\n\t// Add null monitor operations\n\tops.Add(api_operation.Operation(&NullMonitorStatusOperation{}))\n\tops.Add(api_operation.Operation(&NullMonitorInfoOperation{}))\n\tops.Add(api_operation.Operation(&api_monitor.MonitorStandardLogOperation{}))\n\t// Add Null orchestration operations\n\tops.Add(api_operation.Operation(&NullOrchestrateUpOperation{}))\n\tops.Add(api_operation.Operation(&NullOrchestrateDownOperation{}))\n\t// Add Null security handlers\n\tops.Add(api_operation.Operation(&NullSecurityAuthenticateOperation{}))\n\tops.Add(api_operation.Operation(&NullSecurityAuthorizeOperation{}))\n\tops.Add(api_operation.Operation(&NullSecurityUserOperation{}))\n\n\treturn ops.Operations()\n}", "func NewOperations(\n\texecutor interfaces.CommandExecutor,\n\tlc logger.LoggingClient,\n\texecutorPath string) *operations {\n\n\treturn &operations{\n\t\texecutor: executor,\n\t\tloggingClient: lc,\n\t\texecutorPath: executorPath,\n\t}\n}", "func (q *Q) Operations() OperationsQI {\n\treturn &OperationsQ{\n\t\tparent: q,\n\t\tsql: selectOperation,\n\t}\n}", "func (o *ResourceDefinitionFilter) GetOperation() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Operation\n}", "func (c *CloudChannelClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\treturn c.internalClient.GetOperation(ctx, req, opts...)\n}", "func (g *Grafeas) GetOperation(pID, oID string) (*swagger.Operation, *errors.AppError) {\n\treturn g.S.GetOperation(pID, oID)\n}", "func (c *jobsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v2/%v\", req.GetName())\n\n\tparams := url.Values{}\n\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\n\tbaseUrl.RawQuery = params.Encode()\n\n\t// Build HTTP headers from client and context metadata.\n\thds := []string{\"x-goog-request-params\", fmt.Sprintf(\"%s=%v\", \"name\", url.QueryEscape(req.GetName()))}\n\n\thds = append(c.xGoogHeaders, hds...)\n\thds = append(hds, \"Content-Type\", \"application/json\")\n\theaders := gax.BuildHeaders(ctx, hds...)\n\topts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tresp := &longrunningpb.Operation{}\n\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\tif settings.Path != \"\" {\n\t\t\tbaseUrl.Path = settings.Path\n\t\t}\n\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpReq = httpReq.WithContext(ctx)\n\t\thttpReq.Header = headers\n\n\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer httpRsp.Body.Close()\n\n\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}, opts...)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn resp, nil\n}", "func (client ManagementClient) GetOperationResults(hostName string, filter string, top *int32, selectParameter string) (result OperationResultCollection, err error) {\n\treq, err := client.GetOperationResultsPreparer(hostName, filter, top, selectParameter)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"intune.ManagementClient\", \"GetOperationResults\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetOperationResultsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"intune.ManagementClient\", \"GetOperationResults\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetOperationResultsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"intune.ManagementClient\", \"GetOperationResults\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (b *backend) GetSiteOperations(siteDomain string) ([]storage.SiteOperation, error) {\n\tif siteDomain == \"\" {\n\t\treturn nil, trace.BadParameter(\"missing parameter SiteDomain\")\n\t}\n\tids, err := b.getKeys(b.key(sitesP, siteDomain, operationsP))\n\tif err != nil {\n\t\tif trace.IsNotFound(err) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar out []storage.SiteOperation\n\tvar uncachedOperations []string\n\n\tb.cachedCompleteOperationsMutex.RLock()\n\tfor _, id := range ids {\n\t\tif op, ok := b.cachedCompleteOperations[id]; ok {\n\t\t\tout = append(out, *op)\n\t\t} else {\n\t\t\tuncachedOperations = append(uncachedOperations, id)\n\t\t}\n\t}\n\tb.cachedCompleteOperationsMutex.RUnlock()\n\n\tfor _, id := range uncachedOperations {\n\t\top, err := b.GetSiteOperation(siteDomain, id)\n\t\tif err != nil {\n\t\t\tif !trace.IsNotFound(err) {\n\t\t\t\treturn nil, trace.Wrap(err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tout = append(out, *op)\n\t}\n\n\tsort.Sort(operationsSorter(out))\n\treturn out, nil\n}", "func ExampleOperationsClient_List() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armmonitor.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewOperationsClient().List(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.OperationListResult = armmonitor.OperationListResult{\n\t// \tValue: []*armmonitor.Operation{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Operations/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Operations read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Operations\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/MetricDefinitions/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric definitions read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric Definitions\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Metrics/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metrics read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metrics\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/MetricAlerts/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric alert write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric alerts\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/MetricAlerts/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric alert delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric alerts\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/MetricAlerts/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric alert read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric alerts\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale Setting write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale Setting delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale Setting read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Incidents/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule Incidents read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rule Incident resource\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/providers/Microsoft.Insights/MetricDefinitions/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Metric definitions read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Metric Definitions\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActionGroups/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Action group write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Action groups\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActionGroups/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Action group delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Action groups\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActionGroups/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Action group read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Action groups\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActivityLogAlerts/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Activity log alert read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Activity log alert\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActivityLogAlerts/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Activity log alert delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Activity log alert\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActivityLogAlerts/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Activity log alert read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Activity log alert\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ActivityLogAlerts/Activated/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Activity Log Alert Activated\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Activity Log Alert\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/EventCategories/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Event category read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Event category\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/eventtypes/values/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Event types management values read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Events\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/eventtypes/digestevents/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Event types management digest read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Digest events\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/DiagnosticSettings/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Diagnostic settings write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/DiagnosticSettings/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Diagnostic settings delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/DiagnosticSettings/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Diagnostic settings read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ExtendedDiagnosticSettings/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Extended Diagnostic settings write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Extended Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ExtendedDiagnosticSettings/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Extended Diagnostic settings delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Extended Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/ExtendedDiagnosticSettings/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Extended Diagnostic settings read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Extended Diagnostic settings\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/LogProfiles/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Log profile write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Log Profiles\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/LogProfiles/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Log profile delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Log Profiles\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/LogProfiles/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Log profile read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Log Profiles\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/LogDefinitions/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Log Definitions read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Log Definitions\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Scaleup/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale scale up operation\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AutoscaleSettings/Scaledown/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Autoscale scale down operation\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Autoscale\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Activated/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule activated\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Resolved/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule resolved\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/AlertRules/Throttled/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Alert Rule throttled\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Alert Rules\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Register/Action\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Register Microsoft.Insights\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Microsoft.Insights\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Components/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Application insights component write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Application insights components\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Components/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Application insights component delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Application insights components\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Components/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Application insights component read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Application insights components\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Webtests/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Webtest write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Web tests\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Webtests/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Webtest delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Monitoring Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Web tests\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Workbooks/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Workbooks read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Application Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Workbooks\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Workbooks/Write\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Workbooks write\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Application Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Workbooks\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Workbooks/Delete\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Workbooks delete\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Application Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Workbooks\"),\n\t// \t\t\t},\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"Microsoft.Insights/Workbooks/Read\"),\n\t// \t\t\tDisplay: &armmonitor.OperationDisplay{\n\t// \t\t\t\tOperation: to.Ptr(\"Workbooks read\"),\n\t// \t\t\t\tProvider: to.Ptr(\"Microsoft Application Insights\"),\n\t// \t\t\t\tResource: to.Ptr(\"Workbooks\"),\n\t// \t\t\t},\n\t// \t}},\n\t// }\n}", "func (r *AppsOperationsService) Get(appsId string, operationsId string) *AppsOperationsGetCall {\n\tc := &AppsOperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.appsId = appsId\n\tc.operationsId = operationsId\n\treturn c\n}", "func (c *TensorboardClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\treturn c.internalClient.GetOperation(ctx, req, opts...)\n}", "func (c *JobsClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\treturn c.internalClient.GetOperation(ctx, req, opts...)\n}", "func (bc *BaseController) GetOperationsByPermissionID(rID int64) ([]*dream.Operation, error) {\n\n\tresult, err := dream.GetOperationsByPermissionID(bc.DB, rID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}", "func (cli *FakeDatabaseClient) GetOperation(context.Context, *longrunning.GetOperationRequest, ...grpc.CallOption) (*longrunning.Operation, error) {\n\tatomic.AddInt32(&cli.getOperationCalledCnt, 1)\n\n\tswitch cli.NextGetOperationStatus() {\n\tcase StatusDone:\n\t\treturn &longrunning.Operation{Done: true}, nil\n\n\tcase StatusDoneWithError:\n\t\treturn &longrunning.Operation{\n\t\t\tDone: true,\n\t\t\tResult: &longrunning.Operation_Error{\n\t\t\t\tError: &status.Status{Code: int32(codes.Unknown), Message: \"Test Error\"},\n\t\t\t},\n\t\t}, nil\n\n\tcase StatusRunning:\n\t\treturn &longrunning.Operation{}, nil\n\n\tcase StatusNotFound:\n\t\treturn nil, grpcstatus.Errorf(codes.NotFound, \"\")\n\n\tcase StatusUndefined:\n\t\tpanic(\"Misconfigured test, set up expected operation status\")\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unknown status: %v\", cli.NextGetOperationStatus()))\n\t}\n}", "func (r *AppsOperationsService) List(appsId string) *AppsOperationsListCall {\n\tc := &AppsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.appsId = appsId\n\treturn c\n}", "func (handler *LocalHandler_Setting) Operations() api_operation.Operations {\n\tops := api_operation.New_SimpleOperations()\n\n\t// Make a wrapper for the Settings Config interpretation, based on itnerpreting YML settings\n\twrapper := handler_configwrapper.SettingsConfigWrapper(handler_configwrapper.New_BaseSettingConfigWrapperYmlOperation(handler.ConfigWrapper()))\n\n\t// Now we can add config operations that use that Base class\n\tops.Add(api_operation.Operation(&handler_configwrapper.SettingConfigWrapperGetOperation{Wrapper: wrapper}))\n\tops.Add(api_operation.Operation(&handler_configwrapper.SettingConfigWrapperSetOperation{Wrapper: wrapper}))\n\tops.Add(api_operation.Operation(&handler_configwrapper.SettingConfigWrapperListOperation{Wrapper: wrapper}))\n\n\treturn ops.Operations()\n}", "func (operation *Operation) GetTasks() []*Task {\n\n\t// fields\n\tfieldList := \"task.id, task.content, task.start, task.end, task.is_running, task.result, task.explication\"\n\n\t// the query\n\tsql := \"SELECT \" + fieldList + \" FROM `task` WHERE operation=? ORDER BY task.id DESC\"\n\n\trows, err := database.Connection.Query(sql, operation.Action.ID)\n\tif err != nil {\n\t\tfmt.Println(\"Problem when getting all the tasks of the operation (Error #5): \")\n\t\tfmt.Println(err)\n\t}\n\n\tvar (\n\t\tlist []*Task\n\t\tID int\n\t\tstart, end int64\n\t\tisRunning bool\n\t\tcontent, isRunningString, result, explication string\n\t)\n\n\tfor rows.Next() {\n\t\trows.Scan(&ID, &content, &start, &end, &isRunningString, &result, &explication)\n\n\t\tisRunning, err = strconv.ParseBool(isRunningString)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t\tlist = append(list, &Task{\n\t\t\tExplication: explication,\n\t\t\tAction: &Action{\n\t\t\t\tID: ID,\n\t\t\t\tIsRunning: isRunning,\n\t\t\t\tStart: start,\n\t\t\t\tEnd: end,\n\t\t\t\tContent: content,\n\t\t\t\tresult: result,\n\t\t\t},\n\t\t})\n\t}\n\treturn list\n}", "func GetActiveOperations(siteKey SiteKey, operator Operator) (active []SiteOperation, err error) {\n\toperations, err := operator.GetSiteOperations(siteKey, OperationsFilter{\n\t\tActive: true,\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tif len(operations) == 0 {\n\t\treturn nil, trace.NotFound(\"no active operation found for %v\", siteKey)\n\t}\n\n\tfor _, op := range operations {\n\t\tactive = append(active, SiteOperation(op))\n\t}\n\n\treturn active, nil\n}", "func (p *BoteaterServiceClient) FetchOps(ctx context.Context, localRev int64, count int32, globalRev int64, individualRev int64) (r []*OperationStruct, err error) {\r\n var _args121 BoteaterServiceFetchOpsArgs\r\n _args121.LocalRev = localRev\r\n _args121.Count = count\r\n _args121.GlobalRev = globalRev\r\n _args121.IndividualRev = individualRev\r\n var _result122 BoteaterServiceFetchOpsResult\r\n if err = p.Client_().Call(ctx, \"fetchOps\", &_args121, &_result122); err != nil {\r\n return\r\n }\r\n switch {\r\n case _result122.E!= nil:\r\n return r, _result122.E\r\n }\r\n\r\n return _result122.GetSuccess(), nil\r\n}", "func (os *OpSet) Ops() []*Op {\n\treturn os.set\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {\n\tc := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (transactionMeta *TransactionMeta) OperationsMeta() []OperationMeta {\n\tswitch transactionMeta.V {\n\tcase 0:\n\t\treturn *transactionMeta.Operations\n\tcase 1:\n\t\treturn transactionMeta.MustV1().Operations\n\tcase 2:\n\t\treturn transactionMeta.MustV2().Operations\n\tcase 3:\n\t\treturn transactionMeta.MustV3().Operations\n\tdefault:\n\t\tpanic(\"Unsupported TransactionMeta version\")\n\t}\n}", "func (r *InspectOperationsService) Get(name string) *InspectOperationsGetCall {\n\tc := &InspectOperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (c *cloudChannelRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v\", req.GetName())\n\n\tparams := url.Values{}\n\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\n\tbaseUrl.RawQuery = params.Encode()\n\n\t// Build HTTP headers from client and context metadata.\n\thds := []string{\"x-goog-request-params\", fmt.Sprintf(\"%s=%v\", \"name\", url.QueryEscape(req.GetName()))}\n\n\thds = append(c.xGoogHeaders, hds...)\n\thds = append(hds, \"Content-Type\", \"application/json\")\n\theaders := gax.BuildHeaders(ctx, hds...)\n\topts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tresp := &longrunningpb.Operation{}\n\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\tif settings.Path != \"\" {\n\t\t\tbaseUrl.Path = settings.Path\n\t\t}\n\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpReq = httpReq.WithContext(ctx)\n\t\thttpReq.Header = headers\n\n\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer httpRsp.Body.Close()\n\n\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}, opts...)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn resp, nil\n}", "func (req *UpsertObjectRequest) Operations(operations []Operation) *UpsertObjectRequest {\n\treq.operations = operations\n\treturn req\n}", "func (o *Volume) GetIops() int64 {\n\tif o == nil || o.Iops == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.Iops\n}", "func (client DatasetClient) GetOperation(ctx context.Context, operationID string) (result LongRunningOperationResult, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/DatasetClient.GetOperation\")\n defer func() {\n sc := -1\n if result.Response.Response != nil {\n sc = result.Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.GetOperationPreparer(ctx, operationID)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"GetOperation\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.GetOperationSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n err = autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"GetOperation\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.GetOperationResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"GetOperation\", resp, \"Failure responding to request\")\n return\n }\n\n return\n}", "func GetOperation(name string) (*lropb.Operation, error) {\n\tctx := context.Background()\n\tclient, err := automl.NewClient(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewClient: %v\", err)\n\t}\n\tdefer client.Close()\n\n\treq := &lropb.GetOperationRequest{\n\t\tName: name,\n\t}\n\n\treturn client.LROClient.GetOperation(ctx, req)\n}", "func (m *TeamItemRequestBuilder) Operations()(*i9fa0e9d329dc2b42ce0cc0330991bb8f8e864efaaef5061789d895e28321a6b2.OperationsRequestBuilder) {\n return i9fa0e9d329dc2b42ce0cc0330991bb8f8e864efaaef5061789d895e28321a6b2.NewOperationsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (r *OrganizationsOperationsService) List(name string) *OrganizationsOperationsListCall {\n\tc := &OrganizationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (c *OperationClient) Get(ctx context.Context, id uuid.UUID) (*Operation, error) {\n\treturn c.Query().Where(operation.ID(id)).Only(ctx)\n}", "func (c *Client) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\treturn c.internalClient.GetOperation(ctx, req, opts...)\n}", "func (c *Client) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {\n\treturn c.internalClient.GetOperation(ctx, req, opts...)\n}", "func (i *Info) GetQueryOps() []string {\n\n\t// checked in template already, but safety and stuff\n\tif len(i.Selectable) > 0 {\n\t\tos := strings.Split(i.Selectable, \",\")\n\t\tfor x := range os {\n\t\t\tos[x] = superCleanString(os[x])\n\t\t}\n\t\treturn os\n\t}\n\treturn nil\n}", "func (o *TOC) OutputOperations(i int, outputChapter outputs.Chapter, operations *kubernetes.ActionInfoList) error {\n\toperationsSection, err := outputChapter.AddSection(i, \"Operations\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i, operation := range *operations {\n\t\to.OutputOperation(i, operationsSection, &operation)\n\t\t_ = operation\n\t}\n\treturn nil\n}" ]
[ "0.7211943", "0.7144373", "0.7129846", "0.7005646", "0.6984113", "0.6979087", "0.6979087", "0.6970134", "0.6949761", "0.6890829", "0.6889747", "0.6889747", "0.68835425", "0.68729496", "0.68609893", "0.68579656", "0.68536425", "0.67909795", "0.6768954", "0.6740723", "0.6734948", "0.67348295", "0.66751343", "0.66742504", "0.66699624", "0.6633077", "0.6630138", "0.65970755", "0.6535597", "0.6528932", "0.6394858", "0.6394858", "0.63838184", "0.6368351", "0.6361213", "0.6350676", "0.6350676", "0.632308", "0.61999637", "0.6193671", "0.6165864", "0.616416", "0.61617035", "0.6075222", "0.6057926", "0.60416687", "0.59913707", "0.5985264", "0.5961738", "0.58603764", "0.5852363", "0.58127856", "0.57003677", "0.5675637", "0.56630844", "0.565388", "0.5594034", "0.5581831", "0.5539351", "0.5517464", "0.54576683", "0.5442278", "0.5390083", "0.534994", "0.5325316", "0.52941656", "0.5280456", "0.5265064", "0.5264178", "0.52517617", "0.5241402", "0.5230426", "0.5230148", "0.5227759", "0.5217193", "0.5213738", "0.5213012", "0.5204429", "0.5197836", "0.5194437", "0.5172125", "0.51565325", "0.51565325", "0.51565325", "0.51565325", "0.51565325", "0.51542324", "0.51381236", "0.5127272", "0.5123834", "0.5122067", "0.5081803", "0.5079711", "0.50740767", "0.5070642", "0.5063568", "0.50594664", "0.50594664", "0.5055723", "0.5044171" ]
0.83329624
0
GetSharepointIds gets the sharepointIds property value. Returns identifiers useful for SharePoint REST compatibility. Readonly.
func (m *List) GetSharepointIds()(SharepointIdsable) { return m.sharepointIds }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Drive) GetSharePointIds()(SharepointIdsable) {\n return m.sharePointIds\n}", "func (o *MicrosoftGraphItemReference) GetSharepointIds() AnyOfmicrosoftGraphSharepointIds {\n\tif o == nil || o.SharepointIds == nil {\n\t\tvar ret AnyOfmicrosoftGraphSharepointIds\n\t\treturn ret\n\t}\n\treturn *o.SharepointIds\n}", "func (o *MicrosoftGraphListItem) GetSharepointIds() AnyOfmicrosoftGraphSharepointIds {\n\tif o == nil || o.SharepointIds == nil {\n\t\tvar ret AnyOfmicrosoftGraphSharepointIds\n\t\treturn ret\n\t}\n\treturn *o.SharepointIds\n}", "func (m *List) SetSharepointIds(value SharepointIdsable)() {\n m.sharepointIds = value\n}", "func NewSharepointIds()(*SharepointIds) {\n m := &SharepointIds{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func (o *MicrosoftGraphListItem) SetSharepointIds(v AnyOfmicrosoftGraphSharepointIds) {\n\to.SharepointIds = &v\n}", "func (o *MicrosoftGraphItemReference) SetSharepointIds(v AnyOfmicrosoftGraphSharepointIds) {\n\to.SharepointIds = &v\n}", "func (o *MicrosoftGraphListItem) HasSharepointIds() bool {\n\tif o != nil && o.SharepointIds != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *Drive) SetSharePointIds(value SharepointIdsable)() {\n m.sharePointIds = value\n}", "func (o *MicrosoftGraphItemReference) GetSharepointIdsOk() (AnyOfmicrosoftGraphSharepointIds, bool) {\n\tif o == nil || o.SharepointIds == nil {\n\t\tvar ret AnyOfmicrosoftGraphSharepointIds\n\t\treturn ret, false\n\t}\n\treturn *o.SharepointIds, true\n}", "func (o *MicrosoftGraphListItem) GetSharepointIdsOk() (AnyOfmicrosoftGraphSharepointIds, bool) {\n\tif o == nil || o.SharepointIds == nil {\n\t\tvar ret AnyOfmicrosoftGraphSharepointIds\n\t\treturn ret, false\n\t}\n\treturn *o.SharepointIds, true\n}", "func (o *MicrosoftGraphItemReference) HasSharepointIds() bool {\n\tif o != nil && o.SharepointIds != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *SharepointIds) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"listId\", m.GetListId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"listItemId\", m.GetListItemId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"listItemUniqueId\", m.GetListItemUniqueId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"siteId\", m.GetSiteId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"siteUrl\", m.GetSiteUrl())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"tenantId\", m.GetTenantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"webId\", m.GetWebId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func getIds() []string {\n\tclient := &http.Client{}\n\tvar ids []string\n\tsongRequest, err := http.NewRequest(\"GET\", \"https://api.spotify.com/v1/me/tracks?limit=50&offset=0\", nil)\n\tsongRequest.Header.Add(\"Authorization\", key)\n\tresponse, err := client.Do(songRequest)\n\tif err != nil {\n\t\tfmt.Println(\"Request failed with error:\", err)\n\t} else {\n\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\titems := gjson.Get(string(data), \"items\")\n\t\tfor i := 0; i < len(items.Array()); i++ {\n\t\t\ttrack := gjson.Get(items.Array()[i].String(), \"track\")\n\t\t\tid := gjson.Get(track.String(), \"id\")\n\t\t\tids = append(ids, id.String())\n\t\t}\n\t}\n\tids = append(ids, getPlaylistIds()...) // Calls to get song IDs from user playlists\n\treturn fixIds(ids)\n}", "func (m *SharepointIds) GetListItemId()(*string) {\n val, err := m.GetBackingStore().Get(\"listItemId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *SharepointIds) GetListId()(*string) {\n val, err := m.GetBackingStore().Get(\"listId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *DeviceManagementComplexSettingDefinition) GetPropertyDefinitionIds()([]string) {\n val, err := m.GetBackingStore().Get(\"propertyDefinitionIds\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func getPlaylistIds() []string {\n\tclient := &http.Client{}\n\n\tvar ids []string\n\turl := \"https://api.spotify.com/v1/users/\" + userId + \"/playlists?limit=50\"\n\tplaylistRequest, err := http.NewRequest(\"GET\", url, nil)\n\n\tplaylistRequest.Header.Add(\"Authorization\", key)\n\tresponse, err := client.Do(playlistRequest)\n\tif err != nil {\n\t\tfmt.Println(\"Request failed with error:\", err)\n\t} else {\n\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\titems := gjson.Get(string(data), \"items\")\n\t\tfor i := 0; i < len(items.Array()); i++ {\n\t\t\tid := gjson.Get(items.Array()[i].String(), \"id\")\n\t\t\tids = append(ids, id.String())\n\t\t}\n\t}\n\treturn getPlaylistSongIds(ids)\n}", "func (m *SharepointIds) GetListItemUniqueId()(*string) {\n val, err := m.GetBackingStore().Get(\"listItemUniqueId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (d *Dispatch) GetIds(names ...string) (dispid []int32, err error) {\n\tdispid, err = d.Object.GetIDsOfName(names)\n\treturn\n}", "func (m *PromotionMutation) SaleIDs() (ids []int) {\n\tif id := m.sale; id != nil {\n\t\tids = append(ids, *id)\n\t}\n\treturn\n}", "func (o *ViewUserDashboard) GetDashboardSettingIds() []int32 {\n\tif o == nil || o.DashboardSettingIds == nil {\n\t\tvar ret []int32\n\t\treturn ret\n\t}\n\treturn *o.DashboardSettingIds\n}", "func (c *Client) FindReportPointOfSaleReportInvoiceIds(criteria *Criteria, options *Options) ([]int64, error) {\n\tids, err := c.Search(ReportPointOfSaleReportInvoiceModel, criteria, options)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\treturn ids, nil\n}", "func (m *UserMutation) SellsIDs() (ids []int) {\n\tfor id := range m.sells {\n\t\tids = append(ids, id)\n\t}\n\treturn\n}", "func (m *SharepointIds) GetSiteId()(*string) {\n val, err := m.GetBackingStore().Get(\"siteId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (d docs) getIds() (ids []bson.ObjectId) {\n\tfor _, doc := range d {\n\t\tids = append(ids, doc[\"_id\"].(bson.ObjectId))\n\t}\n\treturn\n}", "func (op *ListSharedAccessOp) FolderIds(val ...string) *ListSharedAccessOp {\n\tif op != nil {\n\t\top.QueryOpts.Set(\"folder_ids\", strings.Join(val, \",\"))\n\t}\n\treturn op\n}", "func (c *Client) ListIds() (*[]aadpodid.AzureIdentity, error) {\n\tbegin := time.Now()\n\n\tvar resList []aadpodid.AzureIdentity\n\n\tlist := c.IDInformer.GetStore().List()\n\tfor _, id := range list {\n\t\to, ok := id.(*aadpodv1.AzureIdentity)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"failed to cast %T to %s\", id, aadpodv1.AzureIDResource)\n\t\t}\n\t\t// Note: List items returned from cache have empty Kind and API version..\n\t\t// Work around this issue since we need that for event recording to work.\n\t\to.SetGroupVersionKind(schema.GroupVersionKind{\n\t\t\tGroup: aadpodv1.SchemeGroupVersion.Group,\n\t\t\tVersion: aadpodv1.SchemeGroupVersion.Version,\n\t\t\tKind: reflect.TypeOf(*o).String()})\n\n\t\tout := aadpodv1.ConvertV1IdentityToInternalIdentity(*o)\n\n\t\tresList = append(resList, out)\n\t\tklog.V(6).Infof(\"appending AzureIdentity %s/%s to list.\", o.Namespace, o.Name)\n\t}\n\n\tstats.Aggregate(stats.AzureIdentityList, time.Since(begin))\n\treturn &resList, nil\n}", "func (o *ViewMilestone) GetTasklistIds() []int32 {\n\tif o == nil || o.TasklistIds == nil {\n\t\tvar ret []int32\n\t\treturn ret\n\t}\n\treturn *o.TasklistIds\n}", "func (o *MicrosoftGraphItemReference) GetShareId() string {\n\tif o == nil || o.ShareId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ShareId\n}", "func (m *SharepointIds) GetWebId()(*string) {\n val, err := m.GetBackingStore().Get(\"webId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func getRelatedSites(siteID int) []int {\n\n\tvar relatedSites []int\n\tDB.SQL(`select id from site where parent_site=$1`, siteID).QuerySlice(&relatedSites)\n\trelatedSites = append(relatedSites, siteID)\n\treturn relatedSites\n}", "func (m *RiskyServicePrincipalsDismissPostRequestBody) GetServicePrincipalIds()([]string) {\n val, err := m.GetBackingStore().Get(\"servicePrincipalIds\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func getTeamsIds(context context.Context, githubClient github.Client, githubOrganization string, githubTeams string) []int64 {\n\tgithubTeamsArr := strings.Split(githubTeams, \",\")\n\tteams, _, err := githubClient.Teams.ListTeams(context, githubOrganization, nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %s\", err)\n\t}\n\tvar teamsIds = make([]int64, 0)\n\tfor _, team := range teams {\n\t\tif len(githubTeams) == 0 || contains(githubTeamsArr, *team.Name) {\n\t\t\tteamsIds = append(teamsIds, *team.ID)\n\t\t}\n\t}\n\treturn teamsIds\n}", "func CreateSharepointIdsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSharepointIds(), nil\n}", "func (client ListManagementImageClient) GetAllImageIds(ctx context.Context, listID string) (result ImageIds, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListManagementImageClient.GetAllImageIds\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.GetAllImageIdsPreparer(ctx, listID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementImageClient\", \"GetAllImageIds\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetAllImageIdsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementImageClient\", \"GetAllImageIds\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetAllImageIdsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementImageClient\", \"GetAllImageIds\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (m *Market) GetIDs() []string {\n\treturn m.ids\n}", "func (taskService TaskService) getTaskSites(ctx context.Context, managedEndpoints []gocql.UUID, siteIDs map[string]struct{}, partnerID string) map[string]struct{} {\n\tif len(managedEndpoints) == 0 {\n\t\treturn siteIDs\n\t}\n\n\tvar (\n\t\twg sync.WaitGroup\n\t\tmu sync.Mutex\n\t)\n\twg.Add(len(managedEndpoints))\n\n\tfor _, endpointID := range managedEndpoints {\n\t\tgo func(ctx context.Context, endpointID gocql.UUID) {\n\t\t\tdefer wg.Done()\n\n\t\t\tsiteID, _, err := taskService.assetsService.GetSiteIDByEndpointID(ctx, partnerID, endpointID)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log.WarnfCtx(ctx, \"cannot get siteID for ManagedEndpoint[%v]: %v\", endpointID, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmu.Lock()\n\t\t\tsiteIDs[siteID] = struct{}{}\n\t\t\tmu.Unlock()\n\t\t}(ctx, endpointID)\n\t}\n\n\twg.Wait()\n\treturn siteIDs\n}", "func (o *FiltersSecurityGroup) GetSecurityGroupIds() []string {\n\tif o == nil || o.SecurityGroupIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SecurityGroupIds\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCaller) GetTransactionIds(opts *bind.CallOpts, from *big.Int, to *big.Int, pending bool, executed bool) ([]*big.Int, error) {\n\tvar (\n\t\tret0 = new([]*big.Int)\n\t)\n\tout := ret0\n\terr := _ReserveSpenderMultiSig.contract.Call(opts, out, \"getTransactionIds\", from, to, pending, executed)\n\treturn *ret0, err\n}", "func (pw *PlayerWalker) GetGameIDList(ctx context.Context, region region.Region, accountID string, opts *apiclient.GetMatchlistOptions) ([]int64, error) {\n\tvar gameIDList []int64\n\tmatchlist, err := pw.client.GetMatchlist(ctx, region, accountID, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, match := range matchlist.Matches {\n\t\tgameIDList = append(gameIDList, match.GameID)\n\t}\n\treturn gameIDList, nil\n}", "func (c *CampaignsListCall) Ids(ids ...int64) *CampaignsListCall {\n\tvar ids_ []string\n\tfor _, v := range ids {\n\t\tids_ = append(ids_, fmt.Sprint(v))\n\t}\n\tc.urlParams_.SetMulti(\"ids\", ids_)\n\treturn c\n}", "func (driver *SQLDriver) ListIDs() ([]string, error) {\n\t// Execute a SELECT query to retrieve all the paste IDs\n\trows, err := driver.database.Query(\"SELECT id FROM ?\", driver.table)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\t// Scan the rows into a slice of IDs and return it\n\tvar ids []string\n\terr = rows.Scan(&ids)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ids, nil\n}", "func (m *EntityMutation) SplitsIDs() (ids []int) {\n\tfor id := range m.splits {\n\t\tids = append(ids, id)\n\t}\n\treturn\n}", "func (o *DataExportQuery) GetCampaignIds() []string {\n\tif o == nil || o.CampaignIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.CampaignIds\n}", "func (o GetServiceIdentityOutput) IdentityIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetServiceIdentity) []string { return v.IdentityIds }).(pulumi.StringArrayOutput)\n}", "func getTeamIDs(d *schema.ResourceData) []int {\n\tset := d.Get(\"team_ids\").(*schema.Set)\n\tteamIDs := make([]int, set.Len())\n\tfor i, teamID := range set.List() {\n\t\tteamIDs[i] = teamID.(int)\n\t}\n\treturn teamIDs\n}", "func fetchStoryIDs(feedType *string) []int {\n\turl := fmt.Sprintf(storiesFeedURL, *feedType)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tvar m []int\n\terr = json.Unmarshal(body, &m)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn m\n}", "func (s *Store) ShardIDs() []uint64 {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn s.shardIDs()\n}", "func (o GetFoldersResultOutput) Ids() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetFoldersResult) []string { return v.Ids }).(pulumi.StringArrayOutput)\n}", "func (o LookupNetworkPacketCoreControlPlaneResultOutput) SiteIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupNetworkPacketCoreControlPlaneResult) []string { return v.SiteIds }).(pulumi.StringArrayOutput)\n}", "func GetMenuItemsIds(output *[]int, dishIds []int, date int, db *sqlx.DB) error {\n\t// Build sql query\n\tq, a, _ := squirrel.Select(RowId).From(Table).Where(squirrel.Eq{DishId: dishIds, Date: date}).ToSql()\n\n\treturn db.Select(output, q, a...)\n}", "func (m *SharepointIds) SetListItemId(value *string)() {\n err := m.GetBackingStore().Set(\"listItemId\", value)\n if err != nil {\n panic(err)\n }\n}", "func getPlaylistSongIds(playlistIds []string) []string {\n\tclient := &http.Client{}\n\n\tvar ids []string\n\n\tfor _, plId := range playlistIds {\n\t\turl := \"https://api.spotify.com/v1/playlists/\" + plId + \"/tracks?market=US&fields=items(track(id))&limit=50&offset=0\"\n\t\tplaylistRequest, err := http.NewRequest(\"GET\", url, nil)\n\t\tplaylistRequest.Header.Add(\"Authorization\", key)\n\t\tresponse, err := client.Do(playlistRequest)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Request failed with error:\", err)\n\t\t} else {\n\t\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\t\titems := gjson.Get(string(data), \"items\")\n\t\t\tfor i := 0; i < len(items.Array()); i++ {\n\t\t\t\tid := gjson.Get(items.Array()[i].String(), \"track.id\")\n\t\t\t\tids = append(ids, id.String())\n\t\t\t}\n\t\t}\n\t}\n\treturn ids\n}", "func (m *ServicePrincipalRiskDetection) GetKeyIds()([]string) {\n val, err := m.GetBackingStore().Get(\"keyIds\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func (o GetFlowlogsResultOutput) Ids() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetFlowlogsResult) []string { return v.Ids }).(pulumi.StringArrayOutput)\n}", "func (p *ioThrottlerPool) GetIDs() []string {\n\tvar ids []string\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tfor id := range p.connections {\n\t\tids = append(ids, id)\n\t}\n\treturn ids\n}", "func (c *restClient) ListCollectionIds(ctx context.Context, req *firestorepb.ListCollectionIdsRequest, opts ...gax.CallOption) *StringIterator {\n\tit := &StringIterator{}\n\treq = proto.Clone(req).(*firestorepb.ListCollectionIdsRequest)\n\tm := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) {\n\t\tresp := &firestorepb.ListCollectionIdsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tjsonReq, err := m.Marshal(req)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v:listCollectionIds\", req.GetParent())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"POST\", baseUrl.String(), bytes.NewReader(jsonReq))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetCollectionIds(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func (c *Client) FindSaleReportIds(criteria *Criteria, options *Options) ([]int64, error) {\n\tids, err := c.Search(SaleReportModel, criteria, options)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\treturn ids, nil\n}", "func (c *Client) FindReportSaleReportSaleproformaIds(criteria *Criteria, options *Options) ([]int64, error) {\n\tids, err := c.Search(ReportSaleReportSaleproformaModel, criteria, options)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\treturn ids, nil\n}", "func (a *App) GetIdentitiesList(ctx *fiber.Ctx) {\n\tidentities, err := a.store.GetIdentitiesList()\n\tif err != nil {\n\t\tctx.Send(err)\n\t}\n\terr = ctx.Status(fiber.StatusOK).JSON(identities)\n\tif err != nil {\n\t\tctx.Status(fiber.StatusInternalServerError).JSON(fiber.Map{\n\t\t\t\"error\": model.Errors{\n\t\t\t\tCode: fiber.StatusInternalServerError,\n\t\t\t\tDebug: \"Cannot get identities\",\n\t\t\t\tMessage: err.Error(),\n\t\t\t\tRequest: ctx.Body(),\n\t\t\t\tStatus: \"Bad Request\",\n\t\t\t},\n\t\t})\n\t}\n}", "func (o *MicrosoftGraphMailSearchFolder) GetSourceFolderIds() []string {\n\tif o == nil || o.SourceFolderIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SourceFolderIds\n}", "func (m *SharepointIds) SetListId(value *string)() {\n err := m.GetBackingStore().Set(\"listId\", value)\n if err != nil {\n panic(err)\n }\n}", "func GetFavoriteItemIDs(w http.ResponseWriter, r *http.Request) {\n\tuser := UnmarshalUser(r.Body)\n\tfavoriteItems := dbP.GetFavoriteItemIDs(user.ID)\n\tresponse := marshalToJSON(favoriteItems, w)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(response)\n}", "func (c *Cgroups) ListPids(hs []string) []int {\n\tall := []int{}\n\tencountered := make(map[int]bool)\n\tfor _, h := range hs {\n\t\tall = append(all, c.listPids(h)...)\n\t}\n\n\tmerged := []int{}\n\tfor _, pid := range all {\n\t\tif !encountered[pid] {\n\t\t\tencountered[pid] = true\n\t\t\tmerged = append(merged, pid)\n\t\t}\n\t}\n\n\tsort.Ints(merged)\n\n\treturn merged\n}", "func ShareLists(hrcSrvShare unsafe.Pointer, hrcSrvSource unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpShareLists, 2, uintptr(hrcSrvShare), uintptr(hrcSrvSource), 0)\n\treturn (unsafe.Pointer)(ret)\n}", "func (c *Client) FindSaleOrderLineIds(criteria *Criteria, options *Options) ([]int64, error) {\n\tids, err := c.Search(SaleOrderLineModel, criteria, options)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\treturn ids, nil\n}", "func (o *V1SciNameAndIds) GetSciNameAndIds() []V1SciNameAndIdsSciNameAndId {\n\tif o == nil || o.SciNameAndIds == nil {\n\t\tvar ret []V1SciNameAndIdsSciNameAndId\n\t\treturn ret\n\t}\n\treturn *o.SciNameAndIds\n}", "func (pms MapState) getIdentities(log *logrus.Logger, denied bool) (ingIdentities, egIdentities []int64) {\n\tfor policyMapKey, policyMapValue := range pms {\n\t\tif denied != policyMapValue.IsDeny {\n\t\t\tcontinue\n\t\t}\n\t\tif policyMapKey.DestPort != 0 {\n\t\t\t// If the port is non-zero, then the Key no longer only applies\n\t\t\t// at L3. AllowedIngressIdentities and AllowedEgressIdentities\n\t\t\t// contain sets of which identities (i.e., label-based L3 only)\n\t\t\t// are allowed, so anything which contains L4-related policy should\n\t\t\t// not be added to these sets.\n\t\t\tcontinue\n\t\t}\n\t\tswitch trafficdirection.TrafficDirection(policyMapKey.TrafficDirection) {\n\t\tcase trafficdirection.Ingress:\n\t\t\tingIdentities = append(ingIdentities, int64(policyMapKey.Identity))\n\t\tcase trafficdirection.Egress:\n\t\t\tegIdentities = append(egIdentities, int64(policyMapKey.Identity))\n\t\tdefault:\n\t\t\ttd := trafficdirection.TrafficDirection(policyMapKey.TrafficDirection)\n\t\t\tlog.WithField(logfields.TrafficDirection, td).\n\t\t\t\tErrorf(\"Unexpected traffic direction present in policy map state for endpoint\")\n\t\t}\n\t}\n\treturn ingIdentities, egIdentities\n}", "func (s *Service) ListSharedAccess() *ListSharedAccessOp {\n\treturn &ListSharedAccessOp{\n\t\tCredential: s.credential,\n\t\tMethod: \"GET\",\n\t\tPath: \"shared_access\",\n\t\tAccept: \"application/json\",\n\t\tQueryOpts: make(url.Values),\n\t\tVersion: esign.APIv2,\n\t}\n}", "func (m *DeviceManagementComplexSettingDefinition) SetPropertyDefinitionIds(value []string)() {\n err := m.GetBackingStore().Set(\"propertyDefinitionIds\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o ServiceIdentityOutput) IdentityIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceIdentity) []string { return v.IdentityIds }).(pulumi.StringArrayOutput)\n}", "func (o GetSecondaryIndexesResultOutput) Ids() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetSecondaryIndexesResult) []string { return v.Ids }).(pulumi.StringArrayOutput)\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigSession) GetTransactionIds(from *big.Int, to *big.Int, pending bool, executed bool) ([]*big.Int, error) {\n\treturn _ReserveSpenderMultiSig.Contract.GetTransactionIds(&_ReserveSpenderMultiSig.CallOpts, from, to, pending, executed)\n}", "func (c *Client) ListPodIds(podns, podname string) (map[string][]aadpodid.AzureIdentity, error) {\n\tlist, err := c.ListAssignedIDs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tidStateMap := make(map[string][]aadpodid.AzureIdentity)\n\tfor _, v := range *list {\n\t\tif v.Spec.Pod == podname && v.Spec.PodNamespace == podns {\n\t\t\tidStateMap[v.Status.Status] = append(idStateMap[v.Status.Status], *v.Spec.AzureIdentityRef)\n\t\t}\n\t}\n\treturn idStateMap, nil\n}", "func (mcr *MiddlewareClusterRepo) GetMiddlewareServerIDList(clusterID int) ([]int, error) {\n\tsql := `select id from t_meta_middleware_server_info\n where del_flag = 0\n and cluster_id = ?\n\t\t order by id;\n\t`\n\tlog.Debugf(\"metadata MiddlewareCLusterRepo.GetMiddlewareServerIDList() select sql: %s\", sql)\n\tresult, err := mcr.Execute(sql, clusterID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresultNum := result.RowNumber()\n\tserverIDList := make([]int, resultNum)\n\tfor row := 0; row < resultNum; row++ {\n\t\tserverID, err := result.GetInt(row, constant.ZeroInt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tserverIDList[row] = serverID\n\t}\n\treturn serverIDList, nil\n}", "func (m *OrganizationMutation) StaffsIDs() (ids []int) {\n\tfor id := range m.staffs {\n\t\tids = append(ids, id)\n\t}\n\treturn\n}", "func (m *UserMutation) SpouseIDs() (ids []int) {\n\tif id := m.spouse; id != nil {\n\t\tids = append(ids, *id)\n\t}\n\treturn\n}", "func (s *Server) GetUserFollowingIds(ctx context.Context, req *pbApi.GetBasicUserDataRequest) (*pbApi.UserList, error) {\n\tif s.dbHandler == nil {\n\t\treturn nil, status.Error(codes.Internal, \"No database connection\")\n\t}\n\tpbUser, err := s.dbHandler.User(req.UserId)\n\tif err != nil {\n\t\tif errors.Is(err, dbmodel.ErrUserNotFound) {\n\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\treturn &pbApi.UserList{\n\t\tIds: pbUser.FollowingIds,\n\t}, nil\n}", "func (c *PlacementsListCall) SiteIds(siteIds ...int64) *PlacementsListCall {\n\tvar siteIds_ []string\n\tfor _, v := range siteIds {\n\t\tsiteIds_ = append(siteIds_, fmt.Sprint(v))\n\t}\n\tc.urlParams_.SetMulti(\"siteIds\", siteIds_)\n\treturn c\n}", "func (c *Channel) GetMSPIDs() []string {\n\tac, ok := c.Resources().ApplicationConfig()\n\tif !ok || ac.Organizations() == nil {\n\t\treturn nil\n\t}\n\n\tvar mspIDs []string\n\tfor _, org := range ac.Organizations() {\n\t\tmspIDs = append(mspIDs, org.MSPID())\n\t}\n\n\treturn mspIDs\n}", "func getNewsItems() []string {\n\turl := baseURL + \"/newstories.json\"\n\tbody := fmtRes(url)\n\tstoryIds := strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(string(body)), \"[\"), \"]\")\n\tidSlice := strings.Split(storyIds, \",\")\n\treturn idSlice\n}", "func (o GetTlsActivationIdsResultOutput) Ids() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetTlsActivationIdsResult) []string { return v.Ids }).(pulumi.StringArrayOutput)\n}", "func (c *Client) GetEndpointsByGroupIDs(ctx context.Context, targetIDs []string, createdBy, partnerID string, hasNOCAccess bool) (ids []gocql.UUID, err error) {\n\tvar (\n\t\tuserSites entities.UserSites\n\t\tpayload []dgResponse\n\t\twg sync.WaitGroup\n\t\tuserSitesMap = make(map[string]struct{})\n\t\terrChan = make(chan error, 2)\n\t\tdone = make(chan int)\n\t)\n\n\tif !hasNOCAccess {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\n\t\t\tuserSites, err = c.userRepo.Sites(ctx, partnerID, createdBy)\n\t\t\tif err != nil {\n\t\t\t\terrChan <- fmt.Errorf(\"error while getting user sites fron Cassandra, err: %v\", err)\n\t\t\t}\n\n\t\t\tfor _, siteID := range userSites.SiteIDs {\n\t\t\t\tsiteIDstr := strconv.FormatInt(siteID, 10)\n\t\t\t\tuserSitesMap[siteIDstr] = struct{}{}\n\t\t\t}\n\t\t}()\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\turl := fmt.Sprintf(\"%s/partners/%s/dynamic-groups/managed-endpoints/set?expression=%s\",\n\t\t\tconfig.Config.DynamicGroupsMsURL, partnerID, strings.Join(targetIDs, dgDelimiter))\n\n\t\tif err := integration.GetDataByURL(ctx, &payload, c.httpClient, url, \"\", true); err != nil {\n\t\t\terrChan <- err\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor e := range errChan {\n\t\t\terr = fmt.Errorf(\"%v %v\", err, e)\n\t\t}\n\t\tdone <- 1\n\t}()\n\n\twg.Wait()\n\tclose(errChan)\n\t<-done\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.filterResponse(payload, userSitesMap, hasNOCAccess), nil\n}", "func (keyRing *KeyRing) KeyIds() []uint64 {\n\tvar res []uint64\n\tfor _, e := range keyRing.entities {\n\t\tres = append(res, e.PrimaryKey.KeyId)\n\t}\n\treturn res\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCallerSession) GetTransactionIds(from *big.Int, to *big.Int, pending bool, executed bool) ([]*big.Int, error) {\n\treturn _ReserveSpenderMultiSig.Contract.GetTransactionIds(&_ReserveSpenderMultiSig.CallOpts, from, to, pending, executed)\n}", "func (o *FiltersVmGroup) GetSecurityGroupIds() []string {\n\tif o == nil || o.SecurityGroupIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SecurityGroupIds\n}", "func GetSnapshotIds(ctx *pulumi.Context, args *GetSnapshotIdsArgs, opts ...pulumi.InvokeOption) (*GetSnapshotIdsResult, error) {\n\tvar rv GetSnapshotIdsResult\n\terr := ctx.Invoke(\"aws:ebs/getSnapshotIds:getSnapshotIds\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func getRouteIds(data map[string]string) []string {\n\tids := make([]string, len(data))\n\tindex := 0\n\tfor id, _ := range data {\n\t\tids[index] = id\n\t\tindex++\n\t}\n\n\treturn ids\n}", "func (c *Client) ShardIDs() []uint64 {\n\tvar a []uint64\n\tfor _, dbi := range c.data().Data.Databases {\n\t\tfor _, rpi := range dbi.RetentionPolicies {\n\t\t\tfor _, sgi := range rpi.ShardGroups {\n\t\t\t\tfor _, si := range sgi.Shards {\n\t\t\t\t\ta = append(a, si.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tsort.Sort(uint64Slice(a))\n\treturn a\n}", "func (m *MockResolver) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]dbstore.Upload, error) {\n\tr0, r1 := m.GetUploadsByIDsFunc.nextHook()(v0, v1...)\n\tm.GetUploadsByIDsFunc.appendCall(ResolverGetUploadsByIDsFuncCall{v0, v1, r0, r1})\n\treturn r0, r1\n}", "func (s *Service) ListClientID() []string {\n\tlistIDs := []string{}\n\tfor _, client := range s.Clients {\n\t\tlistIDs = append(listIDs, client.ID.String())\n\t}\n\treturn listIDs\n}", "func (o ResourcePolicyExemptionOutput) PolicyDefinitionReferenceIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyExemption) pulumi.StringArrayOutput { return v.PolicyDefinitionReferenceIds }).(pulumi.StringArrayOutput)\n}", "func GetAllMultiTokenIds() (lups []Lookup, err error) {\n\treturn getAllTokensOfType(2)\n}", "func GetIdentities(accessToken string) ([]client.Identity, error) {\n\tif provider != nil {\n\t\treturn provider.GetIdentities(accessToken)\n\t}\n\treturn []client.Identity{}, fmt.Errorf(\"No auth provider configured\")\n}", "func GetPids() (pids []string, err error) {\n\tp, err := os.Open(util.ProcLocation)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer p.Close()\n\n\tpids = make([]string, 0)\n\tfor {\n\t\tfileInfos, err := p.Readdir(10)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, fileInfo := range fileInfos {\n\t\t\t// We only care about directories, since all pids are dirs\n\t\t\tif !fileInfo.IsDir() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// We only care if the name starts with a numeric\n\t\t\tname := fileInfo.Name()\n\t\t\tif pid, err := strconv.Atoi(name); err == nil {\n\t\t\t\tspid := strconv.Itoa(pid)\n\t\t\t\tpids = append(pids, spid)\n\t\t\t}\n\t\t}\n\t}\n\treturn pids, err\n}", "func (u *AccountRow) GetBookmarkCollectionIDs() (*BookmarkRow, error) {\n\tquery := `\n\t\tselect id, location_ids from bookmarks where id = $1`\n\n\trowData := &BookmarkRow{}\n\trow := GlobalConn.QueryRow(query, u.ID)\n\n\tif err := row.Scan(&rowData.ID, &rowData.LocationIDs); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn rowData, nil\n}", "func (o *ViewUserDashboard) GetDashboardPanelIds() []int32 {\n\tif o == nil || o.DashboardPanelIds == nil {\n\t\tvar ret []int32\n\t\treturn ret\n\t}\n\treturn *o.DashboardPanelIds\n}", "func (o GetAlarmContactsResultOutput) Ids() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetAlarmContactsResult) []string { return v.Ids }).(pulumi.StringArrayOutput)\n}", "func (m *MockUploadService) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]types.Upload, error) {\n\tr0, r1 := m.GetUploadsByIDsFunc.nextHook()(v0, v1...)\n\tm.GetUploadsByIDsFunc.appendCall(UploadServiceGetUploadsByIDsFuncCall{v0, v1, r0, r1})\n\treturn r0, r1\n}" ]
[ "0.8100934", "0.79997236", "0.7919966", "0.67751956", "0.6737591", "0.6716384", "0.66700727", "0.64469844", "0.6421894", "0.62926507", "0.6288443", "0.614765", "0.5920941", "0.5585824", "0.5475095", "0.54425955", "0.5382097", "0.5301088", "0.5294862", "0.5176188", "0.51289743", "0.51190025", "0.5097825", "0.50607044", "0.49863636", "0.49861476", "0.4976786", "0.49594185", "0.49509576", "0.49367857", "0.48744443", "0.48730922", "0.48563495", "0.48118123", "0.4782558", "0.47710624", "0.4764778", "0.47614318", "0.4760126", "0.47419825", "0.47264284", "0.47070095", "0.47018299", "0.46985188", "0.4684871", "0.46710885", "0.46667945", "0.46524453", "0.46524024", "0.46519125", "0.4642974", "0.4640618", "0.46397465", "0.46204215", "0.46094143", "0.4607804", "0.45923606", "0.4590722", "0.45795387", "0.45652258", "0.45648837", "0.45648706", "0.45602864", "0.455754", "0.45550576", "0.45376098", "0.4528312", "0.45276624", "0.45219713", "0.45087934", "0.4502369", "0.4485789", "0.44856766", "0.44807732", "0.44790477", "0.44733086", "0.44723734", "0.445984", "0.44560882", "0.44511473", "0.44488755", "0.44392917", "0.44374537", "0.4431899", "0.44290578", "0.44260547", "0.44229317", "0.4422877", "0.44162023", "0.44149742", "0.44010526", "0.43994245", "0.4393256", "0.4392611", "0.43911827", "0.4390067", "0.4381833", "0.43727905", "0.43661794", "0.43635353" ]
0.80914927
1
GetSubscriptions gets the subscriptions property value. The set of subscriptions on the list.
func (m *List) GetSubscriptions()([]Subscriptionable) { return m.subscriptions }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (svc *SubscriptionService) GetSubscriptions(params *param.GetParams) ([]*nimbleos.Subscription, error) {\n\tsubscriptionResp, err := svc.objectSet.GetObjectListFromParams(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn subscriptionResp, nil\n}", "func (c *Client) GetSubscriptions(queryParams ...string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET SUBSCRIPTIONS ==========\")\n\turl := buildURL(path[\"subscriptions\"])\n\n\treturn c.do(\"GET\", url, \"\", queryParams)\n}", "func (p *PubsubValueStore) GetSubscriptions() []string {\n\tp.mx.Lock()\n\tdefer p.mx.Unlock()\n\n\tvar res []string\n\tfor sub := range p.topics {\n\t\tres = append(res, sub)\n\t}\n\n\treturn res\n}", "func (client *Client) Subscriptions() (*Subscriptions, error) {\n\tsubscriptions := new(Subscriptions)\n\tif err := client.apiGet(MARATHON_API_SUBSCRIPTION, nil, subscriptions); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn subscriptions, nil\n\t}\n}", "func (a Accessor) GetSubscriptionList(service, servicePath string, subscriptions *[]Subscription) error {\n\treturn a.access(&AccessParameter{\n\t\tEpID: EntryPointIDs.Subscriptions,\n\t\tMethod: gohttp.HttpMethods.GET,\n\t\tService: service,\n\t\tServicePath: servicePath,\n\t\tPath: \"\",\n\t\tReceivedBody: subscriptions,\n\t})\n}", "func (subscriptions *Subscriptions) Get() ([]*SubscriptionInfo, error) {\n\tclient := NewHTTPClient(subscriptions.client)\n\tresp, err := client.Get(subscriptions.endpoint, subscriptions.config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata, _ := NormalizeODataCollection(resp)\n\tvar subs []*SubscriptionInfo\n\tif err := json.Unmarshal(data, &subs); err != nil {\n\t\treturn nil, err\n\t}\n\treturn subs, nil\n}", "func (k *Kraken) GetSubscriptions() ([]wshandler.WebsocketChannelSubscription, error) {\n\treturn k.Websocket.GetSubscriptions(), nil\n}", "func (m *SubscriptionManager) Subscriptions() graphqlws.Subscriptions {\n\treturn m.inner.Subscriptions()\n}", "func (r *SubscriptionsService) Get(subscription string) *SubscriptionsGetCall {\n\tc := &SubscriptionsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.subscription = subscription\n\treturn c\n}", "func (client *ClientImpl) ListSubscriptions(ctx context.Context, args ListSubscriptionsArgs) (*[]Subscription, error) {\n\tqueryParams := url.Values{}\n\tif args.PublisherId != nil {\n\t\tqueryParams.Add(\"publisherId\", *args.PublisherId)\n\t}\n\tif args.EventType != nil {\n\t\tqueryParams.Add(\"eventType\", *args.EventType)\n\t}\n\tif args.ConsumerId != nil {\n\t\tqueryParams.Add(\"consumerId\", *args.ConsumerId)\n\t}\n\tif args.ConsumerActionId != nil {\n\t\tqueryParams.Add(\"consumerActionId\", *args.ConsumerActionId)\n\t}\n\tlocationId, _ := uuid.Parse(\"fc50d02a-849f-41fb-8af1-0a5216103269\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"7.1-preview.1\", nil, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []Subscription\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (r *SubscriptionsService) List() *SubscriptionsListCall {\n\tc := &SubscriptionsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\treturn c\n}", "func (c *Client) Subscriptions() []string {\n\tresult := []string{}\n\tfor subscription, subscriber := range c.subscriptions {\n\t\tif subscriber != nil {\n\t\t\tresult = append(result, subscription)\n\t\t}\n\t}\n\treturn result\n}", "func (r *SubscriptionsService) List() *SubscriptionsListCall {\n\treturn &SubscriptionsListCall{\n\t\ts: r.s,\n\t\tcaller_: googleapi.JSONCall{},\n\t\tparams_: make(map[string][]string),\n\t\tpathTemplate_: \"subscriptions\",\n\t\tcontext_: googleapi.NoContext,\n\t}\n}", "func (m *GraphBaseServiceClient) Subscriptions()(*idb8230b65f4a369c23b4d9b41ebe568c657c92f8f77fe36d16d64528b3a317a3.SubscriptionsRequestBuilder) {\n return idb8230b65f4a369c23b4d9b41ebe568c657c92f8f77fe36d16d64528b3a317a3.NewSubscriptionsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Subscriptions()(*idb8230b65f4a369c23b4d9b41ebe568c657c92f8f77fe36d16d64528b3a317a3.SubscriptionsRequestBuilder) {\n return idb8230b65f4a369c23b4d9b41ebe568c657c92f8f77fe36d16d64528b3a317a3.NewSubscriptionsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (ss *SubscriptionsService) Get(ctx context.Context, cID, sID string) (res *Response, s *Subscription, err error) {\n\tu := fmt.Sprintf(\"v2/customers/%s/subscriptions/%s\", cID, sID)\n\n\tres, err = ss.client.get(ctx, u, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(res.content, &s); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *T) Subscriptions() <-chan map[string][]string {\n\treturn s.subscriptionsCh\n}", "func getSubscriptions(request router.Request) (int, []byte) {\n\n\tquery := datastore.NewQuery(SUBSCRIPTION_KEY).Filter(\"Project =\", request.GetPathParams()[\"project_id\"])\n\tsubscriptions := make([]Subscription, 0)\n\t_, err := query.GetAll(request.GetContext(), &subscriptions)\n\n\tif err != nil {\n\t\tlog.Errorf(request.GetContext(), \"Error retriving Subscriptions: %v\", err)\n\t\treturn http.StatusInternalServerError, []byte(err.Error())\n\t}\n\n\tsubscriptionBytes, err := json.MarshalIndent(subscriptions, \"\", \"\t\")\n\n\tif err != nil {\n\t\tlog.Errorf(request.GetContext(), \"Error retriving Subscriptions: %v\", err)\n\t\treturn http.StatusInternalServerError, []byte(err.Error())\n\t}\n\n\treturn http.StatusOK, subscriptionBytes\n\n}", "func (m *List) SetSubscriptions(value []Subscriptionable)() {\n m.subscriptions = value\n}", "func (r *SubscriptionsService) Get(customerId string, subscriptionId string) *SubscriptionsGetCall {\n\treturn &SubscriptionsGetCall{\n\t\ts: r.s,\n\t\tcustomerId: customerId,\n\t\tsubscriptionId: subscriptionId,\n\t\tcaller_: googleapi.JSONCall{},\n\t\tparams_: make(map[string][]string),\n\t\tpathTemplate_: \"customers/{customerId}/subscriptions/{subscriptionId}\",\n\t\tcontext_: googleapi.NoContext,\n\t}\n}", "func GetChatSubscriptions(db *models.DatabaseConfig, chatID int64) ([]*models.Subscription, error) {\n\n\tif db == nil {\n\t\tlog.Println(\"The DB model is nil\")\n\t\treturn nil, errors.New(\"the DB model passed is nil, can't operate\")\n\t}\n\n\tcursor, err := db.MongoClient.Collection(\"subscription\").Find(db.Ctx, bson.M{\"chatid\": chatID})\n\tif err != nil {\n\t\tlog.Println(\"There was an error trying to look for this chat's subscriptions: \", err)\n\t\treturn nil, err\n\t}\n\n\tsubs := make([]*models.Subscription, 0)\n\terr = cursor.All(db.Ctx, &subs)\n\tif err != nil {\n\t\tlog.Println(\"There was an error trying to decode subscriptions into a subscriptions slice: \", err)\n\t\treturn nil, err\n\t}\n\n\treturn subs, nil\n}", "func (r *ProjectsLocationsDataExchangesService) ListSubscriptions(resource string) *ProjectsLocationsDataExchangesListSubscriptionsCall {\n\tc := &ProjectsLocationsDataExchangesListSubscriptionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\treturn c\n}", "func (s *API) ListSubscriptions(status SubscriptionStatus) (data SubscriptionsResponse, err error) {\n\tif status == \"\" {\n\t\tstatus = SubscriptionStatusAll\n\t}\n\tendpoint := zoho.Endpoint{\n\t\tName: \"subscriptions\",\n\t\tURL: fmt.Sprintf(\"https://subscriptions.zoho.%s/api/v1/subscriptions\", s.ZohoTLD),\n\t\tMethod: zoho.HTTPGet,\n\t\tResponseData: &SubscriptionsResponse{},\n\t\tURLParameters: map[string]zoho.Parameter{\n\t\t\t\"filter_by\": zoho.Parameter(status),\n\t\t},\n\t\tHeaders: map[string]string{\n\t\t\tZohoSubscriptionsEndpointHeader: s.OrganizationID,\n\t\t},\n\t}\n\n\terr = s.Zoho.HTTPRequest(&endpoint)\n\tif err != nil {\n\t\treturn SubscriptionsResponse{}, fmt.Errorf(\"Failed to retrieve subscriptions: %s\", err)\n\t}\n\n\tif v, ok := endpoint.ResponseData.(*SubscriptionsResponse); ok {\n\t\treturn *v, nil\n\t}\n\n\treturn SubscriptionsResponse{}, fmt.Errorf(\"Data retrieved was not 'SubscriptionsResponse'\")\n}", "func (r *ProjectsLocationsDataExchangesListingsService) ListSubscriptions(resource string) *ProjectsLocationsDataExchangesListingsListSubscriptionsCall {\n\tc := &ProjectsLocationsDataExchangesListingsListSubscriptionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\treturn c\n}", "func (w *AuthWorker) Subscriptions() []*worker.Subscription {\n\treturn make([]*worker.Subscription, 0)\n}", "func (m *MockSession) GetSubscriptions() []*nats.Subscription {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSubscriptions\")\n\tret0, _ := ret[0].([]*nats.Subscription)\n\treturn ret0\n}", "func (c *Client) ListSubscriptions(namespace string) (*v1alpha1.SubscriptionList, error) {\n\tif err := c.initClient(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsubscriptionList := &v1alpha1.SubscriptionList{}\n\tif err := c.crClient.List(\n\t\tcontext.TODO(),\n\t\tsubscriptionList,\n\t\t&client.ListOptions{\n\t\t\tNamespace: namespace,\n\t\t},\n\t); err != nil {\n\t\treturn subscriptionList, err\n\t}\n\treturn subscriptionList, nil\n}", "func (c *conn) Subscriptions() map[int]*Subscription {\n\treturn c.subcriptions\n}", "func (client NotificationDataPlaneClient) ListSubscriptions(ctx context.Context, request ListSubscriptionsRequest) (response ListSubscriptionsResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listSubscriptions, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tresponse = ListSubscriptionsResponse{RawResponse: ociResponse.HTTPResponse()}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListSubscriptionsResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListSubscriptionsResponse\")\n\t}\n\treturn\n}", "func ListSubscriptions(db bun.IDB, offset, limit uint32) ([]*domain.Subscription, error) {\n\tmodel := []Subscription{}\n\n\tif err := db.NewSelect().Model(&model).Scan(context.Background()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := []*domain.Subscription{}\n\n\tfor _, subscription := range model {\n\t\tres = append(res, &domain.Subscription{\n\t\t\tPK: subscription.PK,\n\t\t\tSubscriberPK: subscription.SubscriberPK,\n\t\t\tListPK: subscription.ListPK,\n\t\t\tEmailAddress: domain.EmailAddress(subscription.EmailAddress),\n\t\t\tData: subscription.Data,\n\t\t\tVersion: subscription.Version,\n\t\t})\n\t}\n\n\treturn res, nil\n}", "func (c *Client) Subscriptions(ctx context.Context) *SubscriptionIterator {\n\treturn &SubscriptionIterator{c.Client.Subscriptions(ctx), c.projectID, c.sensor}\n}", "func (o UserDefinedResourcesPropertiesResponseOutput) QuerySubscriptions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v UserDefinedResourcesPropertiesResponse) []string { return v.QuerySubscriptions }).(pulumi.StringArrayOutput)\n}", "func (o GetTopicSubscriptionsResultOutput) Subscriptions() GetTopicSubscriptionsSubscriptionArrayOutput {\n\treturn o.ApplyT(func(v GetTopicSubscriptionsResult) []GetTopicSubscriptionsSubscription { return v.Subscriptions }).(GetTopicSubscriptionsSubscriptionArrayOutput)\n}", "func (o UserDefinedResourcesPropertiesOutput) QuerySubscriptions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v UserDefinedResourcesProperties) []string { return v.QuerySubscriptions }).(pulumi.StringArrayOutput)\n}", "func (sns *SNS) ListSubscriptions(NextToken *string) (resp *ListSubscriptionsResp, err error) {\n\tresp = &ListSubscriptionsResp{}\n\tparams := makeParams(\"ListSubscriptions\")\n\tif NextToken != nil {\n\t\tparams[\"NextToken\"] = *NextToken\n\t}\n\terr = sns.query(params, resp)\n\treturn\n}", "func (c *consulCoordinator) GetSubscribers(topic StreamID) ([]string, error) {\n\ttags := ParseTags(topic)\n\tlog.Println(\"Publisher tags:\", tags, topic)\n\ttopic = StripTags(topic)\n\tprefix := fmt.Sprintf(\"dagger/subscribers/%s/\", topic)\n\n\tc.subscribersLock.RLock()\n\tsubsList := c.subscribers[prefix]\n\tc.subscribersLock.RUnlock()\n\tif subsList == nil {\n\t\tc.subscribersLock.Lock()\n\t\tsubsList = c.subscribers[prefix]\n\t\t// check again, otherwise someone might have already acquired write lock before us\n\t\tif subsList == nil {\n\t\t\tsubsList = &subscribersList{prefix: prefix, tags: tags, c: c}\n\t\t\terr := subsList.fetch()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tc.subscribers[prefix] = subsList\n\t\t\t// keep subscribers updated and clean up if unused\n\t\t\tgo subsList.sync()\n\t\t}\n\t\tc.subscribersLock.Unlock()\n\t}\n\treturn subsList.get(), nil\n}", "func (_m *DBClient) GetSubscriptions() ([]models.Subscription, error) {\n\tret := _m.Called()\n\n\tvar r0 []models.Subscription\n\tif rf, ok := ret.Get(0).(func() []models.Subscription); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]models.Subscription)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (s *MemoryStore) Subscriptions() []subscription.Subscription {\n\ts.subsMux.RLock()\n\tdefer s.subsMux.RUnlock()\n\n\tsubs := make([]subscription.Subscription, 0, len(s.subscriptions))\n\tfor _, sub := range s.subscriptions {\n\t\tsubs = append(subs, sub)\n\t}\n\treturn subs\n}", "func (d *DatastoreSubscription) List() ([]*Subscription, error) {\n\treturn d.collectByField(func(s *Subscription) bool {\n\t\treturn true\n\t})\n}", "func (c *Contributor) GetSubscriptionsURL() string {\n\tif c == nil || c.SubscriptionsURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *c.SubscriptionsURL\n}", "func (c *Client) Subscriptions() map[string]*Subscription {\n\tsubs := make(map[string]*Subscription)\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tfor k, v := range c.subs {\n\t\tsubs[k] = v\n\t}\n\treturn subs\n}", "func (u *UserLDAPMapping) GetSubscriptionsURL() string {\n\tif u == nil || u.SubscriptionsURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *u.SubscriptionsURL\n}", "func (pager *SubscriptionsPager) GetAll() (allItems []SubscriptionListItem, err error) {\n\treturn pager.GetAllWithContext(context.Background())\n}", "func (ss *SubscriptionsService) List(ctx context.Context, cID string, opts *SubscriptionListOptions) (\n\tres *Response,\n\tsl *SubscriptionList,\n\terr error,\n) {\n\tu := fmt.Sprintf(\"v2/customers/%s/subscriptions\", cID)\n\n\tres, err = ss.list(ctx, u, opts)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(res.content, &sl); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *DefaultApiService) ListSubscription(params *ListSubscriptionParams) (*ListSubscriptionResponse, error) {\n\tpath := \"/v1/Subscriptions\"\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tif params != nil && params.SinkSid != nil {\n\t\tdata.Set(\"SinkSid\", *params.SinkSid)\n\t}\n\tif params != nil && params.PageSize != nil {\n\t\tdata.Set(\"PageSize\", fmt.Sprint(*params.PageSize))\n\t}\n\n\tresp, err := c.requestHandler.Get(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tps := &ListSubscriptionResponse{}\n\tif err := json.NewDecoder(resp.Body).Decode(ps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ps, err\n}", "func (m *MockDB) GetSubscriptions(address, network string) ([]Subscription, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSubscriptions\", address, network)\n\tret0, _ := ret[0].([]Subscription)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (o UserDefinedResourcesPropertiesResponsePtrOutput) QuerySubscriptions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *UserDefinedResourcesPropertiesResponse) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QuerySubscriptions\n\t}).(pulumi.StringArrayOutput)\n}", "func (s *Subscription) GetSubscribed() bool {\n\tif s == nil || s.Subscribed == nil {\n\t\treturn false\n\t}\n\treturn *s.Subscribed\n}", "func (prefs *UserPreferences) ChannelSubscriptions() ([]string, error) {\n\tvar subs []string\n\tif prefs.ChannelSubs != nil {\n\t\tif err := json.Unmarshal(prefs.ChannelSubs, &subs); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn subs, nil\n}", "func (u *User) GetSubscriptionsURL() string {\n\tif u == nil || u.SubscriptionsURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *u.SubscriptionsURL\n}", "func (o UserDefinedResourcesPropertiesPtrOutput) QuerySubscriptions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *UserDefinedResourcesProperties) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QuerySubscriptions\n\t}).(pulumi.StringArrayOutput)\n}", "func (client NotificationDataPlaneClient) listSubscriptions(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/subscriptions\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListSubscriptionsResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func getOutlookSubscriptions(outlookClient *http.Client) (SubscriptionsWrapper, error) {\n\tfullUrl := fmt.Sprintf(\"https://graph.microsoft.com/v1.0/subscriptions\")\n\treq, err := http.NewRequest(\n\t\t\"GET\",\n\t\tfullUrl,\n\t\tnil,\n\t)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\tres, err := outlookClient.Do(req)\n\tif err != nil {\n\t\tlog.Printf(\"suberror Client: %s\", err)\n\t\treturn SubscriptionsWrapper{}, err\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Suberror Body: %s\", err)\n\t\treturn SubscriptionsWrapper{}, err\n\t}\n\n\tnewSubs := SubscriptionsWrapper{}\n\terr = json.Unmarshal(body, &newSubs)\n\tif err != nil {\n\t\treturn SubscriptionsWrapper{}, err\n\t}\n\n\treturn newSubs, nil\n}", "func (s *Simple) Subscriptions() []plugin.Subscription {\n\treturn []plugin.Subscription{\n\t\tplugin.Subscription{\n\t\t\tEventType: event.SystemEventReceivedType,\n\t\t\tType: plugin.Sync,\n\t\t},\n\t}\n}", "func (eventNotifications *EventNotificationsV1) ListSubscriptions(listSubscriptionsOptions *ListSubscriptionsOptions) (result *SubscriptionList, response *core.DetailedResponse, err error) {\n\treturn eventNotifications.ListSubscriptionsWithContext(context.Background(), listSubscriptionsOptions)\n}", "func (mr *MockSessionMockRecorder) GetSubscriptions() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetSubscriptions\", reflect.TypeOf((*MockSession)(nil).GetSubscriptions))\n}", "func (tm *topicManager) SubscribedList() []string {\n\ttm.locker.RLock()\n\tlist := make([]string, 0, len(tm.allTopics))\n\tfor name := range tm.allTopics {\n\t\tlist = append(list, name)\n\t}\n\ttm.locker.RUnlock()\n\treturn list\n}", "func (a *StreamsApiService) GetSubscriptionsExecute(r ApiGetSubscriptionsRequest) (JsonSuccessBase, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue JsonSuccessBase\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"StreamsApiService.GetSubscriptions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/users/me/subscriptions\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.includeSubscribers != nil {\n\t\tlocalVarQueryParams.Add(\"include_subscribers\", parameterToString(*r.includeSubscribers, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (p *Proxy) List() (data [][]string) {\n\tlumber.Trace(\"Proxy listing subscriptions...\")\n\tp.RLock()\n\tdata = p.subscriptions.ToSlice()\n\tp.RUnlock()\n\n\treturn\n}", "func (s *server) ListTopicSubscriptions(ctx context.Context, in *empty.Empty) (*pb.ListTopicSubscriptionsResponse, error) {\n\treturn &pb.ListTopicSubscriptionsResponse{\n\t\tSubscriptions: []*pb.TopicSubscription{\n\t\t\t{Topic: \"TopicA\"},\n\t\t},\n\t}, nil\n}", "func (m *MockISubscription) GetSubscriptions(address, network string) ([]Subscription, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSubscriptions\", address, network)\n\tret0, _ := ret[0].([]Subscription)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetSubscription(ctx context.Context, client k8sclient.Client, installation *integreatlyv1alpha1.RHMI) (*operatorsv1alpha1.Subscription, error) {\n\tfor subscriptionName := range runTypesBySubscription {\n\t\tsubscription := &operatorsv1alpha1.Subscription{}\n\t\terr := client.Get(ctx, k8sclient.ObjectKey{\n\t\t\tName: subscriptionName,\n\t\t\tNamespace: installation.Namespace,\n\t\t}, subscription)\n\t\tif err != nil && errors.IsNotFound(err) {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn subscription, nil\n\t}\n\n\t// If subscription is not found, it could be because the CPaaS CVP build has put a non deterministic name on it.\n\t// This code may be temporary if CPaaS changes to deterministic Subscription names\n\tsubscription, err := GetRhoamCPaaSSubscription(ctx, client, installation.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif subscription != nil {\n\t\treturn subscription, nil\n\t}\n\n\treturn nil, nil\n}", "func getNodeSubscriptions(ctx echo.Context) error {\n\tglog.Infof(\"calling getNodeSubscriptions from %s\", ctx.Request().RemoteAddr)\n\n\tnodeName := ctx.Param(\"nodeName\")\n\tif nodeName == \"\" {\n\t\treturn ctx.JSON(http.StatusBadRequest,\n\t\t\t&response{\n\t\t\t\tSuccess: false,\n\t\t\t\tMessage: \"Invalid parameter\",\n\t\t\t})\n\t}\n\n\tconfig := ctx.(*apiContext).config\n\thosts := config.MustString(\"condutor\", \"mongo\")\n\tsession, err := mgo.Dial(hosts)\n\tif err != nil {\n\t\tglog.Errorf(\"getNodeSubscriptions:%v\", err)\n\t\treturn ctx.JSON(http.StatusInternalServerError,\n\t\t\t&response{\n\t\t\t\tSuccess: false,\n\t\t\t\tMessage: err.Error(),\n\t\t\t})\n\t}\n\tc := session.DB(\"iothub\").C(\"subscriptions\")\n\tdefer session.Close()\n\n\tsubs := []collector.Subscription{}\n\tif err := c.Find(bson.M{\"NodeName\": nodeName}).Limit(100).Iter().All(&subs); err != nil {\n\t\tglog.Errorf(\"getNodeSubscriptions:%v\", err)\n\t\treturn ctx.JSON(http.StatusNotFound,\n\t\t\t&response{\n\t\t\t\tSuccess: false,\n\t\t\t\tMessage: err.Error(),\n\t\t\t})\n\t}\n\treturn ctx.JSON(http.StatusOK, &response{\n\t\tSuccess: true,\n\t\tResult: subs,\n\t})\n}", "func (a *Accessor) GetSubscription(service, servicePath, id string, subscription *Subscription) error {\n\treturn a.access(&AccessParameter{\n\t\tEpID: EntryPointIDs.Subscriptions,\n\t\tMethod: gohttp.HttpMethods.GET,\n\t\tService: service,\n\t\tServicePath: servicePath,\n\t\tPath: fmt.Sprintf(\"/%s\", id),\n\t\tReceivedBody: subscription,\n\t})\n}", "func (eventNotifications *EventNotificationsV1) GetSubscription(getSubscriptionOptions *GetSubscriptionOptions) (result *Subscription, response *core.DetailedResponse, err error) {\n\treturn eventNotifications.GetSubscriptionWithContext(context.Background(), getSubscriptionOptions)\n}", "func GetSubscription(db bun.IDB, listPK, pk uuid.UUID) (*domain.Subscription, error) {\n\tmodel := Subscription{\n\t\tPK: pk,\n\t\tListPK: listPK,\n\t}\n\n\tif err := db.NewSelect().Model(&model).WherePK().Scan(context.Background()); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &domain.Subscription{\n\t\tPK: model.PK,\n\t\tEmailAddress: domain.EmailAddress(model.EmailAddress),\n\t\tVersion: model.Version,\n\t}, nil\n}", "func (r *reconciler) getSubscription(ctx context.Context, t *v1alpha1.Trigger) (*v1alpha1.Subscription, error) {\n\tlist := &v1alpha1.SubscriptionList{}\n\topts := &runtimeclient.ListOptions{\n\t\tNamespace: t.Namespace,\n\t\tLabelSelector: labels.SelectorFromSet(resources.SubscriptionLabels(t)),\n\t\t// Set Raw because if we need to get more than one page, then we will put the continue token\n\t\t// into opts.Raw.Continue.\n\t\tRaw: &metav1.ListOptions{},\n\t}\n\n\terr := r.client.List(ctx, opts, list)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, s := range list.Items {\n\t\tif metav1.IsControlledBy(&s, t) {\n\t\t\treturn &s, nil\n\t\t}\n\t}\n\n\treturn nil, k8serrors.NewNotFound(schema.GroupResource{}, \"\")\n}", "func (r *ProjectsLocationsSubscriptionsService) Get(name string) *ProjectsLocationsSubscriptionsGetCall {\n\tc := &ProjectsLocationsSubscriptionsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func (c *PublisherClient) ListTopicSubscriptions(ctx context.Context, req *pubsubpb.ListTopicSubscriptionsRequest) *StringIterator {\n\tctx = metadata.NewContext(ctx, c.metadata)\n\tit := &StringIterator{}\n\tit.apiCall = func() error {\n\t\tvar resp *pubsubpb.ListTopicSubscriptionsResponse\n\t\terr := gax.Invoke(ctx, func(ctx context.Context) error {\n\t\t\tvar err error\n\t\t\treq.PageToken = it.nextPageToken\n\t\t\treq.PageSize = it.pageSize\n\t\t\tresp, err = c.client.ListTopicSubscriptions(ctx, req)\n\t\t\treturn err\n\t\t}, c.CallOptions.ListTopicSubscriptions...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif resp.NextPageToken == \"\" {\n\t\t\tit.atLastPage = true\n\t\t}\n\t\tit.nextPageToken = resp.NextPageToken\n\t\tit.items = resp.Subscriptions\n\t\treturn nil\n\t}\n\treturn it\n}", "func (client BaseClient) GetSubscription(ctx context.Context, subscriptionID uuid.UUID, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (result SetObject, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/BaseClient.GetSubscription\")\n defer func() {\n sc := -1\n if result.Response.Response != nil {\n sc = result.Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.GetSubscriptionPreparer(ctx, subscriptionID, xMsRequestid, xMsCorrelationid)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetSubscription\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.GetSubscriptionSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetSubscription\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.GetSubscriptionResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetSubscription\", resp, \"Failure responding to request\")\n }\n\n return\n }", "func (a *App) getSubscribersOnline(w http.ResponseWriter, r *http.Request) {\n\n\tsubs, err := models.GetSubscribersOnline(a.jsonrpcHTTPAddr, a.httpClient)\n\tif err != nil {\n\t\trespond.ERROR(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\trespond.JSON(w, http.StatusOK, subs)\n\treturn\n}", "func (r *SubscriptionRepository) Get(id string) (*domain.Subscription, error) {\n\ts, err := r.applyOperation(func() (interface{}, error) {\n\t\treturn r.get(id)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ToDomain(s.(*Subscription)), err\n}", "func (m *UserResource) ListUserSubscriptions(ctx context.Context, userId string) ([]*Subscription, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/users/%v/subscriptions\", userId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar subscription []*Subscription\n\n\tresp, err := rq.Do(ctx, req, &subscription)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn subscription, resp, nil\n}", "func NewSubscriptions(client *gosip.SPClient, endpoint string, config *RequestConfig) *Subscriptions {\n\treturn &Subscriptions{\n\t\tclient: client,\n\t\tendpoint: endpoint,\n\t\tconfig: config,\n\t}\n}", "func (subscription *Subscription) Get() (*SubscriptionInfo, error) {\n\tclient := NewHTTPClient(subscription.client)\n\tresp, err := client.Get(subscription.endpoint, subscription.config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn subscription.parseResponse(resp)\n}", "func (c *Client) GetSubscription(subscriptionID string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET SUBSCRIPTION ==========\")\n\turl := buildURL(path[\"subscriptions\"], subscriptionID)\n\n\treturn c.do(\"GET\", url, \"\", nil)\n}", "func (session Session) GetWebhooks() (result []SubscriptionInfo, err error) {\n\treq, err := getWebhooksSubscriptions(nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsession.addTokenAuth(req)\n\tres, err := session.client.Do(req)\n\tif err != nil {\n\t\tlog.Printf(\"Error while executing GetWebhooks request: %s\", err)\n\t\treturn\n\t}\n\n\tif res.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Request returned: %d\", res.StatusCode)\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading response body: %s\", err)\n\t\treturn\n\t}\n\n\tvar d dataResult\n\tif err = json.Unmarshal(body, &d); err != nil {\n\t\tlog.Printf(\"Error while parsing response body: %s\", err)\n\t\tlog.Printf(\"Body: %s\", body)\n\t\treturn\n\t}\n\n\tfor _, inner := range d.Data {\n\t\tvar sub SubscriptionInfo\n\t\tif err = json.Unmarshal(inner, &sub); err != nil {\n\t\t\tlog.Printf(\"Error while parsing internal JSON: %s\", err)\n\t\t\tlog.Printf(\"Invalid JSON: %s\", inner)\n\t\t\terr = nil\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, sub)\n\t}\n\n\treturn\n}", "func (e *FbEvent) Subscribers() []*Subscription {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\treturn e.subscribers[:]\n}", "func (col *CCPrinterSubscriptionCollection) GetPrinterSubscriptions(ctx context.Context, printerId string) ([]*CCPrinterSubscriptionModel, error) {\n\n\tqueryInput := &dynamodb.QueryInput{\n\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\":printerId\": {\n\t\t\t\tS: aws.String(printerId),\n\t\t\t},\n\t\t},\n\t\tKeyConditionExpression: aws.String(\"PrinterID = :printerId\"),\n\t\tTableName: aws.String(col.tableName),\n\t}\n\n\tresult, err := col.QueryWithContext(ctx, queryInput)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(result.Items) == 0 {\n\t\treturn nil, NotFoundErr\n\t}\n\n\tvar subscriptionsArr []*CCPrinterSubscriptionModel\n\n\tfor _, item := range result.Items {\n\t\tsubscription := CCPrinterSubscriptionModel{}\n\t\terr := dynamodbattribute.UnmarshalMap(item, &subscription)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsubscriptionsArr = append(subscriptionsArr, &subscription)\n\t}\n\n\treturn subscriptionsArr, nil\n}", "func getSubscribers() (subs []common.SubscriberEntry, retErr error) {\n\n\tvar subList []common.SubscriberEntry\n\n\t// Creazione DynamoDB client\n\tsvc := dynamodb.New(common.Sess)\n\n\t// Determino l'input della query\n\tinput := &dynamodb.ScanInput{\n\t\tTableName: aws.String(subTableName),\n\t}\n\n\t// Effettuo la query\n\tresult, err := svc.Scan(input)\n\tif err != nil {\n\t\tcommon.Fatal(\"[BROKER] Errore nell'esecuzione della Query\\n\" + err.Error())\n\t\treturn nil, err\n\t}\n\n\tfor _, r := range result.Items {\n\n\t\tvar subID = common.SubscriberEntry{}\n\n\t\t// Unmarshaling del dato ottenuto\n\t\terr = dynamodbattribute.UnmarshalMap(r, &subID)\n\t\tif err != nil {\n\t\t\tcommon.Fatal(\"Errore nell'unmarshaling della entry\\n\" + err.Error())\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsubList = append(subList, subID)\n\n\t}\n\n\n\treturn subList, nil\n\n}", "func (s *subscriberdbServicer) ListSubscribers(ctx context.Context, req *lte_protos.ListSubscribersRequest) (*lte_protos.ListSubscribersResponse, error) {\n\tgateway := protos.GetClientGateway(ctx)\n\tif gateway == nil {\n\t\treturn nil, status.Errorf(codes.PermissionDenied, \"missing gateway identity\")\n\t}\n\tif !gateway.Registered() {\n\t\treturn nil, status.Errorf(codes.PermissionDenied, \"gateway is not registered\")\n\t}\n\tnetworkID := gateway.NetworkId\n\n\tapnsByName, apnResourcesByAPN, err := loadAPNs(gateway)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsubProtos, nextToken, err := subscriberdb.LoadSubProtosPage(req.PageSize, req.PageToken, networkID, apnsByName, apnResourcesByAPN)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tflatDigest := &lte_protos.Digest{Md5Base64Digest: \"\"}\n\tperSubDigests := []*lte_protos.SubscriberDigestWithID{}\n\t// The digests are sent back during the request for the first page of subscriber data\n\tif req.PageToken == \"\" {\n\t\tflatDigest, _ = s.getDigestInfo(&lte_protos.Digest{Md5Base64Digest: \"\"}, networkID)\n\t\tperSubDigests, err = s.perSubDigestStore.GetDigest(networkID)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to get per-sub digests from store for network %+v: %+v\", networkID, err)\n\t\t}\n\t}\n\n\tlistRes := &lte_protos.ListSubscribersResponse{\n\t\tSubscribers: subProtos,\n\t\tNextPageToken: nextToken,\n\t\tFlatDigest: flatDigest,\n\t\tPerSubDigests: perSubDigests,\n\t}\n\treturn listRes, nil\n}", "func (psc *PubSubChannel) NumSubscriptions() int {\n psc.subsMutex.RLock()\n defer psc.subsMutex.RUnlock()\n return len(psc.subscriptions)\n}", "func (m *consulMetadataReport) GetSubscribedURLs(subscriberMetadataIdentifier *identifier.SubscriberMetadataIdentifier) ([]string, error) {\n\tk := subscriberMetadataIdentifier.GetIdentifierKey()\n\tkv, _, err := m.client.KV().Get(k, nil)\n\tif err != nil || kv == nil {\n\t\treturn emptyStrSlice, err\n\t}\n\treturn []string{string(kv.Value)}, nil\n}", "func (h *Handler) ActiveSubscriptions() int {\n\treturn h.subCancellations.Len()\n}", "func (a *AmsiApiService) SubGET(ctx context.Context, subscriptionType string) (SubscriptionLinkList, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue SubscriptionLinkList\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/subscriptions\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\tlocalVarQueryParams.Add(\"subscriptionType\", parameterToString(subscriptionType, \"\"))\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\tif err == nil {\n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v SubscriptionLinkList\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 401 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 406 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 429 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (client BaseClient) GetSubscriptionOperations(ctx context.Context, subscriptionID uuid.UUID, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (result SetObject, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/BaseClient.GetSubscriptionOperations\")\n defer func() {\n sc := -1\n if result.Response.Response != nil {\n sc = result.Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.GetSubscriptionOperationsPreparer(ctx, subscriptionID, xMsRequestid, xMsCorrelationid)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetSubscriptionOperations\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.GetSubscriptionOperationsSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetSubscriptionOperations\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.GetSubscriptionOperationsResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"GetSubscriptionOperations\", resp, \"Failure responding to request\")\n }\n\n return\n }", "func (s *subscription) Topics() []string {\n\treturn s.topics\n}", "func (client IdentityClient) ListRegionSubscriptions(ctx context.Context, request ListRegionSubscriptionsRequest) (response ListRegionSubscriptionsResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listRegionSubscriptions, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ListRegionSubscriptionsResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListRegionSubscriptionsResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListRegionSubscriptionsResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListRegionSubscriptionsResponse\")\n\t}\n\treturn\n}", "func (st *SubTree)GetSubscribers(topic string)([]*Subscriber,error){\n\ttopicArray,err := PubTopicCheckAndSpilt(topic)\n\tif err!=nil{\n\t\treturn nil,err\n\t}\n\tst.lock.Lock()\n\tdefer st.lock.Unlock()\n\tsubers:=make([]*Subscriber,0)\n\tcurrentLevel :=st.root\n\tif len(topicArray)>0{\n\t\tif topicArray[0] == \"/\" {\n\t\t\tif _, exist := currentLevel.nodes[\"#\"]; exist {\n\t\t\t\tsubers = append(subers,currentLevel.nodes[\"#\"].subList...)\n\t\t\t}\n\t\t\tif _, exist := currentLevel.nodes[\"+\"]; exist {\n\t\t\t\tmatchLevel(currentLevel.nodes[\"/\"].children, topicArray[1:], &subers)\n\t\t\t}\n\t\t\tif _, exist := currentLevel.nodes[\"/\"]; exist {\n\t\t\t\tmatchLevel(currentLevel.nodes[\"/\"].children, topicArray[1:], &subers)\n\t\t\t}\n\t\t} else {\n\t\t\tmatchLevel(st.root, topicArray, &subers)\n\t\t}\n\t}\n\treturn subers,nil\n }", "func (mr *MockDBMockRecorder) GetSubscriptions(address, network interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetSubscriptions\", reflect.TypeOf((*MockDB)(nil).GetSubscriptions), address, network)\n}", "func (m *MockDB) ListSubscriptions(userID uint) ([]Subscription, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListSubscriptions\", userID)\n\tret0, _ := ret[0].([]Subscription)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (ss *SubscriptionsService) All(ctx context.Context, opts *SubscriptionListOptions) (\n\tres *Response,\n\tsl *SubscriptionList,\n\terr error,\n) {\n\tu := \"v2/subscriptions\"\n\n\tres, err = ss.list(ctx, u, opts)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(res.content, &sl); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func getSubscribersID() (subsID []string, retErr error) {\n\n\tvar subList []string\n\n\t// Creazione DynamoDB client\n\tsvc := dynamodb.New(common.Sess)\n\n\t// Determino l'input della query\n\tinput := &dynamodb.ScanInput{\n\t\tTableName: aws.String(subTableName),\n\t}\n\n\t// Effettuo la query\n\tresult, err := svc.Scan(input)\n\tif err != nil {\n\t\tcommon.Fatal(\"[BROKER] Errore nell'esecuzione della Query\\n\" + err.Error())\n\t\treturn nil, err\n\t}\n\n\tfor _, r := range result.Items {\n\n\t\tvar subID = common.SubscriberEntry{}\n\n\t\t// Unmarshaling del dato ottenuto\n\t\terr = dynamodbattribute.UnmarshalMap(r, &subID)\n\t\tif err != nil {\n\t\t\tcommon.Fatal(\"Errore nell'unmarshaling della entry\\n\" + err.Error())\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsubList = append(subList, subID.SubID)\n\n\t}\n\n\n\treturn subList, nil\n\n}", "func NewWeaveSubscriptionsGet(ctx *middleware.Context, handler WeaveSubscriptionsGetHandler) *WeaveSubscriptionsGet {\n\treturn &WeaveSubscriptionsGet{Context: ctx, Handler: handler}\n}", "func (o *ClusterAuthorizationResponse) GetSubscription() ObjectReference {\n\tif o == nil || o.Subscription == nil {\n\t\tvar ret ObjectReference\n\t\treturn ret\n\t}\n\treturn *o.Subscription\n}", "func getSubs(mapper *gosubscribe.Mapper) []*gosubscribe.User {\n\tusers := []*gosubscribe.User{}\n\tsubs := []gosubscribe.Subscription{}\n\tgosubscribe.DB.Table(\"subscriptions\").Where(\"mapper_id = ?\", mapper.ID).Find(&subs)\n\tfor _, sub := range subs {\n\t\tuser, err := gosubscribe.GetUser(sub.UserID)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"No user found for %d\\n\", sub.UserID)\n\t\t} else {\n\t\t\tusers = append(users, user)\n\t\t}\n\t}\n\tlog.Printf(\"Retrieved %d subscriber(s) for %s\\n\", len(users), mapper.Username)\n\treturn users\n}", "func (repo *feedRepository) GetChannels(f *feed.Feed, sortBy string, sortOrder string) ([]*feed.Channel, error) {\n\tchannelSubscriptions := make([]*feed.Channel, 0)\n\trows, err := repo.db.Query(fmt.Sprintf(`\n\t\tSELECT username, name, subscription_time\n\t\tFROM (\n\t\t\t(\n\t\t\t\tSELECT channel_username, subscription_time\n\t\t\t\tFROM feed_subscriptions\n\t\t\t\tWHERE feed_id = $1\n\t\t\t) AS S (username, subscription_time)\n\t\t\tNATURAL JOIN\n\t\t\tchannels\n\t\t)\n\t\tORDER BY %s %s NULLS LAST`, sortBy, sortOrder), f.ID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"querying for feed_subscriptions failed because of: %s\", err.Error())\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tc := new(feed.Channel)\n\t\terr := rows.Scan(&c.Channelname, &c.Name, &c.SubscriptionTime)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"scanning from rows failed because: %s\", err.Error())\n\t\t}\n\t\tchannelSubscriptions = append(channelSubscriptions, c)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"scanning from rows faulty because: %s\", err.Error())\n\t}\n\treturn channelSubscriptions, nil\n}", "func GetSubscribers() (Items, error) {\n\tvar response Response\n\t//nuova GET con query params\n\treq, err := http.NewRequest(\"GET\", \"https://www.googleapis.com/youtube/v3/channels\", nil)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn Items{}, err\n\t}\n\n\t//da qui definiamo i query param\n\tqueryparam := req.URL.Query()\n\tqueryparam.Add(\"key\", os.Getenv(\"YOUTUBE_KEY\"))\n\tqueryparam.Add(\"id\", os.Getenv(\"CHANNEL_ID\"))\n\tqueryparam.Add(\"part\", \"statistics\")\n\t//prearo il nuovo URL\n\treq.URL.RawQuery = queryparam.Encode()\n\n\t//eseguiamo la request con tutti i parametri\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tfmt.Println(\"ERRORE NELLA CHIAMATA: \", err)\n\t\treturn Items{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tfmt.Println(\"Response Status: \", resp.Status)\n\t//se arriviamo qui è perchè abbiamo ottenuto un 200\n\t//leggo l'ogggetto arrivato\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\t//alla fine unmarshal del risultato dentro nostra struct\n\terr = json.Unmarshal(body, &response)\n\tif err != nil {\n\t\treturn Items{}, err\n\t}\n\n\t//mandiamo indietro solo il primo elemento\n\treturn response.Items[0], nil\n}", "func (o *GetSubscriptionsParams) WithPageSize(pageSize *int32) *GetSubscriptionsParams {\n\to.SetPageSize(pageSize)\n\treturn o\n}", "func (m *GraphBaseServiceClient) SubscriptionsById(id string)(*if405c95e51d6685837bc60276ac44a0be46f00a5930cc59ce198c3a5119099a0.SubscriptionItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"subscription%2Did\"] = id\n }\n return if405c95e51d6685837bc60276ac44a0be46f00a5930cc59ce198c3a5119099a0.NewSubscriptionItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}" ]
[ "0.7868426", "0.7729767", "0.7729074", "0.7635478", "0.75740594", "0.74823356", "0.7409729", "0.7403774", "0.7206823", "0.71313256", "0.7025433", "0.7023735", "0.69475216", "0.6929064", "0.6929064", "0.69113976", "0.6910021", "0.68576664", "0.6846115", "0.6791046", "0.6753372", "0.6744555", "0.67294186", "0.67060715", "0.6703233", "0.66073", "0.6584021", "0.65816045", "0.65784806", "0.6565604", "0.65477335", "0.6515876", "0.64940774", "0.648313", "0.6451298", "0.64440703", "0.64429635", "0.64191985", "0.6387902", "0.6387561", "0.6373621", "0.63700235", "0.6345708", "0.6325786", "0.63249373", "0.63153166", "0.6286452", "0.6271136", "0.6266406", "0.6265164", "0.6222942", "0.6222374", "0.61291796", "0.61238354", "0.6121104", "0.6109342", "0.6089806", "0.60471576", "0.60407335", "0.60140955", "0.59885275", "0.5972139", "0.59587497", "0.59586036", "0.5957837", "0.59341586", "0.5925849", "0.5914213", "0.5891211", "0.5870116", "0.586186", "0.5818522", "0.5814893", "0.5809699", "0.5807262", "0.5805765", "0.579935", "0.5787223", "0.57867837", "0.57575595", "0.57098293", "0.5707426", "0.5673956", "0.5672702", "0.5661634", "0.5652127", "0.5645628", "0.56442785", "0.5616718", "0.5609315", "0.5605694", "0.5594208", "0.5580893", "0.55723304", "0.5560775", "0.5557863", "0.5545962", "0.55378246", "0.55335814", "0.5530565" ]
0.8141
0
GetSystem gets the system property value. If present, indicates that this is a systemmanaged list. Readonly.
func (m *List) GetSystem()(SystemFacetable) { return m.system }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client BaseClient) GetSystem(ctx context.Context, pathParameter string) (result System, 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\", \"GetSystem\", err.Error())\n\t}\n\n\treq, err := client.GetSystemPreparer(ctx, pathParameter)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"GetSystem\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetSystemSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"GetSystem\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetSystemResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"GetSystem\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (o *RoleWithAccess) GetSystem() bool {\n\tif o == nil || o.System == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.System\n}", "func (a *Client) GetSystem(params *GetSystemParams) (*GetSystemOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSystemParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getSystem\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/Systems/{identifier}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetSystemReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetSystemOK), nil\n\n}", "func (a *AllApiService) SystemPropertyGetSystemProperty(ctx _context.Context, body SystemPropertyGetSystemProperty) (SystemPropertyGetSystemPropertyResult, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue SystemPropertyGetSystemPropertyResult\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/systemProperty/getSystemProperty\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v SystemPropertyGetSystemPropertyResult\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (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 (m *List) SetSystem(value SystemFacetable)() {\n m.system = value\n}", "func (o *IamServiceProviderAllOf) GetSystem() IamSystemRelationship {\n\tif o == nil || o.System == nil {\n\t\tvar ret IamSystemRelationship\n\t\treturn ret\n\t}\n\treturn *o.System\n}", "func (m *Drive) GetSystem()(SystemFacetable) {\n return m.system\n}", "func (a *AllApiService) SystemPropertyGetSystemProperties(ctx _context.Context, body SystemPropertyGetSystemProperties) ([]SystemPropertyGetSystemPropertiesResultItem, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []SystemPropertyGetSystemPropertiesResultItem\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/systemProperty/getSystemProperties\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v []SystemPropertyGetSystemPropertiesResultItem\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (client *APIClient) GetSystem(systemName string) (system System, err error) {\n\tresponse, err := client.request(\"GET\", urlSystem(systemName), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = utilities.FromJSON(response, &system)\n\treturn\n}", "func (c *Client) GetSystem(name string) (*System, error) {\n\tvar system System\n\n\tresult, err := c.Call(\"get_system\", name, c.Token)\n\tif err != nil {\n\t\treturn &system, err\n\t}\n\n\tif result == \"~\" {\n\t\treturn nil, fmt.Errorf(\"System %s not found.\", name)\n\t}\n\n\tdecodeResult, err := decodeCobblerItem(result, &system)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := decodeResult.(*System)\n\ts.Client = *c\n\n\treturn s, nil\n}", "func (client BaseClient) GetSystems(ctx context.Context, tenant string) (result ListSystem, err error) {\n\treq, err := client.GetSystemsPreparer(ctx, tenant)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"GetSystems\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetSystemsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"GetSystems\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetSystemsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"GetSystems\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (s UserSet) IsSystem() bool {\n\tres := s.Collection().Call(\"IsSystem\")\n\tresTyped, _ := res.(bool)\n\treturn resTyped\n}", "func (o *Block) GetHintSystem(ctx context.Context) (hintSystem bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceBlock, \"HintSystem\").Store(&hintSystem)\n\treturn\n}", "func (s *Systems) GetSystemResource(ctx context.Context, req *systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) {\n\tvar resp systemsproto.SystemsResponse\n\tsessionToken := req.SessionToken\n\tauthResp := s.IsAuthorizedRPC(sessionToken, []string{common.PrivilegeLogin}, []string{})\n\tif authResp.StatusCode != http.StatusOK {\n\t\tlog.Error(\"error while trying to authenticate session\")\n\t\tfillSystemProtoResponse(&resp, authResp)\n\t\treturn &resp, nil\n\t}\n\tvar pc = systems.PluginContact{\n\t\tContactClient: pmbhandle.ContactPlugin,\n\t\tDevicePassword: common.DecryptWithPrivateKey,\n\t\tGetPluginStatus: scommon.GetPluginStatus,\n\t}\n\tdata := pc.GetSystemResource(req)\n\tfillSystemProtoResponse(&resp, data)\n\treturn &resp, nil\n}", "func (o *IamServiceProviderAllOf) GetSystemOk() (*IamSystemRelationship, bool) {\n\tif o == nil || o.System == nil {\n\t\treturn nil, false\n\t}\n\treturn o.System, true\n}", "func (m *AndroidManagedStoreApp) GetIsSystemApp()(*bool) {\n val, err := m.GetBackingStore().Get(\"isSystemApp\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func AvailableSystems() []System {\n\treturn systemRegistry\n}", "func (o *RoleWithAccess) HasSystem() bool {\n\tif o != nil && o.System != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func GetSystemRegistryQuota(pdwQuotaAllowed *DWORD, pdwQuotaUsed *DWORD) bool {\n\tret1 := syscall3(getSystemRegistryQuota, 2,\n\t\tuintptr(unsafe.Pointer(pdwQuotaAllowed)),\n\t\tuintptr(unsafe.Pointer(pdwQuotaUsed)),\n\t\t0)\n\treturn ret1 != 0\n}", "func GetSystemResource(req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) {\n\tconn, err := services.ODIMService.Client(services.Systems)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create client connection: %v\", err)\n\t}\n\tdefer conn.Close()\n\tasService := systemsproto.NewSystemsClient(conn)\n\tresp, err := asService.GetSystemResource(context.TODO(), &req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error: RPC error: %v\", err)\n\t}\n\treturn resp, nil\n}", "func (o IopingSpecVolumeVolumeSourceScaleIOPtrOutput) System() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceScaleIO) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.System\n\t}).(pulumi.StringPtrOutput)\n}", "func (o FioSpecVolumeVolumeSourceScaleIOPtrOutput) System() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceScaleIO) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.System\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *RoleWithAccess) GetSystemOk() (*bool, bool) {\n\tif o == nil || o.System == nil {\n\t\treturn nil, false\n\t}\n\treturn o.System, true\n}", "func (c MethodsCollection) IsSystem() pIsSystem {\n\treturn pIsSystem{\n\t\tMethod: c.MustGet(\"IsSystem\"),\n\t}\n}", "func ListSystems(query, outputFormat string) {\n\tsystemList, err := apiClientV1.GetSystems(false)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not read system users, err='%s'\\n\", err)\n\t}\n\n\toutputData(outputFormat, query, systemList)\n\n}", "func (a *Client) GetSystemTasks(params *GetSystemTasksParams) (*GetSystemTasksOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSystemTasksParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getSystemTasks\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/TaskService/Oem/Tasks/{identifier}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetSystemTasksReader{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.(*GetSystemTasksOK), nil\n\n}", "func (o *IamServiceProviderAllOf) HasSystem() bool {\n\tif o != nil && o.System != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func GetSystem(name string) (System, error) {\n\tswitch name {\n\tcase \"cd\":\n\t\treturn CDSystem, nil\n\tcase \"main\":\n\t\treturn MainSystem, nil\n\tcase \"public\":\n\t\treturn PublicSystem, nil\n\tcase \"publiccd\":\n\t\treturn PublicCDSystem, nil\n\t}\n\treturn System{}, fmt.Errorf(\"invalid system: %s\", name)\n}", "func (o *RoleWithAccess) SetSystem(v bool) {\n\to.System = &v\n}", "func (cli *CLI) SystemStatus() {\n\ts := system.New(types.NamespacedName{Namespace: cli.Namespace, Name: cli.SystemName}, cli.Client, scheme.Scheme, nil)\n\ts.Load()\n\n\t// TEMPORARY ? check PVCs here because we couldn't own them in openshift\n\t// See https://github.com/noobaa/noobaa-operator/issues/12\n\tfor i := range s.CoreApp.Spec.VolumeClaimTemplates {\n\t\tt := &s.CoreApp.Spec.VolumeClaimTemplates[i]\n\t\tpvc := &corev1.PersistentVolumeClaim{\n\t\t\tTypeMeta: metav1.TypeMeta{Kind: \"PersistentVolumeClaim\"},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: t.Name + \"-\" + cli.SystemName + \"-core-0\",\n\t\t\t\tNamespace: cli.Namespace,\n\t\t\t},\n\t\t}\n\t\tutil.KubeCheck(cli.Client, pvc)\n\t}\n\n\t// sys := cli.LoadSystemDefaults()\n\t// util.KubeCheck(cli.Client, sys)\n\tif s.NooBaa.Status.Phase == nbv1.SystemPhaseReady {\n\t\tcli.Log.Printf(\"✅ System Phase is \\\"%s\\\"\\n\", s.NooBaa.Status.Phase)\n\t\tsecretRef := s.NooBaa.Status.Accounts.Admin.SecretRef\n\t\tsecret := &corev1.Secret{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: secretRef.Name,\n\t\t\t\tNamespace: secretRef.Namespace,\n\t\t\t},\n\t\t}\n\t\tutil.KubeCheck(cli.Client, secret)\n\n\t\tcli.Log.Println(\"\")\n\t\tcli.Log.Println(\"#------------------#\")\n\t\tcli.Log.Println(\"#- Mgmt Addresses -#\")\n\t\tcli.Log.Println(\"#------------------#\")\n\t\tcli.Log.Println(\"\")\n\n\t\tcli.Log.Println(\"ExternalDNS :\", s.NooBaa.Status.Services.ServiceMgmt.ExternalDNS)\n\t\tcli.Log.Println(\"ExternalIP :\", s.NooBaa.Status.Services.ServiceMgmt.ExternalIP)\n\t\tcli.Log.Println(\"NodePorts :\", s.NooBaa.Status.Services.ServiceMgmt.NodePorts)\n\t\tcli.Log.Println(\"InternalDNS :\", s.NooBaa.Status.Services.ServiceMgmt.InternalDNS)\n\t\tcli.Log.Println(\"InternalIP :\", s.NooBaa.Status.Services.ServiceMgmt.InternalIP)\n\t\tcli.Log.Println(\"PodPorts :\", s.NooBaa.Status.Services.ServiceMgmt.PodPorts)\n\n\t\tcli.Log.Println(\"\")\n\t\tcli.Log.Println(\"#----------------#\")\n\t\tcli.Log.Println(\"#- S3 Addresses -#\")\n\t\tcli.Log.Println(\"#----------------#\")\n\t\tcli.Log.Println(\"\")\n\n\t\tcli.Log.Println(\"ExternalDNS :\", s.NooBaa.Status.Services.ServiceS3.ExternalDNS)\n\t\tcli.Log.Println(\"ExternalIP :\", s.NooBaa.Status.Services.ServiceS3.ExternalIP)\n\t\tcli.Log.Println(\"NodePorts :\", s.NooBaa.Status.Services.ServiceS3.NodePorts)\n\t\tcli.Log.Println(\"InternalDNS :\", s.NooBaa.Status.Services.ServiceS3.InternalDNS)\n\t\tcli.Log.Println(\"InternalIP :\", s.NooBaa.Status.Services.ServiceS3.InternalIP)\n\t\tcli.Log.Println(\"PodPorts :\", s.NooBaa.Status.Services.ServiceS3.PodPorts)\n\n\t\tcli.Log.Println(\"\")\n\t\tcli.Log.Println(\"#---------------#\")\n\t\tcli.Log.Println(\"#- Credentials -#\")\n\t\tcli.Log.Println(\"#---------------#\")\n\t\tcli.Log.Println(\"\")\n\t\tfor key, value := range secret.Data {\n\t\t\tcli.Log.Printf(\"%s: %s\\n\", key, string(value))\n\t\t}\n\t\tcli.Log.Println(\"\")\n\t} else {\n\t\tcli.Log.Printf(\"❌ System Phase is \\\"%s\\\"\\n\", s.NooBaa.Status.Phase)\n\n\t}\n}", "func GetSystemResolvers() []string {\n\tresolvers, err := GetNameServersFromResolveConfig(defaultResolvConf)\n\tif err != nil {\n\t\treturn []string{}\n\t}\n\treturn resolvers\n}", "func System() disko.System {\n\treturn &linuxSystem{}\n}", "func GetSystemMemory() *System {\n\tinfo, err := mem.VirtualMemory()\n\tif err != nil {\n\t\tfmt.Printf(\"mem.VirtualMemory error: %v\\n\", err)\n\t\treturn &System{}\n\t}\n\n\treturn &System{\n\t\tTotal: info.Total >> 20,\n\t\tFree: info.Free >> 20,\n\t\tUsagePercent: info.UsedPercent,\n\t}\n}", "func GetSystemModule(name string) (SysModule, bool) {\n\tval, ok := systemModules[name]\n\treturn val, ok\n}", "func (client BaseClient) GetSystemsResponder(resp *http.Response) (result ListSystem, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result.Value),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (o *IamServiceProviderAllOf) SetSystem(v IamSystemRelationship) {\n\to.System = &v\n}", "func GetSystemsCollection(req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) {\n\tconn, err := services.ODIMService.Client(services.Systems)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create client connection: %v\", err)\n\t}\n\tdefer conn.Close()\n\tasService := systemsproto.NewSystemsClient(conn)\n\tresp, err := asService.GetSystemsCollection(context.TODO(), &req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error: RPC error: %v\", err)\n\t}\n\treturn resp, nil\n}", "func GetSysMetric() (*SysMetric, error) {\n\tvar m SysMetric\n\n\tcpu, err := cpu.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm.CPUCores = cpu.CPUCount\n\n\tmemory, err := memory.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm.MemoryBytes = memory.Total\n\tm.MemoryBytesUsed = memory.Used\n\n\tm.DiskBytes = getDiskSizeTotal(C.Dir)\n\tm.DiskBytesUsed = getDiskSizeUsed(C.Dir)\n\n\treturn &m, nil\n}", "func (this *KeyspaceTerm) IsSystem() bool {\n\treturn this.path != nil && this.path.IsSystem()\n}", "func (a *Client) System(params *SystemParams, authInfo runtime.ClientAuthInfoWriter) (*SystemOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewSystemParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"system\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/system\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &SystemReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*SystemOK), nil\n\n}", "func GetSystemID() SystemID {\n\treturn SystemID(C.al_get_system_id())\n}", "func GetSystemSettings(paramsReader params.Reader) (settings System, err error) {\n\tsettings.UID, err = paramsReader.GetUID()\n\tif err != nil {\n\t\treturn settings, err\n\t}\n\tsettings.GID, err = paramsReader.GetGID()\n\tif err != nil {\n\t\treturn settings, err\n\t}\n\tsettings.Timezone, err = paramsReader.GetTimezone()\n\tif err != nil {\n\t\treturn settings, err\n\t}\n\tsettings.IPStatusFilepath, err = paramsReader.GetIPStatusFilepath()\n\tif err != nil {\n\t\treturn settings, err\n\t}\n\treturn settings, nil\n}", "func ValidateGetSystemVar(name string, isGlobal bool) error {\n\tsysVar := GetSysVar(name)\n\tif sysVar == nil {\n\t\treturn ErrUnknownSystemVar.GenWithStackByArgs(name)\n\t}\n\tswitch sysVar.Scope {\n\tcase ScopeGlobal:\n\t\tif !isGlobal {\n\t\t\treturn ErrIncorrectScope.GenWithStackByArgs(name, \"GLOBAL\")\n\t\t}\n\tcase ScopeSession:\n\t\tif isGlobal {\n\t\t\treturn ErrIncorrectScope.GenWithStackByArgs(name, \"SESSION\")\n\t\t}\n\t}\n\treturn nil\n}", "func (o IopingSpecVolumeVolumeSourceScaleIOOutput) System() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceScaleIO) string { return v.System }).(pulumi.StringOutput)\n}", "func (s *Systems) GetSystems(ctx context.Context, req *systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) {\n\tvar resp systemsproto.SystemsResponse\n\tsessionToken := req.SessionToken\n\tauthResp := s.IsAuthorizedRPC(sessionToken, []string{common.PrivilegeLogin}, []string{})\n\tif authResp.StatusCode != http.StatusOK {\n\t\tlog.Error(\"error while trying to authenticate session\")\n\t\tfillSystemProtoResponse(&resp, authResp)\n\t\treturn &resp, nil\n\t}\n\tvar pc = systems.PluginContact{\n\t\tContactClient: pmbhandle.ContactPlugin,\n\t\tDevicePassword: common.DecryptWithPrivateKey,\n\t\tGetPluginStatus: scommon.GetPluginStatus,\n\t}\n\tdata := pc.GetSystems(req)\n\tfillSystemProtoResponse(&resp, data)\n\treturn &resp, nil\n}", "func (o *Manager) GetSupportedFilesystems(ctx context.Context) (supportedFilesystems []string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceManager, \"SupportedFilesystems\").Store(&supportedFilesystems)\n\treturn\n}", "func GetSystemInfo(args []string) util.NativeCmdResult {\n\treturn util.NativeCmdResult{\n\t\tStdout: []byte(getSystemInfo()),\n\t\tStderr: nil,\n\t\tErr: nil,\n\t\tExitCode: util.SUCCESS_EXIT_CODE,\n\t}\n}", "func (inst *InitAuctionManagerV2) GetSystemSysvarAccount() *ag_solanago.AccountMeta {\n\treturn inst.AccountMetaSlice[8]\n}", "func (o CustomLayerOutput) SystemPackages() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *CustomLayer) pulumi.StringArrayOutput { return v.SystemPackages }).(pulumi.StringArrayOutput)\n}", "func (o FioSpecVolumeVolumeSourceScaleIOOutput) System() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceScaleIO) string { return v.System }).(pulumi.StringOutput)\n}", "func (a *Client) GetSystemProcessor(params *GetSystemProcessorParams) (*GetSystemProcessorOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSystemProcessorParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getSystemProcessor\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/Systems/{identifier}/Processors/{socket}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetSystemProcessorReader{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.(*GetSystemProcessorOK), nil\n\n}", "func (d *Device) GetSystemInfo() (info SystemInfo) {\n\turl := fmt.Sprintf(\"%s?token=%s\", d.AppServerURL, token)\n\n\tpassThroughRequest := PassThroughRequest{\n\t\tMethod: \"passthrough\",\n\t\tParams: PassThroughRequestParams{\n\t\t\tDeviceID: d.DeviceID,\n\t\t\tRequestData: `{\"system\":{\"get_sysinfo\":{}}}`,\n\t\t},\n\t}\n\n\tpayload, err := json.Marshal(passThroughRequest)\n\tlogIfErr(err)\n\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewReader(payload))\n\tlogIfErr(err)\n\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tres, err := http.DefaultClient.Do(req)\n\tlogIfErr(err)\n\n\tdefer res.Body.Close()\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tlogIfErr(err)\n\n\tresponse := PassThroughResponse{}\n\terr = json.Unmarshal(body, &response)\n\tlogIfErr(err)\n\n\tsysInfoRes := CmdResponseGetSystemInfo{}\n\terr = json.Unmarshal([]byte(response.Result.ResponseData), &sysInfoRes)\n\tlogIfErr(err)\n\n\treturn sysInfoRes.System.GetSysinfo\n}", "func (m *Fake) GetSysctl(sysctl string) (int, error) {\n\tv, found := m.Settings[sysctl]\n\tif !found {\n\t\treturn -1, os.ErrNotExist\n\t}\n\treturn v, nil\n}", "func MockOnGetSystem(ctx context.Context, mockAPI *redfishMocks.RedfishAPI,\n\tsystemID string, computerSystem redfishClient.ComputerSystem,\n\thttpResponse *http.Response, err error, times int) {\n\ttestSystemRequest := redfishClient.ApiGetSystemRequest{}\n\tcall := mockAPI.On(\"GetSystem\", ctx, systemID).Return(testSystemRequest)\n\tif times > 0 {\n\t\tcall.Times(times)\n\t}\n\tcall = mockAPI.On(\"GetSystemExecute\", testSystemRequest).Return(computerSystem, httpResponse, err)\n\tif times > 0 {\n\t\tcall.Times(times)\n\t}\n}", "func (m *Drive) SetSystem(value SystemFacetable)() {\n m.system = value\n}", "func (a *Client) ListSystems(params *ListSystemsParams) (*ListSystemsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListSystemsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"listSystems\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/Systems\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &ListSystemsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*ListSystemsOK), nil\n\n}", "func (c *Client) GetSystems() ([]*System, error) {\n\tvar systems []*System\n\n\tresult, err := c.Call(\"get_systems\", \"\", c.Token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, s := range result.([]interface{}) {\n\t\tvar system System\n\t\tdecodedResult, err := decodeCobblerItem(s, &system)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdecodedSystem := decodedResult.(*System)\n\t\tdecodedSystem.Client = *c\n\t\tsystems = append(systems, decodedSystem)\n\t}\n\n\treturn systems, nil\n}", "func (a *Client) ListSystemProcessors(params *ListSystemProcessorsParams) (*ListSystemProcessorsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListSystemProcessorsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"listSystemProcessors\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/Systems/{identifier}/Processors\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &ListSystemProcessorsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*ListSystemProcessorsOK), nil\n\n}", "func GetSystemPackages(info OS) (packages []storage.SystemPackage) {\n\tvar queries []packageQuery\n\tswitch {\n\tcase info.IsRedHat():\n\t\tqueries = redHatPackageQueries\n\t}\n\tfor _, query := range queries {\n\t\tout, err := exec.Command(query.Command[0], query.Command[1:]...).CombinedOutput()\n\t\tsystemPackage := storage.SystemPackage{\n\t\t\tName: query.Package,\n\t\t}\n\t\tif err != nil {\n\t\t\tsystemPackage.Error = trace.ConvertSystemError(err).Error()\n\t\t} else {\n\t\t\tsystemPackage.Version = strings.TrimSpace(string(out))\n\t\t}\n\t\tpackages = append(packages, systemPackage)\n\t}\n\n\treturn packages\n}", "func (c *ClientIMPL) GetRemoteSystem(ctx context.Context, id string) (resp RemoteSystem, err error) {\n\tsys := RemoteSystem{}\n\tqp := c.APIClient().QueryParamsWithFields(&sys)\n\t_, err = c.APIClient().Query(\n\t\tctx,\n\t\tRequestConfig{\n\t\t\tMethod: \"GET\",\n\t\t\tEndpoint: remoteSystemURL,\n\t\t\tID: id,\n\t\t\tQueryParams: qp,\n\t\t},\n\t\t&resp)\n\treturn resp, WrapErr(err)\n}", "func (*CgroupfsManager) IsSystemd() bool {\n\treturn false\n}", "func (o *ApplianceImageBundleAllOf) GetSystemPackages() []OnpremImagePackage {\n\tif o == nil {\n\t\tvar ret []OnpremImagePackage\n\t\treturn ret\n\t}\n\treturn o.SystemPackages\n}", "func (m *AndroidManagedStoreApp) SetIsSystemApp(value *bool)() {\n err := m.GetBackingStore().Set(\"isSystemApp\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *Systems) GetSystemsCollection(ctx context.Context, req *systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) {\n\tvar resp systemsproto.SystemsResponse\n\tsessionToken := req.SessionToken\n\tauthResp := s.IsAuthorizedRPC(sessionToken, []string{common.PrivilegeLogin}, []string{})\n\tif authResp.StatusCode != http.StatusOK {\n\t\tlog.Error(\"error while trying to authenticate session\")\n\t\tfillSystemProtoResponse(&resp, authResp)\n\t\treturn &resp, nil\n\t}\n\tdata := systems.GetSystemsCollection(req)\n\tfillSystemProtoResponse(&resp, data)\n\treturn &resp, nil\n}", "func (s *DataStore) ListSystemRestores() (map[string]*longhorn.SystemRestore, error) {\n\treturn s.listSystemRestores(labels.Everything())\n}", "func (s *SoundGroup) SystemObject() (*System, error) {\n\tvar system System\n\tres := C.FMOD_SoundGroup_GetSystemObject(s.cptr, &system.cptr)\n\treturn &system, errs[res]\n}", "func GetSystemState(config config.ServerConfig, logger *util.Logger) (system state.SystemState) {\n\tdbHost := config.GetDbHost()\n\tif config.SystemType == \"amazon_rds\" {\n\t\tsystem = rds.GetSystemState(config, logger)\n\t} else if config.SystemType == \"google_cloudsql\" {\n\t\tsystem.Info.Type = state.GoogleCloudSQLSystem\n\t} else if config.SystemType == \"azure_database\" {\n\t\tsystem.Info.Type = state.AzureDatabaseSystem\n\t} else if config.SystemType == \"heroku\" {\n\t\tsystem.Info.Type = state.HerokuSystem\n\t} else if config.SystemType == \"crunchy_bridge\" {\n\t\t// We are assuming container apps are used, which means the collector\n\t\t// runs on the database server itself and can gather local statistics\n\t\tsystem = selfhosted.GetSystemState(config, logger)\n\t\tsystem.Info.Type = state.CrunchyBridgeSystem\n\t} else if dbHost == \"\" || dbHost == \"localhost\" || dbHost == \"127.0.0.1\" || config.AlwaysCollectSystemData {\n\t\tsystem = selfhosted.GetSystemState(config, logger)\n\t}\n\n\tsystem.Info.SystemID = config.SystemID\n\tsystem.Info.SystemScope = config.SystemScope\n\n\treturn\n}", "func (i *Item) Sys() interface{} { return i.directoryEntry }", "func GetSystemRenderContext() (SysRenderContext, error) {\n\tcontext, err := EvtCreateRenderContext(0, 0, EvtRenderContextSystem)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn SysRenderContext(context), nil\n}", "func (s *Tplink) SystemInfo() (SysInfo, error) {\n\tvar (\n\t\tpayload getSysInfo\n\t\tjsonResp SysInfo\n\t)\n\n\tj, _ := json.Marshal(payload)\n\n\tdata := encrypt(string(j))\n\tresp, err := send(s.Host, data)\n\tif err != nil {\n\t\treturn jsonResp, err\n\t}\n\n\tif err := json.Unmarshal([]byte(decrypt(resp)), &jsonResp); err != nil {\n\t\treturn jsonResp, err\n\t}\n\treturn jsonResp, nil\n}", "func (o *os) GetSystemTimeSecs() gdnative.Int {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetSystemTimeSecs()\")\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_system_time_secs\")\n\n\t// Call the parent method.\n\t// int\n\tretPtr := gdnative.NewEmptyInt()\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.NewIntFromPointer(retPtr)\n\treturn ret\n}", "func (o *os) GetSystemTimeMsecs() gdnative.Int {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetSystemTimeMsecs()\")\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_system_time_msecs\")\n\n\t// Call the parent method.\n\t// int\n\tretPtr := gdnative.NewEmptyInt()\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.NewIntFromPointer(retPtr)\n\treturn ret\n}", "func GetHostSys() string {\n\thostSys := os.Getenv(\"HOST_SYS\")\n\tif hostSys == \"\" {\n\t\thostSys = \"/sys\"\n\t}\n\treturn hostSys\n}", "func GetSysCPUCount() int {\n\treturn runtime.NumCPU()\n}", "func (me *XsdGoPkgHasElems_System) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_System; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfor _, x := range me.Systems {\n\t\t\tif err = x.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func GetSystemRequestRPC(req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) {\n\tconn, err := services.ODIMService.Client(services.Systems)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create client connection: %v\", err)\n\t}\n\tdefer conn.Close()\n\tasService := systemsproto.NewSystemsClient(conn)\n\tresp, err := asService.GetSystems(context.TODO(), &req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error: RPC error: %v\", err)\n\t}\n\treturn resp, nil\n}", "func SystemConfig() (*Config, error) {\n\tcfg := C.al_get_system_config()\n\tif cfg == nil {\n\t\treturn nil, errors.New(\"no system config found\")\n\t}\n\treturn (*Config)(cfg), nil\n}", "func (d *DSP) SystemObject() (*System, error) {\n\tvar system System\n\tres := C.FMOD_DSP_GetSystemObject(d.cptr, &system.cptr)\n\treturn &system, errs[res]\n}", "func (b *OGame) GetNbSystems() int64 {\n\treturn b.serverData.Systems\n}", "func (r *CheckConfigurationRead) constraintSystem(cnf *proto.CheckConfig) error {\n\tvar (\n\t\tconfigID, property, value string\n\t\trows *sql.Rows\n\t\terr error\n\t)\n\n\tif rows, err = r.stmtShowConstraintSystem.Query(\n\t\tcnf.ID,\n\t); err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tif err = rows.Scan(\n\t\t\t&configID,\n\t\t\t&property,\n\t\t\t&value,\n\t\t); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tconstraint := proto.CheckConfigConstraint{\n\t\t\tConstraintType: `system`,\n\t\t\tSystem: &proto.PropertySystem{\n\t\t\t\tName: property,\n\t\t\t\tValue: value,\n\t\t\t},\n\t\t}\n\t\tcnf.Constraints = append(cnf.Constraints, constraint)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ChosenSystem() System {\n\treturn system\n}", "func GetSystemRLimit() (uint64, error) {\n\treturn math.MaxInt32, nil\n}", "func (cl *APIClient) UseLIVESystem() *APIClient {\n\tcl.socketConfig.SetSystemEntity(\"54cd\")\n\treturn cl\n}", "func TestGetSysConfig(t *testing.T) {\n\n\tif _, err := Get(programName, confName); err != nil {\n\t\tt.Fatal(\"Got error when system config exists:\", err)\n\t}\n}", "func TestGetDrvCfgSystems(t *testing.T) {\n\tgoscaleio.SDCDevice = goscaleio.IOCTLDevice\n\tsystems, err := goscaleio.DrvCfgQuerySystems()\n\n\t// The response depends on the installation state of the SDC\n\tif goscaleio.DrvCfgIsSDCInstalled() {\n\t\t// SDC is installed, should get at least one ConfiguredSystem\n\t\tassert.NotEmpty(t, systems)\n\t\tassert.Nil(t, err)\n\t\tbFoundSystem := false\n\t\tfor _, s := range *systems {\n\t\t\tassert.NotEqual(t, \"\", s.SystemID)\n\t\t\tassert.NotEqual(t, \"\", s.SdcID)\n\t\t\tif s.SystemID == os.Getenv(\"GOSCALEIO_SYSTEMID\") {\n\t\t\t\tbFoundSystem = true\n\t\t\t}\n\t\t}\n\t\tassert.Equal(t, true, bFoundSystem, \"Unable to find correct MDM system of %s\", os.Getenv(\"GOSCALEIO_SYSTEMID\"))\n\t\tassert.Equal(t, os.Getenv(\"GOSCALEIO_NUMBER_SYSTEMS\"), fmt.Sprintf(\"%d\", len(*systems)))\n\t} else {\n\t\t// SDC is not installed, should get no ConfiguredSystems and an error\n\t\tassert.Empty(t, systems)\n\t\tassert.NotNil(t, err)\n\t\tt.Skip(\"PowerFlex SDC is not installed. Cannot validate DrvCfg functionality\")\n\t}\n}", "func SystemStore(name string) (*CertStore, error) {\n\tcName := C.CString(name)\n\tdefer C.free(unsafe.Pointer(cName))\n\n\thStore := C.openStoreSystem(C.HCRYPTPROV(0), (*C.CHAR)(cName))\n\tif hStore == C.HCERTSTORE(nil) {\n\t\treturn nil, getErr(\"Error getting system cert store\")\n\t}\n\treturn &CertStore{hStore: hStore}, nil\n}", "func (r *SysNet) GetSysNet(rw http.ResponseWriter) error {\n\tpath, err := r.getPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tline, err := share.ReadOneLineFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts := SysNet{\n\t\tPath: r.Path,\n\t\tProperty: r.Property,\n\t\tValue: line,\n\t\tLink: r.Link,\n\t}\n\n\treturn share.JSONResponse(s, rw)\n}", "func (i *Info) GetSystemInformation() (*SystemInformation, error) {\n\tbt := i.GetTablesByType(TableTypeSystemInformation)\n\tif len(bt) == 0 {\n\t\treturn nil, ErrTableNotFound\n\t}\n\t// There can only be one of these.\n\treturn NewSystemInformation(bt[0])\n}", "func (conf *Configuration) GetHostSystem(name string) (string, error) {\n\tctx := context.NewContext(conf.Timeout)\n\tdefer ctx.Cancel()\n\n\treturn conf.GetHostSystemWithContext(ctx, name)\n}", "func (u User) IsSystem() bool {\n\treturn u.HasRole(SystemRole)\n}", "func (api *API) GetSysConfig(c *common.Context) (interface{}, error) {\n\ttp, key := c.Param(\"type\"), c.Param(\"key\")\n\treturn api.sysConfigService.GetSysConfig(tp, key)\n}", "func getSystemTimes(idleTime, kernelTime, userTime *FileTime) bool {\n\tret, _, _ := procGetSystemTimes.Call(\n\t\tuintptr(unsafe.Pointer(idleTime)),\n\t\tuintptr(unsafe.Pointer(kernelTime)),\n\t\tuintptr(unsafe.Pointer(userTime)))\n\n\treturn ret != 0\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 (f *FileInfo) Sys() interface{} {\n\treturn f.sys\n}", "func (f *IBMPISystemPoolClient) GetSystemPools() (models.SystemPools, error) {\n\tparams := p_cloud_system_pools.NewPcloudSystempoolsGetParams().\n\t\tWithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut).\n\t\tWithCloudInstanceID(f.cloudInstanceID)\n\tresp, err := f.session.Power.PCloudSystemPools.PcloudSystempoolsGet(params, f.session.AuthInfo(f.cloudInstanceID))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(errors.GetSystemPoolsOperationFailed, f.cloudInstanceID, err)\n\t}\n\tif resp == nil || resp.Payload == nil {\n\t\treturn nil, fmt.Errorf(\"failed to perform Get System Pools Operation for cloud instance id %s\", f.cloudInstanceID)\n\t}\n\treturn resp.Payload, nil\n}", "func (a *HyperflexApiService) GetHyperflexSysConfigPolicyList(ctx context.Context) ApiGetHyperflexSysConfigPolicyListRequest {\n\treturn ApiGetHyperflexSysConfigPolicyListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (w *PropertyWrite) removeSystem(q *msg.Request, mr *msg.Result) {\n\tvar (\n\t\tres sql.Result\n\t\terr error\n\t)\n\n\tif res, err = w.stmtRemoveSystem.Exec(\n\t\tq.Property.System.Name,\n\t); err != nil {\n\t\tmr.ServerError(err, q.Section)\n\t\treturn\n\t}\n\tif mr.RowCnt(res.RowsAffected()) {\n\t\tmr.Property = append(mr.Property, q.Property)\n\t}\n}", "func (o PhpAppLayerOutput) SystemPackages() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *PhpAppLayer) pulumi.StringArrayOutput { return v.SystemPackages }).(pulumi.StringArrayOutput)\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}" ]
[ "0.6552798", "0.6516161", "0.64446497", "0.5954586", "0.59397334", "0.5910173", "0.5894141", "0.58871907", "0.5834781", "0.5828252", "0.5756128", "0.56791264", "0.5651165", "0.5645735", "0.5644327", "0.5579365", "0.5558257", "0.55290455", "0.5488099", "0.5483745", "0.54779154", "0.54413015", "0.54180455", "0.53987104", "0.53856695", "0.5381043", "0.537117", "0.5367533", "0.5342736", "0.5324748", "0.53139275", "0.5254713", "0.5234105", "0.5231616", "0.5217184", "0.52133", "0.52099603", "0.51954114", "0.5195112", "0.51780206", "0.5157344", "0.51293224", "0.51188135", "0.51119864", "0.51050687", "0.509743", "0.5093461", "0.5088442", "0.50816154", "0.5074069", "0.50705403", "0.50604016", "0.5045197", "0.5043718", "0.50431305", "0.50412065", "0.5009416", "0.49901515", "0.49814385", "0.49777776", "0.49769843", "0.4970744", "0.49620628", "0.49618545", "0.49611607", "0.49572098", "0.49570042", "0.49496153", "0.49489066", "0.49477622", "0.4945295", "0.49217474", "0.49143156", "0.49133608", "0.49075902", "0.48995703", "0.48962438", "0.48860472", "0.48850396", "0.4884086", "0.48835096", "0.48736152", "0.48617664", "0.48547426", "0.48531258", "0.48525503", "0.48355544", "0.4833873", "0.48303357", "0.48281795", "0.48271003", "0.48206562", "0.4818586", "0.48133254", "0.48099673", "0.4807259", "0.480113", "0.47987574", "0.47829124", "0.47809148" ]
0.6885303
0
Serialize serializes information the current object
func (m *List) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) { err := m.BaseItem.Serialize(writer) if err != nil { return err } if m.GetColumns() != nil { cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetColumns()) err = writer.WriteCollectionOfObjectValues("columns", cast) if err != nil { return err } } if m.GetContentTypes() != nil { cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContentTypes()) err = writer.WriteCollectionOfObjectValues("contentTypes", cast) if err != nil { return err } } { err = writer.WriteStringValue("displayName", m.GetDisplayName()) if err != nil { return err } } { err = writer.WriteObjectValue("drive", m.GetDrive()) if err != nil { return err } } if m.GetItems() != nil { cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetItems()) err = writer.WriteCollectionOfObjectValues("items", cast) if err != nil { return err } } { err = writer.WriteObjectValue("list", m.GetList()) if err != nil { return err } } if m.GetOperations() != nil { cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations()) err = writer.WriteCollectionOfObjectValues("operations", cast) if err != nil { return err } } { err = writer.WriteObjectValue("sharepointIds", m.GetSharepointIds()) if err != nil { return err } } if m.GetSubscriptions() != nil { cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSubscriptions()) err = writer.WriteCollectionOfObjectValues("subscriptions", cast) if err != nil { return err } } { err = writer.WriteObjectValue("system", m.GetSystem()) if err != nil { return err } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p Registered) Serialize() common.JSON {\n\treturn common.JSON{\n\t\t\"ID\": p.ID,\n\t\t\"Date\": p.Date,\n\t\t\"Riders\": p.Riders,\n\t\t\"RidersID\": p.RidersID,\n\t\t\"Events\": p.Events,\n\t\t\"EventsID\": p.EventsID,\n\t\t\"StartNumber\": p.StartNumber,\n\t}\n}", "func (m *IncomingContext) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"observedParticipantId\", m.GetObservedParticipantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"onBehalfOf\", m.GetOnBehalfOf())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"sourceParticipantId\", m.GetSourceParticipantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"transferor\", m.GetTransferor())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *LabelActionBase) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"name\", m.GetName())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (b *Uniform) Serialize() interface{} {\n\tdata := make(map[string]interface{})\n\tdata[\"strategy\"] = \"uniform selection\"\n\tdata[\"counts\"] = b.counts\n\tdata[\"values\"] = b.values\n\treturn data\n}", "func (m *ParentLabelDetails) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"color\", m.GetColor())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"id\", m.GetId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteBoolValue(\"isActive\", m.GetIsActive())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"name\", m.GetName())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"parent\", m.GetParent())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteInt32Value(\"sensitivity\", m.GetSensitivity())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"tooltip\", m.GetTooltip())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func Serialize(o interface{}) ([]byte, error) {\n\tautil.TODO(\"CBOR-serialization\")\n\treturn nil, nil\n}", "func (s *State) Serialize() []byte {\n\treturn s.serializer.Serialize(s.structure())\n}", "func (r *SbProxy) Serialize() rotator.Object {\n\tr.RLock()\n\tdefer r.RUnlock()\n\treturn r.serialize()\n}", "func (self *ResTransaction)Serialize()[]byte{\n data, err := json.Marshal(self)\n if err != nil {\n fmt.Println(err)\n }\n return data\n}", "func (this *Transaction) Serialize() []byte {\n\tvar encoded bytes.Buffer\n\n\tenc := gob.NewEncoder(&encoded)\n\terr := enc.Encode(this)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn encoded.Bytes()\n}", "func (e *SetTempoEvent) Serialize() []byte {\n\tbs := []byte{}\n\tbs = append(bs, constant.Meta, constant.SetTempo)\n\tbs = append(bs, 0x03)\n\tbs = append(bs, byte(e.tempo>>16))\n\tbs = append(bs, byte((0xff00&e.tempo)>>8))\n\tbs = append(bs, byte(e.tempo&0xff))\n\n\treturn bs\n}", "func (b *AnnealingEpsilonGreedy) Serialize() interface{} {\n\tdata := make(map[string]interface{})\n\tdata[\"strategy\"] = \"annealing epsilon greedy\"\n\tdata[\"epsilon\"] = b.Epsilon()\n\tdata[\"counts\"] = b.counts\n\tdata[\"values\"] = b.values\n\treturn data\n}", "func (e *Entity) Serialize(w io.Writer) error {\n\terr := e.PrimaryKey.Serialize(w)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, ident := range e.Identities {\n\t\terr = ident.UserId.Serialize(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = ident.SelfSignature.Serialize(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, sig := range ident.Signatures {\n\t\t\terr = sig.Serialize(w)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tfor _, subkey := range e.Subkeys {\n\t\terr = subkey.PublicKey.Serialize(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = subkey.Sig.Serialize(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (f *feature) Serialize() string {\n\tstream, err := json.Marshal(f)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn string(stream)\n}", "func (m *BookingNamedEntity) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (b *EpsilonGreedy) Serialize() interface{} {\n\tdata := make(map[string]interface{})\n\tdata[\"strategy\"] = \"epsilon greedy\"\n\tdata[\"epsilon\"] = b.Epsilon\n\tdata[\"counts\"] = b.counts\n\tdata[\"values\"] = b.values\n\treturn data\n}", "func (m *IdentityProviderBase) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (n Name) Serialize() []byte {\n\tnameData := make([]byte, 0, len(n)+5)\n\tfor _, label := range n.getLabels() {\n\t\tnameData = append(nameData, encodeLabel(label)...)\n\t}\n\t//terminate labels\n\tnameData = append(nameData, byte(0))\n\n\treturn nameData\n}", "func (rs *Restake) Serialize() []byte {\n\treturn byteutil.Must(proto.Marshal(rs.Proto()))\n}", "func (g *Generic) Serialize() ([]byte, error) {\n\tlog.Println(\"DEPRECATED: MarshalBinary instead\")\n\treturn g.MarshalBinary()\n}", "func (JSONPresenter) Serialize(object interface{}) []byte {\n\tserial, err := json.Marshal(object)\n\n\tif err != nil {\n\t\tlog.Printf(\"failed to serialize: \\\"%s\\\"\", err)\n\t}\n\n\treturn serial\n}", "func (m *NamedLocation) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"modifiedDateTime\", m.GetModifiedDateTime())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (b *BundleIdent) Serialize(buffer []byte) []byte {\n\tbuffer = serializeString(b.App, buffer)\n\tbuffer = b.User.Serialize(buffer)\n\tbuffer = serializeString(b.Name, buffer)\n\tbuffer = serializeString(b.Incarnation, buffer)\n\treturn buffer\n}", "func (m *ExternalConnection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"configuration\", m.GetConfiguration())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n if m.GetGroups() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetGroups())\n err = writer.WriteCollectionOfObjectValues(\"groups\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetItems() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetItems())\n err = writer.WriteCollectionOfObjectValues(\"items\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"name\", m.GetName())\n if err != nil {\n return err\n }\n }\n if m.GetOperations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations())\n err = writer.WriteCollectionOfObjectValues(\"operations\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"schema\", m.GetSchema())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *EventMessageDetail) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (out *TransactionOutput) Serialize(bw *io.BinaryWriter) {\n\tbw.WriteLE(out.AssetId)\n\tbw.WriteLE(out.Value)\n\tbw.WriteLE(out.ScriptHash)\n}", "func (in *Store) Serialize() ([]byte, error) {\n\treturn proto.Marshal(in.ToProto())\n}", "func (ds *DepositToStake) Serialize() []byte {\n\treturn byteutil.Must(proto.Marshal(ds.Proto()))\n}", "func Serialize(v interface{}) ([]byte, error) {\n\tbuf := bytes.NewBuffer(make([]byte, 0))\n\tif err := gob.NewEncoder(buf).Encode(v); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (writer *Writer) Serialize(v interface{}) {\n\tif v == nil {\n\t\twriter.WriteNil()\n\t} else {\n\t\tv := reflect.ValueOf(v)\n\t\tvalueEncoders[v.Kind()](writer, v)\n\t}\n}", "func (sh *ServerPropertiesHandle) Serialized() string {\n\tsh.Serialize(sh.serverProperties)\n\treturn sh.String()\n}", "func (sigInfo *TxSignature) Serialize() []byte {\n\tecSig := sigInfo.Signature.Serialize()\n\tecSig = append(ecSig, byte(int(sigInfo.HashType)))\n\treturn ecSig\n}", "func (o *A_2) Serialize(\r\n\tbyteOrder binary.ByteOrder,\r\n\tstream io.Writer,\r\n) error {\r\n\t//TODO: implement\r\n\t/*\r\n\t\tif err := o.cursor.Serialize(byteOrder, stream); err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\t\tif err := o.limit.Serialize(byteOrder, stream); err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t*/\r\n\treturn fmt.Errorf(\"not yet implemented\")\r\n}", "func (f *PushNotice) Serialize(buffer []byte) []byte {\n\tbuffer[0] = byte(f.Flags)\n\tcopy(buffer[1:], f.Data)\n\treturn buffer\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tthis.s(root)\n\treturn \"[\" + strings.Join(this.data, \",\") + \"]\"\n}", "func (acc *Account) Serialize() ([]byte, error) {\n\treturn json.Marshal(acc)\n}", "func (m *saMap) serialize() ([]byte, error) {\n\tm.RLock()\n\tdefer m.RUnlock()\n\treturn json.Marshal(m.ma)\n}", "func (m *ServicePlanInfo) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"appliesTo\", m.GetAppliesTo())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"provisioningStatus\", m.GetProvisioningStatus())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"servicePlanId\", m.GetServicePlanId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"servicePlanName\", m.GetServicePlanName())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (f *CloseNotice) Serialize(buffer []byte) []byte {\n\treturn buffer\n}", "func Serialize(data interface{}) string {\n\tval, _ := json.Marshal(data)\n\treturn string(val);\n}", "func (l *Layer) Serialize() ([]byte, error) {\n\treturn json.Marshal(l)\n}", "func (n *Norm) Serialize() ([]byte, error) {\n\tweightsData, err := json.Marshal(n.Weights)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmagsData, err := json.Marshal(n.Mags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn serializer.SerializeAny(\n\t\tserializer.Bytes(weightsData),\n\t\tserializer.Bytes(magsData),\n\t\tn.Creator,\n\t)\n}", "func (team *Team) Serialize() common.JSON {\n\treturn common.JSON{\n\t\t\"id\": team.ID,\n\t\t\"name\": team.Name,\n\t\t\"description\": team.Description,\n\t\t\"level\": team.Level,\n\t\t\"code\": team.Code,\n\t\t\"city_id\": team.CityID,\n\t\t\"ward_id\": team.WardID,\n\t\t\"district_id\": team.DistrictID,\n\t\t\"since\": team.Since,\n\t\t\"address\": team.Address,\n\t\t\"web\": team.Web,\n\t\t\"facebook_id\": team.FacebookID,\n\t\t\"cover\": team.Cover,\n\t\t\"lng\": team.Lng,\n\t\t\"lat\": team.Lat,\n\t\t\"user\": team.User.Serialize(),\n\t}\n}", "func (s *StoredChannel) serialize() ([]byte, error) {\n\tbuffer := &bytes.Buffer{}\n\tencoder := gob.NewEncoder(buffer)\n\terr := encoder.Encode(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buffer.Bytes(), nil\n}", "func (m *ExternalActivity) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"performedBy\", m.GetPerformedBy())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"startDateTime\", m.GetStartDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetTypeEscaped() != nil {\n cast := (*m.GetTypeEscaped()).String()\n err = writer.WriteStringValue(\"type\", &cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *UserSimulationEventInfo) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"browser\", m.GetBrowser())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteTimeValue(\"eventDateTime\", m.GetEventDateTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"eventName\", m.GetEventName())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"ipAddress\", m.GetIpAddress())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"osPlatformDeviceDetails\", m.GetOsPlatformDeviceDetails())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *OnlineMeetingInfo) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"conferenceId\", m.GetConferenceId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"joinUrl\", m.GetJoinUrl())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n if m.GetPhones() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetPhones()))\n for i, v := range m.GetPhones() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err := writer.WriteCollectionOfObjectValues(\"phones\", cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"quickDial\", m.GetQuickDial())\n if err != nil {\n return err\n }\n }\n if m.GetTollFreeNumbers() != nil {\n err := writer.WriteCollectionOfStringValues(\"tollFreeNumbers\", m.GetTollFreeNumbers())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"tollNumber\", m.GetTollNumber())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *PrintConnector) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"appVersion\", m.GetAppVersion())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"fullyQualifiedDomainName\", m.GetFullyQualifiedDomainName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"location\", m.GetLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"operatingSystem\", m.GetOperatingSystem())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"registeredDateTime\", m.GetRegisteredDateTime())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (self X) Serialise(enc *gob.Encoder) error {\n\treturn enc.Encode(self)\n}", "func (d *DeviceInfo) Serialize() (string, error) {\n\tb, err := json.Marshal(d)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\treturn dfsSerial(root, \"\")\n}", "func (c *CheckboxBase) Serialize(e page.Encoder) {\n\tc.ControlBase.Serialize(e)\n\n\tif err := e.Encode(c.checked); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := e.Encode(c.LabelMode); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := e.Encode(c.labelAttributes); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (p statisticsActionProps) serialize() actionlog.Meta {\n\tvar (\n\t\tm = make(actionlog.Meta)\n\t)\n\n\treturn m\n}", "func (st Account) Serialize() ([]byte, error) {\n\treturn proto.Marshal(st.ToProto())\n}", "func (st Account) Serialize() ([]byte, error) {\n\treturn proto.Marshal(st.ToProto())\n}", "func Serialize(input interface{}) (msg []byte, err error) {\n\tbuffer, err := json.Marshal(input)\n\treturn buffer, err\n\n\t// TODO: Do we really need wire here?\n\t/*\n\t\tvar count int\n\n\t\tbuffer := new(bytes.Buffer)\n\n\t\twire.WriteBinary(input, buffer, &count, &err)\n\n\t\treturn buffer.Bytes(), err\n\t*/\n}", "func (m *KeyValue) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"key\", m.GetKey())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"value\", m.GetValue())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *User) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.DirectoryObject.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"aboutMe\", m.GetAboutMe())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"accountEnabled\", m.GetAccountEnabled())\n if err != nil {\n return err\n }\n }\n if m.GetActivities() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetActivities())\n err = writer.WriteCollectionOfObjectValues(\"activities\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"ageGroup\", m.GetAgeGroup())\n if err != nil {\n return err\n }\n }\n if m.GetAgreementAcceptances() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAgreementAcceptances())\n err = writer.WriteCollectionOfObjectValues(\"agreementAcceptances\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAppRoleAssignments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAppRoleAssignments())\n err = writer.WriteCollectionOfObjectValues(\"appRoleAssignments\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAssignedLicenses() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAssignedLicenses())\n err = writer.WriteCollectionOfObjectValues(\"assignedLicenses\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAssignedPlans() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAssignedPlans())\n err = writer.WriteCollectionOfObjectValues(\"assignedPlans\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"authentication\", m.GetAuthentication())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"authorizationInfo\", m.GetAuthorizationInfo())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"birthday\", m.GetBirthday())\n if err != nil {\n return err\n }\n }\n if m.GetBusinessPhones() != nil {\n err = writer.WriteCollectionOfStringValues(\"businessPhones\", m.GetBusinessPhones())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"calendar\", m.GetCalendar())\n if err != nil {\n return err\n }\n }\n if m.GetCalendarGroups() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCalendarGroups())\n err = writer.WriteCollectionOfObjectValues(\"calendarGroups\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCalendars() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCalendars())\n err = writer.WriteCollectionOfObjectValues(\"calendars\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCalendarView() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCalendarView())\n err = writer.WriteCollectionOfObjectValues(\"calendarView\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetChats() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetChats())\n err = writer.WriteCollectionOfObjectValues(\"chats\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"city\", m.GetCity())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"companyName\", m.GetCompanyName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"consentProvidedForMinor\", m.GetConsentProvidedForMinor())\n if err != nil {\n return err\n }\n }\n if m.GetContactFolders() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContactFolders())\n err = writer.WriteCollectionOfObjectValues(\"contactFolders\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetContacts() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContacts())\n err = writer.WriteCollectionOfObjectValues(\"contacts\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"country\", m.GetCountry())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetCreatedObjects() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCreatedObjects())\n err = writer.WriteCollectionOfObjectValues(\"createdObjects\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"creationType\", m.GetCreationType())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"department\", m.GetDepartment())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"deviceEnrollmentLimit\", m.GetDeviceEnrollmentLimit())\n if err != nil {\n return err\n }\n }\n if m.GetDeviceManagementTroubleshootingEvents() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDeviceManagementTroubleshootingEvents())\n err = writer.WriteCollectionOfObjectValues(\"deviceManagementTroubleshootingEvents\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDirectReports() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDirectReports())\n err = writer.WriteCollectionOfObjectValues(\"directReports\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"drive\", m.GetDrive())\n if err != nil {\n return err\n }\n }\n if m.GetDrives() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDrives())\n err = writer.WriteCollectionOfObjectValues(\"drives\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"employeeHireDate\", m.GetEmployeeHireDate())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"employeeId\", m.GetEmployeeId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"employeeOrgData\", m.GetEmployeeOrgData())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"employeeType\", m.GetEmployeeType())\n if err != nil {\n return err\n }\n }\n if m.GetEvents() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetEvents())\n err = writer.WriteCollectionOfObjectValues(\"events\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetExtensions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetExtensions())\n err = writer.WriteCollectionOfObjectValues(\"extensions\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"externalUserState\", m.GetExternalUserState())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"externalUserStateChangeDateTime\", m.GetExternalUserStateChangeDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"faxNumber\", m.GetFaxNumber())\n if err != nil {\n return err\n }\n }\n if m.GetFollowedSites() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetFollowedSites())\n err = writer.WriteCollectionOfObjectValues(\"followedSites\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"givenName\", m.GetGivenName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"hireDate\", m.GetHireDate())\n if err != nil {\n return err\n }\n }\n if m.GetIdentities() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetIdentities())\n err = writer.WriteCollectionOfObjectValues(\"identities\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetImAddresses() != nil {\n err = writer.WriteCollectionOfStringValues(\"imAddresses\", m.GetImAddresses())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"inferenceClassification\", m.GetInferenceClassification())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"insights\", m.GetInsights())\n if err != nil {\n return err\n }\n }\n if m.GetInterests() != nil {\n err = writer.WriteCollectionOfStringValues(\"interests\", m.GetInterests())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isResourceAccount\", m.GetIsResourceAccount())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"jobTitle\", m.GetJobTitle())\n if err != nil {\n return err\n }\n }\n if m.GetJoinedTeams() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetJoinedTeams())\n err = writer.WriteCollectionOfObjectValues(\"joinedTeams\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastPasswordChangeDateTime\", m.GetLastPasswordChangeDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"legalAgeGroupClassification\", m.GetLegalAgeGroupClassification())\n if err != nil {\n return err\n }\n }\n if m.GetLicenseAssignmentStates() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetLicenseAssignmentStates())\n err = writer.WriteCollectionOfObjectValues(\"licenseAssignmentStates\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetLicenseDetails() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetLicenseDetails())\n err = writer.WriteCollectionOfObjectValues(\"licenseDetails\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mail\", m.GetMail())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"mailboxSettings\", m.GetMailboxSettings())\n if err != nil {\n return err\n }\n }\n if m.GetMailFolders() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMailFolders())\n err = writer.WriteCollectionOfObjectValues(\"mailFolders\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mailNickname\", m.GetMailNickname())\n if err != nil {\n return err\n }\n }\n if m.GetManagedAppRegistrations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetManagedAppRegistrations())\n err = writer.WriteCollectionOfObjectValues(\"managedAppRegistrations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetManagedDevices() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetManagedDevices())\n err = writer.WriteCollectionOfObjectValues(\"managedDevices\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"manager\", m.GetManager())\n if err != nil {\n return err\n }\n }\n if m.GetMemberOf() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMemberOf())\n err = writer.WriteCollectionOfObjectValues(\"memberOf\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetMessages() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMessages())\n err = writer.WriteCollectionOfObjectValues(\"messages\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mobilePhone\", m.GetMobilePhone())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mySite\", m.GetMySite())\n if err != nil {\n return err\n }\n }\n if m.GetOauth2PermissionGrants() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOauth2PermissionGrants())\n err = writer.WriteCollectionOfObjectValues(\"oauth2PermissionGrants\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"officeLocation\", m.GetOfficeLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"onenote\", m.GetOnenote())\n if err != nil {\n return err\n }\n }\n if m.GetOnlineMeetings() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOnlineMeetings())\n err = writer.WriteCollectionOfObjectValues(\"onlineMeetings\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesDistinguishedName\", m.GetOnPremisesDistinguishedName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesDomainName\", m.GetOnPremisesDomainName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"onPremisesExtensionAttributes\", m.GetOnPremisesExtensionAttributes())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesImmutableId\", m.GetOnPremisesImmutableId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"onPremisesLastSyncDateTime\", m.GetOnPremisesLastSyncDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetOnPremisesProvisioningErrors() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOnPremisesProvisioningErrors())\n err = writer.WriteCollectionOfObjectValues(\"onPremisesProvisioningErrors\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesSamAccountName\", m.GetOnPremisesSamAccountName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesSecurityIdentifier\", m.GetOnPremisesSecurityIdentifier())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"onPremisesSyncEnabled\", m.GetOnPremisesSyncEnabled())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesUserPrincipalName\", m.GetOnPremisesUserPrincipalName())\n if err != nil {\n return err\n }\n }\n if m.GetOtherMails() != nil {\n err = writer.WriteCollectionOfStringValues(\"otherMails\", m.GetOtherMails())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"outlook\", m.GetOutlook())\n if err != nil {\n return err\n }\n }\n if m.GetOwnedDevices() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwnedDevices())\n err = writer.WriteCollectionOfObjectValues(\"ownedDevices\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOwnedObjects() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwnedObjects())\n err = writer.WriteCollectionOfObjectValues(\"ownedObjects\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"passwordPolicies\", m.GetPasswordPolicies())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"passwordProfile\", m.GetPasswordProfile())\n if err != nil {\n return err\n }\n }\n if m.GetPastProjects() != nil {\n err = writer.WriteCollectionOfStringValues(\"pastProjects\", m.GetPastProjects())\n if err != nil {\n return err\n }\n }\n if m.GetPeople() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPeople())\n err = writer.WriteCollectionOfObjectValues(\"people\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"photo\", m.GetPhoto())\n if err != nil {\n return err\n }\n }\n if m.GetPhotos() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPhotos())\n err = writer.WriteCollectionOfObjectValues(\"photos\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"planner\", m.GetPlanner())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"postalCode\", m.GetPostalCode())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"preferredDataLocation\", m.GetPreferredDataLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"preferredLanguage\", m.GetPreferredLanguage())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"preferredName\", m.GetPreferredName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"presence\", m.GetPresence())\n if err != nil {\n return err\n }\n }\n if m.GetProvisionedPlans() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetProvisionedPlans())\n err = writer.WriteCollectionOfObjectValues(\"provisionedPlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetProxyAddresses() != nil {\n err = writer.WriteCollectionOfStringValues(\"proxyAddresses\", m.GetProxyAddresses())\n if err != nil {\n return err\n }\n }\n if m.GetRegisteredDevices() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetRegisteredDevices())\n err = writer.WriteCollectionOfObjectValues(\"registeredDevices\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetResponsibilities() != nil {\n err = writer.WriteCollectionOfStringValues(\"responsibilities\", m.GetResponsibilities())\n if err != nil {\n return err\n }\n }\n if m.GetSchools() != nil {\n err = writer.WriteCollectionOfStringValues(\"schools\", m.GetSchools())\n if err != nil {\n return err\n }\n }\n if m.GetScopedRoleMemberOf() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetScopedRoleMemberOf())\n err = writer.WriteCollectionOfObjectValues(\"scopedRoleMemberOf\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"securityIdentifier\", m.GetSecurityIdentifier())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"settings\", m.GetSettings())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"showInAddressList\", m.GetShowInAddressList())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"signInSessionsValidFromDateTime\", m.GetSignInSessionsValidFromDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetSkills() != nil {\n err = writer.WriteCollectionOfStringValues(\"skills\", m.GetSkills())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"state\", m.GetState())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"streetAddress\", m.GetStreetAddress())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"surname\", m.GetSurname())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"teamwork\", m.GetTeamwork())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"todo\", m.GetTodo())\n if err != nil {\n return err\n }\n }\n if m.GetTransitiveMemberOf() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTransitiveMemberOf())\n err = writer.WriteCollectionOfObjectValues(\"transitiveMemberOf\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"usageLocation\", m.GetUsageLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userPrincipalName\", m.GetUserPrincipalName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userType\", m.GetUserType())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (mu *MuHash) Serialize() *SerializedMuHash {\n\tvar out SerializedMuHash\n\tmu.serializeInner(&out)\n\treturn &out\n}", "func (m *SolutionsRoot) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetBusinessScenarios() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBusinessScenarios()))\n for i, v := range m.GetBusinessScenarios() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err := writer.WriteCollectionOfObjectValues(\"businessScenarios\", cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"virtualEvents\", m.GetVirtualEvents())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (bo *BlockObject) toJSON(t *thread) string {\n\treturn bo.toString()\n}", "func (m *Vulnerability) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteBoolValue(\"activeExploitsObserved\", m.GetActiveExploitsObserved())\n if err != nil {\n return err\n }\n }\n if m.GetArticles() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetArticles()))\n for i, v := range m.GetArticles() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"articles\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCommonWeaknessEnumerationIds() != nil {\n err = writer.WriteCollectionOfStringValues(\"commonWeaknessEnumerationIds\", m.GetCommonWeaknessEnumerationIds())\n if err != nil {\n return err\n }\n }\n if m.GetComponents() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetComponents()))\n for i, v := range m.GetComponents() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"components\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"cvss2Summary\", m.GetCvss2Summary())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"cvss3Summary\", m.GetCvss3Summary())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n if m.GetExploits() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetExploits()))\n for i, v := range m.GetExploits() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"exploits\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"exploitsAvailable\", m.GetExploitsAvailable())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hasChatter\", m.GetHasChatter())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastModifiedDateTime\", m.GetLastModifiedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"priorityScore\", m.GetPriorityScore())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"publishedDateTime\", m.GetPublishedDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetReferences() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetReferences()))\n for i, v := range m.GetReferences() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"references\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"remediation\", m.GetRemediation())\n if err != nil {\n return err\n }\n }\n if m.GetSeverity() != nil {\n cast := (*m.GetSeverity()).String()\n err = writer.WriteStringValue(\"severity\", &cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *AuthenticationContext) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetDetail() != nil {\n cast := (*m.GetDetail()).String()\n err := writer.WriteStringValue(\"detail\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"id\", m.GetId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *DiscoveredSensitiveType) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetClassificationAttributes() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetClassificationAttributes()))\n for i, v := range m.GetClassificationAttributes() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err := writer.WriteCollectionOfObjectValues(\"classificationAttributes\", cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteInt32Value(\"confidence\", m.GetConfidence())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteInt32Value(\"count\", m.GetCount())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteUUIDValue(\"id\", m.GetId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (e *RegisterRequest) Serialize() (string, error) {\n\tb, err := json.Marshal(e)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}", "func (m *Set) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetChildren() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetChildren()))\n for i, v := range m.GetChildren() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"children\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n if m.GetLocalizedNames() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetLocalizedNames()))\n for i, v := range m.GetLocalizedNames() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"localizedNames\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"parentGroup\", m.GetParentGroup())\n if err != nil {\n return err\n }\n }\n if m.GetProperties() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetProperties()))\n for i, v := range m.GetProperties() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"properties\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetRelations() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetRelations()))\n for i, v := range m.GetRelations() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"relations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTerms() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTerms()))\n for i, v := range m.GetTerms() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"terms\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *InformationProtection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"bitlocker\", m.GetBitlocker())\n if err != nil {\n return err\n }\n }\n if m.GetDataLossPreventionPolicies() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDataLossPreventionPolicies()))\n for i, v := range m.GetDataLossPreventionPolicies() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"dataLossPreventionPolicies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"policy\", m.GetPolicy())\n if err != nil {\n return err\n }\n }\n if m.GetSensitivityLabels() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSensitivityLabels()))\n for i, v := range m.GetSensitivityLabels() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"sensitivityLabels\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"sensitivityPolicySettings\", m.GetSensitivityPolicySettings())\n if err != nil {\n return err\n }\n }\n if m.GetThreatAssessmentRequests() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetThreatAssessmentRequests()))\n for i, v := range m.GetThreatAssessmentRequests() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"threatAssessmentRequests\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (b *binding) serialize() ([]byte, error) {\n\treturn json.Marshal(b)\n}", "func (m *VirtualEndpoint) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAuditEvents() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAuditEvents()))\n for i, v := range m.GetAuditEvents() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"auditEvents\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetBulkActions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBulkActions()))\n for i, v := range m.GetBulkActions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"bulkActions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCloudPCs() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCloudPCs()))\n for i, v := range m.GetCloudPCs() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"cloudPCs\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"crossCloudGovernmentOrganizationMapping\", m.GetCrossCloudGovernmentOrganizationMapping())\n if err != nil {\n return err\n }\n }\n if m.GetDeviceImages() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDeviceImages()))\n for i, v := range m.GetDeviceImages() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"deviceImages\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetExternalPartnerSettings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetExternalPartnerSettings()))\n for i, v := range m.GetExternalPartnerSettings() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"externalPartnerSettings\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetFrontLineServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetFrontLineServicePlans()))\n for i, v := range m.GetFrontLineServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"frontLineServicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetGalleryImages() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetGalleryImages()))\n for i, v := range m.GetGalleryImages() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"galleryImages\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOnPremisesConnections() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetOnPremisesConnections()))\n for i, v := range m.GetOnPremisesConnections() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"onPremisesConnections\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"organizationSettings\", m.GetOrganizationSettings())\n if err != nil {\n return err\n }\n }\n if m.GetProvisioningPolicies() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetProvisioningPolicies()))\n for i, v := range m.GetProvisioningPolicies() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"provisioningPolicies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"reports\", m.GetReports())\n if err != nil {\n return err\n }\n }\n if m.GetServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetServicePlans()))\n for i, v := range m.GetServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"servicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSharedUseServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSharedUseServicePlans()))\n for i, v := range m.GetSharedUseServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"sharedUseServicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSnapshots() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSnapshots()))\n for i, v := range m.GetSnapshots() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"snapshots\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSupportedRegions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSupportedRegions()))\n for i, v := range m.GetSupportedRegions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"supportedRegions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetUserSettings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetUserSettings()))\n for i, v := range m.GetUserSettings() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"userSettings\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (msg *MsgInv) Serialize(w io.Writer, pver uint32) error {\n\terr := writeCompactSize(w, pver, msg.InvCount())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, inv := range msg.Inventory {\n\t\terr := inv.Serialize(w, pver)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *RemoteAssistancePartner) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastConnectionDateTime\", m.GetLastConnectionDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetOnboardingStatus() != nil {\n cast := (*m.GetOnboardingStatus()).String()\n err = writer.WriteStringValue(\"onboardingStatus\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onboardingUrl\", m.GetOnboardingUrl())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *WorkbookOperation) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"error\", m.GetError())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"resourceLocation\", m.GetResourceLocation())\n if err != nil {\n return err\n }\n }\n if m.GetStatus() != nil {\n cast := (*m.GetStatus()).String()\n err = writer.WriteStringValue(\"status\", &cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *DeviceLocalCredentialInfo) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetCredentials() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCredentials()))\n for i, v := range m.GetCredentials() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"credentials\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"deviceName\", m.GetDeviceName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastBackupDateTime\", m.GetLastBackupDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"refreshDateTime\", m.GetRefreshDateTime())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *Synchronization) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetJobs() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetJobs()))\n for i, v := range m.GetJobs() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"jobs\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSecrets() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSecrets()))\n for i, v := range m.GetSecrets() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"secrets\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTemplates() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTemplates()))\n for i, v := range m.GetTemplates() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"templates\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func serialize(toMarshal interface{}) *bytes.Buffer {\n\tjsonStr, _ := json.Marshal(toMarshal)\n\treturn bytes.NewBuffer(jsonStr)\n}", "func (i Int) Serialize() ([]byte, error) {\n\treturn []byte(strconv.Itoa(int(i))), nil\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\ttmp := []string{}\n\ts(root, &tmp)\n\tthis.SerializeStr = strings.Join(tmp, \",\")\n\treturn this.SerializeStr\n}", "func (e *EntityNotFoundError) Serialize() []byte {\n\tg, _ := json.Marshal(map[string]interface{}{\n\t\t\"code\": \"ERR-001\",\n\t\t\"error\": \"EntityNotFoundError\",\n\t\t\"description\": e.Error(),\n\t\t\"success\": false,\n\t})\n\n\treturn g\n}", "func (f *ProgressNotice) Serialize(buffer []byte) []byte {\n\tbinary.LittleEndian.PutUint64(buffer, f.Offset)\n\tbuffer = f.User.Serialize(buffer[8:])\n\treturn buffer\n}", "func (p ProductSize) Serialize() common.JSON {\n\treturn common.JSON{\n\t\t\"id\": p.ID,\n\t\t\"product_id\": p.ProductID,\n\t\t\"sku\": p.Sku,\n\t\t\"size\": p.Size,\n\t\t\"created_at\": p.CreatedAt,\n\t\t\"created_by\": p.CreatedAt,\n\t\t\"updated_at\": p.CreatedAt,\n\t\t\"updated_by\": p.CreatedAt,\n\t\t\"deleted_at\": p.CreatedAt,\n\t\t\"deleted_by\": p.CreatedAt,\n\t}\n}", "func (user *User) Serialize() common.JSON {\n\treturn common.JSON{\n\t\t\"username\": user.Username,\n\t\t\"id\": user.ID,\n\t\t\"uuid\": user.UUID,\n\t}\n}", "func (bm *BlockMeta) Serialize() ([]byte, error) {\n\tpb, err := bm.Proto()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn proto.Marshal(pb)\n}", "func (s *Session) Serialize() string {\n\tvar str string\n\n\tfor _, tv := range []*Table{s.Filter, s.Nat, s.Mangle} {\n\t\tstr += fmt.Sprintf(\"*%s\\n\", tv.name)\n\t\tfor _, cv := range tv.Chains {\n\t\t\tif cv != nil {\n\t\t\t\tstr += fmt.Sprintf(\":%s %s [0:0]\\n\", cv.name, cv.policy)\n\t\t\t}\n\t\t}\n\t\tfor _, cv := range tv.Chains {\n\t\t\tif cv != nil {\n\t\t\t\tif cv.rules != nil {\n\t\t\t\t\tfor _, rv := range cv.rules {\n\t\t\t\t\t\tstr += rv + \"\\n\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstr += fmt.Sprintf(\"COMMIT\\n\")\n\t}\n\n\treturn str\n}", "func (c *Circle) Serialize() interface{} {\n\tcx := int64(math.Round(c.center.x * configs.HashPrecision))\n\tcy := int64(math.Round(c.center.y * configs.HashPrecision))\n\tcr := int64(math.Round(c.r * configs.HashPrecision))\n\treturn (cx*configs.Prime+cy)*configs.Prime + cr\n}", "func Serialize(object interface{}) ([]byte, error) {\n\tserialized, err := json.Marshal(object)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn serialized, nil\n}", "func (m *SAMap) Serialize() ([]byte, error) {\n\tm.RLock()\n\tdefer m.RUnlock()\n\treturn json.Marshal(m.ma)\n}", "func (req *PutRequest) serialize(w proto.Writer, serialVersion int16) (err error) {\n\treturn req.serializeInternal(w, serialVersion, true)\n}", "func (m *ChannelIdentity) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"channelId\", m.GetChannelId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"teamId\", m.GetTeamId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *PrinterCreateOperation) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.PrintOperation.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"certificate\", m.GetCertificate())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"printer\", m.GetPrinter())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *PrinterCreateOperation) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.PrintOperation.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"certificate\", m.GetCertificate())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"printer\", m.GetPrinter())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func Serialize(ctx context.Context, msgType omci.MessageType, request gopacket.SerializableLayer, tid uint16) ([]byte, error) {\n\tomciLayer := &omci.OMCI{\n\t\tTransactionID: tid,\n\t\tMessageType: msgType,\n\t}\n\treturn SerializeOmciLayer(ctx, omciLayer, request)\n}", "func (m *Schema) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"baseType\", m.GetBaseType())\n if err != nil {\n return err\n }\n }\n if m.GetProperties() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetProperties())\n err = writer.WriteCollectionOfObjectValues(\"properties\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (s *Serializer) Serialize(p svermaker.ProjectVersion) error {\n\ts.SerializerInvoked = true\n\treturn s.SerializerFn(p)\n}", "func serialize(src interface{}) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tenc := gob.NewEncoder(buf)\n\tif err := enc.Encode(src); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (ts *TagSet) Serialization() []byte {\n\treturn ts.serialization\n}", "func (m *CloudPcConnection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"healthCheckStatus\", m.GetHealthCheckStatus())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastRefreshedDateTime\", m.GetLastRefreshedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"tenantDisplayName\", m.GetTenantDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"tenantId\", m.GetTenantId())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *BookingBusiness) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"address\", m.GetAddress())\n if err != nil {\n return err\n }\n }\n if m.GetAppointments() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAppointments()))\n for i, v := range m.GetAppointments() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"appointments\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetBusinessHours() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBusinessHours()))\n for i, v := range m.GetBusinessHours() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"businessHours\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"businessType\", m.GetBusinessType())\n if err != nil {\n return err\n }\n }\n if m.GetCalendarView() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCalendarView()))\n for i, v := range m.GetCalendarView() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"calendarView\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCustomers() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCustomers()))\n for i, v := range m.GetCustomers() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"customers\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCustomQuestions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCustomQuestions()))\n for i, v := range m.GetCustomQuestions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"customQuestions\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"defaultCurrencyIso\", m.GetDefaultCurrencyIso())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"email\", m.GetEmail())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"languageTag\", m.GetLanguageTag())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"phone\", m.GetPhone())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"schedulingPolicy\", m.GetSchedulingPolicy())\n if err != nil {\n return err\n }\n }\n if m.GetServices() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetServices()))\n for i, v := range m.GetServices() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"services\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetStaffMembers() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetStaffMembers()))\n for i, v := range m.GetStaffMembers() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"staffMembers\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"webSiteUrl\", m.GetWebSiteUrl())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *EmbeddedSIMActivationCode) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"integratedCircuitCardIdentifier\", m.GetIntegratedCircuitCardIdentifier())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"matchingIdentifier\", m.GetMatchingIdentifier())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"smdpPlusServerAddress\", m.GetSmdpPlusServerAddress())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (w *Writer) Serialize(v interface{}) *Writer {\n\tif v == nil {\n\t\tw.WriteNil()\n\t} else if rv, ok := v.(reflect.Value); ok {\n\t\tw.WriteValue(rv)\n\t} else {\n\t\tw.WriteValue(reflect.ValueOf(v))\n\t}\n\treturn w\n}", "func (record *SessionRecord) Serialize() ([]byte, error) {\n\trs := &protobuf.RecordStructure{}\n\trs.CurrentSession = record.sessionState.SS\n\tfor _, s := range record.PreviousStates {\n\t\trs.PreviousSessions = append(rs.PreviousSessions, s.SS)\n\t}\n\tb, err := proto.Marshal(rs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}" ]
[ "0.6572986", "0.6466613", "0.6435532", "0.63836247", "0.6377068", "0.63716114", "0.6346305", "0.62336147", "0.6171269", "0.6162533", "0.61441034", "0.6142544", "0.6116166", "0.610626", "0.6100351", "0.6082516", "0.6060808", "0.6053123", "0.6039119", "0.60381764", "0.60261023", "0.60039175", "0.59918606", "0.59914076", "0.5974712", "0.5974484", "0.5970634", "0.5952611", "0.5946486", "0.59450865", "0.5940796", "0.59394485", "0.59394366", "0.59377605", "0.5937568", "0.59360915", "0.5931097", "0.5929001", "0.59284574", "0.59035015", "0.59031016", "0.5895243", "0.58752036", "0.58727145", "0.5855991", "0.5854772", "0.585326", "0.58368224", "0.58364624", "0.58350384", "0.5834011", "0.5812052", "0.58117825", "0.58088374", "0.58088374", "0.5801002", "0.5796614", "0.5796315", "0.5782493", "0.5774934", "0.57711565", "0.57711416", "0.5769109", "0.5768296", "0.57620305", "0.5749026", "0.5744891", "0.57402736", "0.57361037", "0.57326525", "0.5732051", "0.5727444", "0.57250386", "0.57224107", "0.5722387", "0.5717766", "0.57160777", "0.57041603", "0.56997585", "0.5698607", "0.56971216", "0.5697107", "0.5696918", "0.5695454", "0.5685647", "0.56853646", "0.56833076", "0.5671279", "0.56696004", "0.56696004", "0.56692386", "0.5667735", "0.56639826", "0.5662368", "0.5660281", "0.56548345", "0.5651103", "0.56429994", "0.5641443", "0.5641308" ]
0.5830749
51
SetColumns sets the columns property value. The collection of field definitions for this list.
func (m *List) SetColumns(value []ColumnDefinitionable)() { m.columns = value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Creater) SetColumns(c1 []builder.Columns) builder.Creater {\n\n\tcolumnDefs := make([]string, 0, len(c1))\n\n\tfor _, item := range c1 {\n\t\tcolumnDefs = append(columnDefs, fmt.Sprintf(\"%s %s %s\", item.Name, item.Datatype, item.Constraint))\n\t}\n\n\tcolumns := strings.Join(columnDefs, seperator)\n\tc.sql.WriteString(fmt.Sprintf(\"%s %s %s\", \"(\", columns, \");\"))\n\n\treturn c\n}", "func (t *Table) SetColumns(columns []string) *Table {\n\tt.Clear(true)\n\tif t.showIndex {\n\t\tcolumns = append([]string{\"#\"}, columns...)\n\t\tif len(columns) >= 2 {\n\t\t\tt.sortCol = 1\n\t\t\tt.sortType = SortAsc\n\t\t}\n\t} else {\n\t\tif len(columns) >= 1 {\n\t\t\tt.sortCol = 0\n\t\t\tt.sortType = SortAsc\n\t\t}\n\t}\n\tfor i := 0; i < len(columns); i++ {\n\t\tcell := cview.NewTableCell(columns[i])\n\t\tif t.addCellFunc != nil {\n\t\t\tt.addCellFunc(cell, true, 0)\n\t\t}\n\t\tt.Table.SetCell(0, i, cell)\n\t}\n\tt.columns = columns\n\treturn t\n}", "func (o *InlineResponse20075Stats) SetColumns(v InlineResponse20075StatsColumns) {\n\to.Columns = &v\n}", "func SetColumns(names []string) {\n\tvar (\n\t\tn int\n\t\tcurColStr = ColumnsString()\n\t\tnewColumns = make([]*Column, len(GlobalColumns))\n\t)\n\n\tlock.Lock()\n\n\t// add enabled columns by name\n\tfor _, name := range names {\n\t\tnewColumns[n] = popColumn(name)\n\t\tnewColumns[n].Enabled = true\n\t\tn++\n\t}\n\n\t// extend with omitted columns as disabled\n\tfor _, col := range GlobalColumns {\n\t\tnewColumns[n] = col\n\t\tnewColumns[n].Enabled = false\n\t\tn++\n\t}\n\n\tGlobalColumns = newColumns\n\tlock.Unlock()\n\n\tlog.Noticef(\"config change [columns]: %s -> %s\", curColStr, ColumnsString())\n}", "func (o *TelemetryDruidScanRequestAllOf) SetColumns(v []string) {\n\to.Columns = v\n}", "func (o *SummaryResponse) SetColumns(v SummaryColumnResponse) {\n\to.Columns = &v\n}", "func (v *IconView) SetColumns(columns int) {\n\tC.gtk_icon_view_set_columns(v.native(), C.gint(columns))\n}", "func (s *Session) Columns(columns ...string) *Session {\n\ts.initStatemnt()\n\ts.statement.Columns(columns...)\n\treturn s\n}", "func (b *Blueprint) Set(column string, allowed []string) *ColumnDefinition {\n\treturn b.addColumn(\"set\", column, &ColumnOptions{\n\t\tAllowed: allowed,\n\t})\n}", "func (ts *STableSpec) Columns() []IColumnSpec {\n\tif ts._columns == nil {\n\t\tval := reflect.Indirect(reflect.New(ts.structType))\n\t\tts.struct2TableSpec(val)\n\t}\n\treturn ts._columns\n}", "func (v *nicerButSlowerFilmListViewType) Columns() []string {\n\treturn []string{\n\t\t\"FID\",\n\t\t\"title\",\n\t\t\"description\",\n\t\t\"category\",\n\t\t\"price\",\n\t\t\"length\",\n\t\t\"rating\",\n\t\t\"actors\",\n\t}\n}", "func Columns() *ColumnsType {\n\ttable := qbColumnsTable\n\treturn &ColumnsType{\n\t\tqbColumnsFColumnName.Copy(&table),\n\t\tqbColumnsFTableSchema.Copy(&table),\n\t\tqbColumnsFTableName.Copy(&table),\n\t\tqbColumnsFCharacterMaximumLength.Copy(&table),\n\t\t&table,\n\t}\n}", "func (db *DB) InitColumns(param *Params) {\n\n\tvar (\n\t\tname = conf.Get[string](cons.ConfDBName)\n\t\ttables = []string{param.Table}\n\t)\n\n\ttables = append(tables, param.InnerTable...)\n\ttables = append(tables, param.LeftTable...)\n\n\tfor _, v := range tables {\n\t\tif v == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := TableCols[v]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tvar columns []string\n\t\tparam.Data = &columns\n\t\ttb := TableOnly(v)\n\t\tdb.get(&GT{\n\t\t\tParams: &Params{Data: &columns},\n\t\t\tsql: \"SELECT COLUMN_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_NAME = ? and TABLE_SCHEMA = ?\",\n\t\t\tArgs: []any{tb, name},\n\t\t})\n\t\tTableCols[tb] = columns\n\t}\n}", "func (m *List) GetColumns()([]ColumnDefinitionable) {\n return m.columns\n}", "func (q *Query) Columns(names ...string) *Query {\n\tq.headers = append(q.headers, \"Columns: \"+strings.Join(names, \" \"))\n\tq.columns = names\n\treturn q\n}", "func (b CreateIndexBuilder) Columns(columns ...string) CreateIndexBuilder {\n\treturn builder.Set(b, \"Columns\", columns).(CreateIndexBuilder)\n}", "func (r *Reader) SetColumnNames(cols []string) {\n\tif r.ColumnNamesInFirstRow {\n\t\tpanic(\"Should not assign column names when they are expected in the first row\")\n\t}\n\tr.cols = cols\n}", "func (f *fileHelper) setHeaderColumns (str string, col int) {\n\tswitch str {\n\tcase colName:\n\t\tf.nameCol = col\n\tcase colDepartment:\n\t\tf.departCol = col\n\tcase colClient:\n\t\tf.clientCol = col\n\tcase colSede:\n\t\tf.sedeCol = col\n\tcase status:\n\t\tf.statusCol = col\n\t\tf.firstDateCol = col + 1\n\t\tf.fieldsSet = true\n\t}\n}", "func setColumnValues(b *Battery) {\n\tvar remainingFloors int\n\n\t//calculating the remaining floors\n\tif b.numberOfBasements > 0 { //if there are basement floors\n\t\tremainingFloors = b.numberOfFloors % (b.numberOfColumns - 1)\n\t} else { //if there is no basement\n\t\tremainingFloors = b.numberOfFloors % b.numberOfColumns\n\t}\n\n\t//setting the minFloor and maxFloor of each column\n\tif b.numberOfColumns == 1 { //if there is just one column, it serves all the floors of the building\n\t\tinitializeUniqueColumnFloors(b)\n\t} else { //for more than 1 column\n\t\tinitializeMultiColumnFloors(b)\n\n\t\t//adjusting the number of served floors of the columns if there are remaining floors\n\t\tif remainingFloors != 0 { //if the remainingFloors is not zero, then it adds the remaining floors to the last column\n\t\t\tb.columnsList[len(b.columnsList)-1].numberServedFloors = b.numberOfFloorsPerColumn + remainingFloors\n\t\t\tb.columnsList[len(b.columnsList)-1].maxFloor = b.columnsList[len(b.columnsList)-1].minFloor + b.columnsList[len(b.columnsList)-1].numberServedFloors\n\t\t}\n\t\t//if there is a basement, then the first column will serve the basements + RDC\n\t\tif b.numberOfBasements > 0 {\n\t\t\tinitializeBasementColumnFloors(b)\n\t\t}\n\t}\n}", "func (mc *MultiCursor) SetColumn() {\n\tcol := mc.cursors[0].col\n\tminRow, maxRow := mc.MinMaxRow()\n\tmc.cursors = []Cursor{}\n\tfor row := minRow; row <= maxRow; row++ {\n\t\tcursor := Cursor{row: row, col: col, colwant: col}\n\t\tmc.Append(cursor)\n\t}\n}", "func (qr *QueryResponse) Columns() []ColumnItem {\n\treturn qr.ColumnList\n}", "func Columns(columns ...ColumnMap) *MappedColumns {\n\treturn &MappedColumns{columns, func() error { return nil }}\n}", "func (i *Inserter) Columns(s []string) builder.Inserter {\n\tsort.Strings(s)\n\ti.sql.WriteString(strings.Join(s, seperator))\n\ti.sql.WriteString(\" ) values \")\n\treturn i\n}", "func (w *TableWriters) WriteColumns(columns []model.TableColumn) {\n\tfor _, s := range w.writers {\n\t\ts.WriteColumns(columns)\n\t}\n}", "func (fw *FileWriter) Columns() []*Column {\n\treturn fw.schemaWriter.Columns()\n}", "func (l *universalLister) SetSelectedColumns(selectedColumns []string) {\n\tl.selectedColumns = strings.Join(selectedColumns, \", \")\n}", "func (t *Type) SetFields(fields []*Field)", "func (v *actorInfoViewType) Columns() []string {\n\treturn []string{\n\t\t\"actor_id\",\n\t\t\"first_name\",\n\t\t\"last_name\",\n\t\t\"film_info\",\n\t}\n}", "func (r *Iter_UServ_UpdateNameToFoo) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (v *permutationTableType) Columns() []string {\n\treturn []string{\"uuid\", \"data\"}\n}", "func (matrix Matrix4) SetColumn(columnIndex int, columnData vector.Vector) Matrix4 {\n\tfor i := range matrix {\n\t\tmatrix[i][columnIndex] = columnData[i]\n\t}\n\treturn matrix\n}", "func (m *ItemItemsItemWorkbookTablesWorkbookTableItemRequestBuilder) Columns()(*ItemItemsItemWorkbookTablesItemColumnsRequestBuilder) {\n return NewItemItemsItemWorkbookTablesItemColumnsRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (a *SqlAgent) SetUpdateColumns(updateBuilder sq.UpdateBuilder, model interface{}, ignoreColumns ...string) sq.UpdateBuilder {\n\tfieldMap := a.db.Mapper.TypeMap(reflect.TypeOf(model))\n\tvalueMap := a.db.Mapper.FieldMap(reflect.Indirect(reflect.ValueOf(model)))\n\tclauses := make(map[string]interface{})\n\n\tfor _, v := range fieldMap.Index {\n\t\tname := v.Name\n\t\tif isIgnoreFields(name, ignoreColumns) {\n\t\t\tcontinue\n\t\t}\n\t\tif data, ok := valueMap[name]; ok {\n\t\t\tclauses[name] = data.Interface()\n\t\t}\n\t}\n\treturn updateBuilder.SetMap(clauses)\n}", "func (t *Table) SetColumnWidths(widths []int) {\n\tt.columnWidths = widths\n}", "func (ref *UIElement) Columns() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(ColumnsAttribute)\n}", "func (o CassandraSchemaOutput) Columns() ColumnArrayOutput {\n\treturn o.ApplyT(func(v CassandraSchema) []Column { return v.Columns }).(ColumnArrayOutput)\n}", "func (d *dbBase) setColsValues(mi *modelInfo, ind *reflect.Value, cols []string, values []interface{}, tz *time.Location) {\n\tfor i, column := range cols {\n\t\tval := reflect.Indirect(reflect.ValueOf(values[i])).Interface()\n\n\t\tfi := mi.fields.GetByColumn(column)\n\n\t\tfield := ind.FieldByIndex(fi.fieldIndex)\n\n\t\tvalue, err := d.convertValueFromDB(fi, val, tz)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"Raw value: `%v` %s\", val, err.Error()))\n\t\t}\n\n\t\t_, err = d.setFieldValue(fi, value, field)\n\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"Raw value: `%v` %s\", val, err.Error()))\n\t\t}\n\t}\n}", "func (t *NodesTable) Columns() []table.ColumnDefinition {\n\treturn t.columns\n}", "func (d *Dataset) UpdateColumns(a *config.AppContext, cols []models.Node) ([]models.Node, error) {\n\tds := models.Dataset(*d)\n\tres, err := (&ds).UpdateColumns(a.Log, a.Db, cols)\n\t*d = Dataset(ds)\n\treturn res, err\n}", "func (v *coachTableType) Columns() []string {\n\treturn []string{\n\t\t\"id\",\n\t\t\"name\",\n\t\t\"created_at\",\n\t\t\"updated_at\",\n\t}\n}", "func buildGridColumnsData(columns []ColumnSchema ,index int, cols []interface{})[]interface{}{\n\tcols = append(cols, ColumnDefinition{\n\t\tText: columns[index].Name,\n\t\tDataIndex: columns[index].Field,\n\t\tWidth : 120,\n\t\tSortable:true,\n\t\tDataType: columns[index].Type,\n\t})\n\treturn cols;\n}", "func (v *templateTableType) Columns() []string {\n\treturn []string{\n\t\t\"id\",\n\t\t\"title\",\n\t\t\"description\",\n\t\t\"type\",\n\t\t\"note\",\n\t\t\"coach_id\",\n\t\t\"place_id\",\n\t\t\"weekday\",\n\t\t\"start_time\",\n\t\t\"duration\",\n\t\t\"created_at\",\n\t\t\"updated_at\",\n\t}\n}", "func (m *Schema) SetProperties(value []Propertyable)() {\n m.properties = value\n}", "func (m *AccessReviewSet) SetDefinitions(value []AccessReviewScheduleDefinitionable)() {\n m.definitions = value\n}", "func (k *CustomResourceKind) Columns() []*printer.TableColumn {\n\tif k.Spec == nil {\n\t\treturn nil\n\t}\n\n\treturn []*printer.TableColumn{\n\t\t{\n\t\t\tName: \"JSONSchema\",\n\t\t\tValue: k.Spec.JSONSchema,\n\t\t},\n\t}\n}", "func (o CassandraSchemaResponseOutput) Columns() ColumnResponseArrayOutput {\n\treturn o.ApplyT(func(v CassandraSchemaResponse) []ColumnResponse { return v.Columns }).(ColumnResponseArrayOutput)\n}", "func (s *DbRecorder) Columns(includeKeys bool) []string {\n\treturn s.colList(includeKeys, false)\n}", "func (t Table) Columns() []*Column {\n\treturn t.columns\n}", "func (i *PermissionIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (r *filter) Columns() []string {\n\treturn r.input.Columns()\n}", "func (cr *callResult) Columns() []string {\n\tif cr._columns == nil {\n\t\tnumField := len(cr.outputFields)\n\t\tcr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tcr._columns[i] = cr.outputFields[i].Name()\n\t\t}\n\t}\n\treturn cr._columns\n}", "func (cr *callResult) Columns() []string {\n\tif cr._columns == nil {\n\t\tnumField := len(cr.outputFields)\n\t\tcr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tcr._columns[i] = cr.outputFields[i].Name()\n\t\t}\n\t}\n\treturn cr._columns\n}", "func (i *UserPermissionsIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (r *Iter_UServ_CreateUsersTable) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (i *UserIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (i *UserGroupsIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (d *Driver) SetColumn(idx int, c int, rV byte) error {\n\tfor r := 0; r < 8; r++ {\n\t\tvar on bool\n\t\tif (rV>>byte(7-r))&0x01 == 1 {\n\t\t\ton = true\n\t\t}\n\t\tif err := d.SetLed(idx, r, c, on); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (t *Table) SetColumnExpansions(expansions []int) {\n\tt.columnExpansions = expansions\n}", "func (r *Iter_UServ_UpdateUserName) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func Columns(cols ...ColumnCreator) []ColumnCreator {\n\treturn cols\n}", "func (db *DB) Columns(table string) ([]string, error) {\n\tif err := db.db.RLock(); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer db.db.RUnlock()\n\n\ts, err := db.db.Schema(table)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cols []string\n\tfor _, c := range s.Columns {\n\t\tcols = append(cols, c.Column)\n\t}\n\treturn cols, nil\n}", "func (xs *Sheet) SetCol(colFirst int, colLast int, width float64, format *Format, hidden int) int {\n\tfo := uintptr(0)\n\tif nil != format {\n\t\tfo = format.self\n\t}\n\ttmp, _, _ := xs.xb.lib.NewProc(\"xlSheetSetColW\").\n\t\tCall(xs.self, I(colFirst), I(colLast), F(width), fo, I(hidden))\n\n\treturn int(tmp)\n}", "func (v *pgStatDatabaseViewType) Columns() []string {\n\treturn []string{\n\t\t\"datid\",\n\t\t\"datname\",\n\t}\n}", "func (r *Iter_UServ_InsertUsers) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (r *Iter_UServ_GetAllUsers) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (fn *formulaFuncs) COLUMNS(argsList *list.List) formulaArg {\n\tif argsList.Len() != 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"COLUMNS requires 1 argument\")\n\t}\n\tmin, max := calcColumnsMinMax(argsList)\n\tif max == MaxColumns {\n\t\treturn newNumberFormulaArg(float64(MaxColumns))\n\t}\n\tresult := max - min + 1\n\tif max == min {\n\t\tif min == 0 {\n\t\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"invalid reference\")\n\t\t}\n\t\treturn newNumberFormulaArg(float64(1))\n\t}\n\treturn newNumberFormulaArg(float64(result))\n}", "func (o CassandraSchemaPtrOutput) Columns() ColumnArrayOutput {\n\treturn o.ApplyT(func(v *CassandraSchema) []Column {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Columns\n\t}).(ColumnArrayOutput)\n}", "func (o DataSetGeoSpatialColumnGroupOutput) Columns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v DataSetGeoSpatialColumnGroup) []string { return v.Columns }).(pulumi.StringArrayOutput)\n}", "func (i *GroupPermissionsIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}", "func (dao *PagesDao) Columns() PagesColumns {\n\treturn dao.columns\n}", "func (v *pgUserViewType) Columns() []string {\n\treturn []string{\n\t\t\"usesysid\",\n\t\t\"usename\",\n\t}\n}", "func (r *rows) Columns() (c []string) {\n\tif trace {\n\t\tdefer func() {\n\t\t\ttracer(r, \"Columns(): %v\", c)\n\t\t}()\n\t}\n\treturn r.columns\n}", "func (qr *queryResult) Columns() []string {\n\tif qr._columns == nil {\n\t\tnumField := len(qr.fields)\n\t\tqr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tqr._columns[i] = qr.fields[i].Name()\n\t\t}\n\t}\n\treturn qr._columns\n}", "func (qr *queryResult) Columns() []string {\n\tif qr._columns == nil {\n\t\tnumField := len(qr.fields)\n\t\tqr._columns = make([]string, numField)\n\t\tfor i := 0; i < numField; i++ {\n\t\t\tqr._columns[i] = qr.fields[i].Name()\n\t\t}\n\t}\n\treturn qr._columns\n}", "func (m *ItemSitesSiteItemRequestBuilder) Columns()(*ItemSitesItemColumnsRequestBuilder) {\n return NewItemSitesItemColumnsRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (v *productTableType) Columns() []string {\n\treturn []string{\"product_id\", \"party_id\", \"created_at\", \"serial\", \"addr\"}\n}", "func (m *SiteItemRequestBuilder) Columns()(*ItemColumnsRequestBuilder) {\n return NewItemColumnsRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func (c *ProjectsInstancesTablesModifyColumnFamiliesCall) Fields(s ...googleapi.Field) *ProjectsInstancesTablesModifyColumnFamiliesCall {\n\tc.urlParams_.Set(\"fields\", googleapi.CombineFields(s))\n\treturn c\n}", "func (view *CrosstabView) Columns() ([]string, error) {\n\tif view.err != nil {\n\t\treturn nil, view.err\n\t}\n\tcols := make([]string, len(view.hkeys)+1)\n\tcols[0] = view.v\n\tfor i := 0; i < len(view.hkeys); i++ {\n\t\tcols[i+1] = view.hkeys[i].v\n\t}\n\treturn cols, nil\n}", "func (r *Reader) Columns() []Column {\n\treturn r.cols\n}", "func createColumnsList(b *Battery) {\n\tname := 'A'\n\tfor i := 1; i <= b.numberOfColumns; i++ {\n\t\tc := newColumn(i, name, columnActive, b.numberOfElevatorsPerColumn, b.numberOfFloorsPerColumn, b.numberOfBasements, b)\n\t\tb.columnsList = append(b.columnsList, c)\n\t\tname++\n\t}\n}", "func (*__tbl_iba_servers) GetColumns() []string {\n\treturn []string{\"id\", \"name\", \"zex\", \"stort\", \"comment\"}\n}", "func (dao *SysConfigDao) Columns() SysConfigColumns {\n\treturn dao.columns\n}", "func (_m *RepositoryMock) GetColumns() []string {\n\tret := _m.Called()\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func() []string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_article *Article) UpdateColumns(am map[string]interface{}) error {\n\tif _article.Id == 0 {\n\t\treturn errors.New(\"Invalid Id field: it can't be a zero value\")\n\t}\n\terr := UpdateArticle(_article.Id, am)\n\treturn err\n}", "func (m *Model) GetColumns() []Column {\n\treturn m.Columns\n}", "func (r *result) Columns() []string {\n\treturn r.columns\n}", "func (t *table) SetHeaders(h []string) {\n\tt.Headers = h\n}", "func (o CassandraSchemaResponsePtrOutput) Columns() ColumnResponseArrayOutput {\n\treturn o.ApplyT(func(v *CassandraSchemaResponse) []ColumnResponse {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Columns\n\t}).(ColumnResponseArrayOutput)\n}", "func (f *Fields) Set(s []*Field)", "func (r *Iter_UServ_Drop) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (fb *FlowBox) SetColumnSpacing(spacing uint) {\n\tC.gtk_flow_box_set_column_spacing(fb.native(), C.guint(spacing))\n}", "func (q Query) Columns() []string {\n\treturn q.columns\n}", "func (m *MockDriver) Columns(schema, tableName string, whitelist, blacklist []string) ([]drivers.Column, error) {\n\treturn map[string][]drivers.Column{\n\t\t\"pilots\": {\n\t\t\t{Name: \"id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"name\", Type: \"string\", DBType: \"character\"},\n\t\t},\n\t\t\"airports\": {\n\t\t\t{Name: \"id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"size\", Type: \"null.Int\", DBType: \"integer\", Nullable: true},\n\t\t},\n\t\t\"jets\": {\n\t\t\t{Name: \"id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"pilot_id\", Type: \"int\", DBType: \"integer\", Nullable: true, Unique: true},\n\t\t\t{Name: \"airport_id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"name\", Type: \"string\", DBType: \"character\", Nullable: false},\n\t\t\t{Name: \"color\", Type: \"null.String\", DBType: \"character\", Nullable: true},\n\t\t\t{Name: \"uuid\", Type: \"string\", DBType: \"uuid\", Nullable: true},\n\t\t\t{Name: \"identifier\", Type: \"string\", DBType: \"uuid\", Nullable: false},\n\t\t\t{Name: \"cargo\", Type: \"[]byte\", DBType: \"bytea\", Nullable: false},\n\t\t\t{Name: \"manifest\", Type: \"[]byte\", DBType: \"bytea\", Nullable: true, Unique: true},\n\t\t},\n\t\t\"licenses\": {\n\t\t\t{Name: \"id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"pilot_id\", Type: \"int\", DBType: \"integer\"},\n\t\t},\n\t\t\"hangars\": {\n\t\t\t{Name: \"id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"name\", Type: \"string\", DBType: \"character\", Nullable: true, Unique: true},\n\t\t},\n\t\t\"languages\": {\n\t\t\t{Name: \"id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"language\", Type: \"string\", DBType: \"character\", Nullable: false, Unique: true},\n\t\t},\n\t\t\"pilot_languages\": {\n\t\t\t{Name: \"pilot_id\", Type: \"int\", DBType: \"integer\"},\n\t\t\t{Name: \"language_id\", Type: \"int\", DBType: \"integer\"},\n\t\t},\n\t}[tableName], nil\n}", "func (d *PrefsDialog) populateColumns() {\n\t// First add selected columns\n\tselColSpecs := config.GetConfig().QueueColumns\n\tfor _, colSpec := range selColSpecs {\n\t\td.addQueueColumn(colSpec.ID, colSpec.Width, true)\n\t}\n\n\t// Add all unselected columns\n\tfor _, id := range config.MpdTrackAttributeIds {\n\t\t// Check if the ID is already in the list of selected IDs\n\t\tisSelected := false\n\t\tfor _, selSpec := range selColSpecs {\n\t\t\tif id == selSpec.ID {\n\t\t\t\tisSelected = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// If not, add it\n\t\tif !isSelected {\n\t\t\td.addQueueColumn(id, 0, false)\n\t\t}\n\t}\n\td.ColumnsListBox.ShowAll()\n}", "func (b *SelectBuilder) AddColumns(columns ...string) *SelectBuilder {\n\tb.Columns = append(b.Columns, columns...)\n\treturn b\n}", "func (info *ModelInfo) SetColumnName() {\n\tfor table_index, table := range info.TableList {\n\t\tfor col_index, col := range table.ColumnList {\n\t\t\tif strings.EqualFold(\"-\", col.ColumnName) { // 指明不生成表字段\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcol.ColumnName = col.PropName\n\t\t\ttable.ColumnList[col_index] = col\n\t\t}\n\t\tinfo.TableList[table_index] = table\n\t}\n}", "func (r *rows) Columns() []string {\n\treturn r.parent.columns\n}", "func (v *libraryTableType) Columns() []string {\n\treturn []string{\"id\", \"user_id\", \"volume_id\", \"created_at\", \"updated_at\"}\n}", "func (i *GroupIterator) Columns() ([]string, error) {\n\tif i.cols == nil {\n\t\tcols, err := i.rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ti.cols = cols\n\t}\n\treturn i.cols, nil\n}" ]
[ "0.69769454", "0.6804708", "0.67329115", "0.65630496", "0.6390641", "0.6051947", "0.6024405", "0.5607218", "0.5591005", "0.556967", "0.55185026", "0.5513934", "0.5410269", "0.539816", "0.53536016", "0.5328212", "0.52258617", "0.52192163", "0.52094", "0.51368654", "0.5131282", "0.51265967", "0.5082629", "0.5059485", "0.5049625", "0.50261617", "0.50241125", "0.5011801", "0.50109303", "0.50031376", "0.49956384", "0.4980662", "0.4977849", "0.49719882", "0.49666774", "0.49625155", "0.49606866", "0.49562782", "0.49543703", "0.4941839", "0.4921603", "0.49167234", "0.48991227", "0.4872158", "0.48587295", "0.4857346", "0.4848547", "0.4847016", "0.48416835", "0.48409924", "0.4833213", "0.4833213", "0.4823057", "0.48215", "0.48130357", "0.48065925", "0.480118", "0.47733977", "0.476567", "0.47571632", "0.47564727", "0.47546577", "0.47529897", "0.47365603", "0.4735436", "0.47300097", "0.471253", "0.4707334", "0.4705093", "0.4703362", "0.4701374", "0.46865958", "0.46856567", "0.46856567", "0.46761915", "0.46757978", "0.4675394", "0.46713573", "0.4653086", "0.46499547", "0.46468425", "0.46319893", "0.4630998", "0.46268174", "0.46222273", "0.46149603", "0.4614886", "0.46004966", "0.45961547", "0.45920637", "0.45788088", "0.4574054", "0.4570474", "0.4563992", "0.45610535", "0.4554142", "0.45470765", "0.45448327", "0.4544562", "0.45406583" ]
0.7975869
0
SetContentTypes sets the contentTypes property value. The collection of content types present in this list.
func (m *List) SetContentTypes(value []ContentTypeable)() { m.contentTypes = value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *LastMileAccelerationOptions) SetContentTypes(v []string) {\n\to.ContentTypes = &v\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypes(contentTypes *string) {\n\to.ContentTypes = contentTypes\n}", "func ContentTypes(types []string, blacklist bool) Option {\n\treturn func(c *config) error {\n\t\tc.contentTypes = []parsedContentType{}\n\t\tfor _, v := range types {\n\t\t\tmediaType, params, err := mime.ParseMediaType(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.contentTypes = append(c.contentTypes, parsedContentType{mediaType, params})\n\t\t}\n\t\tc.blacklist = blacklist\n\t\treturn nil\n\t}\n}", "func (o *LastMileAccelerationOptions) GetContentTypes() []string {\n\tif o == nil || o.ContentTypes == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.ContentTypes\n}", "func ContentTypes(contentTypes ...string) Option {\n\treturn ArrayOpt(\"content_types\", contentTypes...)\n}", "func (s *ChannelSpecification) SetSupportedContentTypes(v []*string) *ChannelSpecification {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (ht HTMLContentTypeBinder) ContentTypes() []string {\n\treturn []string{\n\t\t\"application/html\",\n\t\t\"text/html\",\n\t\t\"application/x-www-form-urlencoded\",\n\t\t\"html\",\n\t}\n}", "func (s *RecommendationJobPayloadConfig) SetSupportedContentTypes(v []*string) *RecommendationJobPayloadConfig {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (set *ContentTypeSet) Types() (types []ContentType) {\n\tif set == nil || len(set.set) == 0 {\n\t\treturn []ContentType{}\n\t}\n\treturn append(make([]ContentType, 0, len(set.set)), set.set...)\n}", "func (s *InferenceSpecification) SetSupportedContentTypes(v []*string) *InferenceSpecification {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func SetOfContentTypes(types ...ContentType) *ContentTypeSet {\n\tif len(types) == 0 {\n\t\treturn nil\n\t}\n\tset := &ContentTypeSet{\n\t\tset: make([]ContentType, 0, len(types)),\n\t\tpos: -1,\n\t}\nallTypes:\n\tfor _, t := range types {\n\t\t// Let's make sure we have not seen this type before.\n\t\tfor _, tt := range set.set {\n\t\t\tif tt == t {\n\t\t\t\t// Don't add it to the set, already exists\n\t\t\t\tcontinue allTypes\n\t\t\t}\n\t\t}\n\t\tset.set = append(set.set, t)\n\t}\n\tif len(set.set) == 0 {\n\t\treturn nil\n\t}\n\treturn set\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIe(contentTypesIe *string) {\n\to.ContentTypesIe = contentTypesIe\n}", "func (ycp *YamlContentParser) ContentTypes() []string {\n\treturn []string{\"text/x-yaml\", \"application/yaml\", \"text/yaml\", \"application/x-yaml\"}\n}", "func (s *AdditionalInferenceSpecificationDefinition) SetSupportedContentTypes(v []*string) *AdditionalInferenceSpecificationDefinition {\n\ts.SupportedContentTypes = v\n\treturn s\n}", "func (s *CaptureContentTypeHeader) SetCsvContentTypes(v []*string) *CaptureContentTypeHeader {\n\ts.CsvContentTypes = v\n\treturn s\n}", "func (o *ExtrasSavedFiltersListParams) WithContentTypes(contentTypes *string) *ExtrasSavedFiltersListParams {\n\to.SetContentTypes(contentTypes)\n\treturn o\n}", "func (m *List) GetContentTypes()([]ContentTypeable) {\n return m.contentTypes\n}", "func (m *SiteItemRequestBuilder) ContentTypes()(*ItemContentTypesRequestBuilder) {\n return NewItemContentTypesRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func NewContentTypeSet(types ...string) *ContentTypeSet {\n\tif len(types) == 0 {\n\t\treturn nil\n\t}\n\tset := &ContentTypeSet{\n\t\tset: make([]ContentType, 0, len(types)),\n\t\tpos: -1,\n\t}\nallTypes:\n\tfor _, t := range types {\n\t\tmediaType, _, err := mime.ParseMediaType(t)\n\t\tif err != nil {\n\t\t\t// skip types that can not be parsed\n\t\t\tcontinue\n\t\t}\n\t\t// Let's make sure we have not seen this type before.\n\t\tfor _, tt := range set.set {\n\t\t\tif tt == ContentType(mediaType) {\n\t\t\t\t// Don't add it to the set, already exists\n\t\t\t\tcontinue allTypes\n\t\t\t}\n\t\t}\n\t\tset.set = append(set.set, ContentType(mediaType))\n\t}\n\tif len(set.set) == 0 {\n\t\treturn nil\n\t}\n\treturn set\n}", "func (m *ItemSitesSiteItemRequestBuilder) ContentTypes()(*ItemSitesItemContentTypesRequestBuilder) {\n return NewItemSitesItemContentTypesRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (o *LastMileAccelerationOptions) HasContentTypes() bool {\n\tif o != nil && o.ContentTypes != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIc(contentTypesIc *string) {\n\to.ContentTypesIc = contentTypesIc\n}", "func (s *QueryFilters) SetTypes(v []*string) *QueryFilters {\n\ts.Types = v\n\treturn s\n}", "func (s *CaptureContentTypeHeader) SetJsonContentTypes(v []*string) *CaptureContentTypeHeader {\n\ts.JsonContentTypes = v\n\treturn s\n}", "func (_BaseContentSpace *BaseContentSpaceCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseContentSpace.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesNiew(contentTypesNiew *string) {\n\to.ContentTypesNiew = contentTypesNiew\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) ContentTypes(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"contentTypes\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (s *LogSetup) SetTypes(v []*string) *LogSetup {\n\ts.Types = v\n\treturn s\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesNisw(contentTypesNisw *string) {\n\to.ContentTypesNisw = contentTypesNisw\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIsw(contentTypesIsw *string) {\n\to.ContentTypesIsw = contentTypesIsw\n}", "func (s *Channel) SetContentType(v string) *Channel {\n\ts.ContentType = &v\n\treturn s\n}", "func (o *PluginConfigInterface) SetTypes(v []PluginInterfaceType) {\n\to.Types = v\n}", "func (o *MicrosoftGraphListItem) SetContentType(v AnyOfmicrosoftGraphContentTypeInfo) {\n\to.ContentType = &v\n}", "func (s *StartChatContactInput) SetSupportedMessagingContentTypes(v []*string) *StartChatContactInput {\n\ts.SupportedMessagingContentTypes = v\n\treturn s\n}", "func (s *ClarifyInferenceConfig) SetFeatureTypes(v []*string) *ClarifyInferenceConfig {\n\ts.FeatureTypes = v\n\treturn s\n}", "func (_BaseLibrary *BaseLibraryCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseLibrary.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (s *AutoMLChannel) SetContentType(v string) *AutoMLChannel {\n\ts.ContentType = &v\n\treturn s\n}", "func (o *SchemaDefinitionRestDto) SetTypes(v map[string]SchemaType) {\n\to.Types = &v\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesn(contentTypesn *string) {\n\to.ContentTypesn = contentTypesn\n}", "func (o *MicrosoftGraphWorkbookComment) SetContentType(v string) {\n\to.ContentType = &v\n}", "func (_Container *ContainerCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Container.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_AccessIndexor *AccessIndexorCaller) ContentTypes(opts *bind.CallOpts) (struct {\n\tCategory uint8\n\tLength *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _AccessIndexor.contract.Call(opts, &out, \"contentTypes\")\n\n\toutstruct := new(struct {\n\t\tCategory uint8\n\t\tLength *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Category = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.Length = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (s *UtteranceBotResponse) SetContentType(v string) *UtteranceBotResponse {\n\ts.ContentType = &v\n\treturn s\n}", "func (s *AutoMLJobChannel) SetContentType(v string) *AutoMLJobChannel {\n\ts.ContentType = &v\n\treturn s\n}", "func (s *ChatMessage) SetContentType(v string) *ChatMessage {\n\ts.ContentType = &v\n\treturn s\n}", "func (s *MetricsSource) SetContentType(v string) *MetricsSource {\n\ts.ContentType = &v\n\treturn s\n}", "func (s *SendNotificationActionDefinition) SetContentType(v string) *SendNotificationActionDefinition {\n\ts.ContentType = &v\n\treturn s\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) ContentTypes(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"contentTypes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (s *FileSource) SetContentType(v string) *FileSource {\n\ts.ContentType = &v\n\treturn s\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesNic(contentTypesNic *string) {\n\to.ContentTypesNic = contentTypesNic\n}", "func (o *InlineResponse20049Post) SetContentType(v string) {\n\to.ContentType = &v\n}", "func (o *CreateWidgetParams) SetContentType(contentType *string) {\n\to.ContentType = contentType\n}", "func (o *MarketDataSubscribeMarketDataParams) SetContentType(contentType string) {\n\to.ContentType = contentType\n}", "func (o *InlineResponse200115) SetContentType(v string) {\n\to.ContentType = &v\n}", "func (fc *FileCreate) SetContentType(s string) *FileCreate {\n\tfc.mutation.SetContentType(s)\n\treturn fc\n}", "func (o *BranchingModelSettings) SetBranchTypes(v []BranchingModelSettingsBranchTypes) {\n\to.BranchTypes = &v\n}", "func PossibleContentTypes(firstByte byte) (ct ContentTypeOptions) {\n\tif firstByte == 0 {\n\t\treturn 0\n\t}\n\n\tswitch {\n\tcase firstByte < '\\t' /* 9 */ :\n\t\t// not a text\n\t\tif firstByte&^maskWireType == 0 {\n\t\t\treturn 0\n\t\t}\n\tcase firstByte >= legalUtf8:\n\t\tct |= ContentOptionText\n\tcase firstByte < illegalUtf8FirstByte:\n\t\tct |= ContentOptionText\n\t}\n\n\tswitch WireType(firstByte & maskWireType) {\n\tcase WireVarint:\n\t\tif ct&ContentOptionText == 0 && firstByte >= illegalUtf8FirstByte {\n\t\t\tct |= ContentOptionNotation\n\t\t}\n\t\tct |= ContentOptionMessage\n\tcase WireFixed64, WireBytes, WireFixed32, WireStartGroup:\n\t\tct |= ContentOptionMessage\n\tcase WireEndGroup:\n\t\tif ct&ContentOptionText == 0 {\n\t\t\tct |= ContentOptionNotation\n\t\t}\n\t}\n\treturn ct\n}", "func (o *GetContentSourcesUsingGETParams) SetContentType(contentType *string) {\n\to.ContentType = contentType\n}", "func (s *PostAgentProfileInput) SetContentType(v string) *PostAgentProfileInput {\n\ts.ContentType = &v\n\treturn s\n}", "func (s *InferenceExperimentDataStorageConfig) SetContentType(v *CaptureContentTypeHeader) *InferenceExperimentDataStorageConfig {\n\ts.ContentType = v\n\treturn s\n}", "func (s *GetProfileOutput) SetContentType(v string) *GetProfileOutput {\n\ts.ContentType = &v\n\treturn s\n}", "func (c *CreativesListCall) Types(types ...string) *CreativesListCall {\n\tc.urlParams_.SetMulti(\"types\", append([]string{}, types...))\n\treturn c\n}", "func (o *UpdateWidgetParams) SetContentType(contentType *string) {\n\to.ContentType = contentType\n}", "func (s *ListContactReferencesInput) SetReferenceTypes(v []*string) *ListContactReferencesInput {\n\ts.ReferenceTypes = v\n\treturn s\n}", "func (s *TransformInput) SetContentType(v string) *TransformInput {\n\ts.ContentType = &v\n\treturn s\n}", "func (o *BranchingModel) SetBranchTypes(v []BranchingModelBranchTypes) {\n\to.BranchTypes = &v\n}", "func (o *CreateScriptParams) SetContentType(contentType string) {\n\to.ContentType = contentType\n}", "func (o *ExtrasSavedFiltersListParams) SetContentTypesIew(contentTypesIew *string) {\n\to.ContentTypesIew = contentTypesIew\n}", "func (o *TradingTableSubscribeTradingTableParams) SetContentType(contentType string) {\n\to.ContentType = contentType\n}", "func (_BaseContent *BaseContentFilterer) FilterSetContentType(opts *bind.FilterOpts) (*BaseContentSetContentTypeIterator, error) {\n\n\tlogs, sub, err := _BaseContent.contract.FilterLogs(opts, \"SetContentType\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseContentSetContentTypeIterator{contract: _BaseContent.contract, event: \"SetContentType\", logs: logs, sub: sub}, nil\n}", "func (h *ResponseHeader) SetContentType(contentType string) {\n\th.contentType = append(h.contentType[:0], contentType...)\n}", "func (req *Request) SetContentType(val string) {\n\treq.contentType = val\n}", "func (gau *GithubAssetUpdate) SetContentType(s string) *GithubAssetUpdate {\n\tgau.mutation.SetContentType(s)\n\treturn gau\n}", "func (o *ExtrasSavedFiltersListParams) WithContentTypesIe(contentTypesIe *string) *ExtrasSavedFiltersListParams {\n\to.SetContentTypesIe(contentTypesIe)\n\treturn o\n}", "func (m *SiteItemRequestBuilder) ContentTypesById(id string)(*ItemContentTypesContentTypeItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"contentType%2Did\"] = id\n }\n return NewItemContentTypesContentTypeItemRequestBuilderInternal(urlTplParams, m.requestAdapter)\n}", "func (d *cephobject) MigrationTypes(contentType ContentType, refresh bool, copySnapshots bool) []migration.Type {\n\treturn nil\n}", "func (o *PostApplyManifestParams) SetContentType(contentType string) {\n\to.ContentType = contentType\n}", "func (o *ExtrasSavedFiltersListParams) WithContentTypesNisw(contentTypesNisw *string) *ExtrasSavedFiltersListParams {\n\to.SetContentTypesNisw(contentTypesNisw)\n\treturn o\n}", "func (o *ExtrasSavedFiltersListParams) WithContentTypesIc(contentTypesIc *string) *ExtrasSavedFiltersListParams {\n\to.SetContentTypesIc(contentTypesIc)\n\treturn o\n}", "func (s *CreateSubscriberInput) SetAccessTypes(v []*string) *CreateSubscriberInput {\n\ts.AccessTypes = v\n\treturn s\n}", "func (r *Request) SetContentType() *Request {\n\tif nil != r.err {\n\t\treturn r\n\t}\n\tr.contentTypeFlag = true\n\treturn r\n}", "func (m *AttachmentItem) SetContentType(value *string)() {\n m.contentType = value\n}", "func (ctx *Context) SetContentType(contentType string) {\n\tctx.AddHeader(HeaderContentType, contentType)\n}", "func (s *SubscriberResource) SetAccessTypes(v []*string) *SubscriberResource {\n\ts.AccessTypes = v\n\treturn s\n}", "func (gauo *GithubAssetUpdateOne) SetContentType(s string) *GithubAssetUpdateOne {\n\tgauo.mutation.SetContentType(s)\n\treturn gauo\n}", "func (b *HTTPCompressionPolicyApplyConfiguration) WithMimeTypes(values ...v1.CompressionMIMEType) *HTTPCompressionPolicyApplyConfiguration {\n\tfor i := range values {\n\t\tb.MimeTypes = append(b.MimeTypes, values[i])\n\t}\n\treturn b\n}", "func (o *ExtrasSavedFiltersListParams) WithContentTypesNiew(contentTypesNiew *string) *ExtrasSavedFiltersListParams {\n\to.SetContentTypesNiew(contentTypesNiew)\n\treturn o\n}", "func (b *builder) SetQuotaTypes(quotaTypes map[string]*quota.Type) {\n\tb.quotaTypes = quotaTypes\n}", "func (h *RequestHeader) SetContentType(contentType string) {\n\th.contentType = append(h.contentType[:0], contentType...)\n}", "func SetContentTypeHeader(w http.ResponseWriter, filePath string) {\n\tw.Header().Set(\n\t\t\"Content-Type\",\n\t\tcontentTypes[strings.ToLower(path.Ext(filePath))],\n\t)\n}", "func (o *TradingTableUnsubscribeTradingTableParams) SetContentType(contentType string) {\n\to.ContentType = contentType\n}", "func (o *GetContentSourcesUsingGETParams) SetTypeIds(typeIds []string) {\n\to.TypeIds = typeIds\n}", "func (c *Action) SetContentType(val string) string {\n\tvar ctype string\n\tif strings.ContainsRune(val, '/') {\n\t\tctype = val\n\t} else {\n\t\tif !strings.HasPrefix(val, \".\") {\n\t\t\tval = \".\" + val\n\t\t}\n\t\tctype = mime.TypeByExtension(val)\n\t}\n\tif ctype != \"\" {\n\t\tc.SetHeader(\"Content-Type\", ctype)\n\t}\n\treturn ctype\n}", "func (m *WorkbookCommentReply) SetContentType(value *string)() {\n m.contentType = value\n}", "func (*AccountSetContentSettingsRequest) TypeName() string {\n\treturn \"account.setContentSettings\"\n}", "func (o *FiltersVirtualGateway) SetConnectionTypes(v []string) {\n\to.ConnectionTypes = &v\n}", "func (d *ceph) MigrationTypes(contentType ContentType, refresh bool, copySnapshots bool) []migration.Type {\n\tvar rsyncFeatures []string\n\n\t// Do not pass compression argument to rsync if the associated\n\t// config key, that is rsync.compression, is set to false.\n\tif shared.IsFalse(d.Config()[\"rsync.compression\"]) {\n\t\trsyncFeatures = []string{\"xattrs\", \"delete\", \"bidirectional\"}\n\t} else {\n\t\trsyncFeatures = []string{\"xattrs\", \"delete\", \"compress\", \"bidirectional\"}\n\t}\n\n\tif refresh {\n\t\tvar transportType migration.MigrationFSType\n\n\t\tif IsContentBlock(contentType) {\n\t\t\ttransportType = migration.MigrationFSType_BLOCK_AND_RSYNC\n\t\t} else {\n\t\t\ttransportType = migration.MigrationFSType_RSYNC\n\t\t}\n\n\t\treturn []migration.Type{\n\t\t\t{\n\t\t\t\tFSType: transportType,\n\t\t\t\tFeatures: rsyncFeatures,\n\t\t\t},\n\t\t}\n\t}\n\n\tif contentType == ContentTypeBlock {\n\t\treturn []migration.Type{\n\t\t\t{\n\t\t\t\tFSType: migration.MigrationFSType_RBD,\n\t\t\t},\n\t\t\t{\n\t\t\t\tFSType: migration.MigrationFSType_BLOCK_AND_RSYNC,\n\t\t\t\tFeatures: rsyncFeatures,\n\t\t\t},\n\t\t}\n\t}\n\n\treturn []migration.Type{\n\t\t{\n\t\t\tFSType: migration.MigrationFSType_RBD,\n\t\t},\n\t\t{\n\t\t\tFSType: migration.MigrationFSType_RSYNC,\n\t\t\tFeatures: rsyncFeatures,\n\t\t},\n\t}\n}", "func (_options *ToneOptions) SetContentType(contentType string) *ToneOptions {\n\t_options.ContentType = core.StringPtr(contentType)\n\treturn _options\n}", "func UtteranceContentType_Values() []string {\n\treturn []string{\n\t\tUtteranceContentTypePlainText,\n\t\tUtteranceContentTypeCustomPayload,\n\t\tUtteranceContentTypeSsml,\n\t\tUtteranceContentTypeImageResponseCard,\n\t}\n}", "func (o *GetAOrderStatusParams) SetContentType(contentType string) {\n\to.ContentType = contentType\n}" ]
[ "0.8701873", "0.81465465", "0.7151172", "0.70922256", "0.67580223", "0.6733916", "0.672834", "0.6628651", "0.65903586", "0.6576717", "0.6566702", "0.64906377", "0.64708567", "0.64687985", "0.643722", "0.63983715", "0.634481", "0.59890896", "0.59173846", "0.5863382", "0.5862911", "0.57626194", "0.5745951", "0.5733736", "0.57226926", "0.56553864", "0.5624121", "0.562204", "0.5612955", "0.5606856", "0.5573394", "0.5566497", "0.55468655", "0.54874617", "0.5485388", "0.5481515", "0.54725456", "0.5465591", "0.54609114", "0.5429692", "0.54262304", "0.5413263", "0.5403812", "0.5398439", "0.5366545", "0.53573436", "0.53433675", "0.5329195", "0.5326385", "0.52792764", "0.5263121", "0.5255185", "0.52521235", "0.52346903", "0.52256525", "0.52218", "0.5215369", "0.51991206", "0.5196988", "0.51804906", "0.5170642", "0.5156085", "0.51348734", "0.51036084", "0.50974077", "0.5094694", "0.50919586", "0.5081819", "0.50776154", "0.50771654", "0.50769913", "0.5034279", "0.503035", "0.5028191", "0.50190395", "0.50155103", "0.5011351", "0.49837467", "0.497627", "0.4974733", "0.49711138", "0.49677294", "0.4965642", "0.4954936", "0.49525303", "0.49462107", "0.49346215", "0.4908835", "0.48975497", "0.48935467", "0.4873314", "0.48638344", "0.48471776", "0.48443124", "0.48352396", "0.48325044", "0.48256606", "0.48242357", "0.4823492", "0.48116872" ]
0.82240343
1
SetDisplayName sets the displayName property value. The displayable title of the list.
func (m *List) SetDisplayName(value *string)() { m.displayName = value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *ListNodesParams) SetDisplayName(displayName *string) {\n\to.DisplayName = displayName\n}", "func (o *DeviceClient) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (o *SchemaDefinitionRestDto) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (o *AdminSearchUsersV2Params) SetDisplayName(displayName *string) {\n\to.DisplayName = displayName\n}", "func (o *RoleAssignment) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (o *Tier) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (o *RoleWithAccess) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (s *Trial) SetDisplayName(v string) *Trial {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s UserSet) SetDisplayName(value string) {\n\ts.RecordCollection.Set(models.NewFieldName(\"DisplayName\", \"display_name\"), value)\n}", "func (o *MicrosoftGraphModifiedProperty) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (o *User) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (o *User) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (s *Experiment) SetDisplayName(v string) *Experiment {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *ServiceTemplate) SetDisplayName(v string) *ServiceTemplate {\n\ts.DisplayName = &v\n\treturn s\n}", "func (o *MailFolder) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (u *User) SetDisplayName(v string) *User {\n\tu.displayName = strings.TrimSpace(v)\n\treturn u\n}", "func (s *EnvironmentTemplate) SetDisplayName(v string) *EnvironmentTemplate {\n\ts.DisplayName = &v\n\treturn s\n}", "func (o *MicrosoftGraphAppIdentity) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (s *UpdateServiceTemplateInput) SetDisplayName(v string) *UpdateServiceTemplateInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *UpdateEnvironmentTemplateInput) SetDisplayName(v string) *UpdateEnvironmentTemplateInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (o *MicrosoftGraphMailSearchFolder) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (o *MicrosoftGraphEducationSchool) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (uuo *UserUpdateOne) SetDisplayName(s string) *UserUpdateOne {\n\tuuo.mutation.SetDisplayName(s)\n\treturn uuo\n}", "func (s *UpdateExperimentInput) SetDisplayName(v string) *UpdateExperimentInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *ParticipantDetails) SetDisplayName(v string) *ParticipantDetails {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *UpdateTrialInput) SetDisplayName(v string) *UpdateTrialInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (o *MicrosoftGraphSharedPcConfiguration) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (s *Portal) SetDisplayName(v string) *Portal {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *PropertyDefinitionResponse) SetDisplayName(v string) *PropertyDefinitionResponse {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *UpdateIpAccessSettingsInput) SetDisplayName(v string) *UpdateIpAccessSettingsInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *CreateEnvironmentTemplateInput) SetDisplayName(v string) *CreateEnvironmentTemplateInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *CreateServiceTemplateInput) SetDisplayName(v string) *CreateServiceTemplateInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *PropertyDefinitionRequest) SetDisplayName(v string) *PropertyDefinitionRequest {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *IpAccessSettings) SetDisplayName(v string) *IpAccessSettings {\n\ts.DisplayName = &v\n\treturn s\n}", "func (o *MicrosoftGraphEducationUser) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (s *CreateExperimentInput) SetDisplayName(v string) *CreateExperimentInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (m *WorkforceIntegration) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (s *UpdateTrialComponentInput) SetDisplayName(v string) *UpdateTrialComponentInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *ExperimentSummary) SetDisplayName(v string) *ExperimentSummary {\n\ts.DisplayName = &v\n\treturn s\n}", "func (uu *UserUpdate) SetDisplayName(s string) *UserUpdate {\n\tuu.mutation.SetDisplayName(s)\n\treturn uu\n}", "func (m *UserMutation) SetDisplayName(s string) {\n\tm.display_name = &s\n}", "func (s *DescribeLineageGroupOutput) SetDisplayName(v string) *DescribeLineageGroupOutput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *CreateIpAccessSettingsInput) SetDisplayName(v string) *CreateIpAccessSettingsInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *UpdatePortalInput) SetDisplayName(v string) *UpdatePortalInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *ServiceTemplateSummary) SetDisplayName(v string) *ServiceTemplateSummary {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *TrialSummary) SetDisplayName(v string) *TrialSummary {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *TrialComponent) SetDisplayName(v string) *TrialComponent {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *ParticipantDetailsToAdd) SetDisplayName(v string) *ParticipantDetailsToAdd {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *UpdateImageInput) SetDisplayName(v string) *UpdateImageInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *DescribeTrialOutput) SetDisplayName(v string) *DescribeTrialOutput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *CreateTrialInput) SetDisplayName(v string) *CreateTrialInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *EnvironmentTemplateSummary) SetDisplayName(v string) *EnvironmentTemplateSummary {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *LineageGroupSummary) SetDisplayName(v string) *LineageGroupSummary {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *IpAccessSettingsSummary) SetDisplayName(v string) *IpAccessSettingsSummary {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *DescribeExperimentOutput) SetDisplayName(v string) *DescribeExperimentOutput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *DescribeTrialComponentOutput) SetDisplayName(v string) *DescribeTrialComponentOutput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *TrialComponentSummary) SetDisplayName(v string) *TrialComponentSummary {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *KernelSpec) SetDisplayName(v string) *KernelSpec {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *CreateTrialComponentInput) SetDisplayName(v string) *CreateTrialComponentInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (uc *UserCreate) SetDisplayName(s string) *UserCreate {\n\tuc.mutation.SetDisplayName(s)\n\treturn uc\n}", "func (m *IdentityUserFlowAttributeAssignment) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (o *MicrosoftGraphWindows10CompliancePolicy) SetDisplayName(v string) {\n\to.DisplayName = &v\n}", "func (m *RemoteAssistancePartner) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (s *CreatePortalInput) SetDisplayName(v string) *CreatePortalInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *CreateImageInput) SetDisplayName(v string) *CreateImageInput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *PortalSummary) SetDisplayName(v string) *PortalSummary {\n\ts.DisplayName = &v\n\treturn s\n}", "func (s *Image) SetDisplayName(v string) *Image {\n\ts.DisplayName = &v\n\treturn s\n}", "func (m *RoleDefinition) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (m *AccessPackageCatalog) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (s *DescribeImageOutput) SetDisplayName(v string) *DescribeImageOutput {\n\ts.DisplayName = &v\n\treturn s\n}", "func (m *DeviceAndAppManagementAssignmentFilter) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *BrowserSiteList) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (d UserData) SetDisplayName(value string) m.UserData {\n\td.ModelData.Set(models.NewFieldName(\"DisplayName\", \"display_name\"), value)\n\treturn d\n}", "func (m *EducationAssignment) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (m *AccessPackage) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (m *IdentityProviderBase) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (m *User) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (m *ManagedAppPolicy) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (m *Group) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (m *TelecomExpenseManagementPartner) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *MessageRule) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (m *NamedLocation) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (m *Application) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (m *CreatePostRequestBody) SetDisplayName(value *string)() {\n m.displayName = value\n}", "func (m *IndustryDataRunActivity) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *DeviceCategory) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *TeamworkTag) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *DeviceManagementConfigurationSettingDefinition) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Setting) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *RelatedContact) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *BookingNamedEntity) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *ConditionalAccessPolicy) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *CloudPcConnection) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *PrintConnector) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *GroupPolicyDefinition) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *ProfileCardAnnotation) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *ManagementTemplateStep) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *CloudPcAuditEvent) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *DirectorySetting) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *MacOSSoftwareUpdateStateSummary) SetDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"displayName\", value)\n if err != nil {\n panic(err)\n }\n}" ]
[ "0.818561", "0.81110734", "0.8035491", "0.8012668", "0.79528517", "0.79295033", "0.7925276", "0.79108095", "0.7909268", "0.7899301", "0.7893911", "0.7893911", "0.78925425", "0.7877846", "0.7862184", "0.7839893", "0.7839308", "0.7833375", "0.7833274", "0.7830437", "0.78302985", "0.7824427", "0.78243846", "0.78216535", "0.78069395", "0.77854705", "0.77814186", "0.77715284", "0.77702564", "0.77651507", "0.7763112", "0.7762957", "0.7755017", "0.77498406", "0.7748326", "0.77465534", "0.7746457", "0.7746269", "0.7744402", "0.774262", "0.7739389", "0.77340734", "0.77242583", "0.77233243", "0.77226615", "0.77186614", "0.7715423", "0.77076304", "0.7701248", "0.77005035", "0.76976484", "0.7693083", "0.7689645", "0.7683804", "0.76836795", "0.7674185", "0.76662415", "0.7658768", "0.7653017", "0.7652223", "0.7648784", "0.7648554", "0.76343197", "0.76282465", "0.7621786", "0.7605333", "0.7603247", "0.7585185", "0.75384253", "0.752428", "0.74493927", "0.7446598", "0.7444605", "0.7435751", "0.7407117", "0.73957366", "0.73943746", "0.73864925", "0.7351041", "0.7343556", "0.73217964", "0.7320749", "0.73206896", "0.7260955", "0.7245047", "0.72427034", "0.7128426", "0.7121496", "0.7088923", "0.7086111", "0.69818145", "0.69817615", "0.6972566", "0.6951328", "0.69478816", "0.69406456", "0.68876535", "0.6886485", "0.68785805", "0.68012965" ]
0.8070391
2
SetDrive sets the drive property value. Only present on document libraries. Allows access to the list as a [drive][] resource with [driveItems][driveItem].
func (m *List) SetDrive(value Driveable)() { m.drive = value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Group) SetDrive(value Driveable)() {\n m.drive = value\n}", "func (m *User) SetDrive(value Driveable)() {\n m.drive = value\n}", "func (o *User) SetDrive(v AnyOfmicrosoftGraphDrive) {\n\to.Drive = &v\n}", "func (o *User) SetDrive(v Drive) {\n\to.Drive = &v\n}", "func (m *Drive) SetDriveType(value *string)() {\n m.driveType = value\n}", "func (m *User) SetDrives(value []Driveable)() {\n m.drives = value\n}", "func (m *Group) SetDrives(value []Driveable)() {\n m.drives = value\n}", "func (h *stubDriveHandler) SetDrives(offset int64, d []models.Drive) {\n\th.drives = d\n\th.stubDriveIndex = offset\n}", "func (device *DCV2Bricklet) SetDriveMode(mode DriveMode) (err error) {\n\tvar buf bytes.Buffer\n\tbinary.Write(&buf, binary.LittleEndian, mode)\n\n\tresultBytes, err := device.device.Set(uint8(FunctionSetDriveMode), buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(resultBytes) > 0 {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(resultBytes)\n\n\t\tif header.Length != 8 {\n\t\t\treturn fmt.Errorf(\"Received packet of unexpected size %d, instead of %d\", header.Length, 8)\n\t\t}\n\n\t\tif header.ErrorCode != 0 {\n\t\t\treturn DeviceError(header.ErrorCode)\n\t\t}\n\n\t\tbytes.NewBuffer(resultBytes[8:])\n\n\t}\n\n\treturn nil\n}", "func (o *VirtualizationIweClusterAllOf) SetDriveType(v string) {\n\to.DriveType = &v\n}", "func (o *StorageFlexUtilVirtualDrive) SetDriveType(v string) {\n\to.DriveType = &v\n}", "func (repo Repository) Drive(driveID resource.ID) drivestream.DriveReference {\n\treturn Drive{\n\t\tdb: repo.db,\n\t\tdrive: driveID,\n\t}\n}", "func (m *GraphBaseServiceClient) Drive()(*i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.DriveRequestBuilder) {\n return i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.NewDriveRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Drive()(*i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.DriveRequestBuilder) {\n return i926bd489c52af20f44aacc8a450bb0a062290f1d1e44c2fe78d6cc1595c12524.NewDriveRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (o *MicrosoftGraphListItem) SetDriveItem(v AnyOfmicrosoftGraphDriveItem) {\n\to.DriveItem = &v\n}", "func (o *MicrosoftGraphItemReference) SetDriveType(v string) {\n\to.DriveType = &v\n}", "func (o *StoragePhysicalDisk) SetDriveFirmware(v string) {\n\to.DriveFirmware = &v\n}", "func (ref FileView) Drive() resource.ID {\n\treturn ref.drive\n}", "func NewDrive()(*Drive) {\n m := &Drive{\n BaseItem: *NewBaseItem(),\n }\n odataTypeValue := \"#microsoft.graph.drive\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func (o *StoragePhysicalDiskAllOf) SetDriveFirmware(v string) {\n\to.DriveFirmware = &v\n}", "func (o *StoragePhysicalDisk) SetDriveState(v string) {\n\to.DriveState = &v\n}", "func WatchDrive(client *Client, env *util.Env) {\n\tpull := func() {\n\t\tUpdateMenu(client, env)\n\t}\n\tutil.SetInterval(pull, time.Duration(env.CFG.Frequency)*time.Millisecond)\n\tpull()\n}", "func (m *List) GetDrive()(Driveable) {\n return m.drive\n}", "func (o *StorageFlexFlashVirtualDrive) SetDriveScope(v string) {\n\to.DriveScope = &v\n}", "func (o *StoragePhysicalDiskAllOf) SetDriveState(v string) {\n\to.DriveState = &v\n}", "func NewDrive(object dbus.BusObject) *Drive {\n\treturn &Drive{object}\n}", "func (m *Machine) attachDrive(ctx context.Context, dev models.Drive) error {\n\thostPath := StringValue(dev.PathOnHost)\n\tm.logger.Infof(\"Attaching drive %s, slot %s, root %t.\", hostPath, StringValue(dev.DriveID), BoolValue(dev.IsRootDevice))\n\trespNoContent, err := m.client.PutGuestDriveByID(ctx, StringValue(dev.DriveID), &dev)\n\tif err == nil {\n\t\tm.logger.Printf(\"Attached drive %s: %s\", hostPath, respNoContent.Error())\n\t} else {\n\t\tm.logger.Errorf(\"Attach drive failed: %s: %s\", hostPath, err)\n\t}\n\treturn err\n}", "func ExportDrive(conn *dbus.Conn, path dbus.ObjectPath, v Driveer) error {\n\treturn conn.ExportSubtreeMethodTable(map[string]interface{}{\n\t\t\"Eject\": v.Eject,\n\t\t\"SetConfiguration\": v.SetConfiguration,\n\t\t\"PowerOff\": v.PowerOff,\n\t}, path, InterfaceDrive)\n}", "func (o *User) SetDrives(v []MicrosoftGraphDrive) {\n\to.Drives = &v\n}", "func (m *Drive) SetList(value Listable)() {\n m.list = value\n}", "func (o *User) SetDrives(v []Drive) {\n\to.Drives = v\n}", "func (o *MicrosoftGraphItemReference) SetDriveId(v string) {\n\to.DriveId = &v\n}", "func (r ApiUpdateHyperflexDriveRequest) HyperflexDrive(hyperflexDrive HyperflexDrive) ApiUpdateHyperflexDriveRequest {\n\tr.hyperflexDrive = &hyperflexDrive\n\treturn r\n}", "func (m *Drive) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.BaseItem.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetBundles() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetBundles())\n err = writer.WriteCollectionOfObjectValues(\"bundles\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"driveType\", m.GetDriveType())\n if err != nil {\n return err\n }\n }\n if m.GetFollowing() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetFollowing())\n err = writer.WriteCollectionOfObjectValues(\"following\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetItems() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetItems())\n err = writer.WriteCollectionOfObjectValues(\"items\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"list\", m.GetList())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"owner\", m.GetOwner())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"quota\", m.GetQuota())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"root\", m.GetRoot())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"sharePointIds\", m.GetSharePointIds())\n if err != nil {\n return err\n }\n }\n if m.GetSpecial() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSpecial())\n err = writer.WriteCollectionOfObjectValues(\"special\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"system\", m.GetSystem())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (r ApiPatchHyperflexDriveRequest) HyperflexDrive(hyperflexDrive HyperflexDrive) ApiPatchHyperflexDriveRequest {\n\tr.hyperflexDrive = &hyperflexDrive\n\treturn r\n}", "func (m *SiteItemRequestBuilder) Drive()(*ItemDriveRequestBuilder) {\n return NewItemDriveRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func (m *Drive) SetRoot(value DriveItemable)() {\n m.root = value\n}", "func (o *Block) GetDrive(ctx context.Context) (drive dbus.ObjectPath, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceBlock, \"Drive\").Store(&drive)\n\treturn\n}", "func (m *Drive) SetItems(value []DriveItemable)() {\n m.items = value\n}", "func (o *StorageFlexUtilVirtualDrive) SetDriveStatus(v string) {\n\to.DriveStatus = &v\n}", "func (ref *Config) SetPartition(val int32) {\n\tref.Partition = val\n}", "func (o *StorageFlexFlashVirtualDrive) SetDriveStatus(v string) {\n\to.DriveStatus = &v\n}", "func (m *ItemSitesSiteItemRequestBuilder) Drive()(*ItemSitesItemDriveRequestBuilder) {\n return NewItemSitesItemDriveRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (s *BasicStore) SetRobot(r *Robot) {\n\ts.Robot = r\n}", "func Drive(driveS *drive.Service, callArgs *[]string, driveRoot *string, localList *[]string, driveList *map[string]string) error {\r\n\r\n\tfor i := range *localList {\r\n\r\n\t\t//open file\r\n\t\tfLink, err := os.Open((*localList)[i])\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\r\n\t\t//trims file location to include target folder\r\n\t\ttempIn := strings.LastIndex((*callArgs)[2], (*callArgs)[0])\r\n\t\ttempName := (*callArgs)[2][:tempIn]\r\n\r\n\t\t//C:\\Users\\game_game\\go gets cut out leaving \\test\\level two\\level two - two\r\n\t\t//cuts off entry text to only get part we care about\r\n\t\t//mapName name of the to-be map\r\n\t\ttempPath := strings.Replace((*localList)[i], tempName, \"\", 1)\r\n\t\tfmt.Println(tempPath)\r\n\r\n\t\t//finds last slash to get map name\r\n\t\t//map name is called from driveList to get parent id\r\n\t\t//parent id ex driveList[mapName]\r\n\t\ttempIn = strings.LastIndex(tempPath, (*callArgs)[0])\r\n\t\tmapName := tempPath[:tempIn]\r\n\r\n\t\t//gets relative file path - split counts the other side of a slash ex \\foo is length two\r\n\t\t//folder & file length\r\n\t\ttempLen := len(strings.Split(tempPath, (*callArgs)[0]))\r\n\r\n\t\t//gets stats\r\n\t\tfStat, err := fLink.Stat()\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\r\n\t\tswitch {\r\n\r\n\t\t//Seems like a sitched together thing, but the slash causes issues with split\r\n\t\t//resulting in \\foo always being two and \\foo\\whatever being three\r\n\t\t//however, there needs to be slash as this is necessary for building the internal folder tree\r\n\t\tcase fStat.IsDir() && tempLen == 2:\r\n\t\t\terr := driveFolder(driveS, callArgs, *driveRoot, fStat.Name(), tempPath, driveList)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t\tfLink.Close()\r\n\t\t\tcontinue\r\n\r\n\t\t\t//this is here in case a single file is uploaded\r\n\t\tcase !fStat.IsDir() && tempLen == 2:\r\n\t\t\terr := driveFile(driveS, callArgs, *driveRoot, fStat.Name(), fLink)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t\tcontinue\r\n\r\n\t\tcase fStat.IsDir() && tempLen > 2:\r\n\t\t\terr := driveFolder(driveS, callArgs, (*driveList)[mapName], fStat.Name(), tempPath, driveList)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t\tfLink.Close()\r\n\t\t\tcontinue\r\n\r\n\t\tcase !fStat.IsDir() && tempLen > 2:\r\n\t\t\terr := driveFile(driveS, callArgs, (*driveList)[mapName], fStat.Name(), fLink)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t}\r\n\r\n\treturn nil\r\n\r\n}", "func Drive(car Car) Car {\n\tpanic(\"Please implement the Drive function\")\n}", "func (howtoplay *howtoplay) Drive() {\n\tif howtoplay.nextScene != nil {\n\t\tsimra.GetInstance().SetScene(howtoplay.nextScene)\n\t}\n}", "func (h *stubDriveHandler) InDriveSet(path string) bool {\n\tfor _, d := range h.GetDrives() {\n\t\tif firecracker.StringValue(d.PathOnHost) == path {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (computersystem *ComputerSystem) SetBoot(b Boot) error { //nolint\n\tt := struct {\n\t\tBoot Boot\n\t}{Boot: b}\n\treturn computersystem.Patch(computersystem.ODataID, t)\n}", "func (c *FakePortalDocumentClient) SetSorter(sorter func([]*pkg.PortalDocument)) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tc.sorter = sorter\n}", "func (c *CmdReal) SetDir(dir string) {\n\tc.cmd.Dir = dir\n}", "func (o *User) GetDrive() AnyOfmicrosoftGraphDrive {\n\tif o == nil || o.Drive == nil {\n\t\tvar ret AnyOfmicrosoftGraphDrive\n\t\treturn ret\n\t}\n\treturn *o.Drive\n}", "func (o *StorageFlexUtilVirtualDrive) SetVirtualDrive(v string) {\n\to.VirtualDrive = &v\n}", "func (m *User) GetDrive()(Driveable) {\n return m.drive\n}", "func (m *SynchronizationSchema) SetDirectories(value []DirectoryDefinitionable)() {\n err := m.GetBackingStore().Set(\"directories\", value)\n if err != nil {\n panic(err)\n }\n}", "func (t *Title) Drive() {\n\tselect {\n\tcase <-t.sceneChangeCh:\n\t\tt.simra.SetScene(&Game{})\n\tdefault:\n\t\t// nop\n\t}\n}", "func OpenDrive() *OpenDriveOptions {\n\treturn &OpenDriveOptions{}\n}", "func (o *StorageAPI) SetSpec(spec *loads.Document) {\n\to.spec = spec\n}", "func (m *Drive) SetSystem(value SystemFacetable)() {\n m.system = value\n}", "func (o *User) GetDrive() Drive {\n\tif o == nil || o.Drive == nil {\n\t\tvar ret Drive\n\t\treturn ret\n\t}\n\treturn *o.Drive\n}", "func (o *StorageFlexUtilVirtualDrive) GetDriveType() string {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveType\n}", "func (g Graph) CreateDrive(w http.ResponseWriter, r *http.Request) {\n\tus, ok := ctxpkg.ContextGetUser(r.Context())\n\tif !ok {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusUnauthorized, \"invalid user\")\n\t\treturn\n\t}\n\n\t// TODO determine if the user tries to create his own personal space and pass that as a boolean\n\tif !canCreateSpace(r.Context(), false) {\n\t\t// if the permission is not existing for the user in context we can assume we don't have it. Return 401.\n\t\terrorcode.GeneralException.Render(w, r, http.StatusUnauthorized, \"insufficient permissions to create a space.\")\n\t\treturn\n\t}\n\n\tclient := g.GetGatewayClient()\n\tdrive := libregraph.Drive{}\n\tif err := json.NewDecoder(r.Body).Decode(&drive); err != nil {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusBadRequest, \"invalid schema definition\")\n\t\treturn\n\t}\n\tspaceName := *drive.Name\n\tif spaceName == \"\" {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, \"invalid name\")\n\t\treturn\n\t}\n\n\tvar driveType string\n\tif drive.DriveType != nil {\n\t\tdriveType = *drive.DriveType\n\t}\n\tswitch driveType {\n\tcase \"\", \"project\":\n\t\tdriveType = \"project\"\n\tdefault:\n\t\terrorcode.GeneralException.Render(w, r, http.StatusBadRequest, fmt.Sprintf(\"drives of type %s cannot be created via this api\", driveType))\n\t\treturn\n\t}\n\n\tcsr := storageprovider.CreateStorageSpaceRequest{\n\t\tOwner: us,\n\t\tType: driveType,\n\t\tName: spaceName,\n\t\tQuota: getQuota(drive.Quota, g.config.Spaces.DefaultQuota),\n\t}\n\n\tif drive.Description != nil {\n\t\tcsr.Opaque = utils.AppendPlainToOpaque(csr.Opaque, \"description\", *drive.Description)\n\t}\n\n\tif drive.DriveAlias != nil {\n\t\tcsr.Opaque = utils.AppendPlainToOpaque(csr.Opaque, \"spaceAlias\", *drive.DriveAlias)\n\t}\n\n\tresp, err := client.CreateStorageSpace(r.Context(), &csr)\n\tif err != nil {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tif resp.GetStatus().GetCode() != cs3rpc.Code_CODE_OK {\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, \"\")\n\t\treturn\n\t}\n\n\twdu, err := url.Parse(g.config.Spaces.WebDavBase + g.config.Spaces.WebDavPath)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error parsing url\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tnewDrive, err := g.cs3StorageSpaceToDrive(r.Context(), wdu, resp.StorageSpace)\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"error parsing space\")\n\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\trender.Status(r, http.StatusCreated)\n\trender.JSON(w, r, newDrive)\n}", "func (m *Group) GetDrive()(Driveable) {\n return m.drive\n}", "func (o *User) SetDriveExplicitNull(b bool) {\n\to.Drive = nil\n\to.isExplicitNullDrive = b\n}", "func (m *Drive) SetFollowing(value []DriveItemable)() {\n m.following = value\n}", "func (me *TxsdRedefineTimeSyncTokenTypeComplexContentRestrictionDeviceType) Set(s string) {\n\t(*sac.TDeviceTypeType)(me).Set(s)\n}", "func (o *StorageFlexFlashVirtualDrive) SetVirtualDrive(v string) {\n\to.VirtualDrive = &v\n}", "func (c *Client) SetBootDevice(ctx context.Context, bootDevice string, setPersistent, efiBoot bool) (ok bool, err error) {\n\tok, metadata, err := bmc.SetBootDeviceFromInterfaces(ctx, bootDevice, setPersistent, efiBoot, c.Registry.GetDriverInterfaces())\n\tc.setMetadata(metadata)\n\treturn ok, err\n}", "func (c *Client) SetDir(prefix, name string) {\n\tc.Lock()\n\tc.dir = &models.Directory{\n\t\tBase: fmt.Sprintf(\"%v/%v\", prefix, name),\n\t\tElection: fmt.Sprintf(\"%v/%v/%v\", prefix, name, DirectoryElection),\n\t\tRunning: fmt.Sprintf(\"%v/%v/%v\", prefix, name, DirectoryRunning),\n\t\tQueue: fmt.Sprintf(\"%v/%v/%v\", prefix, name, DirectoryQueue),\n\t\tNodes: fmt.Sprintf(\"%v/%v/%v\", prefix, name, DirectoryNodes),\n\t\tMasters: fmt.Sprintf(\"%v/%v/%v\", prefix, name, DirectoryMasters),\n\t}\n\tc.Unlock()\n}", "func (d *Drive) setBrakeMode(brakeMode bool) {\n\t// Set brake mode on motors\n\tif d.brakeModeValid != true {\n\t\td.brakeModeValid = true\n\t\td.brakeMode = !brakeMode // This causes the next section to run\n\t}\n\tif brakeMode != d.brakeMode {\n\t\t// We need to actually set the motor's brake mode\n\t\tif brakeMode == true {\n\t\t\t// Hit the brakes\n\t\t\tMotor.EnableBrakeMode(d.leftMotor)\n\t\t\tMotor.EnableBrakeMode(d.rightMotor)\n\t\t} else {\n\t\t\t// Coast\n\t\t\tMotor.DisableBrakeMode(d.leftMotor)\n\t\t\tMotor.DisableBrakeMode(d.rightMotor)\n\t\t}\n\t\td.brakeMode = brakeMode\n\t} else {\n\t\t// Motor's brake mode already set to what we want, don't do anything\n\t}\n}", "func (h *stubDriveHandler) PatchStubDrive(ctx context.Context, client firecracker.MachineIface, pathOnHost string) (*string, error) {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\n\t// Check to see if stubDriveIndex has increased more than the drive amount.\n\tif h.stubDriveIndex >= int64(len(h.drives)) {\n\t\treturn nil, ErrDrivesExhausted\n\t}\n\n\td := h.drives[h.stubDriveIndex]\n\td.PathOnHost = &pathOnHost\n\n\tif d.DriveID == nil {\n\t\t// this should never happen, but we want to ensure that we never nil\n\t\t// dereference\n\t\treturn nil, ErrDriveIDNil\n\t}\n\n\th.drives[h.stubDriveIndex] = d\n\n\terr := client.UpdateGuestDrive(ctx, firecracker.StringValue(d.DriveID), pathOnHost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th.stubDriveIndex++\n\treturn d.DriveID, nil\n}", "func (c *Client) SetDriver(driver string) {\n\tc.driver = driver\n}", "func (o *DataPlaneAPI) SetSpec(spec *loads.Document) {\n\to.spec = spec\n}", "func (g *GitDriver) SetFilesystem(fs billy.Filesystem) {\n\tg.Filesystem = fs\n}", "func UnexportDrive(conn *dbus.Conn, path dbus.ObjectPath) error {\n\treturn conn.Export(nil, path, InterfaceDrive)\n}", "func (o *MicrosoftGraphItemReference) GetDriveType() string {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveType\n}", "func (o *Partition) SetFlags(ctx context.Context, flags uint64, options map[string]dbus.Variant) (err error) {\n\terr = o.object.CallWithContext(ctx, InterfacePartition+\".SetFlags\", 0, flags, options).Store()\n\treturn\n}", "func (a *HyperflexApiService) UpdateHyperflexDrive(ctx context.Context, moid string) ApiUpdateHyperflexDriveRequest {\n\treturn ApiUpdateHyperflexDriveRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (vuu *VacUserUpdate) SetPartition(s string) *VacUserUpdate {\n\tvuu.mutation.SetPartition(s)\n\treturn vuu\n}", "func (vuuo *VacUserUpdateOne) SetPartition(s string) *VacUserUpdateOne {\n\tvuuo.mutation.SetPartition(s)\n\treturn vuuo\n}", "func (o *MicrosoftGraphItemReference) SetDriveTypeExplicitNull(b bool) {\n\to.DriveType = nil\n\to.isExplicitNullDriveType = b\n}", "func (d Display) SetDriver(driver string) int {\n\treturn int(C.caca_set_display_driver(d.Dp, C.CString(driver)))\n}", "func (m *Machine) UpdateGuestDrive(ctx context.Context, driveID, pathOnHost string, opts ...PatchGuestDriveByIDOpt) error {\n\tif _, err := m.client.PatchGuestDriveByID(ctx, driveID, pathOnHost, opts...); err != nil {\n\t\tm.logger.Errorf(\"PatchGuestDrive failed: %v\", err)\n\t\treturn err\n\t}\n\n\tm.logger.Printf(\"PatchGuestDrive successful\")\n\treturn nil\n}", "func NewWebDAVDrive(ctx context.Context, config types.SM,\n\tutils drive_util.DriveUtils) (types.IDrive, error) {\n\tu := config[\"url\"]\n\tusername := config[\"username\"]\n\tpassword := config[\"password\"]\n\n\tcacheTtl := config.GetDuration(\"cache_ttl\", -1)\n\n\tu = strings.TrimRight(u, \"/\")\n\n\tuu, e := url.Parse(u)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tpathPrefix := uu.Path\n\n\tw := &WebDAVDrive{\n\t\tusername: username, password: password,\n\t\tcacheTTL: cacheTtl, pathPrefix: pathPrefix,\n\t}\n\n\tif cacheTtl <= 0 {\n\t\tw.cache = drive_util.DummyCache()\n\t} else {\n\t\tw.cache = utils.CreateCache(w.deserializeEntry, nil)\n\t}\n\n\tclient, e := req.NewClient(u, w.beforeRequest, w.afterRequest, &http.Client{})\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tw.c = client\n\n\t// check\n\t_, e = w.Get(ctx, \"/\")\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn w, nil\n}", "func (v *IADsNameTranslate) Set(adsPath string, setType uint32) (err error) {\n\treturn ole.NewError(ole.E_NOTIMPL)\n}", "func (o *VirtualizationIweClusterAllOf) GetDriveType() string {\n\tif o == nil || o.DriveType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DriveType\n}", "func (ref *Config) SetPartitioner(val string) {\n\tswitch val {\n\tdefault:\n\t\tref.Errorf(\"Invalid partitioner %s - defaulting to ''\", val)\n\t\tfallthrough\n\tcase \"\":\n\t\tif ref.Partition >= 0 {\n\t\t\tref.Partitioner = sarama.NewManualPartitioner\n\t\t} else {\n\t\t\tref.Partitioner = sarama.NewHashPartitioner\n\t\t}\n\tcase Hash:\n\t\tref.Partitioner = sarama.NewHashPartitioner\n\t\tref.Partition = -1\n\tcase Random:\n\t\tref.Partitioner = sarama.NewRandomPartitioner\n\t\tref.Partition = -1\n\tcase Manual:\n\t\tref.Partitioner = sarama.NewManualPartitioner\n\t\tif ref.Partition < 0 {\n\t\t\tref.Infof(\"Invalid partition %d - defaulting to 0\", ref.Partition)\n\t\t\tref.Partition = 0\n\t\t}\n\t}\n}", "func (v Vehicle) DriveState() (*DriveState, error) {\n\tstateRequest, err := fetchState(\"/drive_state\", v.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn stateRequest.Response.DriveState, nil\n}", "func (m *Drive) SetQuota(value Quotaable)() {\n m.quota = value\n}", "func SetBusiness(biz *types.Business) {\n\tif biz == nil {\n\t\tbiz = types.DefaultBusiness()\n\t} else {\n\t\tbiz.Init()\n\t}\n\tglobalBusiness = biz\n}", "func (o *CredentialProviderAPI) SetSpec(spec *loads.Document) {\n\to.spec = spec\n}", "func (o *WeaviateAPI) SetSpec(spec *loads.Document) {\n\to.spec = spec\n}", "func (c *CmdReal) SetPath(path string) {\n\tc.cmd.Path = path\n}", "func (o *OpenDriveOptions) SetDirectory(dir string) *OpenDriveOptions {\n\tif len(dir) == 0 {\n\t\to.Directory = nil\n\t\treturn o\n\t}\n\to.Directory = &dir\n\treturn o\n}", "func (d *Driver) SetLed(idx int, r, c int, on bool) error {\n\tif err := d.checkIdx(idx); err != nil {\n\t\treturn err\n\t}\n\n\tbuffIdx := (idx-1)*d.Drivers + r\n\tval := byte(0x80) >> byte(c) // 0B10000000 >> c\n\n\tif on {\n\t\td.buff[buffIdx] |= val\n\t} else {\n\t\td.buff[buffIdx] &= ^val\n\n\t}\n\n\treturn nil\n}", "func (o *CloudTidesAPI) SetSpec(spec *loads.Document) {\n\to.spec = spec\n}", "func (m *SharepointIds) SetTenantId(value *string)() {\n err := m.GetBackingStore().Set(\"tenantId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (rb *ResourceBuilder) SetDeviceID(val string) {\n\tif rb.config.DeviceID.Enabled {\n\t\trb.res.Attributes().PutStr(\"device.id\", val)\n\t}\n}", "func (m *Win32LobAppFileSystemDetection) SetPath(value *string)() {\n err := m.GetBackingStore().Set(\"path\", value)\n if err != nil {\n panic(err)\n }\n}", "func (a *HyperflexApiService) PatchHyperflexDrive(ctx context.Context, moid string) ApiPatchHyperflexDriveRequest {\n\treturn ApiPatchHyperflexDriveRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}" ]
[ "0.7992977", "0.78732735", "0.7630548", "0.7536296", "0.69157124", "0.6463099", "0.6364722", "0.62700015", "0.6150766", "0.5855303", "0.5782538", "0.57769513", "0.5764786", "0.5764786", "0.57268894", "0.57063174", "0.56432295", "0.55852723", "0.5579085", "0.55205274", "0.5448137", "0.54276675", "0.5421545", "0.5403223", "0.53710896", "0.52889085", "0.52362806", "0.52357626", "0.5211051", "0.5204756", "0.51860315", "0.51611847", "0.5160898", "0.5114724", "0.50795776", "0.5075082", "0.5031512", "0.50270116", "0.49643332", "0.49365494", "0.49281955", "0.4906391", "0.48988026", "0.4856782", "0.48214325", "0.47900835", "0.47858056", "0.47728047", "0.47574756", "0.4756179", "0.47557154", "0.47465056", "0.4744288", "0.47429535", "0.47424018", "0.47228742", "0.47104934", "0.469997", "0.46990734", "0.46905378", "0.46698764", "0.4664836", "0.46541014", "0.46515724", "0.46453363", "0.46316928", "0.46309662", "0.46201545", "0.4617068", "0.46139297", "0.46120286", "0.4609935", "0.4598056", "0.45882663", "0.45871094", "0.45440394", "0.45222646", "0.45199364", "0.45184693", "0.45180827", "0.45175377", "0.45119643", "0.44996482", "0.44973448", "0.4492858", "0.4492558", "0.44913524", "0.44891196", "0.44823483", "0.44611222", "0.44571468", "0.4450749", "0.4436335", "0.44347775", "0.44236732", "0.44187722", "0.44176713", "0.44162342", "0.44155672", "0.44059247" ]
0.8223476
0