id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens listlengths 21 1.41k | docstring stringlengths 6 2.61k | docstring_tokens listlengths 3 215 | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9,400 | hyperhq/runv | hypervisor/fanout.go | CreateFanout | func CreateFanout(upstream chan *types.VmResponse, size int, block bool) *Fanout {
fo := &Fanout{
size: size,
upstream: upstream,
clients: []chan *types.VmResponse{},
closeSignal: make(chan *types.VmResponse, 1),
running: !block,
lock: sync.RWMutex{},
}
if !block {
fo.start()
}
return fo
} | go | func CreateFanout(upstream chan *types.VmResponse, size int, block bool) *Fanout {
fo := &Fanout{
size: size,
upstream: upstream,
clients: []chan *types.VmResponse{},
closeSignal: make(chan *types.VmResponse, 1),
running: !block,
lock: sync.RWMutex{},
}
if !block {
fo.start()
}
return fo
} | [
"func",
"CreateFanout",
"(",
"upstream",
"chan",
"*",
"types",
".",
"VmResponse",
",",
"size",
"int",
",",
"block",
"bool",
")",
"*",
"Fanout",
"{",
"fo",
":=",
"&",
"Fanout",
"{",
"size",
":",
"size",
",",
"upstream",
":",
"upstream",
",",
"clients",
... | // CreateFanout create a new fanout, and if it is non-blocked, it will start
// the fanout goroutine at once, otherwise it will start the goroutine when it
// get the first client | [
"CreateFanout",
"create",
"a",
"new",
"fanout",
"and",
"if",
"it",
"is",
"non",
"-",
"blocked",
"it",
"will",
"start",
"the",
"fanout",
"goroutine",
"at",
"once",
"otherwise",
"it",
"will",
"start",
"the",
"goroutine",
"when",
"it",
"get",
"the",
"first",
... | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/hypervisor/fanout.go#L22-L37 |
9,401 | hyperhq/runv | cli/spec.go | loadProcessConfig | func loadProcessConfig(path string) (*specs.Process, error) {
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("JSON configuration file for %s not found", path)
}
return nil, err
}
defer f.Close()
var s *specs.Process
if err := json.NewDecoder(f).Decode(&s); err != nil {
return nil, err
}
return s, nil
} | go | func loadProcessConfig(path string) (*specs.Process, error) {
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("JSON configuration file for %s not found", path)
}
return nil, err
}
defer f.Close()
var s *specs.Process
if err := json.NewDecoder(f).Decode(&s); err != nil {
return nil, err
}
return s, nil
} | [
"func",
"loadProcessConfig",
"(",
"path",
"string",
")",
"(",
"*",
"specs",
".",
"Process",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExist",
"(... | // loadProcessConfig loads the process configuration from the provided path. | [
"loadProcessConfig",
"loads",
"the",
"process",
"configuration",
"from",
"the",
"provided",
"path",
"."
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/spec.go#L114-L128 |
9,402 | hyperhq/runv | cli/filesystem.go | preCreateDirs | func preCreateDirs(rootfs string) error {
dirs := []string{
"proc",
"sys",
"dev",
"lib/modules",
}
for _, dir := range dirs {
err := createIfNotExists(filepath.Join(rootfs, dir), true)
if err != nil {
return err
}
}
return nil
} | go | func preCreateDirs(rootfs string) error {
dirs := []string{
"proc",
"sys",
"dev",
"lib/modules",
}
for _, dir := range dirs {
err := createIfNotExists(filepath.Join(rootfs, dir), true)
if err != nil {
return err
}
}
return nil
} | [
"func",
"preCreateDirs",
"(",
"rootfs",
"string",
")",
"error",
"{",
"dirs",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"}",
"\n",
"for",
"_",
",",
"dir",
":=",
"range",
"dirs",
"{",
"err"... | // preCreateDirs creates necessary dirs for hyperstart | [
"preCreateDirs",
"creates",
"necessary",
"dirs",
"for",
"hyperstart"
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/filesystem.go#L104-L118 |
9,403 | hyperhq/runv | hypervisor/network.go | allInterfaces | func (nc *NetworkContext) allInterfaces() (nics []*InterfaceCreated) {
nc.slotLock.Lock()
defer nc.slotLock.Unlock()
for _, v := range nc.eth {
if v != nil {
nics = append(nics, v)
}
}
return
} | go | func (nc *NetworkContext) allInterfaces() (nics []*InterfaceCreated) {
nc.slotLock.Lock()
defer nc.slotLock.Unlock()
for _, v := range nc.eth {
if v != nil {
nics = append(nics, v)
}
}
return
} | [
"func",
"(",
"nc",
"*",
"NetworkContext",
")",
"allInterfaces",
"(",
")",
"(",
"nics",
"[",
"]",
"*",
"InterfaceCreated",
")",
"{",
"nc",
".",
"slotLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"nc",
".",
"slotLock",
".",
"Unlock",
"(",
")",
"\n\n",
... | // allInterfaces return all the network interfaces except loop | [
"allInterfaces",
"return",
"all",
"the",
"network",
"interfaces",
"except",
"loop"
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/hypervisor/network.go#L223-L233 |
9,404 | hyperhq/runv | cli/sandbox.go | lockSandbox | func lockSandbox(sandboxPath string) (*os.File, error) {
lockFilePath := filepath.Join(sandboxPath, "sandbox.lock")
lockFile, err := os.OpenFile(lockFilePath, os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
return nil, err
}
err = syscall.Flock(int(lockFile.Fd()), syscall.LOCK_EX)
if err != nil {
lockFile.Close()
return nil, err
}
return lockFile, nil
} | go | func lockSandbox(sandboxPath string) (*os.File, error) {
lockFilePath := filepath.Join(sandboxPath, "sandbox.lock")
lockFile, err := os.OpenFile(lockFilePath, os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
return nil, err
}
err = syscall.Flock(int(lockFile.Fd()), syscall.LOCK_EX)
if err != nil {
lockFile.Close()
return nil, err
}
return lockFile, nil
} | [
"func",
"lockSandbox",
"(",
"sandboxPath",
"string",
")",
"(",
"*",
"os",
".",
"File",
",",
"error",
")",
"{",
"lockFilePath",
":=",
"filepath",
".",
"Join",
"(",
"sandboxPath",
",",
"\"",
"\"",
")",
"\n\n",
"lockFile",
",",
"err",
":=",
"os",
".",
"... | // lock locks the sandbox to prevent it from being accessed by other processes. | [
"lock",
"locks",
"the",
"sandbox",
"to",
"prevent",
"it",
"from",
"being",
"accessed",
"by",
"other",
"processes",
"."
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/sandbox.go#L257-L272 |
9,405 | hyperhq/runv | cli/sandbox.go | unlockSandbox | func unlockSandbox(lockFile *os.File) error {
if lockFile == nil {
return fmt.Errorf("lockFile cannot be empty")
}
err := syscall.Flock(int(lockFile.Fd()), syscall.LOCK_UN)
if err != nil {
return err
}
lockFile.Close()
return nil
} | go | func unlockSandbox(lockFile *os.File) error {
if lockFile == nil {
return fmt.Errorf("lockFile cannot be empty")
}
err := syscall.Flock(int(lockFile.Fd()), syscall.LOCK_UN)
if err != nil {
return err
}
lockFile.Close()
return nil
} | [
"func",
"unlockSandbox",
"(",
"lockFile",
"*",
"os",
".",
"File",
")",
"error",
"{",
"if",
"lockFile",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"syscall",
".",
"Flock",
"(",
"int",
"(",... | // unlock unlocks the sandbox to allow it being accessed by other processes. | [
"unlock",
"unlocks",
"the",
"sandbox",
"to",
"allow",
"it",
"being",
"accessed",
"by",
"other",
"processes",
"."
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/sandbox.go#L275-L288 |
9,406 | hyperhq/runv | hypervisor/context.go | SendVmEvent | func (ctx *VmContext) SendVmEvent(ev VmEvent) error {
ctx.lock.RLock()
defer ctx.lock.RUnlock()
if ctx.handler == nil {
return fmt.Errorf("VmContext(%s): event handler already shutdown.", ctx.Id)
}
ctx.Hub <- ev
return nil
} | go | func (ctx *VmContext) SendVmEvent(ev VmEvent) error {
ctx.lock.RLock()
defer ctx.lock.RUnlock()
if ctx.handler == nil {
return fmt.Errorf("VmContext(%s): event handler already shutdown.", ctx.Id)
}
ctx.Hub <- ev
return nil
} | [
"func",
"(",
"ctx",
"*",
"VmContext",
")",
"SendVmEvent",
"(",
"ev",
"VmEvent",
")",
"error",
"{",
"ctx",
".",
"lock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"ctx",
".",
"lock",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"ctx",
".",
"handler",
"==",
... | // SendVmEvent enqueues a VmEvent onto the context. Returns an error if there is
// no handler associated with the context. VmEvent handling happens in a
// separate goroutine, so this is thread-safe and asynchronous. | [
"SendVmEvent",
"enqueues",
"a",
"VmEvent",
"onto",
"the",
"context",
".",
"Returns",
"an",
"error",
"if",
"there",
"is",
"no",
"handler",
"associated",
"with",
"the",
"context",
".",
"VmEvent",
"handling",
"happens",
"in",
"a",
"separate",
"goroutine",
"so",
... | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/hypervisor/context.go#L145-L156 |
9,407 | hyperhq/runv | lib/telnet/conn.go | ReadByte | func (c *Conn) ReadByte() (b byte, err error) {
retry := true
for retry && err == nil {
b, retry, err = c.tryReadByte()
}
return
} | go | func (c *Conn) ReadByte() (b byte, err error) {
retry := true
for retry && err == nil {
b, retry, err = c.tryReadByte()
}
return
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"ReadByte",
"(",
")",
"(",
"b",
"byte",
",",
"err",
"error",
")",
"{",
"retry",
":=",
"true",
"\n",
"for",
"retry",
"&&",
"err",
"==",
"nil",
"{",
"b",
",",
"retry",
",",
"err",
"=",
"c",
".",
"tryReadByte",
... | // ReadByte works like bufio.ReadByte | [
"ReadByte",
"works",
"like",
"bufio",
".",
"ReadByte"
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L207-L213 |
9,408 | hyperhq/runv | lib/telnet/conn.go | ReadRune | func (c *Conn) ReadRune() (r rune, size int, err error) {
loop:
r, size, err = c.r.ReadRune()
if err != nil {
return
}
if r != unicode.ReplacementChar || size != 1 {
// Properly readed rune
return
}
// Bad rune
err = c.r.UnreadRune()
if err != nil {
return
}
// Read telnet command or escaped IAC
_, retry, err := c.tryReadByte()
if err != nil {
return
}
if retry {
// This bad rune was a beginning of telnet command. Try read next rune.
goto loop
}
// Return escaped IAC as unicode.ReplacementChar
return
} | go | func (c *Conn) ReadRune() (r rune, size int, err error) {
loop:
r, size, err = c.r.ReadRune()
if err != nil {
return
}
if r != unicode.ReplacementChar || size != 1 {
// Properly readed rune
return
}
// Bad rune
err = c.r.UnreadRune()
if err != nil {
return
}
// Read telnet command or escaped IAC
_, retry, err := c.tryReadByte()
if err != nil {
return
}
if retry {
// This bad rune was a beginning of telnet command. Try read next rune.
goto loop
}
// Return escaped IAC as unicode.ReplacementChar
return
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"ReadRune",
"(",
")",
"(",
"r",
"rune",
",",
"size",
"int",
",",
"err",
"error",
")",
"{",
"loop",
":",
"r",
",",
"size",
",",
"err",
"=",
"c",
".",
"r",
".",
"ReadRune",
"(",
")",
"\n",
"if",
"err",
"!="... | // ReadRune works like bufio.ReadRune | [
"ReadRune",
"works",
"like",
"bufio",
".",
"ReadRune"
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L216-L242 |
9,409 | hyperhq/runv | lib/telnet/conn.go | Read | func (c *Conn) Read(buf []byte) (int, error) {
var n int
for n < len(buf) {
b, err := c.ReadByte()
if err != nil {
return n, err
}
//log.Printf("char: %d %q", b, b)
buf[n] = b
n++
if c.r.Buffered() == 0 {
// Try don't block if can return some data
break
}
}
return n, nil
} | go | func (c *Conn) Read(buf []byte) (int, error) {
var n int
for n < len(buf) {
b, err := c.ReadByte()
if err != nil {
return n, err
}
//log.Printf("char: %d %q", b, b)
buf[n] = b
n++
if c.r.Buffered() == 0 {
// Try don't block if can return some data
break
}
}
return n, nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Read",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"var",
"n",
"int",
"\n",
"for",
"n",
"<",
"len",
"(",
"buf",
")",
"{",
"b",
",",
"err",
":=",
"c",
".",
"ReadByte",
"(",
")... | // Read is for implement an io.Reader interface | [
"Read",
"is",
"for",
"implement",
"an",
"io",
".",
"Reader",
"interface"
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L245-L261 |
9,410 | hyperhq/runv | lib/telnet/conn.go | ReadBytes | func (c *Conn) ReadBytes(delim byte) ([]byte, error) {
var line []byte
for {
b, err := c.ReadByte()
if err != nil {
return nil, err
}
line = append(line, b)
if b == delim {
break
}
}
return line, nil
} | go | func (c *Conn) ReadBytes(delim byte) ([]byte, error) {
var line []byte
for {
b, err := c.ReadByte()
if err != nil {
return nil, err
}
line = append(line, b)
if b == delim {
break
}
}
return line, nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"ReadBytes",
"(",
"delim",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"line",
"[",
"]",
"byte",
"\n",
"for",
"{",
"b",
",",
"err",
":=",
"c",
".",
"ReadByte",
"(",
")",
"\n",
"if",
... | // ReadBytes works like bufio.ReadBytes | [
"ReadBytes",
"works",
"like",
"bufio",
".",
"ReadBytes"
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L264-L277 |
9,411 | hyperhq/runv | lib/telnet/conn.go | SkipBytes | func (c *Conn) SkipBytes(delim byte) error {
for {
b, err := c.ReadByte()
if err != nil {
return err
}
if b == delim {
break
}
}
return nil
} | go | func (c *Conn) SkipBytes(delim byte) error {
for {
b, err := c.ReadByte()
if err != nil {
return err
}
if b == delim {
break
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"SkipBytes",
"(",
"delim",
"byte",
")",
"error",
"{",
"for",
"{",
"b",
",",
"err",
":=",
"c",
".",
"ReadByte",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"b",
"==... | // SkipBytes works like ReadBytes but skips all read data. | [
"SkipBytes",
"works",
"like",
"ReadBytes",
"but",
"skips",
"all",
"read",
"data",
"."
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L280-L291 |
9,412 | hyperhq/runv | lib/telnet/conn.go | ReadString | func (c *Conn) ReadString(delim byte) (string, error) {
bytes, err := c.ReadBytes(delim)
return string(bytes), err
} | go | func (c *Conn) ReadString(delim byte) (string, error) {
bytes, err := c.ReadBytes(delim)
return string(bytes), err
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"ReadString",
"(",
"delim",
"byte",
")",
"(",
"string",
",",
"error",
")",
"{",
"bytes",
",",
"err",
":=",
"c",
".",
"ReadBytes",
"(",
"delim",
")",
"\n",
"return",
"string",
"(",
"bytes",
")",
",",
"err",
"\n"... | // ReadString works like bufio.ReadString | [
"ReadString",
"works",
"like",
"bufio",
".",
"ReadString"
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L294-L297 |
9,413 | hyperhq/runv | lib/telnet/conn.go | ReadUntilIndex | func (c *Conn) ReadUntilIndex(delims ...string) ([]byte, int, error) {
return c.readUntil(true, delims...)
} | go | func (c *Conn) ReadUntilIndex(delims ...string) ([]byte, int, error) {
return c.readUntil(true, delims...)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"ReadUntilIndex",
"(",
"delims",
"...",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"int",
",",
"error",
")",
"{",
"return",
"c",
".",
"readUntil",
"(",
"true",
",",
"delims",
"...",
")",
"\n",
"}"
] | // ReadUntilIndex reads from connection until one of delimiters occurs. Returns
// read data and an index of delimiter or error. | [
"ReadUntilIndex",
"reads",
"from",
"connection",
"until",
"one",
"of",
"delimiters",
"occurs",
".",
"Returns",
"read",
"data",
"and",
"an",
"index",
"of",
"delimiter",
"or",
"error",
"."
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L334-L336 |
9,414 | hyperhq/runv | lib/telnet/conn.go | ReadUntil | func (c *Conn) ReadUntil(delims ...string) ([]byte, error) {
d, _, err := c.readUntil(true, delims...)
return d, err
} | go | func (c *Conn) ReadUntil(delims ...string) ([]byte, error) {
d, _, err := c.readUntil(true, delims...)
return d, err
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"ReadUntil",
"(",
"delims",
"...",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"d",
",",
"_",
",",
"err",
":=",
"c",
".",
"readUntil",
"(",
"true",
",",
"delims",
"...",
")",
"\n",
"return",... | // ReadUntil works like ReadUntilIndex but don't return a delimiter index. | [
"ReadUntil",
"works",
"like",
"ReadUntilIndex",
"but",
"don",
"t",
"return",
"a",
"delimiter",
"index",
"."
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L339-L342 |
9,415 | hyperhq/runv | lib/telnet/conn.go | SkipUntilIndex | func (c *Conn) SkipUntilIndex(delims ...string) (int, error) {
_, i, err := c.readUntil(false, delims...)
return i, err
} | go | func (c *Conn) SkipUntilIndex(delims ...string) (int, error) {
_, i, err := c.readUntil(false, delims...)
return i, err
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"SkipUntilIndex",
"(",
"delims",
"...",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"_",
",",
"i",
",",
"err",
":=",
"c",
".",
"readUntil",
"(",
"false",
",",
"delims",
"...",
")",
"\n",
"return",
"i",
... | // SkipUntilIndex works like ReadUntilIndex but skips all read data. | [
"SkipUntilIndex",
"works",
"like",
"ReadUntilIndex",
"but",
"skips",
"all",
"read",
"data",
"."
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L345-L348 |
9,416 | hyperhq/runv | lib/telnet/conn.go | SkipUntil | func (c *Conn) SkipUntil(delims ...string) error {
_, _, err := c.readUntil(false, delims...)
return err
} | go | func (c *Conn) SkipUntil(delims ...string) error {
_, _, err := c.readUntil(false, delims...)
return err
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"SkipUntil",
"(",
"delims",
"...",
"string",
")",
"error",
"{",
"_",
",",
"_",
",",
"err",
":=",
"c",
".",
"readUntil",
"(",
"false",
",",
"delims",
"...",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // SkipUntil works like ReadUntil but skips all read data. | [
"SkipUntil",
"works",
"like",
"ReadUntil",
"but",
"skips",
"all",
"read",
"data",
"."
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L351-L354 |
9,417 | hyperhq/runv | lib/telnet/conn.go | Write | func (c *Conn) Write(buf []byte) (int, error) {
search := "\xff"
if c.unixWriteMode {
search = "\xff\n"
}
var (
n int
err error
)
for len(buf) > 0 {
var k int
i := bytes.IndexAny(buf, search)
if i == -1 {
k, err = c.Conn.Write(buf)
n += k
break
}
k, err = c.Conn.Write(buf[:i])
n += k
if err != nil {
break
}
switch buf[i] {
case LF:
k, err = c.Conn.Write([]byte{CR, LF})
case cmdIAC:
k, err = c.Conn.Write([]byte{cmdIAC, cmdIAC})
}
n += k
if err != nil {
break
}
buf = buf[i+1:]
}
return n, err
} | go | func (c *Conn) Write(buf []byte) (int, error) {
search := "\xff"
if c.unixWriteMode {
search = "\xff\n"
}
var (
n int
err error
)
for len(buf) > 0 {
var k int
i := bytes.IndexAny(buf, search)
if i == -1 {
k, err = c.Conn.Write(buf)
n += k
break
}
k, err = c.Conn.Write(buf[:i])
n += k
if err != nil {
break
}
switch buf[i] {
case LF:
k, err = c.Conn.Write([]byte{CR, LF})
case cmdIAC:
k, err = c.Conn.Write([]byte{cmdIAC, cmdIAC})
}
n += k
if err != nil {
break
}
buf = buf[i+1:]
}
return n, err
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Write",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"search",
":=",
"\"",
"\\xff",
"\"",
"\n",
"if",
"c",
".",
"unixWriteMode",
"{",
"search",
"=",
"\"",
"\\xff",
"\\n",
"\"",
"\n"... | // Write is for implement an io.Writer interface | [
"Write",
"is",
"for",
"implement",
"an",
"io",
".",
"Writer",
"interface"
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L357-L392 |
9,418 | hyperhq/runv | hypervisor/vm.go | AssociateVm | func AssociateVm(vmId string, data []byte) (*Vm, error) {
var (
PodEvent = make(chan VmEvent, 128)
Status = make(chan *types.VmResponse, 128)
err error
)
vm := newVm(vmId, 0, 0)
vm.ctx, err = VmAssociate(vm.Id, PodEvent, Status, data)
if err != nil {
vm.Log(ERROR, "cannot associate with vm: %v", err)
return nil, err
}
vm.clients = CreateFanout(Status, 128, false)
return vm, nil
} | go | func AssociateVm(vmId string, data []byte) (*Vm, error) {
var (
PodEvent = make(chan VmEvent, 128)
Status = make(chan *types.VmResponse, 128)
err error
)
vm := newVm(vmId, 0, 0)
vm.ctx, err = VmAssociate(vm.Id, PodEvent, Status, data)
if err != nil {
vm.Log(ERROR, "cannot associate with vm: %v", err)
return nil, err
}
vm.clients = CreateFanout(Status, 128, false)
return vm, nil
} | [
"func",
"AssociateVm",
"(",
"vmId",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"*",
"Vm",
",",
"error",
")",
"{",
"var",
"(",
"PodEvent",
"=",
"make",
"(",
"chan",
"VmEvent",
",",
"128",
")",
"\n",
"Status",
"=",
"make",
"(",
"chan",
"*",... | // This function will only be invoked during daemon start | [
"This",
"function",
"will",
"only",
"be",
"invoked",
"during",
"daemon",
"start"
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/hypervisor/vm.go#L83-L99 |
9,419 | hyperhq/runv | cli/network.go | setupNetworkNsTrap | func setupNetworkNsTrap(netNs2Containerd func(NetlinkUpdate)) {
// Subscribe for links change event
chLink := make(chan netlink.LinkUpdate)
doneLink := make(chan struct{})
defer close(doneLink)
if err := netlink.LinkSubscribe(chLink, doneLink); err != nil {
glog.Fatal(err)
}
// Subscribe for addresses change event
chAddr := make(chan netlink.AddrUpdate)
doneAddr := make(chan struct{})
defer close(doneAddr)
if err := netlink.AddrSubscribe(chAddr, doneAddr); err != nil {
glog.Fatal(err)
}
// Subscribe for route change event
chRoute := make(chan netlink.RouteUpdate)
doneRoute := make(chan struct{})
defer close(doneRoute)
if err := netlink.RouteSubscribe(chRoute, doneRoute); err != nil {
glog.Fatal(err)
}
for {
select {
case updateLink := <-chLink:
handleLink(updateLink, netNs2Containerd)
case updateAddr := <-chAddr:
handleAddr(updateAddr, netNs2Containerd)
case updateRoute := <-chRoute:
handleRoute(updateRoute, netNs2Containerd)
}
}
} | go | func setupNetworkNsTrap(netNs2Containerd func(NetlinkUpdate)) {
// Subscribe for links change event
chLink := make(chan netlink.LinkUpdate)
doneLink := make(chan struct{})
defer close(doneLink)
if err := netlink.LinkSubscribe(chLink, doneLink); err != nil {
glog.Fatal(err)
}
// Subscribe for addresses change event
chAddr := make(chan netlink.AddrUpdate)
doneAddr := make(chan struct{})
defer close(doneAddr)
if err := netlink.AddrSubscribe(chAddr, doneAddr); err != nil {
glog.Fatal(err)
}
// Subscribe for route change event
chRoute := make(chan netlink.RouteUpdate)
doneRoute := make(chan struct{})
defer close(doneRoute)
if err := netlink.RouteSubscribe(chRoute, doneRoute); err != nil {
glog.Fatal(err)
}
for {
select {
case updateLink := <-chLink:
handleLink(updateLink, netNs2Containerd)
case updateAddr := <-chAddr:
handleAddr(updateAddr, netNs2Containerd)
case updateRoute := <-chRoute:
handleRoute(updateRoute, netNs2Containerd)
}
}
} | [
"func",
"setupNetworkNsTrap",
"(",
"netNs2Containerd",
"func",
"(",
"NetlinkUpdate",
")",
")",
"{",
"// Subscribe for links change event",
"chLink",
":=",
"make",
"(",
"chan",
"netlink",
".",
"LinkUpdate",
")",
"\n",
"doneLink",
":=",
"make",
"(",
"chan",
"struct"... | // This function should be put into the main process or somewhere that can be
// use to init the network namespace trap. | [
"This",
"function",
"should",
"be",
"put",
"into",
"the",
"main",
"process",
"or",
"somewhere",
"that",
"can",
"be",
"use",
"to",
"init",
"the",
"network",
"namespace",
"trap",
"."
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/network.go#L501-L536 |
9,420 | hyperhq/runv | cli/list.go | fatal | func fatal(err error) {
// make sure the error is written to the logger
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
} | go | func fatal(err error) {
// make sure the error is written to the logger
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
} | [
"func",
"fatal",
"(",
"err",
"error",
")",
"{",
"// make sure the error is written to the logger",
"fmt",
".",
"Fprintln",
"(",
"os",
".",
"Stderr",
",",
"err",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // fatal prints the error's details if it is a runv specific error type
// then exits the program with an exit status of 1. | [
"fatal",
"prints",
"the",
"error",
"s",
"details",
"if",
"it",
"is",
"a",
"runv",
"specific",
"error",
"type",
"then",
"exits",
"the",
"program",
"with",
"an",
"exit",
"status",
"of",
"1",
"."
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/list.go#L142-L146 |
9,421 | hyperhq/runv | hypervisor/errors.go | NewSpecError | func NewSpecError(id, cause string) *CommonError {
return &CommonError{
errType: ET_SPEC,
contextId: id,
cause: "spec error: " + cause,
}
} | go | func NewSpecError(id, cause string) *CommonError {
return &CommonError{
errType: ET_SPEC,
contextId: id,
cause: "spec error: " + cause,
}
} | [
"func",
"NewSpecError",
"(",
"id",
",",
"cause",
"string",
")",
"*",
"CommonError",
"{",
"return",
"&",
"CommonError",
"{",
"errType",
":",
"ET_SPEC",
",",
"contextId",
":",
"id",
",",
"cause",
":",
"\"",
"\"",
"+",
"cause",
",",
"}",
"\n",
"}"
] | // Error in spec, which is either mistake format or content inconsistency, and
// is checked when elements are being added to Sandbox. | [
"Error",
"in",
"spec",
"which",
"is",
"either",
"mistake",
"format",
"or",
"content",
"inconsistency",
"and",
"is",
"checked",
"when",
"elements",
"are",
"being",
"added",
"to",
"Sandbox",
"."
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/hypervisor/errors.go#L44-L50 |
9,422 | hyperhq/runv | hypervisor/kvmtool/lkvm_arm64.go | getGicInfo | func getGicInfo() (info string) {
gicinfo, err := os.Open("/proc/interrupts")
if err != nil {
return "unknown"
}
defer gicinfo.Close()
scanner := bufio.NewScanner(gicinfo)
for scanner.Scan() {
newline := scanner.Text()
list := strings.Fields(newline)
for _, item := range list {
if strings.EqualFold(item, "GICv2") {
return "gicv2"
} else if strings.EqualFold(item, "GICv3") ||
strings.EqualFold(item, "GICv4") {
return "gicv3"
}
}
}
return "unknown"
} | go | func getGicInfo() (info string) {
gicinfo, err := os.Open("/proc/interrupts")
if err != nil {
return "unknown"
}
defer gicinfo.Close()
scanner := bufio.NewScanner(gicinfo)
for scanner.Scan() {
newline := scanner.Text()
list := strings.Fields(newline)
for _, item := range list {
if strings.EqualFold(item, "GICv2") {
return "gicv2"
} else if strings.EqualFold(item, "GICv3") ||
strings.EqualFold(item, "GICv4") {
return "gicv3"
}
}
}
return "unknown"
} | [
"func",
"getGicInfo",
"(",
")",
"(",
"info",
"string",
")",
"{",
"gicinfo",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"defer",
"gicinfo",
".",
"Close",... | // On ARM platform, we have different gic interrupt controllers.
// We have to detect the correct gic chip to set parameter for lkvm. | [
"On",
"ARM",
"platform",
"we",
"have",
"different",
"gic",
"interrupt",
"controllers",
".",
"We",
"have",
"to",
"detect",
"the",
"correct",
"gic",
"chip",
"to",
"set",
"parameter",
"for",
"lkvm",
"."
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/hypervisor/kvmtool/lkvm_arm64.go#L13-L37 |
9,423 | hyperhq/runv | template/template.go | NewVmFromTemplate | func (t *TemplateVmConfig) NewVmFromTemplate(vmName string) (*hypervisor.Vm, error) {
return hypervisor.GetVm(vmName, t.BootConfigFromTemplate(), false)
} | go | func (t *TemplateVmConfig) NewVmFromTemplate(vmName string) (*hypervisor.Vm, error) {
return hypervisor.GetVm(vmName, t.BootConfigFromTemplate(), false)
} | [
"func",
"(",
"t",
"*",
"TemplateVmConfig",
")",
"NewVmFromTemplate",
"(",
"vmName",
"string",
")",
"(",
"*",
"hypervisor",
".",
"Vm",
",",
"error",
")",
"{",
"return",
"hypervisor",
".",
"GetVm",
"(",
"vmName",
",",
"t",
".",
"BootConfigFromTemplate",
"(",... | // boot vm from template, the returned vm is paused | [
"boot",
"vm",
"from",
"template",
"the",
"returned",
"vm",
"is",
"paused"
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/template/template.go#L113-L115 |
9,424 | hyperhq/runv | cli/process.go | NewProcessList | func NewProcessList(root, name string) (*ProcessList, error) {
f, err := os.OpenFile(filepath.Join(root, name, processJSON), os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return nil, err
}
if err = syscall.Flock(int(f.Fd()), syscall.LOCK_SH); err != nil {
f.Close()
return nil, fmt.Errorf("Placing LOCK_SH lock on process json file failed: %s", err.Error())
}
return &ProcessList{file: f}, nil
} | go | func NewProcessList(root, name string) (*ProcessList, error) {
f, err := os.OpenFile(filepath.Join(root, name, processJSON), os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return nil, err
}
if err = syscall.Flock(int(f.Fd()), syscall.LOCK_SH); err != nil {
f.Close()
return nil, fmt.Errorf("Placing LOCK_SH lock on process json file failed: %s", err.Error())
}
return &ProcessList{file: f}, nil
} | [
"func",
"NewProcessList",
"(",
"root",
",",
"name",
"string",
")",
"(",
"*",
"ProcessList",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"filepath",
".",
"Join",
"(",
"root",
",",
"name",
",",
"processJSON",
")",
",",
... | // Return locked processlist, which needs to be released by caller after using | [
"Return",
"locked",
"processlist",
"which",
"needs",
"to",
"be",
"released",
"by",
"caller",
"after",
"using"
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/process.go#L29-L41 |
9,425 | hyperhq/runv | agent/proxy/proxy.go | NewServer | func NewServer(address string, json agent.SandboxAgent) (*grpc.Server, error) {
s := grpc.NewServer()
jp := &jsonProxy{
json: json,
self: s,
}
kagenta.RegisterAgentServiceServer(s, jp)
healthServer := health.NewServer()
grpc_health_v1.RegisterHealthServer(s, healthServer)
return s, nil
} | go | func NewServer(address string, json agent.SandboxAgent) (*grpc.Server, error) {
s := grpc.NewServer()
jp := &jsonProxy{
json: json,
self: s,
}
kagenta.RegisterAgentServiceServer(s, jp)
healthServer := health.NewServer()
grpc_health_v1.RegisterHealthServer(s, healthServer)
return s, nil
} | [
"func",
"NewServer",
"(",
"address",
"string",
",",
"json",
"agent",
".",
"SandboxAgent",
")",
"(",
"*",
"grpc",
".",
"Server",
",",
"error",
")",
"{",
"s",
":=",
"grpc",
".",
"NewServer",
"(",
")",
"\n",
"jp",
":=",
"&",
"jsonProxy",
"{",
"json",
... | // NewServer initializes a brand new grpc server with registered grpc services | [
"NewServer",
"initializes",
"a",
"brand",
"new",
"grpc",
"server",
"with",
"registered",
"grpc",
"services"
] | 10eb6877d5df825f4438f69864a9256f9694741d | https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/agent/proxy/proxy.go#L222-L232 |
9,426 | denisbrodbeck/machineid | id_windows.go | machineID | func machineID() (string, error) {
k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Cryptography`, registry.QUERY_VALUE|registry.WOW64_64KEY)
if err != nil {
return "", err
}
defer k.Close()
s, _, err := k.GetStringValue("MachineGuid")
if err != nil {
return "", err
}
return s, nil
} | go | func machineID() (string, error) {
k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Cryptography`, registry.QUERY_VALUE|registry.WOW64_64KEY)
if err != nil {
return "", err
}
defer k.Close()
s, _, err := k.GetStringValue("MachineGuid")
if err != nil {
return "", err
}
return s, nil
} | [
"func",
"machineID",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"k",
",",
"err",
":=",
"registry",
".",
"OpenKey",
"(",
"registry",
".",
"LOCAL_MACHINE",
",",
"`SOFTWARE\\Microsoft\\Cryptography`",
",",
"registry",
".",
"QUERY_VALUE",
"|",
"registry",
... | // machineID returns the key MachineGuid in registry `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography`.
// If there is an error running the commad an empty string is returned. | [
"machineID",
"returns",
"the",
"key",
"MachineGuid",
"in",
"registry",
"HKEY_LOCAL_MACHINE",
"\\",
"SOFTWARE",
"\\",
"Microsoft",
"\\",
"Cryptography",
".",
"If",
"there",
"is",
"an",
"error",
"running",
"the",
"commad",
"an",
"empty",
"string",
"is",
"returned"... | f07179bb15a0bec252453468aa607c670f5c12b5 | https://github.com/denisbrodbeck/machineid/blob/f07179bb15a0bec252453468aa607c670f5c12b5/id_windows.go#L11-L23 |
9,427 | denisbrodbeck/machineid | id.go | ProtectedID | func ProtectedID(appID string) (string, error) {
id, err := ID()
if err != nil {
return "", fmt.Errorf("machineid: %v", err)
}
return protect(appID, id), nil
} | go | func ProtectedID(appID string) (string, error) {
id, err := ID()
if err != nil {
return "", fmt.Errorf("machineid: %v", err)
}
return protect(appID, id), nil
} | [
"func",
"ProtectedID",
"(",
"appID",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"id",
",",
"err",
":=",
"ID",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err"... | // ProtectedID returns a hashed version of the machine ID in a cryptographically secure way,
// using a fixed, application-specific key.
// Internally, this function calculates HMAC-SHA256 of the application ID, keyed by the machine ID. | [
"ProtectedID",
"returns",
"a",
"hashed",
"version",
"of",
"the",
"machine",
"ID",
"in",
"a",
"cryptographically",
"secure",
"way",
"using",
"a",
"fixed",
"application",
"-",
"specific",
"key",
".",
"Internally",
"this",
"function",
"calculates",
"HMAC",
"-",
"... | f07179bb15a0bec252453468aa607c670f5c12b5 | https://github.com/denisbrodbeck/machineid/blob/f07179bb15a0bec252453468aa607c670f5c12b5/id.go#L39-L45 |
9,428 | denisbrodbeck/machineid | id_darwin.go | machineID | func machineID() (string, error) {
buf := &bytes.Buffer{}
err := run(buf, os.Stderr, "ioreg", "-rd1", "-c", "IOPlatformExpertDevice")
if err != nil {
return "", err
}
id, err := extractID(buf.String())
if err != nil {
return "", err
}
return trim(id), nil
} | go | func machineID() (string, error) {
buf := &bytes.Buffer{}
err := run(buf, os.Stderr, "ioreg", "-rd1", "-c", "IOPlatformExpertDevice")
if err != nil {
return "", err
}
id, err := extractID(buf.String())
if err != nil {
return "", err
}
return trim(id), nil
} | [
"func",
"machineID",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"err",
":=",
"run",
"(",
"buf",
",",
"os",
".",
"Stderr",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
... | // machineID returns the uuid returned by `ioreg -rd1 -c IOPlatformExpertDevice`.
// If there is an error running the commad an empty string is returned. | [
"machineID",
"returns",
"the",
"uuid",
"returned",
"by",
"ioreg",
"-",
"rd1",
"-",
"c",
"IOPlatformExpertDevice",
".",
"If",
"there",
"is",
"an",
"error",
"running",
"the",
"commad",
"an",
"empty",
"string",
"is",
"returned",
"."
] | f07179bb15a0bec252453468aa607c670f5c12b5 | https://github.com/denisbrodbeck/machineid/blob/f07179bb15a0bec252453468aa607c670f5c12b5/id_darwin.go#L14-L25 |
9,429 | denisbrodbeck/machineid | helper.go | run | func run(stdout, stderr io.Writer, cmd string, args ...string) error {
c := exec.Command(cmd, args...)
c.Stdin = os.Stdin
c.Stdout = stdout
c.Stderr = stderr
return c.Run()
} | go | func run(stdout, stderr io.Writer, cmd string, args ...string) error {
c := exec.Command(cmd, args...)
c.Stdin = os.Stdin
c.Stdout = stdout
c.Stderr = stderr
return c.Run()
} | [
"func",
"run",
"(",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
",",
"cmd",
"string",
",",
"args",
"...",
"string",
")",
"error",
"{",
"c",
":=",
"exec",
".",
"Command",
"(",
"cmd",
",",
"args",
"...",
")",
"\n",
"c",
".",
"Stdin",
"=",
"os",
... | // run wraps `exec.Command` with easy access to stdout and stderr. | [
"run",
"wraps",
"exec",
".",
"Command",
"with",
"easy",
"access",
"to",
"stdout",
"and",
"stderr",
"."
] | f07179bb15a0bec252453468aa607c670f5c12b5 | https://github.com/denisbrodbeck/machineid/blob/f07179bb15a0bec252453468aa607c670f5c12b5/helper.go#L15-L21 |
9,430 | denisbrodbeck/machineid | helper.go | protect | func protect(appID, id string) string {
mac := hmac.New(sha256.New, []byte(id))
mac.Write([]byte(appID))
return hex.EncodeToString(mac.Sum(nil))
} | go | func protect(appID, id string) string {
mac := hmac.New(sha256.New, []byte(id))
mac.Write([]byte(appID))
return hex.EncodeToString(mac.Sum(nil))
} | [
"func",
"protect",
"(",
"appID",
",",
"id",
"string",
")",
"string",
"{",
"mac",
":=",
"hmac",
".",
"New",
"(",
"sha256",
".",
"New",
",",
"[",
"]",
"byte",
"(",
"id",
")",
")",
"\n",
"mac",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"appID",
... | // protect calculates HMAC-SHA256 of the application ID, keyed by the machine ID and returns a hex-encoded string. | [
"protect",
"calculates",
"HMAC",
"-",
"SHA256",
"of",
"the",
"application",
"ID",
"keyed",
"by",
"the",
"machine",
"ID",
"and",
"returns",
"a",
"hex",
"-",
"encoded",
"string",
"."
] | f07179bb15a0bec252453468aa607c670f5c12b5 | https://github.com/denisbrodbeck/machineid/blob/f07179bb15a0bec252453468aa607c670f5c12b5/helper.go#L24-L28 |
9,431 | preichenberger/go-coinbasepro | client.go | Headers | func (c *Client) Headers(method, url, timestamp, data string) (map[string]string, error) {
h := make(map[string]string)
h["CB-ACCESS-KEY"] = c.Key
h["CB-ACCESS-PASSPHRASE"] = c.Passphrase
h["CB-ACCESS-TIMESTAMP"] = timestamp
message := fmt.Sprintf(
"%s%s%s%s",
timestamp,
method,
url,
data,
)
sig, err := generateSig(message, c.Secret)
if err != nil {
return nil, err
}
h["CB-ACCESS-SIGN"] = sig
return h, nil
} | go | func (c *Client) Headers(method, url, timestamp, data string) (map[string]string, error) {
h := make(map[string]string)
h["CB-ACCESS-KEY"] = c.Key
h["CB-ACCESS-PASSPHRASE"] = c.Passphrase
h["CB-ACCESS-TIMESTAMP"] = timestamp
message := fmt.Sprintf(
"%s%s%s%s",
timestamp,
method,
url,
data,
)
sig, err := generateSig(message, c.Secret)
if err != nil {
return nil, err
}
h["CB-ACCESS-SIGN"] = sig
return h, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Headers",
"(",
"method",
",",
"url",
",",
"timestamp",
",",
"data",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"h",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string... | // Headers generates a map that can be used as headers to authenticate a request | [
"Headers",
"generates",
"a",
"map",
"that",
"can",
"be",
"used",
"as",
"headers",
"to",
"authenticate",
"a",
"request"
] | b6b44f4eca43ccf9e10750adfaf8511609968757 | https://github.com/preichenberger/go-coinbasepro/blob/b6b44f4eca43ccf9e10750adfaf8511609968757/client.go#L166-L186 |
9,432 | maxbrunsfeld/counterfeiter | generator/fake.go | NewFake | func NewFake(fakeMode FakeMode, targetName string, packagePath string, fakeName string, destinationPackage string, workingDir string) (*Fake, error) {
f := &Fake{
TargetName: targetName,
TargetPackage: packagePath,
Name: fakeName,
Mode: fakeMode,
DestinationPackage: destinationPackage,
Imports: newImports(),
}
f.Imports.Add("sync", "sync")
err := f.loadPackages(workingDir)
if err != nil {
return nil, err
}
// TODO: Package mode here
err = f.findPackage()
if err != nil {
return nil, err
}
if f.IsInterface() || f.Mode == Package {
f.loadMethods()
}
if f.IsFunction() {
err = f.loadMethodForFunction()
if err != nil {
return nil, err
}
}
return f, nil
} | go | func NewFake(fakeMode FakeMode, targetName string, packagePath string, fakeName string, destinationPackage string, workingDir string) (*Fake, error) {
f := &Fake{
TargetName: targetName,
TargetPackage: packagePath,
Name: fakeName,
Mode: fakeMode,
DestinationPackage: destinationPackage,
Imports: newImports(),
}
f.Imports.Add("sync", "sync")
err := f.loadPackages(workingDir)
if err != nil {
return nil, err
}
// TODO: Package mode here
err = f.findPackage()
if err != nil {
return nil, err
}
if f.IsInterface() || f.Mode == Package {
f.loadMethods()
}
if f.IsFunction() {
err = f.loadMethodForFunction()
if err != nil {
return nil, err
}
}
return f, nil
} | [
"func",
"NewFake",
"(",
"fakeMode",
"FakeMode",
",",
"targetName",
"string",
",",
"packagePath",
"string",
",",
"fakeName",
"string",
",",
"destinationPackage",
"string",
",",
"workingDir",
"string",
")",
"(",
"*",
"Fake",
",",
"error",
")",
"{",
"f",
":=",
... | // NewFake returns a Fake that loads the package and finds the interface or the
// function. | [
"NewFake",
"returns",
"a",
"Fake",
"that",
"loads",
"the",
"package",
"and",
"finds",
"the",
"interface",
"or",
"the",
"function",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/fake.go#L51-L83 |
9,433 | maxbrunsfeld/counterfeiter | generator/fake.go | IsInterface | func (f *Fake) IsInterface() bool {
if f.Target == nil || f.Target.Type() == nil {
return false
}
return types.IsInterface(f.Target.Type())
} | go | func (f *Fake) IsInterface() bool {
if f.Target == nil || f.Target.Type() == nil {
return false
}
return types.IsInterface(f.Target.Type())
} | [
"func",
"(",
"f",
"*",
"Fake",
")",
"IsInterface",
"(",
")",
"bool",
"{",
"if",
"f",
".",
"Target",
"==",
"nil",
"||",
"f",
".",
"Target",
".",
"Type",
"(",
")",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"types",
".",
"IsI... | // IsInterface indicates whether the fake is for an interface. | [
"IsInterface",
"indicates",
"whether",
"the",
"fake",
"is",
"for",
"an",
"interface",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/fake.go#L86-L91 |
9,434 | maxbrunsfeld/counterfeiter | generator/fake.go | IsFunction | func (f *Fake) IsFunction() bool {
if f.Target == nil || f.Target.Type() == nil || f.Target.Type().Underlying() == nil {
return false
}
_, ok := f.Target.Type().Underlying().(*types.Signature)
return ok
} | go | func (f *Fake) IsFunction() bool {
if f.Target == nil || f.Target.Type() == nil || f.Target.Type().Underlying() == nil {
return false
}
_, ok := f.Target.Type().Underlying().(*types.Signature)
return ok
} | [
"func",
"(",
"f",
"*",
"Fake",
")",
"IsFunction",
"(",
")",
"bool",
"{",
"if",
"f",
".",
"Target",
"==",
"nil",
"||",
"f",
".",
"Target",
".",
"Type",
"(",
")",
"==",
"nil",
"||",
"f",
".",
"Target",
".",
"Type",
"(",
")",
".",
"Underlying",
... | // IsFunction indicates whether the fake is for a function.. | [
"IsFunction",
"indicates",
"whether",
"the",
"fake",
"is",
"for",
"a",
"function",
".."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/fake.go#L94-L100 |
9,435 | maxbrunsfeld/counterfeiter | generator/fake.go | Generate | func (f *Fake) Generate(runImports bool) ([]byte, error) {
var tmpl *template.Template
if f.IsInterface() {
log.Printf("Writing fake %s for interface %s to package %s\n", f.Name, f.TargetName, f.DestinationPackage)
tmpl = template.Must(template.New("fake").Funcs(interfaceFuncs).Parse(interfaceTemplate))
}
if f.IsFunction() {
log.Printf("Writing fake %s for function %s to package %s\n", f.Name, f.TargetName, f.DestinationPackage)
tmpl = template.Must(template.New("fake").Funcs(functionFuncs).Parse(functionTemplate))
}
if f.Mode == Package {
log.Printf("Writing fake %s for package %s to package %s\n", f.Name, f.TargetPackage, f.DestinationPackage)
tmpl = template.Must(template.New("fake").Funcs(packageFuncs).Parse(packageTemplate))
}
if tmpl == nil {
return nil, errors.New("counterfeiter can only generate fakes for interfaces or specific functions")
}
b := &bytes.Buffer{}
tmpl.Execute(b, f)
if runImports {
return imports.Process("counterfeiter_temp_process_file", b.Bytes(), nil)
}
return b.Bytes(), nil
} | go | func (f *Fake) Generate(runImports bool) ([]byte, error) {
var tmpl *template.Template
if f.IsInterface() {
log.Printf("Writing fake %s for interface %s to package %s\n", f.Name, f.TargetName, f.DestinationPackage)
tmpl = template.Must(template.New("fake").Funcs(interfaceFuncs).Parse(interfaceTemplate))
}
if f.IsFunction() {
log.Printf("Writing fake %s for function %s to package %s\n", f.Name, f.TargetName, f.DestinationPackage)
tmpl = template.Must(template.New("fake").Funcs(functionFuncs).Parse(functionTemplate))
}
if f.Mode == Package {
log.Printf("Writing fake %s for package %s to package %s\n", f.Name, f.TargetPackage, f.DestinationPackage)
tmpl = template.Must(template.New("fake").Funcs(packageFuncs).Parse(packageTemplate))
}
if tmpl == nil {
return nil, errors.New("counterfeiter can only generate fakes for interfaces or specific functions")
}
b := &bytes.Buffer{}
tmpl.Execute(b, f)
if runImports {
return imports.Process("counterfeiter_temp_process_file", b.Bytes(), nil)
}
return b.Bytes(), nil
} | [
"func",
"(",
"f",
"*",
"Fake",
")",
"Generate",
"(",
"runImports",
"bool",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"tmpl",
"*",
"template",
".",
"Template",
"\n",
"if",
"f",
".",
"IsInterface",
"(",
")",
"{",
"log",
".",
"Print... | // Generate uses the Fake to generate an implementation, optionally running
// goimports on the output. | [
"Generate",
"uses",
"the",
"Fake",
"to",
"generate",
"an",
"implementation",
"optionally",
"running",
"goimports",
"on",
"the",
"output",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/fake.go#L118-L142 |
9,436 | maxbrunsfeld/counterfeiter | generator/interface_loader.go | interfaceMethodSet | func interfaceMethodSet(t types.Type) []*rawMethod {
if t == nil {
return nil
}
var result []*rawMethod
methods := typeutil.IntuitiveMethodSet(t, nil)
for i := range methods {
if methods[i].Obj() == nil || methods[i].Type() == nil {
continue
}
fun, ok := methods[i].Obj().(*types.Func)
if !ok {
continue
}
sig, ok := methods[i].Type().(*types.Signature)
if !ok {
continue
}
result = append(result, &rawMethod{
Func: fun,
Signature: sig,
})
}
return result
} | go | func interfaceMethodSet(t types.Type) []*rawMethod {
if t == nil {
return nil
}
var result []*rawMethod
methods := typeutil.IntuitiveMethodSet(t, nil)
for i := range methods {
if methods[i].Obj() == nil || methods[i].Type() == nil {
continue
}
fun, ok := methods[i].Obj().(*types.Func)
if !ok {
continue
}
sig, ok := methods[i].Type().(*types.Signature)
if !ok {
continue
}
result = append(result, &rawMethod{
Func: fun,
Signature: sig,
})
}
return result
} | [
"func",
"interfaceMethodSet",
"(",
"t",
"types",
".",
"Type",
")",
"[",
"]",
"*",
"rawMethod",
"{",
"if",
"t",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"result",
"[",
"]",
"*",
"rawMethod",
"\n",
"methods",
":=",
"typeutil",
".",
... | // interfaceMethodSet identifies the methods that are exported for a given
// interface. | [
"interfaceMethodSet",
"identifies",
"the",
"methods",
"that",
"are",
"exported",
"for",
"a",
"given",
"interface",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/interface_loader.go#L57-L82 |
9,437 | maxbrunsfeld/counterfeiter | generator/param.go | Slices | func (p Params) Slices() Params {
var result Params
for i := range p {
if p[i].IsSlice {
result = append(result, p[i])
}
}
return result
} | go | func (p Params) Slices() Params {
var result Params
for i := range p {
if p[i].IsSlice {
result = append(result, p[i])
}
}
return result
} | [
"func",
"(",
"p",
"Params",
")",
"Slices",
"(",
")",
"Params",
"{",
"var",
"result",
"Params",
"\n",
"for",
"i",
":=",
"range",
"p",
"{",
"if",
"p",
"[",
"i",
"]",
".",
"IsSlice",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"p",
"[",
"i",... | // Slices returns those params that are a slice. | [
"Slices",
"returns",
"those",
"params",
"that",
"are",
"a",
"slice",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L17-L25 |
9,438 | maxbrunsfeld/counterfeiter | generator/param.go | WithPrefix | func (p Params) WithPrefix(prefix string) string {
if len(p) == 0 {
return ""
}
params := []string{}
for i := range p {
if prefix == "" {
params = append(params, unexport(p[i].Name))
} else {
params = append(params, prefix+unexport(p[i].Name))
}
}
return strings.Join(params, ", ")
} | go | func (p Params) WithPrefix(prefix string) string {
if len(p) == 0 {
return ""
}
params := []string{}
for i := range p {
if prefix == "" {
params = append(params, unexport(p[i].Name))
} else {
params = append(params, prefix+unexport(p[i].Name))
}
}
return strings.Join(params, ", ")
} | [
"func",
"(",
"p",
"Params",
")",
"WithPrefix",
"(",
"prefix",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"params",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=... | // WithPrefix builds a string representing a functions parameters, and adds a
// prefix to each. | [
"WithPrefix",
"builds",
"a",
"string",
"representing",
"a",
"functions",
"parameters",
"and",
"adds",
"a",
"prefix",
"to",
"each",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L35-L49 |
9,439 | maxbrunsfeld/counterfeiter | generator/param.go | AsArgs | func (p Params) AsArgs() string {
if len(p) == 0 {
return ""
}
params := []string{}
for i := range p {
params = append(params, p[i].Type)
}
return strings.Join(params, ", ")
} | go | func (p Params) AsArgs() string {
if len(p) == 0 {
return ""
}
params := []string{}
for i := range p {
params = append(params, p[i].Type)
}
return strings.Join(params, ", ")
} | [
"func",
"(",
"p",
"Params",
")",
"AsArgs",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"params",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=",
"range",
"p",
"{",
... | // AsArgs builds a string that represents the parameters to a function as
// arguments to a function invocation. | [
"AsArgs",
"builds",
"a",
"string",
"that",
"represents",
"the",
"parameters",
"to",
"a",
"function",
"as",
"arguments",
"to",
"a",
"function",
"invocation",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L53-L63 |
9,440 | maxbrunsfeld/counterfeiter | generator/param.go | AsNamedArgsWithTypes | func (p Params) AsNamedArgsWithTypes() string {
if len(p) == 0 {
return ""
}
params := []string{}
for i := range p {
params = append(params, unexport(p[i].Name)+" "+p[i].Type)
}
return strings.Join(params, ", ")
} | go | func (p Params) AsNamedArgsWithTypes() string {
if len(p) == 0 {
return ""
}
params := []string{}
for i := range p {
params = append(params, unexport(p[i].Name)+" "+p[i].Type)
}
return strings.Join(params, ", ")
} | [
"func",
"(",
"p",
"Params",
")",
"AsNamedArgsWithTypes",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"params",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=",
"range",
... | // AsNamedArgsWithTypes builds a string that represents parameters as named
// arugments to a function, with associated types. | [
"AsNamedArgsWithTypes",
"builds",
"a",
"string",
"that",
"represents",
"parameters",
"as",
"named",
"arugments",
"to",
"a",
"function",
"with",
"associated",
"types",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L67-L77 |
9,441 | maxbrunsfeld/counterfeiter | generator/param.go | AsNamedArgs | func (p Params) AsNamedArgs() string {
if len(p) == 0 {
return ""
}
params := []string{}
for i := range p {
if p[i].IsSlice {
params = append(params, unexport(p[i].Name)+"Copy")
} else {
params = append(params, unexport(p[i].Name))
}
}
return strings.Join(params, ", ")
} | go | func (p Params) AsNamedArgs() string {
if len(p) == 0 {
return ""
}
params := []string{}
for i := range p {
if p[i].IsSlice {
params = append(params, unexport(p[i].Name)+"Copy")
} else {
params = append(params, unexport(p[i].Name))
}
}
return strings.Join(params, ", ")
} | [
"func",
"(",
"p",
"Params",
")",
"AsNamedArgs",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"params",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=",
"range",
"p",
... | // AsNamedArgs builds a string that represents parameters as named arguments. | [
"AsNamedArgs",
"builds",
"a",
"string",
"that",
"represents",
"parameters",
"as",
"named",
"arguments",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L80-L94 |
9,442 | maxbrunsfeld/counterfeiter | generator/param.go | AsNamedArgsForInvocation | func (p Params) AsNamedArgsForInvocation() string {
if len(p) == 0 {
return ""
}
params := []string{}
for i := range p {
if p[i].IsVariadic {
params = append(params, unexport(p[i].Name)+"...")
} else {
params = append(params, unexport(p[i].Name))
}
}
return strings.Join(params, ", ")
} | go | func (p Params) AsNamedArgsForInvocation() string {
if len(p) == 0 {
return ""
}
params := []string{}
for i := range p {
if p[i].IsVariadic {
params = append(params, unexport(p[i].Name)+"...")
} else {
params = append(params, unexport(p[i].Name))
}
}
return strings.Join(params, ", ")
} | [
"func",
"(",
"p",
"Params",
")",
"AsNamedArgsForInvocation",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"params",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=",
"rang... | // AsNamedArgsForInvocation builds a string that represents a function's
// arguments as required for invocation of the function. | [
"AsNamedArgsForInvocation",
"builds",
"a",
"string",
"that",
"represents",
"a",
"function",
"s",
"arguments",
"as",
"required",
"for",
"invocation",
"of",
"the",
"function",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L98-L112 |
9,443 | maxbrunsfeld/counterfeiter | generator/param.go | AsReturnSignature | func (p Params) AsReturnSignature() string {
if len(p) == 0 {
return ""
}
if len(p) == 1 {
if p[0].IsVariadic {
return strings.Replace(p[0].Type, "...", "[]", -1)
}
return p[0].Type
}
result := "("
for i := range p {
t := p[i].Type
if p[i].IsVariadic {
t = strings.Replace(t, "...", "[]", -1)
}
result = result + t
if i < len(p) {
result = result + ", "
}
}
result = result + ")"
return result
} | go | func (p Params) AsReturnSignature() string {
if len(p) == 0 {
return ""
}
if len(p) == 1 {
if p[0].IsVariadic {
return strings.Replace(p[0].Type, "...", "[]", -1)
}
return p[0].Type
}
result := "("
for i := range p {
t := p[i].Type
if p[i].IsVariadic {
t = strings.Replace(t, "...", "[]", -1)
}
result = result + t
if i < len(p) {
result = result + ", "
}
}
result = result + ")"
return result
} | [
"func",
"(",
"p",
"Params",
")",
"AsReturnSignature",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"len",
"(",
"p",
")",
"==",
"1",
"{",
"if",
"p",
"[",
"0",
"]",
".",
"Is... | // AsReturnSignature builds a string representing signature for the params of
// a function. | [
"AsReturnSignature",
"builds",
"a",
"string",
"representing",
"signature",
"for",
"the",
"params",
"of",
"a",
"function",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L116-L139 |
9,444 | maxbrunsfeld/counterfeiter | generator/import.go | String | func (i Import) String() string {
if path.Base(i.PkgPath) == i.Alias {
return `"` + i.PkgPath + `"`
}
return fmt.Sprintf(`%s "%s"`, i.Alias, i.PkgPath)
} | go | func (i Import) String() string {
if path.Base(i.PkgPath) == i.Alias {
return `"` + i.PkgPath + `"`
}
return fmt.Sprintf(`%s "%s"`, i.Alias, i.PkgPath)
} | [
"func",
"(",
"i",
"Import",
")",
"String",
"(",
")",
"string",
"{",
"if",
"path",
".",
"Base",
"(",
"i",
".",
"PkgPath",
")",
"==",
"i",
".",
"Alias",
"{",
"return",
"`\"`",
"+",
"i",
".",
"PkgPath",
"+",
"`\"`",
"\n",
"}",
"\n",
"return",
"fmt... | // String returns a string that may be used as an import line in a go source
// file. Imports with aliases that match the package basename are printed without
// an alias. | [
"String",
"returns",
"a",
"string",
"that",
"may",
"be",
"used",
"as",
"an",
"import",
"line",
"in",
"a",
"go",
"source",
"file",
".",
"Imports",
"with",
"aliases",
"that",
"match",
"the",
"package",
"basename",
"are",
"printed",
"without",
"an",
"alias",
... | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/import.go#L35-L40 |
9,445 | maxbrunsfeld/counterfeiter | generator/import.go | Add | func (i *Imports) Add(alias string, path string) Import {
path = imports.VendorlessPath(strings.TrimSpace(path))
alias = strings.TrimSpace(alias)
imp, exists := i.ByPkgPath[path]
if exists {
return imp
}
_, exists = i.ByAlias[alias]
if exists {
alias = uniqueAliasForImport(alias, i.ByAlias)
}
result := Import{Alias: alias, PkgPath: path}
i.ByPkgPath[path] = result
i.ByAlias[alias] = result
return result
} | go | func (i *Imports) Add(alias string, path string) Import {
path = imports.VendorlessPath(strings.TrimSpace(path))
alias = strings.TrimSpace(alias)
imp, exists := i.ByPkgPath[path]
if exists {
return imp
}
_, exists = i.ByAlias[alias]
if exists {
alias = uniqueAliasForImport(alias, i.ByAlias)
}
result := Import{Alias: alias, PkgPath: path}
i.ByPkgPath[path] = result
i.ByAlias[alias] = result
return result
} | [
"func",
"(",
"i",
"*",
"Imports",
")",
"Add",
"(",
"alias",
"string",
",",
"path",
"string",
")",
"Import",
"{",
"path",
"=",
"imports",
".",
"VendorlessPath",
"(",
"strings",
".",
"TrimSpace",
"(",
"path",
")",
")",
"\n",
"alias",
"=",
"strings",
".... | // Add creates an import with the given alias and path, and adds it to
// Fake.Imports. | [
"Add",
"creates",
"an",
"import",
"with",
"the",
"given",
"alias",
"and",
"path",
"and",
"adds",
"it",
"to",
"Fake",
".",
"Imports",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/import.go#L44-L62 |
9,446 | maxbrunsfeld/counterfeiter | generator/import.go | AliasForPackage | func (i *Imports) AliasForPackage(p *types.Package) string {
return i.ByPkgPath[imports.VendorlessPath(p.Path())].Alias
} | go | func (i *Imports) AliasForPackage(p *types.Package) string {
return i.ByPkgPath[imports.VendorlessPath(p.Path())].Alias
} | [
"func",
"(",
"i",
"*",
"Imports",
")",
"AliasForPackage",
"(",
"p",
"*",
"types",
".",
"Package",
")",
"string",
"{",
"return",
"i",
".",
"ByPkgPath",
"[",
"imports",
".",
"VendorlessPath",
"(",
"p",
".",
"Path",
"(",
")",
")",
"]",
".",
"Alias",
"... | // AliasForPackage returns a package alias for the package. | [
"AliasForPackage",
"returns",
"a",
"package",
"alias",
"for",
"the",
"package",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/import.go#L74-L76 |
9,447 | maxbrunsfeld/counterfeiter | generator/package_loader.go | packageMethodSet | func packageMethodSet(p *packages.Package) []*rawMethod {
if p == nil || p.Types == nil || p.Types.Scope() == nil {
return nil
}
var result []*rawMethod
scope := p.Types.Scope()
for _, name := range scope.Names() {
obj := scope.Lookup(name)
if !obj.Exported() {
continue // skip unexported names
}
fun, ok := obj.(*types.Func)
if !ok {
continue
}
sig, ok := obj.Type().(*types.Signature)
if !ok {
continue
}
result = append(result, &rawMethod{
Func: fun,
Signature: sig,
})
}
return result
} | go | func packageMethodSet(p *packages.Package) []*rawMethod {
if p == nil || p.Types == nil || p.Types.Scope() == nil {
return nil
}
var result []*rawMethod
scope := p.Types.Scope()
for _, name := range scope.Names() {
obj := scope.Lookup(name)
if !obj.Exported() {
continue // skip unexported names
}
fun, ok := obj.(*types.Func)
if !ok {
continue
}
sig, ok := obj.Type().(*types.Signature)
if !ok {
continue
}
result = append(result, &rawMethod{
Func: fun,
Signature: sig,
})
}
return result
} | [
"func",
"packageMethodSet",
"(",
"p",
"*",
"packages",
".",
"Package",
")",
"[",
"]",
"*",
"rawMethod",
"{",
"if",
"p",
"==",
"nil",
"||",
"p",
".",
"Types",
"==",
"nil",
"||",
"p",
".",
"Types",
".",
"Scope",
"(",
")",
"==",
"nil",
"{",
"return"... | // packageMethodSet identifies the functions that are exported from a given
// package. | [
"packageMethodSet",
"identifies",
"the",
"functions",
"that",
"are",
"exported",
"from",
"a",
"given",
"package",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/package_loader.go#L16-L42 |
9,448 | maxbrunsfeld/counterfeiter | generator/loader.go | addImportsFor | func (f *Fake) addImportsFor(typ types.Type) {
if typ == nil {
return
}
switch t := typ.(type) {
case *types.Basic:
return
case *types.Pointer:
f.addImportsFor(t.Elem())
case *types.Map:
f.addImportsFor(t.Key())
f.addImportsFor(t.Elem())
case *types.Chan:
f.addImportsFor(t.Elem())
case *types.Named:
if t.Obj() != nil && t.Obj().Pkg() != nil {
f.Imports.Add(t.Obj().Pkg().Name(), t.Obj().Pkg().Path())
}
case *types.Slice:
f.addImportsFor(t.Elem())
case *types.Array:
f.addImportsFor(t.Elem())
case *types.Interface:
return
case *types.Signature:
f.addTypesForMethod(t)
default:
log.Printf("!!! WARNING: Missing case for type %s\n", reflect.TypeOf(typ).String())
}
} | go | func (f *Fake) addImportsFor(typ types.Type) {
if typ == nil {
return
}
switch t := typ.(type) {
case *types.Basic:
return
case *types.Pointer:
f.addImportsFor(t.Elem())
case *types.Map:
f.addImportsFor(t.Key())
f.addImportsFor(t.Elem())
case *types.Chan:
f.addImportsFor(t.Elem())
case *types.Named:
if t.Obj() != nil && t.Obj().Pkg() != nil {
f.Imports.Add(t.Obj().Pkg().Name(), t.Obj().Pkg().Path())
}
case *types.Slice:
f.addImportsFor(t.Elem())
case *types.Array:
f.addImportsFor(t.Elem())
case *types.Interface:
return
case *types.Signature:
f.addTypesForMethod(t)
default:
log.Printf("!!! WARNING: Missing case for type %s\n", reflect.TypeOf(typ).String())
}
} | [
"func",
"(",
"f",
"*",
"Fake",
")",
"addImportsFor",
"(",
"typ",
"types",
".",
"Type",
")",
"{",
"if",
"typ",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"switch",
"t",
":=",
"typ",
".",
"(",
"type",
")",
"{",
"case",
"*",
"types",
".",
"Bas... | // addImportsFor inspects the given type and adds imports to the fake if importable
// types are found. | [
"addImportsFor",
"inspects",
"the",
"given",
"type",
"and",
"adds",
"imports",
"to",
"the",
"fake",
"if",
"importable",
"types",
"are",
"found",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/loader.go#L100-L130 |
9,449 | maxbrunsfeld/counterfeiter | generator/return.go | WithPrefix | func (r Returns) WithPrefix(p string) string {
if len(r) == 0 {
return ""
}
rets := []string{}
for i := range r {
if p == "" {
rets = append(rets, unexport(r[i].Name))
} else {
rets = append(rets, p+unexport(r[i].Name))
}
}
return strings.Join(rets, ", ")
} | go | func (r Returns) WithPrefix(p string) string {
if len(r) == 0 {
return ""
}
rets := []string{}
for i := range r {
if p == "" {
rets = append(rets, unexport(r[i].Name))
} else {
rets = append(rets, p+unexport(r[i].Name))
}
}
return strings.Join(rets, ", ")
} | [
"func",
"(",
"r",
"Returns",
")",
"WithPrefix",
"(",
"p",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"r",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"rets",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=",
"... | // WithPrefix builds a string representing the parameters returned from a
// function, and adds a prefix to each. | [
"WithPrefix",
"builds",
"a",
"string",
"representing",
"the",
"parameters",
"returned",
"from",
"a",
"function",
"and",
"adds",
"a",
"prefix",
"to",
"each",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/return.go#L23-L37 |
9,450 | maxbrunsfeld/counterfeiter | generator/return.go | AsArgs | func (r Returns) AsArgs() string {
if len(r) == 0 {
return ""
}
rets := []string{}
for i := range r {
rets = append(rets, r[i].Type)
}
return strings.Join(rets, ", ")
} | go | func (r Returns) AsArgs() string {
if len(r) == 0 {
return ""
}
rets := []string{}
for i := range r {
rets = append(rets, r[i].Type)
}
return strings.Join(rets, ", ")
} | [
"func",
"(",
"r",
"Returns",
")",
"AsArgs",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"r",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"rets",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=",
"range",
"r",
"{",
... | // AsArgs builds a string representing the arguments passed to a function. | [
"AsArgs",
"builds",
"a",
"string",
"representing",
"the",
"arguments",
"passed",
"to",
"a",
"function",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/return.go#L40-L50 |
9,451 | maxbrunsfeld/counterfeiter | generator/return.go | AsNamedArgsWithTypes | func (r Returns) AsNamedArgsWithTypes() string {
if len(r) == 0 {
return ""
}
rets := []string{}
for i := range r {
rets = append(rets, unexport(r[i].Name)+" "+r[i].Type)
}
return strings.Join(rets, ", ")
} | go | func (r Returns) AsNamedArgsWithTypes() string {
if len(r) == 0 {
return ""
}
rets := []string{}
for i := range r {
rets = append(rets, unexport(r[i].Name)+" "+r[i].Type)
}
return strings.Join(rets, ", ")
} | [
"func",
"(",
"r",
"Returns",
")",
"AsNamedArgsWithTypes",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"r",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"rets",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=",
"range",
... | // AsNamedArgsWithTypes builds a string representing a function's named
// arguments, with associated types. | [
"AsNamedArgsWithTypes",
"builds",
"a",
"string",
"representing",
"a",
"function",
"s",
"named",
"arguments",
"with",
"associated",
"types",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/return.go#L54-L64 |
9,452 | maxbrunsfeld/counterfeiter | generator/return.go | AsNamedArgs | func (r Returns) AsNamedArgs() string {
if len(r) == 0 {
return ""
}
rets := []string{}
for i := range r {
rets = append(rets, unexport(r[i].Name))
}
return strings.Join(rets, ", ")
} | go | func (r Returns) AsNamedArgs() string {
if len(r) == 0 {
return ""
}
rets := []string{}
for i := range r {
rets = append(rets, unexport(r[i].Name))
}
return strings.Join(rets, ", ")
} | [
"func",
"(",
"r",
"Returns",
")",
"AsNamedArgs",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"r",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"rets",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=",
"range",
"r",
"... | // AsNamedArgs builds a string representing a function's named arguments. | [
"AsNamedArgs",
"builds",
"a",
"string",
"representing",
"a",
"function",
"s",
"named",
"arguments",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/return.go#L67-L77 |
9,453 | maxbrunsfeld/counterfeiter | generator/return.go | AsReturnSignature | func (r Returns) AsReturnSignature() string {
if len(r) == 0 {
return ""
}
if len(r) == 1 {
return r[0].Type
}
result := "("
for i := range r {
result = result + r[i].Type
if i < len(r) {
result = result + ", "
}
}
result = result + ")"
return result
} | go | func (r Returns) AsReturnSignature() string {
if len(r) == 0 {
return ""
}
if len(r) == 1 {
return r[0].Type
}
result := "("
for i := range r {
result = result + r[i].Type
if i < len(r) {
result = result + ", "
}
}
result = result + ")"
return result
} | [
"func",
"(",
"r",
"Returns",
")",
"AsReturnSignature",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"r",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"len",
"(",
"r",
")",
"==",
"1",
"{",
"return",
"r",
"[",
"0",
"]",
".",
... | // AsReturnSignature builds a string representing signature for the returns of
// a function. | [
"AsReturnSignature",
"builds",
"a",
"string",
"representing",
"signature",
"for",
"the",
"returns",
"of",
"a",
"function",
"."
] | f7bde7cbdb1288611466a0d715b1bbc956519eb1 | https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/return.go#L81-L97 |
9,454 | libp2p/go-libp2p-peerstore | pstoremem/keybook.go | NewKeyBook | func NewKeyBook() pstore.KeyBook {
return &memoryKeyBook{
pks: map[peer.ID]ic.PubKey{},
sks: map[peer.ID]ic.PrivKey{},
}
} | go | func NewKeyBook() pstore.KeyBook {
return &memoryKeyBook{
pks: map[peer.ID]ic.PubKey{},
sks: map[peer.ID]ic.PrivKey{},
}
} | [
"func",
"NewKeyBook",
"(",
")",
"pstore",
".",
"KeyBook",
"{",
"return",
"&",
"memoryKeyBook",
"{",
"pks",
":",
"map",
"[",
"peer",
".",
"ID",
"]",
"ic",
".",
"PubKey",
"{",
"}",
",",
"sks",
":",
"map",
"[",
"peer",
".",
"ID",
"]",
"ic",
".",
"... | // noop new, but in the future we may want to do some init work. | [
"noop",
"new",
"but",
"in",
"the",
"future",
"we",
"may",
"want",
"to",
"do",
"some",
"init",
"work",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/keybook.go#L22-L27 |
9,455 | libp2p/go-libp2p-peerstore | pstoreds/peerstore.go | NewPeerstore | func NewPeerstore(ctx context.Context, store ds.Batching, opts Options) (pstore.Peerstore, error) {
addrBook, err := NewAddrBook(ctx, store, opts)
if err != nil {
return nil, err
}
keyBook, err := NewKeyBook(ctx, store, opts)
if err != nil {
return nil, err
}
peerMetadata, err := NewPeerMetadata(ctx, store, opts)
if err != nil {
return nil, err
}
ps := pstore.NewPeerstore(keyBook, addrBook, peerMetadata)
return ps, nil
} | go | func NewPeerstore(ctx context.Context, store ds.Batching, opts Options) (pstore.Peerstore, error) {
addrBook, err := NewAddrBook(ctx, store, opts)
if err != nil {
return nil, err
}
keyBook, err := NewKeyBook(ctx, store, opts)
if err != nil {
return nil, err
}
peerMetadata, err := NewPeerMetadata(ctx, store, opts)
if err != nil {
return nil, err
}
ps := pstore.NewPeerstore(keyBook, addrBook, peerMetadata)
return ps, nil
} | [
"func",
"NewPeerstore",
"(",
"ctx",
"context",
".",
"Context",
",",
"store",
"ds",
".",
"Batching",
",",
"opts",
"Options",
")",
"(",
"pstore",
".",
"Peerstore",
",",
"error",
")",
"{",
"addrBook",
",",
"err",
":=",
"NewAddrBook",
"(",
"ctx",
",",
"sto... | // NewPeerstore creates a peerstore backed by the provided persistent datastore. | [
"NewPeerstore",
"creates",
"a",
"peerstore",
"backed",
"by",
"the",
"provided",
"persistent",
"datastore",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/peerstore.go#L50-L68 |
9,456 | libp2p/go-libp2p-peerstore | pstoreds/peerstore.go | uniquePeerIds | func uniquePeerIds(ds ds.Datastore, prefix ds.Key, extractor func(result query.Result) string) (peer.IDSlice, error) {
var (
q = query.Query{Prefix: prefix.String(), KeysOnly: true}
results query.Results
err error
)
if results, err = ds.Query(q); err != nil {
log.Error(err)
return nil, err
}
defer results.Close()
idset := make(map[string]struct{})
for result := range results.Next() {
k := extractor(result)
idset[k] = struct{}{}
}
if len(idset) == 0 {
return peer.IDSlice{}, nil
}
ids := make(peer.IDSlice, 0, len(idset))
for id := range idset {
pid, _ := base32.RawStdEncoding.DecodeString(id)
id, _ := peer.IDFromBytes(pid)
ids = append(ids, id)
}
return ids, nil
} | go | func uniquePeerIds(ds ds.Datastore, prefix ds.Key, extractor func(result query.Result) string) (peer.IDSlice, error) {
var (
q = query.Query{Prefix: prefix.String(), KeysOnly: true}
results query.Results
err error
)
if results, err = ds.Query(q); err != nil {
log.Error(err)
return nil, err
}
defer results.Close()
idset := make(map[string]struct{})
for result := range results.Next() {
k := extractor(result)
idset[k] = struct{}{}
}
if len(idset) == 0 {
return peer.IDSlice{}, nil
}
ids := make(peer.IDSlice, 0, len(idset))
for id := range idset {
pid, _ := base32.RawStdEncoding.DecodeString(id)
id, _ := peer.IDFromBytes(pid)
ids = append(ids, id)
}
return ids, nil
} | [
"func",
"uniquePeerIds",
"(",
"ds",
"ds",
".",
"Datastore",
",",
"prefix",
"ds",
".",
"Key",
",",
"extractor",
"func",
"(",
"result",
"query",
".",
"Result",
")",
"string",
")",
"(",
"peer",
".",
"IDSlice",
",",
"error",
")",
"{",
"var",
"(",
"q",
... | // uniquePeerIds extracts and returns unique peer IDs from database keys. | [
"uniquePeerIds",
"extracts",
"and",
"returns",
"unique",
"peer",
"IDs",
"from",
"database",
"keys",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/peerstore.go#L71-L102 |
9,457 | libp2p/go-libp2p-peerstore | metrics.go | RecordLatency | func (m *metrics) RecordLatency(p peer.ID, next time.Duration) {
nextf := float64(next)
s := LatencyEWMASmoothing
if s > 1 || s < 0 {
s = 0.1 // ignore the knob. it's broken. look, it jiggles.
}
m.latmu.Lock()
ewma, found := m.latmap[p]
ewmaf := float64(ewma)
if !found {
m.latmap[p] = next // when no data, just take it as the mean.
} else {
nextf = ((1.0 - s) * ewmaf) + (s * nextf)
m.latmap[p] = time.Duration(nextf)
}
m.latmu.Unlock()
} | go | func (m *metrics) RecordLatency(p peer.ID, next time.Duration) {
nextf := float64(next)
s := LatencyEWMASmoothing
if s > 1 || s < 0 {
s = 0.1 // ignore the knob. it's broken. look, it jiggles.
}
m.latmu.Lock()
ewma, found := m.latmap[p]
ewmaf := float64(ewma)
if !found {
m.latmap[p] = next // when no data, just take it as the mean.
} else {
nextf = ((1.0 - s) * ewmaf) + (s * nextf)
m.latmap[p] = time.Duration(nextf)
}
m.latmu.Unlock()
} | [
"func",
"(",
"m",
"*",
"metrics",
")",
"RecordLatency",
"(",
"p",
"peer",
".",
"ID",
",",
"next",
"time",
".",
"Duration",
")",
"{",
"nextf",
":=",
"float64",
"(",
"next",
")",
"\n",
"s",
":=",
"LatencyEWMASmoothing",
"\n",
"if",
"s",
">",
"1",
"||... | // RecordLatency records a new latency measurement | [
"RecordLatency",
"records",
"a",
"new",
"latency",
"measurement"
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/metrics.go#L39-L56 |
9,458 | libp2p/go-libp2p-peerstore | metrics.go | LatencyEWMA | func (m *metrics) LatencyEWMA(p peer.ID) time.Duration {
m.latmu.RLock()
lat := m.latmap[p]
m.latmu.RUnlock()
return time.Duration(lat)
} | go | func (m *metrics) LatencyEWMA(p peer.ID) time.Duration {
m.latmu.RLock()
lat := m.latmap[p]
m.latmu.RUnlock()
return time.Duration(lat)
} | [
"func",
"(",
"m",
"*",
"metrics",
")",
"LatencyEWMA",
"(",
"p",
"peer",
".",
"ID",
")",
"time",
".",
"Duration",
"{",
"m",
".",
"latmu",
".",
"RLock",
"(",
")",
"\n",
"lat",
":=",
"m",
".",
"latmap",
"[",
"p",
"]",
"\n",
"m",
".",
"latmu",
".... | // LatencyEWMA returns an exponentially-weighted moving avg.
// of all measurements of a peer's latency. | [
"LatencyEWMA",
"returns",
"an",
"exponentially",
"-",
"weighted",
"moving",
"avg",
".",
"of",
"all",
"measurements",
"of",
"a",
"peer",
"s",
"latency",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/metrics.go#L60-L65 |
9,459 | libp2p/go-libp2p-peerstore | pb/custom.go | NewPopulatedProtoAddr | func NewPopulatedProtoAddr(r randyPstore) *ProtoAddr {
a, _ := ma.NewMultiaddr("/ip4/123.123.123.123/tcp/7001")
return &ProtoAddr{Multiaddr: a}
} | go | func NewPopulatedProtoAddr(r randyPstore) *ProtoAddr {
a, _ := ma.NewMultiaddr("/ip4/123.123.123.123/tcp/7001")
return &ProtoAddr{Multiaddr: a}
} | [
"func",
"NewPopulatedProtoAddr",
"(",
"r",
"randyPstore",
")",
"*",
"ProtoAddr",
"{",
"a",
",",
"_",
":=",
"ma",
".",
"NewMultiaddr",
"(",
"\"",
"\"",
")",
"\n",
"return",
"&",
"ProtoAddr",
"{",
"Multiaddr",
":",
"a",
"}",
"\n",
"}"
] | // NewPopulatedProtoAddr generates a populated instance of the custom gogo type ProtoAddr.
// It is required by gogo-generated tests. | [
"NewPopulatedProtoAddr",
"generates",
"a",
"populated",
"instance",
"of",
"the",
"custom",
"gogo",
"type",
"ProtoAddr",
".",
"It",
"is",
"required",
"by",
"gogo",
"-",
"generated",
"tests",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pb/custom.go#L100-L103 |
9,460 | libp2p/go-libp2p-peerstore | pb/custom.go | NewPopulatedProtoPeerID | func NewPopulatedProtoPeerID(r randyPstore) *ProtoPeerID {
id, _ := pt.RandPeerID()
return &ProtoPeerID{ID: id}
} | go | func NewPopulatedProtoPeerID(r randyPstore) *ProtoPeerID {
id, _ := pt.RandPeerID()
return &ProtoPeerID{ID: id}
} | [
"func",
"NewPopulatedProtoPeerID",
"(",
"r",
"randyPstore",
")",
"*",
"ProtoPeerID",
"{",
"id",
",",
"_",
":=",
"pt",
".",
"RandPeerID",
"(",
")",
"\n",
"return",
"&",
"ProtoPeerID",
"{",
"ID",
":",
"id",
"}",
"\n",
"}"
] | // NewPopulatedProtoPeerID generates a populated instance of the custom gogo type ProtoPeerID.
// It is required by gogo-generated tests. | [
"NewPopulatedProtoPeerID",
"generates",
"a",
"populated",
"instance",
"of",
"the",
"custom",
"gogo",
"type",
"ProtoPeerID",
".",
"It",
"is",
"required",
"by",
"gogo",
"-",
"generated",
"tests",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pb/custom.go#L107-L110 |
9,461 | libp2p/go-libp2p-peerstore | pstoremem/addr_book.go | background | func (mab *memoryAddrBook) background() {
ticker := time.NewTicker(1 * time.Hour)
defer ticker.Stop()
for {
select {
case <-ticker.C:
mab.gc()
case <-mab.ctx.Done():
return
}
}
} | go | func (mab *memoryAddrBook) background() {
ticker := time.NewTicker(1 * time.Hour)
defer ticker.Stop()
for {
select {
case <-ticker.C:
mab.gc()
case <-mab.ctx.Done():
return
}
}
} | [
"func",
"(",
"mab",
"*",
"memoryAddrBook",
")",
"background",
"(",
")",
"{",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"1",
"*",
"time",
".",
"Hour",
")",
"\n",
"defer",
"ticker",
".",
"Stop",
"(",
")",
"\n\n",
"for",
"{",
"select",
"{",
"case... | // background periodically schedules a gc | [
"background",
"periodically",
"schedules",
"a",
"gc"
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L60-L73 |
9,462 | libp2p/go-libp2p-peerstore | pstoremem/addr_book.go | gc | func (mab *memoryAddrBook) gc() {
mab.addrmu.Lock()
defer mab.addrmu.Unlock()
now := time.Now()
for p, amap := range mab.addrs {
for k, addr := range amap {
if addr.ExpiredBy(now) {
delete(amap, k)
}
}
if len(amap) == 0 {
delete(mab.addrs, p)
}
}
} | go | func (mab *memoryAddrBook) gc() {
mab.addrmu.Lock()
defer mab.addrmu.Unlock()
now := time.Now()
for p, amap := range mab.addrs {
for k, addr := range amap {
if addr.ExpiredBy(now) {
delete(amap, k)
}
}
if len(amap) == 0 {
delete(mab.addrs, p)
}
}
} | [
"func",
"(",
"mab",
"*",
"memoryAddrBook",
")",
"gc",
"(",
")",
"{",
"mab",
".",
"addrmu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mab",
".",
"addrmu",
".",
"Unlock",
"(",
")",
"\n\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"for",
"p",... | // gc garbage collects the in-memory address book. | [
"gc",
"garbage",
"collects",
"the",
"in",
"-",
"memory",
"address",
"book",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L81-L96 |
9,463 | libp2p/go-libp2p-peerstore | pstoremem/addr_book.go | UpdateAddrs | func (mab *memoryAddrBook) UpdateAddrs(p peer.ID, oldTTL time.Duration, newTTL time.Duration) {
mab.addrmu.Lock()
defer mab.addrmu.Unlock()
amap, found := mab.addrs[p]
if !found {
return
}
exp := time.Now().Add(newTTL)
for k, addr := range amap {
if oldTTL == addr.TTL {
addr.TTL = newTTL
addr.Expires = exp
amap[k] = addr
}
}
} | go | func (mab *memoryAddrBook) UpdateAddrs(p peer.ID, oldTTL time.Duration, newTTL time.Duration) {
mab.addrmu.Lock()
defer mab.addrmu.Unlock()
amap, found := mab.addrs[p]
if !found {
return
}
exp := time.Now().Add(newTTL)
for k, addr := range amap {
if oldTTL == addr.TTL {
addr.TTL = newTTL
addr.Expires = exp
amap[k] = addr
}
}
} | [
"func",
"(",
"mab",
"*",
"memoryAddrBook",
")",
"UpdateAddrs",
"(",
"p",
"peer",
".",
"ID",
",",
"oldTTL",
"time",
".",
"Duration",
",",
"newTTL",
"time",
".",
"Duration",
")",
"{",
"mab",
".",
"addrmu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mab",
... | // UpdateAddrs updates the addresses associated with the given peer that have
// the given oldTTL to have the given newTTL. | [
"UpdateAddrs",
"updates",
"the",
"addresses",
"associated",
"with",
"the",
"given",
"peer",
"that",
"have",
"the",
"given",
"oldTTL",
"to",
"have",
"the",
"given",
"newTTL",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L185-L202 |
9,464 | libp2p/go-libp2p-peerstore | pstoremem/addr_book.go | ClearAddrs | func (mab *memoryAddrBook) ClearAddrs(p peer.ID) {
mab.addrmu.Lock()
defer mab.addrmu.Unlock()
delete(mab.addrs, p)
} | go | func (mab *memoryAddrBook) ClearAddrs(p peer.ID) {
mab.addrmu.Lock()
defer mab.addrmu.Unlock()
delete(mab.addrs, p)
} | [
"func",
"(",
"mab",
"*",
"memoryAddrBook",
")",
"ClearAddrs",
"(",
"p",
"peer",
".",
"ID",
")",
"{",
"mab",
".",
"addrmu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mab",
".",
"addrmu",
".",
"Unlock",
"(",
")",
"\n\n",
"delete",
"(",
"mab",
".",
"ad... | // ClearAddrs removes all previously stored addresses | [
"ClearAddrs",
"removes",
"all",
"previously",
"stored",
"addresses"
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L226-L231 |
9,465 | libp2p/go-libp2p-peerstore | pstoremem/addr_book.go | removeSub | func (mgr *AddrSubManager) removeSub(p peer.ID, s *addrSub) {
mgr.mu.Lock()
defer mgr.mu.Unlock()
subs := mgr.subs[p]
if len(subs) == 1 {
if subs[0] != s {
return
}
delete(mgr.subs, p)
return
}
for i, v := range subs {
if v == s {
subs[i] = subs[len(subs)-1]
subs[len(subs)-1] = nil
mgr.subs[p] = subs[:len(subs)-1]
return
}
}
} | go | func (mgr *AddrSubManager) removeSub(p peer.ID, s *addrSub) {
mgr.mu.Lock()
defer mgr.mu.Unlock()
subs := mgr.subs[p]
if len(subs) == 1 {
if subs[0] != s {
return
}
delete(mgr.subs, p)
return
}
for i, v := range subs {
if v == s {
subs[i] = subs[len(subs)-1]
subs[len(subs)-1] = nil
mgr.subs[p] = subs[:len(subs)-1]
return
}
}
} | [
"func",
"(",
"mgr",
"*",
"AddrSubManager",
")",
"removeSub",
"(",
"p",
"peer",
".",
"ID",
",",
"s",
"*",
"addrSub",
")",
"{",
"mgr",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mgr",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"subs",
":=... | // Used internally by the address stream coroutine to remove a subscription
// from the manager. | [
"Used",
"internally",
"by",
"the",
"address",
"stream",
"coroutine",
"to",
"remove",
"a",
"subscription",
"from",
"the",
"manager",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L278-L299 |
9,466 | libp2p/go-libp2p-peerstore | pstoremem/addr_book.go | BroadcastAddr | func (mgr *AddrSubManager) BroadcastAddr(p peer.ID, addr ma.Multiaddr) {
mgr.mu.RLock()
defer mgr.mu.RUnlock()
if subs, ok := mgr.subs[p]; ok {
for _, sub := range subs {
sub.pubAddr(addr)
}
}
} | go | func (mgr *AddrSubManager) BroadcastAddr(p peer.ID, addr ma.Multiaddr) {
mgr.mu.RLock()
defer mgr.mu.RUnlock()
if subs, ok := mgr.subs[p]; ok {
for _, sub := range subs {
sub.pubAddr(addr)
}
}
} | [
"func",
"(",
"mgr",
"*",
"AddrSubManager",
")",
"BroadcastAddr",
"(",
"p",
"peer",
".",
"ID",
",",
"addr",
"ma",
".",
"Multiaddr",
")",
"{",
"mgr",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"mgr",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n\... | // BroadcastAddr broadcasts a new address to all subscribed streams. | [
"BroadcastAddr",
"broadcasts",
"a",
"new",
"address",
"to",
"all",
"subscribed",
"streams",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L302-L311 |
9,467 | libp2p/go-libp2p-peerstore | pstoremem/addr_book.go | AddrStream | func (mgr *AddrSubManager) AddrStream(ctx context.Context, p peer.ID, initial []ma.Multiaddr) <-chan ma.Multiaddr {
sub := &addrSub{pubch: make(chan ma.Multiaddr), ctx: ctx}
out := make(chan ma.Multiaddr)
mgr.mu.Lock()
if _, ok := mgr.subs[p]; ok {
mgr.subs[p] = append(mgr.subs[p], sub)
} else {
mgr.subs[p] = []*addrSub{sub}
}
mgr.mu.Unlock()
sort.Sort(addr.AddrList(initial))
go func(buffer []ma.Multiaddr) {
defer close(out)
sent := make(map[string]bool, len(buffer))
var outch chan ma.Multiaddr
for _, a := range buffer {
sent[string(a.Bytes())] = true
}
var next ma.Multiaddr
if len(buffer) > 0 {
next = buffer[0]
buffer = buffer[1:]
outch = out
}
for {
select {
case outch <- next:
if len(buffer) > 0 {
next = buffer[0]
buffer = buffer[1:]
} else {
outch = nil
next = nil
}
case naddr := <-sub.pubch:
if sent[string(naddr.Bytes())] {
continue
}
sent[string(naddr.Bytes())] = true
if next == nil {
next = naddr
outch = out
} else {
buffer = append(buffer, naddr)
}
case <-ctx.Done():
mgr.removeSub(p, sub)
return
}
}
}(initial)
return out
} | go | func (mgr *AddrSubManager) AddrStream(ctx context.Context, p peer.ID, initial []ma.Multiaddr) <-chan ma.Multiaddr {
sub := &addrSub{pubch: make(chan ma.Multiaddr), ctx: ctx}
out := make(chan ma.Multiaddr)
mgr.mu.Lock()
if _, ok := mgr.subs[p]; ok {
mgr.subs[p] = append(mgr.subs[p], sub)
} else {
mgr.subs[p] = []*addrSub{sub}
}
mgr.mu.Unlock()
sort.Sort(addr.AddrList(initial))
go func(buffer []ma.Multiaddr) {
defer close(out)
sent := make(map[string]bool, len(buffer))
var outch chan ma.Multiaddr
for _, a := range buffer {
sent[string(a.Bytes())] = true
}
var next ma.Multiaddr
if len(buffer) > 0 {
next = buffer[0]
buffer = buffer[1:]
outch = out
}
for {
select {
case outch <- next:
if len(buffer) > 0 {
next = buffer[0]
buffer = buffer[1:]
} else {
outch = nil
next = nil
}
case naddr := <-sub.pubch:
if sent[string(naddr.Bytes())] {
continue
}
sent[string(naddr.Bytes())] = true
if next == nil {
next = naddr
outch = out
} else {
buffer = append(buffer, naddr)
}
case <-ctx.Done():
mgr.removeSub(p, sub)
return
}
}
}(initial)
return out
} | [
"func",
"(",
"mgr",
"*",
"AddrSubManager",
")",
"AddrStream",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"peer",
".",
"ID",
",",
"initial",
"[",
"]",
"ma",
".",
"Multiaddr",
")",
"<-",
"chan",
"ma",
".",
"Multiaddr",
"{",
"sub",
":=",
"&",
"a... | // AddrStream creates a new subscription for a given peer ID, pre-populating the
// channel with any addresses we might already have on file. | [
"AddrStream",
"creates",
"a",
"new",
"subscription",
"for",
"a",
"given",
"peer",
"ID",
"pre",
"-",
"populating",
"the",
"channel",
"with",
"any",
"addresses",
"we",
"might",
"already",
"have",
"on",
"file",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L315-L377 |
9,468 | libp2p/go-libp2p-peerstore | peerstore.go | NewPeerstore | func NewPeerstore(kb KeyBook, ab AddrBook, md PeerMetadata) Peerstore {
return &peerstore{
KeyBook: kb,
AddrBook: ab,
PeerMetadata: md,
Metrics: NewMetrics(),
internedProtocols: make(map[string]string),
}
} | go | func NewPeerstore(kb KeyBook, ab AddrBook, md PeerMetadata) Peerstore {
return &peerstore{
KeyBook: kb,
AddrBook: ab,
PeerMetadata: md,
Metrics: NewMetrics(),
internedProtocols: make(map[string]string),
}
} | [
"func",
"NewPeerstore",
"(",
"kb",
"KeyBook",
",",
"ab",
"AddrBook",
",",
"md",
"PeerMetadata",
")",
"Peerstore",
"{",
"return",
"&",
"peerstore",
"{",
"KeyBook",
":",
"kb",
",",
"AddrBook",
":",
"ab",
",",
"PeerMetadata",
":",
"md",
",",
"Metrics",
":",... | // NewPeerstore creates a data structure that stores peer data, backed by the
// supplied implementations of KeyBook, AddrBook and PeerMetadata. | [
"NewPeerstore",
"creates",
"a",
"data",
"structure",
"that",
"stores",
"peer",
"data",
"backed",
"by",
"the",
"supplied",
"implementations",
"of",
"KeyBook",
"AddrBook",
"and",
"PeerMetadata",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/peerstore.go#L30-L38 |
9,469 | libp2p/go-libp2p-peerstore | pstoreds/addr_book_gc.go | background | func (gc *dsAddrBookGc) background() {
defer gc.ab.childrenDone.Done()
select {
case <-time.After(gc.ab.opts.GCInitialDelay):
case <-gc.ab.ctx.Done():
// yield if we have been cancelled/closed before the delay elapses.
return
}
purgeTimer := time.NewTicker(gc.ab.opts.GCPurgeInterval)
defer purgeTimer.Stop()
var lookaheadCh <-chan time.Time
if gc.lookaheadEnabled {
lookaheadTimer := time.NewTicker(gc.ab.opts.GCLookaheadInterval)
lookaheadCh = lookaheadTimer.C
gc.populateLookahead() // do a lookahead now
defer lookaheadTimer.Stop()
}
for {
select {
case <-purgeTimer.C:
gc.purgeFunc()
case <-lookaheadCh:
// will never trigger if lookahead is disabled (nil Duration).
gc.populateLookahead()
case <-gc.ctx.Done():
return
}
}
} | go | func (gc *dsAddrBookGc) background() {
defer gc.ab.childrenDone.Done()
select {
case <-time.After(gc.ab.opts.GCInitialDelay):
case <-gc.ab.ctx.Done():
// yield if we have been cancelled/closed before the delay elapses.
return
}
purgeTimer := time.NewTicker(gc.ab.opts.GCPurgeInterval)
defer purgeTimer.Stop()
var lookaheadCh <-chan time.Time
if gc.lookaheadEnabled {
lookaheadTimer := time.NewTicker(gc.ab.opts.GCLookaheadInterval)
lookaheadCh = lookaheadTimer.C
gc.populateLookahead() // do a lookahead now
defer lookaheadTimer.Stop()
}
for {
select {
case <-purgeTimer.C:
gc.purgeFunc()
case <-lookaheadCh:
// will never trigger if lookahead is disabled (nil Duration).
gc.populateLookahead()
case <-gc.ctx.Done():
return
}
}
} | [
"func",
"(",
"gc",
"*",
"dsAddrBookGc",
")",
"background",
"(",
")",
"{",
"defer",
"gc",
".",
"ab",
".",
"childrenDone",
".",
"Done",
"(",
")",
"\n\n",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"gc",
".",
"ab",
".",
"opts",
".",
"GC... | // gc prunes expired addresses from the datastore at regular intervals. It should be spawned as a goroutine. | [
"gc",
"prunes",
"expired",
"addresses",
"from",
"the",
"datastore",
"at",
"regular",
"intervals",
".",
"It",
"should",
"be",
"spawned",
"as",
"a",
"goroutine",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book_gc.go#L94-L128 |
9,470 | libp2p/go-libp2p-peerstore | pstoreds/addr_book.go | flush | func (r *addrsRecord) flush(write ds.Write) (err error) {
key := addrBookBase.ChildString(b32.RawStdEncoding.EncodeToString([]byte(r.Id.ID)))
if len(r.Addrs) == 0 {
if err = write.Delete(key); err == nil {
r.dirty = false
}
return err
}
data, err := r.Marshal()
if err != nil {
return err
}
if err = write.Put(key, data); err != nil {
return err
}
// write succeeded; record is no longer dirty.
r.dirty = false
return nil
} | go | func (r *addrsRecord) flush(write ds.Write) (err error) {
key := addrBookBase.ChildString(b32.RawStdEncoding.EncodeToString([]byte(r.Id.ID)))
if len(r.Addrs) == 0 {
if err = write.Delete(key); err == nil {
r.dirty = false
}
return err
}
data, err := r.Marshal()
if err != nil {
return err
}
if err = write.Put(key, data); err != nil {
return err
}
// write succeeded; record is no longer dirty.
r.dirty = false
return nil
} | [
"func",
"(",
"r",
"*",
"addrsRecord",
")",
"flush",
"(",
"write",
"ds",
".",
"Write",
")",
"(",
"err",
"error",
")",
"{",
"key",
":=",
"addrBookBase",
".",
"ChildString",
"(",
"b32",
".",
"RawStdEncoding",
".",
"EncodeToString",
"(",
"[",
"]",
"byte",
... | // flush writes the record to the datastore by calling ds.Put, unless the record is
// marked for deletion, in which case we call ds.Delete. To be called within a lock. | [
"flush",
"writes",
"the",
"record",
"to",
"the",
"datastore",
"by",
"calling",
"ds",
".",
"Put",
"unless",
"the",
"record",
"is",
"marked",
"for",
"deletion",
"in",
"which",
"case",
"we",
"call",
"ds",
".",
"Delete",
".",
"To",
"be",
"called",
"within",
... | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L48-L67 |
9,471 | libp2p/go-libp2p-peerstore | pstoreds/addr_book.go | AddAddr | func (ab *dsAddrBook) AddAddr(p peer.ID, addr ma.Multiaddr, ttl time.Duration) {
ab.AddAddrs(p, []ma.Multiaddr{addr}, ttl)
} | go | func (ab *dsAddrBook) AddAddr(p peer.ID, addr ma.Multiaddr, ttl time.Duration) {
ab.AddAddrs(p, []ma.Multiaddr{addr}, ttl)
} | [
"func",
"(",
"ab",
"*",
"dsAddrBook",
")",
"AddAddr",
"(",
"p",
"peer",
".",
"ID",
",",
"addr",
"ma",
".",
"Multiaddr",
",",
"ttl",
"time",
".",
"Duration",
")",
"{",
"ab",
".",
"AddAddrs",
"(",
"p",
",",
"[",
"]",
"ma",
".",
"Multiaddr",
"{",
... | // AddAddr will add a new address if it's not already in the AddrBook. | [
"AddAddr",
"will",
"add",
"a",
"new",
"address",
"if",
"it",
"s",
"not",
"already",
"in",
"the",
"AddrBook",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L233-L235 |
9,472 | libp2p/go-libp2p-peerstore | pstoreds/addr_book.go | AddAddrs | func (ab *dsAddrBook) AddAddrs(p peer.ID, addrs []ma.Multiaddr, ttl time.Duration) {
if ttl <= 0 {
return
}
addrs = cleanAddrs(addrs)
ab.setAddrs(p, addrs, ttl, ttlExtend)
} | go | func (ab *dsAddrBook) AddAddrs(p peer.ID, addrs []ma.Multiaddr, ttl time.Duration) {
if ttl <= 0 {
return
}
addrs = cleanAddrs(addrs)
ab.setAddrs(p, addrs, ttl, ttlExtend)
} | [
"func",
"(",
"ab",
"*",
"dsAddrBook",
")",
"AddAddrs",
"(",
"p",
"peer",
".",
"ID",
",",
"addrs",
"[",
"]",
"ma",
".",
"Multiaddr",
",",
"ttl",
"time",
".",
"Duration",
")",
"{",
"if",
"ttl",
"<=",
"0",
"{",
"return",
"\n",
"}",
"\n",
"addrs",
... | // AddAddrs will add many new addresses if they're not already in the AddrBook. | [
"AddAddrs",
"will",
"add",
"many",
"new",
"addresses",
"if",
"they",
"re",
"not",
"already",
"in",
"the",
"AddrBook",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L238-L244 |
9,473 | libp2p/go-libp2p-peerstore | pstoreds/addr_book.go | SetAddr | func (ab *dsAddrBook) SetAddr(p peer.ID, addr ma.Multiaddr, ttl time.Duration) {
ab.SetAddrs(p, []ma.Multiaddr{addr}, ttl)
} | go | func (ab *dsAddrBook) SetAddr(p peer.ID, addr ma.Multiaddr, ttl time.Duration) {
ab.SetAddrs(p, []ma.Multiaddr{addr}, ttl)
} | [
"func",
"(",
"ab",
"*",
"dsAddrBook",
")",
"SetAddr",
"(",
"p",
"peer",
".",
"ID",
",",
"addr",
"ma",
".",
"Multiaddr",
",",
"ttl",
"time",
".",
"Duration",
")",
"{",
"ab",
".",
"SetAddrs",
"(",
"p",
",",
"[",
"]",
"ma",
".",
"Multiaddr",
"{",
... | // SetAddr will add or update the TTL of an address in the AddrBook. | [
"SetAddr",
"will",
"add",
"or",
"update",
"the",
"TTL",
"of",
"an",
"address",
"in",
"the",
"AddrBook",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L247-L249 |
9,474 | libp2p/go-libp2p-peerstore | pstoreds/addr_book.go | SetAddrs | func (ab *dsAddrBook) SetAddrs(p peer.ID, addrs []ma.Multiaddr, ttl time.Duration) {
addrs = cleanAddrs(addrs)
if ttl <= 0 {
ab.deleteAddrs(p, addrs)
return
}
ab.setAddrs(p, addrs, ttl, ttlOverride)
} | go | func (ab *dsAddrBook) SetAddrs(p peer.ID, addrs []ma.Multiaddr, ttl time.Duration) {
addrs = cleanAddrs(addrs)
if ttl <= 0 {
ab.deleteAddrs(p, addrs)
return
}
ab.setAddrs(p, addrs, ttl, ttlOverride)
} | [
"func",
"(",
"ab",
"*",
"dsAddrBook",
")",
"SetAddrs",
"(",
"p",
"peer",
".",
"ID",
",",
"addrs",
"[",
"]",
"ma",
".",
"Multiaddr",
",",
"ttl",
"time",
".",
"Duration",
")",
"{",
"addrs",
"=",
"cleanAddrs",
"(",
"addrs",
")",
"\n",
"if",
"ttl",
"... | // SetAddrs will add or update the TTLs of addresses in the AddrBook. | [
"SetAddrs",
"will",
"add",
"or",
"update",
"the",
"TTLs",
"of",
"addresses",
"in",
"the",
"AddrBook",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L252-L259 |
9,475 | libp2p/go-libp2p-peerstore | pstoreds/addr_book.go | UpdateAddrs | func (ab *dsAddrBook) UpdateAddrs(p peer.ID, oldTTL time.Duration, newTTL time.Duration) {
pr, err := ab.loadRecord(p, true, false)
if err != nil {
log.Errorf("failed to update ttls for peer %s: %s\n", p.Pretty(), err)
return
}
pr.Lock()
defer pr.Unlock()
newExp := time.Now().Add(newTTL).Unix()
for _, entry := range pr.Addrs {
if entry.Ttl != int64(oldTTL) {
continue
}
entry.Ttl, entry.Expiry = int64(newTTL), newExp
pr.dirty = true
}
if pr.clean() {
pr.flush(ab.ds)
}
} | go | func (ab *dsAddrBook) UpdateAddrs(p peer.ID, oldTTL time.Duration, newTTL time.Duration) {
pr, err := ab.loadRecord(p, true, false)
if err != nil {
log.Errorf("failed to update ttls for peer %s: %s\n", p.Pretty(), err)
return
}
pr.Lock()
defer pr.Unlock()
newExp := time.Now().Add(newTTL).Unix()
for _, entry := range pr.Addrs {
if entry.Ttl != int64(oldTTL) {
continue
}
entry.Ttl, entry.Expiry = int64(newTTL), newExp
pr.dirty = true
}
if pr.clean() {
pr.flush(ab.ds)
}
} | [
"func",
"(",
"ab",
"*",
"dsAddrBook",
")",
"UpdateAddrs",
"(",
"p",
"peer",
".",
"ID",
",",
"oldTTL",
"time",
".",
"Duration",
",",
"newTTL",
"time",
".",
"Duration",
")",
"{",
"pr",
",",
"err",
":=",
"ab",
".",
"loadRecord",
"(",
"p",
",",
"true",... | // UpdateAddrs will update any addresses for a given peer and TTL combination to
// have a new TTL. | [
"UpdateAddrs",
"will",
"update",
"any",
"addresses",
"for",
"a",
"given",
"peer",
"and",
"TTL",
"combination",
"to",
"have",
"a",
"new",
"TTL",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L263-L285 |
9,476 | libp2p/go-libp2p-peerstore | pstoreds/addr_book.go | Addrs | func (ab *dsAddrBook) Addrs(p peer.ID) []ma.Multiaddr {
pr, err := ab.loadRecord(p, true, true)
if err != nil {
log.Warning("failed to load peerstore entry for peer %v while querying addrs, err: %v", p, err)
return nil
}
pr.RLock()
defer pr.RUnlock()
addrs := make([]ma.Multiaddr, 0, len(pr.Addrs))
for _, a := range pr.Addrs {
addrs = append(addrs, a.Addr)
}
return addrs
} | go | func (ab *dsAddrBook) Addrs(p peer.ID) []ma.Multiaddr {
pr, err := ab.loadRecord(p, true, true)
if err != nil {
log.Warning("failed to load peerstore entry for peer %v while querying addrs, err: %v", p, err)
return nil
}
pr.RLock()
defer pr.RUnlock()
addrs := make([]ma.Multiaddr, 0, len(pr.Addrs))
for _, a := range pr.Addrs {
addrs = append(addrs, a.Addr)
}
return addrs
} | [
"func",
"(",
"ab",
"*",
"dsAddrBook",
")",
"Addrs",
"(",
"p",
"peer",
".",
"ID",
")",
"[",
"]",
"ma",
".",
"Multiaddr",
"{",
"pr",
",",
"err",
":=",
"ab",
".",
"loadRecord",
"(",
"p",
",",
"true",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"n... | // Addrs returns all of the non-expired addresses for a given peer. | [
"Addrs",
"returns",
"all",
"of",
"the",
"non",
"-",
"expired",
"addresses",
"for",
"a",
"given",
"peer",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L288-L303 |
9,477 | libp2p/go-libp2p-peerstore | pstoreds/addr_book.go | PeersWithAddrs | func (ab *dsAddrBook) PeersWithAddrs() peer.IDSlice {
ids, err := uniquePeerIds(ab.ds, addrBookBase, func(result query.Result) string {
return ds.RawKey(result.Key).Name()
})
if err != nil {
log.Errorf("error while retrieving peers with addresses: %v", err)
}
return ids
} | go | func (ab *dsAddrBook) PeersWithAddrs() peer.IDSlice {
ids, err := uniquePeerIds(ab.ds, addrBookBase, func(result query.Result) string {
return ds.RawKey(result.Key).Name()
})
if err != nil {
log.Errorf("error while retrieving peers with addresses: %v", err)
}
return ids
} | [
"func",
"(",
"ab",
"*",
"dsAddrBook",
")",
"PeersWithAddrs",
"(",
")",
"peer",
".",
"IDSlice",
"{",
"ids",
",",
"err",
":=",
"uniquePeerIds",
"(",
"ab",
".",
"ds",
",",
"addrBookBase",
",",
"func",
"(",
"result",
"query",
".",
"Result",
")",
"string",
... | // Peers returns all of the peer IDs for which the AddrBook has addresses. | [
"Peers",
"returns",
"all",
"of",
"the",
"peer",
"IDs",
"for",
"which",
"the",
"AddrBook",
"has",
"addresses",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L306-L314 |
9,478 | libp2p/go-libp2p-peerstore | pstoreds/addr_book.go | ClearAddrs | func (ab *dsAddrBook) ClearAddrs(p peer.ID) {
ab.cache.Remove(p)
key := addrBookBase.ChildString(b32.RawStdEncoding.EncodeToString([]byte(p)))
if err := ab.ds.Delete(key); err != nil {
log.Errorf("failed to clear addresses for peer %s: %v", p.Pretty(), err)
}
} | go | func (ab *dsAddrBook) ClearAddrs(p peer.ID) {
ab.cache.Remove(p)
key := addrBookBase.ChildString(b32.RawStdEncoding.EncodeToString([]byte(p)))
if err := ab.ds.Delete(key); err != nil {
log.Errorf("failed to clear addresses for peer %s: %v", p.Pretty(), err)
}
} | [
"func",
"(",
"ab",
"*",
"dsAddrBook",
")",
"ClearAddrs",
"(",
"p",
"peer",
".",
"ID",
")",
"{",
"ab",
".",
"cache",
".",
"Remove",
"(",
"p",
")",
"\n\n",
"key",
":=",
"addrBookBase",
".",
"ChildString",
"(",
"b32",
".",
"RawStdEncoding",
".",
"Encode... | // ClearAddrs will delete all known addresses for a peer ID. | [
"ClearAddrs",
"will",
"delete",
"all",
"known",
"addresses",
"for",
"a",
"peer",
"ID",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L324-L331 |
9,479 | libp2p/go-libp2p-peerstore | queue/sync.go | NewChanQueue | func NewChanQueue(ctx context.Context, pq PeerQueue) *ChanQueue {
cq := &ChanQueue{Queue: pq}
cq.process(ctx)
return cq
} | go | func NewChanQueue(ctx context.Context, pq PeerQueue) *ChanQueue {
cq := &ChanQueue{Queue: pq}
cq.process(ctx)
return cq
} | [
"func",
"NewChanQueue",
"(",
"ctx",
"context",
".",
"Context",
",",
"pq",
"PeerQueue",
")",
"*",
"ChanQueue",
"{",
"cq",
":=",
"&",
"ChanQueue",
"{",
"Queue",
":",
"pq",
"}",
"\n",
"cq",
".",
"process",
"(",
"ctx",
")",
"\n",
"return",
"cq",
"\n",
... | // NewChanQueue creates a ChanQueue by wrapping pq. | [
"NewChanQueue",
"creates",
"a",
"ChanQueue",
"by",
"wrapping",
"pq",
"."
] | 96639ef5f4c339131552acf2e283d2d041602798 | https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/queue/sync.go#L20-L24 |
9,480 | sendgrid/rest | rest.go | AddQueryParameters | func AddQueryParameters(baseURL string, queryParams map[string]string) string {
baseURL += "?"
params := url.Values{}
for key, value := range queryParams {
params.Add(key, value)
}
return baseURL + params.Encode()
} | go | func AddQueryParameters(baseURL string, queryParams map[string]string) string {
baseURL += "?"
params := url.Values{}
for key, value := range queryParams {
params.Add(key, value)
}
return baseURL + params.Encode()
} | [
"func",
"AddQueryParameters",
"(",
"baseURL",
"string",
",",
"queryParams",
"map",
"[",
"string",
"]",
"string",
")",
"string",
"{",
"baseURL",
"+=",
"\"",
"\"",
"\n",
"params",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"for",
"key",
",",
"value",
":... | // AddQueryParameters adds query parameters to the URL. | [
"AddQueryParameters",
"adds",
"query",
"parameters",
"to",
"the",
"URL",
"."
] | 8f995deebcbbba440a60746115fdb5524e7cf3fc | https://github.com/sendgrid/rest/blob/8f995deebcbbba440a60746115fdb5524e7cf3fc/rest.go#L60-L67 |
9,481 | sendgrid/rest | rest.go | BuildRequestObject | func BuildRequestObject(request Request) (*http.Request, error) {
// Add any query parameters to the URL.
if len(request.QueryParams) != 0 {
request.BaseURL = AddQueryParameters(request.BaseURL, request.QueryParams)
}
req, err := http.NewRequest(string(request.Method), request.BaseURL, bytes.NewBuffer(request.Body))
if err != nil {
return req, err
}
for key, value := range request.Headers {
req.Header.Set(key, value)
}
_, exists := req.Header["Content-Type"]
if len(request.Body) > 0 && !exists {
req.Header.Set("Content-Type", "application/json")
}
return req, err
} | go | func BuildRequestObject(request Request) (*http.Request, error) {
// Add any query parameters to the URL.
if len(request.QueryParams) != 0 {
request.BaseURL = AddQueryParameters(request.BaseURL, request.QueryParams)
}
req, err := http.NewRequest(string(request.Method), request.BaseURL, bytes.NewBuffer(request.Body))
if err != nil {
return req, err
}
for key, value := range request.Headers {
req.Header.Set(key, value)
}
_, exists := req.Header["Content-Type"]
if len(request.Body) > 0 && !exists {
req.Header.Set("Content-Type", "application/json")
}
return req, err
} | [
"func",
"BuildRequestObject",
"(",
"request",
"Request",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"// Add any query parameters to the URL.",
"if",
"len",
"(",
"request",
".",
"QueryParams",
")",
"!=",
"0",
"{",
"request",
".",
"BaseURL",
... | // BuildRequestObject creates the HTTP request object. | [
"BuildRequestObject",
"creates",
"the",
"HTTP",
"request",
"object",
"."
] | 8f995deebcbbba440a60746115fdb5524e7cf3fc | https://github.com/sendgrid/rest/blob/8f995deebcbbba440a60746115fdb5524e7cf3fc/rest.go#L70-L87 |
9,482 | sendgrid/rest | rest.go | MakeRequest | func MakeRequest(req *http.Request) (*http.Response, error) {
return DefaultClient.HTTPClient.Do(req)
} | go | func MakeRequest(req *http.Request) (*http.Response, error) {
return DefaultClient.HTTPClient.Do(req)
} | [
"func",
"MakeRequest",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"return",
"DefaultClient",
".",
"HTTPClient",
".",
"Do",
"(",
"req",
")",
"\n",
"}"
] | // MakeRequest makes the API call. | [
"MakeRequest",
"makes",
"the",
"API",
"call",
"."
] | 8f995deebcbbba440a60746115fdb5524e7cf3fc | https://github.com/sendgrid/rest/blob/8f995deebcbbba440a60746115fdb5524e7cf3fc/rest.go#L90-L92 |
9,483 | sendgrid/rest | rest.go | BuildResponse | func BuildResponse(res *http.Response) (*Response, error) {
body, err := ioutil.ReadAll(res.Body)
response := Response{
StatusCode: res.StatusCode,
Body: string(body),
Headers: res.Header,
}
res.Body.Close() // nolint
return &response, err
} | go | func BuildResponse(res *http.Response) (*Response, error) {
body, err := ioutil.ReadAll(res.Body)
response := Response{
StatusCode: res.StatusCode,
Body: string(body),
Headers: res.Header,
}
res.Body.Close() // nolint
return &response, err
} | [
"func",
"BuildResponse",
"(",
"res",
"*",
"http",
".",
"Response",
")",
"(",
"*",
"Response",
",",
"error",
")",
"{",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"res",
".",
"Body",
")",
"\n",
"response",
":=",
"Response",
"{",
"StatusCo... | // BuildResponse builds the response struct. | [
"BuildResponse",
"builds",
"the",
"response",
"struct",
"."
] | 8f995deebcbbba440a60746115fdb5524e7cf3fc | https://github.com/sendgrid/rest/blob/8f995deebcbbba440a60746115fdb5524e7cf3fc/rest.go#L95-L104 |
9,484 | sendgrid/rest | rest.go | MakeRequest | func (c *Client) MakeRequest(req *http.Request) (*http.Response, error) {
return c.HTTPClient.Do(req)
} | go | func (c *Client) MakeRequest(req *http.Request) (*http.Response, error) {
return c.HTTPClient.Do(req)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"MakeRequest",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"return",
"c",
".",
"HTTPClient",
".",
"Do",
"(",
"req",
")",
"\n",
"}"
] | // The following functions enable the ability to define a
// custom HTTP Client
// MakeRequest makes the API call. | [
"The",
"following",
"functions",
"enable",
"the",
"ability",
"to",
"define",
"a",
"custom",
"HTTP",
"Client",
"MakeRequest",
"makes",
"the",
"API",
"call",
"."
] | 8f995deebcbbba440a60746115fdb5524e7cf3fc | https://github.com/sendgrid/rest/blob/8f995deebcbbba440a60746115fdb5524e7cf3fc/rest.go#L120-L122 |
9,485 | sendgrid/rest | rest.go | Send | func (c *Client) Send(request Request) (*Response, error) {
// Build the HTTP request object.
req, err := BuildRequestObject(request)
if err != nil {
return nil, err
}
// Build the HTTP client and make the request.
res, err := c.MakeRequest(req)
if err != nil {
return nil, err
}
// Build Response object.
return BuildResponse(res)
} | go | func (c *Client) Send(request Request) (*Response, error) {
// Build the HTTP request object.
req, err := BuildRequestObject(request)
if err != nil {
return nil, err
}
// Build the HTTP client and make the request.
res, err := c.MakeRequest(req)
if err != nil {
return nil, err
}
// Build Response object.
return BuildResponse(res)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Send",
"(",
"request",
"Request",
")",
"(",
"*",
"Response",
",",
"error",
")",
"{",
"// Build the HTTP request object.",
"req",
",",
"err",
":=",
"BuildRequestObject",
"(",
"request",
")",
"\n",
"if",
"err",
"!=",
... | // Send will build your request, make the request, and build your response. | [
"Send",
"will",
"build",
"your",
"request",
"make",
"the",
"request",
"and",
"build",
"your",
"response",
"."
] | 8f995deebcbbba440a60746115fdb5524e7cf3fc | https://github.com/sendgrid/rest/blob/8f995deebcbbba440a60746115fdb5524e7cf3fc/rest.go#L130-L145 |
9,486 | olebedev/when | when.go | Parse | func (p *Parser) Parse(text string, base time.Time) (*Result, error) {
res := Result{
Source: text,
Time: base,
Index: -1,
}
if p.options == nil {
p.options = defaultOptions
}
var err error
// apply middlewares
for _, b := range p.middleware {
text, err = b(text)
if err != nil {
return nil, err
}
}
// find all matches
matches := make([]*rules.Match, 0)
c := float64(0)
for _, rule := range p.rules {
r := rule.Find(text)
if r != nil {
r.Order = c
c++
matches = append(matches, r)
}
}
// not found
if len(matches) == 0 {
return nil, nil
}
// find a cluster
sort.Sort(rules.MatchByIndex(matches))
// get borders of the matches
end := matches[0].Right
res.Index = matches[0].Left
for i, m := range matches {
if m.Left <= end+p.options.Distance {
end = m.Right
} else {
matches = matches[:i]
break
}
}
res.Text = text[res.Index:end]
// apply rules
if p.options.MatchByOrder {
sort.Sort(rules.MatchByOrder(matches))
}
ctx := &rules.Context{Text: res.Text}
applied := false
for _, applier := range matches {
ok, err := applier.Apply(ctx, p.options, res.Time)
if err != nil {
return nil, err
}
applied = ok || applied
}
if !applied {
return nil, nil
}
res.Time, err = ctx.Time(res.Time)
if err != nil {
return nil, errors.Wrap(err, "bind context")
}
return &res, nil
} | go | func (p *Parser) Parse(text string, base time.Time) (*Result, error) {
res := Result{
Source: text,
Time: base,
Index: -1,
}
if p.options == nil {
p.options = defaultOptions
}
var err error
// apply middlewares
for _, b := range p.middleware {
text, err = b(text)
if err != nil {
return nil, err
}
}
// find all matches
matches := make([]*rules.Match, 0)
c := float64(0)
for _, rule := range p.rules {
r := rule.Find(text)
if r != nil {
r.Order = c
c++
matches = append(matches, r)
}
}
// not found
if len(matches) == 0 {
return nil, nil
}
// find a cluster
sort.Sort(rules.MatchByIndex(matches))
// get borders of the matches
end := matches[0].Right
res.Index = matches[0].Left
for i, m := range matches {
if m.Left <= end+p.options.Distance {
end = m.Right
} else {
matches = matches[:i]
break
}
}
res.Text = text[res.Index:end]
// apply rules
if p.options.MatchByOrder {
sort.Sort(rules.MatchByOrder(matches))
}
ctx := &rules.Context{Text: res.Text}
applied := false
for _, applier := range matches {
ok, err := applier.Apply(ctx, p.options, res.Time)
if err != nil {
return nil, err
}
applied = ok || applied
}
if !applied {
return nil, nil
}
res.Time, err = ctx.Time(res.Time)
if err != nil {
return nil, errors.Wrap(err, "bind context")
}
return &res, nil
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"Parse",
"(",
"text",
"string",
",",
"base",
"time",
".",
"Time",
")",
"(",
"*",
"Result",
",",
"error",
")",
"{",
"res",
":=",
"Result",
"{",
"Source",
":",
"text",
",",
"Time",
":",
"base",
",",
"Index",
... | // Parse returns Result and error if any. If have not matches it returns nil, nil. | [
"Parse",
"returns",
"Result",
"and",
"error",
"if",
"any",
".",
"If",
"have",
"not",
"matches",
"it",
"returns",
"nil",
"nil",
"."
] | c3b538a972545a9584eadaea351b97264f29e8a8 | https://github.com/olebedev/when/blob/c3b538a972545a9584eadaea351b97264f29e8a8/when.go#L36-L116 |
9,487 | olebedev/when | when.go | Add | func (p *Parser) Add(r ...rules.Rule) {
p.rules = append(p.rules, r...)
} | go | func (p *Parser) Add(r ...rules.Rule) {
p.rules = append(p.rules, r...)
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"Add",
"(",
"r",
"...",
"rules",
".",
"Rule",
")",
"{",
"p",
".",
"rules",
"=",
"append",
"(",
"p",
".",
"rules",
",",
"r",
"...",
")",
"\n",
"}"
] | // Add adds given rules to the main chain. | [
"Add",
"adds",
"given",
"rules",
"to",
"the",
"main",
"chain",
"."
] | c3b538a972545a9584eadaea351b97264f29e8a8 | https://github.com/olebedev/when/blob/c3b538a972545a9584eadaea351b97264f29e8a8/when.go#L119-L121 |
9,488 | olebedev/when | when.go | Use | func (p *Parser) Use(f ...func(string) (string, error)) {
p.middleware = append(p.middleware, f...)
} | go | func (p *Parser) Use(f ...func(string) (string, error)) {
p.middleware = append(p.middleware, f...)
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"Use",
"(",
"f",
"...",
"func",
"(",
"string",
")",
"(",
"string",
",",
"error",
")",
")",
"{",
"p",
".",
"middleware",
"=",
"append",
"(",
"p",
".",
"middleware",
",",
"f",
"...",
")",
"\n",
"}"
] | // Use adds give functions to middlewares. | [
"Use",
"adds",
"give",
"functions",
"to",
"middlewares",
"."
] | c3b538a972545a9584eadaea351b97264f29e8a8 | https://github.com/olebedev/when/blob/c3b538a972545a9584eadaea351b97264f29e8a8/when.go#L124-L126 |
9,489 | olebedev/when | when.go | New | func New(o *rules.Options) *Parser {
if o == nil {
return &Parser{options: defaultOptions}
}
return &Parser{options: o}
} | go | func New(o *rules.Options) *Parser {
if o == nil {
return &Parser{options: defaultOptions}
}
return &Parser{options: o}
} | [
"func",
"New",
"(",
"o",
"*",
"rules",
".",
"Options",
")",
"*",
"Parser",
"{",
"if",
"o",
"==",
"nil",
"{",
"return",
"&",
"Parser",
"{",
"options",
":",
"defaultOptions",
"}",
"\n",
"}",
"\n",
"return",
"&",
"Parser",
"{",
"options",
":",
"o",
... | // New returns Parser initialised with given options. | [
"New",
"returns",
"Parser",
"initialised",
"with",
"given",
"options",
"."
] | c3b538a972545a9584eadaea351b97264f29e8a8 | https://github.com/olebedev/when/blob/c3b538a972545a9584eadaea351b97264f29e8a8/when.go#L134-L139 |
9,490 | rubyist/circuitbreaker | circuitbreaker.go | NewBreakerWithOptions | func NewBreakerWithOptions(options *Options) *Breaker {
if options == nil {
options = &Options{}
}
if options.Clock == nil {
options.Clock = clock.New()
}
if options.BackOff == nil {
b := backoff.NewExponentialBackOff()
b.InitialInterval = defaultInitialBackOffInterval
b.MaxElapsedTime = defaultBackoffMaxElapsedTime
b.Clock = options.Clock
b.Reset()
options.BackOff = b
}
if options.WindowTime == 0 {
options.WindowTime = DefaultWindowTime
}
if options.WindowBuckets == 0 {
options.WindowBuckets = DefaultWindowBuckets
}
return &Breaker{
BackOff: options.BackOff,
Clock: options.Clock,
ShouldTrip: options.ShouldTrip,
nextBackOff: options.BackOff.NextBackOff(),
counts: newWindow(options.WindowTime, options.WindowBuckets),
}
} | go | func NewBreakerWithOptions(options *Options) *Breaker {
if options == nil {
options = &Options{}
}
if options.Clock == nil {
options.Clock = clock.New()
}
if options.BackOff == nil {
b := backoff.NewExponentialBackOff()
b.InitialInterval = defaultInitialBackOffInterval
b.MaxElapsedTime = defaultBackoffMaxElapsedTime
b.Clock = options.Clock
b.Reset()
options.BackOff = b
}
if options.WindowTime == 0 {
options.WindowTime = DefaultWindowTime
}
if options.WindowBuckets == 0 {
options.WindowBuckets = DefaultWindowBuckets
}
return &Breaker{
BackOff: options.BackOff,
Clock: options.Clock,
ShouldTrip: options.ShouldTrip,
nextBackOff: options.BackOff.NextBackOff(),
counts: newWindow(options.WindowTime, options.WindowBuckets),
}
} | [
"func",
"NewBreakerWithOptions",
"(",
"options",
"*",
"Options",
")",
"*",
"Breaker",
"{",
"if",
"options",
"==",
"nil",
"{",
"options",
"=",
"&",
"Options",
"{",
"}",
"\n",
"}",
"\n\n",
"if",
"options",
".",
"Clock",
"==",
"nil",
"{",
"options",
".",
... | // NewBreakerWithOptions creates a base breaker with a specified backoff, clock and TripFunc | [
"NewBreakerWithOptions",
"creates",
"a",
"base",
"breaker",
"with",
"a",
"specified",
"backoff",
"clock",
"and",
"TripFunc"
] | 2074adba5ddc7d5f7559448a9c3066573521c5bf | https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L130-L163 |
9,491 | rubyist/circuitbreaker | circuitbreaker.go | NewRateBreaker | func NewRateBreaker(rate float64, minSamples int64) *Breaker {
return NewBreakerWithOptions(&Options{
ShouldTrip: RateTripFunc(rate, minSamples),
})
} | go | func NewRateBreaker(rate float64, minSamples int64) *Breaker {
return NewBreakerWithOptions(&Options{
ShouldTrip: RateTripFunc(rate, minSamples),
})
} | [
"func",
"NewRateBreaker",
"(",
"rate",
"float64",
",",
"minSamples",
"int64",
")",
"*",
"Breaker",
"{",
"return",
"NewBreakerWithOptions",
"(",
"&",
"Options",
"{",
"ShouldTrip",
":",
"RateTripFunc",
"(",
"rate",
",",
"minSamples",
")",
",",
"}",
")",
"\n",
... | // NewRateBreaker creates a Breaker with a RateTripFunc. | [
"NewRateBreaker",
"creates",
"a",
"Breaker",
"with",
"a",
"RateTripFunc",
"."
] | 2074adba5ddc7d5f7559448a9c3066573521c5bf | https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L185-L189 |
9,492 | rubyist/circuitbreaker | circuitbreaker.go | Subscribe | func (cb *Breaker) Subscribe() <-chan BreakerEvent {
eventReader := make(chan BreakerEvent)
output := make(chan BreakerEvent, 100)
go func() {
for v := range eventReader {
select {
case output <- v:
default:
<-output
output <- v
}
}
}()
cb.eventReceivers = append(cb.eventReceivers, eventReader)
return output
} | go | func (cb *Breaker) Subscribe() <-chan BreakerEvent {
eventReader := make(chan BreakerEvent)
output := make(chan BreakerEvent, 100)
go func() {
for v := range eventReader {
select {
case output <- v:
default:
<-output
output <- v
}
}
}()
cb.eventReceivers = append(cb.eventReceivers, eventReader)
return output
} | [
"func",
"(",
"cb",
"*",
"Breaker",
")",
"Subscribe",
"(",
")",
"<-",
"chan",
"BreakerEvent",
"{",
"eventReader",
":=",
"make",
"(",
"chan",
"BreakerEvent",
")",
"\n",
"output",
":=",
"make",
"(",
"chan",
"BreakerEvent",
",",
"100",
")",
"\n\n",
"go",
"... | // Subscribe returns a channel of BreakerEvents. Whenever the breaker changes state,
// the state will be sent over the channel. See BreakerEvent for the types of events. | [
"Subscribe",
"returns",
"a",
"channel",
"of",
"BreakerEvents",
".",
"Whenever",
"the",
"breaker",
"changes",
"state",
"the",
"state",
"will",
"be",
"sent",
"over",
"the",
"channel",
".",
"See",
"BreakerEvent",
"for",
"the",
"types",
"of",
"events",
"."
] | 2074adba5ddc7d5f7559448a9c3066573521c5bf | https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L193-L209 |
9,493 | rubyist/circuitbreaker | circuitbreaker.go | AddListener | func (cb *Breaker) AddListener(listener chan ListenerEvent) {
cb.listeners = append(cb.listeners, listener)
} | go | func (cb *Breaker) AddListener(listener chan ListenerEvent) {
cb.listeners = append(cb.listeners, listener)
} | [
"func",
"(",
"cb",
"*",
"Breaker",
")",
"AddListener",
"(",
"listener",
"chan",
"ListenerEvent",
")",
"{",
"cb",
".",
"listeners",
"=",
"append",
"(",
"cb",
".",
"listeners",
",",
"listener",
")",
"\n",
"}"
] | // AddListener adds a channel of ListenerEvents on behalf of a listener.
// The listener channel must be buffered. | [
"AddListener",
"adds",
"a",
"channel",
"of",
"ListenerEvents",
"on",
"behalf",
"of",
"a",
"listener",
".",
"The",
"listener",
"channel",
"must",
"be",
"buffered",
"."
] | 2074adba5ddc7d5f7559448a9c3066573521c5bf | https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L213-L215 |
9,494 | rubyist/circuitbreaker | circuitbreaker.go | RemoveListener | func (cb *Breaker) RemoveListener(listener chan ListenerEvent) bool {
for i, receiver := range cb.listeners {
if listener == receiver {
cb.listeners = append(cb.listeners[:i], cb.listeners[i+1:]...)
return true
}
}
return false
} | go | func (cb *Breaker) RemoveListener(listener chan ListenerEvent) bool {
for i, receiver := range cb.listeners {
if listener == receiver {
cb.listeners = append(cb.listeners[:i], cb.listeners[i+1:]...)
return true
}
}
return false
} | [
"func",
"(",
"cb",
"*",
"Breaker",
")",
"RemoveListener",
"(",
"listener",
"chan",
"ListenerEvent",
")",
"bool",
"{",
"for",
"i",
",",
"receiver",
":=",
"range",
"cb",
".",
"listeners",
"{",
"if",
"listener",
"==",
"receiver",
"{",
"cb",
".",
"listeners"... | // RemoveListener removes a channel previously added via AddListener.
// Once removed, the channel will no longer receive ListenerEvents.
// Returns true if the listener was found and removed. | [
"RemoveListener",
"removes",
"a",
"channel",
"previously",
"added",
"via",
"AddListener",
".",
"Once",
"removed",
"the",
"channel",
"will",
"no",
"longer",
"receive",
"ListenerEvents",
".",
"Returns",
"true",
"if",
"the",
"listener",
"was",
"found",
"and",
"remo... | 2074adba5ddc7d5f7559448a9c3066573521c5bf | https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L220-L228 |
9,495 | rubyist/circuitbreaker | circuitbreaker.go | ResetCounters | func (cb *Breaker) ResetCounters() {
atomic.StoreInt64(&cb.consecFailures, 0)
cb.counts.Reset()
} | go | func (cb *Breaker) ResetCounters() {
atomic.StoreInt64(&cb.consecFailures, 0)
cb.counts.Reset()
} | [
"func",
"(",
"cb",
"*",
"Breaker",
")",
"ResetCounters",
"(",
")",
"{",
"atomic",
".",
"StoreInt64",
"(",
"&",
"cb",
".",
"consecFailures",
",",
"0",
")",
"\n",
"cb",
".",
"counts",
".",
"Reset",
"(",
")",
"\n",
"}"
] | // ResetCounters will reset only the failures, consecFailures, and success counters | [
"ResetCounters",
"will",
"reset",
"only",
"the",
"failures",
"consecFailures",
"and",
"success",
"counters"
] | 2074adba5ddc7d5f7559448a9c3066573521c5bf | https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L250-L253 |
9,496 | rubyist/circuitbreaker | circuitbreaker.go | Fail | func (cb *Breaker) Fail() {
cb.counts.Fail()
atomic.AddInt64(&cb.consecFailures, 1)
now := cb.Clock.Now()
atomic.StoreInt64(&cb.lastFailure, now.UnixNano())
cb.sendEvent(BreakerFail)
if cb.ShouldTrip != nil && cb.ShouldTrip(cb) {
cb.Trip()
}
} | go | func (cb *Breaker) Fail() {
cb.counts.Fail()
atomic.AddInt64(&cb.consecFailures, 1)
now := cb.Clock.Now()
atomic.StoreInt64(&cb.lastFailure, now.UnixNano())
cb.sendEvent(BreakerFail)
if cb.ShouldTrip != nil && cb.ShouldTrip(cb) {
cb.Trip()
}
} | [
"func",
"(",
"cb",
"*",
"Breaker",
")",
"Fail",
"(",
")",
"{",
"cb",
".",
"counts",
".",
"Fail",
"(",
")",
"\n",
"atomic",
".",
"AddInt64",
"(",
"&",
"cb",
".",
"consecFailures",
",",
"1",
")",
"\n",
"now",
":=",
"cb",
".",
"Clock",
".",
"Now",... | // Fail is used to indicate a failure condition the Breaker should record. It will
// increment the failure counters and store the time of the last failure. If the
// breaker has a TripFunc it will be called, tripping the breaker if necessary. | [
"Fail",
"is",
"used",
"to",
"indicate",
"a",
"failure",
"condition",
"the",
"Breaker",
"should",
"record",
".",
"It",
"will",
"increment",
"the",
"failure",
"counters",
"and",
"store",
"the",
"time",
"of",
"the",
"last",
"failure",
".",
"If",
"the",
"break... | 2074adba5ddc7d5f7559448a9c3066573521c5bf | https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L285-L294 |
9,497 | rubyist/circuitbreaker | circuitbreaker.go | Ready | func (cb *Breaker) Ready() bool {
state := cb.state()
if state == halfopen {
atomic.StoreInt64(&cb.halfOpens, 0)
cb.sendEvent(BreakerReady)
}
return state == closed || state == halfopen
} | go | func (cb *Breaker) Ready() bool {
state := cb.state()
if state == halfopen {
atomic.StoreInt64(&cb.halfOpens, 0)
cb.sendEvent(BreakerReady)
}
return state == closed || state == halfopen
} | [
"func",
"(",
"cb",
"*",
"Breaker",
")",
"Ready",
"(",
")",
"bool",
"{",
"state",
":=",
"cb",
".",
"state",
"(",
")",
"\n",
"if",
"state",
"==",
"halfopen",
"{",
"atomic",
".",
"StoreInt64",
"(",
"&",
"cb",
".",
"halfOpens",
",",
"0",
")",
"\n",
... | // Ready will return true if the circuit breaker is ready to call the function.
// It will be ready if the breaker is in a reset state, or if it is time to retry
// the call for auto resetting. | [
"Ready",
"will",
"return",
"true",
"if",
"the",
"circuit",
"breaker",
"is",
"ready",
"to",
"call",
"the",
"function",
".",
"It",
"will",
"be",
"ready",
"if",
"the",
"breaker",
"is",
"in",
"a",
"reset",
"state",
"or",
"if",
"it",
"is",
"time",
"to",
"... | 2074adba5ddc7d5f7559448a9c3066573521c5bf | https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L321-L328 |
9,498 | rubyist/circuitbreaker | circuitbreaker.go | Call | func (cb *Breaker) Call(circuit func() error, timeout time.Duration) error {
return cb.CallContext(context.Background(), circuit, timeout)
} | go | func (cb *Breaker) Call(circuit func() error, timeout time.Duration) error {
return cb.CallContext(context.Background(), circuit, timeout)
} | [
"func",
"(",
"cb",
"*",
"Breaker",
")",
"Call",
"(",
"circuit",
"func",
"(",
")",
"error",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"return",
"cb",
".",
"CallContext",
"(",
"context",
".",
"Background",
"(",
")",
",",
"circuit",
",... | // Call wraps a function the Breaker will protect. A failure is recorded
// whenever the function returns an error. If the called function takes longer
// than timeout to run, a failure will be recorded. | [
"Call",
"wraps",
"a",
"function",
"the",
"Breaker",
"will",
"protect",
".",
"A",
"failure",
"is",
"recorded",
"whenever",
"the",
"function",
"returns",
"an",
"error",
".",
"If",
"the",
"called",
"function",
"takes",
"longer",
"than",
"timeout",
"to",
"run",
... | 2074adba5ddc7d5f7559448a9c3066573521c5bf | https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L333-L335 |
9,499 | rubyist/circuitbreaker | circuitbreaker.go | CallContext | func (cb *Breaker) CallContext(ctx context.Context, circuit func() error, timeout time.Duration) error {
var err error
if !cb.Ready() {
return ErrBreakerOpen
}
if timeout == 0 {
err = circuit()
} else {
c := make(chan error, 1)
go func() {
c <- circuit()
close(c)
}()
select {
case e := <-c:
err = e
case <-cb.Clock.After(timeout):
err = ErrBreakerTimeout
}
}
if err != nil {
if ctx.Err() != context.Canceled {
cb.Fail()
}
return err
}
cb.Success()
return nil
} | go | func (cb *Breaker) CallContext(ctx context.Context, circuit func() error, timeout time.Duration) error {
var err error
if !cb.Ready() {
return ErrBreakerOpen
}
if timeout == 0 {
err = circuit()
} else {
c := make(chan error, 1)
go func() {
c <- circuit()
close(c)
}()
select {
case e := <-c:
err = e
case <-cb.Clock.After(timeout):
err = ErrBreakerTimeout
}
}
if err != nil {
if ctx.Err() != context.Canceled {
cb.Fail()
}
return err
}
cb.Success()
return nil
} | [
"func",
"(",
"cb",
"*",
"Breaker",
")",
"CallContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"circuit",
"func",
"(",
")",
"error",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"var",
"err",
"error",
"\n\n",
"if",
"!",
"cb",
".",
... | // CallContext is same as Call but if the ctx is canceled after the circuit returned an error,
// the error will not be marked as a failure because the call was canceled intentionally. | [
"CallContext",
"is",
"same",
"as",
"Call",
"but",
"if",
"the",
"ctx",
"is",
"canceled",
"after",
"the",
"circuit",
"returned",
"an",
"error",
"the",
"error",
"will",
"not",
"be",
"marked",
"as",
"a",
"failure",
"because",
"the",
"call",
"was",
"canceled",
... | 2074adba5ddc7d5f7559448a9c3066573521c5bf | https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L339-L372 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.