repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
shiyanhui/dht | krpc.go | transaction | func (tm *transactionManager) transaction(
key string, keyType int) *transaction {
sm := tm.transactions
if keyType == 1 {
sm = tm.index
}
v, ok := sm.Get(key)
if !ok {
return nil
}
return v.(*transaction)
} | go | func (tm *transactionManager) transaction(
key string, keyType int) *transaction {
sm := tm.transactions
if keyType == 1 {
sm = tm.index
}
v, ok := sm.Get(key)
if !ok {
return nil
}
return v.(*transaction)
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"transaction",
"(",
"key",
"string",
",",
"keyType",
"int",
")",
"*",
"transaction",
"{",
"sm",
":=",
"tm",
".",
"transactions",
"\n",
"if",
"keyType",
"==",
"1",
"{",
"sm",
"=",
"tm",
".",
"index",
... | // transaction returns a transaction. keyType should be one of 0, 1 which
// represents transId and index each. | [
"transaction",
"returns",
"a",
"transaction",
".",
"keyType",
"should",
"be",
"one",
"of",
"0",
"1",
"which",
"represents",
"transId",
"and",
"index",
"each",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L234-L248 | train |
shiyanhui/dht | krpc.go | filterOne | func (tm *transactionManager) filterOne(
transID string, addr *net.UDPAddr) *transaction {
trans := tm.getByTransID(transID)
if trans == nil || trans.node.addr.String() != addr.String() {
return nil
}
return trans
} | go | func (tm *transactionManager) filterOne(
transID string, addr *net.UDPAddr) *transaction {
trans := tm.getByTransID(transID)
if trans == nil || trans.node.addr.String() != addr.String() {
return nil
}
return trans
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"filterOne",
"(",
"transID",
"string",
",",
"addr",
"*",
"net",
".",
"UDPAddr",
")",
"*",
"transaction",
"{",
"trans",
":=",
"tm",
".",
"getByTransID",
"(",
"transID",
")",
"\n",
"if",
"trans",
"==",
"... | // transaction gets the proper transaction with whose id is transId and
// address is addr. | [
"transaction",
"gets",
"the",
"proper",
"transaction",
"with",
"whose",
"id",
"is",
"transId",
"and",
"address",
"is",
"addr",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L262-L271 | train |
shiyanhui/dht | krpc.go | query | func (tm *transactionManager) query(q *query, try int) {
transID := q.data["t"].(string)
trans := tm.newTransaction(transID, q)
tm.insert(trans)
defer tm.delete(trans.id)
success := false
for i := 0; i < try; i++ {
if err := send(tm.dht, q.node.addr, q.data); err != nil {
break
}
select {
case <-trans.response:
success = true
break
case <-time.After(time.Second * 15):
}
}
if !success && q.node.id != nil {
tm.dht.blackList.insert(q.node.addr.IP.String(), q.node.addr.Port)
tm.dht.routingTable.RemoveByAddr(q.node.addr.String())
}
} | go | func (tm *transactionManager) query(q *query, try int) {
transID := q.data["t"].(string)
trans := tm.newTransaction(transID, q)
tm.insert(trans)
defer tm.delete(trans.id)
success := false
for i := 0; i < try; i++ {
if err := send(tm.dht, q.node.addr, q.data); err != nil {
break
}
select {
case <-trans.response:
success = true
break
case <-time.After(time.Second * 15):
}
}
if !success && q.node.id != nil {
tm.dht.blackList.insert(q.node.addr.IP.String(), q.node.addr.Port)
tm.dht.routingTable.RemoveByAddr(q.node.addr.String())
}
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"query",
"(",
"q",
"*",
"query",
",",
"try",
"int",
")",
"{",
"transID",
":=",
"q",
".",
"data",
"[",
"\"t\"",
"]",
".",
"(",
"string",
")",
"\n",
"trans",
":=",
"tm",
".",
"newTransaction",
"(",
... | // query sends the query-formed data to udp and wait for the response.
// When timeout, it will retry `try - 1` times, which means it will query
// `try` times totally. | [
"query",
"sends",
"the",
"query",
"-",
"formed",
"data",
"to",
"udp",
"and",
"wait",
"for",
"the",
"response",
".",
"When",
"timeout",
"it",
"will",
"retry",
"try",
"-",
"1",
"times",
"which",
"means",
"it",
"will",
"query",
"try",
"times",
"totally",
... | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L276-L301 | train |
shiyanhui/dht | krpc.go | run | func (tm *transactionManager) run() {
var q *query
for {
select {
case q = <-tm.queryChan:
go tm.query(q, tm.dht.Try)
}
}
} | go | func (tm *transactionManager) run() {
var q *query
for {
select {
case q = <-tm.queryChan:
go tm.query(q, tm.dht.Try)
}
}
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"run",
"(",
")",
"{",
"var",
"q",
"*",
"query",
"\n",
"for",
"{",
"select",
"{",
"case",
"q",
"=",
"<-",
"tm",
".",
"queryChan",
":",
"go",
"tm",
".",
"query",
"(",
"q",
",",
"tm",
".",
"dht",
... | // run starts to listen and consume the query chan. | [
"run",
"starts",
"to",
"listen",
"and",
"consume",
"the",
"query",
"chan",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L304-L313 | train |
shiyanhui/dht | krpc.go | sendQuery | func (tm *transactionManager) sendQuery(
no *node, queryType string, a map[string]interface{}) {
// If the target is self, then stop.
if no.id != nil && no.id.RawString() == tm.dht.node.id.RawString() ||
tm.getByIndex(tm.genIndexKey(queryType, no.addr.String())) != nil ||
tm.dht.blackList.in(no.addr.IP.String(), no.addr.Port) {
return
}
data := makeQuery(tm.genTransID(), queryType, a)
tm.queryChan <- &query{
node: no,
data: data,
}
} | go | func (tm *transactionManager) sendQuery(
no *node, queryType string, a map[string]interface{}) {
// If the target is self, then stop.
if no.id != nil && no.id.RawString() == tm.dht.node.id.RawString() ||
tm.getByIndex(tm.genIndexKey(queryType, no.addr.String())) != nil ||
tm.dht.blackList.in(no.addr.IP.String(), no.addr.Port) {
return
}
data := makeQuery(tm.genTransID(), queryType, a)
tm.queryChan <- &query{
node: no,
data: data,
}
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"sendQuery",
"(",
"no",
"*",
"node",
",",
"queryType",
"string",
",",
"a",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"if",
"no",
".",
"id",
"!=",
"nil",
"&&",
"no",
".",
"id",
"... | // sendQuery send query-formed data to the chan. | [
"sendQuery",
"send",
"query",
"-",
"formed",
"data",
"to",
"the",
"chan",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L316-L331 | train |
shiyanhui/dht | krpc.go | ping | func (tm *transactionManager) ping(no *node) {
tm.sendQuery(no, pingType, map[string]interface{}{
"id": tm.dht.id(no.id.RawString()),
})
} | go | func (tm *transactionManager) ping(no *node) {
tm.sendQuery(no, pingType, map[string]interface{}{
"id": tm.dht.id(no.id.RawString()),
})
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"ping",
"(",
"no",
"*",
"node",
")",
"{",
"tm",
".",
"sendQuery",
"(",
"no",
",",
"pingType",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"id\"",
":",
"tm",
".",
"dht",
".",
"id... | // ping sends ping query to the chan. | [
"ping",
"sends",
"ping",
"query",
"to",
"the",
"chan",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L334-L338 | train |
shiyanhui/dht | krpc.go | findNode | func (tm *transactionManager) findNode(no *node, target string) {
tm.sendQuery(no, findNodeType, map[string]interface{}{
"id": tm.dht.id(target),
"target": target,
})
} | go | func (tm *transactionManager) findNode(no *node, target string) {
tm.sendQuery(no, findNodeType, map[string]interface{}{
"id": tm.dht.id(target),
"target": target,
})
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"findNode",
"(",
"no",
"*",
"node",
",",
"target",
"string",
")",
"{",
"tm",
".",
"sendQuery",
"(",
"no",
",",
"findNodeType",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"id\"",
":... | // findNode sends find_node query to the chan. | [
"findNode",
"sends",
"find_node",
"query",
"to",
"the",
"chan",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L341-L346 | train |
shiyanhui/dht | krpc.go | getPeers | func (tm *transactionManager) getPeers(no *node, infoHash string) {
tm.sendQuery(no, getPeersType, map[string]interface{}{
"id": tm.dht.id(infoHash),
"info_hash": infoHash,
})
} | go | func (tm *transactionManager) getPeers(no *node, infoHash string) {
tm.sendQuery(no, getPeersType, map[string]interface{}{
"id": tm.dht.id(infoHash),
"info_hash": infoHash,
})
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"getPeers",
"(",
"no",
"*",
"node",
",",
"infoHash",
"string",
")",
"{",
"tm",
".",
"sendQuery",
"(",
"no",
",",
"getPeersType",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"id\"",
... | // getPeers sends get_peers query to the chan. | [
"getPeers",
"sends",
"get_peers",
"query",
"to",
"the",
"chan",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L349-L354 | train |
shiyanhui/dht | krpc.go | announcePeer | func (tm *transactionManager) announcePeer(
no *node, infoHash string, impliedPort, port int, token string) {
tm.sendQuery(no, announcePeerType, map[string]interface{}{
"id": tm.dht.id(no.id.RawString()),
"info_hash": infoHash,
"implied_port": impliedPort,
"port": port,
"token": token,
})
} | go | func (tm *transactionManager) announcePeer(
no *node, infoHash string, impliedPort, port int, token string) {
tm.sendQuery(no, announcePeerType, map[string]interface{}{
"id": tm.dht.id(no.id.RawString()),
"info_hash": infoHash,
"implied_port": impliedPort,
"port": port,
"token": token,
})
} | [
"func",
"(",
"tm",
"*",
"transactionManager",
")",
"announcePeer",
"(",
"no",
"*",
"node",
",",
"infoHash",
"string",
",",
"impliedPort",
",",
"port",
"int",
",",
"token",
"string",
")",
"{",
"tm",
".",
"sendQuery",
"(",
"no",
",",
"announcePeerType",
",... | // announcePeer sends announce_peer query to the chan. | [
"announcePeer",
"sends",
"announce_peer",
"query",
"to",
"the",
"chan",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L357-L367 | train |
shiyanhui/dht | krpc.go | ParseKey | func ParseKey(data map[string]interface{}, key string, t string) error {
val, ok := data[key]
if !ok {
return errors.New("lack of key")
}
switch t {
case "string":
_, ok = val.(string)
case "int":
_, ok = val.(int)
case "map":
_, ok = val.(map[string]interface{})
case "list":
_, ok = val.([]interface{})
default:
panic("invalid type")
}
if !ok {
return errors.New("invalid key type")
}
return nil
} | go | func ParseKey(data map[string]interface{}, key string, t string) error {
val, ok := data[key]
if !ok {
return errors.New("lack of key")
}
switch t {
case "string":
_, ok = val.(string)
case "int":
_, ok = val.(int)
case "map":
_, ok = val.(map[string]interface{})
case "list":
_, ok = val.([]interface{})
default:
panic("invalid type")
}
if !ok {
return errors.New("invalid key type")
}
return nil
} | [
"func",
"ParseKey",
"(",
"data",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"key",
"string",
",",
"t",
"string",
")",
"error",
"{",
"val",
",",
"ok",
":=",
"data",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
... | // ParseKey parses the key in dict data. `t` is type of the keyed value.
// It's one of "int", "string", "map", "list". | [
"ParseKey",
"parses",
"the",
"key",
"in",
"dict",
"data",
".",
"t",
"is",
"type",
"of",
"the",
"keyed",
"value",
".",
"It",
"s",
"one",
"of",
"int",
"string",
"map",
"list",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L371-L395 | train |
shiyanhui/dht | krpc.go | ParseKeys | func ParseKeys(data map[string]interface{}, pairs [][]string) error {
for _, args := range pairs {
key, t := args[0], args[1]
if err := ParseKey(data, key, t); err != nil {
return err
}
}
return nil
} | go | func ParseKeys(data map[string]interface{}, pairs [][]string) error {
for _, args := range pairs {
key, t := args[0], args[1]
if err := ParseKey(data, key, t); err != nil {
return err
}
}
return nil
} | [
"func",
"ParseKeys",
"(",
"data",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"pairs",
"[",
"]",
"[",
"]",
"string",
")",
"error",
"{",
"for",
"_",
",",
"args",
":=",
"range",
"pairs",
"{",
"key",
",",
"t",
":=",
"args",
"[",
"0",
"]... | // ParseKeys parses keys. It just wraps ParseKey. | [
"ParseKeys",
"parses",
"keys",
".",
"It",
"just",
"wraps",
"ParseKey",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L398-L406 | train |
shiyanhui/dht | krpc.go | parseMessage | func parseMessage(data interface{}) (map[string]interface{}, error) {
response, ok := data.(map[string]interface{})
if !ok {
return nil, errors.New("response is not dict")
}
if err := ParseKeys(
response, [][]string{{"t", "string"}, {"y", "string"}}); err != nil {
return nil, err
}
return response, nil
} | go | func parseMessage(data interface{}) (map[string]interface{}, error) {
response, ok := data.(map[string]interface{})
if !ok {
return nil, errors.New("response is not dict")
}
if err := ParseKeys(
response, [][]string{{"t", "string"}, {"y", "string"}}); err != nil {
return nil, err
}
return response, nil
} | [
"func",
"parseMessage",
"(",
"data",
"interface",
"{",
"}",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"response",
",",
"ok",
":=",
"data",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
... | // parseMessage parses the basic data received from udp.
// It returns a map value. | [
"parseMessage",
"parses",
"the",
"basic",
"data",
"received",
"from",
"udp",
".",
"It",
"returns",
"a",
"map",
"value",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L410-L422 | train |
shiyanhui/dht | krpc.go | findOn | func findOn(dht *DHT, r map[string]interface{}, target *bitmap,
queryType string) error {
if err := ParseKey(r, "nodes", "string"); err != nil {
return err
}
nodes := r["nodes"].(string)
if len(nodes)%26 != 0 {
return errors.New("the length of nodes should can be divided by 26")
}
hasNew, found := false, false
for i := 0; i < len(nodes)/26; i++ {
no, _ := newNodeFromCompactInfo(
string(nodes[i*26:(i+1)*26]), dht.Network)
if no.id.RawString() == target.RawString() {
found = true
}
if dht.routingTable.Insert(no) {
hasNew = true
}
}
if found || !hasNew {
return nil
}
targetID := target.RawString()
for _, no := range dht.routingTable.GetNeighbors(target, dht.K) {
switch queryType {
case findNodeType:
dht.transactionManager.findNode(no, targetID)
case getPeersType:
dht.transactionManager.getPeers(no, targetID)
default:
panic("invalid find type")
}
}
return nil
} | go | func findOn(dht *DHT, r map[string]interface{}, target *bitmap,
queryType string) error {
if err := ParseKey(r, "nodes", "string"); err != nil {
return err
}
nodes := r["nodes"].(string)
if len(nodes)%26 != 0 {
return errors.New("the length of nodes should can be divided by 26")
}
hasNew, found := false, false
for i := 0; i < len(nodes)/26; i++ {
no, _ := newNodeFromCompactInfo(
string(nodes[i*26:(i+1)*26]), dht.Network)
if no.id.RawString() == target.RawString() {
found = true
}
if dht.routingTable.Insert(no) {
hasNew = true
}
}
if found || !hasNew {
return nil
}
targetID := target.RawString()
for _, no := range dht.routingTable.GetNeighbors(target, dht.K) {
switch queryType {
case findNodeType:
dht.transactionManager.findNode(no, targetID)
case getPeersType:
dht.transactionManager.getPeers(no, targetID)
default:
panic("invalid find type")
}
}
return nil
} | [
"func",
"findOn",
"(",
"dht",
"*",
"DHT",
",",
"r",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"target",
"*",
"bitmap",
",",
"queryType",
"string",
")",
"error",
"{",
"if",
"err",
":=",
"ParseKey",
"(",
"r",
",",
"\"nodes\"",
",",
"\"st... | // findOn puts nodes in the response to the routingTable, then if target is in
// the nodes or all nodes are in the routingTable, it stops. Otherwise it
// continues to findNode or getPeers. | [
"findOn",
"puts",
"nodes",
"in",
"the",
"response",
"to",
"the",
"routingTable",
"then",
"if",
"target",
"is",
"in",
"the",
"nodes",
"or",
"all",
"nodes",
"are",
"in",
"the",
"routingTable",
"it",
"stops",
".",
"Otherwise",
"it",
"continues",
"to",
"findNo... | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L595-L637 | train |
shiyanhui/dht | krpc.go | handleError | func handleError(dht *DHT, addr *net.UDPAddr,
response map[string]interface{}) (success bool) {
if err := ParseKey(response, "e", "list"); err != nil {
return
}
if e := response["e"].([]interface{}); len(e) != 2 {
return
}
if trans := dht.transactionManager.filterOne(
response["t"].(string), addr); trans != nil {
trans.response <- struct{}{}
}
return true
} | go | func handleError(dht *DHT, addr *net.UDPAddr,
response map[string]interface{}) (success bool) {
if err := ParseKey(response, "e", "list"); err != nil {
return
}
if e := response["e"].([]interface{}); len(e) != 2 {
return
}
if trans := dht.transactionManager.filterOne(
response["t"].(string), addr); trans != nil {
trans.response <- struct{}{}
}
return true
} | [
"func",
"handleError",
"(",
"dht",
"*",
"DHT",
",",
"addr",
"*",
"net",
".",
"UDPAddr",
",",
"response",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"success",
"bool",
")",
"{",
"if",
"err",
":=",
"ParseKey",
"(",
"response",
",",
"... | // handleError handles errors received from udp. | [
"handleError",
"handles",
"errors",
"received",
"from",
"udp",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L728-L746 | train |
shiyanhui/dht | krpc.go | handle | func handle(dht *DHT, pkt packet) {
if len(dht.workerTokens) == dht.PacketWorkerLimit {
return
}
dht.workerTokens <- struct{}{}
go func() {
defer func() {
<-dht.workerTokens
}()
if dht.blackList.in(pkt.raddr.IP.String(), pkt.raddr.Port) {
return
}
data, err := Decode(pkt.data)
if err != nil {
return
}
response, err := parseMessage(data)
if err != nil {
return
}
if f, ok := handlers[response["y"].(string)]; ok {
f(dht, pkt.raddr, response)
}
}()
} | go | func handle(dht *DHT, pkt packet) {
if len(dht.workerTokens) == dht.PacketWorkerLimit {
return
}
dht.workerTokens <- struct{}{}
go func() {
defer func() {
<-dht.workerTokens
}()
if dht.blackList.in(pkt.raddr.IP.String(), pkt.raddr.Port) {
return
}
data, err := Decode(pkt.data)
if err != nil {
return
}
response, err := parseMessage(data)
if err != nil {
return
}
if f, ok := handlers[response["y"].(string)]; ok {
f(dht, pkt.raddr, response)
}
}()
} | [
"func",
"handle",
"(",
"dht",
"*",
"DHT",
",",
"pkt",
"packet",
")",
"{",
"if",
"len",
"(",
"dht",
".",
"workerTokens",
")",
"==",
"dht",
".",
"PacketWorkerLimit",
"{",
"return",
"\n",
"}",
"\n",
"dht",
".",
"workerTokens",
"<-",
"struct",
"{",
"}",
... | // handle handles packets received from udp. | [
"handle",
"handles",
"packets",
"received",
"from",
"udp",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/krpc.go#L755-L785 | train |
shiyanhui/dht | util.go | randomString | func randomString(size int) string {
buff := make([]byte, size)
rand.Read(buff)
return string(buff)
} | go | func randomString(size int) string {
buff := make([]byte, size)
rand.Read(buff)
return string(buff)
} | [
"func",
"randomString",
"(",
"size",
"int",
")",
"string",
"{",
"buff",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"size",
")",
"\n",
"rand",
".",
"Read",
"(",
"buff",
")",
"\n",
"return",
"string",
"(",
"buff",
")",
"\n",
"}"
] | // randomString generates a size-length string randomly. | [
"randomString",
"generates",
"a",
"size",
"-",
"length",
"string",
"randomly",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/util.go#L15-L19 | train |
shiyanhui/dht | util.go | bytes2int | func bytes2int(data []byte) uint64 {
n, val := len(data), uint64(0)
if n > 8 {
panic("data too long")
}
for i, b := range data {
val += uint64(b) << uint64((n-i-1)*8)
}
return val
} | go | func bytes2int(data []byte) uint64 {
n, val := len(data), uint64(0)
if n > 8 {
panic("data too long")
}
for i, b := range data {
val += uint64(b) << uint64((n-i-1)*8)
}
return val
} | [
"func",
"bytes2int",
"(",
"data",
"[",
"]",
"byte",
")",
"uint64",
"{",
"n",
",",
"val",
":=",
"len",
"(",
"data",
")",
",",
"uint64",
"(",
"0",
")",
"\n",
"if",
"n",
">",
"8",
"{",
"panic",
"(",
"\"data too long\"",
")",
"\n",
"}",
"\n",
"for"... | // bytes2int returns the int value it represents. | [
"bytes2int",
"returns",
"the",
"int",
"value",
"it",
"represents",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/util.go#L22-L32 | train |
shiyanhui/dht | util.go | int2bytes | func int2bytes(val uint64) []byte {
data, j := make([]byte, 8), -1
for i := 0; i < 8; i++ {
shift := uint64((7 - i) * 8)
data[i] = byte((val & (0xff << shift)) >> shift)
if j == -1 && data[i] != 0 {
j = i
}
}
if j != -1 {
return data[j:]
}
return data[:1]
} | go | func int2bytes(val uint64) []byte {
data, j := make([]byte, 8), -1
for i := 0; i < 8; i++ {
shift := uint64((7 - i) * 8)
data[i] = byte((val & (0xff << shift)) >> shift)
if j == -1 && data[i] != 0 {
j = i
}
}
if j != -1 {
return data[j:]
}
return data[:1]
} | [
"func",
"int2bytes",
"(",
"val",
"uint64",
")",
"[",
"]",
"byte",
"{",
"data",
",",
"j",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"8",
")",
",",
"-",
"1",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"8",
";",
"i",
"++",
"{",
"shift",
":=... | // int2bytes returns the byte array it represents. | [
"int2bytes",
"returns",
"the",
"byte",
"array",
"it",
"represents",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/util.go#L35-L50 | train |
shiyanhui/dht | util.go | getLocalIPs | func getLocalIPs() (ips []string) {
ips = make([]string, 0, 6)
addrs, err := net.InterfaceAddrs()
if err != nil {
return
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
ips = append(ips, ip.String())
}
return
} | go | func getLocalIPs() (ips []string) {
ips = make([]string, 0, 6)
addrs, err := net.InterfaceAddrs()
if err != nil {
return
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
ips = append(ips, ip.String())
}
return
} | [
"func",
"getLocalIPs",
"(",
")",
"(",
"ips",
"[",
"]",
"string",
")",
"{",
"ips",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"6",
")",
"\n",
"addrs",
",",
"err",
":=",
"net",
".",
"InterfaceAddrs",
"(",
")",
"\n",
"if",
"err",
"!=",
... | // getLocalIPs returns local ips. | [
"getLocalIPs",
"returns",
"local",
"ips",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/util.go#L85-L101 | train |
shiyanhui/dht | util.go | getRemoteIP | func getRemoteIP() (ip string, err error) {
client := &http.Client{
Timeout: time.Second * 30,
}
req, err := http.NewRequest("GET", "http://ifconfig.me", nil)
if err != nil {
return
}
req.Header.Set("User-Agent", "curl")
res, err := client.Do(req)
if err != nil {
return
}
defer res.Body.Close()
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
ip = string(data)
return
} | go | func getRemoteIP() (ip string, err error) {
client := &http.Client{
Timeout: time.Second * 30,
}
req, err := http.NewRequest("GET", "http://ifconfig.me", nil)
if err != nil {
return
}
req.Header.Set("User-Agent", "curl")
res, err := client.Do(req)
if err != nil {
return
}
defer res.Body.Close()
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
ip = string(data)
return
} | [
"func",
"getRemoteIP",
"(",
")",
"(",
"ip",
"string",
",",
"err",
"error",
")",
"{",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"Timeout",
":",
"time",
".",
"Second",
"*",
"30",
",",
"}",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequ... | // getRemoteIP returns the wlan ip. | [
"getRemoteIP",
"returns",
"the",
"wlan",
"ip",
"."
] | 1b3b78ecf279a28409577382c3ae95df5703cf50 | https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/util.go#L104-L129 | train |
oklog/ulid | ulid.go | New | func New(ms uint64, entropy io.Reader) (id ULID, err error) {
if err = id.SetTime(ms); err != nil {
return id, err
}
switch e := entropy.(type) {
case nil:
return id, err
case MonotonicReader:
err = e.MonotonicRead(ms, id[6:])
default:
_, err = io.ReadFull(e, id[6:])
}
return id, err
} | go | func New(ms uint64, entropy io.Reader) (id ULID, err error) {
if err = id.SetTime(ms); err != nil {
return id, err
}
switch e := entropy.(type) {
case nil:
return id, err
case MonotonicReader:
err = e.MonotonicRead(ms, id[6:])
default:
_, err = io.ReadFull(e, id[6:])
}
return id, err
} | [
"func",
"New",
"(",
"ms",
"uint64",
",",
"entropy",
"io",
".",
"Reader",
")",
"(",
"id",
"ULID",
",",
"err",
"error",
")",
"{",
"if",
"err",
"=",
"id",
".",
"SetTime",
"(",
"ms",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"id",
",",
"err",
... | // New returns an ULID with the given Unix milliseconds timestamp and an
// optional entropy source. Use the Timestamp function to convert
// a time.Time to Unix milliseconds.
//
// ErrBigTime is returned when passing a timestamp bigger than MaxTime.
// Reading from the entropy source may also return an error.
//
// Safety for concurrent use is only dependent on the safety of the
// entropy source. | [
"New",
"returns",
"an",
"ULID",
"with",
"the",
"given",
"Unix",
"milliseconds",
"timestamp",
"and",
"an",
"optional",
"entropy",
"source",
".",
"Use",
"the",
"Timestamp",
"function",
"to",
"convert",
"a",
"time",
".",
"Time",
"to",
"Unix",
"milliseconds",
".... | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L97-L112 | train |
oklog/ulid | ulid.go | MustNew | func MustNew(ms uint64, entropy io.Reader) ULID {
id, err := New(ms, entropy)
if err != nil {
panic(err)
}
return id
} | go | func MustNew(ms uint64, entropy io.Reader) ULID {
id, err := New(ms, entropy)
if err != nil {
panic(err)
}
return id
} | [
"func",
"MustNew",
"(",
"ms",
"uint64",
",",
"entropy",
"io",
".",
"Reader",
")",
"ULID",
"{",
"id",
",",
"err",
":=",
"New",
"(",
"ms",
",",
"entropy",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"retur... | // MustNew is a convenience function equivalent to New that panics on failure
// instead of returning an error. | [
"MustNew",
"is",
"a",
"convenience",
"function",
"equivalent",
"to",
"New",
"that",
"panics",
"on",
"failure",
"instead",
"of",
"returning",
"an",
"error",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L116-L122 | train |
oklog/ulid | ulid.go | MustParse | func MustParse(ulid string) ULID {
id, err := Parse(ulid)
if err != nil {
panic(err)
}
return id
} | go | func MustParse(ulid string) ULID {
id, err := Parse(ulid)
if err != nil {
panic(err)
}
return id
} | [
"func",
"MustParse",
"(",
"ulid",
"string",
")",
"ULID",
"{",
"id",
",",
"err",
":=",
"Parse",
"(",
"ulid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"id",
"\n",
"}"
] | // MustParse is a convenience function equivalent to Parse that panics on failure
// instead of returning an error. | [
"MustParse",
"is",
"a",
"convenience",
"function",
"equivalent",
"to",
"Parse",
"that",
"panics",
"on",
"failure",
"instead",
"of",
"returning",
"an",
"error",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L219-L225 | train |
oklog/ulid | ulid.go | MustParseStrict | func MustParseStrict(ulid string) ULID {
id, err := ParseStrict(ulid)
if err != nil {
panic(err)
}
return id
} | go | func MustParseStrict(ulid string) ULID {
id, err := ParseStrict(ulid)
if err != nil {
panic(err)
}
return id
} | [
"func",
"MustParseStrict",
"(",
"ulid",
"string",
")",
"ULID",
"{",
"id",
",",
"err",
":=",
"ParseStrict",
"(",
"ulid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"id",
"\n",
"}"
] | // MustParseStrict is a convenience function equivalent to ParseStrict that
// panics on failure instead of returning an error. | [
"MustParseStrict",
"is",
"a",
"convenience",
"function",
"equivalent",
"to",
"ParseStrict",
"that",
"panics",
"on",
"failure",
"instead",
"of",
"returning",
"an",
"error",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L229-L235 | train |
oklog/ulid | ulid.go | MarshalBinary | func (id ULID) MarshalBinary() ([]byte, error) {
ulid := make([]byte, len(id))
return ulid, id.MarshalBinaryTo(ulid)
} | go | func (id ULID) MarshalBinary() ([]byte, error) {
ulid := make([]byte, len(id))
return ulid, id.MarshalBinaryTo(ulid)
} | [
"func",
"(",
"id",
"ULID",
")",
"MarshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"ulid",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"id",
")",
")",
"\n",
"return",
"ulid",
",",
"id",
".",
"MarshalBinaryTo",
"... | // MarshalBinary implements the encoding.BinaryMarshaler interface by
// returning the ULID as a byte slice. | [
"MarshalBinary",
"implements",
"the",
"encoding",
".",
"BinaryMarshaler",
"interface",
"by",
"returning",
"the",
"ULID",
"as",
"a",
"byte",
"slice",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L248-L251 | train |
oklog/ulid | ulid.go | UnmarshalBinary | func (id *ULID) UnmarshalBinary(data []byte) error {
if len(data) != len(*id) {
return ErrDataSize
}
copy((*id)[:], data)
return nil
} | go | func (id *ULID) UnmarshalBinary(data []byte) error {
if len(data) != len(*id) {
return ErrDataSize
}
copy((*id)[:], data)
return nil
} | [
"func",
"(",
"id",
"*",
"ULID",
")",
"UnmarshalBinary",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"len",
"(",
"data",
")",
"!=",
"len",
"(",
"*",
"id",
")",
"{",
"return",
"ErrDataSize",
"\n",
"}",
"\n",
"copy",
"(",
"(",
"*",
"id... | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface by
// copying the passed data and converting it to an ULID. ErrDataSize is
// returned if the data length is different from ULID length. | [
"UnmarshalBinary",
"implements",
"the",
"encoding",
".",
"BinaryUnmarshaler",
"interface",
"by",
"copying",
"the",
"passed",
"data",
"and",
"converting",
"it",
"to",
"an",
"ULID",
".",
"ErrDataSize",
"is",
"returned",
"if",
"the",
"data",
"length",
"is",
"differ... | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L267-L274 | train |
oklog/ulid | ulid.go | MarshalText | func (id ULID) MarshalText() ([]byte, error) {
ulid := make([]byte, EncodedSize)
return ulid, id.MarshalTextTo(ulid)
} | go | func (id ULID) MarshalText() ([]byte, error) {
ulid := make([]byte, EncodedSize)
return ulid, id.MarshalTextTo(ulid)
} | [
"func",
"(",
"id",
"ULID",
")",
"MarshalText",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"ulid",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"EncodedSize",
")",
"\n",
"return",
"ulid",
",",
"id",
".",
"MarshalTextTo",
"(",
"ulid",
")... | // MarshalText implements the encoding.TextMarshaler interface by
// returning the string encoded ULID. | [
"MarshalText",
"implements",
"the",
"encoding",
".",
"TextMarshaler",
"interface",
"by",
"returning",
"the",
"string",
"encoded",
"ULID",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L281-L284 | train |
oklog/ulid | ulid.go | Time | func (id ULID) Time() uint64 {
return uint64(id[5]) | uint64(id[4])<<8 |
uint64(id[3])<<16 | uint64(id[2])<<24 |
uint64(id[1])<<32 | uint64(id[0])<<40
} | go | func (id ULID) Time() uint64 {
return uint64(id[5]) | uint64(id[4])<<8 |
uint64(id[3])<<16 | uint64(id[2])<<24 |
uint64(id[1])<<32 | uint64(id[0])<<40
} | [
"func",
"(",
"id",
"ULID",
")",
"Time",
"(",
")",
"uint64",
"{",
"return",
"uint64",
"(",
"id",
"[",
"5",
"]",
")",
"|",
"uint64",
"(",
"id",
"[",
"4",
"]",
")",
"<<",
"8",
"|",
"uint64",
"(",
"id",
"[",
"3",
"]",
")",
"<<",
"16",
"|",
"u... | // Time returns the Unix time in milliseconds encoded in the ULID.
// Use the top level Time function to convert the returned value to
// a time.Time. | [
"Time",
"returns",
"the",
"Unix",
"time",
"in",
"milliseconds",
"encoded",
"in",
"the",
"ULID",
".",
"Use",
"the",
"top",
"level",
"Time",
"function",
"to",
"convert",
"the",
"returned",
"value",
"to",
"a",
"time",
".",
"Time",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L375-L379 | train |
oklog/ulid | ulid.go | Timestamp | func Timestamp(t time.Time) uint64 {
return uint64(t.Unix())*1000 +
uint64(t.Nanosecond()/int(time.Millisecond))
} | go | func Timestamp(t time.Time) uint64 {
return uint64(t.Unix())*1000 +
uint64(t.Nanosecond()/int(time.Millisecond))
} | [
"func",
"Timestamp",
"(",
"t",
"time",
".",
"Time",
")",
"uint64",
"{",
"return",
"uint64",
"(",
"t",
".",
"Unix",
"(",
")",
")",
"*",
"1000",
"+",
"uint64",
"(",
"t",
".",
"Nanosecond",
"(",
")",
"/",
"int",
"(",
"time",
".",
"Millisecond",
")",... | // Timestamp converts a time.Time to Unix milliseconds.
//
// Because of the way ULID stores time, times from the year
// 10889 produces undefined results. | [
"Timestamp",
"converts",
"a",
"time",
".",
"Time",
"to",
"Unix",
"milliseconds",
".",
"Because",
"of",
"the",
"way",
"ULID",
"stores",
"time",
"times",
"from",
"the",
"year",
"10889",
"produces",
"undefined",
"results",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L398-L401 | train |
oklog/ulid | ulid.go | Time | func Time(ms uint64) time.Time {
s := int64(ms / 1e3)
ns := int64((ms % 1e3) * 1e6)
return time.Unix(s, ns)
} | go | func Time(ms uint64) time.Time {
s := int64(ms / 1e3)
ns := int64((ms % 1e3) * 1e6)
return time.Unix(s, ns)
} | [
"func",
"Time",
"(",
"ms",
"uint64",
")",
"time",
".",
"Time",
"{",
"s",
":=",
"int64",
"(",
"ms",
"/",
"1e3",
")",
"\n",
"ns",
":=",
"int64",
"(",
"(",
"ms",
"%",
"1e3",
")",
"*",
"1e6",
")",
"\n",
"return",
"time",
".",
"Unix",
"(",
"s",
... | // Time converts Unix milliseconds in the format
// returned by the Timestamp function to a time.Time. | [
"Time",
"converts",
"Unix",
"milliseconds",
"in",
"the",
"format",
"returned",
"by",
"the",
"Timestamp",
"function",
"to",
"a",
"time",
".",
"Time",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L405-L409 | train |
oklog/ulid | ulid.go | SetTime | func (id *ULID) SetTime(ms uint64) error {
if ms > maxTime {
return ErrBigTime
}
(*id)[0] = byte(ms >> 40)
(*id)[1] = byte(ms >> 32)
(*id)[2] = byte(ms >> 24)
(*id)[3] = byte(ms >> 16)
(*id)[4] = byte(ms >> 8)
(*id)[5] = byte(ms)
return nil
} | go | func (id *ULID) SetTime(ms uint64) error {
if ms > maxTime {
return ErrBigTime
}
(*id)[0] = byte(ms >> 40)
(*id)[1] = byte(ms >> 32)
(*id)[2] = byte(ms >> 24)
(*id)[3] = byte(ms >> 16)
(*id)[4] = byte(ms >> 8)
(*id)[5] = byte(ms)
return nil
} | [
"func",
"(",
"id",
"*",
"ULID",
")",
"SetTime",
"(",
"ms",
"uint64",
")",
"error",
"{",
"if",
"ms",
">",
"maxTime",
"{",
"return",
"ErrBigTime",
"\n",
"}",
"\n",
"(",
"*",
"id",
")",
"[",
"0",
"]",
"=",
"byte",
"(",
"ms",
">>",
"40",
")",
"\n... | // SetTime sets the time component of the ULID to the given Unix time
// in milliseconds. | [
"SetTime",
"sets",
"the",
"time",
"component",
"of",
"the",
"ULID",
"to",
"the",
"given",
"Unix",
"time",
"in",
"milliseconds",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L413-L426 | train |
oklog/ulid | ulid.go | Entropy | func (id ULID) Entropy() []byte {
e := make([]byte, 10)
copy(e, id[6:])
return e
} | go | func (id ULID) Entropy() []byte {
e := make([]byte, 10)
copy(e, id[6:])
return e
} | [
"func",
"(",
"id",
"ULID",
")",
"Entropy",
"(",
")",
"[",
"]",
"byte",
"{",
"e",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"10",
")",
"\n",
"copy",
"(",
"e",
",",
"id",
"[",
"6",
":",
"]",
")",
"\n",
"return",
"e",
"\n",
"}"
] | // Entropy returns the entropy from the ULID. | [
"Entropy",
"returns",
"the",
"entropy",
"from",
"the",
"ULID",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L429-L433 | train |
oklog/ulid | ulid.go | Scan | func (id *ULID) Scan(src interface{}) error {
switch x := src.(type) {
case nil:
return nil
case string:
return id.UnmarshalText([]byte(x))
case []byte:
return id.UnmarshalBinary(x)
}
return ErrScanValue
} | go | func (id *ULID) Scan(src interface{}) error {
switch x := src.(type) {
case nil:
return nil
case string:
return id.UnmarshalText([]byte(x))
case []byte:
return id.UnmarshalBinary(x)
}
return ErrScanValue
} | [
"func",
"(",
"id",
"*",
"ULID",
")",
"Scan",
"(",
"src",
"interface",
"{",
"}",
")",
"error",
"{",
"switch",
"x",
":=",
"src",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"return",
"nil",
"\n",
"case",
"string",
":",
"return",
"id",
".",
"U... | // Scan implements the sql.Scanner interface. It supports scanning
// a string or byte slice. | [
"Scan",
"implements",
"the",
"sql",
".",
"Scanner",
"interface",
".",
"It",
"supports",
"scanning",
"a",
"string",
"or",
"byte",
"slice",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L454-L465 | train |
oklog/ulid | ulid.go | MonotonicRead | func (m *MonotonicEntropy) MonotonicRead(ms uint64, entropy []byte) (err error) {
if !m.entropy.IsZero() && m.ms == ms {
err = m.increment()
m.entropy.AppendTo(entropy)
} else if _, err = io.ReadFull(m.Reader, entropy); err == nil {
m.ms = ms
m.entropy.SetBytes(entropy)
}
return err
} | go | func (m *MonotonicEntropy) MonotonicRead(ms uint64, entropy []byte) (err error) {
if !m.entropy.IsZero() && m.ms == ms {
err = m.increment()
m.entropy.AppendTo(entropy)
} else if _, err = io.ReadFull(m.Reader, entropy); err == nil {
m.ms = ms
m.entropy.SetBytes(entropy)
}
return err
} | [
"func",
"(",
"m",
"*",
"MonotonicEntropy",
")",
"MonotonicRead",
"(",
"ms",
"uint64",
",",
"entropy",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"if",
"!",
"m",
".",
"entropy",
".",
"IsZero",
"(",
")",
"&&",
"m",
".",
"ms",
"==",
"ms",... | // MonotonicRead implements the MonotonicReader interface. | [
"MonotonicRead",
"implements",
"the",
"MonotonicReader",
"interface",
"."
] | bacfb41fdd06edf5294635d18ec387dee671a964 | https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L528-L537 | train |
olekukonko/tablewriter | table.go | NewWriter | func NewWriter(writer io.Writer) *Table {
t := &Table{
out: writer,
rows: [][]string{},
lines: [][][]string{},
cs: make(map[int]int),
rs: make(map[int]int),
headers: [][]string{},
footers: [][]string{},
caption: false,
captionText: "Table caption.",
autoFmt: true,
autoWrap: true,
reflowText: true,
mW: MAX_ROW_WIDTH,
pCenter: CENTER,
pRow: ROW,
pColumn: COLUMN,
tColumn: -1,
tRow: -1,
hAlign: ALIGN_DEFAULT,
fAlign: ALIGN_DEFAULT,
align: ALIGN_DEFAULT,
newLine: NEWLINE,
rowLine: false,
hdrLine: true,
borders: Border{Left: true, Right: true, Bottom: true, Top: true},
colSize: -1,
headerParams: []string{},
columnsParams: []string{},
footerParams: []string{},
columnsAlign: []int{}}
return t
} | go | func NewWriter(writer io.Writer) *Table {
t := &Table{
out: writer,
rows: [][]string{},
lines: [][][]string{},
cs: make(map[int]int),
rs: make(map[int]int),
headers: [][]string{},
footers: [][]string{},
caption: false,
captionText: "Table caption.",
autoFmt: true,
autoWrap: true,
reflowText: true,
mW: MAX_ROW_WIDTH,
pCenter: CENTER,
pRow: ROW,
pColumn: COLUMN,
tColumn: -1,
tRow: -1,
hAlign: ALIGN_DEFAULT,
fAlign: ALIGN_DEFAULT,
align: ALIGN_DEFAULT,
newLine: NEWLINE,
rowLine: false,
hdrLine: true,
borders: Border{Left: true, Right: true, Bottom: true, Top: true},
colSize: -1,
headerParams: []string{},
columnsParams: []string{},
footerParams: []string{},
columnsAlign: []int{}}
return t
} | [
"func",
"NewWriter",
"(",
"writer",
"io",
".",
"Writer",
")",
"*",
"Table",
"{",
"t",
":=",
"&",
"Table",
"{",
"out",
":",
"writer",
",",
"rows",
":",
"[",
"]",
"[",
"]",
"string",
"{",
"}",
",",
"lines",
":",
"[",
"]",
"[",
"]",
"[",
"]",
... | // Start New Table
// Take io.Writer Directly | [
"Start",
"New",
"Table",
"Take",
"io",
".",
"Writer",
"Directly"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L86-L119 | train |
olekukonko/tablewriter | table.go | Render | func (t *Table) Render() {
if t.borders.Top {
t.printLine(true)
}
t.printHeading()
if t.autoMergeCells {
t.printRowsMergeCells()
} else {
t.printRows()
}
if !t.rowLine && t.borders.Bottom {
t.printLine(true)
}
t.printFooter()
if t.caption {
t.printCaption()
}
} | go | func (t *Table) Render() {
if t.borders.Top {
t.printLine(true)
}
t.printHeading()
if t.autoMergeCells {
t.printRowsMergeCells()
} else {
t.printRows()
}
if !t.rowLine && t.borders.Bottom {
t.printLine(true)
}
t.printFooter()
if t.caption {
t.printCaption()
}
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"Render",
"(",
")",
"{",
"if",
"t",
".",
"borders",
".",
"Top",
"{",
"t",
".",
"printLine",
"(",
"true",
")",
"\n",
"}",
"\n",
"t",
".",
"printHeading",
"(",
")",
"\n",
"if",
"t",
".",
"autoMergeCells",
"{",... | // Render table output | [
"Render",
"table",
"output"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L122-L140 | train |
olekukonko/tablewriter | table.go | SetHeader | func (t *Table) SetHeader(keys []string) {
t.colSize = len(keys)
for i, v := range keys {
lines := t.parseDimension(v, i, headerRowIdx)
t.headers = append(t.headers, lines)
}
} | go | func (t *Table) SetHeader(keys []string) {
t.colSize = len(keys)
for i, v := range keys {
lines := t.parseDimension(v, i, headerRowIdx)
t.headers = append(t.headers, lines)
}
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"SetHeader",
"(",
"keys",
"[",
"]",
"string",
")",
"{",
"t",
".",
"colSize",
"=",
"len",
"(",
"keys",
")",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"keys",
"{",
"lines",
":=",
"t",
".",
"parseDimension",
"... | // Set table header | [
"Set",
"table",
"header"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L148-L154 | train |
olekukonko/tablewriter | table.go | SetFooter | func (t *Table) SetFooter(keys []string) {
//t.colSize = len(keys)
for i, v := range keys {
lines := t.parseDimension(v, i, footerRowIdx)
t.footers = append(t.footers, lines)
}
} | go | func (t *Table) SetFooter(keys []string) {
//t.colSize = len(keys)
for i, v := range keys {
lines := t.parseDimension(v, i, footerRowIdx)
t.footers = append(t.footers, lines)
}
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"SetFooter",
"(",
"keys",
"[",
"]",
"string",
")",
"{",
"for",
"i",
",",
"v",
":=",
"range",
"keys",
"{",
"lines",
":=",
"t",
".",
"parseDimension",
"(",
"v",
",",
"i",
",",
"footerRowIdx",
")",
"\n",
"t",
"... | // Set table Footer | [
"Set",
"table",
"Footer"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L157-L163 | train |
olekukonko/tablewriter | table.go | SetCaption | func (t *Table) SetCaption(caption bool, captionText ...string) {
t.caption = caption
if len(captionText) == 1 {
t.captionText = captionText[0]
}
} | go | func (t *Table) SetCaption(caption bool, captionText ...string) {
t.caption = caption
if len(captionText) == 1 {
t.captionText = captionText[0]
}
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"SetCaption",
"(",
"caption",
"bool",
",",
"captionText",
"...",
"string",
")",
"{",
"t",
".",
"caption",
"=",
"caption",
"\n",
"if",
"len",
"(",
"captionText",
")",
"==",
"1",
"{",
"t",
".",
"captionText",
"=",
... | // Set table Caption | [
"Set",
"table",
"Caption"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L166-L171 | train |
olekukonko/tablewriter | table.go | SetColMinWidth | func (t *Table) SetColMinWidth(column int, width int) {
t.cs[column] = width
} | go | func (t *Table) SetColMinWidth(column int, width int) {
t.cs[column] = width
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"SetColMinWidth",
"(",
"column",
"int",
",",
"width",
"int",
")",
"{",
"t",
".",
"cs",
"[",
"column",
"]",
"=",
"width",
"\n",
"}"
] | // Set the minimal width for a column | [
"Set",
"the",
"minimal",
"width",
"for",
"a",
"column"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L194-L196 | train |
olekukonko/tablewriter | table.go | Append | func (t *Table) Append(row []string) {
rowSize := len(t.headers)
if rowSize > t.colSize {
t.colSize = rowSize
}
n := len(t.lines)
line := [][]string{}
for i, v := range row {
// Detect string width
// Detect String height
// Break strings into words
out := t.parseDimension(v, i, n)
// Append broken words
line = append(line, out)
}
t.lines = append(t.lines, line)
} | go | func (t *Table) Append(row []string) {
rowSize := len(t.headers)
if rowSize > t.colSize {
t.colSize = rowSize
}
n := len(t.lines)
line := [][]string{}
for i, v := range row {
// Detect string width
// Detect String height
// Break strings into words
out := t.parseDimension(v, i, n)
// Append broken words
line = append(line, out)
}
t.lines = append(t.lines, line)
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"Append",
"(",
"row",
"[",
"]",
"string",
")",
"{",
"rowSize",
":=",
"len",
"(",
"t",
".",
"headers",
")",
"\n",
"if",
"rowSize",
">",
"t",
".",
"colSize",
"{",
"t",
".",
"colSize",
"=",
"rowSize",
"\n",
"}"... | // Append row to table | [
"Append",
"row",
"to",
"table"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L278-L297 | train |
olekukonko/tablewriter | table.go | AppendBulk | func (t *Table) AppendBulk(rows [][]string) {
for _, row := range rows {
t.Append(row)
}
} | go | func (t *Table) AppendBulk(rows [][]string) {
for _, row := range rows {
t.Append(row)
}
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"AppendBulk",
"(",
"rows",
"[",
"]",
"[",
"]",
"string",
")",
"{",
"for",
"_",
",",
"row",
":=",
"range",
"rows",
"{",
"t",
".",
"Append",
"(",
"row",
")",
"\n",
"}",
"\n",
"}"
] | // Allow Support for Bulk Append
// Eliminates repeated for loops | [
"Allow",
"Support",
"for",
"Bulk",
"Append",
"Eliminates",
"repeated",
"for",
"loops"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L301-L305 | train |
olekukonko/tablewriter | table.go | center | func (t *Table) center(i int) string {
if i == -1 && !t.borders.Left {
return t.pRow
}
if i == len(t.cs)-1 && !t.borders.Right {
return t.pRow
}
return t.pCenter
} | go | func (t *Table) center(i int) string {
if i == -1 && !t.borders.Left {
return t.pRow
}
if i == len(t.cs)-1 && !t.borders.Right {
return t.pRow
}
return t.pCenter
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"center",
"(",
"i",
"int",
")",
"string",
"{",
"if",
"i",
"==",
"-",
"1",
"&&",
"!",
"t",
".",
"borders",
".",
"Left",
"{",
"return",
"t",
".",
"pRow",
"\n",
"}",
"\n",
"if",
"i",
"==",
"len",
"(",
"t",
... | // Center based on position and border. | [
"Center",
"based",
"on",
"position",
"and",
"border",
"."
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L323-L333 | train |
olekukonko/tablewriter | table.go | printLine | func (t *Table) printLine(nl bool) {
fmt.Fprint(t.out, t.center(-1))
for i := 0; i < len(t.cs); i++ {
v := t.cs[i]
fmt.Fprintf(t.out, "%s%s%s%s",
t.pRow,
strings.Repeat(string(t.pRow), v),
t.pRow,
t.center(i))
}
if nl {
fmt.Fprint(t.out, t.newLine)
}
} | go | func (t *Table) printLine(nl bool) {
fmt.Fprint(t.out, t.center(-1))
for i := 0; i < len(t.cs); i++ {
v := t.cs[i]
fmt.Fprintf(t.out, "%s%s%s%s",
t.pRow,
strings.Repeat(string(t.pRow), v),
t.pRow,
t.center(i))
}
if nl {
fmt.Fprint(t.out, t.newLine)
}
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"printLine",
"(",
"nl",
"bool",
")",
"{",
"fmt",
".",
"Fprint",
"(",
"t",
".",
"out",
",",
"t",
".",
"center",
"(",
"-",
"1",
")",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"t",
".",... | // Print line based on row width | [
"Print",
"line",
"based",
"on",
"row",
"width"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L336-L349 | train |
olekukonko/tablewriter | table.go | printLineOptionalCellSeparators | func (t *Table) printLineOptionalCellSeparators(nl bool, displayCellSeparator []bool) {
fmt.Fprint(t.out, t.pCenter)
for i := 0; i < len(t.cs); i++ {
v := t.cs[i]
if i > len(displayCellSeparator) || displayCellSeparator[i] {
// Display the cell separator
fmt.Fprintf(t.out, "%s%s%s%s",
t.pRow,
strings.Repeat(string(t.pRow), v),
t.pRow,
t.pCenter)
} else {
// Don't display the cell separator for this cell
fmt.Fprintf(t.out, "%s%s",
strings.Repeat(" ", v+2),
t.pCenter)
}
}
if nl {
fmt.Fprint(t.out, t.newLine)
}
} | go | func (t *Table) printLineOptionalCellSeparators(nl bool, displayCellSeparator []bool) {
fmt.Fprint(t.out, t.pCenter)
for i := 0; i < len(t.cs); i++ {
v := t.cs[i]
if i > len(displayCellSeparator) || displayCellSeparator[i] {
// Display the cell separator
fmt.Fprintf(t.out, "%s%s%s%s",
t.pRow,
strings.Repeat(string(t.pRow), v),
t.pRow,
t.pCenter)
} else {
// Don't display the cell separator for this cell
fmt.Fprintf(t.out, "%s%s",
strings.Repeat(" ", v+2),
t.pCenter)
}
}
if nl {
fmt.Fprint(t.out, t.newLine)
}
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"printLineOptionalCellSeparators",
"(",
"nl",
"bool",
",",
"displayCellSeparator",
"[",
"]",
"bool",
")",
"{",
"fmt",
".",
"Fprint",
"(",
"t",
".",
"out",
",",
"t",
".",
"pCenter",
")",
"\n",
"for",
"i",
":=",
"0"... | // Print line based on row width with our without cell separator | [
"Print",
"line",
"based",
"on",
"row",
"width",
"with",
"our",
"without",
"cell",
"separator"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L352-L373 | train |
olekukonko/tablewriter | table.go | pad | func pad(align int) func(string, string, int) string {
padFunc := Pad
switch align {
case ALIGN_LEFT:
padFunc = PadRight
case ALIGN_RIGHT:
padFunc = PadLeft
}
return padFunc
} | go | func pad(align int) func(string, string, int) string {
padFunc := Pad
switch align {
case ALIGN_LEFT:
padFunc = PadRight
case ALIGN_RIGHT:
padFunc = PadLeft
}
return padFunc
} | [
"func",
"pad",
"(",
"align",
"int",
")",
"func",
"(",
"string",
",",
"string",
",",
"int",
")",
"string",
"{",
"padFunc",
":=",
"Pad",
"\n",
"switch",
"align",
"{",
"case",
"ALIGN_LEFT",
":",
"padFunc",
"=",
"PadRight",
"\n",
"case",
"ALIGN_RIGHT",
":"... | // Return the PadRight function if align is left, PadLeft if align is right,
// and Pad by default | [
"Return",
"the",
"PadRight",
"function",
"if",
"align",
"is",
"left",
"PadLeft",
"if",
"align",
"is",
"right",
"and",
"Pad",
"by",
"default"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L377-L386 | train |
olekukonko/tablewriter | table.go | printCaption | func (t Table) printCaption() {
width := t.getTableWidth()
paragraph, _ := WrapString(t.captionText, width)
for linecount := 0; linecount < len(paragraph); linecount++ {
fmt.Fprintln(t.out, paragraph[linecount])
}
} | go | func (t Table) printCaption() {
width := t.getTableWidth()
paragraph, _ := WrapString(t.captionText, width)
for linecount := 0; linecount < len(paragraph); linecount++ {
fmt.Fprintln(t.out, paragraph[linecount])
}
} | [
"func",
"(",
"t",
"Table",
")",
"printCaption",
"(",
")",
"{",
"width",
":=",
"t",
".",
"getTableWidth",
"(",
")",
"\n",
"paragraph",
",",
"_",
":=",
"WrapString",
"(",
"t",
".",
"captionText",
",",
"width",
")",
"\n",
"for",
"linecount",
":=",
"0",
... | // Print caption text | [
"Print",
"caption",
"text"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L580-L586 | train |
olekukonko/tablewriter | table.go | getTableWidth | func (t Table) getTableWidth() int {
var chars int
for _, v := range t.cs {
chars += v
}
// Add chars, spaces, seperators to calculate the total width of the table.
// ncols := t.colSize
// spaces := ncols * 2
// seps := ncols + 1
return (chars + (3 * t.colSize) + 2)
} | go | func (t Table) getTableWidth() int {
var chars int
for _, v := range t.cs {
chars += v
}
// Add chars, spaces, seperators to calculate the total width of the table.
// ncols := t.colSize
// spaces := ncols * 2
// seps := ncols + 1
return (chars + (3 * t.colSize) + 2)
} | [
"func",
"(",
"t",
"Table",
")",
"getTableWidth",
"(",
")",
"int",
"{",
"var",
"chars",
"int",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"t",
".",
"cs",
"{",
"chars",
"+=",
"v",
"\n",
"}",
"\n",
"return",
"(",
"chars",
"+",
"(",
"3",
"*",
"t"... | // Calculate the total number of characters in a row | [
"Calculate",
"the",
"total",
"number",
"of",
"characters",
"in",
"a",
"row"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L589-L601 | train |
olekukonko/tablewriter | table.go | printRow | func (t *Table) printRow(columns [][]string, rowIdx int) {
// Get Maximum Height
max := t.rs[rowIdx]
total := len(columns)
// TODO Fix uneven col size
// if total < t.colSize {
// for n := t.colSize - total; n < t.colSize ; n++ {
// columns = append(columns, []string{SPACE})
// t.cs[n] = t.mW
// }
//}
// Pad Each Height
pads := []int{}
// Checking for ANSI escape sequences for columns
is_esc_seq := false
if len(t.columnsParams) > 0 {
is_esc_seq = true
}
t.fillAlignment(total)
for i, line := range columns {
length := len(line)
pad := max - length
pads = append(pads, pad)
for n := 0; n < pad; n++ {
columns[i] = append(columns[i], " ")
}
}
//fmt.Println(max, "\n")
for x := 0; x < max; x++ {
for y := 0; y < total; y++ {
// Check if border is set
fmt.Fprint(t.out, ConditionString((!t.borders.Left && y == 0), SPACE, t.pColumn))
fmt.Fprintf(t.out, SPACE)
str := columns[y][x]
// Embedding escape sequence with column value
if is_esc_seq {
str = format(str, t.columnsParams[y])
}
// This would print alignment
// Default alignment would use multiple configuration
switch t.columnsAlign[y] {
case ALIGN_CENTER: //
fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y]))
case ALIGN_RIGHT:
fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y]))
case ALIGN_LEFT:
fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y]))
default:
if decimal.MatchString(strings.TrimSpace(str)) || percent.MatchString(strings.TrimSpace(str)) {
fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y]))
} else {
fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y]))
// TODO Custom alignment per column
//if max == 1 || pads[y] > 0 {
// fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y]))
//} else {
// fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y]))
//}
}
}
fmt.Fprintf(t.out, SPACE)
}
// Check if border is set
// Replace with space if not set
fmt.Fprint(t.out, ConditionString(t.borders.Left, t.pColumn, SPACE))
fmt.Fprint(t.out, t.newLine)
}
if t.rowLine {
t.printLine(true)
}
} | go | func (t *Table) printRow(columns [][]string, rowIdx int) {
// Get Maximum Height
max := t.rs[rowIdx]
total := len(columns)
// TODO Fix uneven col size
// if total < t.colSize {
// for n := t.colSize - total; n < t.colSize ; n++ {
// columns = append(columns, []string{SPACE})
// t.cs[n] = t.mW
// }
//}
// Pad Each Height
pads := []int{}
// Checking for ANSI escape sequences for columns
is_esc_seq := false
if len(t.columnsParams) > 0 {
is_esc_seq = true
}
t.fillAlignment(total)
for i, line := range columns {
length := len(line)
pad := max - length
pads = append(pads, pad)
for n := 0; n < pad; n++ {
columns[i] = append(columns[i], " ")
}
}
//fmt.Println(max, "\n")
for x := 0; x < max; x++ {
for y := 0; y < total; y++ {
// Check if border is set
fmt.Fprint(t.out, ConditionString((!t.borders.Left && y == 0), SPACE, t.pColumn))
fmt.Fprintf(t.out, SPACE)
str := columns[y][x]
// Embedding escape sequence with column value
if is_esc_seq {
str = format(str, t.columnsParams[y])
}
// This would print alignment
// Default alignment would use multiple configuration
switch t.columnsAlign[y] {
case ALIGN_CENTER: //
fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y]))
case ALIGN_RIGHT:
fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y]))
case ALIGN_LEFT:
fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y]))
default:
if decimal.MatchString(strings.TrimSpace(str)) || percent.MatchString(strings.TrimSpace(str)) {
fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y]))
} else {
fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y]))
// TODO Custom alignment per column
//if max == 1 || pads[y] > 0 {
// fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y]))
//} else {
// fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y]))
//}
}
}
fmt.Fprintf(t.out, SPACE)
}
// Check if border is set
// Replace with space if not set
fmt.Fprint(t.out, ConditionString(t.borders.Left, t.pColumn, SPACE))
fmt.Fprint(t.out, t.newLine)
}
if t.rowLine {
t.printLine(true)
}
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"printRow",
"(",
"columns",
"[",
"]",
"[",
"]",
"string",
",",
"rowIdx",
"int",
")",
"{",
"max",
":=",
"t",
".",
"rs",
"[",
"rowIdx",
"]",
"\n",
"total",
":=",
"len",
"(",
"columns",
")",
"\n",
"pads",
":=",... | // Print Row Information
// Adjust column alignment based on type | [
"Print",
"Row",
"Information",
"Adjust",
"column",
"alignment",
"based",
"on",
"type"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L621-L702 | train |
olekukonko/tablewriter | table.go | printRowsMergeCells | func (t *Table) printRowsMergeCells() {
var previousLine []string
var displayCellBorder []bool
var tmpWriter bytes.Buffer
for i, lines := range t.lines {
// We store the display of the current line in a tmp writer, as we need to know which border needs to be print above
previousLine, displayCellBorder = t.printRowMergeCells(&tmpWriter, lines, i, previousLine)
if i > 0 { //We don't need to print borders above first line
if t.rowLine {
t.printLineOptionalCellSeparators(true, displayCellBorder)
}
}
tmpWriter.WriteTo(t.out)
}
//Print the end of the table
if t.rowLine {
t.printLine(true)
}
} | go | func (t *Table) printRowsMergeCells() {
var previousLine []string
var displayCellBorder []bool
var tmpWriter bytes.Buffer
for i, lines := range t.lines {
// We store the display of the current line in a tmp writer, as we need to know which border needs to be print above
previousLine, displayCellBorder = t.printRowMergeCells(&tmpWriter, lines, i, previousLine)
if i > 0 { //We don't need to print borders above first line
if t.rowLine {
t.printLineOptionalCellSeparators(true, displayCellBorder)
}
}
tmpWriter.WriteTo(t.out)
}
//Print the end of the table
if t.rowLine {
t.printLine(true)
}
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"printRowsMergeCells",
"(",
")",
"{",
"var",
"previousLine",
"[",
"]",
"string",
"\n",
"var",
"displayCellBorder",
"[",
"]",
"bool",
"\n",
"var",
"tmpWriter",
"bytes",
".",
"Buffer",
"\n",
"for",
"i",
",",
"lines",
... | // Print the rows of the table and merge the cells that are identical | [
"Print",
"the",
"rows",
"of",
"the",
"table",
"and",
"merge",
"the",
"cells",
"that",
"are",
"identical"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L705-L723 | train |
olekukonko/tablewriter | csv.go | NewCSV | func NewCSV(writer io.Writer, fileName string, hasHeader bool) (*Table, error) {
file, err := os.Open(fileName)
if err != nil {
return &Table{}, err
}
defer file.Close()
csvReader := csv.NewReader(file)
t, err := NewCSVReader(writer, csvReader, hasHeader)
return t, err
} | go | func NewCSV(writer io.Writer, fileName string, hasHeader bool) (*Table, error) {
file, err := os.Open(fileName)
if err != nil {
return &Table{}, err
}
defer file.Close()
csvReader := csv.NewReader(file)
t, err := NewCSVReader(writer, csvReader, hasHeader)
return t, err
} | [
"func",
"NewCSV",
"(",
"writer",
"io",
".",
"Writer",
",",
"fileName",
"string",
",",
"hasHeader",
"bool",
")",
"(",
"*",
"Table",
",",
"error",
")",
"{",
"file",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"fileName",
")",
"\n",
"if",
"err",
"!=",
... | // Start A new table by importing from a CSV file
// Takes io.Writer and csv File name | [
"Start",
"A",
"new",
"table",
"by",
"importing",
"from",
"a",
"CSV",
"file",
"Takes",
"io",
".",
"Writer",
"and",
"csv",
"File",
"name"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/csv.go#L18-L27 | train |
olekukonko/tablewriter | table_with_color.go | format | func format(s string, codes interface{}) string {
var seq string
switch v := codes.(type) {
case string:
seq = v
case []int:
seq = makeSequence(v)
default:
return s
}
if len(seq) == 0 {
return s
}
return startFormat(seq) + s + stopFormat()
} | go | func format(s string, codes interface{}) string {
var seq string
switch v := codes.(type) {
case string:
seq = v
case []int:
seq = makeSequence(v)
default:
return s
}
if len(seq) == 0 {
return s
}
return startFormat(seq) + s + stopFormat()
} | [
"func",
"format",
"(",
"s",
"string",
",",
"codes",
"interface",
"{",
"}",
")",
"string",
"{",
"var",
"seq",
"string",
"\n",
"switch",
"v",
":=",
"codes",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"seq",
"=",
"v",
"\n",
"case",
"[",
"]",... | // Adding ANSI escape sequences before and after string | [
"Adding",
"ANSI",
"escape",
"sequences",
"before",
"and",
"after",
"string"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table_with_color.go#L83-L100 | train |
olekukonko/tablewriter | util.go | ConditionString | func ConditionString(cond bool, valid, inValid string) string {
if cond {
return valid
}
return inValid
} | go | func ConditionString(cond bool, valid, inValid string) string {
if cond {
return valid
}
return inValid
} | [
"func",
"ConditionString",
"(",
"cond",
"bool",
",",
"valid",
",",
"inValid",
"string",
")",
"string",
"{",
"if",
"cond",
"{",
"return",
"valid",
"\n",
"}",
"\n",
"return",
"inValid",
"\n",
"}"
] | // Simple Condition for string
// Returns value based on condition | [
"Simple",
"Condition",
"for",
"string",
"Returns",
"value",
"based",
"on",
"condition"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/util.go#L26-L31 | train |
olekukonko/tablewriter | util.go | Title | func Title(name string) string {
origLen := len(name)
rs := []rune(name)
for i, r := range rs {
switch r {
case '_':
rs[i] = ' '
case '.':
// ignore floating number 0.0
if (i != 0 && !isNumOrSpace(rs[i-1])) || (i != len(rs)-1 && !isNumOrSpace(rs[i+1])) {
rs[i] = ' '
}
}
}
name = string(rs)
name = strings.TrimSpace(name)
if len(name) == 0 && origLen > 0 {
// Keep at least one character. This is important to preserve
// empty lines in multi-line headers/footers.
name = " "
}
return strings.ToUpper(name)
} | go | func Title(name string) string {
origLen := len(name)
rs := []rune(name)
for i, r := range rs {
switch r {
case '_':
rs[i] = ' '
case '.':
// ignore floating number 0.0
if (i != 0 && !isNumOrSpace(rs[i-1])) || (i != len(rs)-1 && !isNumOrSpace(rs[i+1])) {
rs[i] = ' '
}
}
}
name = string(rs)
name = strings.TrimSpace(name)
if len(name) == 0 && origLen > 0 {
// Keep at least one character. This is important to preserve
// empty lines in multi-line headers/footers.
name = " "
}
return strings.ToUpper(name)
} | [
"func",
"Title",
"(",
"name",
"string",
")",
"string",
"{",
"origLen",
":=",
"len",
"(",
"name",
")",
"\n",
"rs",
":=",
"[",
"]",
"rune",
"(",
"name",
")",
"\n",
"for",
"i",
",",
"r",
":=",
"range",
"rs",
"{",
"switch",
"r",
"{",
"case",
"'_'",... | // Format Table Header
// Replace _ , . and spaces | [
"Format",
"Table",
"Header",
"Replace",
"_",
".",
"and",
"spaces"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/util.go#L39-L61 | train |
olekukonko/tablewriter | util.go | Pad | func Pad(s, pad string, width int) string {
gap := width - DisplayWidth(s)
if gap > 0 {
gapLeft := int(math.Ceil(float64(gap / 2)))
gapRight := gap - gapLeft
return strings.Repeat(string(pad), gapLeft) + s + strings.Repeat(string(pad), gapRight)
}
return s
} | go | func Pad(s, pad string, width int) string {
gap := width - DisplayWidth(s)
if gap > 0 {
gapLeft := int(math.Ceil(float64(gap / 2)))
gapRight := gap - gapLeft
return strings.Repeat(string(pad), gapLeft) + s + strings.Repeat(string(pad), gapRight)
}
return s
} | [
"func",
"Pad",
"(",
"s",
",",
"pad",
"string",
",",
"width",
"int",
")",
"string",
"{",
"gap",
":=",
"width",
"-",
"DisplayWidth",
"(",
"s",
")",
"\n",
"if",
"gap",
">",
"0",
"{",
"gapLeft",
":=",
"int",
"(",
"math",
".",
"Ceil",
"(",
"float64",
... | // Pad String
// Attempts to place string in the center | [
"Pad",
"String",
"Attempts",
"to",
"place",
"string",
"in",
"the",
"center"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/util.go#L65-L73 | train |
olekukonko/tablewriter | util.go | PadRight | func PadRight(s, pad string, width int) string {
gap := width - DisplayWidth(s)
if gap > 0 {
return s + strings.Repeat(string(pad), gap)
}
return s
} | go | func PadRight(s, pad string, width int) string {
gap := width - DisplayWidth(s)
if gap > 0 {
return s + strings.Repeat(string(pad), gap)
}
return s
} | [
"func",
"PadRight",
"(",
"s",
",",
"pad",
"string",
",",
"width",
"int",
")",
"string",
"{",
"gap",
":=",
"width",
"-",
"DisplayWidth",
"(",
"s",
")",
"\n",
"if",
"gap",
">",
"0",
"{",
"return",
"s",
"+",
"strings",
".",
"Repeat",
"(",
"string",
... | // Pad String Right position
// This would place string at the left side of the screen | [
"Pad",
"String",
"Right",
"position",
"This",
"would",
"place",
"string",
"at",
"the",
"left",
"side",
"of",
"the",
"screen"
] | 7e037d187b0c13d81ccf0dd1c6b990c2759e6597 | https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/util.go#L77-L83 | train |
openzipkin/zipkin-go | propagation/b3/grpc.go | ExtractGRPC | func ExtractGRPC(md *metadata.MD) propagation.Extractor {
return func() (*model.SpanContext, error) {
var (
traceIDHeader = GetGRPCHeader(md, TraceID)
spanIDHeader = GetGRPCHeader(md, SpanID)
parentSpanIDHeader = GetGRPCHeader(md, ParentSpanID)
sampledHeader = GetGRPCHeader(md, Sampled)
flagsHeader = GetGRPCHeader(md, Flags)
)
return ParseHeaders(
traceIDHeader, spanIDHeader, parentSpanIDHeader, sampledHeader,
flagsHeader,
)
}
} | go | func ExtractGRPC(md *metadata.MD) propagation.Extractor {
return func() (*model.SpanContext, error) {
var (
traceIDHeader = GetGRPCHeader(md, TraceID)
spanIDHeader = GetGRPCHeader(md, SpanID)
parentSpanIDHeader = GetGRPCHeader(md, ParentSpanID)
sampledHeader = GetGRPCHeader(md, Sampled)
flagsHeader = GetGRPCHeader(md, Flags)
)
return ParseHeaders(
traceIDHeader, spanIDHeader, parentSpanIDHeader, sampledHeader,
flagsHeader,
)
}
} | [
"func",
"ExtractGRPC",
"(",
"md",
"*",
"metadata",
".",
"MD",
")",
"propagation",
".",
"Extractor",
"{",
"return",
"func",
"(",
")",
"(",
"*",
"model",
".",
"SpanContext",
",",
"error",
")",
"{",
"var",
"(",
"traceIDHeader",
"=",
"GetGRPCHeader",
"(",
... | // ExtractGRPC will extract a span.Context from the gRPC Request metadata if
// found in B3 header format. | [
"ExtractGRPC",
"will",
"extract",
"a",
"span",
".",
"Context",
"from",
"the",
"gRPC",
"Request",
"metadata",
"if",
"found",
"in",
"B3",
"header",
"format",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/propagation/b3/grpc.go#L26-L41 | train |
openzipkin/zipkin-go | propagation/b3/grpc.go | InjectGRPC | func InjectGRPC(md *metadata.MD) propagation.Injector {
return func(sc model.SpanContext) error {
if (model.SpanContext{}) == sc {
return ErrEmptyContext
}
if sc.Debug {
setGRPCHeader(md, Flags, "1")
} else if sc.Sampled != nil {
// Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled,
// we don't send "X-B3-Sampled" if Debug is set.
if *sc.Sampled {
setGRPCHeader(md, Sampled, "1")
} else {
setGRPCHeader(md, Sampled, "0")
}
}
if !sc.TraceID.Empty() && sc.ID > 0 {
// set identifiers
setGRPCHeader(md, TraceID, sc.TraceID.String())
setGRPCHeader(md, SpanID, sc.ID.String())
if sc.ParentID != nil {
setGRPCHeader(md, ParentSpanID, sc.ParentID.String())
}
}
return nil
}
} | go | func InjectGRPC(md *metadata.MD) propagation.Injector {
return func(sc model.SpanContext) error {
if (model.SpanContext{}) == sc {
return ErrEmptyContext
}
if sc.Debug {
setGRPCHeader(md, Flags, "1")
} else if sc.Sampled != nil {
// Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled,
// we don't send "X-B3-Sampled" if Debug is set.
if *sc.Sampled {
setGRPCHeader(md, Sampled, "1")
} else {
setGRPCHeader(md, Sampled, "0")
}
}
if !sc.TraceID.Empty() && sc.ID > 0 {
// set identifiers
setGRPCHeader(md, TraceID, sc.TraceID.String())
setGRPCHeader(md, SpanID, sc.ID.String())
if sc.ParentID != nil {
setGRPCHeader(md, ParentSpanID, sc.ParentID.String())
}
}
return nil
}
} | [
"func",
"InjectGRPC",
"(",
"md",
"*",
"metadata",
".",
"MD",
")",
"propagation",
".",
"Injector",
"{",
"return",
"func",
"(",
"sc",
"model",
".",
"SpanContext",
")",
"error",
"{",
"if",
"(",
"model",
".",
"SpanContext",
"{",
"}",
")",
"==",
"sc",
"{"... | // InjectGRPC will inject a span.Context into gRPC metadata. | [
"InjectGRPC",
"will",
"inject",
"a",
"span",
".",
"Context",
"into",
"gRPC",
"metadata",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/propagation/b3/grpc.go#L44-L73 | train |
openzipkin/zipkin-go | propagation/b3/grpc.go | GetGRPCHeader | func GetGRPCHeader(md *metadata.MD, key string) string {
v := (*md)[key]
if len(v) < 1 {
return ""
}
return v[len(v)-1]
} | go | func GetGRPCHeader(md *metadata.MD, key string) string {
v := (*md)[key]
if len(v) < 1 {
return ""
}
return v[len(v)-1]
} | [
"func",
"GetGRPCHeader",
"(",
"md",
"*",
"metadata",
".",
"MD",
",",
"key",
"string",
")",
"string",
"{",
"v",
":=",
"(",
"*",
"md",
")",
"[",
"key",
"]",
"\n",
"if",
"len",
"(",
"v",
")",
"<",
"1",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"re... | // GetGRPCHeader retrieves the last value found for a particular key. If key is
// not found it returns an empty string. | [
"GetGRPCHeader",
"retrieves",
"the",
"last",
"value",
"found",
"for",
"a",
"particular",
"key",
".",
"If",
"key",
"is",
"not",
"found",
"it",
"returns",
"an",
"empty",
"string",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/propagation/b3/grpc.go#L77-L83 | train |
openzipkin/zipkin-go | reporter/recorder/recorder.go | Send | func (r *ReporterRecorder) Send(span model.SpanModel) {
r.mtx.Lock()
r.spans = append(r.spans, span)
r.mtx.Unlock()
} | go | func (r *ReporterRecorder) Send(span model.SpanModel) {
r.mtx.Lock()
r.spans = append(r.spans, span)
r.mtx.Unlock()
} | [
"func",
"(",
"r",
"*",
"ReporterRecorder",
")",
"Send",
"(",
"span",
"model",
".",
"SpanModel",
")",
"{",
"r",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"r",
".",
"spans",
"=",
"append",
"(",
"r",
".",
"spans",
",",
"span",
")",
"\n",
"r",
".",
... | // Send adds the provided span to the span list held by the recorder. | [
"Send",
"adds",
"the",
"provided",
"span",
"to",
"the",
"span",
"list",
"held",
"by",
"the",
"recorder",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/recorder/recorder.go#L38-L42 | train |
openzipkin/zipkin-go | reporter/recorder/recorder.go | Flush | func (r *ReporterRecorder) Flush() []model.SpanModel {
r.mtx.Lock()
spans := r.spans
r.spans = nil
r.mtx.Unlock()
return spans
} | go | func (r *ReporterRecorder) Flush() []model.SpanModel {
r.mtx.Lock()
spans := r.spans
r.spans = nil
r.mtx.Unlock()
return spans
} | [
"func",
"(",
"r",
"*",
"ReporterRecorder",
")",
"Flush",
"(",
")",
"[",
"]",
"model",
".",
"SpanModel",
"{",
"r",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"spans",
":=",
"r",
".",
"spans",
"\n",
"r",
".",
"spans",
"=",
"nil",
"\n",
"r",
".",
... | // Flush returns all recorded spans and clears its internal span storage | [
"Flush",
"returns",
"all",
"recorded",
"spans",
"and",
"clears",
"its",
"internal",
"span",
"storage"
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/recorder/recorder.go#L45-L51 | train |
openzipkin/zipkin-go | tracer_options.go | WithLocalEndpoint | func WithLocalEndpoint(e *model.Endpoint) TracerOption {
return func(o *Tracer) error {
if e == nil {
o.localEndpoint = nil
return nil
}
ep := *e
o.localEndpoint = &ep
return nil
}
} | go | func WithLocalEndpoint(e *model.Endpoint) TracerOption {
return func(o *Tracer) error {
if e == nil {
o.localEndpoint = nil
return nil
}
ep := *e
o.localEndpoint = &ep
return nil
}
} | [
"func",
"WithLocalEndpoint",
"(",
"e",
"*",
"model",
".",
"Endpoint",
")",
"TracerOption",
"{",
"return",
"func",
"(",
"o",
"*",
"Tracer",
")",
"error",
"{",
"if",
"e",
"==",
"nil",
"{",
"o",
".",
"localEndpoint",
"=",
"nil",
"\n",
"return",
"nil",
"... | // WithLocalEndpoint sets the local endpoint of the tracer. | [
"WithLocalEndpoint",
"sets",
"the",
"local",
"endpoint",
"of",
"the",
"tracer",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L45-L55 | train |
openzipkin/zipkin-go | tracer_options.go | WithExtractFailurePolicy | func WithExtractFailurePolicy(p ExtractFailurePolicy) TracerOption {
return func(o *Tracer) error {
if p < 0 || p > ExtractFailurePolicyTagAndRestart {
return ErrInvalidExtractFailurePolicy
}
o.extractFailurePolicy = p
return nil
}
} | go | func WithExtractFailurePolicy(p ExtractFailurePolicy) TracerOption {
return func(o *Tracer) error {
if p < 0 || p > ExtractFailurePolicyTagAndRestart {
return ErrInvalidExtractFailurePolicy
}
o.extractFailurePolicy = p
return nil
}
} | [
"func",
"WithExtractFailurePolicy",
"(",
"p",
"ExtractFailurePolicy",
")",
"TracerOption",
"{",
"return",
"func",
"(",
"o",
"*",
"Tracer",
")",
"error",
"{",
"if",
"p",
"<",
"0",
"||",
"p",
">",
"ExtractFailurePolicyTagAndRestart",
"{",
"return",
"ErrInvalidExtr... | // WithExtractFailurePolicy allows one to set the ExtractFailurePolicy. | [
"WithExtractFailurePolicy",
"allows",
"one",
"to",
"set",
"the",
"ExtractFailurePolicy",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L58-L66 | train |
openzipkin/zipkin-go | tracer_options.go | WithNoopSpan | func WithNoopSpan(unsampledNoop bool) TracerOption {
return func(o *Tracer) error {
o.unsampledNoop = unsampledNoop
return nil
}
} | go | func WithNoopSpan(unsampledNoop bool) TracerOption {
return func(o *Tracer) error {
o.unsampledNoop = unsampledNoop
return nil
}
} | [
"func",
"WithNoopSpan",
"(",
"unsampledNoop",
"bool",
")",
"TracerOption",
"{",
"return",
"func",
"(",
"o",
"*",
"Tracer",
")",
"error",
"{",
"o",
".",
"unsampledNoop",
"=",
"unsampledNoop",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // WithNoopSpan if set to true will switch to a NoopSpan implementation
// if the trace is not sampled. | [
"WithNoopSpan",
"if",
"set",
"to",
"true",
"will",
"switch",
"to",
"a",
"NoopSpan",
"implementation",
"if",
"the",
"trace",
"is",
"not",
"sampled",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L70-L75 | train |
openzipkin/zipkin-go | tracer_options.go | WithSampler | func WithSampler(sampler Sampler) TracerOption {
return func(o *Tracer) error {
o.sampler = sampler
return nil
}
} | go | func WithSampler(sampler Sampler) TracerOption {
return func(o *Tracer) error {
o.sampler = sampler
return nil
}
} | [
"func",
"WithSampler",
"(",
"sampler",
"Sampler",
")",
"TracerOption",
"{",
"return",
"func",
"(",
"o",
"*",
"Tracer",
")",
"error",
"{",
"o",
".",
"sampler",
"=",
"sampler",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // WithSampler allows one to set a Sampler function | [
"WithSampler",
"allows",
"one",
"to",
"set",
"a",
"Sampler",
"function"
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L89-L94 | train |
openzipkin/zipkin-go | tracer_options.go | WithTraceID128Bit | func WithTraceID128Bit(val bool) TracerOption {
return func(o *Tracer) error {
if val {
o.generate = idgenerator.NewRandom128()
} else {
o.generate = idgenerator.NewRandom64()
}
return nil
}
} | go | func WithTraceID128Bit(val bool) TracerOption {
return func(o *Tracer) error {
if val {
o.generate = idgenerator.NewRandom128()
} else {
o.generate = idgenerator.NewRandom64()
}
return nil
}
} | [
"func",
"WithTraceID128Bit",
"(",
"val",
"bool",
")",
"TracerOption",
"{",
"return",
"func",
"(",
"o",
"*",
"Tracer",
")",
"error",
"{",
"if",
"val",
"{",
"o",
".",
"generate",
"=",
"idgenerator",
".",
"NewRandom128",
"(",
")",
"\n",
"}",
"else",
"{",
... | // WithTraceID128Bit if set to true will instruct the Tracer to start traces
// with 128 bit TraceID's. If set to false the Tracer will start traces with
// 64 bits. | [
"WithTraceID128Bit",
"if",
"set",
"to",
"true",
"will",
"instruct",
"the",
"Tracer",
"to",
"start",
"traces",
"with",
"128",
"bit",
"TraceID",
"s",
".",
"If",
"set",
"to",
"false",
"the",
"Tracer",
"will",
"start",
"traces",
"with",
"64",
"bits",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L99-L108 | train |
openzipkin/zipkin-go | tracer_options.go | WithIDGenerator | func WithIDGenerator(generator idgenerator.IDGenerator) TracerOption {
return func(o *Tracer) error {
o.generate = generator
return nil
}
} | go | func WithIDGenerator(generator idgenerator.IDGenerator) TracerOption {
return func(o *Tracer) error {
o.generate = generator
return nil
}
} | [
"func",
"WithIDGenerator",
"(",
"generator",
"idgenerator",
".",
"IDGenerator",
")",
"TracerOption",
"{",
"return",
"func",
"(",
"o",
"*",
"Tracer",
")",
"error",
"{",
"o",
".",
"generate",
"=",
"generator",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // WithIDGenerator allows one to set a custom ID Generator | [
"WithIDGenerator",
"allows",
"one",
"to",
"set",
"a",
"custom",
"ID",
"Generator"
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L111-L116 | train |
openzipkin/zipkin-go | tracer_options.go | WithTags | func WithTags(tags map[string]string) TracerOption {
return func(o *Tracer) error {
for k, v := range tags {
o.defaultTags[k] = v
}
return nil
}
} | go | func WithTags(tags map[string]string) TracerOption {
return func(o *Tracer) error {
for k, v := range tags {
o.defaultTags[k] = v
}
return nil
}
} | [
"func",
"WithTags",
"(",
"tags",
"map",
"[",
"string",
"]",
"string",
")",
"TracerOption",
"{",
"return",
"func",
"(",
"o",
"*",
"Tracer",
")",
"error",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"tags",
"{",
"o",
".",
"defaultTags",
"[",
"k",
"]",
... | // WithTags allows one to set default tags to be added to each created span | [
"WithTags",
"allows",
"one",
"to",
"set",
"default",
"tags",
"to",
"be",
"added",
"to",
"each",
"created",
"span"
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L119-L126 | train |
openzipkin/zipkin-go | tracer_options.go | WithNoopTracer | func WithNoopTracer(tracerNoop bool) TracerOption {
return func(o *Tracer) error {
if tracerNoop {
o.noop = 1
} else {
o.noop = 0
}
return nil
}
} | go | func WithNoopTracer(tracerNoop bool) TracerOption {
return func(o *Tracer) error {
if tracerNoop {
o.noop = 1
} else {
o.noop = 0
}
return nil
}
} | [
"func",
"WithNoopTracer",
"(",
"tracerNoop",
"bool",
")",
"TracerOption",
"{",
"return",
"func",
"(",
"o",
"*",
"Tracer",
")",
"error",
"{",
"if",
"tracerNoop",
"{",
"o",
".",
"noop",
"=",
"1",
"\n",
"}",
"else",
"{",
"o",
".",
"noop",
"=",
"0",
"\... | // WithNoopTracer allows one to start the Tracer as Noop implementation. | [
"WithNoopTracer",
"allows",
"one",
"to",
"start",
"the",
"Tracer",
"as",
"Noop",
"implementation",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L129-L138 | train |
openzipkin/zipkin-go | middleware/grpc/client.go | NewClientHandler | func NewClientHandler(tracer *zipkin.Tracer, options ...ClientOption) stats.Handler {
c := &clientHandler{
tracer: tracer,
}
for _, option := range options {
option(c)
}
return c
} | go | func NewClientHandler(tracer *zipkin.Tracer, options ...ClientOption) stats.Handler {
c := &clientHandler{
tracer: tracer,
}
for _, option := range options {
option(c)
}
return c
} | [
"func",
"NewClientHandler",
"(",
"tracer",
"*",
"zipkin",
".",
"Tracer",
",",
"options",
"...",
"ClientOption",
")",
"stats",
".",
"Handler",
"{",
"c",
":=",
"&",
"clientHandler",
"{",
"tracer",
":",
"tracer",
",",
"}",
"\n",
"for",
"_",
",",
"option",
... | // NewClientHandler returns a stats.Handler which can be used with grpc.WithStatsHandler to add
// tracing to a gRPC client. The gRPC method name is used as the span name and by default the only
// tags are the gRPC status code if the call fails. | [
"NewClientHandler",
"returns",
"a",
"stats",
".",
"Handler",
"which",
"can",
"be",
"used",
"with",
"grpc",
".",
"WithStatsHandler",
"to",
"add",
"tracing",
"to",
"a",
"gRPC",
"client",
".",
"The",
"gRPC",
"method",
"name",
"is",
"used",
"as",
"the",
"span"... | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/grpc/client.go#L47-L55 | train |
openzipkin/zipkin-go | reporter/log/log.go | NewReporter | func NewReporter(l *log.Logger) reporter.Reporter {
if l == nil {
// use standard type of log setup
l = log.New(os.Stderr, "", log.LstdFlags)
}
return &logReporter{
logger: l,
}
} | go | func NewReporter(l *log.Logger) reporter.Reporter {
if l == nil {
// use standard type of log setup
l = log.New(os.Stderr, "", log.LstdFlags)
}
return &logReporter{
logger: l,
}
} | [
"func",
"NewReporter",
"(",
"l",
"*",
"log",
".",
"Logger",
")",
"reporter",
".",
"Reporter",
"{",
"if",
"l",
"==",
"nil",
"{",
"l",
"=",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"\"\"",
",",
"log",
".",
"LstdFlags",
")",
"\n",
"}",
"\... | // NewReporter returns a new log reporter. | [
"NewReporter",
"returns",
"a",
"new",
"log",
"reporter",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/log/log.go#L37-L45 | train |
openzipkin/zipkin-go | reporter/log/log.go | Send | func (r *logReporter) Send(s model.SpanModel) {
if b, err := json.MarshalIndent(s, "", " "); err == nil {
r.logger.Printf("%s:\n%s\n\n", time.Now(), string(b))
}
} | go | func (r *logReporter) Send(s model.SpanModel) {
if b, err := json.MarshalIndent(s, "", " "); err == nil {
r.logger.Printf("%s:\n%s\n\n", time.Now(), string(b))
}
} | [
"func",
"(",
"r",
"*",
"logReporter",
")",
"Send",
"(",
"s",
"model",
".",
"SpanModel",
")",
"{",
"if",
"b",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"s",
",",
"\"\"",
",",
"\" \"",
")",
";",
"err",
"==",
"nil",
"{",
"r",
".",
"log... | // Send outputs a span to the Go logger. | [
"Send",
"outputs",
"a",
"span",
"to",
"the",
"Go",
"logger",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/log/log.go#L48-L52 | train |
openzipkin/zipkin-go | context.go | NewContext | func NewContext(ctx context.Context, s Span) context.Context {
return context.WithValue(ctx, spanKey, s)
} | go | func NewContext(ctx context.Context, s Span) context.Context {
return context.WithValue(ctx, spanKey, s)
} | [
"func",
"NewContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"s",
"Span",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"spanKey",
",",
"s",
")",
"\n",
"}"
] | // NewContext stores a Zipkin Span into Go's context propagation mechanism. | [
"NewContext",
"stores",
"a",
"Zipkin",
"Span",
"into",
"Go",
"s",
"context",
"propagation",
"mechanism",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/context.go#L46-L48 | train |
openzipkin/zipkin-go | reporter/http/http.go | Timeout | func Timeout(duration time.Duration) ReporterOption {
return func(r *httpReporter) { r.client.Timeout = duration }
} | go | func Timeout(duration time.Duration) ReporterOption {
return func(r *httpReporter) { r.client.Timeout = duration }
} | [
"func",
"Timeout",
"(",
"duration",
"time",
".",
"Duration",
")",
"ReporterOption",
"{",
"return",
"func",
"(",
"r",
"*",
"httpReporter",
")",
"{",
"r",
".",
"client",
".",
"Timeout",
"=",
"duration",
"}",
"\n",
"}"
] | // Timeout sets maximum timeout for http request. | [
"Timeout",
"sets",
"maximum",
"timeout",
"for",
"http",
"request",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/http/http.go#L173-L175 | train |
openzipkin/zipkin-go | reporter/http/http.go | BatchInterval | func BatchInterval(d time.Duration) ReporterOption {
return func(r *httpReporter) { r.batchInterval = d }
} | go | func BatchInterval(d time.Duration) ReporterOption {
return func(r *httpReporter) { r.batchInterval = d }
} | [
"func",
"BatchInterval",
"(",
"d",
"time",
".",
"Duration",
")",
"ReporterOption",
"{",
"return",
"func",
"(",
"r",
"*",
"httpReporter",
")",
"{",
"r",
".",
"batchInterval",
"=",
"d",
"}",
"\n",
"}"
] | // BatchInterval sets the maximum duration we will buffer traces before
// emitting them to the collector. The default batch interval is 1 second. | [
"BatchInterval",
"sets",
"the",
"maximum",
"duration",
"we",
"will",
"buffer",
"traces",
"before",
"emitting",
"them",
"to",
"the",
"collector",
".",
"The",
"default",
"batch",
"interval",
"is",
"1",
"second",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/http/http.go#L191-L193 | train |
openzipkin/zipkin-go | reporter/http/http.go | Client | func Client(client *http.Client) ReporterOption {
return func(r *httpReporter) { r.client = client }
} | go | func Client(client *http.Client) ReporterOption {
return func(r *httpReporter) { r.client = client }
} | [
"func",
"Client",
"(",
"client",
"*",
"http",
".",
"Client",
")",
"ReporterOption",
"{",
"return",
"func",
"(",
"r",
"*",
"httpReporter",
")",
"{",
"r",
".",
"client",
"=",
"client",
"}",
"\n",
"}"
] | // Client sets a custom http client to use. | [
"Client",
"sets",
"a",
"custom",
"http",
"client",
"to",
"use",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/http/http.go#L196-L198 | train |
openzipkin/zipkin-go | middleware/http/server.go | NewServerMiddleware | func NewServerMiddleware(t *zipkin.Tracer, options ...ServerOption) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
h := &handler{
tracer: t,
next: next,
}
for _, option := range options {
option(h)
}
return h
}
} | go | func NewServerMiddleware(t *zipkin.Tracer, options ...ServerOption) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
h := &handler{
tracer: t,
next: next,
}
for _, option := range options {
option(h)
}
return h
}
} | [
"func",
"NewServerMiddleware",
"(",
"t",
"*",
"zipkin",
".",
"Tracer",
",",
"options",
"...",
"ServerOption",
")",
"func",
"(",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"func",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
... | // NewServerMiddleware returns a http.Handler middleware with Zipkin tracing. | [
"NewServerMiddleware",
"returns",
"a",
"http",
".",
"Handler",
"middleware",
"with",
"Zipkin",
"tracing",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/server.go#L74-L85 | train |
openzipkin/zipkin-go | proto/v2/decode_proto.go | ParseSpans | func ParseSpans(protoBlob []byte, debugWasSet bool) (zss []*zipkinmodel.SpanModel, err error) {
var listOfSpans ListOfSpans
if err := proto.Unmarshal(protoBlob, &listOfSpans); err != nil {
return nil, err
}
for _, zps := range listOfSpans.Spans {
zms, err := protoSpanToModelSpan(zps, debugWasSet)
if err != nil {
return zss, err
}
zss = append(zss, zms)
}
return zss, nil
} | go | func ParseSpans(protoBlob []byte, debugWasSet bool) (zss []*zipkinmodel.SpanModel, err error) {
var listOfSpans ListOfSpans
if err := proto.Unmarshal(protoBlob, &listOfSpans); err != nil {
return nil, err
}
for _, zps := range listOfSpans.Spans {
zms, err := protoSpanToModelSpan(zps, debugWasSet)
if err != nil {
return zss, err
}
zss = append(zss, zms)
}
return zss, nil
} | [
"func",
"ParseSpans",
"(",
"protoBlob",
"[",
"]",
"byte",
",",
"debugWasSet",
"bool",
")",
"(",
"zss",
"[",
"]",
"*",
"zipkinmodel",
".",
"SpanModel",
",",
"err",
"error",
")",
"{",
"var",
"listOfSpans",
"ListOfSpans",
"\n",
"if",
"err",
":=",
"proto",
... | // ParseSpans parses zipkinmodel.SpanModel values from data serialized by Protobuf3.
// debugWasSet is a boolean that toggles the Debug field of each Span. Its value
// is usually retrieved from the transport headers when the "X-B3-Flags" header has a value of 1. | [
"ParseSpans",
"parses",
"zipkinmodel",
".",
"SpanModel",
"values",
"from",
"data",
"serialized",
"by",
"Protobuf3",
".",
"debugWasSet",
"is",
"a",
"boolean",
"that",
"toggles",
"the",
"Debug",
"field",
"of",
"each",
"Span",
".",
"Its",
"value",
"is",
"usually"... | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/proto/v2/decode_proto.go#L35-L48 | train |
openzipkin/zipkin-go | proto/v2/encode_proto.go | Serialize | func (SpanSerializer) Serialize(sms []*zipkinmodel.SpanModel) (protoBlob []byte, err error) {
var listOfSpans ListOfSpans
for _, sm := range sms {
sp, err := modelSpanToProtoSpan(sm)
if err != nil {
return nil, err
}
listOfSpans.Spans = append(listOfSpans.Spans, sp)
}
return proto.Marshal(&listOfSpans)
} | go | func (SpanSerializer) Serialize(sms []*zipkinmodel.SpanModel) (protoBlob []byte, err error) {
var listOfSpans ListOfSpans
for _, sm := range sms {
sp, err := modelSpanToProtoSpan(sm)
if err != nil {
return nil, err
}
listOfSpans.Spans = append(listOfSpans.Spans, sp)
}
return proto.Marshal(&listOfSpans)
} | [
"func",
"(",
"SpanSerializer",
")",
"Serialize",
"(",
"sms",
"[",
"]",
"*",
"zipkinmodel",
".",
"SpanModel",
")",
"(",
"protoBlob",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"var",
"listOfSpans",
"ListOfSpans",
"\n",
"for",
"_",
",",
"sm",
":=",... | // Serialize takes an array of zipkin SpanModel objects and serializes it to a protobuf blob. | [
"Serialize",
"takes",
"an",
"array",
"of",
"zipkin",
"SpanModel",
"objects",
"and",
"serializes",
"it",
"to",
"a",
"protobuf",
"blob",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/proto/v2/encode_proto.go#L32-L44 | train |
openzipkin/zipkin-go | model/span.go | MarshalJSON | func (s SpanModel) MarshalJSON() ([]byte, error) {
type Alias SpanModel
var timestamp int64
if !s.Timestamp.IsZero() {
if s.Timestamp.Unix() < 1 {
// Zipkin does not allow Timestamps before Unix epoch
return nil, ErrValidTimestampRequired
}
timestamp = s.Timestamp.Round(time.Microsecond).UnixNano() / 1e3
}
if s.Duration < time.Microsecond {
if s.Duration < 0 {
// negative duration is not allowed and signals a timing logic error
return nil, ErrValidDurationRequired
} else if s.Duration > 0 {
// sub microsecond durations are reported as 1 microsecond
s.Duration = 1 * time.Microsecond
}
} else {
// Duration will be rounded to nearest microsecond representation.
//
// NOTE: Duration.Round() is not available in Go 1.8 which we still support.
// To handle microsecond resolution rounding we'll add 500 nanoseconds to
// the duration. When truncated to microseconds in the call to marshal, it
// will be naturally rounded. See TestSpanDurationRounding in span_test.go
s.Duration += 500 * time.Nanosecond
}
if s.LocalEndpoint.Empty() {
s.LocalEndpoint = nil
}
if s.RemoteEndpoint.Empty() {
s.RemoteEndpoint = nil
}
return json.Marshal(&struct {
T int64 `json:"timestamp,omitempty"`
D int64 `json:"duration,omitempty"`
Alias
}{
T: timestamp,
D: s.Duration.Nanoseconds() / 1e3,
Alias: (Alias)(s),
})
} | go | func (s SpanModel) MarshalJSON() ([]byte, error) {
type Alias SpanModel
var timestamp int64
if !s.Timestamp.IsZero() {
if s.Timestamp.Unix() < 1 {
// Zipkin does not allow Timestamps before Unix epoch
return nil, ErrValidTimestampRequired
}
timestamp = s.Timestamp.Round(time.Microsecond).UnixNano() / 1e3
}
if s.Duration < time.Microsecond {
if s.Duration < 0 {
// negative duration is not allowed and signals a timing logic error
return nil, ErrValidDurationRequired
} else if s.Duration > 0 {
// sub microsecond durations are reported as 1 microsecond
s.Duration = 1 * time.Microsecond
}
} else {
// Duration will be rounded to nearest microsecond representation.
//
// NOTE: Duration.Round() is not available in Go 1.8 which we still support.
// To handle microsecond resolution rounding we'll add 500 nanoseconds to
// the duration. When truncated to microseconds in the call to marshal, it
// will be naturally rounded. See TestSpanDurationRounding in span_test.go
s.Duration += 500 * time.Nanosecond
}
if s.LocalEndpoint.Empty() {
s.LocalEndpoint = nil
}
if s.RemoteEndpoint.Empty() {
s.RemoteEndpoint = nil
}
return json.Marshal(&struct {
T int64 `json:"timestamp,omitempty"`
D int64 `json:"duration,omitempty"`
Alias
}{
T: timestamp,
D: s.Duration.Nanoseconds() / 1e3,
Alias: (Alias)(s),
})
} | [
"func",
"(",
"s",
"SpanModel",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"type",
"Alias",
"SpanModel",
"\n",
"var",
"timestamp",
"int64",
"\n",
"if",
"!",
"s",
".",
"Timestamp",
".",
"IsZero",
"(",
")",
"{",
"if",... | // MarshalJSON exports our Model into the correct format for the Zipkin V2 API. | [
"MarshalJSON",
"exports",
"our",
"Model",
"into",
"the",
"correct",
"format",
"for",
"the",
"Zipkin",
"V2",
"API",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/span.go#L60-L107 | train |
openzipkin/zipkin-go | model/span.go | UnmarshalJSON | func (s *SpanModel) UnmarshalJSON(b []byte) error {
type Alias SpanModel
span := &struct {
T uint64 `json:"timestamp,omitempty"`
D uint64 `json:"duration,omitempty"`
*Alias
}{
Alias: (*Alias)(s),
}
if err := json.Unmarshal(b, &span); err != nil {
return err
}
if s.ID < 1 {
return ErrValidIDRequired
}
if span.T > 0 {
s.Timestamp = time.Unix(0, int64(span.T)*1e3)
}
s.Duration = time.Duration(span.D*1e3) * time.Nanosecond
if s.LocalEndpoint.Empty() {
s.LocalEndpoint = nil
}
if s.RemoteEndpoint.Empty() {
s.RemoteEndpoint = nil
}
return nil
} | go | func (s *SpanModel) UnmarshalJSON(b []byte) error {
type Alias SpanModel
span := &struct {
T uint64 `json:"timestamp,omitempty"`
D uint64 `json:"duration,omitempty"`
*Alias
}{
Alias: (*Alias)(s),
}
if err := json.Unmarshal(b, &span); err != nil {
return err
}
if s.ID < 1 {
return ErrValidIDRequired
}
if span.T > 0 {
s.Timestamp = time.Unix(0, int64(span.T)*1e3)
}
s.Duration = time.Duration(span.D*1e3) * time.Nanosecond
if s.LocalEndpoint.Empty() {
s.LocalEndpoint = nil
}
if s.RemoteEndpoint.Empty() {
s.RemoteEndpoint = nil
}
return nil
} | [
"func",
"(",
"s",
"*",
"SpanModel",
")",
"UnmarshalJSON",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"type",
"Alias",
"SpanModel",
"\n",
"span",
":=",
"&",
"struct",
"{",
"T",
"uint64",
"`json:\"timestamp,omitempty\"`",
"\n",
"D",
"uint64",
"`json:\"du... | // UnmarshalJSON imports our Model from a Zipkin V2 API compatible span
// representation. | [
"UnmarshalJSON",
"imports",
"our",
"Model",
"from",
"a",
"Zipkin",
"V2",
"API",
"compatible",
"span",
"representation",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/span.go#L111-L138 | train |
openzipkin/zipkin-go | tags.go | Set | func (t Tag) Set(s Span, value string) {
s.Tag(string(t), value)
} | go | func (t Tag) Set(s Span, value string) {
s.Tag(string(t), value)
} | [
"func",
"(",
"t",
"Tag",
")",
"Set",
"(",
"s",
"Span",
",",
"value",
"string",
")",
"{",
"s",
".",
"Tag",
"(",
"string",
"(",
"t",
")",
",",
"value",
")",
"\n",
"}"
] | // Set a standard Tag with a payload on provided Span. | [
"Set",
"a",
"standard",
"Tag",
"with",
"a",
"payload",
"on",
"provided",
"Span",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tags.go#L35-L37 | train |
openzipkin/zipkin-go | sample.go | NewModuloSampler | func NewModuloSampler(mod uint64) Sampler {
if mod < 2 {
return AlwaysSample
}
return func(id uint64) bool {
return (id % mod) == 0
}
} | go | func NewModuloSampler(mod uint64) Sampler {
if mod < 2 {
return AlwaysSample
}
return func(id uint64) bool {
return (id % mod) == 0
}
} | [
"func",
"NewModuloSampler",
"(",
"mod",
"uint64",
")",
"Sampler",
"{",
"if",
"mod",
"<",
"2",
"{",
"return",
"AlwaysSample",
"\n",
"}",
"\n",
"return",
"func",
"(",
"id",
"uint64",
")",
"bool",
"{",
"return",
"(",
"id",
"%",
"mod",
")",
"==",
"0",
... | // NewModuloSampler provides a generic type Sampler. | [
"NewModuloSampler",
"provides",
"a",
"generic",
"type",
"Sampler",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/sample.go#L40-L47 | train |
openzipkin/zipkin-go | tracer.go | NewTracer | func NewTracer(rep reporter.Reporter, opts ...TracerOption) (*Tracer, error) {
// set default tracer options
t := &Tracer{
defaultTags: make(map[string]string),
extractFailurePolicy: ExtractFailurePolicyRestart,
sampler: AlwaysSample,
generate: idgenerator.NewRandom64(),
reporter: rep,
localEndpoint: nil,
noop: 0,
sharedSpans: true,
unsampledNoop: false,
}
// if no reporter was provided we default to noop implementation.
if t.reporter == nil {
t.reporter = reporter.NewNoopReporter()
t.noop = 1
}
// process functional options
for _, opt := range opts {
if err := opt(t); err != nil {
return nil, err
}
}
return t, nil
} | go | func NewTracer(rep reporter.Reporter, opts ...TracerOption) (*Tracer, error) {
// set default tracer options
t := &Tracer{
defaultTags: make(map[string]string),
extractFailurePolicy: ExtractFailurePolicyRestart,
sampler: AlwaysSample,
generate: idgenerator.NewRandom64(),
reporter: rep,
localEndpoint: nil,
noop: 0,
sharedSpans: true,
unsampledNoop: false,
}
// if no reporter was provided we default to noop implementation.
if t.reporter == nil {
t.reporter = reporter.NewNoopReporter()
t.noop = 1
}
// process functional options
for _, opt := range opts {
if err := opt(t); err != nil {
return nil, err
}
}
return t, nil
} | [
"func",
"NewTracer",
"(",
"rep",
"reporter",
".",
"Reporter",
",",
"opts",
"...",
"TracerOption",
")",
"(",
"*",
"Tracer",
",",
"error",
")",
"{",
"t",
":=",
"&",
"Tracer",
"{",
"defaultTags",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")... | // NewTracer returns a new Zipkin Tracer. | [
"NewTracer",
"returns",
"a",
"new",
"Zipkin",
"Tracer",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer.go#L43-L71 | train |
openzipkin/zipkin-go | tracer.go | StartSpanFromContext | func (t *Tracer) StartSpanFromContext(ctx context.Context, name string, options ...SpanOption) (Span, context.Context) {
if parentSpan := SpanFromContext(ctx); parentSpan != nil {
options = append(options, Parent(parentSpan.Context()))
}
span := t.StartSpan(name, options...)
return span, NewContext(ctx, span)
} | go | func (t *Tracer) StartSpanFromContext(ctx context.Context, name string, options ...SpanOption) (Span, context.Context) {
if parentSpan := SpanFromContext(ctx); parentSpan != nil {
options = append(options, Parent(parentSpan.Context()))
}
span := t.StartSpan(name, options...)
return span, NewContext(ctx, span)
} | [
"func",
"(",
"t",
"*",
"Tracer",
")",
"StartSpanFromContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
",",
"options",
"...",
"SpanOption",
")",
"(",
"Span",
",",
"context",
".",
"Context",
")",
"{",
"if",
"parentSpan",
":=",
"SpanFr... | // StartSpanFromContext creates and starts a span using the span found in
// context as parent. If no parent span is found a root span is created. | [
"StartSpanFromContext",
"creates",
"and",
"starts",
"a",
"span",
"using",
"the",
"span",
"found",
"in",
"context",
"as",
"parent",
".",
"If",
"no",
"parent",
"span",
"is",
"found",
"a",
"root",
"span",
"is",
"created",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer.go#L75-L81 | train |
openzipkin/zipkin-go | tracer.go | StartSpan | func (t *Tracer) StartSpan(name string, options ...SpanOption) Span {
if atomic.LoadInt32(&t.noop) == 1 {
return &noopSpan{}
}
s := &spanImpl{
SpanModel: model.SpanModel{
Kind: model.Undetermined,
Name: name,
LocalEndpoint: t.localEndpoint,
Annotations: make([]model.Annotation, 0),
Tags: make(map[string]string),
},
flushOnFinish: true,
tracer: t,
}
// add default tracer tags to span
for k, v := range t.defaultTags {
s.Tag(k, v)
}
// handle provided functional options
for _, option := range options {
option(t, s)
}
if s.TraceID.Empty() {
// create root span
s.SpanContext.TraceID = t.generate.TraceID()
s.SpanContext.ID = t.generate.SpanID(s.SpanContext.TraceID)
} else {
// valid parent context found
if t.sharedSpans && s.Kind == model.Server {
// join span
s.Shared = true
} else {
// regular child span
parentID := s.SpanContext.ID
s.SpanContext.ParentID = &parentID
s.SpanContext.ID = t.generate.SpanID(model.TraceID{})
}
}
if !s.SpanContext.Debug && s.Sampled == nil {
// deferred sampled context found, invoke sampler
sampled := t.sampler(s.SpanContext.TraceID.Low)
s.SpanContext.Sampled = &sampled
if sampled {
s.mustCollect = 1
}
} else {
if s.SpanContext.Debug || *s.Sampled {
s.mustCollect = 1
}
}
if t.unsampledNoop && s.mustCollect == 0 {
// trace not being sampled and noop requested
return &noopSpan{
SpanContext: s.SpanContext,
}
}
// add start time
if s.Timestamp.IsZero() {
s.Timestamp = time.Now()
}
return s
} | go | func (t *Tracer) StartSpan(name string, options ...SpanOption) Span {
if atomic.LoadInt32(&t.noop) == 1 {
return &noopSpan{}
}
s := &spanImpl{
SpanModel: model.SpanModel{
Kind: model.Undetermined,
Name: name,
LocalEndpoint: t.localEndpoint,
Annotations: make([]model.Annotation, 0),
Tags: make(map[string]string),
},
flushOnFinish: true,
tracer: t,
}
// add default tracer tags to span
for k, v := range t.defaultTags {
s.Tag(k, v)
}
// handle provided functional options
for _, option := range options {
option(t, s)
}
if s.TraceID.Empty() {
// create root span
s.SpanContext.TraceID = t.generate.TraceID()
s.SpanContext.ID = t.generate.SpanID(s.SpanContext.TraceID)
} else {
// valid parent context found
if t.sharedSpans && s.Kind == model.Server {
// join span
s.Shared = true
} else {
// regular child span
parentID := s.SpanContext.ID
s.SpanContext.ParentID = &parentID
s.SpanContext.ID = t.generate.SpanID(model.TraceID{})
}
}
if !s.SpanContext.Debug && s.Sampled == nil {
// deferred sampled context found, invoke sampler
sampled := t.sampler(s.SpanContext.TraceID.Low)
s.SpanContext.Sampled = &sampled
if sampled {
s.mustCollect = 1
}
} else {
if s.SpanContext.Debug || *s.Sampled {
s.mustCollect = 1
}
}
if t.unsampledNoop && s.mustCollect == 0 {
// trace not being sampled and noop requested
return &noopSpan{
SpanContext: s.SpanContext,
}
}
// add start time
if s.Timestamp.IsZero() {
s.Timestamp = time.Now()
}
return s
} | [
"func",
"(",
"t",
"*",
"Tracer",
")",
"StartSpan",
"(",
"name",
"string",
",",
"options",
"...",
"SpanOption",
")",
"Span",
"{",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"noop",
")",
"==",
"1",
"{",
"return",
"&",
"noopSpan",
"{",
"}",... | // StartSpan creates and starts a span. | [
"StartSpan",
"creates",
"and",
"starts",
"a",
"span",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer.go#L84-L153 | train |
openzipkin/zipkin-go | tracer.go | Extract | func (t *Tracer) Extract(extractor propagation.Extractor) (sc model.SpanContext) {
if atomic.LoadInt32(&t.noop) == 1 {
return
}
psc, err := extractor()
if psc != nil {
sc = *psc
}
sc.Err = err
return
} | go | func (t *Tracer) Extract(extractor propagation.Extractor) (sc model.SpanContext) {
if atomic.LoadInt32(&t.noop) == 1 {
return
}
psc, err := extractor()
if psc != nil {
sc = *psc
}
sc.Err = err
return
} | [
"func",
"(",
"t",
"*",
"Tracer",
")",
"Extract",
"(",
"extractor",
"propagation",
".",
"Extractor",
")",
"(",
"sc",
"model",
".",
"SpanContext",
")",
"{",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"noop",
")",
"==",
"1",
"{",
"return",
... | // Extract extracts a SpanContext using the provided Extractor function. | [
"Extract",
"extracts",
"a",
"SpanContext",
"using",
"the",
"provided",
"Extractor",
"function",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer.go#L156-L166 | train |
openzipkin/zipkin-go | tracer.go | SetNoop | func (t *Tracer) SetNoop(noop bool) {
if noop {
atomic.CompareAndSwapInt32(&t.noop, 0, 1)
} else {
atomic.CompareAndSwapInt32(&t.noop, 1, 0)
}
} | go | func (t *Tracer) SetNoop(noop bool) {
if noop {
atomic.CompareAndSwapInt32(&t.noop, 0, 1)
} else {
atomic.CompareAndSwapInt32(&t.noop, 1, 0)
}
} | [
"func",
"(",
"t",
"*",
"Tracer",
")",
"SetNoop",
"(",
"noop",
"bool",
")",
"{",
"if",
"noop",
"{",
"atomic",
".",
"CompareAndSwapInt32",
"(",
"&",
"t",
".",
"noop",
",",
"0",
",",
"1",
")",
"\n",
"}",
"else",
"{",
"atomic",
".",
"CompareAndSwapInt3... | // SetNoop allows for killswitch behavior. If set to true the tracer will return
// noopSpans and all data is dropped. This allows operators to stop tracing in
// risk scenarios. Set back to false to resume tracing. | [
"SetNoop",
"allows",
"for",
"killswitch",
"behavior",
".",
"If",
"set",
"to",
"true",
"the",
"tracer",
"will",
"return",
"noopSpans",
"and",
"all",
"data",
"is",
"dropped",
".",
"This",
"allows",
"operators",
"to",
"stop",
"tracing",
"in",
"risk",
"scenarios... | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer.go#L171-L177 | train |
openzipkin/zipkin-go | tracer.go | LocalEndpoint | func (t *Tracer) LocalEndpoint() *model.Endpoint {
if t.localEndpoint == nil {
return nil
}
ep := *t.localEndpoint
return &ep
} | go | func (t *Tracer) LocalEndpoint() *model.Endpoint {
if t.localEndpoint == nil {
return nil
}
ep := *t.localEndpoint
return &ep
} | [
"func",
"(",
"t",
"*",
"Tracer",
")",
"LocalEndpoint",
"(",
")",
"*",
"model",
".",
"Endpoint",
"{",
"if",
"t",
".",
"localEndpoint",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"ep",
":=",
"*",
"t",
".",
"localEndpoint",
"\n",
"return",
"&... | // LocalEndpoint returns a copy of the currently set local endpoint of the
// tracer instance. | [
"LocalEndpoint",
"returns",
"a",
"copy",
"of",
"the",
"currently",
"set",
"local",
"endpoint",
"of",
"the",
"tracer",
"instance",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer.go#L181-L187 | train |
openzipkin/zipkin-go | endpoint.go | NewEndpoint | func NewEndpoint(serviceName string, hostPort string) (*model.Endpoint, error) {
e := &model.Endpoint{
ServiceName: serviceName,
}
if hostPort == "" || hostPort == ":0" {
if serviceName == "" {
// if all properties are empty we should not have an Endpoint object.
return nil, nil
}
return e, nil
}
if strings.IndexByte(hostPort, ':') < 0 {
hostPort += ":0"
}
host, port, err := net.SplitHostPort(hostPort)
if err != nil {
return nil, err
}
p, err := strconv.ParseUint(port, 10, 16)
if err != nil {
return nil, err
}
e.Port = uint16(p)
addrs, err := net.LookupIP(host)
if err != nil {
return nil, err
}
for i := range addrs {
addr := addrs[i].To4()
if addr == nil {
// IPv6 - 16 bytes
if e.IPv6 == nil {
e.IPv6 = addrs[i].To16()
}
} else {
// IPv4 - 4 bytes
if e.IPv4 == nil {
e.IPv4 = addr
}
}
if e.IPv4 != nil && e.IPv6 != nil {
// Both IPv4 & IPv6 have been set, done...
break
}
}
return e, nil
} | go | func NewEndpoint(serviceName string, hostPort string) (*model.Endpoint, error) {
e := &model.Endpoint{
ServiceName: serviceName,
}
if hostPort == "" || hostPort == ":0" {
if serviceName == "" {
// if all properties are empty we should not have an Endpoint object.
return nil, nil
}
return e, nil
}
if strings.IndexByte(hostPort, ':') < 0 {
hostPort += ":0"
}
host, port, err := net.SplitHostPort(hostPort)
if err != nil {
return nil, err
}
p, err := strconv.ParseUint(port, 10, 16)
if err != nil {
return nil, err
}
e.Port = uint16(p)
addrs, err := net.LookupIP(host)
if err != nil {
return nil, err
}
for i := range addrs {
addr := addrs[i].To4()
if addr == nil {
// IPv6 - 16 bytes
if e.IPv6 == nil {
e.IPv6 = addrs[i].To16()
}
} else {
// IPv4 - 4 bytes
if e.IPv4 == nil {
e.IPv4 = addr
}
}
if e.IPv4 != nil && e.IPv6 != nil {
// Both IPv4 & IPv6 have been set, done...
break
}
}
return e, nil
} | [
"func",
"NewEndpoint",
"(",
"serviceName",
"string",
",",
"hostPort",
"string",
")",
"(",
"*",
"model",
".",
"Endpoint",
",",
"error",
")",
"{",
"e",
":=",
"&",
"model",
".",
"Endpoint",
"{",
"ServiceName",
":",
"serviceName",
",",
"}",
"\n",
"if",
"ho... | // NewEndpoint creates a new endpoint given the provided serviceName and
// hostPort. | [
"NewEndpoint",
"creates",
"a",
"new",
"endpoint",
"given",
"the",
"provided",
"serviceName",
"and",
"hostPort",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/endpoint.go#L27-L80 | train |
openzipkin/zipkin-go | reporter/kafka/kafka.go | Producer | func Producer(p sarama.AsyncProducer) ReporterOption {
return func(c *kafkaReporter) {
c.producer = p
}
} | go | func Producer(p sarama.AsyncProducer) ReporterOption {
return func(c *kafkaReporter) {
c.producer = p
}
} | [
"func",
"Producer",
"(",
"p",
"sarama",
".",
"AsyncProducer",
")",
"ReporterOption",
"{",
"return",
"func",
"(",
"c",
"*",
"kafkaReporter",
")",
"{",
"c",
".",
"producer",
"=",
"p",
"\n",
"}",
"\n",
"}"
] | // Producer sets the producer used to produce to Kafka. | [
"Producer",
"sets",
"the",
"producer",
"used",
"to",
"produce",
"to",
"Kafka",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/kafka/kafka.go#L56-L60 | train |
openzipkin/zipkin-go | middleware/grpc/server.go | NewServerHandler | func NewServerHandler(tracer *zipkin.Tracer, options ...ServerOption) stats.Handler {
c := &serverHandler{
tracer: tracer,
}
for _, option := range options {
option(c)
}
return c
} | go | func NewServerHandler(tracer *zipkin.Tracer, options ...ServerOption) stats.Handler {
c := &serverHandler{
tracer: tracer,
}
for _, option := range options {
option(c)
}
return c
} | [
"func",
"NewServerHandler",
"(",
"tracer",
"*",
"zipkin",
".",
"Tracer",
",",
"options",
"...",
"ServerOption",
")",
"stats",
".",
"Handler",
"{",
"c",
":=",
"&",
"serverHandler",
"{",
"tracer",
":",
"tracer",
",",
"}",
"\n",
"for",
"_",
",",
"option",
... | // NewServerHandler returns a stats.Handler which can be used with grpc.WithStatsHandler to add
// tracing to a gRPC server. The gRPC method name is used as the span name and by default the only
// tags are the gRPC status code if the call fails. Use ServerTags to add additional tags that
// should be applied to all spans. | [
"NewServerHandler",
"returns",
"a",
"stats",
".",
"Handler",
"which",
"can",
"be",
"used",
"with",
"grpc",
".",
"WithStatsHandler",
"to",
"add",
"tracing",
"to",
"a",
"gRPC",
"server",
".",
"The",
"gRPC",
"method",
"name",
"is",
"used",
"as",
"the",
"span"... | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/grpc/server.go#L46-L54 | train |
openzipkin/zipkin-go | span_options.go | Kind | func Kind(kind model.Kind) SpanOption {
return func(t *Tracer, s *spanImpl) {
s.Kind = kind
}
} | go | func Kind(kind model.Kind) SpanOption {
return func(t *Tracer, s *spanImpl) {
s.Kind = kind
}
} | [
"func",
"Kind",
"(",
"kind",
"model",
".",
"Kind",
")",
"SpanOption",
"{",
"return",
"func",
"(",
"t",
"*",
"Tracer",
",",
"s",
"*",
"spanImpl",
")",
"{",
"s",
".",
"Kind",
"=",
"kind",
"\n",
"}",
"\n",
"}"
] | // Kind sets the kind of the span being created.. | [
"Kind",
"sets",
"the",
"kind",
"of",
"the",
"span",
"being",
"created",
".."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/span_options.go#L28-L32 | train |
openzipkin/zipkin-go | span_options.go | Parent | func Parent(sc model.SpanContext) SpanOption {
return func(t *Tracer, s *spanImpl) {
if sc.Err != nil {
// encountered an extraction error
switch t.extractFailurePolicy {
case ExtractFailurePolicyRestart:
case ExtractFailurePolicyError:
panic(s.SpanContext.Err)
case ExtractFailurePolicyTagAndRestart:
s.Tags["error.extract"] = sc.Err.Error()
default:
panic(ErrInvalidExtractFailurePolicy)
}
/* don't use provided SpanContext, but restart trace */
return
}
s.SpanContext = sc
}
} | go | func Parent(sc model.SpanContext) SpanOption {
return func(t *Tracer, s *spanImpl) {
if sc.Err != nil {
// encountered an extraction error
switch t.extractFailurePolicy {
case ExtractFailurePolicyRestart:
case ExtractFailurePolicyError:
panic(s.SpanContext.Err)
case ExtractFailurePolicyTagAndRestart:
s.Tags["error.extract"] = sc.Err.Error()
default:
panic(ErrInvalidExtractFailurePolicy)
}
/* don't use provided SpanContext, but restart trace */
return
}
s.SpanContext = sc
}
} | [
"func",
"Parent",
"(",
"sc",
"model",
".",
"SpanContext",
")",
"SpanOption",
"{",
"return",
"func",
"(",
"t",
"*",
"Tracer",
",",
"s",
"*",
"spanImpl",
")",
"{",
"if",
"sc",
".",
"Err",
"!=",
"nil",
"{",
"switch",
"t",
".",
"extractFailurePolicy",
"{... | // Parent will use provided SpanContext as parent to the span being created. | [
"Parent",
"will",
"use",
"provided",
"SpanContext",
"as",
"parent",
"to",
"the",
"span",
"being",
"created",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/span_options.go#L35-L53 | train |
openzipkin/zipkin-go | span_options.go | StartTime | func StartTime(start time.Time) SpanOption {
return func(t *Tracer, s *spanImpl) {
s.Timestamp = start
}
} | go | func StartTime(start time.Time) SpanOption {
return func(t *Tracer, s *spanImpl) {
s.Timestamp = start
}
} | [
"func",
"StartTime",
"(",
"start",
"time",
".",
"Time",
")",
"SpanOption",
"{",
"return",
"func",
"(",
"t",
"*",
"Tracer",
",",
"s",
"*",
"spanImpl",
")",
"{",
"s",
".",
"Timestamp",
"=",
"start",
"\n",
"}",
"\n",
"}"
] | // StartTime uses a given start time for the span being created. | [
"StartTime",
"uses",
"a",
"given",
"start",
"time",
"for",
"the",
"span",
"being",
"created",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/span_options.go#L56-L60 | train |
openzipkin/zipkin-go | span_options.go | RemoteEndpoint | func RemoteEndpoint(e *model.Endpoint) SpanOption {
return func(t *Tracer, s *spanImpl) {
s.RemoteEndpoint = e
}
} | go | func RemoteEndpoint(e *model.Endpoint) SpanOption {
return func(t *Tracer, s *spanImpl) {
s.RemoteEndpoint = e
}
} | [
"func",
"RemoteEndpoint",
"(",
"e",
"*",
"model",
".",
"Endpoint",
")",
"SpanOption",
"{",
"return",
"func",
"(",
"t",
"*",
"Tracer",
",",
"s",
"*",
"spanImpl",
")",
"{",
"s",
".",
"RemoteEndpoint",
"=",
"e",
"\n",
"}",
"\n",
"}"
] | // RemoteEndpoint sets the remote endpoint of the span being created. | [
"RemoteEndpoint",
"sets",
"the",
"remote",
"endpoint",
"of",
"the",
"span",
"being",
"created",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/span_options.go#L63-L67 | train |
openzipkin/zipkin-go | span_options.go | Tags | func Tags(tags map[string]string) SpanOption {
return func(t *Tracer, s *spanImpl) {
for k, v := range tags {
s.Tags[k] = v
}
}
} | go | func Tags(tags map[string]string) SpanOption {
return func(t *Tracer, s *spanImpl) {
for k, v := range tags {
s.Tags[k] = v
}
}
} | [
"func",
"Tags",
"(",
"tags",
"map",
"[",
"string",
"]",
"string",
")",
"SpanOption",
"{",
"return",
"func",
"(",
"t",
"*",
"Tracer",
",",
"s",
"*",
"spanImpl",
")",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"tags",
"{",
"s",
".",
"Tags",
"[",
"... | // Tags sets initial tags for the span being created. If default tracer tags
// are present they will be overwritten on key collisions. | [
"Tags",
"sets",
"initial",
"tags",
"for",
"the",
"span",
"being",
"created",
".",
"If",
"default",
"tracer",
"tags",
"are",
"present",
"they",
"will",
"be",
"overwritten",
"on",
"key",
"collisions",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/span_options.go#L71-L77 | train |
openzipkin/zipkin-go | model/traceid.go | String | func (t TraceID) String() string {
if t.High == 0 {
return fmt.Sprintf("%016x", t.Low)
}
return fmt.Sprintf("%016x%016x", t.High, t.Low)
} | go | func (t TraceID) String() string {
if t.High == 0 {
return fmt.Sprintf("%016x", t.Low)
}
return fmt.Sprintf("%016x%016x", t.High, t.Low)
} | [
"func",
"(",
"t",
"TraceID",
")",
"String",
"(",
")",
"string",
"{",
"if",
"t",
".",
"High",
"==",
"0",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%016x\"",
",",
"t",
".",
"Low",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\... | // String outputs the 128-bit traceID as hex string. | [
"String",
"outputs",
"the",
"128",
"-",
"bit",
"traceID",
"as",
"hex",
"string",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/traceid.go#L35-L40 | train |
openzipkin/zipkin-go | model/traceid.go | TraceIDFromHex | func TraceIDFromHex(h string) (t TraceID, err error) {
if len(h) > 16 {
if t.High, err = strconv.ParseUint(h[0:len(h)-16], 16, 64); err != nil {
return
}
t.Low, err = strconv.ParseUint(h[len(h)-16:], 16, 64)
return
}
t.Low, err = strconv.ParseUint(h, 16, 64)
return
} | go | func TraceIDFromHex(h string) (t TraceID, err error) {
if len(h) > 16 {
if t.High, err = strconv.ParseUint(h[0:len(h)-16], 16, 64); err != nil {
return
}
t.Low, err = strconv.ParseUint(h[len(h)-16:], 16, 64)
return
}
t.Low, err = strconv.ParseUint(h, 16, 64)
return
} | [
"func",
"TraceIDFromHex",
"(",
"h",
"string",
")",
"(",
"t",
"TraceID",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"h",
")",
">",
"16",
"{",
"if",
"t",
".",
"High",
",",
"err",
"=",
"strconv",
".",
"ParseUint",
"(",
"h",
"[",
"0",
":",
... | // TraceIDFromHex returns the TraceID from a hex string. | [
"TraceIDFromHex",
"returns",
"the",
"TraceID",
"from",
"a",
"hex",
"string",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/traceid.go#L43-L53 | train |
openzipkin/zipkin-go | model/traceid.go | MarshalJSON | func (t TraceID) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", t.String())), nil
} | go | func (t TraceID) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", t.String())), nil
} | [
"func",
"(",
"t",
"TraceID",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%q\"",
",",
"t",
".",
"String",
"(",
")",
")",
")",
",",
"nil",
"\n",
"}... | // MarshalJSON custom JSON serializer to export the TraceID in the required
// zero padded hex representation. | [
"MarshalJSON",
"custom",
"JSON",
"serializer",
"to",
"export",
"the",
"TraceID",
"in",
"the",
"required",
"zero",
"padded",
"hex",
"representation",
"."
] | a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962 | https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/traceid.go#L57-L59 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.