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 list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
151,500 | cosiner/gohper | crypto/tls2/tls.go | CAPool | func CAPool(pems ...string) (p *x509.CertPool, err error) {
var data []byte
for i := 0; i < len(pems) && err == nil; i++ {
if data, err = ioutil.ReadFile(pems[i]); err == nil {
if p == nil {
p = x509.NewCertPool()
}
if !p.AppendCertsFromPEM(data) {
err = ErrBadPEMFile
}
}
}
return
} | go | func CAPool(pems ...string) (p *x509.CertPool, err error) {
var data []byte
for i := 0; i < len(pems) && err == nil; i++ {
if data, err = ioutil.ReadFile(pems[i]); err == nil {
if p == nil {
p = x509.NewCertPool()
}
if !p.AppendCertsFromPEM(data) {
err = ErrBadPEMFile
}
}
}
return
} | [
"func",
"CAPool",
"(",
"pems",
"...",
"string",
")",
"(",
"p",
"*",
"x509",
".",
"CertPool",
",",
"err",
"error",
")",
"{",
"var",
"data",
"[",
"]",
"byte",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"pems",
")",
"&&",
"err",
"==... | // CAPool create a ca pool use pem files | [
"CAPool",
"create",
"a",
"ca",
"pool",
"use",
"pem",
"files"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/crypto/tls2/tls.go#L13-L28 |
151,501 | cosiner/gohper | io2/filter.go | FilterRead | func FilterRead(r io.Reader, filter func(int, []byte) error) error {
return Filter(r, nil, false, func(linenum int, line []byte) ([]byte, error) {
return nil, filter(linenum, line)
})
} | go | func FilterRead(r io.Reader, filter func(int, []byte) error) error {
return Filter(r, nil, false, func(linenum int, line []byte) ([]byte, error) {
return nil, filter(linenum, line)
})
} | [
"func",
"FilterRead",
"(",
"r",
"io",
".",
"Reader",
",",
"filter",
"func",
"(",
"int",
",",
"[",
"]",
"byte",
")",
"error",
")",
"error",
"{",
"return",
"Filter",
"(",
"r",
",",
"nil",
",",
"false",
",",
"func",
"(",
"linenum",
"int",
",",
"line... | // FilterRead filter line from reader | [
"FilterRead",
"filter",
"line",
"from",
"reader"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/io2/filter.go#L19-L23 |
151,502 | cosiner/gohper | io2/filter.go | Filter | func Filter(r io.Reader, w io.Writer, sync bool, filter LineFilterFunc) error {
var (
save = func([]byte) {}
flush = func() error { return nil }
)
if w != nil {
var bufw interface {
Write([]byte) (int, error)
WriteString(string) (int, error)
}
if sync { // use bufio.Writer
bw := BufWriter(w)
flush = func() error {
return bw.Flush()
}
bufw = bw
} else { // use bytes.Buffer
bw := bytes.NewBuffer(make([]byte, 0, FileBufferSIze))
flush = func() error {
_, err := w.Write(bw.Bytes())
return err
}
bufw = bw
}
save = func(line []byte) {
bufw.Write(line)
bufw.WriteString("\n")
}
}
if filter == nil {
filter = NopLineFilter
}
var (
line []byte
linenum int
err error
br = BufReader(r)
)
for err == nil {
if line, _, err = br.ReadLine(); err == nil {
linenum++
if line, err = filter(linenum, line); err == nil || err == io.EOF {
if line != nil {
save(line)
}
}
}
}
if err == io.EOF {
flush()
err = nil
}
return err
} | go | func Filter(r io.Reader, w io.Writer, sync bool, filter LineFilterFunc) error {
var (
save = func([]byte) {}
flush = func() error { return nil }
)
if w != nil {
var bufw interface {
Write([]byte) (int, error)
WriteString(string) (int, error)
}
if sync { // use bufio.Writer
bw := BufWriter(w)
flush = func() error {
return bw.Flush()
}
bufw = bw
} else { // use bytes.Buffer
bw := bytes.NewBuffer(make([]byte, 0, FileBufferSIze))
flush = func() error {
_, err := w.Write(bw.Bytes())
return err
}
bufw = bw
}
save = func(line []byte) {
bufw.Write(line)
bufw.WriteString("\n")
}
}
if filter == nil {
filter = NopLineFilter
}
var (
line []byte
linenum int
err error
br = BufReader(r)
)
for err == nil {
if line, _, err = br.ReadLine(); err == nil {
linenum++
if line, err = filter(linenum, line); err == nil || err == io.EOF {
if line != nil {
save(line)
}
}
}
}
if err == io.EOF {
flush()
err = nil
}
return err
} | [
"func",
"Filter",
"(",
"r",
"io",
".",
"Reader",
",",
"w",
"io",
".",
"Writer",
",",
"sync",
"bool",
",",
"filter",
"LineFilterFunc",
")",
"error",
"{",
"var",
"(",
"save",
"=",
"func",
"(",
"[",
"]",
"byte",
")",
"{",
"}",
"\n",
"flush",
"=",
... | // Filter readline from reader, after filter, if sync set at the end, and writer is non-null,
// write content to writer, otherwise, every read operation will followed by
// a write operation
//
// return an error to stop filter, io.EOF means normal stop | [
"Filter",
"readline",
"from",
"reader",
"after",
"filter",
"if",
"sync",
"set",
"at",
"the",
"end",
"and",
"writer",
"is",
"non",
"-",
"null",
"write",
"content",
"to",
"writer",
"otherwise",
"every",
"read",
"operation",
"will",
"followed",
"by",
"a",
"wr... | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/io2/filter.go#L30-L91 |
151,503 | cosiner/gohper | os2/file/file.go | IsSymlink | func IsSymlink(fname string) bool {
fi, err := os.Lstat(fname)
return err == nil && (fi.Mode()&os.ModeSymlink == os.ModeSymlink)
} | go | func IsSymlink(fname string) bool {
fi, err := os.Lstat(fname)
return err == nil && (fi.Mode()&os.ModeSymlink == os.ModeSymlink)
} | [
"func",
"IsSymlink",
"(",
"fname",
"string",
")",
"bool",
"{",
"fi",
",",
"err",
":=",
"os",
".",
"Lstat",
"(",
"fname",
")",
"\n\n",
"return",
"err",
"==",
"nil",
"&&",
"(",
"fi",
".",
"Mode",
"(",
")",
"&",
"os",
".",
"ModeSymlink",
"==",
"os",... | // IsSymlink check whether or not given name is a symlink | [
"IsSymlink",
"check",
"whether",
"or",
"not",
"given",
"name",
"is",
"a",
"symlink"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/os2/file/file.go#L46-L50 |
151,504 | cosiner/gohper | os2/file/file.go | IsModifiedAfter | func IsModifiedAfter(fname string, fn func()) bool {
fi1, err := os.Stat(fname)
fn()
fi2, _ := os.Stat(fname)
return err == nil && !fi1.ModTime().Equal(fi2.ModTime())
} | go | func IsModifiedAfter(fname string, fn func()) bool {
fi1, err := os.Stat(fname)
fn()
fi2, _ := os.Stat(fname)
return err == nil && !fi1.ModTime().Equal(fi2.ModTime())
} | [
"func",
"IsModifiedAfter",
"(",
"fname",
"string",
",",
"fn",
"func",
"(",
")",
")",
"bool",
"{",
"fi1",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"fname",
")",
"\n",
"fn",
"(",
")",
"\n",
"fi2",
",",
"_",
":=",
"os",
".",
"Stat",
"(",
"fname",... | // IsModifiedAfter check whether or not file is modified by the function | [
"IsModifiedAfter",
"check",
"whether",
"or",
"not",
"file",
"is",
"modified",
"by",
"the",
"function"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/os2/file/file.go#L53-L59 |
151,505 | cosiner/gohper | os2/file/file.go | TruncSeek | func TruncSeek(fd *os.File) {
if fd != nil {
fd.Truncate(0)
fd.Seek(0, os.SEEK_SET)
}
} | go | func TruncSeek(fd *os.File) {
if fd != nil {
fd.Truncate(0)
fd.Seek(0, os.SEEK_SET)
}
} | [
"func",
"TruncSeek",
"(",
"fd",
"*",
"os",
".",
"File",
")",
"{",
"if",
"fd",
"!=",
"nil",
"{",
"fd",
".",
"Truncate",
"(",
"0",
")",
"\n",
"fd",
".",
"Seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"\n",
"}",
"\n",
"}"
] | // TruncSeek truncate file size to 0 and seek current positon to 0 | [
"TruncSeek",
"truncate",
"file",
"size",
"to",
"0",
"and",
"seek",
"current",
"positon",
"to",
"0"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/os2/file/file.go#L62-L67 |
151,506 | cosiner/gohper | ds/tree/trie.go | moveAllToChild | func (t *Trie) moveAllToChild(childStr string, newStr string) {
rnCopy := &Trie{
Str: childStr,
ChildChars: t.ChildChars,
Childs: t.Childs,
Value: t.Value,
}
t.ChildChars, t.Childs, t.Value = nil, nil, nil
t.addChild(childStr[0], rnCopy)
t.Str = newStr
} | go | func (t *Trie) moveAllToChild(childStr string, newStr string) {
rnCopy := &Trie{
Str: childStr,
ChildChars: t.ChildChars,
Childs: t.Childs,
Value: t.Value,
}
t.ChildChars, t.Childs, t.Value = nil, nil, nil
t.addChild(childStr[0], rnCopy)
t.Str = newStr
} | [
"func",
"(",
"t",
"*",
"Trie",
")",
"moveAllToChild",
"(",
"childStr",
"string",
",",
"newStr",
"string",
")",
"{",
"rnCopy",
":=",
"&",
"Trie",
"{",
"Str",
":",
"childStr",
",",
"ChildChars",
":",
"t",
".",
"ChildChars",
",",
"Childs",
":",
"t",
"."... | // moveAllToChild move all atreeributes to a new node, and make this new node
// as one of it's child | [
"moveAllToChild",
"move",
"all",
"atreeributes",
"to",
"a",
"new",
"node",
"and",
"make",
"this",
"new",
"node",
"as",
"one",
"of",
"it",
"s",
"child"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/tree/trie.go#L62-L73 |
151,507 | cosiner/gohper | ds/tree/trie.go | addChild | func (t *Trie) addChild(b byte, n *Trie) {
chars, childs := t.ChildChars, t.Childs
l := len(chars)
chars, childs = make([]byte, l+1), make([]*Trie, l+1)
copy(chars, t.ChildChars)
copy(childs, t.Childs)
for ; l > 0 && chars[l-1] > b; l-- {
chars[l], childs[l] = chars[l-1], childs[l-1]
}
chars[l], childs[l] = b, n
t.ChildChars, t.Childs = chars, childs
} | go | func (t *Trie) addChild(b byte, n *Trie) {
chars, childs := t.ChildChars, t.Childs
l := len(chars)
chars, childs = make([]byte, l+1), make([]*Trie, l+1)
copy(chars, t.ChildChars)
copy(childs, t.Childs)
for ; l > 0 && chars[l-1] > b; l-- {
chars[l], childs[l] = chars[l-1], childs[l-1]
}
chars[l], childs[l] = b, n
t.ChildChars, t.Childs = chars, childs
} | [
"func",
"(",
"t",
"*",
"Trie",
")",
"addChild",
"(",
"b",
"byte",
",",
"n",
"*",
"Trie",
")",
"{",
"chars",
",",
"childs",
":=",
"t",
".",
"ChildChars",
",",
"t",
".",
"Childs",
"\n",
"l",
":=",
"len",
"(",
"chars",
")",
"\n",
"chars",
",",
"... | // addChild add an child, all Childs is sorted | [
"addChild",
"add",
"an",
"child",
"all",
"Childs",
"is",
"sorted"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/tree/trie.go#L76-L88 |
151,508 | cosiner/gohper | ds/tree/trie.go | MatchValue | func (t *Trie) MatchValue(path string) interface{} {
t, _, m := t.Match(path)
if m != TRIE_FULL {
return nil
}
return t.Value
} | go | func (t *Trie) MatchValue(path string) interface{} {
t, _, m := t.Match(path)
if m != TRIE_FULL {
return nil
}
return t.Value
} | [
"func",
"(",
"t",
"*",
"Trie",
")",
"MatchValue",
"(",
"path",
"string",
")",
"interface",
"{",
"}",
"{",
"t",
",",
"_",
",",
"m",
":=",
"t",
".",
"Match",
"(",
"path",
")",
"\n",
"if",
"m",
"!=",
"TRIE_FULL",
"{",
"return",
"nil",
"\n",
"}",
... | // Match one longest route node and return values of path variable | [
"Match",
"one",
"longest",
"route",
"node",
"and",
"return",
"values",
"of",
"path",
"variable"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/tree/trie.go#L146-L153 |
151,509 | cosiner/gohper | ds/tree/trie.go | PrefixMatchValue | func (t *Trie) PrefixMatchValue(path string) interface{} {
if t = t.prefixMatch(nil, path); t == nil {
return nil
}
return t.Value
} | go | func (t *Trie) PrefixMatchValue(path string) interface{} {
if t = t.prefixMatch(nil, path); t == nil {
return nil
}
return t.Value
} | [
"func",
"(",
"t",
"*",
"Trie",
")",
"PrefixMatchValue",
"(",
"path",
"string",
")",
"interface",
"{",
"}",
"{",
"if",
"t",
"=",
"t",
".",
"prefixMatch",
"(",
"nil",
",",
"path",
")",
";",
"t",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",... | // PrefixMatchValue assumes each node as a prefix, it will match the longest prefix
// and return it's node value or nil | [
"PrefixMatchValue",
"assumes",
"each",
"node",
"as",
"a",
"prefix",
"it",
"will",
"match",
"the",
"longest",
"prefix",
"and",
"return",
"it",
"s",
"node",
"value",
"or",
"nil"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/tree/trie.go#L184-L190 |
151,510 | cosiner/gohper | goutil/format.go | Format | func Format(fname string, r io.Reader, w io.Writer) error {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, fname, r, parser.ParseComments)
if err != nil {
return err
}
return format.Node(w, fset, f)
} | go | func Format(fname string, r io.Reader, w io.Writer) error {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, fname, r, parser.ParseComments)
if err != nil {
return err
}
return format.Node(w, fset, f)
} | [
"func",
"Format",
"(",
"fname",
"string",
",",
"r",
"io",
".",
"Reader",
",",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"fset",
":=",
"token",
".",
"NewFileSet",
"(",
")",
"\n",
"f",
",",
"err",
":=",
"parser",
".",
"ParseFile",
"(",
"fset",
"... | // Format source from reader to writer | [
"Format",
"source",
"from",
"reader",
"to",
"writer"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/goutil/format.go#L11-L19 |
151,511 | cosiner/gohper | reflect2/reflect.go | IsSlice | func IsSlice(s interface{}) bool {
return s != nil && reflect.TypeOf(s).Kind() == reflect.Slice
} | go | func IsSlice(s interface{}) bool {
return s != nil && reflect.TypeOf(s).Kind() == reflect.Slice
} | [
"func",
"IsSlice",
"(",
"s",
"interface",
"{",
"}",
")",
"bool",
"{",
"return",
"s",
"!=",
"nil",
"&&",
"reflect",
".",
"TypeOf",
"(",
"s",
")",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Slice",
"\n",
"}"
] | // IsSlice check whether or not param is slice | [
"IsSlice",
"check",
"whether",
"or",
"not",
"param",
"is",
"slice"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/reflect2/reflect.go#L17-L19 |
151,512 | cosiner/gohper | reflect2/reflect.go | IndirectType | func IndirectType(v interface{}) reflect.Type {
typ := reflect.TypeOf(v)
if typ.Kind() == reflect.Ptr {
return typ.Elem()
}
return typ
} | go | func IndirectType(v interface{}) reflect.Type {
typ := reflect.TypeOf(v)
if typ.Kind() == reflect.Ptr {
return typ.Elem()
}
return typ
} | [
"func",
"IndirectType",
"(",
"v",
"interface",
"{",
"}",
")",
"reflect",
".",
"Type",
"{",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"v",
")",
"\n",
"if",
"typ",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"return",
"typ",
".",
"El... | // IndirectType return real type of value without pointer | [
"IndirectType",
"return",
"real",
"type",
"of",
"value",
"without",
"pointer"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/reflect2/reflect.go#L27-L34 |
151,513 | cosiner/gohper | reflect2/reflect.go | UnmarshalPrimitive | func UnmarshalPrimitive(str string, v reflect.Value) error {
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
switch k := v.Kind(); k {
case reflect.Bool:
v.SetBool(str[0] == 't')
case reflect.String:
v.SetString(str)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return err
}
v.SetInt(n)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
n, err := strconv.ParseUint(str, 10, 64)
if err == nil {
return err
}
v.SetUint(n)
case reflect.Float32, reflect.Float64:
n, err := strconv.ParseFloat(str, v.Type().Bits())
if err == nil {
return err
}
v.SetFloat(n)
default:
return ErrNonPrimitive
}
return nil
} | go | func UnmarshalPrimitive(str string, v reflect.Value) error {
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
switch k := v.Kind(); k {
case reflect.Bool:
v.SetBool(str[0] == 't')
case reflect.String:
v.SetString(str)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return err
}
v.SetInt(n)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
n, err := strconv.ParseUint(str, 10, 64)
if err == nil {
return err
}
v.SetUint(n)
case reflect.Float32, reflect.Float64:
n, err := strconv.ParseFloat(str, v.Type().Bits())
if err == nil {
return err
}
v.SetFloat(n)
default:
return ErrNonPrimitive
}
return nil
} | [
"func",
"UnmarshalPrimitive",
"(",
"str",
"string",
",",
"v",
"reflect",
".",
"Value",
")",
"error",
"{",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"v",
"=",
"v",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n\n",
"switch",
"k",
... | // UnmarshalPrimitive unmarshal bytes to primitive | [
"UnmarshalPrimitive",
"unmarshal",
"bytes",
"to",
"primitive"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/reflect2/reflect.go#L46-L81 |
151,514 | cosiner/gohper | utils/validate/validate.go | Validate | func (vc ValidChain) Validate(s string) error {
for _, v := range vc {
if e := v(s); e != nil {
return e
}
}
return nil
} | go | func (vc ValidChain) Validate(s string) error {
for _, v := range vc {
if e := v(s); e != nil {
return e
}
}
return nil
} | [
"func",
"(",
"vc",
"ValidChain",
")",
"Validate",
"(",
"s",
"string",
")",
"error",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"vc",
"{",
"if",
"e",
":=",
"v",
"(",
"s",
")",
";",
"e",
"!=",
"nil",
"{",
"return",
"e",
"\n",
"}",
"\n",
"}",
"... | // Validate string with validators, return first error or nil | [
"Validate",
"string",
"with",
"validators",
"return",
"first",
"error",
"or",
"nil"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/utils/validate/validate.go#L50-L58 |
151,515 | cosiner/gohper | crypto/encrypt/encrypt.go | Encode | func Encode(hash hash.Hash, msg, salt []byte) ([]byte, []byte, error) {
if hash == nil {
hash = sha256.New()
}
rand, err := rand.B.Alphanumeric(hash.Size())
if err != nil {
return nil, nil, err
}
return SaltEncode(hash, msg, salt, rand), rand, err
} | go | func Encode(hash hash.Hash, msg, salt []byte) ([]byte, []byte, error) {
if hash == nil {
hash = sha256.New()
}
rand, err := rand.B.Alphanumeric(hash.Size())
if err != nil {
return nil, nil, err
}
return SaltEncode(hash, msg, salt, rand), rand, err
} | [
"func",
"Encode",
"(",
"hash",
"hash",
".",
"Hash",
",",
"msg",
",",
"salt",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"hash",
"==",
"nil",
"{",
"hash",
"=",
"sha256",
".",
"New",
"(",
... | // Encode a message with fixed salt, return the encoded message and random salt | [
"Encode",
"a",
"message",
"with",
"fixed",
"salt",
"return",
"the",
"encoded",
"message",
"and",
"random",
"salt"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/crypto/encrypt/encrypt.go#L16-L26 |
151,516 | cosiner/gohper | crypto/encrypt/encrypt.go | SaltEncode | func SaltEncode(hash hash.Hash, msg, fixed, rand []byte) []byte {
if hash == nil {
hash = sha256.New()
}
hash.Write(msg)
enc := hash.Sum(nil)
hash.Reset()
hash.Write(fixed)
hash.Write(rand)
new := hash.Sum(nil)
hash.Reset()
hash.Write(enc)
hash.Write(new)
return hash.Sum(nil)
} | go | func SaltEncode(hash hash.Hash, msg, fixed, rand []byte) []byte {
if hash == nil {
hash = sha256.New()
}
hash.Write(msg)
enc := hash.Sum(nil)
hash.Reset()
hash.Write(fixed)
hash.Write(rand)
new := hash.Sum(nil)
hash.Reset()
hash.Write(enc)
hash.Write(new)
return hash.Sum(nil)
} | [
"func",
"SaltEncode",
"(",
"hash",
"hash",
".",
"Hash",
",",
"msg",
",",
"fixed",
",",
"rand",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"if",
"hash",
"==",
"nil",
"{",
"hash",
"=",
"sha256",
".",
"New",
"(",
")",
"\n",
"}",
"\n\n",
"hash",... | // SaltEncode encode the message with a fixed salt and a random salt, typically
// used to verify | [
"SaltEncode",
"encode",
"the",
"message",
"with",
"a",
"fixed",
"salt",
"and",
"a",
"random",
"salt",
"typically",
"used",
"to",
"verify"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/crypto/encrypt/encrypt.go#L30-L48 |
151,517 | cosiner/gohper | crypto/encrypt/encrypt.go | Verify | func Verify(hash hash.Hash, msg, salt, randSalt, pass []byte) bool {
return bytes.Equal(SaltEncode(hash, msg, salt, randSalt), pass)
} | go | func Verify(hash hash.Hash, msg, salt, randSalt, pass []byte) bool {
return bytes.Equal(SaltEncode(hash, msg, salt, randSalt), pass)
} | [
"func",
"Verify",
"(",
"hash",
"hash",
".",
"Hash",
",",
"msg",
",",
"salt",
",",
"randSalt",
",",
"pass",
"[",
"]",
"byte",
")",
"bool",
"{",
"return",
"bytes",
".",
"Equal",
"(",
"SaltEncode",
"(",
"hash",
",",
"msg",
",",
"salt",
",",
"randSalt"... | // Verify will encode msg, salt, randSalt, then compare it with encoded password,
// return true if equal, else false | [
"Verify",
"will",
"encode",
"msg",
"salt",
"randSalt",
"then",
"compare",
"it",
"with",
"encoded",
"password",
"return",
"true",
"if",
"equal",
"else",
"false"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/crypto/encrypt/encrypt.go#L52-L54 |
151,518 | cosiner/gohper | time2/time.go | DateDefNow | func DateDefNow(year, month, day, hour, minute, sec, nsec int) time.Time {
now := Now()
nyear, nmonth, nday := now.Date()
nhour, nminute, nsec := now.Clock()
if year < 0 {
year = nyear
}
if month < 0 {
month = int(nmonth)
}
if day < 0 {
day = nday
}
if hour < 0 {
hour = nhour
}
if minute < 0 {
minute = nminute
}
if sec < 0 {
sec = nsec
}
return time.Date(year, time.Month(month), day, hour, minute, sec, nsec, Location)
} | go | func DateDefNow(year, month, day, hour, minute, sec, nsec int) time.Time {
now := Now()
nyear, nmonth, nday := now.Date()
nhour, nminute, nsec := now.Clock()
if year < 0 {
year = nyear
}
if month < 0 {
month = int(nmonth)
}
if day < 0 {
day = nday
}
if hour < 0 {
hour = nhour
}
if minute < 0 {
minute = nminute
}
if sec < 0 {
sec = nsec
}
return time.Date(year, time.Month(month), day, hour, minute, sec, nsec, Location)
} | [
"func",
"DateDefNow",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"minute",
",",
"sec",
",",
"nsec",
"int",
")",
"time",
".",
"Time",
"{",
"now",
":=",
"Now",
"(",
")",
"\n",
"nyear",
",",
"nmonth",
",",
"nday",
":=",
"now",
".",
"... | // DateDefNow create a timestamp with given field, default use value of now if a
// field is less than 0 | [
"DateDefNow",
"create",
"a",
"timestamp",
"with",
"given",
"field",
"default",
"use",
"value",
"of",
"now",
"if",
"a",
"field",
"is",
"less",
"than",
"0"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/time2/time.go#L179-L203 |
151,519 | cosiner/gohper | utils/token/token.go | encrypt | func (c *Cipher) encrypt(deadline uint64, b []byte) []byte {
result := make([]byte, c.hdrLen+len(b))
binary.BigEndian.PutUint64(result[c.sigLen:c.hdrLen], deadline)
copy(result[c.hdrLen:], b)
hash := hmac.New(c.hash, c.signKey)
hash.Write(b)
hash.Write(result[c.sigLen:c.hdrLen])
copy(result, hash.Sum(nil)[:c.sigLen])
return result
} | go | func (c *Cipher) encrypt(deadline uint64, b []byte) []byte {
result := make([]byte, c.hdrLen+len(b))
binary.BigEndian.PutUint64(result[c.sigLen:c.hdrLen], deadline)
copy(result[c.hdrLen:], b)
hash := hmac.New(c.hash, c.signKey)
hash.Write(b)
hash.Write(result[c.sigLen:c.hdrLen])
copy(result, hash.Sum(nil)[:c.sigLen])
return result
} | [
"func",
"(",
"c",
"*",
"Cipher",
")",
"encrypt",
"(",
"deadline",
"uint64",
",",
"b",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"result",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"c",
".",
"hdrLen",
"+",
"len",
"(",
"b",
")",
")",
"\n",
... | // | signature | deadline | str | [
"|",
"signature",
"|",
"deadline",
"|",
"str"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/utils/token/token.go#L45-L56 |
151,520 | cosiner/gohper | ds/region/num.go | SeqByDir | func SeqByDir(a, b int, dir Direction) (int, int) {
if dir == POSITIVE {
return a, b
}
return b, a
} | go | func SeqByDir(a, b int, dir Direction) (int, int) {
if dir == POSITIVE {
return a, b
}
return b, a
} | [
"func",
"SeqByDir",
"(",
"a",
",",
"b",
"int",
",",
"dir",
"Direction",
")",
"(",
"int",
",",
"int",
")",
"{",
"if",
"dir",
"==",
"POSITIVE",
"{",
"return",
"a",
",",
"b",
"\n",
"}",
"\n\n",
"return",
"b",
",",
"a",
"\n",
"}"
] | // SeqByDir return the sequence of a and b sorted by direction
// if it's positive, a, b is returned, otherwise, b, a is returned | [
"SeqByDir",
"return",
"the",
"sequence",
"of",
"a",
"and",
"b",
"sorted",
"by",
"direction",
"if",
"it",
"s",
"positive",
"a",
"b",
"is",
"returned",
"otherwise",
"b",
"a",
"is",
"returned"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/region/num.go#L13-L19 |
151,521 | cosiner/gohper | ds/region/num.go | MinByDir | func MinByDir(a, b int, dir Direction) int {
if dir == POSITIVE {
return a
}
return b
} | go | func MinByDir(a, b int, dir Direction) int {
if dir == POSITIVE {
return a
}
return b
} | [
"func",
"MinByDir",
"(",
"a",
",",
"b",
"int",
",",
"dir",
"Direction",
")",
"int",
"{",
"if",
"dir",
"==",
"POSITIVE",
"{",
"return",
"a",
"\n",
"}",
"\n\n",
"return",
"b",
"\n",
"}"
] | // MinByDir return minimum of a and b sorted by direction | [
"MinByDir",
"return",
"minimum",
"of",
"a",
"and",
"b",
"sorted",
"by",
"direction"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/region/num.go#L22-L28 |
151,522 | cosiner/gohper | ds/region/num.go | MaxByDir | func MaxByDir(a, b int, dir Direction) int {
if dir == POSITIVE {
return b
}
return a
} | go | func MaxByDir(a, b int, dir Direction) int {
if dir == POSITIVE {
return b
}
return a
} | [
"func",
"MaxByDir",
"(",
"a",
",",
"b",
"int",
",",
"dir",
"Direction",
")",
"int",
"{",
"if",
"dir",
"==",
"POSITIVE",
"{",
"return",
"b",
"\n",
"}",
"\n\n",
"return",
"a",
"\n",
"}"
] | // MaxByDir return maxium of a and b sorted by direction | [
"MaxByDir",
"return",
"maxium",
"of",
"a",
"and",
"b",
"sorted",
"by",
"direction"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/region/num.go#L31-L37 |
151,523 | cosiner/gohper | ds/region/num.go | Seq | func Seq(a, b int) (int, int) {
if a <= b {
return a, b
}
return b, a
} | go | func Seq(a, b int) (int, int) {
if a <= b {
return a, b
}
return b, a
} | [
"func",
"Seq",
"(",
"a",
",",
"b",
"int",
")",
"(",
"int",
",",
"int",
")",
"{",
"if",
"a",
"<=",
"b",
"{",
"return",
"a",
",",
"b",
"\n",
"}",
"\n\n",
"return",
"b",
",",
"a",
"\n",
"}"
] | // Seq return sequenced a and b | [
"Seq",
"return",
"sequenced",
"a",
"and",
"b"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/region/num.go#L40-L46 |
151,524 | cosiner/gohper | ds/region/num.go | Mid | func Mid(a, b, c int) int {
if a >= b {
if b >= c {
return b
} else if a >= c {
return c
} else {
return a
}
} else {
if c <= a {
return a
} else if c <= b {
return c
} else {
return b
}
}
} | go | func Mid(a, b, c int) int {
if a >= b {
if b >= c {
return b
} else if a >= c {
return c
} else {
return a
}
} else {
if c <= a {
return a
} else if c <= b {
return c
} else {
return b
}
}
} | [
"func",
"Mid",
"(",
"a",
",",
"b",
",",
"c",
"int",
")",
"int",
"{",
"if",
"a",
">=",
"b",
"{",
"if",
"b",
">=",
"c",
"{",
"return",
"b",
"\n",
"}",
"else",
"if",
"a",
">=",
"c",
"{",
"return",
"c",
"\n",
"}",
"else",
"{",
"return",
"a",
... | // Mid return mid of three | [
"Mid",
"return",
"mid",
"of",
"three"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/region/num.go#L67-L85 |
151,525 | cosiner/gohper | ds/region/num.go | Pow | func Pow(base, power uint) uint64 {
n := uint64(1)
ubase := uint64(base)
for power > 0 {
n *= ubase
power--
}
return uint64(n)
} | go | func Pow(base, power uint) uint64 {
n := uint64(1)
ubase := uint64(base)
for power > 0 {
n *= ubase
power--
}
return uint64(n)
} | [
"func",
"Pow",
"(",
"base",
",",
"power",
"uint",
")",
"uint64",
"{",
"n",
":=",
"uint64",
"(",
"1",
")",
"\n",
"ubase",
":=",
"uint64",
"(",
"base",
")",
"\n",
"for",
"power",
">",
"0",
"{",
"n",
"*=",
"ubase",
"\n",
"power",
"--",
"\n",
"}",
... | // Pow return power of a base number | [
"Pow",
"return",
"power",
"of",
"a",
"base",
"number"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/region/num.go#L97-L106 |
151,526 | cosiner/gohper | bytes2/pool.go | ShrinkTo | func (p *ListPool) ShrinkTo(count int) {
if count < 0 {
return
}
p.Lock()
c := p.Count - count
if c > 0 {
p.Count = count
}
for ; c > 0; c-- {
p.head = p.head.next
}
p.Unlock()
} | go | func (p *ListPool) ShrinkTo(count int) {
if count < 0 {
return
}
p.Lock()
c := p.Count - count
if c > 0 {
p.Count = count
}
for ; c > 0; c-- {
p.head = p.head.next
}
p.Unlock()
} | [
"func",
"(",
"p",
"*",
"ListPool",
")",
"ShrinkTo",
"(",
"count",
"int",
")",
"{",
"if",
"count",
"<",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"p",
".",
"Lock",
"(",
")",
"\n",
"c",
":=",
"p",
".",
"Count",
"-",
"count",
"\n",
"if",
"c",
">",
... | // ShrinkTo cause the ListPool's buffer count reduce to count | [
"ShrinkTo",
"cause",
"the",
"ListPool",
"s",
"buffer",
"count",
"reduce",
"to",
"count"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/bytes2/pool.go#L171-L185 |
151,527 | cosiner/gohper | bytes2/pool.go | SyncSlotPool | func SyncSlotPool(slot, bufsize int, allowsmall bool) Pool {
var pools = make([]Pool, slot)
for i := 0; i < slot; i++ {
pools[i] = NewSyncPool(bufsize, allowsmall)
}
return NewSlotPool(pools)
} | go | func SyncSlotPool(slot, bufsize int, allowsmall bool) Pool {
var pools = make([]Pool, slot)
for i := 0; i < slot; i++ {
pools[i] = NewSyncPool(bufsize, allowsmall)
}
return NewSlotPool(pools)
} | [
"func",
"SyncSlotPool",
"(",
"slot",
",",
"bufsize",
"int",
",",
"allowsmall",
"bool",
")",
"Pool",
"{",
"var",
"pools",
"=",
"make",
"(",
"[",
"]",
"Pool",
",",
"slot",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"slot",
";",
"i",
"++",
"... | // SyncSlotPool create a SlotPool based on SyncPool | [
"SyncSlotPool",
"create",
"a",
"SlotPool",
"based",
"on",
"SyncPool"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/bytes2/pool.go#L225-L232 |
151,528 | cosiner/gohper | bytes2/pool.go | ListSlotPool | func ListSlotPool(slot, bufsize int, allowsmall bool) Pool {
var pools = make([]Pool, slot)
for i := 0; i < slot; i++ {
pools[i] = NewListPool(bufsize, allowsmall)
}
return NewSlotPool(pools)
} | go | func ListSlotPool(slot, bufsize int, allowsmall bool) Pool {
var pools = make([]Pool, slot)
for i := 0; i < slot; i++ {
pools[i] = NewListPool(bufsize, allowsmall)
}
return NewSlotPool(pools)
} | [
"func",
"ListSlotPool",
"(",
"slot",
",",
"bufsize",
"int",
",",
"allowsmall",
"bool",
")",
"Pool",
"{",
"var",
"pools",
"=",
"make",
"(",
"[",
"]",
"Pool",
",",
"slot",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"slot",
";",
"i",
"++",
"... | // SyncSlotPool create a SlotPool based on ListPool | [
"SyncSlotPool",
"create",
"a",
"SlotPool",
"based",
"on",
"ListPool"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/bytes2/pool.go#L235-L242 |
151,529 | cosiner/gohper | bytes2/bytes.go | SplitAndTrim | func SplitAndTrim(s, sep []byte) [][]byte {
sp := bytes.Split(s, sep)
for i, n := 0, len(sp); i < n; i++ {
sp[i] = bytes.TrimSpace(sp[i])
}
return sp
} | go | func SplitAndTrim(s, sep []byte) [][]byte {
sp := bytes.Split(s, sep)
for i, n := 0, len(sp); i < n; i++ {
sp[i] = bytes.TrimSpace(sp[i])
}
return sp
} | [
"func",
"SplitAndTrim",
"(",
"s",
",",
"sep",
"[",
"]",
"byte",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"sp",
":=",
"bytes",
".",
"Split",
"(",
"s",
",",
"sep",
")",
"\n",
"for",
"i",
",",
"n",
":=",
"0",
",",
"len",
"(",
"sp",
")",
";",
"i... | // SplitAndTrim split bytes array, and trim space on each section | [
"SplitAndTrim",
"split",
"bytes",
"array",
"and",
"trim",
"space",
"on",
"each",
"section"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/bytes2/bytes.go#L11-L18 |
151,530 | cosiner/gohper | bytes2/bytes.go | TrimAfter | func TrimAfter(s, delim []byte) []byte {
if idx := bytes.Index(s, delim); idx >= 0 {
s = s[:idx]
}
return bytes.TrimSpace(s)
} | go | func TrimAfter(s, delim []byte) []byte {
if idx := bytes.Index(s, delim); idx >= 0 {
s = s[:idx]
}
return bytes.TrimSpace(s)
} | [
"func",
"TrimAfter",
"(",
"s",
",",
"delim",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"if",
"idx",
":=",
"bytes",
".",
"Index",
"(",
"s",
",",
"delim",
")",
";",
"idx",
">=",
"0",
"{",
"s",
"=",
"s",
"[",
":",
"idx",
"]",
"\n",
"}",
... | // TrimAfter remove bytes after delimeter, and trim space on remains | [
"TrimAfter",
"remove",
"bytes",
"after",
"delimeter",
"and",
"trim",
"space",
"on",
"remains"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/bytes2/bytes.go#L21-L27 |
151,531 | cosiner/gohper | bytes2/bytes.go | IsAllBytesIn | func IsAllBytesIn(bs, encoding []byte) bool {
var is = true
for i := 0; i < len(bs) && is; i++ {
is = index.ByteIn(bs[i], encoding...) >= 0
}
return is
} | go | func IsAllBytesIn(bs, encoding []byte) bool {
var is = true
for i := 0; i < len(bs) && is; i++ {
is = index.ByteIn(bs[i], encoding...) >= 0
}
return is
} | [
"func",
"IsAllBytesIn",
"(",
"bs",
",",
"encoding",
"[",
"]",
"byte",
")",
"bool",
"{",
"var",
"is",
"=",
"true",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"bs",
")",
"&&",
"is",
";",
"i",
"++",
"{",
"is",
"=",
"index",
".",
"... | // IsAllBytesIn check whether all bytes is in given encoding bytes | [
"IsAllBytesIn",
"check",
"whether",
"all",
"bytes",
"is",
"in",
"given",
"encoding",
"bytes"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/bytes2/bytes.go#L38-L45 |
151,532 | cosiner/gohper | io2/writer_chain.go | NewWriterChain | func NewWriterChain(wr io.Writer) WriterChain {
if wr == nil {
return nil
}
return &writerChain{top: wr, base: wr, next: nil}
} | go | func NewWriterChain(wr io.Writer) WriterChain {
if wr == nil {
return nil
}
return &writerChain{top: wr, base: wr, next: nil}
} | [
"func",
"NewWriterChain",
"(",
"wr",
"io",
".",
"Writer",
")",
"WriterChain",
"{",
"if",
"wr",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"writerChain",
"{",
"top",
":",
"wr",
",",
"base",
":",
"wr",
",",
"next",
":",
"nil",... | // NewWriterChain create a new writer chain based on given writer
// parameter must not be nil, otherwise, nil was returned | [
"NewWriterChain",
"create",
"a",
"new",
"writer",
"chain",
"based",
"on",
"given",
"writer",
"parameter",
"must",
"not",
"be",
"nil",
"otherwise",
"nil",
"was",
"returned"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/io2/writer_chain.go#L22-L27 |
151,533 | cosiner/gohper | io2/writer_chain.go | Wrap | func (wc *writerChain) Wrap(wr io.Writer) {
newChain := &writerChain{
top: wc.top,
next: wc.next,
}
wc.top = wr
wc.next = newChain
} | go | func (wc *writerChain) Wrap(wr io.Writer) {
newChain := &writerChain{
top: wc.top,
next: wc.next,
}
wc.top = wr
wc.next = newChain
} | [
"func",
"(",
"wc",
"*",
"writerChain",
")",
"Wrap",
"(",
"wr",
"io",
".",
"Writer",
")",
"{",
"newChain",
":=",
"&",
"writerChain",
"{",
"top",
":",
"wc",
".",
"top",
",",
"next",
":",
"wc",
".",
"next",
",",
"}",
"\n\n",
"wc",
".",
"top",
"=",... | // Wrap add a writer to top of the writer chain | [
"Wrap",
"add",
"a",
"writer",
"to",
"top",
"of",
"the",
"writer",
"chain"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/io2/writer_chain.go#L44-L52 |
151,534 | cosiner/gohper | io2/writer_chain.go | Unwrap | func (wc *writerChain) Unwrap() (w io.Writer) {
next := wc.next
if next == nil {
return nil
}
w = wc.top
wc.top = next.top
wc.next = next.next
return w
} | go | func (wc *writerChain) Unwrap() (w io.Writer) {
next := wc.next
if next == nil {
return nil
}
w = wc.top
wc.top = next.top
wc.next = next.next
return w
} | [
"func",
"(",
"wc",
"*",
"writerChain",
")",
"Unwrap",
"(",
")",
"(",
"w",
"io",
".",
"Writer",
")",
"{",
"next",
":=",
"wc",
".",
"next",
"\n",
"if",
"next",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"w",
"=",
"wc",
".",
"top",
"\... | // Unwrap remove a writer on the top of writer chain and return it,
// if there is only the base one, nil was returned | [
"Unwrap",
"remove",
"a",
"writer",
"on",
"the",
"top",
"of",
"writer",
"chain",
"and",
"return",
"it",
"if",
"there",
"is",
"only",
"the",
"base",
"one",
"nil",
"was",
"returned"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/io2/writer_chain.go#L56-L67 |
151,535 | cosiner/gohper | crypto/rand/rand.go | Numberal | func (f BytesFunc) Numberal(n int) ([]byte, error) {
return f(n, NUMERALS)
} | go | func (f BytesFunc) Numberal(n int) ([]byte, error) {
return f(n, NUMERALS)
} | [
"func",
"(",
"f",
"BytesFunc",
")",
"Numberal",
"(",
"n",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"f",
"(",
"n",
",",
"NUMERALS",
")",
"\n",
"}"
] | // NumberalBytes generate random ASCII bytes | [
"NumberalBytes",
"generate",
"random",
"ASCII",
"bytes"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/crypto/rand/rand.go#L55-L57 |
151,536 | cosiner/gohper | crypto/rand/rand.go | Alphabet | func (f BytesFunc) Alphabet(n int) ([]byte, error) {
return f(n, ALPHABET)
} | go | func (f BytesFunc) Alphabet(n int) ([]byte, error) {
return f(n, ALPHABET)
} | [
"func",
"(",
"f",
"BytesFunc",
")",
"Alphabet",
"(",
"n",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"f",
"(",
"n",
",",
"ALPHABET",
")",
"\n",
"}"
] | // AlphabetBytes generate random ALPHABET bytes | [
"AlphabetBytes",
"generate",
"random",
"ALPHABET",
"bytes"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/crypto/rand/rand.go#L60-L62 |
151,537 | cosiner/gohper | crypto/rand/rand.go | Alphanumeric | func (f BytesFunc) Alphanumeric(n int) ([]byte, error) {
return f(n, ALPHANUMERIC)
} | go | func (f BytesFunc) Alphanumeric(n int) ([]byte, error) {
return f(n, ALPHANUMERIC)
} | [
"func",
"(",
"f",
"BytesFunc",
")",
"Alphanumeric",
"(",
"n",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"f",
"(",
"n",
",",
"ALPHANUMERIC",
")",
"\n",
"}"
] | // AlphanumericBytes generate random ALPHABET and numberic bytes | [
"AlphanumericBytes",
"generate",
"random",
"ALPHABET",
"and",
"numberic",
"bytes"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/crypto/rand/rand.go#L65-L67 |
151,538 | cosiner/gohper | crypto/rand/rand.go | Numberal | func (f StringFunc) Numberal(n int) (string, error) {
return f(n, NUMERALS)
} | go | func (f StringFunc) Numberal(n int) (string, error) {
return f(n, NUMERALS)
} | [
"func",
"(",
"f",
"StringFunc",
")",
"Numberal",
"(",
"n",
"int",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"f",
"(",
"n",
",",
"NUMERALS",
")",
"\n",
"}"
] | // Numberal generate random numberal string | [
"Numberal",
"generate",
"random",
"numberal",
"string"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/crypto/rand/rand.go#L70-L72 |
151,539 | cosiner/gohper | crypto/rand/rand.go | Alphabet | func (f StringFunc) Alphabet(n int) (string, error) {
return f(n, ALPHABET)
} | go | func (f StringFunc) Alphabet(n int) (string, error) {
return f(n, ALPHABET)
} | [
"func",
"(",
"f",
"StringFunc",
")",
"Alphabet",
"(",
"n",
"int",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"f",
"(",
"n",
",",
"ALPHABET",
")",
"\n",
"}"
] | // Alphabet generate random ALPHABET string | [
"Alphabet",
"generate",
"random",
"ALPHABET",
"string"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/crypto/rand/rand.go#L75-L77 |
151,540 | cosiner/gohper | crypto/rand/rand.go | Alphanumeric | func (f StringFunc) Alphanumeric(n int) (string, error) {
return f(n, ALPHANUMERIC)
} | go | func (f StringFunc) Alphanumeric(n int) (string, error) {
return f(n, ALPHANUMERIC)
} | [
"func",
"(",
"f",
"StringFunc",
")",
"Alphanumeric",
"(",
"n",
"int",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"f",
"(",
"n",
",",
"ALPHANUMERIC",
")",
"\n",
"}"
] | // Alphanumeric generate random ALPHABET and numberic string | [
"Alphanumeric",
"generate",
"random",
"ALPHABET",
"and",
"numberic",
"string"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/crypto/rand/rand.go#L80-L82 |
151,541 | cosiner/gohper | strings2/case.go | ToSnake | func ToSnake(s string) string {
num := len(s)
need := false // need determin if it's necessery to add a '_'
snake := make([]byte, 0, len(s)*2)
for i := 0; i < num; i++ {
c := s[i]
if c >= 'A' && c <= 'Z' {
c = c - 'A' + 'a'
if need {
snake = append(snake, '_')
}
} else {
// if previous is '_' or ' ',
// there is no need to add extra '_' before
need = (c != '_' && c != ' ')
}
snake = append(snake, c)
}
return string(snake)
} | go | func ToSnake(s string) string {
num := len(s)
need := false // need determin if it's necessery to add a '_'
snake := make([]byte, 0, len(s)*2)
for i := 0; i < num; i++ {
c := s[i]
if c >= 'A' && c <= 'Z' {
c = c - 'A' + 'a'
if need {
snake = append(snake, '_')
}
} else {
// if previous is '_' or ' ',
// there is no need to add extra '_' before
need = (c != '_' && c != ' ')
}
snake = append(snake, c)
}
return string(snake)
} | [
"func",
"ToSnake",
"(",
"s",
"string",
")",
"string",
"{",
"num",
":=",
"len",
"(",
"s",
")",
"\n",
"need",
":=",
"false",
"// need determin if it's necessery to add a '_'",
"\n\n",
"snake",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"len",
"(",... | // ToSnake string, XxYy to xx_yy, X_Y to x_y | [
"ToSnake",
"string",
"XxYy",
"to",
"xx_yy",
"X_Y",
"to",
"x_y"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/strings2/case.go#L6-L28 |
151,542 | cosiner/gohper | strings2/case.go | ToAbridge | func ToAbridge(str string) string {
l := len(str)
if l == 0 {
return ""
}
arbi := []byte{str[0]}
for i := 1; i < l; i++ {
b := str[i]
if unibyte.IsUpper(b) {
arbi = append(arbi, b)
}
}
return string(arbi)
} | go | func ToAbridge(str string) string {
l := len(str)
if l == 0 {
return ""
}
arbi := []byte{str[0]}
for i := 1; i < l; i++ {
b := str[i]
if unibyte.IsUpper(b) {
arbi = append(arbi, b)
}
}
return string(arbi)
} | [
"func",
"ToAbridge",
"(",
"str",
"string",
")",
"string",
"{",
"l",
":=",
"len",
"(",
"str",
")",
"\n",
"if",
"l",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"arbi",
":=",
"[",
"]",
"byte",
"{",
"str",
"[",
"0",
"]",
"}",
"\n",
... | // ToAbridge extract first letter and all upper case letter
// from string as it's abridge case | [
"ToAbridge",
"extract",
"first",
"letter",
"and",
"all",
"upper",
"case",
"letter",
"from",
"string",
"as",
"it",
"s",
"abridge",
"case"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/strings2/case.go#L66-L81 |
151,543 | cosiner/gohper | strings2/case.go | ToLowerAbridge | func ToLowerAbridge(str string) (s string) {
l := len(str)
if l == 0 {
return ""
}
arbi := []byte{unibyte.ToLower(str[0])}
for i := 1; i < l; i++ {
b := str[i]
if unibyte.IsUpper(b) {
arbi = append(arbi, unibyte.ToLower(b))
}
}
return string(arbi)
} | go | func ToLowerAbridge(str string) (s string) {
l := len(str)
if l == 0 {
return ""
}
arbi := []byte{unibyte.ToLower(str[0])}
for i := 1; i < l; i++ {
b := str[i]
if unibyte.IsUpper(b) {
arbi = append(arbi, unibyte.ToLower(b))
}
}
return string(arbi)
} | [
"func",
"ToLowerAbridge",
"(",
"str",
"string",
")",
"(",
"s",
"string",
")",
"{",
"l",
":=",
"len",
"(",
"str",
")",
"\n",
"if",
"l",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"arbi",
":=",
"[",
"]",
"byte",
"{",
"unibyte",
".",... | // ToLowerAbridge extract first letter and all upper case letter
// from string as it's abridge case, and convert it to lower case | [
"ToLowerAbridge",
"extract",
"first",
"letter",
"and",
"all",
"upper",
"case",
"letter",
"from",
"string",
"as",
"it",
"s",
"abridge",
"case",
"and",
"convert",
"it",
"to",
"lower",
"case"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/strings2/case.go#L85-L100 |
151,544 | cosiner/gohper | utils/pair/pair.go | Parse | func Parse(str, sep string) *Pair {
return parse(str, strings.Index(str, sep))
} | go | func Parse(str, sep string) *Pair {
return parse(str, strings.Index(str, sep))
} | [
"func",
"Parse",
"(",
"str",
",",
"sep",
"string",
")",
"*",
"Pair",
"{",
"return",
"parse",
"(",
"str",
",",
"strings",
".",
"Index",
"(",
"str",
",",
"sep",
")",
")",
"\n",
"}"
] | // Parse seperate string use first seperator string | [
"Parse",
"seperate",
"string",
"use",
"first",
"seperator",
"string"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/utils/pair/pair.go#L18-L20 |
151,545 | cosiner/gohper | utils/pair/pair.go | Rparse | func Rparse(str, sep string) *Pair {
return parse(str, strings.LastIndex(str, sep))
} | go | func Rparse(str, sep string) *Pair {
return parse(str, strings.LastIndex(str, sep))
} | [
"func",
"Rparse",
"(",
"str",
",",
"sep",
"string",
")",
"*",
"Pair",
"{",
"return",
"parse",
"(",
"str",
",",
"strings",
".",
"LastIndex",
"(",
"str",
",",
"sep",
")",
")",
"\n",
"}"
] | // Rparse seperate string use last seperator string | [
"Rparse",
"seperate",
"string",
"use",
"last",
"seperator",
"string"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/utils/pair/pair.go#L23-L25 |
151,546 | cosiner/gohper | utils/pair/pair.go | ParsePairWith | func ParsePairWith(str, sep string, sepIndexFn func(string, string) int) *Pair {
return parse(str, sepIndexFn(str, sep))
} | go | func ParsePairWith(str, sep string, sepIndexFn func(string, string) int) *Pair {
return parse(str, sepIndexFn(str, sep))
} | [
"func",
"ParsePairWith",
"(",
"str",
",",
"sep",
"string",
",",
"sepIndexFn",
"func",
"(",
"string",
",",
"string",
")",
"int",
")",
"*",
"Pair",
"{",
"return",
"parse",
"(",
"str",
",",
"sepIndexFn",
"(",
"str",
",",
"sep",
")",
")",
"\n",
"}"
] | // ParsePairWith seperate string use given function | [
"ParsePairWith",
"seperate",
"string",
"use",
"given",
"function"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/utils/pair/pair.go#L28-L30 |
151,547 | cosiner/gohper | utils/pair/pair.go | parse | func parse(str string, index int) *Pair {
var key, value string
if index > 0 {
key, value = str[:index], str[index+1:]
} else if index == 0 {
key, value = "", str[1:]
} else if index < 0 {
key, value = str, ""
}
return &Pair{Key: key, Value: value}
} | go | func parse(str string, index int) *Pair {
var key, value string
if index > 0 {
key, value = str[:index], str[index+1:]
} else if index == 0 {
key, value = "", str[1:]
} else if index < 0 {
key, value = str, ""
}
return &Pair{Key: key, Value: value}
} | [
"func",
"parse",
"(",
"str",
"string",
",",
"index",
"int",
")",
"*",
"Pair",
"{",
"var",
"key",
",",
"value",
"string",
"\n",
"if",
"index",
">",
"0",
"{",
"key",
",",
"value",
"=",
"str",
"[",
":",
"index",
"]",
",",
"str",
"[",
"index",
"+",... | // parse seperate string at given index
// if key or value is nil, set to "" | [
"parse",
"seperate",
"string",
"at",
"given",
"index",
"if",
"key",
"or",
"value",
"is",
"nil",
"set",
"to"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/utils/pair/pair.go#L34-L45 |
151,548 | cosiner/gohper | utils/pair/pair.go | String | func (p *Pair) String() string {
return fmt.Sprintf("(%s:%s)", p.Key, p.Value)
} | go | func (p *Pair) String() string {
return fmt.Sprintf("(%s:%s)", p.Key, p.Value)
} | [
"func",
"(",
"p",
"*",
"Pair",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
".",
"Key",
",",
"p",
".",
"Value",
")",
"\n",
"}"
] | // String return pair's display string, format as key=value | [
"String",
"return",
"pair",
"s",
"display",
"string",
"format",
"as",
"key",
"=",
"value"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/utils/pair/pair.go#L48-L50 |
151,549 | cosiner/gohper | utils/pair/pair.go | Trim | func (p *Pair) Trim() *Pair {
p.Key = strings.TrimSpace(p.Key)
p.Value = strings.TrimSpace(p.Value)
return p
} | go | func (p *Pair) Trim() *Pair {
p.Key = strings.TrimSpace(p.Key)
p.Value = strings.TrimSpace(p.Value)
return p
} | [
"func",
"(",
"p",
"*",
"Pair",
")",
"Trim",
"(",
")",
"*",
"Pair",
"{",
"p",
".",
"Key",
"=",
"strings",
".",
"TrimSpace",
"(",
"p",
".",
"Key",
")",
"\n",
"p",
".",
"Value",
"=",
"strings",
".",
"TrimSpace",
"(",
"p",
".",
"Value",
")",
"\n\... | // Trim trim all space of pair's key and value | [
"Trim",
"trim",
"all",
"space",
"of",
"pair",
"s",
"key",
"and",
"value"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/utils/pair/pair.go#L53-L58 |
151,550 | cosiner/gohper | utils/pair/pair.go | TrimQuote | func (p *Pair) TrimQuote() bool {
key, match := strings2.TrimQuote(p.Key)
if !match {
return false
}
fmt.Println(p.Value)
value, match := strings2.TrimQuote(p.Value)
fmt.Println(value, match)
if !match {
return false
}
p.Key, p.Value = key, value
return true
} | go | func (p *Pair) TrimQuote() bool {
key, match := strings2.TrimQuote(p.Key)
if !match {
return false
}
fmt.Println(p.Value)
value, match := strings2.TrimQuote(p.Value)
fmt.Println(value, match)
if !match {
return false
}
p.Key, p.Value = key, value
return true
} | [
"func",
"(",
"p",
"*",
"Pair",
")",
"TrimQuote",
"(",
")",
"bool",
"{",
"key",
",",
"match",
":=",
"strings2",
".",
"TrimQuote",
"(",
"p",
".",
"Key",
")",
"\n",
"if",
"!",
"match",
"{",
"return",
"false",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
... | // TrimQuote trim quote for pair's key and value | [
"TrimQuote",
"trim",
"quote",
"for",
"pair",
"s",
"key",
"and",
"value"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/utils/pair/pair.go#L61-L76 |
151,551 | cosiner/gohper | utils/pair/pair.go | ValueOrKey | func (p *Pair) ValueOrKey() string {
if p.HasValue() {
return p.Value
}
return p.Key
} | go | func (p *Pair) ValueOrKey() string {
if p.HasValue() {
return p.Value
}
return p.Key
} | [
"func",
"(",
"p",
"*",
"Pair",
")",
"ValueOrKey",
"(",
")",
"string",
"{",
"if",
"p",
".",
"HasValue",
"(",
")",
"{",
"return",
"p",
".",
"Value",
"\n",
"}",
"\n\n",
"return",
"p",
".",
"Key",
"\n",
"}"
] | // ValueOrKey return value when value is not "", otherwise return key | [
"ValueOrKey",
"return",
"value",
"when",
"value",
"is",
"not",
"otherwise",
"return",
"key"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/utils/pair/pair.go#L99-L105 |
151,552 | cosiner/gohper | sync2/sync.go | Do | func (o *Once) Do(fn ...func()) bool {
if !atomic.CompareAndSwapUint32((*uint32)(o), 0, 1) {
return false
}
for _, f := range fn {
if f != nil {
f()
}
}
return true
} | go | func (o *Once) Do(fn ...func()) bool {
if !atomic.CompareAndSwapUint32((*uint32)(o), 0, 1) {
return false
}
for _, f := range fn {
if f != nil {
f()
}
}
return true
} | [
"func",
"(",
"o",
"*",
"Once",
")",
"Do",
"(",
"fn",
"...",
"func",
"(",
")",
")",
"bool",
"{",
"if",
"!",
"atomic",
".",
"CompareAndSwapUint32",
"(",
"(",
"*",
"uint32",
")",
"(",
"o",
")",
",",
"0",
",",
"1",
")",
"{",
"return",
"false",
"\... | // Do will do f only once no matter it's successful or not
// if f is blocked, Do will also be | [
"Do",
"will",
"do",
"f",
"only",
"once",
"no",
"matter",
"it",
"s",
"successful",
"or",
"not",
"if",
"f",
"is",
"blocked",
"Do",
"will",
"also",
"be"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/sync2/sync.go#L10-L20 |
151,553 | cosiner/gohper | utils/bytesize/bytesize.go | SizeDef | func SizeDef(size string, defSize uint64) (s uint64) {
var err error
if s, err = Size(size); err != nil {
return defSize
}
return s
} | go | func SizeDef(size string, defSize uint64) (s uint64) {
var err error
if s, err = Size(size); err != nil {
return defSize
}
return s
} | [
"func",
"SizeDef",
"(",
"size",
"string",
",",
"defSize",
"uint64",
")",
"(",
"s",
"uint64",
")",
"{",
"var",
"err",
"error",
"\n",
"if",
"s",
",",
"err",
"=",
"Size",
"(",
"size",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"defSize",
"\n",
"}"... | // SizeDef is same as Size, on error return default size | [
"SizeDef",
"is",
"same",
"as",
"Size",
"on",
"error",
"return",
"default",
"size"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/utils/bytesize/bytesize.go#L55-L62 |
151,554 | cosiner/gohper | utils/bytesize/bytesize.go | MustSize | func MustSize(size string) (s uint64) {
s, err := Size(size)
if err != nil {
panic(err)
}
return s
} | go | func MustSize(size string) (s uint64) {
s, err := Size(size)
if err != nil {
panic(err)
}
return s
} | [
"func",
"MustSize",
"(",
"size",
"string",
")",
"(",
"s",
"uint64",
")",
"{",
"s",
",",
"err",
":=",
"Size",
"(",
"size",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"s",
"\n",
"}"
] | // MustSize is same as Size, on error panic | [
"MustSize",
"is",
"same",
"as",
"Size",
"on",
"error",
"panic"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/utils/bytesize/bytesize.go#L65-L72 |
151,555 | cosiner/gohper | ds/bitset/bits.go | BitsList | func BitsList(bits ...uint) *Bits {
var s uint64
for _, b := range bits {
s |= uint64(1 << b)
}
return ((*Bits)(&s))
} | go | func BitsList(bits ...uint) *Bits {
var s uint64
for _, b := range bits {
s |= uint64(1 << b)
}
return ((*Bits)(&s))
} | [
"func",
"BitsList",
"(",
"bits",
"...",
"uint",
")",
"*",
"Bits",
"{",
"var",
"s",
"uint64",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"bits",
"{",
"s",
"|=",
"uint64",
"(",
"1",
"<<",
"b",
")",
"\n",
"}",
"\n\n",
"return",
"(",
"(",
"*",
"B... | // BitsList create a Bits, set all bits in list to 1 | [
"BitsList",
"create",
"a",
"Bits",
"set",
"all",
"bits",
"in",
"list",
"to",
"1"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/bitset/bits.go#L14-L21 |
151,556 | cosiner/gohper | ds/bitset/bits.go | SetTo | func (s *Bits) SetTo(index uint, val bool) {
if val {
s.Set(index)
} else {
s.Unset(index)
}
} | go | func (s *Bits) SetTo(index uint, val bool) {
if val {
s.Set(index)
} else {
s.Unset(index)
}
} | [
"func",
"(",
"s",
"*",
"Bits",
")",
"SetTo",
"(",
"index",
"uint",
",",
"val",
"bool",
")",
"{",
"if",
"val",
"{",
"s",
".",
"Set",
"(",
"index",
")",
"\n",
"}",
"else",
"{",
"s",
".",
"Unset",
"(",
"index",
")",
"\n",
"}",
"\n",
"}"
] | // SetTo set bit at given index to 1 if val is true, else set to 0 | [
"SetTo",
"set",
"bit",
"at",
"given",
"index",
"to",
"1",
"if",
"val",
"is",
"true",
"else",
"set",
"to",
"0"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/bitset/bits.go#L56-L62 |
151,557 | cosiner/gohper | ds/bitset/bits.go | BitCount | func BitCount(n uint64) int {
n -= (n >> 1) & 0x5555555555555555
n = (n>>2)&0x3333333333333333 + n&0x3333333333333333
n += n >> 4
n &= 0x0f0f0f0f0f0f0f0f
n *= 0x0101010101010101
return int(n >> 56)
} | go | func BitCount(n uint64) int {
n -= (n >> 1) & 0x5555555555555555
n = (n>>2)&0x3333333333333333 + n&0x3333333333333333
n += n >> 4
n &= 0x0f0f0f0f0f0f0f0f
n *= 0x0101010101010101
return int(n >> 56)
} | [
"func",
"BitCount",
"(",
"n",
"uint64",
")",
"int",
"{",
"n",
"-=",
"(",
"n",
">>",
"1",
")",
"&",
"0x5555555555555555",
"\n",
"n",
"=",
"(",
"n",
">>",
"2",
")",
"&",
"0x3333333333333333",
"+",
"n",
"&",
"0x3333333333333333",
"\n",
"n",
"+=",
"n",... | // BitCount return count of 1 bit in uint64 | [
"BitCount",
"return",
"count",
"of",
"1",
"bit",
"in",
"uint64"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/bitset/bits.go#L110-L118 |
151,558 | cosiner/gohper | ds/bitset/bits.go | BitCountUint | func BitCountUint(x uint) int {
var n = uint64(x)
n -= (n >> 1) & 0x5555555555555555
n = (n>>2)&0x3333333333333333 + n&0x3333333333333333
n += n >> 4
n &= 0x0f0f0f0f0f0f0f0f
n *= 0x0101010101010101
return int(n >> 56)
} | go | func BitCountUint(x uint) int {
var n = uint64(x)
n -= (n >> 1) & 0x5555555555555555
n = (n>>2)&0x3333333333333333 + n&0x3333333333333333
n += n >> 4
n &= 0x0f0f0f0f0f0f0f0f
n *= 0x0101010101010101
return int(n >> 56)
} | [
"func",
"BitCountUint",
"(",
"x",
"uint",
")",
"int",
"{",
"var",
"n",
"=",
"uint64",
"(",
"x",
")",
"\n",
"n",
"-=",
"(",
"n",
">>",
"1",
")",
"&",
"0x5555555555555555",
"\n",
"n",
"=",
"(",
"n",
">>",
"2",
")",
"&",
"0x3333333333333333",
"+",
... | // BitCountUint return count of 1 bit in uint | [
"BitCountUint",
"return",
"count",
"of",
"1",
"bit",
"in",
"uint"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/ds/bitset/bits.go#L121-L130 |
151,559 | cosiner/gohper | terminal/color/renderer.go | New | func New(codes ...Code) *Renderer {
return &Renderer{
begin: []byte(Begin(codes...)),
end: []byte(End()),
}
} | go | func New(codes ...Code) *Renderer {
return &Renderer{
begin: []byte(Begin(codes...)),
end: []byte(End()),
}
} | [
"func",
"New",
"(",
"codes",
"...",
"Code",
")",
"*",
"Renderer",
"{",
"return",
"&",
"Renderer",
"{",
"begin",
":",
"[",
"]",
"byte",
"(",
"Begin",
"(",
"codes",
"...",
")",
")",
",",
"end",
":",
"[",
"]",
"byte",
"(",
"End",
"(",
")",
")",
... | // New a terminal color render, | [
"New",
"a",
"terminal",
"color",
"render"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/terminal/color/renderer.go#L29-L34 |
151,560 | cosiner/gohper | terminal/color/renderer.go | Render | func (r *Renderer) Render(str []byte) []byte {
bl, sl, el := len(r.begin), len(str), len(r.end)
data := make([]byte, bl+sl+el)
copy(data, r.begin)
copy(data[bl:], str)
copy(data[bl+sl:], r.end)
return data
} | go | func (r *Renderer) Render(str []byte) []byte {
bl, sl, el := len(r.begin), len(str), len(r.end)
data := make([]byte, bl+sl+el)
copy(data, r.begin)
copy(data[bl:], str)
copy(data[bl+sl:], r.end)
return data
} | [
"func",
"(",
"r",
"*",
"Renderer",
")",
"Render",
"(",
"str",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"bl",
",",
"sl",
",",
"el",
":=",
"len",
"(",
"r",
".",
"begin",
")",
",",
"len",
"(",
"str",
")",
",",
"len",
"(",
"r",
".",
"end... | // Render rend a string | [
"Render",
"rend",
"a",
"string"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/terminal/color/renderer.go#L45-L52 |
151,561 | cosiner/gohper | terminal/color/renderer.go | RenderTo | func (r *Renderer) RenderTo(w io.Writer, str ...[]byte) (int, error) {
err := r.Begin(w)
var (
n int
c int
)
for i := 0; err == nil && i < len(str); i++ {
c, err = w.Write(str[i])
n += c
}
r.End(w)
return n, err
} | go | func (r *Renderer) RenderTo(w io.Writer, str ...[]byte) (int, error) {
err := r.Begin(w)
var (
n int
c int
)
for i := 0; err == nil && i < len(str); i++ {
c, err = w.Write(str[i])
n += c
}
r.End(w)
return n, err
} | [
"func",
"(",
"r",
"*",
"Renderer",
")",
"RenderTo",
"(",
"w",
"io",
".",
"Writer",
",",
"str",
"...",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"err",
":=",
"r",
".",
"Begin",
"(",
"w",
")",
"\n",
"var",
"(",
"n",
"int",
"\... | // RenderTo render string to writer | [
"RenderTo",
"render",
"string",
"to",
"writer"
] | 700f92d01d8a55070e4db9cf57bc3d346d65c9e8 | https://github.com/cosiner/gohper/blob/700f92d01d8a55070e4db9cf57bc3d346d65c9e8/terminal/color/renderer.go#L59-L71 |
151,562 | vulcand/vulcan | threshold/parse.go | ParseExpression | func ParseExpression(in string) (Predicate, error) {
p, err := predicate.NewParser(predicate.Def{
Operators: predicate.Operators{
AND: AND,
OR: OR,
EQ: EQ,
NEQ: NEQ,
LT: LT,
LE: LE,
GT: GT,
GE: GE,
},
Functions: map[string]interface{}{
"RequestMethod": RequestMethod,
"IsNetworkError": IsNetworkError,
"Attempts": Attempts,
"ResponseCode": ResponseCode,
},
})
if err != nil {
return nil, err
}
out, err := p.Parse(convertLegacy(in))
if err != nil {
return nil, err
}
pr, ok := out.(Predicate)
if !ok {
return nil, fmt.Errorf("expected predicate, got %T", out)
}
return pr, nil
} | go | func ParseExpression(in string) (Predicate, error) {
p, err := predicate.NewParser(predicate.Def{
Operators: predicate.Operators{
AND: AND,
OR: OR,
EQ: EQ,
NEQ: NEQ,
LT: LT,
LE: LE,
GT: GT,
GE: GE,
},
Functions: map[string]interface{}{
"RequestMethod": RequestMethod,
"IsNetworkError": IsNetworkError,
"Attempts": Attempts,
"ResponseCode": ResponseCode,
},
})
if err != nil {
return nil, err
}
out, err := p.Parse(convertLegacy(in))
if err != nil {
return nil, err
}
pr, ok := out.(Predicate)
if !ok {
return nil, fmt.Errorf("expected predicate, got %T", out)
}
return pr, nil
} | [
"func",
"ParseExpression",
"(",
"in",
"string",
")",
"(",
"Predicate",
",",
"error",
")",
"{",
"p",
",",
"err",
":=",
"predicate",
".",
"NewParser",
"(",
"predicate",
".",
"Def",
"{",
"Operators",
":",
"predicate",
".",
"Operators",
"{",
"AND",
":",
"A... | // Parses expression in the go language into Failover predicates | [
"Parses",
"expression",
"in",
"the",
"go",
"language",
"into",
"Failover",
"predicates"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/threshold/parse.go#L11-L42 |
151,563 | vulcand/vulcan | middleware/chain.go | getIter | func (c *chain) getIter() *iter {
c.mutex.RLock()
defer c.mutex.RUnlock()
return newIter(c.callbacks)
} | go | func (c *chain) getIter() *iter {
c.mutex.RLock()
defer c.mutex.RUnlock()
return newIter(c.callbacks)
} | [
"func",
"(",
"c",
"*",
"chain",
")",
"getIter",
"(",
")",
"*",
"iter",
"{",
"c",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"c",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"newIter",
"(",
"c",
".",
"callbacks",
")",
"\n",... | // Note that we hold read lock to get access to the current iterator | [
"Note",
"that",
"we",
"hold",
"read",
"lock",
"to",
"get",
"access",
"to",
"the",
"current",
"iterator"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/middleware/chain.go#L231-L235 |
151,564 | vulcand/vulcan | metrics/histogram.go | NewHDRHistogramFn | func NewHDRHistogramFn(low, high int64, sigfigs int) NewHistogramFn {
return func() (Histogram, error) {
return NewHDRHistogram(low, high, sigfigs)
}
} | go | func NewHDRHistogramFn(low, high int64, sigfigs int) NewHistogramFn {
return func() (Histogram, error) {
return NewHDRHistogram(low, high, sigfigs)
}
} | [
"func",
"NewHDRHistogramFn",
"(",
"low",
",",
"high",
"int64",
",",
"sigfigs",
"int",
")",
"NewHistogramFn",
"{",
"return",
"func",
"(",
")",
"(",
"Histogram",
",",
"error",
")",
"{",
"return",
"NewHDRHistogram",
"(",
"low",
",",
"high",
",",
"sigfigs",
... | // NewHDRHistogramFn creates a constructor of HDR histograms with predefined parameters. | [
"NewHDRHistogramFn",
"creates",
"a",
"constructor",
"of",
"HDR",
"histograms",
"with",
"predefined",
"parameters",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/metrics/histogram.go#L38-L42 |
151,565 | vulcand/vulcan | loadbalance/roundrobin/roundrobin.go | AddEndpointWithOptions | func (r *RoundRobin) AddEndpointWithOptions(endpoint endpoint.Endpoint, options EndpointOptions) error {
r.mutex.Lock()
defer r.mutex.Unlock()
if endpoint == nil {
return fmt.Errorf("Endpoint can't be nil")
}
if e, _ := r.findEndpointByUrl(endpoint.GetUrl()); e != nil {
return fmt.Errorf("Endpoint already exists")
}
we, err := r.newWeightedEndpoint(endpoint, options)
if err != nil {
return err
}
r.endpoints = append(r.endpoints, we)
r.resetState()
return nil
} | go | func (r *RoundRobin) AddEndpointWithOptions(endpoint endpoint.Endpoint, options EndpointOptions) error {
r.mutex.Lock()
defer r.mutex.Unlock()
if endpoint == nil {
return fmt.Errorf("Endpoint can't be nil")
}
if e, _ := r.findEndpointByUrl(endpoint.GetUrl()); e != nil {
return fmt.Errorf("Endpoint already exists")
}
we, err := r.newWeightedEndpoint(endpoint, options)
if err != nil {
return err
}
r.endpoints = append(r.endpoints, we)
r.resetState()
return nil
} | [
"func",
"(",
"r",
"*",
"RoundRobin",
")",
"AddEndpointWithOptions",
"(",
"endpoint",
"endpoint",
".",
"Endpoint",
",",
"options",
"EndpointOptions",
")",
"error",
"{",
"r",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"mutex",
".",
"Unlo... | // In case if endpoint is already present in the load balancer, returns error | [
"In",
"case",
"if",
"endpoint",
"is",
"already",
"present",
"in",
"the",
"load",
"balancer",
"returns",
"error"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/loadbalance/roundrobin/roundrobin.go#L159-L179 |
151,566 | vulcand/vulcan | circuitbreaker/predicates.go | MustParseExpression | func MustParseExpression(in string) threshold.Predicate {
e, err := ParseExpression(in)
if err != nil {
panic(err)
}
return e
} | go | func MustParseExpression(in string) threshold.Predicate {
e, err := ParseExpression(in)
if err != nil {
panic(err)
}
return e
} | [
"func",
"MustParseExpression",
"(",
"in",
"string",
")",
"threshold",
".",
"Predicate",
"{",
"e",
",",
"err",
":=",
"ParseExpression",
"(",
"in",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"e",
"\n"... | // MustParseExpresison calls ParseExpression and panics if expression is incorrect, for use in tests | [
"MustParseExpresison",
"calls",
"ParseExpression",
"and",
"panics",
"if",
"expression",
"is",
"incorrect",
"for",
"use",
"in",
"tests"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/circuitbreaker/predicates.go#L15-L21 |
151,567 | vulcand/vulcan | circuitbreaker/predicates.go | ParseExpression | func ParseExpression(in string) (threshold.Predicate, error) {
p, err := predicate.NewParser(predicate.Def{
Operators: predicate.Operators{
AND: threshold.AND,
OR: threshold.OR,
EQ: threshold.EQ,
NEQ: threshold.NEQ,
LT: threshold.LT,
LE: threshold.LE,
GT: threshold.GT,
GE: threshold.GE,
},
Functions: map[string]interface{}{
"LatencyAtQuantileMS": latencyAtQuantile,
"NetworkErrorRatio": networkErrorRatio,
"ResponseCodeRatio": responseCodeRatio,
},
})
if err != nil {
return nil, err
}
out, err := p.Parse(in)
if err != nil {
return nil, err
}
pr, ok := out.(threshold.Predicate)
if !ok {
return nil, fmt.Errorf("expected predicate, got %T", out)
}
return pr, nil
} | go | func ParseExpression(in string) (threshold.Predicate, error) {
p, err := predicate.NewParser(predicate.Def{
Operators: predicate.Operators{
AND: threshold.AND,
OR: threshold.OR,
EQ: threshold.EQ,
NEQ: threshold.NEQ,
LT: threshold.LT,
LE: threshold.LE,
GT: threshold.GT,
GE: threshold.GE,
},
Functions: map[string]interface{}{
"LatencyAtQuantileMS": latencyAtQuantile,
"NetworkErrorRatio": networkErrorRatio,
"ResponseCodeRatio": responseCodeRatio,
},
})
if err != nil {
return nil, err
}
out, err := p.Parse(in)
if err != nil {
return nil, err
}
pr, ok := out.(threshold.Predicate)
if !ok {
return nil, fmt.Errorf("expected predicate, got %T", out)
}
return pr, nil
} | [
"func",
"ParseExpression",
"(",
"in",
"string",
")",
"(",
"threshold",
".",
"Predicate",
",",
"error",
")",
"{",
"p",
",",
"err",
":=",
"predicate",
".",
"NewParser",
"(",
"predicate",
".",
"Def",
"{",
"Operators",
":",
"predicate",
".",
"Operators",
"{"... | // ParseExpression parses expression in the go language into predicates. | [
"ParseExpression",
"parses",
"expression",
"in",
"the",
"go",
"language",
"into",
"predicates",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/circuitbreaker/predicates.go#L24-L54 |
151,568 | goware/disque | disque.go | New | func New(address string, extra ...string) (*Pool, error) {
pool := &redis.Pool{
MaxIdle: 1024,
MaxActive: 1024,
IdleTimeout: 300 * time.Second,
Wait: true,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", address)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
return &Pool{redis: pool}, nil
} | go | func New(address string, extra ...string) (*Pool, error) {
pool := &redis.Pool{
MaxIdle: 1024,
MaxActive: 1024,
IdleTimeout: 300 * time.Second,
Wait: true,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", address)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
return &Pool{redis: pool}, nil
} | [
"func",
"New",
"(",
"address",
"string",
",",
"extra",
"...",
"string",
")",
"(",
"*",
"Pool",
",",
"error",
")",
"{",
"pool",
":=",
"&",
"redis",
".",
"Pool",
"{",
"MaxIdle",
":",
"1024",
",",
"MaxActive",
":",
"1024",
",",
"IdleTimeout",
":",
"30... | // New creates a new connection to a given Disque Pool. | [
"New",
"creates",
"a",
"new",
"connection",
"to",
"a",
"given",
"Disque",
"Pool",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/disque.go#L20-L40 |
151,569 | goware/disque | disque.go | Ping | func (pool *Pool) Ping() error {
sess := pool.redis.Get()
defer sess.Close()
if _, err := sess.Do("PING"); err != nil {
return err
}
return nil
} | go | func (pool *Pool) Ping() error {
sess := pool.redis.Get()
defer sess.Close()
if _, err := sess.Do("PING"); err != nil {
return err
}
return nil
} | [
"func",
"(",
"pool",
"*",
"Pool",
")",
"Ping",
"(",
")",
"error",
"{",
"sess",
":=",
"pool",
".",
"redis",
".",
"Get",
"(",
")",
"\n",
"defer",
"sess",
".",
"Close",
"(",
")",
"\n\n",
"if",
"_",
",",
"err",
":=",
"sess",
".",
"Do",
"(",
"\"",... | // Ping returns nil if Disque Pool is alive, error otherwise. | [
"Ping",
"returns",
"nil",
"if",
"Disque",
"Pool",
"is",
"alive",
"error",
"otherwise",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/disque.go#L52-L60 |
151,570 | goware/disque | disque.go | Add | func (pool *Pool) Add(data string, queue string) (*Job, error) {
args := []interface{}{
"ADDJOB",
queue,
data,
int(pool.conf.Timeout.Nanoseconds() / 1000000),
}
if pool.conf.Replicate > 0 {
args = append(args, "REPLICATE", pool.conf.Replicate)
}
if pool.conf.Delay > 0 {
delay := int(pool.conf.Delay.Seconds())
if delay == 0 {
delay = 1
}
args = append(args, "DELAY", delay)
}
if pool.conf.RetryAfter > 0 {
retry := int(pool.conf.RetryAfter.Seconds())
if retry == 0 {
retry = 1
}
args = append(args, "RETRY", retry)
}
if pool.conf.TTL > 0 {
ttl := int(pool.conf.TTL.Seconds())
if ttl == 0 {
ttl = 1
}
args = append(args, "TTL", ttl)
}
if pool.conf.MaxLen > 0 {
args = append(args, "MAXLEN", pool.conf.MaxLen)
}
reply, err := pool.do(args)
if err != nil {
return nil, err
}
id, ok := reply.(string)
if !ok {
return nil, errors.New("unexpected reply: id")
}
return &Job{
ID: id,
Data: data,
Queue: queue,
}, nil
} | go | func (pool *Pool) Add(data string, queue string) (*Job, error) {
args := []interface{}{
"ADDJOB",
queue,
data,
int(pool.conf.Timeout.Nanoseconds() / 1000000),
}
if pool.conf.Replicate > 0 {
args = append(args, "REPLICATE", pool.conf.Replicate)
}
if pool.conf.Delay > 0 {
delay := int(pool.conf.Delay.Seconds())
if delay == 0 {
delay = 1
}
args = append(args, "DELAY", delay)
}
if pool.conf.RetryAfter > 0 {
retry := int(pool.conf.RetryAfter.Seconds())
if retry == 0 {
retry = 1
}
args = append(args, "RETRY", retry)
}
if pool.conf.TTL > 0 {
ttl := int(pool.conf.TTL.Seconds())
if ttl == 0 {
ttl = 1
}
args = append(args, "TTL", ttl)
}
if pool.conf.MaxLen > 0 {
args = append(args, "MAXLEN", pool.conf.MaxLen)
}
reply, err := pool.do(args)
if err != nil {
return nil, err
}
id, ok := reply.(string)
if !ok {
return nil, errors.New("unexpected reply: id")
}
return &Job{
ID: id,
Data: data,
Queue: queue,
}, nil
} | [
"func",
"(",
"pool",
"*",
"Pool",
")",
"Add",
"(",
"data",
"string",
",",
"queue",
"string",
")",
"(",
"*",
"Job",
",",
"error",
")",
"{",
"args",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
",",
"queue",
",",
"data",
",",
"int",
... | // Add enqueues new job with a specified data to a given queue. | [
"Add",
"enqueues",
"new",
"job",
"with",
"a",
"specified",
"data",
"to",
"a",
"given",
"queue",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/disque.go#L106-L157 |
151,571 | goware/disque | disque.go | Len | func (pool *Pool) Len(queue string) (int, error) {
sess := pool.redis.Get()
defer sess.Close()
length, err := redis.Int(sess.Do("QLEN", queue))
if err != nil {
return 0, err
}
return length, nil
} | go | func (pool *Pool) Len(queue string) (int, error) {
sess := pool.redis.Get()
defer sess.Close()
length, err := redis.Int(sess.Do("QLEN", queue))
if err != nil {
return 0, err
}
return length, nil
} | [
"func",
"(",
"pool",
"*",
"Pool",
")",
"Len",
"(",
"queue",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"sess",
":=",
"pool",
".",
"redis",
".",
"Get",
"(",
")",
"\n",
"defer",
"sess",
".",
"Close",
"(",
")",
"\n\n",
"length",
",",
"err"... | // Len returns length of a given queue. | [
"Len",
"returns",
"length",
"of",
"a",
"given",
"queue",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/disque.go#L351-L361 |
151,572 | goware/disque | disque.go | ActiveLen | func (pool *Pool) ActiveLen(queue string) (int, error) {
sess := pool.redis.Get()
defer sess.Close()
reply, err := sess.Do("JSCAN", "QUEUE", queue, "STATE", "active")
if err != nil {
return 0, err
}
replyArr, ok := reply.([]interface{})
if !ok || len(replyArr) != 2 {
return 0, errors.New("unexpected reply #1")
}
jobs, ok := replyArr[1].([]interface{})
if !ok {
return 0, errors.New("unexpected reply #2")
}
return len(jobs), nil
} | go | func (pool *Pool) ActiveLen(queue string) (int, error) {
sess := pool.redis.Get()
defer sess.Close()
reply, err := sess.Do("JSCAN", "QUEUE", queue, "STATE", "active")
if err != nil {
return 0, err
}
replyArr, ok := reply.([]interface{})
if !ok || len(replyArr) != 2 {
return 0, errors.New("unexpected reply #1")
}
jobs, ok := replyArr[1].([]interface{})
if !ok {
return 0, errors.New("unexpected reply #2")
}
return len(jobs), nil
} | [
"func",
"(",
"pool",
"*",
"Pool",
")",
"ActiveLen",
"(",
"queue",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"sess",
":=",
"pool",
".",
"redis",
".",
"Get",
"(",
")",
"\n",
"defer",
"sess",
".",
"Close",
"(",
")",
"\n\n",
"reply",
",",
... | // ActiveLen returns length of active jobs taken from a given queue. | [
"ActiveLen",
"returns",
"length",
"of",
"active",
"jobs",
"taken",
"from",
"a",
"given",
"queue",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/disque.go#L364-L381 |
151,573 | vulcand/vulcan | location/httploc/httploc.go | RoundTrip | func (l *HttpLocation) RoundTrip(req request.Request) (*http.Response, error) {
// Get options and transport as one single read transaction.
// Options and transport may change if someone calls SetOptions
o, tr := l.GetOptionsAndTransport()
originalRequest := req.GetHttpRequest()
// Check request size first, if that exceeds the limit, we don't bother reading the request.
if l.isRequestOverLimit(req) {
return nil, errors.FromStatus(http.StatusRequestEntityTooLarge)
}
// Read the body while keeping this location's limits in mind. This reader controls the maximum bytes
// to read into memory and disk. This reader returns an error if the total request size exceeds the
// prefefined MaxSizeBytes. This can occur if we got chunked request, in this case ContentLength would be set to -1
// and the reader would be unbounded bufio in the http.Server
body, err := netutils.NewBodyBufferWithOptions(originalRequest.Body, netutils.BodyBufferOptions{
MemBufferBytes: o.Limits.MaxMemBodyBytes,
MaxSizeBytes: o.Limits.MaxBodyBytes,
})
if err != nil {
return nil, err
}
if body == nil {
return nil, fmt.Errorf("Empty body")
}
// Set request body to buffered reader that can replay the read and execute Seek
req.SetBody(body)
// Note that we don't change the original request Body as it's handled by the http server
defer body.Close()
for {
_, err := req.GetBody().Seek(0, 0)
if err != nil {
return nil, err
}
endpoint, err := l.loadBalancer.NextEndpoint(req)
if err != nil {
log.Errorf("Load Balancer failure: %s", err)
return nil, err
}
// Adds headers, changes urls. Note that we rewrite request each time we proxy it to the
// endpoint, so that each try gets a fresh start
req.SetHttpRequest(l.copyRequest(originalRequest, req.GetBody(), endpoint))
// In case if error is not nil, we allow load balancer to choose the next endpoint
// e.g. to do request failover. Nil error means that we got proxied the request successfully.
response, err := l.proxyToEndpoint(tr, &o, endpoint, req)
if o.FailoverPredicate(req) {
continue
} else {
return response, err
}
}
log.Errorf("All endpoints failed!")
return nil, fmt.Errorf("All endpoints failed")
} | go | func (l *HttpLocation) RoundTrip(req request.Request) (*http.Response, error) {
// Get options and transport as one single read transaction.
// Options and transport may change if someone calls SetOptions
o, tr := l.GetOptionsAndTransport()
originalRequest := req.GetHttpRequest()
// Check request size first, if that exceeds the limit, we don't bother reading the request.
if l.isRequestOverLimit(req) {
return nil, errors.FromStatus(http.StatusRequestEntityTooLarge)
}
// Read the body while keeping this location's limits in mind. This reader controls the maximum bytes
// to read into memory and disk. This reader returns an error if the total request size exceeds the
// prefefined MaxSizeBytes. This can occur if we got chunked request, in this case ContentLength would be set to -1
// and the reader would be unbounded bufio in the http.Server
body, err := netutils.NewBodyBufferWithOptions(originalRequest.Body, netutils.BodyBufferOptions{
MemBufferBytes: o.Limits.MaxMemBodyBytes,
MaxSizeBytes: o.Limits.MaxBodyBytes,
})
if err != nil {
return nil, err
}
if body == nil {
return nil, fmt.Errorf("Empty body")
}
// Set request body to buffered reader that can replay the read and execute Seek
req.SetBody(body)
// Note that we don't change the original request Body as it's handled by the http server
defer body.Close()
for {
_, err := req.GetBody().Seek(0, 0)
if err != nil {
return nil, err
}
endpoint, err := l.loadBalancer.NextEndpoint(req)
if err != nil {
log.Errorf("Load Balancer failure: %s", err)
return nil, err
}
// Adds headers, changes urls. Note that we rewrite request each time we proxy it to the
// endpoint, so that each try gets a fresh start
req.SetHttpRequest(l.copyRequest(originalRequest, req.GetBody(), endpoint))
// In case if error is not nil, we allow load balancer to choose the next endpoint
// e.g. to do request failover. Nil error means that we got proxied the request successfully.
response, err := l.proxyToEndpoint(tr, &o, endpoint, req)
if o.FailoverPredicate(req) {
continue
} else {
return response, err
}
}
log.Errorf("All endpoints failed!")
return nil, fmt.Errorf("All endpoints failed")
} | [
"func",
"(",
"l",
"*",
"HttpLocation",
")",
"RoundTrip",
"(",
"req",
"request",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"// Get options and transport as one single read transaction.",
"// Options and transport may change if someon... | // Round trips the request to one of the endpoints and returns the response. | [
"Round",
"trips",
"the",
"request",
"to",
"one",
"of",
"the",
"endpoints",
"and",
"returns",
"the",
"response",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/location/httploc/httploc.go#L179-L237 |
151,574 | vulcand/vulcan | location/httploc/httploc.go | unwindIter | func (l *HttpLocation) unwindIter(it *middleware.MiddlewareIter, req request.Request, a request.Attempt) {
for v := it.Prev(); v != nil; v = it.Prev() {
v.ProcessResponse(req, a)
}
} | go | func (l *HttpLocation) unwindIter(it *middleware.MiddlewareIter, req request.Request, a request.Attempt) {
for v := it.Prev(); v != nil; v = it.Prev() {
v.ProcessResponse(req, a)
}
} | [
"func",
"(",
"l",
"*",
"HttpLocation",
")",
"unwindIter",
"(",
"it",
"*",
"middleware",
".",
"MiddlewareIter",
",",
"req",
"request",
".",
"Request",
",",
"a",
"request",
".",
"Attempt",
")",
"{",
"for",
"v",
":=",
"it",
".",
"Prev",
"(",
")",
";",
... | // Unwind middlewares iterator in reverse order | [
"Unwind",
"middlewares",
"iterator",
"in",
"reverse",
"order"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/location/httploc/httploc.go#L248-L252 |
151,575 | vulcand/vulcan | location/httploc/httploc.go | proxyToEndpoint | func (l *HttpLocation) proxyToEndpoint(tr *http.Transport, o *Options, endpoint endpoint.Endpoint, req request.Request) (*http.Response, error) {
a := &request.BaseAttempt{Endpoint: endpoint}
l.observerChain.ObserveRequest(req)
defer l.observerChain.ObserveResponse(req, a)
defer req.AddAttempt(a)
it := l.middlewareChain.GetIter()
defer l.unwindIter(it, req, a)
for v := it.Next(); v != nil; v = it.Next() {
a.Response, a.Error = v.ProcessRequest(req)
if a.Response != nil || a.Error != nil {
// Move the iterator forward to count it again once we unwind the chain
it.Next()
log.Errorf("Midleware intercepted request with response=%v, error=%v", a.Response, a.Error)
return a.Response, a.Error
}
}
// Forward the request and mirror the response
start := o.TimeProvider.UtcNow()
re, err := tr.RoundTrip(req.GetHttpRequest())
// Read the response as soon as we can, this will allow to release a connection to the pool
a.Response, a.Error = readResponse(&o.Limits, re, err)
a.Duration = o.TimeProvider.UtcNow().Sub(start)
return a.Response, a.Error
} | go | func (l *HttpLocation) proxyToEndpoint(tr *http.Transport, o *Options, endpoint endpoint.Endpoint, req request.Request) (*http.Response, error) {
a := &request.BaseAttempt{Endpoint: endpoint}
l.observerChain.ObserveRequest(req)
defer l.observerChain.ObserveResponse(req, a)
defer req.AddAttempt(a)
it := l.middlewareChain.GetIter()
defer l.unwindIter(it, req, a)
for v := it.Next(); v != nil; v = it.Next() {
a.Response, a.Error = v.ProcessRequest(req)
if a.Response != nil || a.Error != nil {
// Move the iterator forward to count it again once we unwind the chain
it.Next()
log.Errorf("Midleware intercepted request with response=%v, error=%v", a.Response, a.Error)
return a.Response, a.Error
}
}
// Forward the request and mirror the response
start := o.TimeProvider.UtcNow()
re, err := tr.RoundTrip(req.GetHttpRequest())
// Read the response as soon as we can, this will allow to release a connection to the pool
a.Response, a.Error = readResponse(&o.Limits, re, err)
a.Duration = o.TimeProvider.UtcNow().Sub(start)
return a.Response, a.Error
} | [
"func",
"(",
"l",
"*",
"HttpLocation",
")",
"proxyToEndpoint",
"(",
"tr",
"*",
"http",
".",
"Transport",
",",
"o",
"*",
"Options",
",",
"endpoint",
"endpoint",
".",
"Endpoint",
",",
"req",
"request",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Respons... | // Proxy the request to the given endpoint, execute observers and middlewares chains | [
"Proxy",
"the",
"request",
"to",
"the",
"given",
"endpoint",
"execute",
"observers",
"and",
"middlewares",
"chains"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/location/httploc/httploc.go#L262-L291 |
151,576 | vulcand/vulcan | location/httploc/httploc.go | readResponse | func readResponse(l *Limits, re *http.Response, err error) (*http.Response, error) {
if re == nil || re.Body == nil {
return nil, err
}
// Closing a response body releases connection to the pool in transport
body := re.Body
defer body.Close()
newBody, err := netutils.NewBodyBufferWithOptions(body, netutils.BodyBufferOptions{
MemBufferBytes: l.MaxMemBodyBytes,
MaxSizeBytes: l.MaxBodyBytes,
})
if err != nil {
return nil, err
}
re.Body = newBody
return re, nil
} | go | func readResponse(l *Limits, re *http.Response, err error) (*http.Response, error) {
if re == nil || re.Body == nil {
return nil, err
}
// Closing a response body releases connection to the pool in transport
body := re.Body
defer body.Close()
newBody, err := netutils.NewBodyBufferWithOptions(body, netutils.BodyBufferOptions{
MemBufferBytes: l.MaxMemBodyBytes,
MaxSizeBytes: l.MaxBodyBytes,
})
if err != nil {
return nil, err
}
re.Body = newBody
return re, nil
} | [
"func",
"readResponse",
"(",
"l",
"*",
"Limits",
",",
"re",
"*",
"http",
".",
"Response",
",",
"err",
"error",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"re",
"==",
"nil",
"||",
"re",
".",
"Body",
"==",
"nil",
"{",
"... | // readResponse reads the response body into buffer, closes the original response body to release the connection
// and replaces the body with the buffer. | [
"readResponse",
"reads",
"the",
"response",
"body",
"into",
"buffer",
"closes",
"the",
"original",
"response",
"body",
"to",
"release",
"the",
"connection",
"and",
"replaces",
"the",
"body",
"with",
"the",
"buffer",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/location/httploc/httploc.go#L321-L337 |
151,577 | goware/disque | config.go | Use | func (pool *Pool) Use(conf Config) *Pool {
pool.conf = conf
return pool
} | go | func (pool *Pool) Use(conf Config) *Pool {
pool.conf = conf
return pool
} | [
"func",
"(",
"pool",
"*",
"Pool",
")",
"Use",
"(",
"conf",
"Config",
")",
"*",
"Pool",
"{",
"pool",
".",
"conf",
"=",
"conf",
"\n",
"return",
"pool",
"\n",
"}"
] | // Use applies given config to every subsequent operation of this connection. | [
"Use",
"applies",
"given",
"config",
"to",
"every",
"subsequent",
"operation",
"of",
"this",
"connection",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/config.go#L16-L19 |
151,578 | goware/disque | config.go | With | func (pool *Pool) With(conf Config) *Pool {
return &Pool{redis: pool.redis, conf: conf}
} | go | func (pool *Pool) With(conf Config) *Pool {
return &Pool{redis: pool.redis, conf: conf}
} | [
"func",
"(",
"pool",
"*",
"Pool",
")",
"With",
"(",
"conf",
"Config",
")",
"*",
"Pool",
"{",
"return",
"&",
"Pool",
"{",
"redis",
":",
"pool",
".",
"redis",
",",
"conf",
":",
"conf",
"}",
"\n",
"}"
] | // With applies given config to a single operation. | [
"With",
"applies",
"given",
"config",
"to",
"a",
"single",
"operation",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/config.go#L22-L24 |
151,579 | goware/disque | config.go | Timeout | func (pool *Pool) Timeout(timeout time.Duration) *Pool {
pool.conf.Timeout = timeout
return &Pool{redis: pool.redis, conf: pool.conf}
} | go | func (pool *Pool) Timeout(timeout time.Duration) *Pool {
pool.conf.Timeout = timeout
return &Pool{redis: pool.redis, conf: pool.conf}
} | [
"func",
"(",
"pool",
"*",
"Pool",
")",
"Timeout",
"(",
"timeout",
"time",
".",
"Duration",
")",
"*",
"Pool",
"{",
"pool",
".",
"conf",
".",
"Timeout",
"=",
"timeout",
"\n",
"return",
"&",
"Pool",
"{",
"redis",
":",
"pool",
".",
"redis",
",",
"conf"... | // Timeout option applied to a single operation. | [
"Timeout",
"option",
"applied",
"to",
"a",
"single",
"operation",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/config.go#L27-L30 |
151,580 | goware/disque | config.go | Replicate | func (pool *Pool) Replicate(replicate int) *Pool {
pool.conf.Replicate = replicate
return &Pool{redis: pool.redis, conf: pool.conf}
} | go | func (pool *Pool) Replicate(replicate int) *Pool {
pool.conf.Replicate = replicate
return &Pool{redis: pool.redis, conf: pool.conf}
} | [
"func",
"(",
"pool",
"*",
"Pool",
")",
"Replicate",
"(",
"replicate",
"int",
")",
"*",
"Pool",
"{",
"pool",
".",
"conf",
".",
"Replicate",
"=",
"replicate",
"\n",
"return",
"&",
"Pool",
"{",
"redis",
":",
"pool",
".",
"redis",
",",
"conf",
":",
"po... | // Replicate option applied to a single operation. | [
"Replicate",
"option",
"applied",
"to",
"a",
"single",
"operation",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/config.go#L33-L36 |
151,581 | goware/disque | config.go | Delay | func (pool *Pool) Delay(delay time.Duration) *Pool {
pool.conf.Delay = delay
return &Pool{redis: pool.redis, conf: pool.conf}
} | go | func (pool *Pool) Delay(delay time.Duration) *Pool {
pool.conf.Delay = delay
return &Pool{redis: pool.redis, conf: pool.conf}
} | [
"func",
"(",
"pool",
"*",
"Pool",
")",
"Delay",
"(",
"delay",
"time",
".",
"Duration",
")",
"*",
"Pool",
"{",
"pool",
".",
"conf",
".",
"Delay",
"=",
"delay",
"\n",
"return",
"&",
"Pool",
"{",
"redis",
":",
"pool",
".",
"redis",
",",
"conf",
":",... | // Delay option applied to a single operation. | [
"Delay",
"option",
"applied",
"to",
"a",
"single",
"operation",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/config.go#L39-L42 |
151,582 | goware/disque | config.go | RetryAfter | func (pool *Pool) RetryAfter(after time.Duration) *Pool {
pool.conf.RetryAfter = after
return &Pool{redis: pool.redis, conf: pool.conf}
} | go | func (pool *Pool) RetryAfter(after time.Duration) *Pool {
pool.conf.RetryAfter = after
return &Pool{redis: pool.redis, conf: pool.conf}
} | [
"func",
"(",
"pool",
"*",
"Pool",
")",
"RetryAfter",
"(",
"after",
"time",
".",
"Duration",
")",
"*",
"Pool",
"{",
"pool",
".",
"conf",
".",
"RetryAfter",
"=",
"after",
"\n",
"return",
"&",
"Pool",
"{",
"redis",
":",
"pool",
".",
"redis",
",",
"con... | // RetryAfter option applied to a single operation. | [
"RetryAfter",
"option",
"applied",
"to",
"a",
"single",
"operation",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/config.go#L45-L48 |
151,583 | goware/disque | config.go | TTL | func (pool *Pool) TTL(ttl time.Duration) *Pool {
pool.conf.TTL = ttl
return &Pool{redis: pool.redis, conf: pool.conf}
} | go | func (pool *Pool) TTL(ttl time.Duration) *Pool {
pool.conf.TTL = ttl
return &Pool{redis: pool.redis, conf: pool.conf}
} | [
"func",
"(",
"pool",
"*",
"Pool",
")",
"TTL",
"(",
"ttl",
"time",
".",
"Duration",
")",
"*",
"Pool",
"{",
"pool",
".",
"conf",
".",
"TTL",
"=",
"ttl",
"\n",
"return",
"&",
"Pool",
"{",
"redis",
":",
"pool",
".",
"redis",
",",
"conf",
":",
"pool... | // TTL option applied to a single operation. | [
"TTL",
"option",
"applied",
"to",
"a",
"single",
"operation",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/config.go#L51-L54 |
151,584 | goware/disque | config.go | MaxLen | func (pool *Pool) MaxLen(maxlen int) *Pool {
pool.conf.MaxLen = maxlen
return &Pool{redis: pool.redis, conf: pool.conf}
} | go | func (pool *Pool) MaxLen(maxlen int) *Pool {
pool.conf.MaxLen = maxlen
return &Pool{redis: pool.redis, conf: pool.conf}
} | [
"func",
"(",
"pool",
"*",
"Pool",
")",
"MaxLen",
"(",
"maxlen",
"int",
")",
"*",
"Pool",
"{",
"pool",
".",
"conf",
".",
"MaxLen",
"=",
"maxlen",
"\n",
"return",
"&",
"Pool",
"{",
"redis",
":",
"pool",
".",
"redis",
",",
"conf",
":",
"pool",
".",
... | // MaxLen option applied to a single operation. | [
"MaxLen",
"option",
"applied",
"to",
"a",
"single",
"operation",
"."
] | ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4 | https://github.com/goware/disque/blob/ae073e1aae12fdbc3ce259ce64fbb46e6f514eb4/config.go#L57-L60 |
151,585 | tv42/topic | topic.go | New | func New() *Topic {
t := &Topic{}
broadcast := make(chan interface{}, 100)
t.Broadcast = broadcast
t.connections = make(map[chan<- interface{}]nothing)
go t.run(broadcast)
return t
} | go | func New() *Topic {
t := &Topic{}
broadcast := make(chan interface{}, 100)
t.Broadcast = broadcast
t.connections = make(map[chan<- interface{}]nothing)
go t.run(broadcast)
return t
} | [
"func",
"New",
"(",
")",
"*",
"Topic",
"{",
"t",
":=",
"&",
"Topic",
"{",
"}",
"\n",
"broadcast",
":=",
"make",
"(",
"chan",
"interface",
"{",
"}",
",",
"100",
")",
"\n",
"t",
".",
"Broadcast",
"=",
"broadcast",
"\n",
"t",
".",
"connections",
"="... | // New creates a new topic. Messages can be broadcast on this topic,
// and registered consumers are guaranteed to either receive them, or
// see a channel close. | [
"New",
"creates",
"a",
"new",
"topic",
".",
"Messages",
"can",
"be",
"broadcast",
"on",
"this",
"topic",
"and",
"registered",
"consumers",
"are",
"guaranteed",
"to",
"either",
"receive",
"them",
"or",
"see",
"a",
"channel",
"close",
"."
] | aa72cbe81b4823f349da47a4d749cdda61677c09 | https://github.com/tv42/topic/blob/aa72cbe81b4823f349da47a4d749cdda61677c09/topic.go#L31-L38 |
151,586 | tv42/topic | topic.go | Register | func (t *Topic) Register(ch chan<- interface{}) {
t.lock.Lock()
defer t.lock.Unlock()
t.connections[ch] = nothing{}
} | go | func (t *Topic) Register(ch chan<- interface{}) {
t.lock.Lock()
defer t.lock.Unlock()
t.connections[ch] = nothing{}
} | [
"func",
"(",
"t",
"*",
"Topic",
")",
"Register",
"(",
"ch",
"chan",
"<-",
"interface",
"{",
"}",
")",
"{",
"t",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"t",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"t",
".",
"connections",
"[",
... | // Register starts receiving messages on the given channel. If a
// channel close is seen, either the topic has been shut down, or the
// consumer was too slow, and should re-register. | [
"Register",
"starts",
"receiving",
"messages",
"on",
"the",
"given",
"channel",
".",
"If",
"a",
"channel",
"close",
"is",
"seen",
"either",
"the",
"topic",
"has",
"been",
"shut",
"down",
"or",
"the",
"consumer",
"was",
"too",
"slow",
"and",
"should",
"re",... | aa72cbe81b4823f349da47a4d749cdda61677c09 | https://github.com/tv42/topic/blob/aa72cbe81b4823f349da47a4d749cdda61677c09/topic.go#L67-L71 |
151,587 | tv42/topic | topic.go | Unregister | func (t *Topic) Unregister(ch chan<- interface{}) {
t.lock.Lock()
defer t.lock.Unlock()
// double-close is not safe, so make sure we didn't already
// drop this consumer as too slow
_, ok := t.connections[ch]
if ok {
delete(t.connections, ch)
close(ch)
}
} | go | func (t *Topic) Unregister(ch chan<- interface{}) {
t.lock.Lock()
defer t.lock.Unlock()
// double-close is not safe, so make sure we didn't already
// drop this consumer as too slow
_, ok := t.connections[ch]
if ok {
delete(t.connections, ch)
close(ch)
}
} | [
"func",
"(",
"t",
"*",
"Topic",
")",
"Unregister",
"(",
"ch",
"chan",
"<-",
"interface",
"{",
"}",
")",
"{",
"t",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"t",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"// double-close is not safe, so m... | // Unregister stops receiving messages on this channel. | [
"Unregister",
"stops",
"receiving",
"messages",
"on",
"this",
"channel",
"."
] | aa72cbe81b4823f349da47a4d749cdda61677c09 | https://github.com/tv42/topic/blob/aa72cbe81b4823f349da47a4d749cdda61677c09/topic.go#L74-L85 |
151,588 | vulcand/vulcan | metrics/roundtrip.go | NewRoundTripMetrics | func NewRoundTripMetrics(o RoundTripOptions) (*RoundTripMetrics, error) {
o = setDefaults(o)
h, err := NewRollingHistogram(
// this will create subhistograms
NewHDRHistogramFn(o.HistMin, o.HistMax, o.HistSignificantFigures),
// number of buckets in a rolling histogram
o.HistBuckets,
// rolling period for a histogram
o.HistPeriod,
o.TimeProvider)
if err != nil {
return nil, err
}
m := &RoundTripMetrics{
statusCodes: make(map[int]*RollingCounter),
histogram: h,
o: &o,
}
netErrors, err := m.newCounter()
if err != nil {
return nil, err
}
total, err := m.newCounter()
if err != nil {
return nil, err
}
m.netErrors = netErrors
m.total = total
return m, nil
} | go | func NewRoundTripMetrics(o RoundTripOptions) (*RoundTripMetrics, error) {
o = setDefaults(o)
h, err := NewRollingHistogram(
// this will create subhistograms
NewHDRHistogramFn(o.HistMin, o.HistMax, o.HistSignificantFigures),
// number of buckets in a rolling histogram
o.HistBuckets,
// rolling period for a histogram
o.HistPeriod,
o.TimeProvider)
if err != nil {
return nil, err
}
m := &RoundTripMetrics{
statusCodes: make(map[int]*RollingCounter),
histogram: h,
o: &o,
}
netErrors, err := m.newCounter()
if err != nil {
return nil, err
}
total, err := m.newCounter()
if err != nil {
return nil, err
}
m.netErrors = netErrors
m.total = total
return m, nil
} | [
"func",
"NewRoundTripMetrics",
"(",
"o",
"RoundTripOptions",
")",
"(",
"*",
"RoundTripMetrics",
",",
"error",
")",
"{",
"o",
"=",
"setDefaults",
"(",
"o",
")",
"\n\n",
"h",
",",
"err",
":=",
"NewRollingHistogram",
"(",
"// this will create subhistograms",
"NewHD... | // NewRoundTripMetrics returns new instance of metrics collector. | [
"NewRoundTripMetrics",
"returns",
"new",
"instance",
"of",
"metrics",
"collector",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/metrics/roundtrip.go#L46-L80 |
151,589 | vulcand/vulcan | metrics/roundtrip.go | GetNetworkErrorRatio | func (m *RoundTripMetrics) GetNetworkErrorRatio() float64 {
if m.total.Count() == 0 {
return 0
}
return float64(m.netErrors.Count()) / float64(m.total.Count())
} | go | func (m *RoundTripMetrics) GetNetworkErrorRatio() float64 {
if m.total.Count() == 0 {
return 0
}
return float64(m.netErrors.Count()) / float64(m.total.Count())
} | [
"func",
"(",
"m",
"*",
"RoundTripMetrics",
")",
"GetNetworkErrorRatio",
"(",
")",
"float64",
"{",
"if",
"m",
".",
"total",
".",
"Count",
"(",
")",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"float64",
"(",
"m",
".",
"netErrors",
".",
... | // GetNetworkErrorRatio calculates the amont of network errors such as time outs and dropped connection
// that occured in the given time window compared to the total requests count. | [
"GetNetworkErrorRatio",
"calculates",
"the",
"amont",
"of",
"network",
"errors",
"such",
"as",
"time",
"outs",
"and",
"dropped",
"connection",
"that",
"occured",
"in",
"the",
"given",
"time",
"window",
"compared",
"to",
"the",
"total",
"requests",
"count",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/metrics/roundtrip.go#L89-L94 |
151,590 | vulcand/vulcan | metrics/roundtrip.go | RecordMetrics | func (m *RoundTripMetrics) RecordMetrics(a request.Attempt) {
m.total.Inc()
m.recordNetError(a)
m.recordLatency(a)
m.recordStatusCode(a)
} | go | func (m *RoundTripMetrics) RecordMetrics(a request.Attempt) {
m.total.Inc()
m.recordNetError(a)
m.recordLatency(a)
m.recordStatusCode(a)
} | [
"func",
"(",
"m",
"*",
"RoundTripMetrics",
")",
"RecordMetrics",
"(",
"a",
"request",
".",
"Attempt",
")",
"{",
"m",
".",
"total",
".",
"Inc",
"(",
")",
"\n",
"m",
".",
"recordNetError",
"(",
"a",
")",
"\n",
"m",
".",
"recordLatency",
"(",
"a",
")"... | // RecordMetrics updates internal metrics collection based on the data from passed request. | [
"RecordMetrics",
"updates",
"internal",
"metrics",
"collection",
"based",
"on",
"the",
"data",
"from",
"passed",
"request",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/metrics/roundtrip.go#L115-L120 |
151,591 | vulcand/vulcan | metrics/roundtrip.go | GetStatusCodesCounts | func (m *RoundTripMetrics) GetStatusCodesCounts() map[int]int64 {
sc := make(map[int]int64)
for k, v := range m.statusCodes {
if v.Count() != 0 {
sc[k] = v.Count()
}
}
return sc
} | go | func (m *RoundTripMetrics) GetStatusCodesCounts() map[int]int64 {
sc := make(map[int]int64)
for k, v := range m.statusCodes {
if v.Count() != 0 {
sc[k] = v.Count()
}
}
return sc
} | [
"func",
"(",
"m",
"*",
"RoundTripMetrics",
")",
"GetStatusCodesCounts",
"(",
")",
"map",
"[",
"int",
"]",
"int64",
"{",
"sc",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"int64",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
".",
"statusCodes... | // GetStatusCodesCounts returns map with counts of the response codes | [
"GetStatusCodesCounts",
"returns",
"map",
"with",
"counts",
"of",
"the",
"response",
"codes"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/metrics/roundtrip.go#L133-L141 |
151,592 | vulcand/vulcan | limit/limiter.go | MapClientIp | func MapClientIp(req request.Request) (string, int64, error) {
t, err := RequestToClientIp(req)
return t, 1, err
} | go | func MapClientIp(req request.Request) (string, int64, error) {
t, err := RequestToClientIp(req)
return t, 1, err
} | [
"func",
"MapClientIp",
"(",
"req",
"request",
".",
"Request",
")",
"(",
"string",
",",
"int64",
",",
"error",
")",
"{",
"t",
",",
"err",
":=",
"RequestToClientIp",
"(",
"req",
")",
"\n",
"return",
"t",
",",
"1",
",",
"err",
"\n",
"}"
] | // MapClientIp creates a mapper that allows rate limiting of requests per client ip | [
"MapClientIp",
"creates",
"a",
"mapper",
"that",
"allows",
"rate",
"limiting",
"of",
"requests",
"per",
"client",
"ip"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/limit/limiter.go#L35-L38 |
151,593 | vulcand/vulcan | limit/limiter.go | MakeMapper | func MakeMapper(t TokenMapperFn, a AmountMapperFn) MapperFn {
return func(r request.Request) (string, int64, error) {
token, err := t(r)
if err != nil {
return "", -1, err
}
amount, err := a(r)
if err != nil {
return "", -1, err
}
return token, amount, nil
}
} | go | func MakeMapper(t TokenMapperFn, a AmountMapperFn) MapperFn {
return func(r request.Request) (string, int64, error) {
token, err := t(r)
if err != nil {
return "", -1, err
}
amount, err := a(r)
if err != nil {
return "", -1, err
}
return token, amount, nil
}
} | [
"func",
"MakeMapper",
"(",
"t",
"TokenMapperFn",
",",
"a",
"AmountMapperFn",
")",
"MapperFn",
"{",
"return",
"func",
"(",
"r",
"request",
".",
"Request",
")",
"(",
"string",
",",
"int64",
",",
"error",
")",
"{",
"token",
",",
"err",
":=",
"t",
"(",
"... | // Make mapper constructs the mapper function out of two functions - token mapper and amount mapper | [
"Make",
"mapper",
"constructs",
"the",
"mapper",
"function",
"out",
"of",
"two",
"functions",
"-",
"token",
"mapper",
"and",
"amount",
"mapper"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/limit/limiter.go#L58-L70 |
151,594 | vulcand/vulcan | limit/limiter.go | RequestToClientIp | func RequestToClientIp(req request.Request) (string, error) {
vals := strings.SplitN(req.GetHttpRequest().RemoteAddr, ":", 2)
if len(vals[0]) == 0 {
return "", fmt.Errorf("Failed to parse client IP")
}
return vals[0], nil
} | go | func RequestToClientIp(req request.Request) (string, error) {
vals := strings.SplitN(req.GetHttpRequest().RemoteAddr, ":", 2)
if len(vals[0]) == 0 {
return "", fmt.Errorf("Failed to parse client IP")
}
return vals[0], nil
} | [
"func",
"RequestToClientIp",
"(",
"req",
"request",
".",
"Request",
")",
"(",
"string",
",",
"error",
")",
"{",
"vals",
":=",
"strings",
".",
"SplitN",
"(",
"req",
".",
"GetHttpRequest",
"(",
")",
".",
"RemoteAddr",
",",
"\"",
"\"",
",",
"2",
")",
"\... | // RequestToClientIp is a TokenMapper that maps the request to the client IP. | [
"RequestToClientIp",
"is",
"a",
"TokenMapper",
"that",
"maps",
"the",
"request",
"to",
"the",
"client",
"IP",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/limit/limiter.go#L73-L79 |
151,595 | vulcand/vulcan | limit/limiter.go | RequestToHost | func RequestToHost(req request.Request) (string, error) {
return req.GetHttpRequest().Host, nil
} | go | func RequestToHost(req request.Request) (string, error) {
return req.GetHttpRequest().Host, nil
} | [
"func",
"RequestToHost",
"(",
"req",
"request",
".",
"Request",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"req",
".",
"GetHttpRequest",
"(",
")",
".",
"Host",
",",
"nil",
"\n",
"}"
] | // RequestToHost maps request to the host value | [
"RequestToHost",
"maps",
"request",
"to",
"the",
"host",
"value"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/limit/limiter.go#L82-L84 |
151,596 | vulcand/vulcan | limit/limiter.go | MakeRequestToHeader | func MakeRequestToHeader(header string) TokenMapperFn {
return func(req request.Request) (string, error) {
return req.GetHttpRequest().Header.Get(header), nil
}
} | go | func MakeRequestToHeader(header string) TokenMapperFn {
return func(req request.Request) (string, error) {
return req.GetHttpRequest().Header.Get(header), nil
}
} | [
"func",
"MakeRequestToHeader",
"(",
"header",
"string",
")",
"TokenMapperFn",
"{",
"return",
"func",
"(",
"req",
"request",
".",
"Request",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"req",
".",
"GetHttpRequest",
"(",
")",
".",
"Header",
".",
... | // MakeTokenMapperByHeader creates a TokenMapper that maps the incoming request to the header value. | [
"MakeTokenMapperByHeader",
"creates",
"a",
"TokenMapper",
"that",
"maps",
"the",
"incoming",
"request",
"to",
"the",
"header",
"value",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/limit/limiter.go#L97-L101 |
151,597 | vulcand/vulcan | limit/limiter.go | MakeTokenMapperFromVariable | func MakeTokenMapperFromVariable(variable string) (TokenMapperFn, error) {
if variable == "client.ip" {
return RequestToClientIp, nil
}
if variable == "request.host" {
return RequestToHost, nil
}
if strings.HasPrefix(variable, "request.header.") {
header := strings.TrimPrefix(variable, "request.header.")
if len(header) == 0 {
return nil, fmt.Errorf("Wrong header: %s", header)
}
return MakeRequestToHeader(header), nil
}
return nil, fmt.Errorf("Unsupported limiting variable: '%s'", variable)
} | go | func MakeTokenMapperFromVariable(variable string) (TokenMapperFn, error) {
if variable == "client.ip" {
return RequestToClientIp, nil
}
if variable == "request.host" {
return RequestToHost, nil
}
if strings.HasPrefix(variable, "request.header.") {
header := strings.TrimPrefix(variable, "request.header.")
if len(header) == 0 {
return nil, fmt.Errorf("Wrong header: %s", header)
}
return MakeRequestToHeader(header), nil
}
return nil, fmt.Errorf("Unsupported limiting variable: '%s'", variable)
} | [
"func",
"MakeTokenMapperFromVariable",
"(",
"variable",
"string",
")",
"(",
"TokenMapperFn",
",",
"error",
")",
"{",
"if",
"variable",
"==",
"\"",
"\"",
"{",
"return",
"RequestToClientIp",
",",
"nil",
"\n",
"}",
"\n",
"if",
"variable",
"==",
"\"",
"\"",
"{... | // Converts varaiable string to a mapper function used in limiters | [
"Converts",
"varaiable",
"string",
"to",
"a",
"mapper",
"function",
"used",
"in",
"limiters"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/limit/limiter.go#L104-L119 |
151,598 | vulcand/vulcan | loadbalance/roundrobin/fsm.go | AdjustWeights | func (fsm *FSMHandler) AdjustWeights() ([]SuggestedWeight, error) {
// In this case adjusting weights would have no effect, so do nothing
if len(fsm.endpoints) < 2 {
return fsm.originalWeights, nil
}
// Metrics are not ready
if !metricsReady(fsm.endpoints) {
return fsm.originalWeights, nil
}
if !fsm.timerExpired() {
return fsm.lastWeights, nil
}
// Select endpoints with highest error rates and lower their weight
good, bad := splitEndpoints(fsm.endpoints)
// No endpoints that are different by their quality, so converge weights
if len(bad) == 0 || len(good) == 0 {
weights, changed := fsm.convergeWeights()
if changed {
fsm.lastWeights = weights
fsm.setTimer()
}
return fsm.lastWeights, nil
}
fsm.lastWeights = fsm.adjustWeights(good, bad)
fsm.setTimer()
return fsm.lastWeights, nil
} | go | func (fsm *FSMHandler) AdjustWeights() ([]SuggestedWeight, error) {
// In this case adjusting weights would have no effect, so do nothing
if len(fsm.endpoints) < 2 {
return fsm.originalWeights, nil
}
// Metrics are not ready
if !metricsReady(fsm.endpoints) {
return fsm.originalWeights, nil
}
if !fsm.timerExpired() {
return fsm.lastWeights, nil
}
// Select endpoints with highest error rates and lower their weight
good, bad := splitEndpoints(fsm.endpoints)
// No endpoints that are different by their quality, so converge weights
if len(bad) == 0 || len(good) == 0 {
weights, changed := fsm.convergeWeights()
if changed {
fsm.lastWeights = weights
fsm.setTimer()
}
return fsm.lastWeights, nil
}
fsm.lastWeights = fsm.adjustWeights(good, bad)
fsm.setTimer()
return fsm.lastWeights, nil
} | [
"func",
"(",
"fsm",
"*",
"FSMHandler",
")",
"AdjustWeights",
"(",
")",
"(",
"[",
"]",
"SuggestedWeight",
",",
"error",
")",
"{",
"// In this case adjusting weights would have no effect, so do nothing",
"if",
"len",
"(",
"fsm",
".",
"endpoints",
")",
"<",
"2",
"{... | // Called on every load balancer NextEndpoint call, returns the suggested weights
// on every call, can adjust weights if needed. | [
"Called",
"on",
"every",
"load",
"balancer",
"NextEndpoint",
"call",
"returns",
"the",
"suggested",
"weights",
"on",
"every",
"call",
"can",
"adjust",
"weights",
"if",
"needed",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/loadbalance/roundrobin/fsm.go#L60-L86 |
151,599 | vulcand/vulcan | loadbalance/roundrobin/fsm.go | splitEndpoints | func splitEndpoints(endpoints []*WeightedEndpoint) (map[string]bool, map[string]bool) {
failRates := make([]float64, len(endpoints))
for i, e := range endpoints {
failRates[i] = e.failRate()
}
g, b := metrics.SplitFloat64(1.5, 0, failRates)
good, bad := make(map[string]bool, len(g)), make(map[string]bool, len(b))
for _, e := range endpoints {
if g[e.failRate()] {
good[e.GetId()] = true
} else {
bad[e.GetId()] = true
}
}
return good, bad
} | go | func splitEndpoints(endpoints []*WeightedEndpoint) (map[string]bool, map[string]bool) {
failRates := make([]float64, len(endpoints))
for i, e := range endpoints {
failRates[i] = e.failRate()
}
g, b := metrics.SplitFloat64(1.5, 0, failRates)
good, bad := make(map[string]bool, len(g)), make(map[string]bool, len(b))
for _, e := range endpoints {
if g[e.failRate()] {
good[e.GetId()] = true
} else {
bad[e.GetId()] = true
}
}
return good, bad
} | [
"func",
"splitEndpoints",
"(",
"endpoints",
"[",
"]",
"*",
"WeightedEndpoint",
")",
"(",
"map",
"[",
"string",
"]",
"bool",
",",
"map",
"[",
"string",
"]",
"bool",
")",
"{",
"failRates",
":=",
"make",
"(",
"[",
"]",
"float64",
",",
"len",
"(",
"endpo... | // splitEndpoints splits endpoints into two groups of endpoints with bad and good failure rate.
// It does compare relative performances of the endpoints though, so if all endpoints have approximately the same error rate
// this function returns the result as if all endpoints are equally good. | [
"splitEndpoints",
"splits",
"endpoints",
"into",
"two",
"groups",
"of",
"endpoints",
"with",
"bad",
"and",
"good",
"failure",
"rate",
".",
"It",
"does",
"compare",
"relative",
"performances",
"of",
"the",
"endpoints",
"though",
"so",
"if",
"all",
"endpoints",
... | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/loadbalance/roundrobin/fsm.go#L181-L201 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.