repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
nats-io/nats-streaming-server | server/client.go | addSub | func (cs *clientStore) addSub(ID string, sub *subState) bool {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return false
}
c.Lock()
c.subs = append(c.subs, sub)
c.Unlock()
return true
} | go | func (cs *clientStore) addSub(ID string, sub *subState) bool {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return false
}
c.Lock()
c.subs = append(c.subs, sub)
c.Unlock()
return true
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"addSub",
"(",
"ID",
"string",
",",
"sub",
"*",
"subState",
")",
"bool",
"{",
"cs",
".",
"RLock",
"(",
")",
"\n",
"defer",
"cs",
".",
"RUnlock",
"(",
")",
"\n",
"c",
":=",
"cs",
".",
"clients",
"[",
"ID",
"]",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"c",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"subs",
"=",
"append",
"(",
"c",
".",
"subs",
",",
"sub",
")",
"\n",
"c",
".",
"Unlock",
"(",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // AddSub adds the subscription to the client identified by clientID
// and returns true only if the client has not been unregistered,
// otherwise returns false. | [
"AddSub",
"adds",
"the",
"subscription",
"to",
"the",
"client",
"identified",
"by",
"clientID",
"and",
"returns",
"true",
"only",
"if",
"the",
"client",
"has",
"not",
"been",
"unregistered",
"otherwise",
"returns",
"false",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L241-L252 | train |
nats-io/nats-streaming-server | server/client.go | removeSub | func (cs *clientStore) removeSub(ID string, sub *subState) bool {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return false
}
c.Lock()
removed := false
c.subs, removed = sub.deleteFromList(c.subs)
c.Unlock()
return removed
} | go | func (cs *clientStore) removeSub(ID string, sub *subState) bool {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return false
}
c.Lock()
removed := false
c.subs, removed = sub.deleteFromList(c.subs)
c.Unlock()
return removed
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"removeSub",
"(",
"ID",
"string",
",",
"sub",
"*",
"subState",
")",
"bool",
"{",
"cs",
".",
"RLock",
"(",
")",
"\n",
"defer",
"cs",
".",
"RUnlock",
"(",
")",
"\n",
"c",
":=",
"cs",
".",
"clients",
"[",
"ID",
"]",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"c",
".",
"Lock",
"(",
")",
"\n",
"removed",
":=",
"false",
"\n",
"c",
".",
"subs",
",",
"removed",
"=",
"sub",
".",
"deleteFromList",
"(",
"c",
".",
"subs",
")",
"\n",
"c",
".",
"Unlock",
"(",
")",
"\n",
"return",
"removed",
"\n",
"}"
] | // RemoveSub removes the subscription from the client identified by clientID
// and returns true only if the client has not been unregistered and that
// the subscription was found, otherwise returns false. | [
"RemoveSub",
"removes",
"the",
"subscription",
"from",
"the",
"client",
"identified",
"by",
"clientID",
"and",
"returns",
"true",
"only",
"if",
"the",
"client",
"has",
"not",
"been",
"unregistered",
"and",
"that",
"the",
"subscription",
"was",
"found",
"otherwise",
"returns",
"false",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L257-L269 | train |
nats-io/nats-streaming-server | server/client.go | recoverClients | func (cs *clientStore) recoverClients(clients []*stores.Client) {
cs.Lock()
for _, sc := range clients {
client := &client{info: sc, subs: make([]*subState, 0, 4)}
cs.clients[client.info.ID] = client
if len(client.info.ConnID) > 0 {
cs.connIDs[string(client.info.ConnID)] = client
}
}
cs.Unlock()
} | go | func (cs *clientStore) recoverClients(clients []*stores.Client) {
cs.Lock()
for _, sc := range clients {
client := &client{info: sc, subs: make([]*subState, 0, 4)}
cs.clients[client.info.ID] = client
if len(client.info.ConnID) > 0 {
cs.connIDs[string(client.info.ConnID)] = client
}
}
cs.Unlock()
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"recoverClients",
"(",
"clients",
"[",
"]",
"*",
"stores",
".",
"Client",
")",
"{",
"cs",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"sc",
":=",
"range",
"clients",
"{",
"client",
":=",
"&",
"client",
"{",
"info",
":",
"sc",
",",
"subs",
":",
"make",
"(",
"[",
"]",
"*",
"subState",
",",
"0",
",",
"4",
")",
"}",
"\n",
"cs",
".",
"clients",
"[",
"client",
".",
"info",
".",
"ID",
"]",
"=",
"client",
"\n",
"if",
"len",
"(",
"client",
".",
"info",
".",
"ConnID",
")",
">",
"0",
"{",
"cs",
".",
"connIDs",
"[",
"string",
"(",
"client",
".",
"info",
".",
"ConnID",
")",
"]",
"=",
"client",
"\n",
"}",
"\n",
"}",
"\n",
"cs",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // recoverClients recreates the content of the client store based on clients
// information recovered from the Store. | [
"recoverClients",
"recreates",
"the",
"content",
"of",
"the",
"client",
"store",
"based",
"on",
"clients",
"information",
"recovered",
"from",
"the",
"Store",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L273-L283 | train |
nats-io/nats-streaming-server | server/client.go | setClientHB | func (cs *clientStore) setClientHB(ID string, interval time.Duration, f func()) {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return
}
c.Lock()
if c.hbt == nil {
c.hbt = time.AfterFunc(interval, f)
}
c.Unlock()
} | go | func (cs *clientStore) setClientHB(ID string, interval time.Duration, f func()) {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return
}
c.Lock()
if c.hbt == nil {
c.hbt = time.AfterFunc(interval, f)
}
c.Unlock()
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"setClientHB",
"(",
"ID",
"string",
",",
"interval",
"time",
".",
"Duration",
",",
"f",
"func",
"(",
")",
")",
"{",
"cs",
".",
"RLock",
"(",
")",
"\n",
"defer",
"cs",
".",
"RUnlock",
"(",
")",
"\n",
"c",
":=",
"cs",
".",
"clients",
"[",
"ID",
"]",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"c",
".",
"Lock",
"(",
")",
"\n",
"if",
"c",
".",
"hbt",
"==",
"nil",
"{",
"c",
".",
"hbt",
"=",
"time",
".",
"AfterFunc",
"(",
"interval",
",",
"f",
")",
"\n",
"}",
"\n",
"c",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // setClientHB will lookup the client `ID` and, if present, set the
// client's timer with the given interval and function. | [
"setClientHB",
"will",
"lookup",
"the",
"client",
"ID",
"and",
"if",
"present",
"set",
"the",
"client",
"s",
"timer",
"with",
"the",
"given",
"interval",
"and",
"function",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L287-L299 | train |
nats-io/nats-streaming-server | server/client.go | removeClientHB | func (cs *clientStore) removeClientHB(c *client) {
if c == nil {
return
}
c.Lock()
if c.hbt != nil {
c.hbt.Stop()
c.hbt = nil
}
c.Unlock()
} | go | func (cs *clientStore) removeClientHB(c *client) {
if c == nil {
return
}
c.Lock()
if c.hbt != nil {
c.hbt.Stop()
c.hbt = nil
}
c.Unlock()
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"removeClientHB",
"(",
"c",
"*",
"client",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"c",
".",
"Lock",
"(",
")",
"\n",
"if",
"c",
".",
"hbt",
"!=",
"nil",
"{",
"c",
".",
"hbt",
".",
"Stop",
"(",
")",
"\n",
"c",
".",
"hbt",
"=",
"nil",
"\n",
"}",
"\n",
"c",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // removeClientHB will stop and remove the client's heartbeat timer, if
// present. | [
"removeClientHB",
"will",
"stop",
"and",
"remove",
"the",
"client",
"s",
"heartbeat",
"timer",
"if",
"present",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L303-L313 | train |
nats-io/nats-streaming-server | server/client.go | count | func (cs *clientStore) count() int {
cs.RLock()
total := len(cs.clients)
cs.RUnlock()
return total
} | go | func (cs *clientStore) count() int {
cs.RLock()
total := len(cs.clients)
cs.RUnlock()
return total
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"count",
"(",
")",
"int",
"{",
"cs",
".",
"RLock",
"(",
")",
"\n",
"total",
":=",
"len",
"(",
"cs",
".",
"clients",
")",
"\n",
"cs",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"total",
"\n",
"}"
] | // count returns the number of registered clients | [
"count",
"returns",
"the",
"number",
"of",
"registered",
"clients"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L329-L334 | train |
nats-io/nats-streaming-server | server/clustering.go | shutdown | func (r *raftNode) shutdown() error {
r.Lock()
if r.closed {
r.Unlock()
return nil
}
r.closed = true
r.Unlock()
if r.Raft != nil {
if err := r.Raft.Shutdown().Error(); err != nil {
return err
}
}
if r.transport != nil {
if err := r.transport.Close(); err != nil {
return err
}
}
if r.store != nil {
if err := r.store.Close(); err != nil {
return err
}
}
if r.joinSub != nil {
if err := r.joinSub.Unsubscribe(); err != nil {
return err
}
}
if r.logInput != nil {
if err := r.logInput.Close(); err != nil {
return err
}
}
return nil
} | go | func (r *raftNode) shutdown() error {
r.Lock()
if r.closed {
r.Unlock()
return nil
}
r.closed = true
r.Unlock()
if r.Raft != nil {
if err := r.Raft.Shutdown().Error(); err != nil {
return err
}
}
if r.transport != nil {
if err := r.transport.Close(); err != nil {
return err
}
}
if r.store != nil {
if err := r.store.Close(); err != nil {
return err
}
}
if r.joinSub != nil {
if err := r.joinSub.Unsubscribe(); err != nil {
return err
}
}
if r.logInput != nil {
if err := r.logInput.Close(); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"r",
"*",
"raftNode",
")",
"shutdown",
"(",
")",
"error",
"{",
"r",
".",
"Lock",
"(",
")",
"\n",
"if",
"r",
".",
"closed",
"{",
"r",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"r",
".",
"closed",
"=",
"true",
"\n",
"r",
".",
"Unlock",
"(",
")",
"\n",
"if",
"r",
".",
"Raft",
"!=",
"nil",
"{",
"if",
"err",
":=",
"r",
".",
"Raft",
".",
"Shutdown",
"(",
")",
".",
"Error",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"transport",
"!=",
"nil",
"{",
"if",
"err",
":=",
"r",
".",
"transport",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"store",
"!=",
"nil",
"{",
"if",
"err",
":=",
"r",
".",
"store",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"joinSub",
"!=",
"nil",
"{",
"if",
"err",
":=",
"r",
".",
"joinSub",
".",
"Unsubscribe",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"logInput",
"!=",
"nil",
"{",
"if",
"err",
":=",
"r",
".",
"logInput",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // shutdown attempts to stop the Raft node. | [
"shutdown",
"attempts",
"to",
"stop",
"the",
"Raft",
"node",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/clustering.go#L96-L130 | train |
nats-io/nats-streaming-server | server/clustering.go | createServerRaftNode | func (s *StanServer) createServerRaftNode(hasStreamingState bool) error {
var (
name = s.info.ClusterID
addr = s.getClusteringAddr(name)
existingState, err = s.createRaftNode(name)
)
if err != nil {
return err
}
if !existingState && hasStreamingState {
return fmt.Errorf("streaming state was recovered but cluster log path %q is empty", s.opts.Clustering.RaftLogPath)
}
node := s.raft
// Bootstrap if there is no previous state and we are starting this node as
// a seed or a cluster configuration is provided.
bootstrap := !existingState && (s.opts.Clustering.Bootstrap || len(s.opts.Clustering.Peers) > 0)
if bootstrap {
if err := s.bootstrapCluster(name, node.Raft); err != nil {
node.shutdown()
return err
}
} else if !existingState {
// Attempt to join the cluster if we're not bootstrapping.
req, err := (&spb.RaftJoinRequest{NodeID: s.opts.Clustering.NodeID, NodeAddr: addr}).Marshal()
if err != nil {
panic(err)
}
var (
joined = false
resp = &spb.RaftJoinResponse{}
)
s.log.Debugf("Joining Raft group %s", name)
// Attempt to join up to 5 times before giving up.
for i := 0; i < 5; i++ {
r, err := s.ncr.Request(fmt.Sprintf("%s.%s.join", defaultRaftPrefix, name), req, joinRaftGroupTimeout)
if err != nil {
time.Sleep(20 * time.Millisecond)
continue
}
if err := resp.Unmarshal(r.Data); err != nil {
time.Sleep(20 * time.Millisecond)
continue
}
if resp.Error != "" {
time.Sleep(20 * time.Millisecond)
continue
}
joined = true
break
}
if !joined {
node.shutdown()
return fmt.Errorf("failed to join Raft group %s", name)
}
}
if s.opts.Clustering.Bootstrap {
// If node is started with bootstrap, regardless if state exist or not, try to
// detect (and report) other nodes in same cluster started with bootstrap=true.
s.wg.Add(1)
go func() {
s.detectBootstrapMisconfig(name)
s.wg.Done()
}()
}
return nil
} | go | func (s *StanServer) createServerRaftNode(hasStreamingState bool) error {
var (
name = s.info.ClusterID
addr = s.getClusteringAddr(name)
existingState, err = s.createRaftNode(name)
)
if err != nil {
return err
}
if !existingState && hasStreamingState {
return fmt.Errorf("streaming state was recovered but cluster log path %q is empty", s.opts.Clustering.RaftLogPath)
}
node := s.raft
// Bootstrap if there is no previous state and we are starting this node as
// a seed or a cluster configuration is provided.
bootstrap := !existingState && (s.opts.Clustering.Bootstrap || len(s.opts.Clustering.Peers) > 0)
if bootstrap {
if err := s.bootstrapCluster(name, node.Raft); err != nil {
node.shutdown()
return err
}
} else if !existingState {
// Attempt to join the cluster if we're not bootstrapping.
req, err := (&spb.RaftJoinRequest{NodeID: s.opts.Clustering.NodeID, NodeAddr: addr}).Marshal()
if err != nil {
panic(err)
}
var (
joined = false
resp = &spb.RaftJoinResponse{}
)
s.log.Debugf("Joining Raft group %s", name)
// Attempt to join up to 5 times before giving up.
for i := 0; i < 5; i++ {
r, err := s.ncr.Request(fmt.Sprintf("%s.%s.join", defaultRaftPrefix, name), req, joinRaftGroupTimeout)
if err != nil {
time.Sleep(20 * time.Millisecond)
continue
}
if err := resp.Unmarshal(r.Data); err != nil {
time.Sleep(20 * time.Millisecond)
continue
}
if resp.Error != "" {
time.Sleep(20 * time.Millisecond)
continue
}
joined = true
break
}
if !joined {
node.shutdown()
return fmt.Errorf("failed to join Raft group %s", name)
}
}
if s.opts.Clustering.Bootstrap {
// If node is started with bootstrap, regardless if state exist or not, try to
// detect (and report) other nodes in same cluster started with bootstrap=true.
s.wg.Add(1)
go func() {
s.detectBootstrapMisconfig(name)
s.wg.Done()
}()
}
return nil
} | [
"func",
"(",
"s",
"*",
"StanServer",
")",
"createServerRaftNode",
"(",
"hasStreamingState",
"bool",
")",
"error",
"{",
"var",
"(",
"name",
"=",
"s",
".",
"info",
".",
"ClusterID",
"\n",
"addr",
"=",
"s",
".",
"getClusteringAddr",
"(",
"name",
")",
"\n",
"existingState",
",",
"err",
"=",
"s",
".",
"createRaftNode",
"(",
"name",
")",
"\n",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"existingState",
"&&",
"hasStreamingState",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
".",
"opts",
".",
"Clustering",
".",
"RaftLogPath",
")",
"\n",
"}",
"\n",
"node",
":=",
"s",
".",
"raft",
"\n\n",
"// Bootstrap if there is no previous state and we are starting this node as",
"// a seed or a cluster configuration is provided.",
"bootstrap",
":=",
"!",
"existingState",
"&&",
"(",
"s",
".",
"opts",
".",
"Clustering",
".",
"Bootstrap",
"||",
"len",
"(",
"s",
".",
"opts",
".",
"Clustering",
".",
"Peers",
")",
">",
"0",
")",
"\n",
"if",
"bootstrap",
"{",
"if",
"err",
":=",
"s",
".",
"bootstrapCluster",
"(",
"name",
",",
"node",
".",
"Raft",
")",
";",
"err",
"!=",
"nil",
"{",
"node",
".",
"shutdown",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"if",
"!",
"existingState",
"{",
"// Attempt to join the cluster if we're not bootstrapping.",
"req",
",",
"err",
":=",
"(",
"&",
"spb",
".",
"RaftJoinRequest",
"{",
"NodeID",
":",
"s",
".",
"opts",
".",
"Clustering",
".",
"NodeID",
",",
"NodeAddr",
":",
"addr",
"}",
")",
".",
"Marshal",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"var",
"(",
"joined",
"=",
"false",
"\n",
"resp",
"=",
"&",
"spb",
".",
"RaftJoinResponse",
"{",
"}",
"\n",
")",
"\n",
"s",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"// Attempt to join up to 5 times before giving up.",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"5",
";",
"i",
"++",
"{",
"r",
",",
"err",
":=",
"s",
".",
"ncr",
".",
"Request",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"defaultRaftPrefix",
",",
"name",
")",
",",
"req",
",",
"joinRaftGroupTimeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"time",
".",
"Sleep",
"(",
"20",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"err",
":=",
"resp",
".",
"Unmarshal",
"(",
"r",
".",
"Data",
")",
";",
"err",
"!=",
"nil",
"{",
"time",
".",
"Sleep",
"(",
"20",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"resp",
".",
"Error",
"!=",
"\"",
"\"",
"{",
"time",
".",
"Sleep",
"(",
"20",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"joined",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"!",
"joined",
"{",
"node",
".",
"shutdown",
"(",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"s",
".",
"opts",
".",
"Clustering",
".",
"Bootstrap",
"{",
"// If node is started with bootstrap, regardless if state exist or not, try to",
"// detect (and report) other nodes in same cluster started with bootstrap=true.",
"s",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"s",
".",
"detectBootstrapMisconfig",
"(",
"name",
")",
"\n",
"s",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // createRaftNode creates and starts a new Raft node. | [
"createRaftNode",
"creates",
"and",
"starts",
"a",
"new",
"Raft",
"node",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/clustering.go#L133-L199 | train |
nats-io/nats-streaming-server | server/clustering.go | bootstrapCluster | func (s *StanServer) bootstrapCluster(name string, node *raft.Raft) error {
var (
addr = s.getClusteringAddr(name)
// Include ourself in the cluster.
servers = []raft.Server{raft.Server{
ID: raft.ServerID(s.opts.Clustering.NodeID),
Address: raft.ServerAddress(addr),
}}
)
if len(s.opts.Clustering.Peers) > 0 {
// Bootstrap using provided cluster configuration.
s.log.Debugf("Bootstrapping Raft group %s using provided configuration", name)
for _, peer := range s.opts.Clustering.Peers {
servers = append(servers, raft.Server{
ID: raft.ServerID(peer),
Address: raft.ServerAddress(s.getClusteringPeerAddr(name, peer)),
})
}
} else {
// Bootstrap as a seed node.
s.log.Debugf("Bootstrapping Raft group %s as seed node", name)
}
config := raft.Configuration{Servers: servers}
return node.BootstrapCluster(config).Error()
} | go | func (s *StanServer) bootstrapCluster(name string, node *raft.Raft) error {
var (
addr = s.getClusteringAddr(name)
// Include ourself in the cluster.
servers = []raft.Server{raft.Server{
ID: raft.ServerID(s.opts.Clustering.NodeID),
Address: raft.ServerAddress(addr),
}}
)
if len(s.opts.Clustering.Peers) > 0 {
// Bootstrap using provided cluster configuration.
s.log.Debugf("Bootstrapping Raft group %s using provided configuration", name)
for _, peer := range s.opts.Clustering.Peers {
servers = append(servers, raft.Server{
ID: raft.ServerID(peer),
Address: raft.ServerAddress(s.getClusteringPeerAddr(name, peer)),
})
}
} else {
// Bootstrap as a seed node.
s.log.Debugf("Bootstrapping Raft group %s as seed node", name)
}
config := raft.Configuration{Servers: servers}
return node.BootstrapCluster(config).Error()
} | [
"func",
"(",
"s",
"*",
"StanServer",
")",
"bootstrapCluster",
"(",
"name",
"string",
",",
"node",
"*",
"raft",
".",
"Raft",
")",
"error",
"{",
"var",
"(",
"addr",
"=",
"s",
".",
"getClusteringAddr",
"(",
"name",
")",
"\n",
"// Include ourself in the cluster.",
"servers",
"=",
"[",
"]",
"raft",
".",
"Server",
"{",
"raft",
".",
"Server",
"{",
"ID",
":",
"raft",
".",
"ServerID",
"(",
"s",
".",
"opts",
".",
"Clustering",
".",
"NodeID",
")",
",",
"Address",
":",
"raft",
".",
"ServerAddress",
"(",
"addr",
")",
",",
"}",
"}",
"\n",
")",
"\n",
"if",
"len",
"(",
"s",
".",
"opts",
".",
"Clustering",
".",
"Peers",
")",
">",
"0",
"{",
"// Bootstrap using provided cluster configuration.",
"s",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"for",
"_",
",",
"peer",
":=",
"range",
"s",
".",
"opts",
".",
"Clustering",
".",
"Peers",
"{",
"servers",
"=",
"append",
"(",
"servers",
",",
"raft",
".",
"Server",
"{",
"ID",
":",
"raft",
".",
"ServerID",
"(",
"peer",
")",
",",
"Address",
":",
"raft",
".",
"ServerAddress",
"(",
"s",
".",
"getClusteringPeerAddr",
"(",
"name",
",",
"peer",
")",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// Bootstrap as a seed node.",
"s",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"config",
":=",
"raft",
".",
"Configuration",
"{",
"Servers",
":",
"servers",
"}",
"\n",
"return",
"node",
".",
"BootstrapCluster",
"(",
"config",
")",
".",
"Error",
"(",
")",
"\n",
"}"
] | // bootstrapCluster bootstraps the node for the provided Raft group either as a
// seed node or with the given peer configuration, depending on configuration
// and with the latter taking precedence. | [
"bootstrapCluster",
"bootstraps",
"the",
"node",
"for",
"the",
"provided",
"Raft",
"group",
"either",
"as",
"a",
"seed",
"node",
"or",
"with",
"the",
"given",
"peer",
"configuration",
"depending",
"on",
"configuration",
"and",
"with",
"the",
"latter",
"taking",
"precedence",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/clustering.go#L420-L444 | train |
nats-io/nats-streaming-server | server/clustering.go | Apply | func (r *raftFSM) Apply(l *raft.Log) interface{} {
s := r.server
op := &spb.RaftOperation{}
if err := op.Unmarshal(l.Data); err != nil {
panic(err)
}
switch op.OpType {
case spb.RaftOperation_Publish:
// Message replication.
var (
c *channel
err error
lastSeq uint64
)
for _, msg := range op.PublishBatch.Messages {
// This is a batch for a given channel, so lookup channel once.
if c == nil {
c, err = s.lookupOrCreateChannel(msg.Subject)
// That should not be the case, but if it happens,
// just bail out.
if err == ErrChanDelInProgress {
return nil
}
lastSeq, err = c.store.Msgs.LastSequence()
}
if err == nil && lastSeq < msg.Sequence-1 {
err = s.raft.fsm.restoreMsgsFromSnapshot(c, lastSeq+1, msg.Sequence-1)
}
if err == nil {
_, err = c.store.Msgs.Store(msg)
}
if err != nil {
return fmt.Errorf("failed to store replicated message %d on channel %s: %v",
msg.Sequence, msg.Subject, err)
}
}
return nil
case spb.RaftOperation_Connect:
// Client connection create replication.
return s.processConnect(op.ClientConnect.Request, op.ClientConnect.Refresh)
case spb.RaftOperation_Disconnect:
// Client connection close replication.
return s.closeClient(op.ClientDisconnect.ClientID)
case spb.RaftOperation_Subscribe:
// Subscription replication.
sub, err := s.processSub(nil, op.Sub.Request, op.Sub.AckInbox, op.Sub.ID)
return &replicatedSub{sub: sub, err: err}
case spb.RaftOperation_RemoveSubscription:
fallthrough
case spb.RaftOperation_CloseSubscription:
// Close/Unsub subscription replication.
isSubClose := op.OpType == spb.RaftOperation_CloseSubscription
s.closeMu.Lock()
err := s.unsubscribe(op.Unsub, isSubClose)
s.closeMu.Unlock()
return err
case spb.RaftOperation_SendAndAck:
if !s.isLeader() {
s.processReplicatedSendAndAck(op.SubSentAck)
}
return nil
case spb.RaftOperation_DeleteChannel:
s.processDeleteChannel(op.Channel)
return nil
default:
panic(fmt.Sprintf("unknown op type %s", op.OpType))
}
} | go | func (r *raftFSM) Apply(l *raft.Log) interface{} {
s := r.server
op := &spb.RaftOperation{}
if err := op.Unmarshal(l.Data); err != nil {
panic(err)
}
switch op.OpType {
case spb.RaftOperation_Publish:
// Message replication.
var (
c *channel
err error
lastSeq uint64
)
for _, msg := range op.PublishBatch.Messages {
// This is a batch for a given channel, so lookup channel once.
if c == nil {
c, err = s.lookupOrCreateChannel(msg.Subject)
// That should not be the case, but if it happens,
// just bail out.
if err == ErrChanDelInProgress {
return nil
}
lastSeq, err = c.store.Msgs.LastSequence()
}
if err == nil && lastSeq < msg.Sequence-1 {
err = s.raft.fsm.restoreMsgsFromSnapshot(c, lastSeq+1, msg.Sequence-1)
}
if err == nil {
_, err = c.store.Msgs.Store(msg)
}
if err != nil {
return fmt.Errorf("failed to store replicated message %d on channel %s: %v",
msg.Sequence, msg.Subject, err)
}
}
return nil
case spb.RaftOperation_Connect:
// Client connection create replication.
return s.processConnect(op.ClientConnect.Request, op.ClientConnect.Refresh)
case spb.RaftOperation_Disconnect:
// Client connection close replication.
return s.closeClient(op.ClientDisconnect.ClientID)
case spb.RaftOperation_Subscribe:
// Subscription replication.
sub, err := s.processSub(nil, op.Sub.Request, op.Sub.AckInbox, op.Sub.ID)
return &replicatedSub{sub: sub, err: err}
case spb.RaftOperation_RemoveSubscription:
fallthrough
case spb.RaftOperation_CloseSubscription:
// Close/Unsub subscription replication.
isSubClose := op.OpType == spb.RaftOperation_CloseSubscription
s.closeMu.Lock()
err := s.unsubscribe(op.Unsub, isSubClose)
s.closeMu.Unlock()
return err
case spb.RaftOperation_SendAndAck:
if !s.isLeader() {
s.processReplicatedSendAndAck(op.SubSentAck)
}
return nil
case spb.RaftOperation_DeleteChannel:
s.processDeleteChannel(op.Channel)
return nil
default:
panic(fmt.Sprintf("unknown op type %s", op.OpType))
}
} | [
"func",
"(",
"r",
"*",
"raftFSM",
")",
"Apply",
"(",
"l",
"*",
"raft",
".",
"Log",
")",
"interface",
"{",
"}",
"{",
"s",
":=",
"r",
".",
"server",
"\n",
"op",
":=",
"&",
"spb",
".",
"RaftOperation",
"{",
"}",
"\n",
"if",
"err",
":=",
"op",
".",
"Unmarshal",
"(",
"l",
".",
"Data",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"switch",
"op",
".",
"OpType",
"{",
"case",
"spb",
".",
"RaftOperation_Publish",
":",
"// Message replication.",
"var",
"(",
"c",
"*",
"channel",
"\n",
"err",
"error",
"\n",
"lastSeq",
"uint64",
"\n",
")",
"\n",
"for",
"_",
",",
"msg",
":=",
"range",
"op",
".",
"PublishBatch",
".",
"Messages",
"{",
"// This is a batch for a given channel, so lookup channel once.",
"if",
"c",
"==",
"nil",
"{",
"c",
",",
"err",
"=",
"s",
".",
"lookupOrCreateChannel",
"(",
"msg",
".",
"Subject",
")",
"\n",
"// That should not be the case, but if it happens,",
"// just bail out.",
"if",
"err",
"==",
"ErrChanDelInProgress",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"lastSeq",
",",
"err",
"=",
"c",
".",
"store",
".",
"Msgs",
".",
"LastSequence",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"lastSeq",
"<",
"msg",
".",
"Sequence",
"-",
"1",
"{",
"err",
"=",
"s",
".",
"raft",
".",
"fsm",
".",
"restoreMsgsFromSnapshot",
"(",
"c",
",",
"lastSeq",
"+",
"1",
",",
"msg",
".",
"Sequence",
"-",
"1",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"{",
"_",
",",
"err",
"=",
"c",
".",
"store",
".",
"Msgs",
".",
"Store",
"(",
"msg",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"msg",
".",
"Sequence",
",",
"msg",
".",
"Subject",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"case",
"spb",
".",
"RaftOperation_Connect",
":",
"// Client connection create replication.",
"return",
"s",
".",
"processConnect",
"(",
"op",
".",
"ClientConnect",
".",
"Request",
",",
"op",
".",
"ClientConnect",
".",
"Refresh",
")",
"\n",
"case",
"spb",
".",
"RaftOperation_Disconnect",
":",
"// Client connection close replication.",
"return",
"s",
".",
"closeClient",
"(",
"op",
".",
"ClientDisconnect",
".",
"ClientID",
")",
"\n",
"case",
"spb",
".",
"RaftOperation_Subscribe",
":",
"// Subscription replication.",
"sub",
",",
"err",
":=",
"s",
".",
"processSub",
"(",
"nil",
",",
"op",
".",
"Sub",
".",
"Request",
",",
"op",
".",
"Sub",
".",
"AckInbox",
",",
"op",
".",
"Sub",
".",
"ID",
")",
"\n",
"return",
"&",
"replicatedSub",
"{",
"sub",
":",
"sub",
",",
"err",
":",
"err",
"}",
"\n",
"case",
"spb",
".",
"RaftOperation_RemoveSubscription",
":",
"fallthrough",
"\n",
"case",
"spb",
".",
"RaftOperation_CloseSubscription",
":",
"// Close/Unsub subscription replication.",
"isSubClose",
":=",
"op",
".",
"OpType",
"==",
"spb",
".",
"RaftOperation_CloseSubscription",
"\n",
"s",
".",
"closeMu",
".",
"Lock",
"(",
")",
"\n",
"err",
":=",
"s",
".",
"unsubscribe",
"(",
"op",
".",
"Unsub",
",",
"isSubClose",
")",
"\n",
"s",
".",
"closeMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"case",
"spb",
".",
"RaftOperation_SendAndAck",
":",
"if",
"!",
"s",
".",
"isLeader",
"(",
")",
"{",
"s",
".",
"processReplicatedSendAndAck",
"(",
"op",
".",
"SubSentAck",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"case",
"spb",
".",
"RaftOperation_DeleteChannel",
":",
"s",
".",
"processDeleteChannel",
"(",
"op",
".",
"Channel",
")",
"\n",
"return",
"nil",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"op",
".",
"OpType",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Apply log is invoked once a log entry is committed.
// It returns a value which will be made available in the
// ApplyFuture returned by Raft.Apply method if that
// method was called on the same Raft node as the FSM. | [
"Apply",
"log",
"is",
"invoked",
"once",
"a",
"log",
"entry",
"is",
"committed",
".",
"It",
"returns",
"a",
"value",
"which",
"will",
"be",
"made",
"available",
"in",
"the",
"ApplyFuture",
"returned",
"by",
"Raft",
".",
"Apply",
"method",
"if",
"that",
"method",
"was",
"called",
"on",
"the",
"same",
"Raft",
"node",
"as",
"the",
"FSM",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/clustering.go#L458-L525 | train |
nats-io/nats-streaming-server | util/util.go | EnsureBufBigEnough | func EnsureBufBigEnough(buf []byte, needed int) []byte {
if buf == nil {
return make([]byte, needed)
} else if needed > len(buf) {
return make([]byte, int(float32(needed)*1.1))
}
return buf
} | go | func EnsureBufBigEnough(buf []byte, needed int) []byte {
if buf == nil {
return make([]byte, needed)
} else if needed > len(buf) {
return make([]byte, int(float32(needed)*1.1))
}
return buf
} | [
"func",
"EnsureBufBigEnough",
"(",
"buf",
"[",
"]",
"byte",
",",
"needed",
"int",
")",
"[",
"]",
"byte",
"{",
"if",
"buf",
"==",
"nil",
"{",
"return",
"make",
"(",
"[",
"]",
"byte",
",",
"needed",
")",
"\n",
"}",
"else",
"if",
"needed",
">",
"len",
"(",
"buf",
")",
"{",
"return",
"make",
"(",
"[",
"]",
"byte",
",",
"int",
"(",
"float32",
"(",
"needed",
")",
"*",
"1.1",
")",
")",
"\n",
"}",
"\n",
"return",
"buf",
"\n",
"}"
] | // EnsureBufBigEnough checks that given buffer is big enough to hold 'needed'
// bytes, otherwise returns a buffer of a size of at least 'needed' bytes. | [
"EnsureBufBigEnough",
"checks",
"that",
"given",
"buffer",
"is",
"big",
"enough",
"to",
"hold",
"needed",
"bytes",
"otherwise",
"returns",
"a",
"buffer",
"of",
"a",
"size",
"of",
"at",
"least",
"needed",
"bytes",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/util/util.go#L109-L116 | train |
nats-io/nats-streaming-server | util/util.go | CloseFile | func CloseFile(err error, f io.Closer) error {
if lerr := f.Close(); lerr != nil && err == nil {
err = lerr
}
return err
} | go | func CloseFile(err error, f io.Closer) error {
if lerr := f.Close(); lerr != nil && err == nil {
err = lerr
}
return err
} | [
"func",
"CloseFile",
"(",
"err",
"error",
",",
"f",
"io",
".",
"Closer",
")",
"error",
"{",
"if",
"lerr",
":=",
"f",
".",
"Close",
"(",
")",
";",
"lerr",
"!=",
"nil",
"&&",
"err",
"==",
"nil",
"{",
"err",
"=",
"lerr",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // CloseFile closes the given file and report the possible error only
// if the given error `err` is not already set. | [
"CloseFile",
"closes",
"the",
"given",
"file",
"and",
"report",
"the",
"possible",
"error",
"only",
"if",
"the",
"given",
"error",
"err",
"is",
"not",
"already",
"set",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/util/util.go#L144-L149 | train |
nats-io/nats-streaming-server | util/util.go | FriendlyBytes | func FriendlyBytes(bytes int64) string {
fbytes := float64(bytes)
base := 1024
pre := []string{"K", "M", "G", "T", "P", "E"}
if fbytes < float64(base) {
return fmt.Sprintf("%v B", fbytes)
}
exp := int(math.Log(fbytes) / math.Log(float64(base)))
index := exp - 1
return fmt.Sprintf("%.2f %sB", fbytes/math.Pow(float64(base), float64(exp)), pre[index])
} | go | func FriendlyBytes(bytes int64) string {
fbytes := float64(bytes)
base := 1024
pre := []string{"K", "M", "G", "T", "P", "E"}
if fbytes < float64(base) {
return fmt.Sprintf("%v B", fbytes)
}
exp := int(math.Log(fbytes) / math.Log(float64(base)))
index := exp - 1
return fmt.Sprintf("%.2f %sB", fbytes/math.Pow(float64(base), float64(exp)), pre[index])
} | [
"func",
"FriendlyBytes",
"(",
"bytes",
"int64",
")",
"string",
"{",
"fbytes",
":=",
"float64",
"(",
"bytes",
")",
"\n",
"base",
":=",
"1024",
"\n",
"pre",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"if",
"fbytes",
"<",
"float64",
"(",
"base",
")",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"fbytes",
")",
"\n",
"}",
"\n",
"exp",
":=",
"int",
"(",
"math",
".",
"Log",
"(",
"fbytes",
")",
"/",
"math",
".",
"Log",
"(",
"float64",
"(",
"base",
")",
")",
")",
"\n",
"index",
":=",
"exp",
"-",
"1",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"fbytes",
"/",
"math",
".",
"Pow",
"(",
"float64",
"(",
"base",
")",
",",
"float64",
"(",
"exp",
")",
")",
",",
"pre",
"[",
"index",
"]",
")",
"\n",
"}"
] | // FriendlyBytes returns a string with the given bytes int64
// represented as a size, such as 1KB, 10MB, etc... | [
"FriendlyBytes",
"returns",
"a",
"string",
"with",
"the",
"given",
"bytes",
"int64",
"represented",
"as",
"a",
"size",
"such",
"as",
"1KB",
"10MB",
"etc",
"..."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/util/util.go#L207-L217 | train |
nats-io/nats-streaming-server | stores/cryptostore.go | Encrypt | func (s *EDStore) Encrypt(pbuf *[]byte, data []byte) ([]byte, error) {
var buf []byte
// If given a buffer, use that one
if pbuf != nil {
buf = *pbuf
}
// Make sure size is ok, expand if necessary
buf = util.EnsureBufBigEnough(buf, 1+s.nonceSize+s.cryptoOverhead+len(data))
// If buffer was passed, update the reference
if pbuf != nil {
*pbuf = buf
}
buf[0] = s.code
copy(buf[1:], s.nonce)
copy(buf[1+s.nonceSize:], data)
dst := buf[1+s.nonceSize : 1+s.nonceSize+len(data)]
ed := s.gcm.Seal(dst[:0], s.nonce, dst, nil)
for i := s.nonceSize - 1; i >= 0; i-- {
s.nonce[i]++
if s.nonce[i] != 0 {
break
}
}
return buf[:1+s.nonceSize+len(ed)], nil
} | go | func (s *EDStore) Encrypt(pbuf *[]byte, data []byte) ([]byte, error) {
var buf []byte
// If given a buffer, use that one
if pbuf != nil {
buf = *pbuf
}
// Make sure size is ok, expand if necessary
buf = util.EnsureBufBigEnough(buf, 1+s.nonceSize+s.cryptoOverhead+len(data))
// If buffer was passed, update the reference
if pbuf != nil {
*pbuf = buf
}
buf[0] = s.code
copy(buf[1:], s.nonce)
copy(buf[1+s.nonceSize:], data)
dst := buf[1+s.nonceSize : 1+s.nonceSize+len(data)]
ed := s.gcm.Seal(dst[:0], s.nonce, dst, nil)
for i := s.nonceSize - 1; i >= 0; i-- {
s.nonce[i]++
if s.nonce[i] != 0 {
break
}
}
return buf[:1+s.nonceSize+len(ed)], nil
} | [
"func",
"(",
"s",
"*",
"EDStore",
")",
"Encrypt",
"(",
"pbuf",
"*",
"[",
"]",
"byte",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"buf",
"[",
"]",
"byte",
"\n",
"// If given a buffer, use that one",
"if",
"pbuf",
"!=",
"nil",
"{",
"buf",
"=",
"*",
"pbuf",
"\n",
"}",
"\n",
"// Make sure size is ok, expand if necessary",
"buf",
"=",
"util",
".",
"EnsureBufBigEnough",
"(",
"buf",
",",
"1",
"+",
"s",
".",
"nonceSize",
"+",
"s",
".",
"cryptoOverhead",
"+",
"len",
"(",
"data",
")",
")",
"\n",
"// If buffer was passed, update the reference",
"if",
"pbuf",
"!=",
"nil",
"{",
"*",
"pbuf",
"=",
"buf",
"\n",
"}",
"\n",
"buf",
"[",
"0",
"]",
"=",
"s",
".",
"code",
"\n",
"copy",
"(",
"buf",
"[",
"1",
":",
"]",
",",
"s",
".",
"nonce",
")",
"\n",
"copy",
"(",
"buf",
"[",
"1",
"+",
"s",
".",
"nonceSize",
":",
"]",
",",
"data",
")",
"\n",
"dst",
":=",
"buf",
"[",
"1",
"+",
"s",
".",
"nonceSize",
":",
"1",
"+",
"s",
".",
"nonceSize",
"+",
"len",
"(",
"data",
")",
"]",
"\n",
"ed",
":=",
"s",
".",
"gcm",
".",
"Seal",
"(",
"dst",
"[",
":",
"0",
"]",
",",
"s",
".",
"nonce",
",",
"dst",
",",
"nil",
")",
"\n",
"for",
"i",
":=",
"s",
".",
"nonceSize",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"s",
".",
"nonce",
"[",
"i",
"]",
"++",
"\n",
"if",
"s",
".",
"nonce",
"[",
"i",
"]",
"!=",
"0",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"buf",
"[",
":",
"1",
"+",
"s",
".",
"nonceSize",
"+",
"len",
"(",
"ed",
")",
"]",
",",
"nil",
"\n",
"}"
] | // Encrypt returns the encrypted data or an error | [
"Encrypt",
"returns",
"the",
"encrypted",
"data",
"or",
"an",
"error"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/cryptostore.go#L201-L225 | train |
nats-io/nats-streaming-server | stores/cryptostore.go | Decrypt | func (s *EDStore) Decrypt(dst []byte, cipherText []byte) ([]byte, error) {
var gcm cipher.AEAD
if len(cipherText) > 0 {
switch cipherText[0] {
case CryptoCodeAES:
gcm = s.aesgcm
case CryptoCodeChaCha:
gcm = s.chachagcm
default:
// Anything else, assume no algo or something we don't know how to decrypt.
return cipherText, nil
}
}
if len(cipherText) <= 1+s.nonceSize {
return nil, fmt.Errorf("trying to decrypt data that is not (len=%v)", len(cipherText))
}
dd, err := gcm.Open(dst, cipherText[1:1+s.nonceSize], cipherText[1+s.nonceSize:], nil)
if err != nil {
return nil, err
}
return dd, nil
} | go | func (s *EDStore) Decrypt(dst []byte, cipherText []byte) ([]byte, error) {
var gcm cipher.AEAD
if len(cipherText) > 0 {
switch cipherText[0] {
case CryptoCodeAES:
gcm = s.aesgcm
case CryptoCodeChaCha:
gcm = s.chachagcm
default:
// Anything else, assume no algo or something we don't know how to decrypt.
return cipherText, nil
}
}
if len(cipherText) <= 1+s.nonceSize {
return nil, fmt.Errorf("trying to decrypt data that is not (len=%v)", len(cipherText))
}
dd, err := gcm.Open(dst, cipherText[1:1+s.nonceSize], cipherText[1+s.nonceSize:], nil)
if err != nil {
return nil, err
}
return dd, nil
} | [
"func",
"(",
"s",
"*",
"EDStore",
")",
"Decrypt",
"(",
"dst",
"[",
"]",
"byte",
",",
"cipherText",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"gcm",
"cipher",
".",
"AEAD",
"\n",
"if",
"len",
"(",
"cipherText",
")",
">",
"0",
"{",
"switch",
"cipherText",
"[",
"0",
"]",
"{",
"case",
"CryptoCodeAES",
":",
"gcm",
"=",
"s",
".",
"aesgcm",
"\n",
"case",
"CryptoCodeChaCha",
":",
"gcm",
"=",
"s",
".",
"chachagcm",
"\n",
"default",
":",
"// Anything else, assume no algo or something we don't know how to decrypt.",
"return",
"cipherText",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"cipherText",
")",
"<=",
"1",
"+",
"s",
".",
"nonceSize",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"cipherText",
")",
")",
"\n",
"}",
"\n",
"dd",
",",
"err",
":=",
"gcm",
".",
"Open",
"(",
"dst",
",",
"cipherText",
"[",
"1",
":",
"1",
"+",
"s",
".",
"nonceSize",
"]",
",",
"cipherText",
"[",
"1",
"+",
"s",
".",
"nonceSize",
":",
"]",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"dd",
",",
"nil",
"\n",
"}"
] | // Decrypt returns the decrypted data or an error | [
"Decrypt",
"returns",
"the",
"decrypted",
"data",
"or",
"an",
"error"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/cryptostore.go#L228-L249 | train |
nats-io/nats-streaming-server | stores/cryptostore.go | NewCryptoStore | func NewCryptoStore(s Store, encryptionCipher string, encryptionKey []byte) (*CryptoStore, error) {
code, mkh, err := createMasterKeyHash(encryptionCipher, encryptionKey)
if err != nil {
return nil, err
}
cs := &CryptoStore{
Store: s,
code: code,
mkh: mkh,
}
// On success, erase the key
for i := 0; i < len(encryptionKey); i++ {
encryptionKey[i] = 'x'
}
return cs, nil
} | go | func NewCryptoStore(s Store, encryptionCipher string, encryptionKey []byte) (*CryptoStore, error) {
code, mkh, err := createMasterKeyHash(encryptionCipher, encryptionKey)
if err != nil {
return nil, err
}
cs := &CryptoStore{
Store: s,
code: code,
mkh: mkh,
}
// On success, erase the key
for i := 0; i < len(encryptionKey); i++ {
encryptionKey[i] = 'x'
}
return cs, nil
} | [
"func",
"NewCryptoStore",
"(",
"s",
"Store",
",",
"encryptionCipher",
"string",
",",
"encryptionKey",
"[",
"]",
"byte",
")",
"(",
"*",
"CryptoStore",
",",
"error",
")",
"{",
"code",
",",
"mkh",
",",
"err",
":=",
"createMasterKeyHash",
"(",
"encryptionCipher",
",",
"encryptionKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"cs",
":=",
"&",
"CryptoStore",
"{",
"Store",
":",
"s",
",",
"code",
":",
"code",
",",
"mkh",
":",
"mkh",
",",
"}",
"\n",
"// On success, erase the key",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"encryptionKey",
")",
";",
"i",
"++",
"{",
"encryptionKey",
"[",
"i",
"]",
"=",
"'x'",
"\n",
"}",
"\n",
"return",
"cs",
",",
"nil",
"\n",
"}"
] | // NewCryptoStore returns a CryptoStore instance with
// given underlying store. | [
"NewCryptoStore",
"returns",
"a",
"CryptoStore",
"instance",
"with",
"given",
"underlying",
"store",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/cryptostore.go#L253-L268 | train |
nats-io/nats-streaming-server | stores/limits.go | Clone | func (sl *StoreLimits) Clone() *StoreLimits {
cloned := *sl
cloned.PerChannel = sl.ClonePerChannelMap()
return &cloned
} | go | func (sl *StoreLimits) Clone() *StoreLimits {
cloned := *sl
cloned.PerChannel = sl.ClonePerChannelMap()
return &cloned
} | [
"func",
"(",
"sl",
"*",
"StoreLimits",
")",
"Clone",
"(",
")",
"*",
"StoreLimits",
"{",
"cloned",
":=",
"*",
"sl",
"\n",
"cloned",
".",
"PerChannel",
"=",
"sl",
".",
"ClonePerChannelMap",
"(",
")",
"\n",
"return",
"&",
"cloned",
"\n",
"}"
] | // Clone returns a copy of the store limits | [
"Clone",
"returns",
"a",
"copy",
"of",
"the",
"store",
"limits"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/limits.go#L31-L35 | train |
nats-io/nats-streaming-server | stores/limits.go | ClonePerChannelMap | func (sl *StoreLimits) ClonePerChannelMap() map[string]*ChannelLimits {
if sl.PerChannel == nil {
return nil
}
clone := make(map[string]*ChannelLimits, len(sl.PerChannel))
for k, v := range sl.PerChannel {
copyVal := *v
clone[k] = ©Val
}
return clone
} | go | func (sl *StoreLimits) ClonePerChannelMap() map[string]*ChannelLimits {
if sl.PerChannel == nil {
return nil
}
clone := make(map[string]*ChannelLimits, len(sl.PerChannel))
for k, v := range sl.PerChannel {
copyVal := *v
clone[k] = ©Val
}
return clone
} | [
"func",
"(",
"sl",
"*",
"StoreLimits",
")",
"ClonePerChannelMap",
"(",
")",
"map",
"[",
"string",
"]",
"*",
"ChannelLimits",
"{",
"if",
"sl",
".",
"PerChannel",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"clone",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"ChannelLimits",
",",
"len",
"(",
"sl",
".",
"PerChannel",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"sl",
".",
"PerChannel",
"{",
"copyVal",
":=",
"*",
"v",
"\n",
"clone",
"[",
"k",
"]",
"=",
"&",
"copyVal",
"\n",
"}",
"\n",
"return",
"clone",
"\n",
"}"
] | // ClonePerChannelMap returns a deep copy of the StoreLimits's PerChannel map | [
"ClonePerChannelMap",
"returns",
"a",
"deep",
"copy",
"of",
"the",
"StoreLimits",
"s",
"PerChannel",
"map"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/limits.go#L38-L48 | train |
nats-io/nats-streaming-server | stores/limits.go | Print | func (sl *StoreLimits) Print() []string {
sublist := util.NewSublist()
for cn, cl := range sl.PerChannel {
sublist.Insert(cn, &channelLimitInfo{
name: cn,
limits: cl,
isLiteral: util.IsChannelNameLiteral(cn),
})
}
maxLevels := sublist.NumLevels()
txt := []string{}
title := "---------- Store Limits ----------"
txt = append(txt, title)
txt = append(txt, fmt.Sprintf("Channels: %s",
getLimitStr(true, int64(sl.MaxChannels),
int64(DefaultStoreLimits.MaxChannels),
limitCount)))
maxLen := len(title)
txt = append(txt, "--------- Channels Limits --------")
txt = append(txt, getGlobalLimitsPrintLines(&sl.ChannelLimits)...)
if len(sl.PerChannel) > 0 {
channels := sublist.Subjects()
channelLines := []string{}
for _, cn := range channels {
r := sublist.Match(cn)
var prev *channelLimitInfo
for i := 0; i < len(r); i++ {
channel := r[i].(*channelLimitInfo)
if channel.name == cn {
var parentLimits *ChannelLimits
if prev == nil {
parentLimits = &sl.ChannelLimits
} else {
parentLimits = prev.limits
}
channelLines = append(channelLines,
getChannelLimitsPrintLines(i, maxLevels, &maxLen, channel.name, channel.limits, parentLimits)...)
break
}
prev = channel
}
}
title := " List of Channels "
numberDashesLeft := (maxLen - len(title)) / 2
numberDashesRight := maxLen - len(title) - numberDashesLeft
title = fmt.Sprintf("%s%s%s",
repeatChar("-", numberDashesLeft),
title,
repeatChar("-", numberDashesRight))
txt = append(txt, title)
txt = append(txt, channelLines...)
}
txt = append(txt, repeatChar("-", maxLen))
return txt
} | go | func (sl *StoreLimits) Print() []string {
sublist := util.NewSublist()
for cn, cl := range sl.PerChannel {
sublist.Insert(cn, &channelLimitInfo{
name: cn,
limits: cl,
isLiteral: util.IsChannelNameLiteral(cn),
})
}
maxLevels := sublist.NumLevels()
txt := []string{}
title := "---------- Store Limits ----------"
txt = append(txt, title)
txt = append(txt, fmt.Sprintf("Channels: %s",
getLimitStr(true, int64(sl.MaxChannels),
int64(DefaultStoreLimits.MaxChannels),
limitCount)))
maxLen := len(title)
txt = append(txt, "--------- Channels Limits --------")
txt = append(txt, getGlobalLimitsPrintLines(&sl.ChannelLimits)...)
if len(sl.PerChannel) > 0 {
channels := sublist.Subjects()
channelLines := []string{}
for _, cn := range channels {
r := sublist.Match(cn)
var prev *channelLimitInfo
for i := 0; i < len(r); i++ {
channel := r[i].(*channelLimitInfo)
if channel.name == cn {
var parentLimits *ChannelLimits
if prev == nil {
parentLimits = &sl.ChannelLimits
} else {
parentLimits = prev.limits
}
channelLines = append(channelLines,
getChannelLimitsPrintLines(i, maxLevels, &maxLen, channel.name, channel.limits, parentLimits)...)
break
}
prev = channel
}
}
title := " List of Channels "
numberDashesLeft := (maxLen - len(title)) / 2
numberDashesRight := maxLen - len(title) - numberDashesLeft
title = fmt.Sprintf("%s%s%s",
repeatChar("-", numberDashesLeft),
title,
repeatChar("-", numberDashesRight))
txt = append(txt, title)
txt = append(txt, channelLines...)
}
txt = append(txt, repeatChar("-", maxLen))
return txt
} | [
"func",
"(",
"sl",
"*",
"StoreLimits",
")",
"Print",
"(",
")",
"[",
"]",
"string",
"{",
"sublist",
":=",
"util",
".",
"NewSublist",
"(",
")",
"\n",
"for",
"cn",
",",
"cl",
":=",
"range",
"sl",
".",
"PerChannel",
"{",
"sublist",
".",
"Insert",
"(",
"cn",
",",
"&",
"channelLimitInfo",
"{",
"name",
":",
"cn",
",",
"limits",
":",
"cl",
",",
"isLiteral",
":",
"util",
".",
"IsChannelNameLiteral",
"(",
"cn",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"maxLevels",
":=",
"sublist",
".",
"NumLevels",
"(",
")",
"\n",
"txt",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"title",
":=",
"\"",
"\"",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"title",
")",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"getLimitStr",
"(",
"true",
",",
"int64",
"(",
"sl",
".",
"MaxChannels",
")",
",",
"int64",
"(",
"DefaultStoreLimits",
".",
"MaxChannels",
")",
",",
"limitCount",
")",
")",
")",
"\n",
"maxLen",
":=",
"len",
"(",
"title",
")",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"\"",
"\"",
")",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"getGlobalLimitsPrintLines",
"(",
"&",
"sl",
".",
"ChannelLimits",
")",
"...",
")",
"\n",
"if",
"len",
"(",
"sl",
".",
"PerChannel",
")",
">",
"0",
"{",
"channels",
":=",
"sublist",
".",
"Subjects",
"(",
")",
"\n",
"channelLines",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"cn",
":=",
"range",
"channels",
"{",
"r",
":=",
"sublist",
".",
"Match",
"(",
"cn",
")",
"\n",
"var",
"prev",
"*",
"channelLimitInfo",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"r",
")",
";",
"i",
"++",
"{",
"channel",
":=",
"r",
"[",
"i",
"]",
".",
"(",
"*",
"channelLimitInfo",
")",
"\n",
"if",
"channel",
".",
"name",
"==",
"cn",
"{",
"var",
"parentLimits",
"*",
"ChannelLimits",
"\n",
"if",
"prev",
"==",
"nil",
"{",
"parentLimits",
"=",
"&",
"sl",
".",
"ChannelLimits",
"\n",
"}",
"else",
"{",
"parentLimits",
"=",
"prev",
".",
"limits",
"\n",
"}",
"\n",
"channelLines",
"=",
"append",
"(",
"channelLines",
",",
"getChannelLimitsPrintLines",
"(",
"i",
",",
"maxLevels",
",",
"&",
"maxLen",
",",
"channel",
".",
"name",
",",
"channel",
".",
"limits",
",",
"parentLimits",
")",
"...",
")",
"\n",
"break",
"\n",
"}",
"\n",
"prev",
"=",
"channel",
"\n",
"}",
"\n",
"}",
"\n",
"title",
":=",
"\"",
"\"",
"\n",
"numberDashesLeft",
":=",
"(",
"maxLen",
"-",
"len",
"(",
"title",
")",
")",
"/",
"2",
"\n",
"numberDashesRight",
":=",
"maxLen",
"-",
"len",
"(",
"title",
")",
"-",
"numberDashesLeft",
"\n",
"title",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"repeatChar",
"(",
"\"",
"\"",
",",
"numberDashesLeft",
")",
",",
"title",
",",
"repeatChar",
"(",
"\"",
"\"",
",",
"numberDashesRight",
")",
")",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"title",
")",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"channelLines",
"...",
")",
"\n",
"}",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"repeatChar",
"(",
"\"",
"\"",
",",
"maxLen",
")",
")",
"\n",
"return",
"txt",
"\n",
"}"
] | // Print returns an array of strings suitable for printing the store limits. | [
"Print",
"returns",
"an",
"array",
"of",
"strings",
"suitable",
"for",
"printing",
"the",
"store",
"limits",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/limits.go#L188-L242 | train |
jasonlvhit/gocron | gocron.go | NewJob | func NewJob(intervel uint64) *Job {
return &Job{
intervel,
"", "", "",
time.Unix(0, 0),
time.Unix(0, 0), 0,
time.Sunday,
make(map[string]interface{}),
make(map[string]([]interface{})),
}
} | go | func NewJob(intervel uint64) *Job {
return &Job{
intervel,
"", "", "",
time.Unix(0, 0),
time.Unix(0, 0), 0,
time.Sunday,
make(map[string]interface{}),
make(map[string]([]interface{})),
}
} | [
"func",
"NewJob",
"(",
"intervel",
"uint64",
")",
"*",
"Job",
"{",
"return",
"&",
"Job",
"{",
"intervel",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
",",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
",",
"0",
",",
"time",
".",
"Sunday",
",",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
",",
"make",
"(",
"map",
"[",
"string",
"]",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
")",
",",
"}",
"\n",
"}"
] | // Create a new job with the time interval. | [
"Create",
"a",
"new",
"job",
"with",
"the",
"time",
"interval",
"."
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L72-L82 | train |
jasonlvhit/gocron | gocron.go | run | func (j *Job) run() (result []reflect.Value, err error) {
f := reflect.ValueOf(j.funcs[j.jobFunc])
params := j.fparams[j.jobFunc]
if len(params) != f.Type().NumIn() {
err = errors.New("the number of param is not adapted")
return
}
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
result = f.Call(in)
j.lastRun = time.Now()
j.scheduleNextRun()
return
} | go | func (j *Job) run() (result []reflect.Value, err error) {
f := reflect.ValueOf(j.funcs[j.jobFunc])
params := j.fparams[j.jobFunc]
if len(params) != f.Type().NumIn() {
err = errors.New("the number of param is not adapted")
return
}
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
result = f.Call(in)
j.lastRun = time.Now()
j.scheduleNextRun()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"run",
"(",
")",
"(",
"result",
"[",
"]",
"reflect",
".",
"Value",
",",
"err",
"error",
")",
"{",
"f",
":=",
"reflect",
".",
"ValueOf",
"(",
"j",
".",
"funcs",
"[",
"j",
".",
"jobFunc",
"]",
")",
"\n",
"params",
":=",
"j",
".",
"fparams",
"[",
"j",
".",
"jobFunc",
"]",
"\n",
"if",
"len",
"(",
"params",
")",
"!=",
"f",
".",
"Type",
"(",
")",
".",
"NumIn",
"(",
")",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"in",
":=",
"make",
"(",
"[",
"]",
"reflect",
".",
"Value",
",",
"len",
"(",
"params",
")",
")",
"\n",
"for",
"k",
",",
"param",
":=",
"range",
"params",
"{",
"in",
"[",
"k",
"]",
"=",
"reflect",
".",
"ValueOf",
"(",
"param",
")",
"\n",
"}",
"\n",
"result",
"=",
"f",
".",
"Call",
"(",
"in",
")",
"\n",
"j",
".",
"lastRun",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"j",
".",
"scheduleNextRun",
"(",
")",
"\n",
"return",
"\n",
"}"
] | //Run the job and immediately reschedule it | [
"Run",
"the",
"job",
"and",
"immediately",
"reschedule",
"it"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L90-L105 | train |
jasonlvhit/gocron | gocron.go | getFunctionName | func getFunctionName(fn interface{}) string {
return runtime.FuncForPC(reflect.ValueOf((fn)).Pointer()).Name()
} | go | func getFunctionName(fn interface{}) string {
return runtime.FuncForPC(reflect.ValueOf((fn)).Pointer()).Name()
} | [
"func",
"getFunctionName",
"(",
"fn",
"interface",
"{",
"}",
")",
"string",
"{",
"return",
"runtime",
".",
"FuncForPC",
"(",
"reflect",
".",
"ValueOf",
"(",
"(",
"fn",
")",
")",
".",
"Pointer",
"(",
")",
")",
".",
"Name",
"(",
")",
"\n",
"}"
] | // for given function fn, get the name of function. | [
"for",
"given",
"function",
"fn",
"get",
"the",
"name",
"of",
"function",
"."
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L108-L110 | train |
jasonlvhit/gocron | gocron.go | Do | func (j *Job) Do(jobFun interface{}, params ...interface{}) {
typ := reflect.TypeOf(jobFun)
if typ.Kind() != reflect.Func {
panic("only function can be schedule into the job queue.")
}
fname := getFunctionName(jobFun)
j.funcs[fname] = jobFun
j.fparams[fname] = params
j.jobFunc = fname
//schedule the next run
j.scheduleNextRun()
} | go | func (j *Job) Do(jobFun interface{}, params ...interface{}) {
typ := reflect.TypeOf(jobFun)
if typ.Kind() != reflect.Func {
panic("only function can be schedule into the job queue.")
}
fname := getFunctionName(jobFun)
j.funcs[fname] = jobFun
j.fparams[fname] = params
j.jobFunc = fname
//schedule the next run
j.scheduleNextRun()
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Do",
"(",
"jobFun",
"interface",
"{",
"}",
",",
"params",
"...",
"interface",
"{",
"}",
")",
"{",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"jobFun",
")",
"\n",
"if",
"typ",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Func",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"fname",
":=",
"getFunctionName",
"(",
"jobFun",
")",
"\n",
"j",
".",
"funcs",
"[",
"fname",
"]",
"=",
"jobFun",
"\n",
"j",
".",
"fparams",
"[",
"fname",
"]",
"=",
"params",
"\n",
"j",
".",
"jobFunc",
"=",
"fname",
"\n",
"//schedule the next run",
"j",
".",
"scheduleNextRun",
"(",
")",
"\n",
"}"
] | // Specifies the jobFunc that should be called every time the job runs
// | [
"Specifies",
"the",
"jobFunc",
"that",
"should",
"be",
"called",
"every",
"time",
"the",
"job",
"runs"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L114-L126 | train |
jasonlvhit/gocron | gocron.go | scheduleNextRun | func (j *Job) scheduleNextRun() {
if j.lastRun == time.Unix(0, 0) {
if j.unit == "weeks" {
i := time.Now().Weekday() - j.startDay
if i < 0 {
i = 7 + i
}
j.lastRun = time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day()-int(i), 0, 0, 0, 0, loc)
} else {
j.lastRun = time.Now()
}
}
if j.period != 0 {
// translate all the units to the Seconds
j.nextRun = j.lastRun.Add(j.period * time.Second)
} else {
switch j.unit {
case "minutes":
j.period = time.Duration(j.interval * 60)
break
case "hours":
j.period = time.Duration(j.interval * 60 * 60)
break
case "days":
j.period = time.Duration(j.interval * 60 * 60 * 24)
break
case "weeks":
j.period = time.Duration(j.interval * 60 * 60 * 24 * 7)
break
case "seconds":
j.period = time.Duration(j.interval)
}
j.nextRun = j.lastRun.Add(j.period * time.Second)
}
} | go | func (j *Job) scheduleNextRun() {
if j.lastRun == time.Unix(0, 0) {
if j.unit == "weeks" {
i := time.Now().Weekday() - j.startDay
if i < 0 {
i = 7 + i
}
j.lastRun = time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day()-int(i), 0, 0, 0, 0, loc)
} else {
j.lastRun = time.Now()
}
}
if j.period != 0 {
// translate all the units to the Seconds
j.nextRun = j.lastRun.Add(j.period * time.Second)
} else {
switch j.unit {
case "minutes":
j.period = time.Duration(j.interval * 60)
break
case "hours":
j.period = time.Duration(j.interval * 60 * 60)
break
case "days":
j.period = time.Duration(j.interval * 60 * 60 * 24)
break
case "weeks":
j.period = time.Duration(j.interval * 60 * 60 * 24 * 7)
break
case "seconds":
j.period = time.Duration(j.interval)
}
j.nextRun = j.lastRun.Add(j.period * time.Second)
}
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"scheduleNextRun",
"(",
")",
"{",
"if",
"j",
".",
"lastRun",
"==",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
"{",
"if",
"j",
".",
"unit",
"==",
"\"",
"\"",
"{",
"i",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Weekday",
"(",
")",
"-",
"j",
".",
"startDay",
"\n",
"if",
"i",
"<",
"0",
"{",
"i",
"=",
"7",
"+",
"i",
"\n",
"}",
"\n",
"j",
".",
"lastRun",
"=",
"time",
".",
"Date",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Year",
"(",
")",
",",
"time",
".",
"Now",
"(",
")",
".",
"Month",
"(",
")",
",",
"time",
".",
"Now",
"(",
")",
".",
"Day",
"(",
")",
"-",
"int",
"(",
"i",
")",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"loc",
")",
"\n\n",
"}",
"else",
"{",
"j",
".",
"lastRun",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"j",
".",
"period",
"!=",
"0",
"{",
"// translate all the units to the Seconds",
"j",
".",
"nextRun",
"=",
"j",
".",
"lastRun",
".",
"Add",
"(",
"j",
".",
"period",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"else",
"{",
"switch",
"j",
".",
"unit",
"{",
"case",
"\"",
"\"",
":",
"j",
".",
"period",
"=",
"time",
".",
"Duration",
"(",
"j",
".",
"interval",
"*",
"60",
")",
"\n",
"break",
"\n",
"case",
"\"",
"\"",
":",
"j",
".",
"period",
"=",
"time",
".",
"Duration",
"(",
"j",
".",
"interval",
"*",
"60",
"*",
"60",
")",
"\n",
"break",
"\n",
"case",
"\"",
"\"",
":",
"j",
".",
"period",
"=",
"time",
".",
"Duration",
"(",
"j",
".",
"interval",
"*",
"60",
"*",
"60",
"*",
"24",
")",
"\n",
"break",
"\n",
"case",
"\"",
"\"",
":",
"j",
".",
"period",
"=",
"time",
".",
"Duration",
"(",
"j",
".",
"interval",
"*",
"60",
"*",
"60",
"*",
"24",
"*",
"7",
")",
"\n",
"break",
"\n",
"case",
"\"",
"\"",
":",
"j",
".",
"period",
"=",
"time",
".",
"Duration",
"(",
"j",
".",
"interval",
")",
"\n",
"}",
"\n",
"j",
".",
"nextRun",
"=",
"j",
".",
"lastRun",
".",
"Add",
"(",
"j",
".",
"period",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\n",
"}"
] | //Compute the instant when this job should run next | [
"Compute",
"the",
"instant",
"when",
"this",
"job",
"should",
"run",
"next"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L184-L220 | train |
jasonlvhit/gocron | gocron.go | Second | func (j *Job) Second() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Seconds()
return
} | go | func (j *Job) Second() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Seconds()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Second",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"job",
"=",
"j",
".",
"Seconds",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // the follow functions set the job's unit with seconds,minutes,hours...
// Set the unit with second | [
"the",
"follow",
"functions",
"set",
"the",
"job",
"s",
"unit",
"with",
"seconds",
"minutes",
"hours",
"...",
"Set",
"the",
"unit",
"with",
"second"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L230-L236 | train |
jasonlvhit/gocron | gocron.go | Minute | func (j *Job) Minute() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Minutes()
return
} | go | func (j *Job) Minute() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Minutes()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Minute",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"job",
"=",
"j",
".",
"Minutes",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the unit with minute, which interval is 1 | [
"Set",
"the",
"unit",
"with",
"minute",
"which",
"interval",
"is",
"1"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L245-L251 | train |
jasonlvhit/gocron | gocron.go | Hour | func (j *Job) Hour() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Hours()
return
} | go | func (j *Job) Hour() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Hours()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Hour",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"job",
"=",
"j",
".",
"Hours",
"(",
")",
"\n",
"return",
"\n",
"}"
] | //set the unit with hour, which interval is 1 | [
"set",
"the",
"unit",
"with",
"hour",
"which",
"interval",
"is",
"1"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L260-L266 | train |
jasonlvhit/gocron | gocron.go | Day | func (j *Job) Day() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Days()
return
} | go | func (j *Job) Day() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Days()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Day",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"job",
"=",
"j",
".",
"Days",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the job's unit with day, which interval is 1 | [
"Set",
"the",
"job",
"s",
"unit",
"with",
"day",
"which",
"interval",
"is",
"1"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L275-L281 | train |
jasonlvhit/gocron | gocron.go | Tuesday | func (j *Job) Tuesday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 2
job = j.Weeks()
return
} | go | func (j *Job) Tuesday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 2
job = j.Weeks()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Tuesday",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"j",
".",
"startDay",
"=",
"2",
"\n",
"job",
"=",
"j",
".",
"Weeks",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the start day with Tuesday | [
"Set",
"the",
"start",
"day",
"with",
"Tuesday"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L301-L308 | train |
jasonlvhit/gocron | gocron.go | Wednesday | func (j *Job) Wednesday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 3
job = j.Weeks()
return
} | go | func (j *Job) Wednesday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 3
job = j.Weeks()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Wednesday",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"j",
".",
"startDay",
"=",
"3",
"\n",
"job",
"=",
"j",
".",
"Weeks",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the start day woth Wednesday | [
"Set",
"the",
"start",
"day",
"woth",
"Wednesday"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L311-L318 | train |
jasonlvhit/gocron | gocron.go | Thursday | func (j *Job) Thursday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 4
job = j.Weeks()
return
} | go | func (j *Job) Thursday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 4
job = j.Weeks()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Thursday",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"j",
".",
"startDay",
"=",
"4",
"\n",
"job",
"=",
"j",
".",
"Weeks",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the start day with thursday | [
"Set",
"the",
"start",
"day",
"with",
"thursday"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L321-L328 | train |
jasonlvhit/gocron | gocron.go | Friday | func (j *Job) Friday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 5
job = j.Weeks()
return
} | go | func (j *Job) Friday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 5
job = j.Weeks()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Friday",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"j",
".",
"startDay",
"=",
"5",
"\n",
"job",
"=",
"j",
".",
"Weeks",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the start day with friday | [
"Set",
"the",
"start",
"day",
"with",
"friday"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L331-L338 | train |
jasonlvhit/gocron | gocron.go | Saturday | func (j *Job) Saturday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 6
job = j.Weeks()
return
} | go | func (j *Job) Saturday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 6
job = j.Weeks()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Saturday",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"j",
".",
"startDay",
"=",
"6",
"\n",
"job",
"=",
"j",
".",
"Weeks",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the start day with saturday | [
"Set",
"the",
"start",
"day",
"with",
"saturday"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L341-L348 | train |
jasonlvhit/gocron | gocron.go | Sunday | func (j *Job) Sunday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 0
job = j.Weeks()
return
} | go | func (j *Job) Sunday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 0
job = j.Weeks()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Sunday",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"j",
".",
"startDay",
"=",
"0",
"\n",
"job",
"=",
"j",
".",
"Weeks",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the start day with sunday | [
"Set",
"the",
"start",
"day",
"with",
"sunday"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L351-L358 | train |
jasonlvhit/gocron | gocron.go | getRunnableJobs | func (s *Scheduler) getRunnableJobs() (running_jobs [MAXJOBNUM]*Job, n int) {
runnableJobs := [MAXJOBNUM]*Job{}
n = 0
sort.Sort(s)
for i := 0; i < s.size; i++ {
if s.jobs[i].shouldRun() {
runnableJobs[n] = s.jobs[i]
//fmt.Println(runnableJobs)
n++
} else {
break
}
}
return runnableJobs, n
} | go | func (s *Scheduler) getRunnableJobs() (running_jobs [MAXJOBNUM]*Job, n int) {
runnableJobs := [MAXJOBNUM]*Job{}
n = 0
sort.Sort(s)
for i := 0; i < s.size; i++ {
if s.jobs[i].shouldRun() {
runnableJobs[n] = s.jobs[i]
//fmt.Println(runnableJobs)
n++
} else {
break
}
}
return runnableJobs, n
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"getRunnableJobs",
"(",
")",
"(",
"running_jobs",
"[",
"MAXJOBNUM",
"]",
"*",
"Job",
",",
"n",
"int",
")",
"{",
"runnableJobs",
":=",
"[",
"MAXJOBNUM",
"]",
"*",
"Job",
"{",
"}",
"\n",
"n",
"=",
"0",
"\n",
"sort",
".",
"Sort",
"(",
"s",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"s",
".",
"size",
";",
"i",
"++",
"{",
"if",
"s",
".",
"jobs",
"[",
"i",
"]",
".",
"shouldRun",
"(",
")",
"{",
"runnableJobs",
"[",
"n",
"]",
"=",
"s",
".",
"jobs",
"[",
"i",
"]",
"\n",
"//fmt.Println(runnableJobs)",
"n",
"++",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"runnableJobs",
",",
"n",
"\n",
"}"
] | // Get the current runnable jobs, which shouldRun is True | [
"Get",
"the",
"current",
"runnable",
"jobs",
"which",
"shouldRun",
"is",
"True"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L395-L410 | train |
jasonlvhit/gocron | gocron.go | NextRun | func (s *Scheduler) NextRun() (*Job, time.Time) {
if s.size <= 0 {
return nil, time.Now()
}
sort.Sort(s)
return s.jobs[0], s.jobs[0].nextRun
} | go | func (s *Scheduler) NextRun() (*Job, time.Time) {
if s.size <= 0 {
return nil, time.Now()
}
sort.Sort(s)
return s.jobs[0], s.jobs[0].nextRun
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"NextRun",
"(",
")",
"(",
"*",
"Job",
",",
"time",
".",
"Time",
")",
"{",
"if",
"s",
".",
"size",
"<=",
"0",
"{",
"return",
"nil",
",",
"time",
".",
"Now",
"(",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"s",
")",
"\n",
"return",
"s",
".",
"jobs",
"[",
"0",
"]",
",",
"s",
".",
"jobs",
"[",
"0",
"]",
".",
"nextRun",
"\n",
"}"
] | // Datetime when the next job should run. | [
"Datetime",
"when",
"the",
"next",
"job",
"should",
"run",
"."
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L413-L419 | train |
jasonlvhit/gocron | gocron.go | Every | func (s *Scheduler) Every(interval uint64) *Job {
job := NewJob(interval)
s.jobs[s.size] = job
s.size++
return job
} | go | func (s *Scheduler) Every(interval uint64) *Job {
job := NewJob(interval)
s.jobs[s.size] = job
s.size++
return job
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Every",
"(",
"interval",
"uint64",
")",
"*",
"Job",
"{",
"job",
":=",
"NewJob",
"(",
"interval",
")",
"\n",
"s",
".",
"jobs",
"[",
"s",
".",
"size",
"]",
"=",
"job",
"\n",
"s",
".",
"size",
"++",
"\n",
"return",
"job",
"\n",
"}"
] | // Schedule a new periodic job | [
"Schedule",
"a",
"new",
"periodic",
"job"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L422-L427 | train |
jasonlvhit/gocron | gocron.go | RunPending | func (s *Scheduler) RunPending() {
runnableJobs, n := s.getRunnableJobs()
if n != 0 {
for i := 0; i < n; i++ {
runnableJobs[i].run()
}
}
} | go | func (s *Scheduler) RunPending() {
runnableJobs, n := s.getRunnableJobs()
if n != 0 {
for i := 0; i < n; i++ {
runnableJobs[i].run()
}
}
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"RunPending",
"(",
")",
"{",
"runnableJobs",
",",
"n",
":=",
"s",
".",
"getRunnableJobs",
"(",
")",
"\n\n",
"if",
"n",
"!=",
"0",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"runnableJobs",
"[",
"i",
"]",
".",
"run",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Run all the jobs that are scheduled to run. | [
"Run",
"all",
"the",
"jobs",
"that",
"are",
"scheduled",
"to",
"run",
"."
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L430-L438 | train |
jasonlvhit/gocron | gocron.go | RunAll | func (s *Scheduler) RunAll() {
for i := 0; i < s.size; i++ {
s.jobs[i].run()
}
} | go | func (s *Scheduler) RunAll() {
for i := 0; i < s.size; i++ {
s.jobs[i].run()
}
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"RunAll",
"(",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"s",
".",
"size",
";",
"i",
"++",
"{",
"s",
".",
"jobs",
"[",
"i",
"]",
".",
"run",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Run all jobs regardless if they are scheduled to run or not | [
"Run",
"all",
"jobs",
"regardless",
"if",
"they",
"are",
"scheduled",
"to",
"run",
"or",
"not"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L441-L445 | train |
jasonlvhit/gocron | gocron.go | RunAllwithDelay | func (s *Scheduler) RunAllwithDelay(d int) {
for i := 0; i < s.size; i++ {
s.jobs[i].run()
time.Sleep(time.Duration(d))
}
} | go | func (s *Scheduler) RunAllwithDelay(d int) {
for i := 0; i < s.size; i++ {
s.jobs[i].run()
time.Sleep(time.Duration(d))
}
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"RunAllwithDelay",
"(",
"d",
"int",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"s",
".",
"size",
";",
"i",
"++",
"{",
"s",
".",
"jobs",
"[",
"i",
"]",
".",
"run",
"(",
")",
"\n",
"time",
".",
"Sleep",
"(",
"time",
".",
"Duration",
"(",
"d",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Run all jobs with delay seconds | [
"Run",
"all",
"jobs",
"with",
"delay",
"seconds"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L448-L453 | train |
jasonlvhit/gocron | gocron.go | Remove | func (s *Scheduler) Remove(j interface{}) {
i := 0
found := false
for ; i < s.size; i++ {
if s.jobs[i].jobFunc == getFunctionName(j) {
found = true
break
}
}
if !found {
return
}
for j := (i + 1); j < s.size; j++ {
s.jobs[i] = s.jobs[j]
i++
}
s.size = s.size - 1
} | go | func (s *Scheduler) Remove(j interface{}) {
i := 0
found := false
for ; i < s.size; i++ {
if s.jobs[i].jobFunc == getFunctionName(j) {
found = true
break
}
}
if !found {
return
}
for j := (i + 1); j < s.size; j++ {
s.jobs[i] = s.jobs[j]
i++
}
s.size = s.size - 1
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Remove",
"(",
"j",
"interface",
"{",
"}",
")",
"{",
"i",
":=",
"0",
"\n",
"found",
":=",
"false",
"\n\n",
"for",
";",
"i",
"<",
"s",
".",
"size",
";",
"i",
"++",
"{",
"if",
"s",
".",
"jobs",
"[",
"i",
"]",
".",
"jobFunc",
"==",
"getFunctionName",
"(",
"j",
")",
"{",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"found",
"{",
"return",
"\n",
"}",
"\n\n",
"for",
"j",
":=",
"(",
"i",
"+",
"1",
")",
";",
"j",
"<",
"s",
".",
"size",
";",
"j",
"++",
"{",
"s",
".",
"jobs",
"[",
"i",
"]",
"=",
"s",
".",
"jobs",
"[",
"j",
"]",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"s",
".",
"size",
"=",
"s",
".",
"size",
"-",
"1",
"\n",
"}"
] | // Remove specific job j | [
"Remove",
"specific",
"job",
"j"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L456-L476 | train |
jasonlvhit/gocron | gocron.go | Clear | func (s *Scheduler) Clear() {
for i := 0; i < s.size; i++ {
s.jobs[i] = nil
}
s.size = 0
} | go | func (s *Scheduler) Clear() {
for i := 0; i < s.size; i++ {
s.jobs[i] = nil
}
s.size = 0
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Clear",
"(",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"s",
".",
"size",
";",
"i",
"++",
"{",
"s",
".",
"jobs",
"[",
"i",
"]",
"=",
"nil",
"\n",
"}",
"\n",
"s",
".",
"size",
"=",
"0",
"\n",
"}"
] | // Delete all scheduled jobs | [
"Delete",
"all",
"scheduled",
"jobs"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L479-L484 | train |
jasonlvhit/gocron | gocron.go | Start | func (s *Scheduler) Start() chan bool {
stopped := make(chan bool, 1)
ticker := time.NewTicker(1 * time.Second)
go func() {
for {
select {
case <-ticker.C:
s.RunPending()
case <-stopped:
return
}
}
}()
return stopped
} | go | func (s *Scheduler) Start() chan bool {
stopped := make(chan bool, 1)
ticker := time.NewTicker(1 * time.Second)
go func() {
for {
select {
case <-ticker.C:
s.RunPending()
case <-stopped:
return
}
}
}()
return stopped
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Start",
"(",
")",
"chan",
"bool",
"{",
"stopped",
":=",
"make",
"(",
"chan",
"bool",
",",
"1",
")",
"\n",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"1",
"*",
"time",
".",
"Second",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"ticker",
".",
"C",
":",
"s",
".",
"RunPending",
"(",
")",
"\n",
"case",
"<-",
"stopped",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"stopped",
"\n",
"}"
] | // Start all the pending jobs
// Add seconds ticker | [
"Start",
"all",
"the",
"pending",
"jobs",
"Add",
"seconds",
"ticker"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L488-L504 | train |
hyperledger/burrow | acm/acmstate/state.go | GlobalAccountPermissions | func GlobalAccountPermissions(getter AccountGetter) permission.AccountPermissions {
if getter == nil {
return permission.AccountPermissions{
Roles: []string{},
}
}
return GlobalPermissionsAccount(getter).Permissions
} | go | func GlobalAccountPermissions(getter AccountGetter) permission.AccountPermissions {
if getter == nil {
return permission.AccountPermissions{
Roles: []string{},
}
}
return GlobalPermissionsAccount(getter).Permissions
} | [
"func",
"GlobalAccountPermissions",
"(",
"getter",
"AccountGetter",
")",
"permission",
".",
"AccountPermissions",
"{",
"if",
"getter",
"==",
"nil",
"{",
"return",
"permission",
".",
"AccountPermissions",
"{",
"Roles",
":",
"[",
"]",
"string",
"{",
"}",
",",
"}",
"\n",
"}",
"\n",
"return",
"GlobalPermissionsAccount",
"(",
"getter",
")",
".",
"Permissions",
"\n",
"}"
] | // Get global permissions from the account at GlobalPermissionsAddress | [
"Get",
"global",
"permissions",
"from",
"the",
"account",
"at",
"GlobalPermissionsAddress"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/acmstate/state.go#L108-L115 | train |
hyperledger/burrow | execution/state/accounts.go | GetAccount | func (s *ReadState) GetAccount(address crypto.Address) (*acm.Account, error) {
tree, err := s.Forest.Reader(keys.Account.Prefix())
if err != nil {
return nil, err
}
accBytes := tree.Get(keys.Account.KeyNoPrefix(address))
if accBytes == nil {
return nil, nil
}
return acm.Decode(accBytes)
} | go | func (s *ReadState) GetAccount(address crypto.Address) (*acm.Account, error) {
tree, err := s.Forest.Reader(keys.Account.Prefix())
if err != nil {
return nil, err
}
accBytes := tree.Get(keys.Account.KeyNoPrefix(address))
if accBytes == nil {
return nil, nil
}
return acm.Decode(accBytes)
} | [
"func",
"(",
"s",
"*",
"ReadState",
")",
"GetAccount",
"(",
"address",
"crypto",
".",
"Address",
")",
"(",
"*",
"acm",
".",
"Account",
",",
"error",
")",
"{",
"tree",
",",
"err",
":=",
"s",
".",
"Forest",
".",
"Reader",
"(",
"keys",
".",
"Account",
".",
"Prefix",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"accBytes",
":=",
"tree",
".",
"Get",
"(",
"keys",
".",
"Account",
".",
"KeyNoPrefix",
"(",
"address",
")",
")",
"\n",
"if",
"accBytes",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"acm",
".",
"Decode",
"(",
"accBytes",
")",
"\n",
"}"
] | // Returns nil if account does not exist with given address. | [
"Returns",
"nil",
"if",
"account",
"does",
"not",
"exist",
"with",
"given",
"address",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/state/accounts.go#L13-L23 | train |
hyperledger/burrow | execution/state/validators.go | LoadValidatorRing | func LoadValidatorRing(version int64, ringSize int,
getImmutable func(version int64) (*storage.ImmutableForest, error)) (*validator.Ring, error) {
// In this method we have to page through previous version of the tree in order to reconstruct the in-memory
// ring structure. The corner cases are a little subtle but printing the buckets helps
// The basic idea is to load each version of the tree ringSize back, work out the difference that must have occurred
// between each bucket in the ring, and apply each diff to the ring. Once the ring is full it is symmetrical (up to
// a reindexing). If we are loading a chain whose height is less than the ring size we need to get the initial state
// correct
startVersion := version - int64(ringSize)
if startVersion < 1 {
// The ring will not be fully populated
startVersion = 1
}
var err error
// Read state to pull immutable forests from
rs := &ReadState{}
// Start with an empty ring - we want the initial bucket to have no cumulative power
ring := validator.NewRing(nil, ringSize)
// Load the IAVL state
rs.Forest, err = getImmutable(startVersion)
// Write the validator state at startVersion from IAVL tree into the ring's current bucket delta
err = validator.Write(ring, rs)
if err != nil {
return nil, err
}
// Rotate, now we have [ {bucket 0: cum: {}, delta: {start version changes} }, {bucket 1: cum: {start version changes}, delta {}, ... ]
// which is what we need (in particular we need this initial state if we are loading into a incompletely populated ring
_, _, err = ring.Rotate()
if err != nil {
return nil, err
}
// Rebuild validator Ring
for v := startVersion + 1; v <= version; v++ {
// Update IAVL read state to version of interest
rs.Forest, err = getImmutable(v)
if err != nil {
return nil, err
}
// Calculate the difference between the rings current cum and what is in state at this version
diff, err := validator.Diff(ring.CurrentSet(), rs)
if err != nil {
return nil, err
}
// Write that diff into the ring (just like it was when it was originally written to setPower)
err = validator.Write(ring, diff)
if err != nil {
return nil, err
}
// Rotate just like it was on the original commit
_, _, err = ring.Rotate()
if err != nil {
return nil, err
}
}
// Our ring should be the same up to symmetry in its index so we reindex to regain equality with the version we are loading
// This is the head index we would have had if we had started from version 1 like the chain did
ring.ReIndex(int(version % int64(ringSize)))
return ring, err
} | go | func LoadValidatorRing(version int64, ringSize int,
getImmutable func(version int64) (*storage.ImmutableForest, error)) (*validator.Ring, error) {
// In this method we have to page through previous version of the tree in order to reconstruct the in-memory
// ring structure. The corner cases are a little subtle but printing the buckets helps
// The basic idea is to load each version of the tree ringSize back, work out the difference that must have occurred
// between each bucket in the ring, and apply each diff to the ring. Once the ring is full it is symmetrical (up to
// a reindexing). If we are loading a chain whose height is less than the ring size we need to get the initial state
// correct
startVersion := version - int64(ringSize)
if startVersion < 1 {
// The ring will not be fully populated
startVersion = 1
}
var err error
// Read state to pull immutable forests from
rs := &ReadState{}
// Start with an empty ring - we want the initial bucket to have no cumulative power
ring := validator.NewRing(nil, ringSize)
// Load the IAVL state
rs.Forest, err = getImmutable(startVersion)
// Write the validator state at startVersion from IAVL tree into the ring's current bucket delta
err = validator.Write(ring, rs)
if err != nil {
return nil, err
}
// Rotate, now we have [ {bucket 0: cum: {}, delta: {start version changes} }, {bucket 1: cum: {start version changes}, delta {}, ... ]
// which is what we need (in particular we need this initial state if we are loading into a incompletely populated ring
_, _, err = ring.Rotate()
if err != nil {
return nil, err
}
// Rebuild validator Ring
for v := startVersion + 1; v <= version; v++ {
// Update IAVL read state to version of interest
rs.Forest, err = getImmutable(v)
if err != nil {
return nil, err
}
// Calculate the difference between the rings current cum and what is in state at this version
diff, err := validator.Diff(ring.CurrentSet(), rs)
if err != nil {
return nil, err
}
// Write that diff into the ring (just like it was when it was originally written to setPower)
err = validator.Write(ring, diff)
if err != nil {
return nil, err
}
// Rotate just like it was on the original commit
_, _, err = ring.Rotate()
if err != nil {
return nil, err
}
}
// Our ring should be the same up to symmetry in its index so we reindex to regain equality with the version we are loading
// This is the head index we would have had if we had started from version 1 like the chain did
ring.ReIndex(int(version % int64(ringSize)))
return ring, err
} | [
"func",
"LoadValidatorRing",
"(",
"version",
"int64",
",",
"ringSize",
"int",
",",
"getImmutable",
"func",
"(",
"version",
"int64",
")",
"(",
"*",
"storage",
".",
"ImmutableForest",
",",
"error",
")",
")",
"(",
"*",
"validator",
".",
"Ring",
",",
"error",
")",
"{",
"// In this method we have to page through previous version of the tree in order to reconstruct the in-memory",
"// ring structure. The corner cases are a little subtle but printing the buckets helps",
"// The basic idea is to load each version of the tree ringSize back, work out the difference that must have occurred",
"// between each bucket in the ring, and apply each diff to the ring. Once the ring is full it is symmetrical (up to",
"// a reindexing). If we are loading a chain whose height is less than the ring size we need to get the initial state",
"// correct",
"startVersion",
":=",
"version",
"-",
"int64",
"(",
"ringSize",
")",
"\n",
"if",
"startVersion",
"<",
"1",
"{",
"// The ring will not be fully populated",
"startVersion",
"=",
"1",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"// Read state to pull immutable forests from",
"rs",
":=",
"&",
"ReadState",
"{",
"}",
"\n",
"// Start with an empty ring - we want the initial bucket to have no cumulative power",
"ring",
":=",
"validator",
".",
"NewRing",
"(",
"nil",
",",
"ringSize",
")",
"\n",
"// Load the IAVL state",
"rs",
".",
"Forest",
",",
"err",
"=",
"getImmutable",
"(",
"startVersion",
")",
"\n",
"// Write the validator state at startVersion from IAVL tree into the ring's current bucket delta",
"err",
"=",
"validator",
".",
"Write",
"(",
"ring",
",",
"rs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// Rotate, now we have [ {bucket 0: cum: {}, delta: {start version changes} }, {bucket 1: cum: {start version changes}, delta {}, ... ]",
"// which is what we need (in particular we need this initial state if we are loading into a incompletely populated ring",
"_",
",",
"_",
",",
"err",
"=",
"ring",
".",
"Rotate",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Rebuild validator Ring",
"for",
"v",
":=",
"startVersion",
"+",
"1",
";",
"v",
"<=",
"version",
";",
"v",
"++",
"{",
"// Update IAVL read state to version of interest",
"rs",
".",
"Forest",
",",
"err",
"=",
"getImmutable",
"(",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// Calculate the difference between the rings current cum and what is in state at this version",
"diff",
",",
"err",
":=",
"validator",
".",
"Diff",
"(",
"ring",
".",
"CurrentSet",
"(",
")",
",",
"rs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// Write that diff into the ring (just like it was when it was originally written to setPower)",
"err",
"=",
"validator",
".",
"Write",
"(",
"ring",
",",
"diff",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// Rotate just like it was on the original commit",
"_",
",",
"_",
",",
"err",
"=",
"ring",
".",
"Rotate",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// Our ring should be the same up to symmetry in its index so we reindex to regain equality with the version we are loading",
"// This is the head index we would have had if we had started from version 1 like the chain did",
"ring",
".",
"ReIndex",
"(",
"int",
"(",
"version",
"%",
"int64",
"(",
"ringSize",
")",
")",
")",
"\n",
"return",
"ring",
",",
"err",
"\n",
"}"
] | // Initialises the validator Ring from the validator storage in forest | [
"Initialises",
"the",
"validator",
"Ring",
"from",
"the",
"validator",
"storage",
"in",
"forest"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/state/validators.go#L15-L77 | train |
hyperledger/burrow | storage/key_format.go | ScanBytes | func (kf *KeyFormat) ScanBytes(key []byte) [][]byte {
segments := make([][]byte, len(kf.layout))
n := kf.prefix.Length()
for i, l := range kf.layout {
if l == 0 {
// Must be final variadic segment
segments[i] = key[n:]
return segments
}
n += l
if n > len(key) {
return segments[:i]
}
segments[i] = key[n-l : n]
}
return segments
} | go | func (kf *KeyFormat) ScanBytes(key []byte) [][]byte {
segments := make([][]byte, len(kf.layout))
n := kf.prefix.Length()
for i, l := range kf.layout {
if l == 0 {
// Must be final variadic segment
segments[i] = key[n:]
return segments
}
n += l
if n > len(key) {
return segments[:i]
}
segments[i] = key[n-l : n]
}
return segments
} | [
"func",
"(",
"kf",
"*",
"KeyFormat",
")",
"ScanBytes",
"(",
"key",
"[",
"]",
"byte",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"segments",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"len",
"(",
"kf",
".",
"layout",
")",
")",
"\n",
"n",
":=",
"kf",
".",
"prefix",
".",
"Length",
"(",
")",
"\n",
"for",
"i",
",",
"l",
":=",
"range",
"kf",
".",
"layout",
"{",
"if",
"l",
"==",
"0",
"{",
"// Must be final variadic segment",
"segments",
"[",
"i",
"]",
"=",
"key",
"[",
"n",
":",
"]",
"\n",
"return",
"segments",
"\n",
"}",
"\n",
"n",
"+=",
"l",
"\n",
"if",
"n",
">",
"len",
"(",
"key",
")",
"{",
"return",
"segments",
"[",
":",
"i",
"]",
"\n",
"}",
"\n",
"segments",
"[",
"i",
"]",
"=",
"key",
"[",
"n",
"-",
"l",
":",
"n",
"]",
"\n",
"}",
"\n",
"return",
"segments",
"\n",
"}"
] | // Reads out the bytes associated with each segment of the key format from key. | [
"Reads",
"out",
"the",
"bytes",
"associated",
"with",
"each",
"segment",
"of",
"the",
"key",
"format",
"from",
"key",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/key_format.go#L111-L127 | train |
hyperledger/burrow | storage/key_format.go | ScanNoPrefix | func (kf *KeyFormat) ScanNoPrefix(key []byte, args ...interface{}) error {
// Just pad by the length of the prefix
paddedKey := make([]byte, len(kf.prefix)+len(key))
copy(paddedKey[len(kf.prefix):], key)
return kf.Scan(paddedKey, args...)
} | go | func (kf *KeyFormat) ScanNoPrefix(key []byte, args ...interface{}) error {
// Just pad by the length of the prefix
paddedKey := make([]byte, len(kf.prefix)+len(key))
copy(paddedKey[len(kf.prefix):], key)
return kf.Scan(paddedKey, args...)
} | [
"func",
"(",
"kf",
"*",
"KeyFormat",
")",
"ScanNoPrefix",
"(",
"key",
"[",
"]",
"byte",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"// Just pad by the length of the prefix",
"paddedKey",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"kf",
".",
"prefix",
")",
"+",
"len",
"(",
"key",
")",
")",
"\n",
"copy",
"(",
"paddedKey",
"[",
"len",
"(",
"kf",
".",
"prefix",
")",
":",
"]",
",",
"key",
")",
"\n",
"return",
"kf",
".",
"Scan",
"(",
"paddedKey",
",",
"args",
"...",
")",
"\n",
"}"
] | // Like Scan but adds expects a key with the KeyFormat's prefix trimmed | [
"Like",
"Scan",
"but",
"adds",
"expects",
"a",
"key",
"with",
"the",
"KeyFormat",
"s",
"prefix",
"trimmed"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/key_format.go#L149-L154 | train |
hyperledger/burrow | storage/key_format.go | KeyNoPrefix | func (kf *KeyFormat) KeyNoPrefix(args ...interface{}) (Prefix, error) {
key, err := kf.Key(args...)
if err != nil {
return nil, err
}
return key[len(kf.prefix):], nil
} | go | func (kf *KeyFormat) KeyNoPrefix(args ...interface{}) (Prefix, error) {
key, err := kf.Key(args...)
if err != nil {
return nil, err
}
return key[len(kf.prefix):], nil
} | [
"func",
"(",
"kf",
"*",
"KeyFormat",
")",
"KeyNoPrefix",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"Prefix",
",",
"error",
")",
"{",
"key",
",",
"err",
":=",
"kf",
".",
"Key",
"(",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"key",
"[",
"len",
"(",
"kf",
".",
"prefix",
")",
":",
"]",
",",
"nil",
"\n",
"}"
] | // Like Key but removes the prefix string | [
"Like",
"Key",
"but",
"removes",
"the",
"prefix",
"string"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/key_format.go#L157-L163 | train |
hyperledger/burrow | storage/key_format.go | Fix | func (kf *KeyFormat) Fix(args ...interface{}) (*KeyFormat, error) {
key, err := kf.Key(args...)
if err != nil {
return nil, err
}
return NewKeyFormat(string(key), kf.layout[len(args):]...)
} | go | func (kf *KeyFormat) Fix(args ...interface{}) (*KeyFormat, error) {
key, err := kf.Key(args...)
if err != nil {
return nil, err
}
return NewKeyFormat(string(key), kf.layout[len(args):]...)
} | [
"func",
"(",
"kf",
"*",
"KeyFormat",
")",
"Fix",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"*",
"KeyFormat",
",",
"error",
")",
"{",
"key",
",",
"err",
":=",
"kf",
".",
"Key",
"(",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"NewKeyFormat",
"(",
"string",
"(",
"key",
")",
",",
"kf",
".",
"layout",
"[",
"len",
"(",
"args",
")",
":",
"]",
"...",
")",
"\n",
"}"
] | // Fixes the first args many segments as the prefix of a new KeyFormat by using the args to generate a key that becomes
// that prefix. Any remaining unassigned segments become the layout of the new KeyFormat. | [
"Fixes",
"the",
"first",
"args",
"many",
"segments",
"as",
"the",
"prefix",
"of",
"a",
"new",
"KeyFormat",
"by",
"using",
"the",
"args",
"to",
"generate",
"a",
"key",
"that",
"becomes",
"that",
"prefix",
".",
"Any",
"remaining",
"unassigned",
"segments",
"become",
"the",
"layout",
"of",
"the",
"new",
"KeyFormat",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/key_format.go#L167-L173 | train |
hyperledger/burrow | storage/key_format.go | Iterator | func (kf *KeyFormat) Iterator(iterable KVIterable, start, end []byte, reverse ...bool) KVIterator {
if len(reverse) > 0 && reverse[0] {
return kf.prefix.Iterator(iterable.ReverseIterator, start, end)
}
return kf.prefix.Iterator(iterable.Iterator, start, end)
} | go | func (kf *KeyFormat) Iterator(iterable KVIterable, start, end []byte, reverse ...bool) KVIterator {
if len(reverse) > 0 && reverse[0] {
return kf.prefix.Iterator(iterable.ReverseIterator, start, end)
}
return kf.prefix.Iterator(iterable.Iterator, start, end)
} | [
"func",
"(",
"kf",
"*",
"KeyFormat",
")",
"Iterator",
"(",
"iterable",
"KVIterable",
",",
"start",
",",
"end",
"[",
"]",
"byte",
",",
"reverse",
"...",
"bool",
")",
"KVIterator",
"{",
"if",
"len",
"(",
"reverse",
")",
">",
"0",
"&&",
"reverse",
"[",
"0",
"]",
"{",
"return",
"kf",
".",
"prefix",
".",
"Iterator",
"(",
"iterable",
".",
"ReverseIterator",
",",
"start",
",",
"end",
")",
"\n",
"}",
"\n",
"return",
"kf",
".",
"prefix",
".",
"Iterator",
"(",
"iterable",
".",
"Iterator",
",",
"start",
",",
"end",
")",
"\n",
"}"
] | // Returns an iterator over the underlying iterable using this KeyFormat's prefix. This is to support proper iteration over the
// prefix in the presence of nil start or end which requests iteration to the inclusive edges of the domain. An optional
// argument for reverse can be passed to get reverse iteration. | [
"Returns",
"an",
"iterator",
"over",
"the",
"underlying",
"iterable",
"using",
"this",
"KeyFormat",
"s",
"prefix",
".",
"This",
"is",
"to",
"support",
"proper",
"iteration",
"over",
"the",
"prefix",
"in",
"the",
"presence",
"of",
"nil",
"start",
"or",
"end",
"which",
"requests",
"iteration",
"to",
"the",
"inclusive",
"edges",
"of",
"the",
"domain",
".",
"An",
"optional",
"argument",
"for",
"reverse",
"can",
"be",
"passed",
"to",
"get",
"reverse",
"iteration",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/key_format.go#L178-L183 | train |
hyperledger/burrow | vent/service/server.go | NewServer | func NewServer(cfg *config.VentConfig, log *logger.Logger, consumer *Consumer) *Server {
// setup handlers
mux := http.NewServeMux()
mux.HandleFunc("/health", healthHandler(consumer))
return &Server{
Config: cfg,
Log: log,
Consumer: consumer,
mux: mux,
stopCh: make(chan bool, 1),
}
} | go | func NewServer(cfg *config.VentConfig, log *logger.Logger, consumer *Consumer) *Server {
// setup handlers
mux := http.NewServeMux()
mux.HandleFunc("/health", healthHandler(consumer))
return &Server{
Config: cfg,
Log: log,
Consumer: consumer,
mux: mux,
stopCh: make(chan bool, 1),
}
} | [
"func",
"NewServer",
"(",
"cfg",
"*",
"config",
".",
"VentConfig",
",",
"log",
"*",
"logger",
".",
"Logger",
",",
"consumer",
"*",
"Consumer",
")",
"*",
"Server",
"{",
"// setup handlers",
"mux",
":=",
"http",
".",
"NewServeMux",
"(",
")",
"\n\n",
"mux",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"healthHandler",
"(",
"consumer",
")",
")",
"\n\n",
"return",
"&",
"Server",
"{",
"Config",
":",
"cfg",
",",
"Log",
":",
"log",
",",
"Consumer",
":",
"consumer",
",",
"mux",
":",
"mux",
",",
"stopCh",
":",
"make",
"(",
"chan",
"bool",
",",
"1",
")",
",",
"}",
"\n",
"}"
] | // NewServer returns a new HTTP server | [
"NewServer",
"returns",
"a",
"new",
"HTTP",
"server"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/service/server.go#L21-L34 | train |
hyperledger/burrow | vent/service/server.go | Run | func (s *Server) Run() {
s.Log.Info("msg", "Starting HTTP Server")
// start http server
httpServer := &http.Server{Addr: s.Config.HTTPAddr, Handler: s}
go func() {
s.Log.Info("msg", "HTTP Server listening", "address", s.Config.HTTPAddr)
httpServer.ListenAndServe()
}()
// wait for stop signal
<-s.stopCh
s.Log.Info("msg", "Shutting down HTTP Server...")
httpServer.Shutdown(context.Background())
} | go | func (s *Server) Run() {
s.Log.Info("msg", "Starting HTTP Server")
// start http server
httpServer := &http.Server{Addr: s.Config.HTTPAddr, Handler: s}
go func() {
s.Log.Info("msg", "HTTP Server listening", "address", s.Config.HTTPAddr)
httpServer.ListenAndServe()
}()
// wait for stop signal
<-s.stopCh
s.Log.Info("msg", "Shutting down HTTP Server...")
httpServer.Shutdown(context.Background())
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Run",
"(",
")",
"{",
"s",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// start http server",
"httpServer",
":=",
"&",
"http",
".",
"Server",
"{",
"Addr",
":",
"s",
".",
"Config",
".",
"HTTPAddr",
",",
"Handler",
":",
"s",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"s",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"s",
".",
"Config",
".",
"HTTPAddr",
")",
"\n",
"httpServer",
".",
"ListenAndServe",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"// wait for stop signal",
"<-",
"s",
".",
"stopCh",
"\n\n",
"s",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"httpServer",
".",
"Shutdown",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n",
"}"
] | // Run starts the HTTP server | [
"Run",
"starts",
"the",
"HTTP",
"server"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/service/server.go#L37-L54 | train |
hyperledger/burrow | vent/service/server.go | ServeHTTP | func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
s.mux.ServeHTTP(resp, req)
} | go | func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
s.mux.ServeHTTP(resp, req)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ServeHTTP",
"(",
"resp",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"s",
".",
"mux",
".",
"ServeHTTP",
"(",
"resp",
",",
"req",
")",
"\n",
"}"
] | // ServeHTTP dispatches the HTTP requests using the Server Mux | [
"ServeHTTP",
"dispatches",
"the",
"HTTP",
"requests",
"using",
"the",
"Server",
"Mux"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/service/server.go#L57-L59 | train |
hyperledger/burrow | vent/service/rowbuilder.go | buildEventData | func buildEventData(projection *sqlsol.Projection, eventClass *types.EventClass, event *exec.Event, abiSpec *abi.AbiSpec,
l *logger.Logger) (types.EventDataRow, error) {
// a fresh new row to store column/value data
row := make(map[string]interface{})
// get header & log data for the given event
eventHeader := event.GetHeader()
eventLog := event.GetLog()
// decode event data using the provided abi specification
decodedData, err := decodeEvent(eventHeader, eventLog, abiSpec)
if err != nil {
return types.EventDataRow{}, errors.Wrapf(err, "Error decoding event (filter: %s)", eventClass.Filter)
}
l.Info("msg", fmt.Sprintf("Unpacked data: %v", decodedData), "eventName", decodedData[types.EventNameLabel])
rowAction := types.ActionUpsert
// for each data element, maps to SQL columnName and gets its value
// if there is no matching column for the item, it doesn't need to be stored in db
for fieldName, value := range decodedData {
// Can't think of case where we will get a key that is empty, but if we ever did we should not treat
// it as a delete marker when the delete marker field in unset
if eventClass.DeleteMarkerField != "" && eventClass.DeleteMarkerField == fieldName {
rowAction = types.ActionDelete
}
fieldMapping := eventClass.GetFieldMapping(fieldName)
if fieldMapping == nil {
continue
}
column, err := projection.GetColumn(eventClass.TableName, fieldMapping.ColumnName)
if err == nil {
if fieldMapping.BytesToString {
if bs, ok := value.(*[]byte); ok {
str := sanitiseBytesForString(*bs, l)
row[column.Name] = interface{}(str)
continue
}
}
row[column.Name] = value
} else {
l.Debug("msg", "could not get column", "err", err)
}
}
return types.EventDataRow{Action: rowAction, RowData: row, EventClass: eventClass}, nil
} | go | func buildEventData(projection *sqlsol.Projection, eventClass *types.EventClass, event *exec.Event, abiSpec *abi.AbiSpec,
l *logger.Logger) (types.EventDataRow, error) {
// a fresh new row to store column/value data
row := make(map[string]interface{})
// get header & log data for the given event
eventHeader := event.GetHeader()
eventLog := event.GetLog()
// decode event data using the provided abi specification
decodedData, err := decodeEvent(eventHeader, eventLog, abiSpec)
if err != nil {
return types.EventDataRow{}, errors.Wrapf(err, "Error decoding event (filter: %s)", eventClass.Filter)
}
l.Info("msg", fmt.Sprintf("Unpacked data: %v", decodedData), "eventName", decodedData[types.EventNameLabel])
rowAction := types.ActionUpsert
// for each data element, maps to SQL columnName and gets its value
// if there is no matching column for the item, it doesn't need to be stored in db
for fieldName, value := range decodedData {
// Can't think of case where we will get a key that is empty, but if we ever did we should not treat
// it as a delete marker when the delete marker field in unset
if eventClass.DeleteMarkerField != "" && eventClass.DeleteMarkerField == fieldName {
rowAction = types.ActionDelete
}
fieldMapping := eventClass.GetFieldMapping(fieldName)
if fieldMapping == nil {
continue
}
column, err := projection.GetColumn(eventClass.TableName, fieldMapping.ColumnName)
if err == nil {
if fieldMapping.BytesToString {
if bs, ok := value.(*[]byte); ok {
str := sanitiseBytesForString(*bs, l)
row[column.Name] = interface{}(str)
continue
}
}
row[column.Name] = value
} else {
l.Debug("msg", "could not get column", "err", err)
}
}
return types.EventDataRow{Action: rowAction, RowData: row, EventClass: eventClass}, nil
} | [
"func",
"buildEventData",
"(",
"projection",
"*",
"sqlsol",
".",
"Projection",
",",
"eventClass",
"*",
"types",
".",
"EventClass",
",",
"event",
"*",
"exec",
".",
"Event",
",",
"abiSpec",
"*",
"abi",
".",
"AbiSpec",
",",
"l",
"*",
"logger",
".",
"Logger",
")",
"(",
"types",
".",
"EventDataRow",
",",
"error",
")",
"{",
"// a fresh new row to store column/value data",
"row",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n\n",
"// get header & log data for the given event",
"eventHeader",
":=",
"event",
".",
"GetHeader",
"(",
")",
"\n",
"eventLog",
":=",
"event",
".",
"GetLog",
"(",
")",
"\n\n",
"// decode event data using the provided abi specification",
"decodedData",
",",
"err",
":=",
"decodeEvent",
"(",
"eventHeader",
",",
"eventLog",
",",
"abiSpec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"eventClass",
".",
"Filter",
")",
"\n",
"}",
"\n\n",
"l",
".",
"Info",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"decodedData",
")",
",",
"\"",
"\"",
",",
"decodedData",
"[",
"types",
".",
"EventNameLabel",
"]",
")",
"\n\n",
"rowAction",
":=",
"types",
".",
"ActionUpsert",
"\n\n",
"// for each data element, maps to SQL columnName and gets its value",
"// if there is no matching column for the item, it doesn't need to be stored in db",
"for",
"fieldName",
",",
"value",
":=",
"range",
"decodedData",
"{",
"// Can't think of case where we will get a key that is empty, but if we ever did we should not treat",
"// it as a delete marker when the delete marker field in unset",
"if",
"eventClass",
".",
"DeleteMarkerField",
"!=",
"\"",
"\"",
"&&",
"eventClass",
".",
"DeleteMarkerField",
"==",
"fieldName",
"{",
"rowAction",
"=",
"types",
".",
"ActionDelete",
"\n",
"}",
"\n",
"fieldMapping",
":=",
"eventClass",
".",
"GetFieldMapping",
"(",
"fieldName",
")",
"\n",
"if",
"fieldMapping",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"column",
",",
"err",
":=",
"projection",
".",
"GetColumn",
"(",
"eventClass",
".",
"TableName",
",",
"fieldMapping",
".",
"ColumnName",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"if",
"fieldMapping",
".",
"BytesToString",
"{",
"if",
"bs",
",",
"ok",
":=",
"value",
".",
"(",
"*",
"[",
"]",
"byte",
")",
";",
"ok",
"{",
"str",
":=",
"sanitiseBytesForString",
"(",
"*",
"bs",
",",
"l",
")",
"\n",
"row",
"[",
"column",
".",
"Name",
"]",
"=",
"interface",
"{",
"}",
"(",
"str",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"row",
"[",
"column",
".",
"Name",
"]",
"=",
"value",
"\n",
"}",
"else",
"{",
"l",
".",
"Debug",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"types",
".",
"EventDataRow",
"{",
"Action",
":",
"rowAction",
",",
"RowData",
":",
"row",
",",
"EventClass",
":",
"eventClass",
"}",
",",
"nil",
"\n",
"}"
] | // buildEventData builds event data from transactions | [
"buildEventData",
"builds",
"event",
"data",
"from",
"transactions"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/service/rowbuilder.go#L19-L67 | train |
hyperledger/burrow | vent/service/rowbuilder.go | buildBlkData | func buildBlkData(tbls types.EventTables, block *exec.BlockExecution) (types.EventDataRow, error) {
// a fresh new row to store column/value data
row := make(map[string]interface{})
// block raw data
if _, ok := tbls[types.SQLBlockTableName]; ok {
blockHeader, err := json.Marshal(block.Header)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("Couldn't marshal BlockHeader in block %v", block)
}
row[types.SQLColumnLabelHeight] = fmt.Sprintf("%v", block.Height)
row[types.SQLColumnLabelBlockHeader] = string(blockHeader)
} else {
return types.EventDataRow{}, fmt.Errorf("table: %s not found in table structure %v", types.SQLBlockTableName, tbls)
}
return types.EventDataRow{Action: types.ActionUpsert, RowData: row}, nil
} | go | func buildBlkData(tbls types.EventTables, block *exec.BlockExecution) (types.EventDataRow, error) {
// a fresh new row to store column/value data
row := make(map[string]interface{})
// block raw data
if _, ok := tbls[types.SQLBlockTableName]; ok {
blockHeader, err := json.Marshal(block.Header)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("Couldn't marshal BlockHeader in block %v", block)
}
row[types.SQLColumnLabelHeight] = fmt.Sprintf("%v", block.Height)
row[types.SQLColumnLabelBlockHeader] = string(blockHeader)
} else {
return types.EventDataRow{}, fmt.Errorf("table: %s not found in table structure %v", types.SQLBlockTableName, tbls)
}
return types.EventDataRow{Action: types.ActionUpsert, RowData: row}, nil
} | [
"func",
"buildBlkData",
"(",
"tbls",
"types",
".",
"EventTables",
",",
"block",
"*",
"exec",
".",
"BlockExecution",
")",
"(",
"types",
".",
"EventDataRow",
",",
"error",
")",
"{",
"// a fresh new row to store column/value data",
"row",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n\n",
"// block raw data",
"if",
"_",
",",
"ok",
":=",
"tbls",
"[",
"types",
".",
"SQLBlockTableName",
"]",
";",
"ok",
"{",
"blockHeader",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"block",
".",
"Header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"block",
")",
"\n",
"}",
"\n\n",
"row",
"[",
"types",
".",
"SQLColumnLabelHeight",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"block",
".",
"Height",
")",
"\n",
"row",
"[",
"types",
".",
"SQLColumnLabelBlockHeader",
"]",
"=",
"string",
"(",
"blockHeader",
")",
"\n",
"}",
"else",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"types",
".",
"SQLBlockTableName",
",",
"tbls",
")",
"\n",
"}",
"\n\n",
"return",
"types",
".",
"EventDataRow",
"{",
"Action",
":",
"types",
".",
"ActionUpsert",
",",
"RowData",
":",
"row",
"}",
",",
"nil",
"\n",
"}"
] | // buildBlkData builds block data from block stream | [
"buildBlkData",
"builds",
"block",
"data",
"from",
"block",
"stream"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/service/rowbuilder.go#L70-L88 | train |
hyperledger/burrow | vent/service/rowbuilder.go | buildTxData | func buildTxData(txe *exec.TxExecution) (types.EventDataRow, error) {
// transaction raw data
envelope, err := json.Marshal(txe.Envelope)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal envelope in tx %v", txe)
}
events, err := json.Marshal(txe.Events)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal events in tx %v", txe)
}
result, err := json.Marshal(txe.Result)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal result in tx %v", txe)
}
receipt, err := json.Marshal(txe.Receipt)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal receipt in tx %v", txe)
}
exception, err := json.Marshal(txe.Exception)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal exception in tx %v", txe)
}
return types.EventDataRow{
Action: types.ActionUpsert,
RowData: map[string]interface{}{
types.SQLColumnLabelHeight: txe.Height,
types.SQLColumnLabelTxHash: txe.TxHash.String(),
types.SQLColumnLabelIndex: txe.Index,
types.SQLColumnLabelTxType: txe.TxType.String(),
types.SQLColumnLabelEnvelope: string(envelope),
types.SQLColumnLabelEvents: string(events),
types.SQLColumnLabelResult: string(result),
types.SQLColumnLabelReceipt: string(receipt),
types.SQLColumnLabelException: string(exception),
},
}, nil
} | go | func buildTxData(txe *exec.TxExecution) (types.EventDataRow, error) {
// transaction raw data
envelope, err := json.Marshal(txe.Envelope)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal envelope in tx %v", txe)
}
events, err := json.Marshal(txe.Events)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal events in tx %v", txe)
}
result, err := json.Marshal(txe.Result)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal result in tx %v", txe)
}
receipt, err := json.Marshal(txe.Receipt)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal receipt in tx %v", txe)
}
exception, err := json.Marshal(txe.Exception)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal exception in tx %v", txe)
}
return types.EventDataRow{
Action: types.ActionUpsert,
RowData: map[string]interface{}{
types.SQLColumnLabelHeight: txe.Height,
types.SQLColumnLabelTxHash: txe.TxHash.String(),
types.SQLColumnLabelIndex: txe.Index,
types.SQLColumnLabelTxType: txe.TxType.String(),
types.SQLColumnLabelEnvelope: string(envelope),
types.SQLColumnLabelEvents: string(events),
types.SQLColumnLabelResult: string(result),
types.SQLColumnLabelReceipt: string(receipt),
types.SQLColumnLabelException: string(exception),
},
}, nil
} | [
"func",
"buildTxData",
"(",
"txe",
"*",
"exec",
".",
"TxExecution",
")",
"(",
"types",
".",
"EventDataRow",
",",
"error",
")",
"{",
"// transaction raw data",
"envelope",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"txe",
".",
"Envelope",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"txe",
")",
"\n",
"}",
"\n\n",
"events",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"txe",
".",
"Events",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"txe",
")",
"\n",
"}",
"\n\n",
"result",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"txe",
".",
"Result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"txe",
")",
"\n",
"}",
"\n\n",
"receipt",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"txe",
".",
"Receipt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"txe",
")",
"\n",
"}",
"\n\n",
"exception",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"txe",
".",
"Exception",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"txe",
")",
"\n",
"}",
"\n",
"return",
"types",
".",
"EventDataRow",
"{",
"Action",
":",
"types",
".",
"ActionUpsert",
",",
"RowData",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"types",
".",
"SQLColumnLabelHeight",
":",
"txe",
".",
"Height",
",",
"types",
".",
"SQLColumnLabelTxHash",
":",
"txe",
".",
"TxHash",
".",
"String",
"(",
")",
",",
"types",
".",
"SQLColumnLabelIndex",
":",
"txe",
".",
"Index",
",",
"types",
".",
"SQLColumnLabelTxType",
":",
"txe",
".",
"TxType",
".",
"String",
"(",
")",
",",
"types",
".",
"SQLColumnLabelEnvelope",
":",
"string",
"(",
"envelope",
")",
",",
"types",
".",
"SQLColumnLabelEvents",
":",
"string",
"(",
"events",
")",
",",
"types",
".",
"SQLColumnLabelResult",
":",
"string",
"(",
"result",
")",
",",
"types",
".",
"SQLColumnLabelReceipt",
":",
"string",
"(",
"receipt",
")",
",",
"types",
".",
"SQLColumnLabelException",
":",
"string",
"(",
"exception",
")",
",",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // buildTxData builds transaction data from tx stream | [
"buildTxData",
"builds",
"transaction",
"data",
"from",
"tx",
"stream"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/service/rowbuilder.go#L91-L131 | train |
hyperledger/burrow | event/pubsub/pubsub.go | NewServer | func NewServer(options ...Option) *Server {
s := &Server{
subscriptions: make(map[string]map[string]query.Query),
}
s.BaseService = *common.NewBaseService(nil, "PubSub", s)
for _, option := range options {
option(s)
}
// if BufferCapacity option was not set, the channel is unbuffered
s.cmds = make(chan cmd, s.cmdsCap)
return s
} | go | func NewServer(options ...Option) *Server {
s := &Server{
subscriptions: make(map[string]map[string]query.Query),
}
s.BaseService = *common.NewBaseService(nil, "PubSub", s)
for _, option := range options {
option(s)
}
// if BufferCapacity option was not set, the channel is unbuffered
s.cmds = make(chan cmd, s.cmdsCap)
return s
} | [
"func",
"NewServer",
"(",
"options",
"...",
"Option",
")",
"*",
"Server",
"{",
"s",
":=",
"&",
"Server",
"{",
"subscriptions",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"query",
".",
"Query",
")",
",",
"}",
"\n",
"s",
".",
"BaseService",
"=",
"*",
"common",
".",
"NewBaseService",
"(",
"nil",
",",
"\"",
"\"",
",",
"s",
")",
"\n\n",
"for",
"_",
",",
"option",
":=",
"range",
"options",
"{",
"option",
"(",
"s",
")",
"\n",
"}",
"\n\n",
"// if BufferCapacity option was not set, the channel is unbuffered",
"s",
".",
"cmds",
"=",
"make",
"(",
"chan",
"cmd",
",",
"s",
".",
"cmdsCap",
")",
"\n\n",
"return",
"s",
"\n",
"}"
] | // NewServer returns a new server. See the commentary on the Option functions
// for a detailed description of how to configure buffering. If no options are
// provided, the resulting server's queue is unbuffered. | [
"NewServer",
"returns",
"a",
"new",
"server",
".",
"See",
"the",
"commentary",
"on",
"the",
"Option",
"functions",
"for",
"a",
"detailed",
"description",
"of",
"how",
"to",
"configure",
"buffering",
".",
"If",
"no",
"options",
"are",
"provided",
"the",
"resulting",
"server",
"s",
"queue",
"is",
"unbuffered",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/pubsub/pubsub.go#L71-L85 | train |
hyperledger/burrow | event/pubsub/pubsub.go | Subscribe | func (s *Server) Subscribe(ctx context.Context, clientID string, qry query.Query, outBuffer int) (<-chan interface{}, error) {
s.mtx.RLock()
clientSubscriptions, ok := s.subscriptions[clientID]
if ok {
_, ok = clientSubscriptions[qry.String()]
}
s.mtx.RUnlock()
if ok {
return nil, ErrAlreadySubscribed
}
// We are responsible for closing this channel so we create it
out := make(chan interface{}, outBuffer)
select {
case s.cmds <- cmd{op: sub, clientID: clientID, query: qry, ch: out}:
s.mtx.Lock()
if _, ok = s.subscriptions[clientID]; !ok {
s.subscriptions[clientID] = make(map[string]query.Query)
}
// preserve original query
// see Unsubscribe
s.subscriptions[clientID][qry.String()] = qry
s.mtx.Unlock()
return out, nil
case <-ctx.Done():
return nil, ctx.Err()
}
} | go | func (s *Server) Subscribe(ctx context.Context, clientID string, qry query.Query, outBuffer int) (<-chan interface{}, error) {
s.mtx.RLock()
clientSubscriptions, ok := s.subscriptions[clientID]
if ok {
_, ok = clientSubscriptions[qry.String()]
}
s.mtx.RUnlock()
if ok {
return nil, ErrAlreadySubscribed
}
// We are responsible for closing this channel so we create it
out := make(chan interface{}, outBuffer)
select {
case s.cmds <- cmd{op: sub, clientID: clientID, query: qry, ch: out}:
s.mtx.Lock()
if _, ok = s.subscriptions[clientID]; !ok {
s.subscriptions[clientID] = make(map[string]query.Query)
}
// preserve original query
// see Unsubscribe
s.subscriptions[clientID][qry.String()] = qry
s.mtx.Unlock()
return out, nil
case <-ctx.Done():
return nil, ctx.Err()
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Subscribe",
"(",
"ctx",
"context",
".",
"Context",
",",
"clientID",
"string",
",",
"qry",
"query",
".",
"Query",
",",
"outBuffer",
"int",
")",
"(",
"<-",
"chan",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"s",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"clientSubscriptions",
",",
"ok",
":=",
"s",
".",
"subscriptions",
"[",
"clientID",
"]",
"\n",
"if",
"ok",
"{",
"_",
",",
"ok",
"=",
"clientSubscriptions",
"[",
"qry",
".",
"String",
"(",
")",
"]",
"\n",
"}",
"\n",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"ok",
"{",
"return",
"nil",
",",
"ErrAlreadySubscribed",
"\n",
"}",
"\n",
"// We are responsible for closing this channel so we create it",
"out",
":=",
"make",
"(",
"chan",
"interface",
"{",
"}",
",",
"outBuffer",
")",
"\n",
"select",
"{",
"case",
"s",
".",
"cmds",
"<-",
"cmd",
"{",
"op",
":",
"sub",
",",
"clientID",
":",
"clientID",
",",
"query",
":",
"qry",
",",
"ch",
":",
"out",
"}",
":",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
"=",
"s",
".",
"subscriptions",
"[",
"clientID",
"]",
";",
"!",
"ok",
"{",
"s",
".",
"subscriptions",
"[",
"clientID",
"]",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"query",
".",
"Query",
")",
"\n",
"}",
"\n",
"// preserve original query",
"// see Unsubscribe",
"s",
".",
"subscriptions",
"[",
"clientID",
"]",
"[",
"qry",
".",
"String",
"(",
")",
"]",
"=",
"qry",
"\n",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"return",
"out",
",",
"nil",
"\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"nil",
",",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Subscribe creates a subscription for the given client. It accepts a channel
// on which messages matching the given query can be received. An error will be
// returned to the caller if the context is canceled or if subscription already
// exist for pair clientID and query. | [
"Subscribe",
"creates",
"a",
"subscription",
"for",
"the",
"given",
"client",
".",
"It",
"accepts",
"a",
"channel",
"on",
"which",
"messages",
"matching",
"the",
"given",
"query",
"can",
"be",
"received",
".",
"An",
"error",
"will",
"be",
"returned",
"to",
"the",
"caller",
"if",
"the",
"context",
"is",
"canceled",
"or",
"if",
"subscription",
"already",
"exist",
"for",
"pair",
"clientID",
"and",
"query",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/pubsub/pubsub.go#L108-L134 | train |
hyperledger/burrow | event/pubsub/pubsub.go | Publish | func (s *Server) Publish(ctx context.Context, msg interface{}) error {
return s.PublishWithTags(ctx, msg, query.TagMap(make(map[string]interface{})))
} | go | func (s *Server) Publish(ctx context.Context, msg interface{}) error {
return s.PublishWithTags(ctx, msg, query.TagMap(make(map[string]interface{})))
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Publish",
"(",
"ctx",
"context",
".",
"Context",
",",
"msg",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"s",
".",
"PublishWithTags",
"(",
"ctx",
",",
"msg",
",",
"query",
".",
"TagMap",
"(",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
")",
")",
"\n",
"}"
] | // Publish publishes the given message. An error will be returned to the caller
// if the context is canceled. | [
"Publish",
"publishes",
"the",
"given",
"message",
".",
"An",
"error",
"will",
"be",
"returned",
"to",
"the",
"caller",
"if",
"the",
"context",
"is",
"canceled",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/pubsub/pubsub.go#L186-L188 | train |
hyperledger/burrow | event/pubsub/pubsub.go | PublishWithTags | func (s *Server) PublishWithTags(ctx context.Context, msg interface{}, tags query.Tagged) error {
select {
case s.cmds <- cmd{op: pub, msg: msg, tags: tags}:
return nil
case <-ctx.Done():
return ctx.Err()
}
} | go | func (s *Server) PublishWithTags(ctx context.Context, msg interface{}, tags query.Tagged) error {
select {
case s.cmds <- cmd{op: pub, msg: msg, tags: tags}:
return nil
case <-ctx.Done():
return ctx.Err()
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"PublishWithTags",
"(",
"ctx",
"context",
".",
"Context",
",",
"msg",
"interface",
"{",
"}",
",",
"tags",
"query",
".",
"Tagged",
")",
"error",
"{",
"select",
"{",
"case",
"s",
".",
"cmds",
"<-",
"cmd",
"{",
"op",
":",
"pub",
",",
"msg",
":",
"msg",
",",
"tags",
":",
"tags",
"}",
":",
"return",
"nil",
"\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // PublishWithTags publishes the given message with the set of tags. The set is
// matched with clients queries. If there is a match, the message is sent to
// the client. | [
"PublishWithTags",
"publishes",
"the",
"given",
"message",
"with",
"the",
"set",
"of",
"tags",
".",
"The",
"set",
"is",
"matched",
"with",
"clients",
"queries",
".",
"If",
"there",
"is",
"a",
"match",
"the",
"message",
"is",
"sent",
"to",
"the",
"client",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/pubsub/pubsub.go#L193-L200 | train |
hyperledger/burrow | logging/loggers/sort_logger.go | SortLogger | func SortLogger(outputLogger log.Logger, keys ...string) log.Logger {
indices := make(map[string]int, len(keys))
for i, k := range keys {
indices[k] = i
}
return log.LoggerFunc(func(keyvals ...interface{}) error {
sortKeyvals(indices, keyvals)
return outputLogger.Log(keyvals...)
})
} | go | func SortLogger(outputLogger log.Logger, keys ...string) log.Logger {
indices := make(map[string]int, len(keys))
for i, k := range keys {
indices[k] = i
}
return log.LoggerFunc(func(keyvals ...interface{}) error {
sortKeyvals(indices, keyvals)
return outputLogger.Log(keyvals...)
})
} | [
"func",
"SortLogger",
"(",
"outputLogger",
"log",
".",
"Logger",
",",
"keys",
"...",
"string",
")",
"log",
".",
"Logger",
"{",
"indices",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"int",
",",
"len",
"(",
"keys",
")",
")",
"\n",
"for",
"i",
",",
"k",
":=",
"range",
"keys",
"{",
"indices",
"[",
"k",
"]",
"=",
"i",
"\n",
"}",
"\n",
"return",
"log",
".",
"LoggerFunc",
"(",
"func",
"(",
"keyvals",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"sortKeyvals",
"(",
"indices",
",",
"keyvals",
")",
"\n",
"return",
"outputLogger",
".",
"Log",
"(",
"keyvals",
"...",
")",
"\n",
"}",
")",
"\n",
"}"
] | // Provides a logger that sorts key-values with keys in keys before other key-values | [
"Provides",
"a",
"logger",
"that",
"sorts",
"key",
"-",
"values",
"with",
"keys",
"in",
"keys",
"before",
"other",
"key",
"-",
"values"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/logging/loggers/sort_logger.go#L63-L72 | train |
hyperledger/burrow | permission/account_permissions.go | HasRole | func (ap AccountPermissions) HasRole(role string) bool {
role = string(binary.RightPadBytes([]byte(role), 32))
for _, r := range ap.Roles {
if r == role {
return true
}
}
return false
} | go | func (ap AccountPermissions) HasRole(role string) bool {
role = string(binary.RightPadBytes([]byte(role), 32))
for _, r := range ap.Roles {
if r == role {
return true
}
}
return false
} | [
"func",
"(",
"ap",
"AccountPermissions",
")",
"HasRole",
"(",
"role",
"string",
")",
"bool",
"{",
"role",
"=",
"string",
"(",
"binary",
".",
"RightPadBytes",
"(",
"[",
"]",
"byte",
"(",
"role",
")",
",",
"32",
")",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"ap",
".",
"Roles",
"{",
"if",
"r",
"==",
"role",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Returns true if the role is found | [
"Returns",
"true",
"if",
"the",
"role",
"is",
"found"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/permission/account_permissions.go#L19-L27 | train |
hyperledger/burrow | permission/account_permissions.go | RemoveRole | func (ap *AccountPermissions) RemoveRole(role string) bool {
role = string(binary.RightPadBytes([]byte(role), 32))
for i, r := range ap.Roles {
if r == role {
post := []string{}
if len(ap.Roles) > i+1 {
post = ap.Roles[i+1:]
}
ap.Roles = append(ap.Roles[:i], post...)
return true
}
}
return false
} | go | func (ap *AccountPermissions) RemoveRole(role string) bool {
role = string(binary.RightPadBytes([]byte(role), 32))
for i, r := range ap.Roles {
if r == role {
post := []string{}
if len(ap.Roles) > i+1 {
post = ap.Roles[i+1:]
}
ap.Roles = append(ap.Roles[:i], post...)
return true
}
}
return false
} | [
"func",
"(",
"ap",
"*",
"AccountPermissions",
")",
"RemoveRole",
"(",
"role",
"string",
")",
"bool",
"{",
"role",
"=",
"string",
"(",
"binary",
".",
"RightPadBytes",
"(",
"[",
"]",
"byte",
"(",
"role",
")",
",",
"32",
")",
")",
"\n",
"for",
"i",
",",
"r",
":=",
"range",
"ap",
".",
"Roles",
"{",
"if",
"r",
"==",
"role",
"{",
"post",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"if",
"len",
"(",
"ap",
".",
"Roles",
")",
">",
"i",
"+",
"1",
"{",
"post",
"=",
"ap",
".",
"Roles",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"}",
"\n",
"ap",
".",
"Roles",
"=",
"append",
"(",
"ap",
".",
"Roles",
"[",
":",
"i",
"]",
",",
"post",
"...",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Returns true if the role is removed, and false if it is not found | [
"Returns",
"true",
"if",
"the",
"role",
"is",
"removed",
"and",
"false",
"if",
"it",
"is",
"not",
"found"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/permission/account_permissions.go#L42-L55 | train |
hyperledger/burrow | permission/account_permissions.go | Clone | func (ap *AccountPermissions) Clone() AccountPermissions {
// clone base permissions
basePermissionsClone := ap.Base
var rolesClone []string
// It helps if we normalise empty roles to []string(nil) rather than []string{}
if len(ap.Roles) > 0 {
// clone roles []string
rolesClone = make([]string, len(ap.Roles))
// strings are immutable so copy suffices
copy(rolesClone, ap.Roles)
}
return AccountPermissions{
Base: basePermissionsClone,
Roles: rolesClone,
}
} | go | func (ap *AccountPermissions) Clone() AccountPermissions {
// clone base permissions
basePermissionsClone := ap.Base
var rolesClone []string
// It helps if we normalise empty roles to []string(nil) rather than []string{}
if len(ap.Roles) > 0 {
// clone roles []string
rolesClone = make([]string, len(ap.Roles))
// strings are immutable so copy suffices
copy(rolesClone, ap.Roles)
}
return AccountPermissions{
Base: basePermissionsClone,
Roles: rolesClone,
}
} | [
"func",
"(",
"ap",
"*",
"AccountPermissions",
")",
"Clone",
"(",
")",
"AccountPermissions",
"{",
"// clone base permissions",
"basePermissionsClone",
":=",
"ap",
".",
"Base",
"\n",
"var",
"rolesClone",
"[",
"]",
"string",
"\n",
"// It helps if we normalise empty roles to []string(nil) rather than []string{}",
"if",
"len",
"(",
"ap",
".",
"Roles",
")",
">",
"0",
"{",
"// clone roles []string",
"rolesClone",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"ap",
".",
"Roles",
")",
")",
"\n",
"// strings are immutable so copy suffices",
"copy",
"(",
"rolesClone",
",",
"ap",
".",
"Roles",
")",
"\n",
"}",
"\n\n",
"return",
"AccountPermissions",
"{",
"Base",
":",
"basePermissionsClone",
",",
"Roles",
":",
"rolesClone",
",",
"}",
"\n",
"}"
] | // Clone clones the account permissions | [
"Clone",
"clones",
"the",
"account",
"permissions"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/permission/account_permissions.go#L58-L74 | train |
hyperledger/burrow | txs/envelope.go | RealisePublicKey | func (s *Signatory) RealisePublicKey(getter acmstate.AccountGetter) error {
const errPrefix = "could not realise public key for signatory"
if s.PublicKey == nil {
if s.Address == nil {
return fmt.Errorf("%s: address not provided", errPrefix)
}
acc, err := getter.GetAccount(*s.Address)
if err != nil {
return fmt.Errorf("%s: could not get account %v: %v", errPrefix, *s.Address, err)
}
publicKey := acc.PublicKey
s.PublicKey = &publicKey
}
if !s.PublicKey.IsValid() {
return fmt.Errorf("%s: public key %v is invalid", errPrefix, *s.PublicKey)
}
address := s.PublicKey.GetAddress()
if s.Address == nil {
s.Address = &address
} else if address != *s.Address {
return fmt.Errorf("address %v provided with signatory does not match address generated from "+
"public key %v", *s.Address, address)
}
return nil
} | go | func (s *Signatory) RealisePublicKey(getter acmstate.AccountGetter) error {
const errPrefix = "could not realise public key for signatory"
if s.PublicKey == nil {
if s.Address == nil {
return fmt.Errorf("%s: address not provided", errPrefix)
}
acc, err := getter.GetAccount(*s.Address)
if err != nil {
return fmt.Errorf("%s: could not get account %v: %v", errPrefix, *s.Address, err)
}
publicKey := acc.PublicKey
s.PublicKey = &publicKey
}
if !s.PublicKey.IsValid() {
return fmt.Errorf("%s: public key %v is invalid", errPrefix, *s.PublicKey)
}
address := s.PublicKey.GetAddress()
if s.Address == nil {
s.Address = &address
} else if address != *s.Address {
return fmt.Errorf("address %v provided with signatory does not match address generated from "+
"public key %v", *s.Address, address)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Signatory",
")",
"RealisePublicKey",
"(",
"getter",
"acmstate",
".",
"AccountGetter",
")",
"error",
"{",
"const",
"errPrefix",
"=",
"\"",
"\"",
"\n",
"if",
"s",
".",
"PublicKey",
"==",
"nil",
"{",
"if",
"s",
".",
"Address",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"errPrefix",
")",
"\n",
"}",
"\n",
"acc",
",",
"err",
":=",
"getter",
".",
"GetAccount",
"(",
"*",
"s",
".",
"Address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"errPrefix",
",",
"*",
"s",
".",
"Address",
",",
"err",
")",
"\n",
"}",
"\n",
"publicKey",
":=",
"acc",
".",
"PublicKey",
"\n",
"s",
".",
"PublicKey",
"=",
"&",
"publicKey",
"\n",
"}",
"\n",
"if",
"!",
"s",
".",
"PublicKey",
".",
"IsValid",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"errPrefix",
",",
"*",
"s",
".",
"PublicKey",
")",
"\n",
"}",
"\n",
"address",
":=",
"s",
".",
"PublicKey",
".",
"GetAddress",
"(",
")",
"\n",
"if",
"s",
".",
"Address",
"==",
"nil",
"{",
"s",
".",
"Address",
"=",
"&",
"address",
"\n",
"}",
"else",
"if",
"address",
"!=",
"*",
"s",
".",
"Address",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"*",
"s",
".",
"Address",
",",
"address",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Attempts to 'realise' the PublicKey and Address of a Signatory possibly referring to state
// in the case where the Signatory contains an Address by no PublicKey. Checks consistency in other
// cases, possibly generating the Address from the PublicKey | [
"Attempts",
"to",
"realise",
"the",
"PublicKey",
"and",
"Address",
"of",
"a",
"Signatory",
"possibly",
"referring",
"to",
"state",
"in",
"the",
"case",
"where",
"the",
"Signatory",
"contains",
"an",
"Address",
"by",
"no",
"PublicKey",
".",
"Checks",
"consistency",
"in",
"other",
"cases",
"possibly",
"generating",
"the",
"Address",
"from",
"the",
"PublicKey"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/txs/envelope.go#L41-L65 | train |
hyperledger/burrow | vent/types/event_class.go | Validate | func (ec *EventClass) Validate() error {
return validation.ValidateStruct(ec,
validation.Field(&ec.TableName, validation.Required, validation.Length(1, 60)),
validation.Field(&ec.Filter, validation.Required),
validation.Field(&ec.FieldMappings, validation.Required, validation.Length(1, 0)),
)
} | go | func (ec *EventClass) Validate() error {
return validation.ValidateStruct(ec,
validation.Field(&ec.TableName, validation.Required, validation.Length(1, 60)),
validation.Field(&ec.Filter, validation.Required),
validation.Field(&ec.FieldMappings, validation.Required, validation.Length(1, 0)),
)
} | [
"func",
"(",
"ec",
"*",
"EventClass",
")",
"Validate",
"(",
")",
"error",
"{",
"return",
"validation",
".",
"ValidateStruct",
"(",
"ec",
",",
"validation",
".",
"Field",
"(",
"&",
"ec",
".",
"TableName",
",",
"validation",
".",
"Required",
",",
"validation",
".",
"Length",
"(",
"1",
",",
"60",
")",
")",
",",
"validation",
".",
"Field",
"(",
"&",
"ec",
".",
"Filter",
",",
"validation",
".",
"Required",
")",
",",
"validation",
".",
"Field",
"(",
"&",
"ec",
".",
"FieldMappings",
",",
"validation",
".",
"Required",
",",
"validation",
".",
"Length",
"(",
"1",
",",
"0",
")",
")",
",",
")",
"\n",
"}"
] | // Validate checks the structure of an EventClass | [
"Validate",
"checks",
"the",
"structure",
"of",
"an",
"EventClass"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/types/event_class.go#L33-L39 | train |
hyperledger/burrow | vent/types/event_class.go | Validate | func (evColumn EventFieldMapping) Validate() error {
return validation.ValidateStruct(&evColumn,
validation.Field(&evColumn.ColumnName, validation.Required, validation.Length(1, 60)),
)
} | go | func (evColumn EventFieldMapping) Validate() error {
return validation.ValidateStruct(&evColumn,
validation.Field(&evColumn.ColumnName, validation.Required, validation.Length(1, 60)),
)
} | [
"func",
"(",
"evColumn",
"EventFieldMapping",
")",
"Validate",
"(",
")",
"error",
"{",
"return",
"validation",
".",
"ValidateStruct",
"(",
"&",
"evColumn",
",",
"validation",
".",
"Field",
"(",
"&",
"evColumn",
".",
"ColumnName",
",",
"validation",
".",
"Required",
",",
"validation",
".",
"Length",
"(",
"1",
",",
"60",
")",
")",
",",
")",
"\n",
"}"
] | // Validate checks the structure of an EventFieldMapping | [
"Validate",
"checks",
"the",
"structure",
"of",
"an",
"EventFieldMapping"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/types/event_class.go#L88-L92 | train |
hyperledger/burrow | storage/mutable_forest.go | Load | func (muf *MutableForest) Load(version int64) error {
return muf.commitsTree.Load(version, true)
} | go | func (muf *MutableForest) Load(version int64) error {
return muf.commitsTree.Load(version, true)
} | [
"func",
"(",
"muf",
"*",
"MutableForest",
")",
"Load",
"(",
"version",
"int64",
")",
"error",
"{",
"return",
"muf",
".",
"commitsTree",
".",
"Load",
"(",
"version",
",",
"true",
")",
"\n",
"}"
] | // Load mutable forest from database, pass overwriting = true if you wish to make writes to version version + 1.
// this will | [
"Load",
"mutable",
"forest",
"from",
"database",
"pass",
"overwriting",
"=",
"true",
"if",
"you",
"wish",
"to",
"make",
"writes",
"to",
"version",
"version",
"+",
"1",
".",
"this",
"will"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/mutable_forest.go#L84-L86 | train |
hyperledger/burrow | storage/mutable_forest.go | Writer | func (muf *MutableForest) Writer(prefix []byte) (*RWTree, error) {
// Try dirty cache first (if tree is new it may only be in this location)
prefixString := string(prefix)
if tree, ok := muf.dirty[prefixString]; ok {
return tree, nil
}
tree, err := muf.tree(prefix)
if err != nil {
return nil, err
}
// Mark tree as dirty
muf.dirty[prefixString] = tree
muf.dirtyPrefixes = append(muf.dirtyPrefixes, prefixString)
return tree, nil
} | go | func (muf *MutableForest) Writer(prefix []byte) (*RWTree, error) {
// Try dirty cache first (if tree is new it may only be in this location)
prefixString := string(prefix)
if tree, ok := muf.dirty[prefixString]; ok {
return tree, nil
}
tree, err := muf.tree(prefix)
if err != nil {
return nil, err
}
// Mark tree as dirty
muf.dirty[prefixString] = tree
muf.dirtyPrefixes = append(muf.dirtyPrefixes, prefixString)
return tree, nil
} | [
"func",
"(",
"muf",
"*",
"MutableForest",
")",
"Writer",
"(",
"prefix",
"[",
"]",
"byte",
")",
"(",
"*",
"RWTree",
",",
"error",
")",
"{",
"// Try dirty cache first (if tree is new it may only be in this location)",
"prefixString",
":=",
"string",
"(",
"prefix",
")",
"\n",
"if",
"tree",
",",
"ok",
":=",
"muf",
".",
"dirty",
"[",
"prefixString",
"]",
";",
"ok",
"{",
"return",
"tree",
",",
"nil",
"\n",
"}",
"\n",
"tree",
",",
"err",
":=",
"muf",
".",
"tree",
"(",
"prefix",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// Mark tree as dirty",
"muf",
".",
"dirty",
"[",
"prefixString",
"]",
"=",
"tree",
"\n",
"muf",
".",
"dirtyPrefixes",
"=",
"append",
"(",
"muf",
".",
"dirtyPrefixes",
",",
"prefixString",
")",
"\n",
"return",
"tree",
",",
"nil",
"\n",
"}"
] | // Calls to writer should be serialised as should writes to the tree | [
"Calls",
"to",
"writer",
"should",
"be",
"serialised",
"as",
"should",
"writes",
"to",
"the",
"tree"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/mutable_forest.go#L115-L129 | train |
hyperledger/burrow | storage/mutable_forest.go | Delete | func (muf *MutableForest) Delete(prefix []byte) (*CommitID, error) {
bs, removed := muf.commitsTree.Delete(prefix)
if !removed {
return nil, nil
}
return UnmarshalCommitID(bs)
} | go | func (muf *MutableForest) Delete(prefix []byte) (*CommitID, error) {
bs, removed := muf.commitsTree.Delete(prefix)
if !removed {
return nil, nil
}
return UnmarshalCommitID(bs)
} | [
"func",
"(",
"muf",
"*",
"MutableForest",
")",
"Delete",
"(",
"prefix",
"[",
"]",
"byte",
")",
"(",
"*",
"CommitID",
",",
"error",
")",
"{",
"bs",
",",
"removed",
":=",
"muf",
".",
"commitsTree",
".",
"Delete",
"(",
"prefix",
")",
"\n",
"if",
"!",
"removed",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"UnmarshalCommitID",
"(",
"bs",
")",
"\n",
"}"
] | // Delete a tree - if the tree exists will return the CommitID of the latest saved version | [
"Delete",
"a",
"tree",
"-",
"if",
"the",
"tree",
"exists",
"will",
"return",
"the",
"CommitID",
"of",
"the",
"latest",
"saved",
"version"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/mutable_forest.go#L132-L138 | train |
hyperledger/burrow | logging/loggers/multiple_output_logger.go | NewMultipleOutputLogger | func NewMultipleOutputLogger(outputLoggers ...log.Logger) log.Logger {
moLogger := make(MultipleOutputLogger, 0, len(outputLoggers))
// Flatten any MultipleOutputLoggers
for _, ol := range outputLoggers {
if ls, ok := ol.(MultipleOutputLogger); ok {
moLogger = append(moLogger, ls...)
} else {
moLogger = append(moLogger, ol)
}
}
return moLogger
} | go | func NewMultipleOutputLogger(outputLoggers ...log.Logger) log.Logger {
moLogger := make(MultipleOutputLogger, 0, len(outputLoggers))
// Flatten any MultipleOutputLoggers
for _, ol := range outputLoggers {
if ls, ok := ol.(MultipleOutputLogger); ok {
moLogger = append(moLogger, ls...)
} else {
moLogger = append(moLogger, ol)
}
}
return moLogger
} | [
"func",
"NewMultipleOutputLogger",
"(",
"outputLoggers",
"...",
"log",
".",
"Logger",
")",
"log",
".",
"Logger",
"{",
"moLogger",
":=",
"make",
"(",
"MultipleOutputLogger",
",",
"0",
",",
"len",
"(",
"outputLoggers",
")",
")",
"\n",
"// Flatten any MultipleOutputLoggers",
"for",
"_",
",",
"ol",
":=",
"range",
"outputLoggers",
"{",
"if",
"ls",
",",
"ok",
":=",
"ol",
".",
"(",
"MultipleOutputLogger",
")",
";",
"ok",
"{",
"moLogger",
"=",
"append",
"(",
"moLogger",
",",
"ls",
"...",
")",
"\n",
"}",
"else",
"{",
"moLogger",
"=",
"append",
"(",
"moLogger",
",",
"ol",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"moLogger",
"\n",
"}"
] | // Creates a logger that forks log messages to each of its outputLoggers | [
"Creates",
"a",
"logger",
"that",
"forks",
"log",
"messages",
"to",
"each",
"of",
"its",
"outputLoggers"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/logging/loggers/multiple_output_logger.go#L40-L51 | train |
hyperledger/burrow | deploy/util/readers.go | ReadTxSignAndBroadcast | func ReadTxSignAndBroadcast(txe *exec.TxExecution, err error, logger *logging.Logger) error {
// if there's an error just return.
if err != nil {
return err
}
// if there is nothing to unpack then just return.
if txe == nil {
return nil
}
// Unpack and display for the user.
height := fmt.Sprintf("%d", txe.Height)
if txe.Receipt.CreatesContract {
logger.InfoMsg("Tx Return",
"addr", txe.Receipt.ContractAddress.String(),
"Transaction Hash", hex.EncodeToString(txe.TxHash))
} else {
logger.InfoMsg("Tx Return",
"Transaction Hash", hex.EncodeToString(txe.TxHash),
"Block Height", height)
ret := txe.GetResult().GetReturn()
if len(ret) != 0 {
logger.InfoMsg("Return",
"Return Value", hex.EncodeUpperToString(ret),
"Exception", txe.Exception)
}
}
return nil
} | go | func ReadTxSignAndBroadcast(txe *exec.TxExecution, err error, logger *logging.Logger) error {
// if there's an error just return.
if err != nil {
return err
}
// if there is nothing to unpack then just return.
if txe == nil {
return nil
}
// Unpack and display for the user.
height := fmt.Sprintf("%d", txe.Height)
if txe.Receipt.CreatesContract {
logger.InfoMsg("Tx Return",
"addr", txe.Receipt.ContractAddress.String(),
"Transaction Hash", hex.EncodeToString(txe.TxHash))
} else {
logger.InfoMsg("Tx Return",
"Transaction Hash", hex.EncodeToString(txe.TxHash),
"Block Height", height)
ret := txe.GetResult().GetReturn()
if len(ret) != 0 {
logger.InfoMsg("Return",
"Return Value", hex.EncodeUpperToString(ret),
"Exception", txe.Exception)
}
}
return nil
} | [
"func",
"ReadTxSignAndBroadcast",
"(",
"txe",
"*",
"exec",
".",
"TxExecution",
",",
"err",
"error",
",",
"logger",
"*",
"logging",
".",
"Logger",
")",
"error",
"{",
"// if there's an error just return.",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// if there is nothing to unpack then just return.",
"if",
"txe",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Unpack and display for the user.",
"height",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"txe",
".",
"Height",
")",
"\n\n",
"if",
"txe",
".",
"Receipt",
".",
"CreatesContract",
"{",
"logger",
".",
"InfoMsg",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"txe",
".",
"Receipt",
".",
"ContractAddress",
".",
"String",
"(",
")",
",",
"\"",
"\"",
",",
"hex",
".",
"EncodeToString",
"(",
"txe",
".",
"TxHash",
")",
")",
"\n",
"}",
"else",
"{",
"logger",
".",
"InfoMsg",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hex",
".",
"EncodeToString",
"(",
"txe",
".",
"TxHash",
")",
",",
"\"",
"\"",
",",
"height",
")",
"\n\n",
"ret",
":=",
"txe",
".",
"GetResult",
"(",
")",
".",
"GetReturn",
"(",
")",
"\n",
"if",
"len",
"(",
"ret",
")",
"!=",
"0",
"{",
"logger",
".",
"InfoMsg",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hex",
".",
"EncodeUpperToString",
"(",
"ret",
")",
",",
"\"",
"\"",
",",
"txe",
".",
"Exception",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // This is a closer function which is called by most of the tx_run functions | [
"This",
"is",
"a",
"closer",
"function",
"which",
"is",
"called",
"by",
"most",
"of",
"the",
"tx_run",
"functions"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/util/readers.go#L16-L48 | train |
hyperledger/burrow | deploy/util/readers.go | GetBoolResponse | func GetBoolResponse(question string, defaultAnswer bool, reader *os.File, logger *logging.Logger) (bool, error) {
var result bool
readr := bufio.NewReader(reader)
logger.InfoMsg(question)
text, _ := readr.ReadString('\n')
text = strings.Replace(text, "\n", "", 1)
if text == "" {
return defaultAnswer, nil
}
if text == "Yes" || text == "YES" || text == "Y" || text == "y" {
result = true
} else {
result = false
}
return result, nil
} | go | func GetBoolResponse(question string, defaultAnswer bool, reader *os.File, logger *logging.Logger) (bool, error) {
var result bool
readr := bufio.NewReader(reader)
logger.InfoMsg(question)
text, _ := readr.ReadString('\n')
text = strings.Replace(text, "\n", "", 1)
if text == "" {
return defaultAnswer, nil
}
if text == "Yes" || text == "YES" || text == "Y" || text == "y" {
result = true
} else {
result = false
}
return result, nil
} | [
"func",
"GetBoolResponse",
"(",
"question",
"string",
",",
"defaultAnswer",
"bool",
",",
"reader",
"*",
"os",
".",
"File",
",",
"logger",
"*",
"logging",
".",
"Logger",
")",
"(",
"bool",
",",
"error",
")",
"{",
"var",
"result",
"bool",
"\n",
"readr",
":=",
"bufio",
".",
"NewReader",
"(",
"reader",
")",
"\n",
"logger",
".",
"InfoMsg",
"(",
"question",
")",
"\n\n",
"text",
",",
"_",
":=",
"readr",
".",
"ReadString",
"(",
"'\\n'",
")",
"\n",
"text",
"=",
"strings",
".",
"Replace",
"(",
"text",
",",
"\"",
"\\n",
"\"",
",",
"\"",
"\"",
",",
"1",
")",
"\n",
"if",
"text",
"==",
"\"",
"\"",
"{",
"return",
"defaultAnswer",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"text",
"==",
"\"",
"\"",
"||",
"text",
"==",
"\"",
"\"",
"||",
"text",
"==",
"\"",
"\"",
"||",
"text",
"==",
"\"",
"\"",
"{",
"result",
"=",
"true",
"\n",
"}",
"else",
"{",
"result",
"=",
"false",
"\n",
"}",
"\n\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // displays the question, scans for the response, if the response is an empty
// string will return default, otherwise will parseBool and return the result. | [
"displays",
"the",
"question",
"scans",
"for",
"the",
"response",
"if",
"the",
"response",
"is",
"an",
"empty",
"string",
"will",
"return",
"default",
"otherwise",
"will",
"parseBool",
"and",
"return",
"the",
"result",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/util/readers.go#L81-L99 | train |
hyperledger/burrow | execution/proposal/cache.go | Flush | func (cache *Cache) Flush(output Writer, backend Reader) error {
err := cache.Sync(output)
if err != nil {
return err
}
cache.Reset(backend)
return nil
} | go | func (cache *Cache) Flush(output Writer, backend Reader) error {
err := cache.Sync(output)
if err != nil {
return err
}
cache.Reset(backend)
return nil
} | [
"func",
"(",
"cache",
"*",
"Cache",
")",
"Flush",
"(",
"output",
"Writer",
",",
"backend",
"Reader",
")",
"error",
"{",
"err",
":=",
"cache",
".",
"Sync",
"(",
"output",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"cache",
".",
"Reset",
"(",
"backend",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Syncs the Cache and Resets it to use Writer as the backend Reader | [
"Syncs",
"the",
"Cache",
"and",
"Resets",
"it",
"to",
"use",
"Writer",
"as",
"the",
"backend",
"Reader"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/proposal/cache.go#L163-L170 | train |
hyperledger/burrow | vent/config/config.go | DefaultVentConfig | func DefaultVentConfig() *VentConfig {
return &VentConfig{
DBAdapter: types.PostgresDB,
DBURL: DefaultPostgresDBURL,
DBSchema: "vent",
GRPCAddr: "localhost:10997",
HTTPAddr: "0.0.0.0:8080",
LogLevel: "debug",
DBBlockTx: false,
AnnounceEvery: time.Second * 5,
}
} | go | func DefaultVentConfig() *VentConfig {
return &VentConfig{
DBAdapter: types.PostgresDB,
DBURL: DefaultPostgresDBURL,
DBSchema: "vent",
GRPCAddr: "localhost:10997",
HTTPAddr: "0.0.0.0:8080",
LogLevel: "debug",
DBBlockTx: false,
AnnounceEvery: time.Second * 5,
}
} | [
"func",
"DefaultVentConfig",
"(",
")",
"*",
"VentConfig",
"{",
"return",
"&",
"VentConfig",
"{",
"DBAdapter",
":",
"types",
".",
"PostgresDB",
",",
"DBURL",
":",
"DefaultPostgresDBURL",
",",
"DBSchema",
":",
"\"",
"\"",
",",
"GRPCAddr",
":",
"\"",
"\"",
",",
"HTTPAddr",
":",
"\"",
"\"",
",",
"LogLevel",
":",
"\"",
"\"",
",",
"DBBlockTx",
":",
"false",
",",
"AnnounceEvery",
":",
"time",
".",
"Second",
"*",
"5",
",",
"}",
"\n",
"}"
] | // DefaultFlags returns a configuration with default values | [
"DefaultFlags",
"returns",
"a",
"configuration",
"with",
"default",
"values"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/config/config.go#L27-L38 | train |
hyperledger/burrow | rpc/metrics/exporter.go | NewExporter | func NewExporter(service InfoService, blockSampleSize int, logger *logging.Logger) (*Exporter, error) {
chainStatus, err := service.Status()
if err != nil {
return nil, fmt.Errorf("NewExporter(): %v", err)
}
return &Exporter{
datum: &Datum{},
service: service,
chainID: chainStatus.NodeInfo.Network,
validatorMoniker: chainStatus.NodeInfo.Moniker,
blockSampleSize: uint64(blockSampleSize),
txPerBlockHistogramBuilder: makeHistogramBuilder(identity),
timePerBlockHistogramBuilder: makeHistogramBuilder(significantFiguresRounder(significantFiguresForSeconds)),
logger: logger.With(structure.ComponentKey, "Metrics_Exporter"),
}, nil
} | go | func NewExporter(service InfoService, blockSampleSize int, logger *logging.Logger) (*Exporter, error) {
chainStatus, err := service.Status()
if err != nil {
return nil, fmt.Errorf("NewExporter(): %v", err)
}
return &Exporter{
datum: &Datum{},
service: service,
chainID: chainStatus.NodeInfo.Network,
validatorMoniker: chainStatus.NodeInfo.Moniker,
blockSampleSize: uint64(blockSampleSize),
txPerBlockHistogramBuilder: makeHistogramBuilder(identity),
timePerBlockHistogramBuilder: makeHistogramBuilder(significantFiguresRounder(significantFiguresForSeconds)),
logger: logger.With(structure.ComponentKey, "Metrics_Exporter"),
}, nil
} | [
"func",
"NewExporter",
"(",
"service",
"InfoService",
",",
"blockSampleSize",
"int",
",",
"logger",
"*",
"logging",
".",
"Logger",
")",
"(",
"*",
"Exporter",
",",
"error",
")",
"{",
"chainStatus",
",",
"err",
":=",
"service",
".",
"Status",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"Exporter",
"{",
"datum",
":",
"&",
"Datum",
"{",
"}",
",",
"service",
":",
"service",
",",
"chainID",
":",
"chainStatus",
".",
"NodeInfo",
".",
"Network",
",",
"validatorMoniker",
":",
"chainStatus",
".",
"NodeInfo",
".",
"Moniker",
",",
"blockSampleSize",
":",
"uint64",
"(",
"blockSampleSize",
")",
",",
"txPerBlockHistogramBuilder",
":",
"makeHistogramBuilder",
"(",
"identity",
")",
",",
"timePerBlockHistogramBuilder",
":",
"makeHistogramBuilder",
"(",
"significantFiguresRounder",
"(",
"significantFiguresForSeconds",
")",
")",
",",
"logger",
":",
"logger",
".",
"With",
"(",
"structure",
".",
"ComponentKey",
",",
"\"",
"\"",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Exporter uses the InfoService to provide pre-aggregated metrics of various types that are then passed to prometheus
// as Const metrics rather than being accumulated by individual operations throughout the rest of the Burrow code. | [
"Exporter",
"uses",
"the",
"InfoService",
"to",
"provide",
"pre",
"-",
"aggregated",
"metrics",
"of",
"various",
"types",
"that",
"are",
"then",
"passed",
"to",
"prometheus",
"as",
"Const",
"metrics",
"rather",
"than",
"being",
"accumulated",
"by",
"individual",
"operations",
"throughout",
"the",
"rest",
"of",
"the",
"Burrow",
"code",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/rpc/metrics/exporter.go#L77-L92 | train |
hyperledger/burrow | rpc/metrics/exporter.go | Describe | func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
for _, m := range MetricDescriptions {
ch <- m
}
} | go | func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
for _, m := range MetricDescriptions {
ch <- m
}
} | [
"func",
"(",
"e",
"*",
"Exporter",
")",
"Describe",
"(",
"ch",
"chan",
"<-",
"*",
"prometheus",
".",
"Desc",
")",
"{",
"for",
"_",
",",
"m",
":=",
"range",
"MetricDescriptions",
"{",
"ch",
"<-",
"m",
"\n",
"}",
"\n",
"}"
] | // Describe - loops through the API metrics and passes them to prometheus.Describe | [
"Describe",
"-",
"loops",
"through",
"the",
"API",
"metrics",
"and",
"passes",
"them",
"to",
"prometheus",
".",
"Describe"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/rpc/metrics/exporter.go#L95-L99 | train |
hyperledger/burrow | rpc/metrics/exporter.go | gatherData | func (e *Exporter) gatherData() error {
var err error
err = e.getStatus()
if err != nil {
return err
}
err = e.getMemPoolDepth()
if err != nil {
return err
}
err = e.getPeers()
if err != nil {
return err
}
blocks, err := e.getBlocks()
if err != nil {
return err
}
err = e.getTxBuckets(blocks.BlockMetas)
if err != nil {
return err
}
err = e.getBlockTimeBuckets(blocks.BlockMetas)
if err != nil {
return err
}
e.getAccountStats()
return nil
} | go | func (e *Exporter) gatherData() error {
var err error
err = e.getStatus()
if err != nil {
return err
}
err = e.getMemPoolDepth()
if err != nil {
return err
}
err = e.getPeers()
if err != nil {
return err
}
blocks, err := e.getBlocks()
if err != nil {
return err
}
err = e.getTxBuckets(blocks.BlockMetas)
if err != nil {
return err
}
err = e.getBlockTimeBuckets(blocks.BlockMetas)
if err != nil {
return err
}
e.getAccountStats()
return nil
} | [
"func",
"(",
"e",
"*",
"Exporter",
")",
"gatherData",
"(",
")",
"error",
"{",
"var",
"err",
"error",
"\n\n",
"err",
"=",
"e",
".",
"getStatus",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"e",
".",
"getMemPoolDepth",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"e",
".",
"getPeers",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"blocks",
",",
"err",
":=",
"e",
".",
"getBlocks",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"e",
".",
"getTxBuckets",
"(",
"blocks",
".",
"BlockMetas",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"e",
".",
"getBlockTimeBuckets",
"(",
"blocks",
".",
"BlockMetas",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"e",
".",
"getAccountStats",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // gatherData - Collects the data from the API and stores into struct | [
"gatherData",
"-",
"Collects",
"the",
"data",
"from",
"the",
"API",
"and",
"stores",
"into",
"struct"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/rpc/metrics/exporter.go#L181-L211 | train |
hyperledger/burrow | rpc/metrics/exporter.go | getPeers | func (e *Exporter) getPeers() error {
peers := e.service.Peers()
e.datum.TotalPeers = float64(len(peers))
e.datum.InboundPeers = 0
e.datum.OutboundPeers = 0
for _, peer := range peers {
if peer.IsOutbound {
e.datum.OutboundPeers += 1
} else {
e.datum.InboundPeers += 1
}
}
return nil
} | go | func (e *Exporter) getPeers() error {
peers := e.service.Peers()
e.datum.TotalPeers = float64(len(peers))
e.datum.InboundPeers = 0
e.datum.OutboundPeers = 0
for _, peer := range peers {
if peer.IsOutbound {
e.datum.OutboundPeers += 1
} else {
e.datum.InboundPeers += 1
}
}
return nil
} | [
"func",
"(",
"e",
"*",
"Exporter",
")",
"getPeers",
"(",
")",
"error",
"{",
"peers",
":=",
"e",
".",
"service",
".",
"Peers",
"(",
")",
"\n",
"e",
".",
"datum",
".",
"TotalPeers",
"=",
"float64",
"(",
"len",
"(",
"peers",
")",
")",
"\n",
"e",
".",
"datum",
".",
"InboundPeers",
"=",
"0",
"\n",
"e",
".",
"datum",
".",
"OutboundPeers",
"=",
"0",
"\n\n",
"for",
"_",
",",
"peer",
":=",
"range",
"peers",
"{",
"if",
"peer",
".",
"IsOutbound",
"{",
"e",
".",
"datum",
".",
"OutboundPeers",
"+=",
"1",
"\n",
"}",
"else",
"{",
"e",
".",
"datum",
".",
"InboundPeers",
"+=",
"1",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Get total peers | [
"Get",
"total",
"peers"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/rpc/metrics/exporter.go#L234-L249 | train |
hyperledger/burrow | rpc/metrics/exporter.go | getTxBuckets | func (e *Exporter) getTxBuckets(blockMetas []*types.BlockMeta) error {
e.datum.TotalTxs = 0
e.datum.TxPerBlockBuckets = map[float64]uint64{}
if len(blockMetas) == 0 {
return nil
}
// Collect number of txs per block as an array of floats
txsPerBlock := make([]float64, len(blockMetas))
for i, block := range blockMetas {
txsPerBlock[i] = float64(block.Header.NumTxs)
}
e.datum.TxPerBlockBuckets, e.datum.TotalTxs = e.txPerBlockHistogramBuilder(txsPerBlock)
return nil
} | go | func (e *Exporter) getTxBuckets(blockMetas []*types.BlockMeta) error {
e.datum.TotalTxs = 0
e.datum.TxPerBlockBuckets = map[float64]uint64{}
if len(blockMetas) == 0 {
return nil
}
// Collect number of txs per block as an array of floats
txsPerBlock := make([]float64, len(blockMetas))
for i, block := range blockMetas {
txsPerBlock[i] = float64(block.Header.NumTxs)
}
e.datum.TxPerBlockBuckets, e.datum.TotalTxs = e.txPerBlockHistogramBuilder(txsPerBlock)
return nil
} | [
"func",
"(",
"e",
"*",
"Exporter",
")",
"getTxBuckets",
"(",
"blockMetas",
"[",
"]",
"*",
"types",
".",
"BlockMeta",
")",
"error",
"{",
"e",
".",
"datum",
".",
"TotalTxs",
"=",
"0",
"\n",
"e",
".",
"datum",
".",
"TxPerBlockBuckets",
"=",
"map",
"[",
"float64",
"]",
"uint64",
"{",
"}",
"\n",
"if",
"len",
"(",
"blockMetas",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"// Collect number of txs per block as an array of floats",
"txsPerBlock",
":=",
"make",
"(",
"[",
"]",
"float64",
",",
"len",
"(",
"blockMetas",
")",
")",
"\n",
"for",
"i",
",",
"block",
":=",
"range",
"blockMetas",
"{",
"txsPerBlock",
"[",
"i",
"]",
"=",
"float64",
"(",
"block",
".",
"Header",
".",
"NumTxs",
")",
"\n",
"}",
"\n\n",
"e",
".",
"datum",
".",
"TxPerBlockBuckets",
",",
"e",
".",
"datum",
".",
"TotalTxs",
"=",
"e",
".",
"txPerBlockHistogramBuilder",
"(",
"txsPerBlock",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Get transaction buckets | [
"Get",
"transaction",
"buckets"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/rpc/metrics/exporter.go#L277-L291 | train |
hyperledger/burrow | event/query/query.go | Conditions | func (q *query) Conditions() []Condition {
conditions := make([]Condition, 0)
buffer, begin, end := q.parser.Buffer, 0, 0
var tag string
var op Operator
// tokens must be in the following order: tag ("tx.gas") -> operator ("=") -> operand ("7")
for _, token := range q.parser.Tokens() {
switch token.pegRule {
case rulePegText:
begin, end = int(token.begin), int(token.end)
case ruletag:
tag = buffer[begin:end]
case rulele:
op = OpLessEqual
case rulege:
op = OpGreaterEqual
case rulel:
op = OpLess
case ruleg:
op = OpGreater
case ruleequal:
op = OpEqual
case rulecontains:
op = OpContains
case rulevalue:
// strip single quotes from value (i.e. "'NewBlock'" -> "NewBlock")
valueWithoutSingleQuotes := buffer[begin+1 : end-1]
conditions = append(conditions, Condition{tag, op, valueWithoutSingleQuotes})
case rulenumber:
number := buffer[begin:end]
if strings.ContainsAny(number, ".") { // if it looks like a floating-point number
value, err := strconv.ParseFloat(number, 64)
if err != nil {
panic(fmt.Sprintf("got %v while trying to parse %s as float64 (should never happen if the grammar is correct)", err, number))
}
conditions = append(conditions, Condition{tag, op, value})
} else {
value, err := strconv.ParseInt(number, 10, 64)
if err != nil {
panic(fmt.Sprintf("got %v while trying to parse %s as int64 (should never happen if the grammar is correct)", err, number))
}
conditions = append(conditions, Condition{tag, op, value})
}
case ruletime:
value, err := time.Parse(TimeLayout, buffer[begin:end])
if err != nil {
panic(fmt.Sprintf("got %v while trying to parse %s as time.Time / RFC3339 (should never happen if the grammar is correct)", err, buffer[begin:end]))
}
conditions = append(conditions, Condition{tag, op, value})
case ruledate:
value, err := time.Parse("2006-01-02", buffer[begin:end])
if err != nil {
panic(fmt.Sprintf("got %v while trying to parse %s as time.Time / '2006-01-02' (should never happen if the grammar is correct)", err, buffer[begin:end]))
}
conditions = append(conditions, Condition{tag, op, value})
}
}
return conditions
} | go | func (q *query) Conditions() []Condition {
conditions := make([]Condition, 0)
buffer, begin, end := q.parser.Buffer, 0, 0
var tag string
var op Operator
// tokens must be in the following order: tag ("tx.gas") -> operator ("=") -> operand ("7")
for _, token := range q.parser.Tokens() {
switch token.pegRule {
case rulePegText:
begin, end = int(token.begin), int(token.end)
case ruletag:
tag = buffer[begin:end]
case rulele:
op = OpLessEqual
case rulege:
op = OpGreaterEqual
case rulel:
op = OpLess
case ruleg:
op = OpGreater
case ruleequal:
op = OpEqual
case rulecontains:
op = OpContains
case rulevalue:
// strip single quotes from value (i.e. "'NewBlock'" -> "NewBlock")
valueWithoutSingleQuotes := buffer[begin+1 : end-1]
conditions = append(conditions, Condition{tag, op, valueWithoutSingleQuotes})
case rulenumber:
number := buffer[begin:end]
if strings.ContainsAny(number, ".") { // if it looks like a floating-point number
value, err := strconv.ParseFloat(number, 64)
if err != nil {
panic(fmt.Sprintf("got %v while trying to parse %s as float64 (should never happen if the grammar is correct)", err, number))
}
conditions = append(conditions, Condition{tag, op, value})
} else {
value, err := strconv.ParseInt(number, 10, 64)
if err != nil {
panic(fmt.Sprintf("got %v while trying to parse %s as int64 (should never happen if the grammar is correct)", err, number))
}
conditions = append(conditions, Condition{tag, op, value})
}
case ruletime:
value, err := time.Parse(TimeLayout, buffer[begin:end])
if err != nil {
panic(fmt.Sprintf("got %v while trying to parse %s as time.Time / RFC3339 (should never happen if the grammar is correct)", err, buffer[begin:end]))
}
conditions = append(conditions, Condition{tag, op, value})
case ruledate:
value, err := time.Parse("2006-01-02", buffer[begin:end])
if err != nil {
panic(fmt.Sprintf("got %v while trying to parse %s as time.Time / '2006-01-02' (should never happen if the grammar is correct)", err, buffer[begin:end]))
}
conditions = append(conditions, Condition{tag, op, value})
}
}
return conditions
} | [
"func",
"(",
"q",
"*",
"query",
")",
"Conditions",
"(",
")",
"[",
"]",
"Condition",
"{",
"conditions",
":=",
"make",
"(",
"[",
"]",
"Condition",
",",
"0",
")",
"\n\n",
"buffer",
",",
"begin",
",",
"end",
":=",
"q",
".",
"parser",
".",
"Buffer",
",",
"0",
",",
"0",
"\n\n",
"var",
"tag",
"string",
"\n",
"var",
"op",
"Operator",
"\n\n",
"// tokens must be in the following order: tag (\"tx.gas\") -> operator (\"=\") -> operand (\"7\")",
"for",
"_",
",",
"token",
":=",
"range",
"q",
".",
"parser",
".",
"Tokens",
"(",
")",
"{",
"switch",
"token",
".",
"pegRule",
"{",
"case",
"rulePegText",
":",
"begin",
",",
"end",
"=",
"int",
"(",
"token",
".",
"begin",
")",
",",
"int",
"(",
"token",
".",
"end",
")",
"\n",
"case",
"ruletag",
":",
"tag",
"=",
"buffer",
"[",
"begin",
":",
"end",
"]",
"\n",
"case",
"rulele",
":",
"op",
"=",
"OpLessEqual",
"\n",
"case",
"rulege",
":",
"op",
"=",
"OpGreaterEqual",
"\n",
"case",
"rulel",
":",
"op",
"=",
"OpLess",
"\n",
"case",
"ruleg",
":",
"op",
"=",
"OpGreater",
"\n",
"case",
"ruleequal",
":",
"op",
"=",
"OpEqual",
"\n",
"case",
"rulecontains",
":",
"op",
"=",
"OpContains",
"\n",
"case",
"rulevalue",
":",
"// strip single quotes from value (i.e. \"'NewBlock'\" -> \"NewBlock\")",
"valueWithoutSingleQuotes",
":=",
"buffer",
"[",
"begin",
"+",
"1",
":",
"end",
"-",
"1",
"]",
"\n",
"conditions",
"=",
"append",
"(",
"conditions",
",",
"Condition",
"{",
"tag",
",",
"op",
",",
"valueWithoutSingleQuotes",
"}",
")",
"\n",
"case",
"rulenumber",
":",
"number",
":=",
"buffer",
"[",
"begin",
":",
"end",
"]",
"\n",
"if",
"strings",
".",
"ContainsAny",
"(",
"number",
",",
"\"",
"\"",
")",
"{",
"// if it looks like a floating-point number",
"value",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"number",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
",",
"number",
")",
")",
"\n",
"}",
"\n",
"conditions",
"=",
"append",
"(",
"conditions",
",",
"Condition",
"{",
"tag",
",",
"op",
",",
"value",
"}",
")",
"\n",
"}",
"else",
"{",
"value",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"number",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
",",
"number",
")",
")",
"\n",
"}",
"\n",
"conditions",
"=",
"append",
"(",
"conditions",
",",
"Condition",
"{",
"tag",
",",
"op",
",",
"value",
"}",
")",
"\n",
"}",
"\n",
"case",
"ruletime",
":",
"value",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"TimeLayout",
",",
"buffer",
"[",
"begin",
":",
"end",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
",",
"buffer",
"[",
"begin",
":",
"end",
"]",
")",
")",
"\n",
"}",
"\n",
"conditions",
"=",
"append",
"(",
"conditions",
",",
"Condition",
"{",
"tag",
",",
"op",
",",
"value",
"}",
")",
"\n",
"case",
"ruledate",
":",
"value",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"\"",
"\"",
",",
"buffer",
"[",
"begin",
":",
"end",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
",",
"buffer",
"[",
"begin",
":",
"end",
"]",
")",
")",
"\n",
"}",
"\n",
"conditions",
"=",
"append",
"(",
"conditions",
",",
"Condition",
"{",
"tag",
",",
"op",
",",
"value",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"conditions",
"\n",
"}"
] | // Conditions returns a list of conditions. | [
"Conditions",
"returns",
"a",
"list",
"of",
"conditions",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/query/query.go#L93-L156 | train |
hyperledger/burrow | deploy/def/job.go | PayloadField | func (job *Job) PayloadField() (reflect.Value, error) {
rv := reflect.ValueOf(job).Elem()
rt := rv.Type()
payloadIndex := -1
for i := 0; i < rt.NumField(); i++ {
if rt.Field(i).Type.Implements(payloadType) && !rv.Field(i).IsNil() {
if payloadIndex >= 0 {
return reflect.Value{}, fmt.Errorf("only one Job payload field should be set, but both '%v' and '%v' are set",
rt.Field(payloadIndex).Name, rt.Field(i).Name)
}
payloadIndex = i
}
}
if payloadIndex == -1 {
return reflect.Value{}, fmt.Errorf("Job has no payload, please set at least one job value")
}
return rv.Field(payloadIndex), nil
} | go | func (job *Job) PayloadField() (reflect.Value, error) {
rv := reflect.ValueOf(job).Elem()
rt := rv.Type()
payloadIndex := -1
for i := 0; i < rt.NumField(); i++ {
if rt.Field(i).Type.Implements(payloadType) && !rv.Field(i).IsNil() {
if payloadIndex >= 0 {
return reflect.Value{}, fmt.Errorf("only one Job payload field should be set, but both '%v' and '%v' are set",
rt.Field(payloadIndex).Name, rt.Field(i).Name)
}
payloadIndex = i
}
}
if payloadIndex == -1 {
return reflect.Value{}, fmt.Errorf("Job has no payload, please set at least one job value")
}
return rv.Field(payloadIndex), nil
} | [
"func",
"(",
"job",
"*",
"Job",
")",
"PayloadField",
"(",
")",
"(",
"reflect",
".",
"Value",
",",
"error",
")",
"{",
"rv",
":=",
"reflect",
".",
"ValueOf",
"(",
"job",
")",
".",
"Elem",
"(",
")",
"\n",
"rt",
":=",
"rv",
".",
"Type",
"(",
")",
"\n\n",
"payloadIndex",
":=",
"-",
"1",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"rt",
".",
"NumField",
"(",
")",
";",
"i",
"++",
"{",
"if",
"rt",
".",
"Field",
"(",
"i",
")",
".",
"Type",
".",
"Implements",
"(",
"payloadType",
")",
"&&",
"!",
"rv",
".",
"Field",
"(",
"i",
")",
".",
"IsNil",
"(",
")",
"{",
"if",
"payloadIndex",
">=",
"0",
"{",
"return",
"reflect",
".",
"Value",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rt",
".",
"Field",
"(",
"payloadIndex",
")",
".",
"Name",
",",
"rt",
".",
"Field",
"(",
"i",
")",
".",
"Name",
")",
"\n",
"}",
"\n",
"payloadIndex",
"=",
"i",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"payloadIndex",
"==",
"-",
"1",
"{",
"return",
"reflect",
".",
"Value",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"rv",
".",
"Field",
"(",
"payloadIndex",
")",
",",
"nil",
"\n",
"}"
] | // Ensures only one Job payload is set and returns a pointer to that field or an error if none or multiple
// job payload fields are set | [
"Ensures",
"only",
"one",
"Job",
"payload",
"is",
"set",
"and",
"returns",
"a",
"pointer",
"to",
"that",
"field",
"or",
"an",
"error",
"if",
"none",
"or",
"multiple",
"job",
"payload",
"fields",
"are",
"set"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/def/job.go#L95-L114 | train |
hyperledger/burrow | crypto/public_key.go | PublicKeyLength | func PublicKeyLength(curveType CurveType) int {
switch curveType {
case CurveTypeEd25519:
return ed25519.PublicKeySize
case CurveTypeSecp256k1:
return btcec.PubKeyBytesLenCompressed
default:
// Other functions rely on this
return 0
}
} | go | func PublicKeyLength(curveType CurveType) int {
switch curveType {
case CurveTypeEd25519:
return ed25519.PublicKeySize
case CurveTypeSecp256k1:
return btcec.PubKeyBytesLenCompressed
default:
// Other functions rely on this
return 0
}
} | [
"func",
"PublicKeyLength",
"(",
"curveType",
"CurveType",
")",
"int",
"{",
"switch",
"curveType",
"{",
"case",
"CurveTypeEd25519",
":",
"return",
"ed25519",
".",
"PublicKeySize",
"\n",
"case",
"CurveTypeSecp256k1",
":",
"return",
"btcec",
".",
"PubKeyBytesLenCompressed",
"\n",
"default",
":",
"// Other functions rely on this",
"return",
"0",
"\n",
"}",
"\n",
"}"
] | // Returns the length in bytes of the public key | [
"Returns",
"the",
"length",
"in",
"bytes",
"of",
"the",
"public",
"key"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/crypto/public_key.go#L26-L36 | train |
hyperledger/burrow | crypto/public_key.go | EncodeFixedWidth | func (p PublicKey) EncodeFixedWidth() []byte {
encoded := make([]byte, PublicKeyFixedWidthEncodingLength)
encoded[0] = p.CurveType.Byte()
copy(encoded[1:], p.PublicKey)
return encoded
} | go | func (p PublicKey) EncodeFixedWidth() []byte {
encoded := make([]byte, PublicKeyFixedWidthEncodingLength)
encoded[0] = p.CurveType.Byte()
copy(encoded[1:], p.PublicKey)
return encoded
} | [
"func",
"(",
"p",
"PublicKey",
")",
"EncodeFixedWidth",
"(",
")",
"[",
"]",
"byte",
"{",
"encoded",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"PublicKeyFixedWidthEncodingLength",
")",
"\n",
"encoded",
"[",
"0",
"]",
"=",
"p",
".",
"CurveType",
".",
"Byte",
"(",
")",
"\n",
"copy",
"(",
"encoded",
"[",
"1",
":",
"]",
",",
"p",
".",
"PublicKey",
")",
"\n",
"return",
"encoded",
"\n",
"}"
] | // Produces a binary encoding of the CurveType byte plus
// the public key for padded to a fixed width on the right | [
"Produces",
"a",
"binary",
"encoding",
"of",
"the",
"CurveType",
"byte",
"plus",
"the",
"public",
"key",
"for",
"padded",
"to",
"a",
"fixed",
"width",
"on",
"the",
"right"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/crypto/public_key.go#L145-L150 | train |
hyperledger/burrow | crypto/address.go | SequenceNonce | func SequenceNonce(address Address, sequence uint64) []byte {
bs := make([]byte, 8)
binary.PutUint64BE(bs, sequence)
return Nonce(address, bs)
} | go | func SequenceNonce(address Address, sequence uint64) []byte {
bs := make([]byte, 8)
binary.PutUint64BE(bs, sequence)
return Nonce(address, bs)
} | [
"func",
"SequenceNonce",
"(",
"address",
"Address",
",",
"sequence",
"uint64",
")",
"[",
"]",
"byte",
"{",
"bs",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"8",
")",
"\n",
"binary",
".",
"PutUint64BE",
"(",
"bs",
",",
"sequence",
")",
"\n",
"return",
"Nonce",
"(",
"address",
",",
"bs",
")",
"\n",
"}"
] | // Obtain a nearly unique nonce based on a montonic account sequence number | [
"Obtain",
"a",
"nearly",
"unique",
"nonce",
"based",
"on",
"a",
"montonic",
"account",
"sequence",
"number"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/crypto/address.go#L191-L195 | train |
hyperledger/burrow | rpc/rpcquery/query_server.go | GetBlockHeader | func (qs *queryServer) GetBlockHeader(ctx context.Context, param *GetBlockParam) (*types.Header, error) {
header, err := qs.blockchain.GetBlockHeader(param.Height)
if err != nil {
return nil, err
}
abciHeader := tmtypes.TM2PB.Header(header)
return &abciHeader, nil
} | go | func (qs *queryServer) GetBlockHeader(ctx context.Context, param *GetBlockParam) (*types.Header, error) {
header, err := qs.blockchain.GetBlockHeader(param.Height)
if err != nil {
return nil, err
}
abciHeader := tmtypes.TM2PB.Header(header)
return &abciHeader, nil
} | [
"func",
"(",
"qs",
"*",
"queryServer",
")",
"GetBlockHeader",
"(",
"ctx",
"context",
".",
"Context",
",",
"param",
"*",
"GetBlockParam",
")",
"(",
"*",
"types",
".",
"Header",
",",
"error",
")",
"{",
"header",
",",
"err",
":=",
"qs",
".",
"blockchain",
".",
"GetBlockHeader",
"(",
"param",
".",
"Height",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"abciHeader",
":=",
"tmtypes",
".",
"TM2PB",
".",
"Header",
"(",
"header",
")",
"\n",
"return",
"&",
"abciHeader",
",",
"nil",
"\n",
"}"
] | // Tendermint and blocks | [
"Tendermint",
"and",
"blocks"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/rpc/rpcquery/query_server.go#L181-L188 | train |
hyperledger/burrow | keys/key_store.go | IsValidKeyJson | func IsValidKeyJson(j []byte) []byte {
j1 := new(keyJSON)
e1 := json.Unmarshal(j, &j1)
if e1 == nil {
addr, _ := hex.DecodeString(j1.Address)
return addr
}
return nil
} | go | func IsValidKeyJson(j []byte) []byte {
j1 := new(keyJSON)
e1 := json.Unmarshal(j, &j1)
if e1 == nil {
addr, _ := hex.DecodeString(j1.Address)
return addr
}
return nil
} | [
"func",
"IsValidKeyJson",
"(",
"j",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"j1",
":=",
"new",
"(",
"keyJSON",
")",
"\n",
"e1",
":=",
"json",
".",
"Unmarshal",
"(",
"j",
",",
"&",
"j1",
")",
"\n",
"if",
"e1",
"==",
"nil",
"{",
"addr",
",",
"_",
":=",
"hex",
".",
"DecodeString",
"(",
"j1",
".",
"Address",
")",
"\n",
"return",
"addr",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // returns the address if valid, nil otherwise | [
"returns",
"the",
"address",
"if",
"valid",
"nil",
"otherwise"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/keys/key_store.go#L96-L104 | train |
hyperledger/burrow | consensus/tendermint/priv_validator_memory.go | NewPrivValidatorMemory | func NewPrivValidatorMemory(addressable crypto.Addressable, signer crypto.Signer) *privValidatorMemory {
return &privValidatorMemory{
Addressable: addressable,
signer: asTendermintSigner(signer),
lastSignedInfo: NewLastSignedInfo(),
}
} | go | func NewPrivValidatorMemory(addressable crypto.Addressable, signer crypto.Signer) *privValidatorMemory {
return &privValidatorMemory{
Addressable: addressable,
signer: asTendermintSigner(signer),
lastSignedInfo: NewLastSignedInfo(),
}
} | [
"func",
"NewPrivValidatorMemory",
"(",
"addressable",
"crypto",
".",
"Addressable",
",",
"signer",
"crypto",
".",
"Signer",
")",
"*",
"privValidatorMemory",
"{",
"return",
"&",
"privValidatorMemory",
"{",
"Addressable",
":",
"addressable",
",",
"signer",
":",
"asTendermintSigner",
"(",
"signer",
")",
",",
"lastSignedInfo",
":",
"NewLastSignedInfo",
"(",
")",
",",
"}",
"\n",
"}"
] | // Create a PrivValidator with in-memory state that takes an addressable representing the validator identity
// and a signer providing private signing for that identity. | [
"Create",
"a",
"PrivValidator",
"with",
"in",
"-",
"memory",
"state",
"that",
"takes",
"an",
"addressable",
"representing",
"the",
"validator",
"identity",
"and",
"a",
"signer",
"providing",
"private",
"signing",
"for",
"that",
"identity",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/consensus/tendermint/priv_validator_memory.go#L19-L25 | train |
hyperledger/burrow | util/snatives/templates/indent_writer.go | NewIndentWriter | func NewIndentWriter(indentLevel uint, indentString string,
writer io.Writer) *indentWriter {
return &indentWriter{
writer: writer,
indentLevel: indentLevel,
indentBytes: []byte(indentString),
indent: true,
}
} | go | func NewIndentWriter(indentLevel uint, indentString string,
writer io.Writer) *indentWriter {
return &indentWriter{
writer: writer,
indentLevel: indentLevel,
indentBytes: []byte(indentString),
indent: true,
}
} | [
"func",
"NewIndentWriter",
"(",
"indentLevel",
"uint",
",",
"indentString",
"string",
",",
"writer",
"io",
".",
"Writer",
")",
"*",
"indentWriter",
"{",
"return",
"&",
"indentWriter",
"{",
"writer",
":",
"writer",
",",
"indentLevel",
":",
"indentLevel",
",",
"indentBytes",
":",
"[",
"]",
"byte",
"(",
"indentString",
")",
",",
"indent",
":",
"true",
",",
"}",
"\n",
"}"
] | // indentWriter indents all lines written to it with a specified indent string
// indented the specified number of indents | [
"indentWriter",
"indents",
"all",
"lines",
"written",
"to",
"it",
"with",
"a",
"specified",
"indent",
"string",
"indented",
"the",
"specified",
"number",
"of",
"indents"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/util/snatives/templates/indent_writer.go#L32-L40 | train |
hyperledger/burrow | acm/validator/ring.go | NewRing | func NewRing(initialSet Iterable, windowSize int) *Ring {
if windowSize < 1 {
windowSize = 1
}
vc := &Ring{
buckets: make([]*Bucket, windowSize),
power: NewTrimSet(),
size: windowSize,
}
for i := 0; i < windowSize; i++ {
vc.buckets[i] = NewBucket()
}
if initialSet != nil {
vc.populated = 1
vc.buckets[0] = NewBucket(initialSet)
}
return vc
} | go | func NewRing(initialSet Iterable, windowSize int) *Ring {
if windowSize < 1 {
windowSize = 1
}
vc := &Ring{
buckets: make([]*Bucket, windowSize),
power: NewTrimSet(),
size: windowSize,
}
for i := 0; i < windowSize; i++ {
vc.buckets[i] = NewBucket()
}
if initialSet != nil {
vc.populated = 1
vc.buckets[0] = NewBucket(initialSet)
}
return vc
} | [
"func",
"NewRing",
"(",
"initialSet",
"Iterable",
",",
"windowSize",
"int",
")",
"*",
"Ring",
"{",
"if",
"windowSize",
"<",
"1",
"{",
"windowSize",
"=",
"1",
"\n",
"}",
"\n",
"vc",
":=",
"&",
"Ring",
"{",
"buckets",
":",
"make",
"(",
"[",
"]",
"*",
"Bucket",
",",
"windowSize",
")",
",",
"power",
":",
"NewTrimSet",
"(",
")",
",",
"size",
":",
"windowSize",
",",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"windowSize",
";",
"i",
"++",
"{",
"vc",
".",
"buckets",
"[",
"i",
"]",
"=",
"NewBucket",
"(",
")",
"\n",
"}",
"\n",
"if",
"initialSet",
"!=",
"nil",
"{",
"vc",
".",
"populated",
"=",
"1",
"\n",
"vc",
".",
"buckets",
"[",
"0",
"]",
"=",
"NewBucket",
"(",
"initialSet",
")",
"\n",
"}",
"\n",
"return",
"vc",
"\n",
"}"
] | // Provides a sliding window over the last size buckets of validator power changes | [
"Provides",
"a",
"sliding",
"window",
"over",
"the",
"last",
"size",
"buckets",
"of",
"validator",
"power",
"changes"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/validator/ring.go#L40-L57 | train |
hyperledger/burrow | acm/validator/ring.go | Power | func (vc *Ring) Power(id crypto.Address) (*big.Int, error) {
return vc.GetPower(id), nil
} | go | func (vc *Ring) Power(id crypto.Address) (*big.Int, error) {
return vc.GetPower(id), nil
} | [
"func",
"(",
"vc",
"*",
"Ring",
")",
"Power",
"(",
"id",
"crypto",
".",
"Address",
")",
"(",
"*",
"big",
".",
"Int",
",",
"error",
")",
"{",
"return",
"vc",
".",
"GetPower",
"(",
"id",
")",
",",
"nil",
"\n",
"}"
] | // Implement Reader
// Get power at index from the delta bucket then falling through to the cumulative | [
"Implement",
"Reader",
"Get",
"power",
"at",
"index",
"from",
"the",
"delta",
"bucket",
"then",
"falling",
"through",
"to",
"the",
"cumulative"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/validator/ring.go#L61-L63 | train |
hyperledger/burrow | acm/validator/ring.go | Rotate | func (vc *Ring) Rotate() (totalPowerChange *big.Int, totalFlow *big.Int, err error) {
// Subtract the tail bucket (if any) from the total
err = Subtract(vc.power, vc.Next().Delta)
if err != nil {
return
}
// Capture current head as previous before advancing buffer
prevHead := vc.Head()
// Add head delta to total power
err = Add(vc.power, prevHead.Delta)
if err != nil {
return
}
// Advance the ring buffer
vc.head = vc.index(1)
// Overwrite new head bucket (previous tail) with a fresh bucket with Previous_i+1 = Next_i = Previous_i + Delta_i
vc.buckets[vc.head] = NewBucket(prevHead.Next)
// Capture flow before we wipe it
totalFlow = prevHead.Flow.totalPower
// Subtract the previous bucket total power so we can add on the current buckets power after this
totalPowerChange = new(big.Int).Sub(vc.Head().Previous.TotalPower(), prevHead.Previous.TotalPower())
// Record how many of our buckets we have cycled over
if vc.populated < vc.size {
vc.populated++
}
return
} | go | func (vc *Ring) Rotate() (totalPowerChange *big.Int, totalFlow *big.Int, err error) {
// Subtract the tail bucket (if any) from the total
err = Subtract(vc.power, vc.Next().Delta)
if err != nil {
return
}
// Capture current head as previous before advancing buffer
prevHead := vc.Head()
// Add head delta to total power
err = Add(vc.power, prevHead.Delta)
if err != nil {
return
}
// Advance the ring buffer
vc.head = vc.index(1)
// Overwrite new head bucket (previous tail) with a fresh bucket with Previous_i+1 = Next_i = Previous_i + Delta_i
vc.buckets[vc.head] = NewBucket(prevHead.Next)
// Capture flow before we wipe it
totalFlow = prevHead.Flow.totalPower
// Subtract the previous bucket total power so we can add on the current buckets power after this
totalPowerChange = new(big.Int).Sub(vc.Head().Previous.TotalPower(), prevHead.Previous.TotalPower())
// Record how many of our buckets we have cycled over
if vc.populated < vc.size {
vc.populated++
}
return
} | [
"func",
"(",
"vc",
"*",
"Ring",
")",
"Rotate",
"(",
")",
"(",
"totalPowerChange",
"*",
"big",
".",
"Int",
",",
"totalFlow",
"*",
"big",
".",
"Int",
",",
"err",
"error",
")",
"{",
"// Subtract the tail bucket (if any) from the total",
"err",
"=",
"Subtract",
"(",
"vc",
".",
"power",
",",
"vc",
".",
"Next",
"(",
")",
".",
"Delta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// Capture current head as previous before advancing buffer",
"prevHead",
":=",
"vc",
".",
"Head",
"(",
")",
"\n",
"// Add head delta to total power",
"err",
"=",
"Add",
"(",
"vc",
".",
"power",
",",
"prevHead",
".",
"Delta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// Advance the ring buffer",
"vc",
".",
"head",
"=",
"vc",
".",
"index",
"(",
"1",
")",
"\n",
"// Overwrite new head bucket (previous tail) with a fresh bucket with Previous_i+1 = Next_i = Previous_i + Delta_i",
"vc",
".",
"buckets",
"[",
"vc",
".",
"head",
"]",
"=",
"NewBucket",
"(",
"prevHead",
".",
"Next",
")",
"\n",
"// Capture flow before we wipe it",
"totalFlow",
"=",
"prevHead",
".",
"Flow",
".",
"totalPower",
"\n",
"// Subtract the previous bucket total power so we can add on the current buckets power after this",
"totalPowerChange",
"=",
"new",
"(",
"big",
".",
"Int",
")",
".",
"Sub",
"(",
"vc",
".",
"Head",
"(",
")",
".",
"Previous",
".",
"TotalPower",
"(",
")",
",",
"prevHead",
".",
"Previous",
".",
"TotalPower",
"(",
")",
")",
"\n",
"// Record how many of our buckets we have cycled over",
"if",
"vc",
".",
"populated",
"<",
"vc",
".",
"size",
"{",
"vc",
".",
"populated",
"++",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Advance the current head bucket to the next bucket and returns the change in total power between the previous bucket
// and the current head, and the total flow which is the sum of absolute values of all changes each validator's power
// after rotation the next head is a copy of the current head | [
"Advance",
"the",
"current",
"head",
"bucket",
"to",
"the",
"next",
"bucket",
"and",
"returns",
"the",
"change",
"in",
"total",
"power",
"between",
"the",
"previous",
"bucket",
"and",
"the",
"current",
"head",
"and",
"the",
"total",
"flow",
"which",
"is",
"the",
"sum",
"of",
"absolute",
"values",
"of",
"all",
"changes",
"each",
"validator",
"s",
"power",
"after",
"rotation",
"the",
"next",
"head",
"is",
"a",
"copy",
"of",
"the",
"current",
"head"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/validator/ring.go#L86-L112 | train |
hyperledger/burrow | acm/validator/ring.go | OrderedBuckets | func (vc *Ring) OrderedBuckets() []*Bucket {
buckets := make([]*Bucket, len(vc.buckets))
for i := int(0); i < vc.size; i++ {
index := vc.index(-i)
buckets[i] = vc.buckets[index]
}
return buckets
} | go | func (vc *Ring) OrderedBuckets() []*Bucket {
buckets := make([]*Bucket, len(vc.buckets))
for i := int(0); i < vc.size; i++ {
index := vc.index(-i)
buckets[i] = vc.buckets[index]
}
return buckets
} | [
"func",
"(",
"vc",
"*",
"Ring",
")",
"OrderedBuckets",
"(",
")",
"[",
"]",
"*",
"Bucket",
"{",
"buckets",
":=",
"make",
"(",
"[",
"]",
"*",
"Bucket",
",",
"len",
"(",
"vc",
".",
"buckets",
")",
")",
"\n",
"for",
"i",
":=",
"int",
"(",
"0",
")",
";",
"i",
"<",
"vc",
".",
"size",
";",
"i",
"++",
"{",
"index",
":=",
"vc",
".",
"index",
"(",
"-",
"i",
")",
"\n",
"buckets",
"[",
"i",
"]",
"=",
"vc",
".",
"buckets",
"[",
"index",
"]",
"\n",
"}",
"\n",
"return",
"buckets",
"\n",
"}"
] | // Returns buckets in order head, previous, ... | [
"Returns",
"buckets",
"in",
"order",
"head",
"previous",
"..."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/validator/ring.go#L169-L176 | train |
hyperledger/burrow | execution/evm/asm/bc/helpers.go | Concat | func Concat(bss ...[]byte) []byte {
offset := 0
for _, bs := range bss {
offset += len(bs)
}
bytes := make([]byte, offset)
offset = 0
for _, bs := range bss {
for i, b := range bs {
bytes[offset+i] = b
}
offset += len(bs)
}
return bytes
} | go | func Concat(bss ...[]byte) []byte {
offset := 0
for _, bs := range bss {
offset += len(bs)
}
bytes := make([]byte, offset)
offset = 0
for _, bs := range bss {
for i, b := range bs {
bytes[offset+i] = b
}
offset += len(bs)
}
return bytes
} | [
"func",
"Concat",
"(",
"bss",
"...",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"offset",
":=",
"0",
"\n",
"for",
"_",
",",
"bs",
":=",
"range",
"bss",
"{",
"offset",
"+=",
"len",
"(",
"bs",
")",
"\n",
"}",
"\n",
"bytes",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"offset",
")",
"\n",
"offset",
"=",
"0",
"\n",
"for",
"_",
",",
"bs",
":=",
"range",
"bss",
"{",
"for",
"i",
",",
"b",
":=",
"range",
"bs",
"{",
"bytes",
"[",
"offset",
"+",
"i",
"]",
"=",
"b",
"\n",
"}",
"\n",
"offset",
"+=",
"len",
"(",
"bs",
")",
"\n",
"}",
"\n",
"return",
"bytes",
"\n",
"}"
] | // Concatenate multiple byte slices without unnecessary copying | [
"Concatenate",
"multiple",
"byte",
"slices",
"without",
"unnecessary",
"copying"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/asm/bc/helpers.go#L14-L28 | train |
hyperledger/burrow | execution/evm/asm/bc/helpers.go | MustSplice | func MustSplice(bytelikes ...interface{}) []byte {
spliced, err := Splice(bytelikes...)
if err != nil {
panic(err)
}
return spliced
} | go | func MustSplice(bytelikes ...interface{}) []byte {
spliced, err := Splice(bytelikes...)
if err != nil {
panic(err)
}
return spliced
} | [
"func",
"MustSplice",
"(",
"bytelikes",
"...",
"interface",
"{",
"}",
")",
"[",
"]",
"byte",
"{",
"spliced",
",",
"err",
":=",
"Splice",
"(",
"bytelikes",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"spliced",
"\n",
"}"
] | // Splice or panic | [
"Splice",
"or",
"panic"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/asm/bc/helpers.go#L31-L37 | train |
hyperledger/burrow | execution/evm/asm/bc/helpers.go | byteSlicify | func byteSlicify(bytelike interface{}) ([]byte, error) {
switch b := bytelike.(type) {
case byte:
return []byte{b}, nil
case asm.OpCode:
return []byte{byte(b)}, nil
case int:
if int(byte(b)) != b {
return nil, fmt.Errorf("the int %v does not fit inside a byte", b)
}
return []byte{byte(b)}, nil
case int64:
if int64(byte(b)) != b {
return nil, fmt.Errorf("the int64 %v does not fit inside a byte", b)
}
return []byte{byte(b)}, nil
case uint64:
if uint64(byte(b)) != b {
return nil, fmt.Errorf("the uint64 %v does not fit inside a byte", b)
}
return []byte{byte(b)}, nil
case string:
return []byte(b), nil
case ByteSlicable:
return b.Bytes(), nil
case []byte:
return b, nil
default:
return nil, fmt.Errorf("could not convert %s to a byte or sequence of bytes", bytelike)
}
} | go | func byteSlicify(bytelike interface{}) ([]byte, error) {
switch b := bytelike.(type) {
case byte:
return []byte{b}, nil
case asm.OpCode:
return []byte{byte(b)}, nil
case int:
if int(byte(b)) != b {
return nil, fmt.Errorf("the int %v does not fit inside a byte", b)
}
return []byte{byte(b)}, nil
case int64:
if int64(byte(b)) != b {
return nil, fmt.Errorf("the int64 %v does not fit inside a byte", b)
}
return []byte{byte(b)}, nil
case uint64:
if uint64(byte(b)) != b {
return nil, fmt.Errorf("the uint64 %v does not fit inside a byte", b)
}
return []byte{byte(b)}, nil
case string:
return []byte(b), nil
case ByteSlicable:
return b.Bytes(), nil
case []byte:
return b, nil
default:
return nil, fmt.Errorf("could not convert %s to a byte or sequence of bytes", bytelike)
}
} | [
"func",
"byteSlicify",
"(",
"bytelike",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"switch",
"b",
":=",
"bytelike",
".",
"(",
"type",
")",
"{",
"case",
"byte",
":",
"return",
"[",
"]",
"byte",
"{",
"b",
"}",
",",
"nil",
"\n",
"case",
"asm",
".",
"OpCode",
":",
"return",
"[",
"]",
"byte",
"{",
"byte",
"(",
"b",
")",
"}",
",",
"nil",
"\n",
"case",
"int",
":",
"if",
"int",
"(",
"byte",
"(",
"b",
")",
")",
"!=",
"b",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"b",
")",
"\n",
"}",
"\n",
"return",
"[",
"]",
"byte",
"{",
"byte",
"(",
"b",
")",
"}",
",",
"nil",
"\n",
"case",
"int64",
":",
"if",
"int64",
"(",
"byte",
"(",
"b",
")",
")",
"!=",
"b",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"b",
")",
"\n",
"}",
"\n",
"return",
"[",
"]",
"byte",
"{",
"byte",
"(",
"b",
")",
"}",
",",
"nil",
"\n",
"case",
"uint64",
":",
"if",
"uint64",
"(",
"byte",
"(",
"b",
")",
")",
"!=",
"b",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"b",
")",
"\n",
"}",
"\n",
"return",
"[",
"]",
"byte",
"{",
"byte",
"(",
"b",
")",
"}",
",",
"nil",
"\n",
"case",
"string",
":",
"return",
"[",
"]",
"byte",
"(",
"b",
")",
",",
"nil",
"\n",
"case",
"ByteSlicable",
":",
"return",
"b",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"case",
"[",
"]",
"byte",
":",
"return",
"b",
",",
"nil",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"bytelike",
")",
"\n",
"}",
"\n",
"}"
] | // Convert anything byte or byte slice like to a byte slice | [
"Convert",
"anything",
"byte",
"or",
"byte",
"slice",
"like",
"to",
"a",
"byte",
"slice"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/asm/bc/helpers.go#L56-L86 | train |
hyperledger/burrow | util/slice/slice.go | CopyPrepend | func CopyPrepend(slice []interface{}, elements ...interface{}) []interface{} {
elementsLength := len(elements)
newSlice := make([]interface{}, len(slice)+elementsLength)
for i, e := range elements {
newSlice[i] = e
}
for i, e := range slice {
newSlice[elementsLength+i] = e
}
return newSlice
} | go | func CopyPrepend(slice []interface{}, elements ...interface{}) []interface{} {
elementsLength := len(elements)
newSlice := make([]interface{}, len(slice)+elementsLength)
for i, e := range elements {
newSlice[i] = e
}
for i, e := range slice {
newSlice[elementsLength+i] = e
}
return newSlice
} | [
"func",
"CopyPrepend",
"(",
"slice",
"[",
"]",
"interface",
"{",
"}",
",",
"elements",
"...",
"interface",
"{",
"}",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"elementsLength",
":=",
"len",
"(",
"elements",
")",
"\n",
"newSlice",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"slice",
")",
"+",
"elementsLength",
")",
"\n",
"for",
"i",
",",
"e",
":=",
"range",
"elements",
"{",
"newSlice",
"[",
"i",
"]",
"=",
"e",
"\n",
"}",
"\n",
"for",
"i",
",",
"e",
":=",
"range",
"slice",
"{",
"newSlice",
"[",
"elementsLength",
"+",
"i",
"]",
"=",
"e",
"\n",
"}",
"\n",
"return",
"newSlice",
"\n",
"}"
] | // Prepend elements to slice in the order they appear | [
"Prepend",
"elements",
"to",
"slice",
"in",
"the",
"order",
"they",
"appear"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/util/slice/slice.go#L41-L51 | train |
hyperledger/burrow | util/slice/slice.go | Concat | func Concat(slices ...[]interface{}) []interface{} {
offset := 0
for _, slice := range slices {
offset += len(slice)
}
concat := make([]interface{}, offset)
offset = 0
for _, slice := range slices {
for i, e := range slice {
concat[offset+i] = e
}
offset += len(slice)
}
return concat
} | go | func Concat(slices ...[]interface{}) []interface{} {
offset := 0
for _, slice := range slices {
offset += len(slice)
}
concat := make([]interface{}, offset)
offset = 0
for _, slice := range slices {
for i, e := range slice {
concat[offset+i] = e
}
offset += len(slice)
}
return concat
} | [
"func",
"Concat",
"(",
"slices",
"...",
"[",
"]",
"interface",
"{",
"}",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"offset",
":=",
"0",
"\n",
"for",
"_",
",",
"slice",
":=",
"range",
"slices",
"{",
"offset",
"+=",
"len",
"(",
"slice",
")",
"\n",
"}",
"\n",
"concat",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"offset",
")",
"\n",
"offset",
"=",
"0",
"\n",
"for",
"_",
",",
"slice",
":=",
"range",
"slices",
"{",
"for",
"i",
",",
"e",
":=",
"range",
"slice",
"{",
"concat",
"[",
"offset",
"+",
"i",
"]",
"=",
"e",
"\n",
"}",
"\n",
"offset",
"+=",
"len",
"(",
"slice",
")",
"\n",
"}",
"\n",
"return",
"concat",
"\n",
"}"
] | // Concatenate slices into a single slice | [
"Concatenate",
"slices",
"into",
"a",
"single",
"slice"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/util/slice/slice.go#L54-L68 | train |
hyperledger/burrow | util/slice/slice.go | Delete | func Delete(slice []interface{}, i int, n int) []interface{} {
return append(slice[:i], slice[i+n:]...)
} | go | func Delete(slice []interface{}, i int, n int) []interface{} {
return append(slice[:i], slice[i+n:]...)
} | [
"func",
"Delete",
"(",
"slice",
"[",
"]",
"interface",
"{",
"}",
",",
"i",
"int",
",",
"n",
"int",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"return",
"append",
"(",
"slice",
"[",
":",
"i",
"]",
",",
"slice",
"[",
"i",
"+",
"n",
":",
"]",
"...",
")",
"\n",
"}"
] | // Deletes n elements starting with the ith from a slice by splicing.
// Beware uses append so the underlying backing array will be modified! | [
"Deletes",
"n",
"elements",
"starting",
"with",
"the",
"ith",
"from",
"a",
"slice",
"by",
"splicing",
".",
"Beware",
"uses",
"append",
"so",
"the",
"underlying",
"backing",
"array",
"will",
"be",
"modified!"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/util/slice/slice.go#L72-L74 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.