nwo stringlengths 7 28 | sha stringlengths 40 40 | path stringlengths 6 81 | language stringclasses 1 value | identifier stringlengths 1 29 | parameters stringlengths 2 104 | argument_list stringclasses 1 value | return_statement stringclasses 1 value | docstring stringlengths 0 765 | docstring_summary stringlengths 0 735 | docstring_tokens list | function stringlengths 66 9.83k | function_tokens list | url stringlengths 90 185 | score float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mattbaird/elastigo | 2fe47fd29e4b70353f852ede77a196830d2924ec | lib/searchfilter.go | go | NewGeoField | (field string, latitude float32, longitude float32) | // NewGeoField is a helper function to create values for the GeoDistance filters | NewGeoField is a helper function to create values for the GeoDistance filters | [
"NewGeoField",
"is",
"a",
"helper",
"function",
"to",
"create",
"values",
"for",
"the",
"GeoDistance",
"filters"
] | func NewGeoField(field string, latitude float32, longitude float32) GeoField {
return GeoField{
GeoLocation: GeoLocation{Latitude: latitude, Longitude: longitude},
Field: field}
} | [
"func",
"NewGeoField",
"(",
"field",
"string",
",",
"latitude",
"float32",
",",
"longitude",
"float32",
")",
"GeoField",
"{",
"return",
"GeoField",
"{",
"GeoLocation",
":",
"GeoLocation",
"{",
"Latitude",
":",
"latitude",
",",
"Longitude",
":",
"longitude",
"}... | https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L324-L328 | 0.576001 | ||
cloudfoundry/bosh-utils | 757f0ce2bf30bab7848e17679ca54f74e574facb | httpclient/socksify.go | go | SOCKS5DialFuncFromEnvironment | (origDialer DialFunc, socks5Proxy ProxyDialer) | [] | func SOCKS5DialFuncFromEnvironment(origDialer DialFunc, socks5Proxy ProxyDialer) DialFunc {
allProxy := os.Getenv("BOSH_ALL_PROXY")
if len(allProxy) == 0 {
return origDialer
}
if strings.HasPrefix(allProxy, "ssh+") {
allProxy = strings.TrimPrefix(allProxy, "ssh+")
proxyURL, err := url.Parse(allProxy)
if err != nil {
return errorDialFunc(err, "Parsing BOSH_ALL_PROXY url")
}
queryMap, err := url.ParseQuery(proxyURL.RawQuery)
if err != nil {
return errorDialFunc(err, "Parsing BOSH_ALL_PROXY query params")
}
username := ""
if proxyURL.User != nil {
username = proxyURL.User.Username()
}
proxySSHKeyPath := queryMap.Get("private-key")
if proxySSHKeyPath == "" {
return errorDialFunc(
bosherr.Error("Required query param 'private-key' not found"),
"Parsing BOSH_ALL_PROXY query params",
)
}
proxySSHKey, err := ioutil.ReadFile(proxySSHKeyPath)
if err != nil {
return errorDialFunc(err, "Reading private key file for SOCKS5 Proxy")
}
var (
dialer proxy.DialFunc
mut sync.RWMutex
)
return func(network, address string) (net.Conn, error) {
mut.RLock()
haveDialer := dialer != nil
mut.RUnlock()
if haveDialer {
return dialer(network, address)
}
mut.Lock()
defer mut.Unlock()
if dialer == nil {
proxyDialer, err := socks5Proxy.Dialer(username, string(proxySSHKey), proxyURL.Host)
if err != nil {
return nil, bosherr.WrapErrorf(err, "Creating SOCKS5 dialer")
}
dialer = proxyDialer
}
return dialer(network, address)
}
}
proxyURL, err := url.Parse(allProxy)
if err != nil {
return errorDialFunc(err, "Parsing BOSH_ALL_PROXY url")
}
proxy, err := goproxy.FromURL(proxyURL, origDialer)
if err != nil {
return errorDialFunc(err, "Parsing BOSH_ALL_PROXY url")
}
noProxy := os.Getenv("no_proxy")
if len(noProxy) == 0 {
return proxy.Dial
}
perHost := goproxy.NewPerHost(proxy, origDialer)
perHost.AddFromString(noProxy)
return perHost.Dial
} | [
"func",
"SOCKS5DialFuncFromEnvironment",
"(",
"origDialer",
"DialFunc",
",",
"socks5Proxy",
"ProxyDialer",
")",
"DialFunc",
"{",
"allProxy",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"allProxy",
")",
"==",
"0",
"{",
"return",
... | https://github.com/cloudfoundry/bosh-utils/blob/757f0ce2bf30bab7848e17679ca54f74e574facb/httpclient/socksify.go#L25-L107 | 0.574427 | ||||
gopherjs/webgl | 39bd6d41eeb587730fcaa65adf71978fb10675bc | webgl.go | go | Viewport | (c *Context) (x, y, width, height int) | // public function vertexAttrib1f(indx:GLuint, x:GLfloat) : Void;
// public function vertexAttrib2f(indx:GLuint, x:GLfloat, y:GLfloat) : Void;
// public function vertexAttrib3f(indx:GLuint, x:GLfloat, y:GLfloat, z:GLfloat) : Void;
// public function vertexAttrib4f(indx:GLuint, x:GLfloat, y:GLfloat, z:GLfloat, w:GLfloat) : Void;
// public function vertexAttrib1fv(indx:GLuint, values:ArrayAccess<Float>) : Void;
// public function vertexAttrib2fv(indx:GLuint, values:ArrayAccess<Float>) : Void;
// public function vertexAttrib3fv(indx:GLuint, values:ArrayAccess<Float>) : Void;
// public function vertexAttrib4fv(indx:GLuint, values:ArrayAccess<Float>) : Void;
// Represents a rectangular viewable area that contains
// the rendering results of the drawing buffer. | public function vertexAttrib1f(indx:GLuint, x:GLfloat) : Void;
public function vertexAttrib2f(indx:GLuint, x:GLfloat, y:GLfloat) : Void;
public function vertexAttrib3f(indx:GLuint, x:GLfloat, y:GLfloat, z:GLfloat) : Void;
public function vertexAttrib4f(indx:GLuint, x:GLfloat, y:GLfloat, z:GLfloat, w:GLfloat) : Void;
public function vertexAttrib1fv(indx:GLuint, values:ArrayAccess<Float>) : Void;
public function vertexAttrib2fv(indx:GLuint, values:ArrayAccess<Float>) : Void;
public function vertexAttrib3fv(indx:GLuint, values:ArrayAccess<Float>) : Void;
public function vertexAttrib4fv(indx:GLuint, values:ArrayAccess<Float>) : Void;
Represents a rectangular viewable area that contains
the rendering results of the drawing buffer. | [
"public",
"function",
"vertexAttrib1f",
"(",
"indx",
":",
"GLuint",
"x",
":",
"GLfloat",
")",
":",
"Void",
";",
"public",
"function",
"vertexAttrib2f",
"(",
"indx",
":",
"GLuint",
"x",
":",
"GLfloat",
"y",
":",
"GLfloat",
")",
":",
"Void",
";",
"public",... | func (c *Context) Viewport(x, y, width, height int) {
c.Call("viewport", x, y, width, height)
} | [
"func",
"(",
"c",
"*",
"Context",
")",
"Viewport",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
"int",
")",
"{",
"c",
".",
"Call",
"(",
"\"",
"\"",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
"\n",
"}"
] | https://github.com/gopherjs/webgl/blob/39bd6d41eeb587730fcaa65adf71978fb10675bc/webgl.go#L1008-L1010 | 0.568816 | ||
go-openapi/swag | b3e2804c8535ee0d1b89320afd98474d5b8e9e3b | convert.go | go | ConvertInt8 | (str string) | // ConvertInt8 turn a string into int8 boolean | ConvertInt8 turn a string into int8 boolean | [
"ConvertInt8",
"turn",
"a",
"string",
"into",
"int8",
"boolean"
] | func ConvertInt8(str string) (int8, error) {
i, err := strconv.ParseInt(str, 10, 8)
if err != nil {
return 0, err
}
return int8(i), nil
} | [
"func",
"ConvertInt8",
"(",
"str",
"string",
")",
"(",
"int8",
",",
"error",
")",
"{",
"i",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"str",
",",
"10",
",",
"8",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n"... | https://github.com/go-openapi/swag/blob/b3e2804c8535ee0d1b89320afd98474d5b8e9e3b/convert.go#L91-L97 | 0.568089 | ||
go-openapi/swag | b3e2804c8535ee0d1b89320afd98474d5b8e9e3b | json.go | go | ToDynamicJSON | (data interface{}) | // ToDynamicJSON turns an object into a properly JSON typed structure | ToDynamicJSON turns an object into a properly JSON typed structure | [
"ToDynamicJSON",
"turns",
"an",
"object",
"into",
"a",
"properly",
"JSON",
"typed",
"structure"
] | func ToDynamicJSON(data interface{}) interface{} {
// TODO: convert straight to a json typed map (mergo + iterate?)
b, err := json.Marshal(data)
if err != nil {
log.Println(err)
}
var res interface{}
if err := json.Unmarshal(b, &res); err != nil {
log.Println(err)
}
return res
} | [
"func",
"ToDynamicJSON",
"(",
"data",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
"{",
"// TODO: convert straight to a json typed map (mergo + iterate?)",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"... | https://github.com/go-openapi/swag/blob/b3e2804c8535ee0d1b89320afd98474d5b8e9e3b/json.go#L170-L181 | 0.568089 | ||
koron/go-dproxy | fd990aff3734271e213a87f118319cf104bb2dd6 | set.go | go | ArrayArray | (p *setProxy) () | [] | func (p *setProxy) ArrayArray() ([][]interface{}, error) {
r := make([][]interface{}, len(p.values))
for i, v := range p.values {
switch v := v.(type) {
case []interface{}:
r[i] = v
default:
return nil, elementTypeError(p, i, Tarray, v)
}
}
return r, nil
} | [
"func",
"(",
"p",
"*",
"setProxy",
")",
"ArrayArray",
"(",
")",
"(",
"[",
"]",
"[",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"r",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"p",
".",
"values",
... | https://github.com/koron/go-dproxy/blob/fd990aff3734271e213a87f118319cf104bb2dd6/set.go#L90-L101 | 0.564041 | ||||
softlayer/softlayer-go | aa510384a41b6450fa6a50e943ed32f5e838fada | services/network.go | go | GetByIpAddress | (r Network_Subnet_IpAddress) (ipAddress *string) | // Search for an IP address record by IP address. | Search for an IP address record by IP address. | [
"Search",
"for",
"an",
"IP",
"address",
"record",
"by",
"IP",
"address",
"."
] | func (r Network_Subnet_IpAddress) GetByIpAddress(ipAddress *string) (resp datatypes.Network_Subnet_IpAddress, err error) {
params := []interface{}{
ipAddress,
}
err = r.Session.DoRequest("SoftLayer_Network_Subnet_IpAddress", "getByIpAddress", params, &r.Options, &resp)
return
} | [
"func",
"(",
"r",
"Network_Subnet_IpAddress",
")",
"GetByIpAddress",
"(",
"ipAddress",
"*",
"string",
")",
"(",
"resp",
"datatypes",
".",
"Network_Subnet_IpAddress",
",",
"err",
"error",
")",
"{",
"params",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"ipAddr... | https://github.com/softlayer/softlayer-go/blob/aa510384a41b6450fa6a50e943ed32f5e838fada/services/network.go#L14465-L14471 | 0.559208 | ||
luci/luci-go | f6cef429871eee3be7c6903af88d3ee884eaf683 | common/retry/limited.go | go | Next | (i *Limited) (ctx context.Context, _ error) | // Next implements the Iterator interface. | Next implements the Iterator interface. | [
"Next",
"implements",
"the",
"Iterator",
"interface",
"."
] | func (i *Limited) Next(ctx context.Context, _ error) time.Duration {
switch {
case i.Retries == 0:
return Stop
case i.Retries > 0:
i.Retries--
}
// If there is a maximum total time, enforce it.
if i.MaxTotal > 0 {
now := clock.Now(ctx)
if i.startTime.IsZero() {
i.startTime = now
}
var elapsed time.Duration
if now.After(i.startTime) {
elapsed = now.Sub(i.startTime)
}
// Remaining time is the difference between total allowed time and elapsed
// time.
remaining := i.MaxTotal - elapsed
if remaining <= 0 {
// No more time!
i.Retries = 0
return Stop
}
}
return i.Delay
} | [
"func",
"(",
"i",
"*",
"Limited",
")",
"Next",
"(",
"ctx",
"context",
".",
"Context",
",",
"_",
"error",
")",
"time",
".",
"Duration",
"{",
"switch",
"{",
"case",
"i",
".",
"Retries",
"==",
"0",
":",
"return",
"Stop",
"\n",
"case",
"i",
".",
"Ret... | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/retry/limited.go#L45-L76 | 0.55891 | ||
leesper/go_rng | 5344a9259b21627d94279721ab1f27eb029194e7 | binomial.go | go | binomial | (bing BinomialGenerator) (n int64, p float64) | [] | func (bing BinomialGenerator) binomial(n int64, p float64) int64 {
if !(0.0 <= p && p <= 1.0) {
panic(fmt.Sprintf("Invalid probability p: %.2f", p))
}
if n <= 0 {
panic(fmt.Sprintf("Invalid parameter n: %d", n))
}
var i, result int64
for i = 0; i < n; i++ {
if bing.uniform.Float64() < p {
result++
}
}
return result
} | [
"func",
"(",
"bing",
"BinomialGenerator",
")",
"binomial",
"(",
"n",
"int64",
",",
"p",
"float64",
")",
"int64",
"{",
"if",
"!",
"(",
"0.0",
"<=",
"p",
"&&",
"p",
"<=",
"1.0",
")",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
... | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/binomial.go#L51-L65 | 0.556019 | ||||
fabric8-services/fabric8-wit | 54759c80c42ff2cf29b352e0f6c9330ce4ad7fce | kubernetes/deployments_kubeclient.go | go | getRoutesFromRouteList | (list map[string]interface{}) | [] | func getRoutesFromRouteList(list map[string]interface{}) ([]interface{}, error) {
// Parse list of routes
kind, ok := list["kind"].(string)
if !ok || kind != "RouteList" {
return nil, errs.New("No route list returned from endpoint")
}
items, ok := list["items"].([]interface{})
if !ok {
return nil, errs.New("No list of routes in response")
}
return items, nil
} | [
"func",
"getRoutesFromRouteList",
"(",
"list",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"// Parse list of routes",
"kind",
",",
"ok",
":=",
"list",
"[",
"\"",
"\"",
"]",
".",
... | https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L2066-L2077 | 0.530833 | ||||
fabric8-services/fabric8-wit | 54759c80c42ff2cf29b352e0f6c9330ce4ad7fce | search/search_repository.go | go | getSearchQueryFromURLString | (url string) | /*
getSearchQueryFromURLString gets a url string and checks if that matches with any of known urls.
Respectively it will return a string that can be directly used in search query
e.g>
Unknown url : www.google.com then response = "www.google.com:*"
Known url : almighty.io/detail/500 then response = "500:* | almighty.io/detail/500"
*/ | /*
getSearchQueryFromURLString gets a url string and checks if that matches with any of known urls.
Respectively it will return a string that can be directly used in search query
e.g>
Unknown url : www.google.com then response = "www.google.com:*"
Known url : almighty.io/detail/500 then response = "500:* | almighty.io/detail/500" | [
"/",
"*",
"getSearchQueryFromURLString",
"gets",
"a",
"url",
"string",
"and",
"checks",
"if",
"that",
"matches",
"with",
"any",
"of",
"known",
"urls",
".",
"Respectively",
"it",
"will",
"return",
"a",
"string",
"that",
"can",
"be",
"directly",
"used",
"in",
... | func getSearchQueryFromURLString(url string) string {
known, patternName := isKnownURL(url)
if known {
// this url is known to system
return getSearchQueryFromURLPattern(patternName, url)
}
// any URL other than our system's
// return url without protocol
return sanitizeURL(url) + ":*"
} | [
"func",
"getSearchQueryFromURLString",
"(",
"url",
"string",
")",
"string",
"{",
"known",
",",
"patternName",
":=",
"isKnownURL",
"(",
"url",
")",
"\n",
"if",
"known",
"{",
"// this url is known to system",
"return",
"getSearchQueryFromURLPattern",
"(",
"patternName",... | https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/search/search_repository.go#L204-L213 | 0.530833 | ||
segmentio/objconv | 7a1d7b8e6f3551b30751e6b2ea6bae500883870e | adapters/net/url/encode.go | go | encodeURL | (e objconv.Encoder, v reflect.Value) | [] | func encodeURL(e objconv.Encoder, v reflect.Value) error {
u := v.Interface().(url.URL)
return e.Encode(u.String())
} | [
"func",
"encodeURL",
"(",
"e",
"objconv",
".",
"Encoder",
",",
"v",
"reflect",
".",
"Value",
")",
"error",
"{",
"u",
":=",
"v",
".",
"Interface",
"(",
")",
".",
"(",
"url",
".",
"URL",
")",
"\n",
"return",
"e",
".",
"Encode",
"(",
"u",
".",
"St... | https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/adapters/net/url/encode.go#L10-L13 | 0.52595 | ||||
ardielle/ardielle-go | c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff | rdl/basictypes_model.go | go | NewMapArrayTest | (init ...*MapArrayTest) | //
// NewMapArrayTest - creates an initialized MapArrayTest instance, returns a pointer to it
// | NewMapArrayTest - creates an initialized MapArrayTest instance, returns a pointer to it | [
"NewMapArrayTest",
"-",
"creates",
"an",
"initialized",
"MapArrayTest",
"instance",
"returns",
"a",
"pointer",
"to",
"it"
] | func NewMapArrayTest(init ...*MapArrayTest) *MapArrayTest {
var o *MapArrayTest
if len(init) == 1 {
o = init[0]
} else {
o = new(MapArrayTest)
}
return o.Init()
} | [
"func",
"NewMapArrayTest",
"(",
"init",
"...",
"*",
"MapArrayTest",
")",
"*",
"MapArrayTest",
"{",
"var",
"o",
"*",
"MapArrayTest",
"\n",
"if",
"len",
"(",
"init",
")",
"==",
"1",
"{",
"o",
"=",
"init",
"[",
"0",
"]",
"\n",
"}",
"else",
"{",
"o",
... | https://github.com/ardielle/ardielle-go/blob/c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff/rdl/basictypes_model.go#L284-L292 | 0.520639 | ||
volatiletech/abcweb | 9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66 | abcsessions/middleware.go | go | SetCookie | (s *sessionsResponseWriter) (cookie *http.Cookie) | [] | func (s *sessionsResponseWriter) SetCookie(cookie *http.Cookie) {
if s.cookies == nil {
s.cookies = make(map[string]*http.Cookie)
}
if len(cookie.Name) == 0 {
panic("cookie name cannot be empty")
}
s.cookies[cookie.Name] = cookie
} | [
"func",
"(",
"s",
"*",
"sessionsResponseWriter",
")",
"SetCookie",
"(",
"cookie",
"*",
"http",
".",
"Cookie",
")",
"{",
"if",
"s",
".",
"cookies",
"==",
"nil",
"{",
"s",
".",
"cookies",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"http",
".",... | https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/middleware.go#L50-L60 | 0.515641 | ||||
miketheprogrammer/go-thrust | 6aa55589fcc4ec586d442e4f7ed315afe3dfcda9 | lib/spawn/helper_windows.go | go | executableNotExist | () | [] | func executableNotExist() bool {
_, err := os.Stat(GetExecutablePath())
return os.IsNotExist(err)
} | [
"func",
"executableNotExist",
"(",
")",
"bool",
"{",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"GetExecutablePath",
"(",
")",
")",
"\n",
"return",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"\n",
"}"
] | https://github.com/miketheprogrammer/go-thrust/blob/6aa55589fcc4ec586d442e4f7ed315afe3dfcda9/lib/spawn/helper_windows.go#L51-L54 | 0.464537 | ||||
rsc/rsc | fc62025902295658a9c7e89418e095fd598b2682 | google/gmail/gmail.go | go | parsecmd | (line string) | [] | func parsecmd(line string) (cmd *Cmd, err error) {
cmd = &Cmd{}
line = strings.TrimSpace(line)
if line == "" {
// Empty command is a special case: advance and print.
cmd.F = pcmd
if dot == nil {
cmd.A1 = 1
cmd.A2 = 1
} else {
n := msgNum[dot.Msg] + 2
if n > len(msgs) {
return nil, fmt.Errorf("out of messages")
}
cmd.A1 = n
cmd.A2 = n
}
return cmd, nil
}
// Global search?
if line[0] == 'g' {
line = line[1:]
if line == "" || line[0] != '/' {
// No search string means all messages.
cmd.A1 = 1
cmd.A2 = len(msgs)
} else if line[0] == '/' {
re, rest, err := parsere(line)
if err != nil {
return nil, err
}
line = rest
// Find all messages matching this search string.
var targ []*imap.Msg
for _, m := range msgs {
if re.MatchString(header(m)) {
targ = append(targ, m)
}
}
if len(targ) == 0 {
return nil, fmt.Errorf("no matches")
}
cmd.Targs = targ
}
} else {
// Parse an address.
a1, targ, rest, err := parseaddr(line, 1)
if err != nil {
return nil, err
}
if targ != nil {
cmd.Targ = targ
line = rest
} else {
if a1 < 1 || a1 > len(msgs) {
return nil, fmt.Errorf("message number %d out of range", a1)
}
cmd.A1 = a1
cmd.A2 = a1
a2 := a1
if rest != "" && rest[0] == ',' {
// This is an address range.
a2, targ, rest, err = parseaddr(rest[1:], len(msgs))
if err != nil {
return nil, err
}
if a2 < 1 || a2 > len(msgs) {
return nil, fmt.Errorf("message number %d out of range", a2)
}
cmd.A2 = a2
} else if rest == line {
// There was no address.
if dot == nil {
cmd.A1 = 1
cmd.A2 = 0
} else {
if dot != nil {
if dot == &dot.Msg.Root {
// If dot is a plain msg, use a range so that dp works.
cmd.A1 = msgNum[dot.Msg] + 1
cmd.A2 = cmd.A1
} else {
cmd.Targ = dot
}
}
}
}
line = rest
}
}
cmd.Line = strings.TrimSpace(line)
// Insert space after ! or | for tokenization.
switch {
case strings.HasPrefix(cmd.Line, "||"):
cmd.Line = cmd.Line[:2] + " " + cmd.Line[2:]
case strings.HasPrefix(cmd.Line, "!"), strings.HasPrefix(cmd.Line, "|"):
cmd.Line = cmd.Line[:1] + " " + cmd.Line[1:]
}
av := strings.Fields(cmd.Line)
cmd.Args = av
if len(av) == 0 || av[0] == "" {
// Default is to print.
cmd.F = pcmd
return cmd, nil
}
name := av[0]
cmd.ArgLine = strings.TrimSpace(cmd.Line[len(av[0]):])
// Hack to allow t prefix on all commands.
if len(name) >= 2 && name[0] == 't' {
cmd.Thread = true
name = name[1:]
}
// Hack to allow d prefix on all commands.
if len(name) >= 2 && name[0] == 'd' {
cmd.Delete = true
name = name[1:]
}
cmd.Name = name
// Search command table.
for _, ct := range cmdtab {
if ct.Name == name {
if ct.Args == 0 && len(av) > 1 {
return nil, fmt.Errorf("%s doesn't take an argument", name)
}
cmd.F = ct.F
cmd.TF = ct.TF
if name == "m" {
// mute applies to all thread no matter what
cmd.Thread = true
}
return cmd, nil
}
}
return nil, fmt.Errorf("unknown command %s", name)
} | [
"func",
"parsecmd",
"(",
"line",
"string",
")",
"(",
"cmd",
"*",
"Cmd",
",",
"err",
"error",
")",
"{",
"cmd",
"=",
"&",
"Cmd",
"{",
"}",
"\n",
"line",
"=",
"strings",
".",
"TrimSpace",
"(",
"line",
")",
"\n",
"if",
"line",
"==",
"\"",
"\"",
"{"... | https://github.com/rsc/rsc/blob/fc62025902295658a9c7e89418e095fd598b2682/google/gmail/gmail.go#L275-L417 | 0.435933 | ||||
control-center/serviced | 7028f598e6a224b4d421e09cb9b582ad7d000304 | datastore/datastore.go | go | deserialize | (ds *DataStore) (kind string, jsonMsg JSONMessage, entity ValidEntity) | [] | func (ds *DataStore) deserialize(kind string, jsonMsg JSONMessage, entity ValidEntity) error {
// hook for looking up deserializers by kind; default json Unmarshal for now
if err := SafeUnmarshal(jsonMsg.Bytes(), entity); err != nil {
return err
}
entity.SetDatabaseVersion(jsonMsg.Version())
return nil
} | [
"func",
"(",
"ds",
"*",
"DataStore",
")",
"deserialize",
"(",
"kind",
"string",
",",
"jsonMsg",
"JSONMessage",
",",
"entity",
"ValidEntity",
")",
"error",
"{",
"// hook for looking up deserializers by kind; default json Unmarshal for now",
"if",
"err",
":=",
"SafeUnmars... | https://github.com/control-center/serviced/blob/7028f598e6a224b4d421e09cb9b582ad7d000304/datastore/datastore.go#L170-L177 | 0.39751 | ||||
control-center/serviced | 7028f598e6a224b4d421e09cb9b582ad7d000304 | cli/api/logs.go | go | retrieveLogs | (exporter *logExporter) () | // Retrieve log data from ES-logstash, writing the log messages to separate files based on the group-by criteria. | Retrieve log data from ES-logstash, writing the log messages to separate files based on the group-by criteria. | [
"Retrieve",
"log",
"data",
"from",
"ES",
"-",
"logstash",
"writing",
"the",
"log",
"messages",
"to",
"separate",
"files",
"based",
"on",
"the",
"group",
"-",
"by",
"criteria",
"."
] | func (exporter *logExporter) retrieveLogs() (foundIndexedDay bool, numWarnings int, e error) {
numWarnings = 0
foundIndexedDay = false
// fileIndex is a map of parsedMessage to an index into exporter.outputFiles
exporter.fileIndex = NewFileIndex(exporter.GroupBy)
for _, yyyymmdd := range exporter.days {
// Skip the indexes that are filtered out by the date range
if (exporter.FromDate != "" && yyyymmdd < exporter.FromDate) || (exporter.ToDate != "" && yyyymmdd > exporter.ToDate) {
continue
} else {
foundIndexedDay = true
}
if exporter.Debug {
log.WithFields(logrus.Fields{
"date": yyyymmdd,
}).Info("Querying logstash for given date")
}
log := log.WithFields(logrus.Fields{
"date": yyyymmdd,
})
log.Info("Retrieving Logstash Elastic results for one day")
result, e := exporter.Driver.StartSearch(yyyymmdd, exporter.query)
if e != nil {
return foundIndexedDay, numWarnings, fmt.Errorf("failed to search elasticsearch for day %s: %s", yyyymmdd, e)
}
if exporter.Debug {
log.WithFields(logrus.Fields{
"date": yyyymmdd,
"totalmsgs": result.Hits.Total,
}).Info("Found log messages")
}
//TODO: Submit a patch to elastigo to support the "clear scroll" api. Add a "defer" here.
remaining := result.Hits.Total > 0
for remaining {
result, e = exporter.Driver.ScrollSearch(result.ScrollId)
if e != nil {
return foundIndexedDay, numWarnings, e
}
hits := result.Hits.Hits
total := len(hits)
for i := 0; i < total; i++ {
message, e := parseLogSource(yyyymmdd, hits[i].Source)
if e != nil {
return foundIndexedDay, numWarnings, e
}
// Ignore log messages sent directly from serviced and serviced-controller; only
// export logs from the applications themselves. Note that filebeat is hard-coded
// to set the _type property to "log" and we only use filebeat for messages from the
// application services.
if message.Type != "log" {
continue
}
if len(exporter.minDateFound) == 0 || yyyymmdd < exporter.minDateFound {
exporter.minDateFound = yyyymmdd
}
if len(exporter.maxDateFound) == 0 || yyyymmdd > exporter.maxDateFound {
exporter.maxDateFound = yyyymmdd
}
// add a new tempfile
if _, found := exporter.fileIndex.FindIndexForMessage(message); !found {
index := len(exporter.outputFiles)
filename := filepath.Join(exporter.tempdir, exporter.fileIndex.GetFileName(index, message))
file, e := os.Create(filename)
if e != nil {
return foundIndexedDay, numWarnings, fmt.Errorf("failed to create file %s: %s", filename, e)
}
exporter.fileIndex.AddIndexForMessage(index, message)
outputFile := outputFileInfo{
File: file,
Name: filename,
HostID: message.HostID,
ContainerID: message.ContainerID,
LogFileName: message.LogFileName,
ServiceID: message.ServiceID,
}
exporter.outputFiles = append(exporter.outputFiles, outputFile)
}
index, _ := exporter.fileIndex.FindIndexForMessage(message)
exporter.outputFiles[index].LineCount += len(message.Lines)
file := exporter.outputFiles[index].File
filename := exporter.outputFiles[index].Name
for _, line := range message.Lines {
formatted := fmt.Sprintf("%016x\t%016x\t%s\n", line.Timestamp, line.Offset, line.Message)
if _, e := file.WriteString(formatted); e != nil {
return foundIndexedDay, numWarnings, fmt.Errorf("failed writing to file %s: %s", filename, e)
}
}
if len(message.Warnings) > 0 {
if _, e := exporter.parseWarningsFile.WriteString(message.Warnings); e != nil {
return foundIndexedDay, numWarnings, fmt.Errorf("failed writing to file %s: %s", exporter.parseWarningsFilename, e)
}
numWarnings++
}
}
remaining = len(hits) > 0
}
}
return foundIndexedDay, numWarnings, nil
} | [
"func",
"(",
"exporter",
"*",
"logExporter",
")",
"retrieveLogs",
"(",
")",
"(",
"foundIndexedDay",
"bool",
",",
"numWarnings",
"int",
",",
"e",
"error",
")",
"{",
"numWarnings",
"=",
"0",
"\n",
"foundIndexedDay",
"=",
"false",
"\n",
"// fileIndex is a map of ... | https://github.com/control-center/serviced/blob/7028f598e6a224b4d421e09cb9b582ad7d000304/cli/api/logs.go#L511-L616 | 0.39751 | ||
signalfx/gateway | 60f8886d9dbf529d974d8f3c0b9e932d8a7570a0 | config/config.go | go | stringToURL | (s string) | [] | func stringToURL(s string) (u *url.URL, err error) {
if s != "" && !strings.HasPrefix(s, "http") {
u, err = url.Parse(fmt.Sprintf("http://%s", s))
} else {
u, err = url.Parse(s)
}
return u, err
} | [
"func",
"stringToURL",
"(",
"s",
"string",
")",
"(",
"u",
"*",
"url",
".",
"URL",
",",
"err",
"error",
")",
"{",
"if",
"s",
"!=",
"\"",
"\"",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"s",
",",
"\"",
"\"",
")",
"{",
"u",
",",
"err",
"=",
... | https://github.com/signalfx/gateway/blob/60f8886d9dbf529d974d8f3c0b9e932d8a7570a0/config/config.go#L179-L187 | 0.396888 | ||||
chzyer/logex | 445be9e134b204a8c920a30fedad02b2f2ab1efd | logex.go | go | Pretty | (l Logger) (os ...interface{}) | // output objects to json format | output objects to json format | [
"output",
"objects",
"to",
"json",
"format"
] | func (l Logger) Pretty(os ...interface{}) {
content := ""
for i := range os {
if ret, err := json.MarshalIndent(os[i], "", "\t"); err == nil {
content += string(ret) + "\n"
}
}
l.Output(2, PRETTY+content)
} | [
"func",
"(",
"l",
"Logger",
")",
"Pretty",
"(",
"os",
"...",
"interface",
"{",
"}",
")",
"{",
"content",
":=",
"\"",
"\"",
"\n",
"for",
"i",
":=",
"range",
"os",
"{",
"if",
"ret",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"os",
"[",
... | https://github.com/chzyer/logex/blob/445be9e134b204a8c920a30fedad02b2f2ab1efd/logex.go#L109-L117 | 0.395561 | ||
pivotal-cf/go-pivnet | e68f8203b478c0c65b90f196471522949c002710 | release_dependencies.go | go | List | (r ReleaseDependenciesService) (productSlug string, releaseID int) | [] | func (r ReleaseDependenciesService) List(productSlug string, releaseID int) ([]ReleaseDependency, error) {
url := fmt.Sprintf(
"/products/%s/releases/%d/dependencies",
productSlug,
releaseID,
)
var response ReleaseDependenciesResponse
resp, err := r.client.MakeRequest(
"GET",
url,
http.StatusOK,
nil,
)
if err != nil {
return nil, err
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
return nil, err
}
return response.ReleaseDependencies, nil
} | [
"func",
"(",
"r",
"ReleaseDependenciesService",
")",
"List",
"(",
"productSlug",
"string",
",",
"releaseID",
"int",
")",
"(",
"[",
"]",
"ReleaseDependency",
",",
"error",
")",
"{",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"productSlug",
... | https://github.com/pivotal-cf/go-pivnet/blob/e68f8203b478c0c65b90f196471522949c002710/release_dependencies.go#L28-L53 | 0.394364 | ||||
clbanning/x2j | 5e605d46809c441eb0e565867b63f7d80c9140c2 | x2j.go | go | DocToJsonIndent | (doc string, recast ...bool) | // DocToJsonIndent - return an XML doc as a prettified JSON string.
// If the optional argument 'recast' is 'true', then values will be converted to boolean or float64 if possible.
// Note: recasting is only applied to element values, not attribute values. | DocToJsonIndent - return an XML doc as a prettified JSON string.
If the optional argument 'recast' is 'true', then values will be converted to boolean or float64 if possible.
Note: recasting is only applied to element values, not attribute values. | [
"DocToJsonIndent",
"-",
"return",
"an",
"XML",
"doc",
"as",
"a",
"prettified",
"JSON",
"string",
".",
"If",
"the",
"optional",
"argument",
"recast",
"is",
"true",
"then",
"values",
"will",
"be",
"converted",
"to",
"boolean",
"or",
"float64",
"if",
"possible"... | func DocToJsonIndent(doc string, recast ...bool) (string, error) {
var r bool
if len(recast) == 1 {
r = recast[0]
}
m, merr := xmlToMap([]byte(doc), r)
if m == nil || merr != nil {
return "", merr
}
b, berr := json.MarshalIndent(m, "", " ")
if berr != nil {
return "", berr
}
// NOTE: don't have to worry about safe JSON marshaling with json.Marshal, since '<' and '>" are reservedin XML.
return string(b), nil
} | [
"func",
"DocToJsonIndent",
"(",
"doc",
"string",
",",
"recast",
"...",
"bool",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"r",
"bool",
"\n",
"if",
"len",
"(",
"recast",
")",
"==",
"1",
"{",
"r",
"=",
"recast",
"[",
"0",
"]",
"\n",
"}",
... | https://github.com/clbanning/x2j/blob/5e605d46809c441eb0e565867b63f7d80c9140c2/x2j.go#L124-L141 | 0.393908 | ||
ChrisTrenkamp/goxpath | c385f95c6022e7756e91beac5f5510872f7dcb7d | internal/execxp/findutil/findUtil.go | go | findAncestor | (x tree.Node, p *pathexpr.PathExpr, ret *[]tree.Node) | [] | func findAncestor(x tree.Node, p *pathexpr.PathExpr, ret *[]tree.Node) {
if x.GetNodeType() == tree.NtRoot {
return
}
addNode(x.GetParent(), p, ret)
findAncestor(x.GetParent(), p, ret)
} | [
"func",
"findAncestor",
"(",
"x",
"tree",
".",
"Node",
",",
"p",
"*",
"pathexpr",
".",
"PathExpr",
",",
"ret",
"*",
"[",
"]",
"tree",
".",
"Node",
")",
"{",
"if",
"x",
".",
"GetNodeType",
"(",
")",
"==",
"tree",
".",
"NtRoot",
"{",
"return",
"\n"... | https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/internal/execxp/findutil/findUtil.go#L48-L55 | 0.392763 | ||||
jpfielding/gorets | 1fe0f2d805aec564b6a18e24909e0f544a71e0a3 | pkg/util/metadata_conversion.go | go | Convert | (cm AsStandard) () | // Convert ... | Convert ... | [
"Convert",
"..."
] | func (cm AsStandard) Convert() (*metadata.MSystem, error) {
ms := &metadata.MSystem{}
ms.Date = metadata.DateTime(cm.MSystem.Date)
ms.Version = metadata.Version(cm.MSystem.Version)
ms.System.ID = cm.MSystem.System.ID
ms.System.Description = cm.MSystem.System.Description
ms.System.MetadataID = cm.MSystem.System.MetadataID
ms.System.TimeZoneOffset = cm.MSystem.System.TimeZoneOffset
ms.System.Comments = cm.MSystem.Comments
// TODO figure out how compact system sub-elements exists
ms.System.MForeignKey = cm.MForeignKey()
ms.System.MResource = cm.MResource()
ms.System.MFilter = cm.MFilter()
return ms, nil
} | [
"func",
"(",
"cm",
"AsStandard",
")",
"Convert",
"(",
")",
"(",
"*",
"metadata",
".",
"MSystem",
",",
"error",
")",
"{",
"ms",
":=",
"&",
"metadata",
".",
"MSystem",
"{",
"}",
"\n",
"ms",
".",
"Date",
"=",
"metadata",
".",
"DateTime",
"(",
"cm",
... | https://github.com/jpfielding/gorets/blob/1fe0f2d805aec564b6a18e24909e0f544a71e0a3/pkg/util/metadata_conversion.go#L17-L31 | 0.391862 | ||
grokify/gotilla | a89420864b4d1cc22c57bcc025cc960a91372b37 | strconv/phonenumber/fictitiousgenerator.go | go | RandomLocalNumberUSAreaCodes | (fng *FakeNumberGenerator) (acs []uint16) | // RandomLocalNumberUS returns a US E.164 number
// AreaCode + Prefix + Line Number | RandomLocalNumberUS returns a US E.164 number
AreaCode + Prefix + Line Number | [
"RandomLocalNumberUS",
"returns",
"a",
"US",
"E",
".",
"164",
"number",
"AreaCode",
"+",
"Prefix",
"+",
"Line",
"Number"
] | func (fng *FakeNumberGenerator) RandomLocalNumberUSAreaCodes(acs []uint16) uint64 {
ac := acs[fng.Rand.Intn(len(acs))]
return fng.LocalNumberUS(ac, fng.RandomLineNumber())
} | [
"func",
"(",
"fng",
"*",
"FakeNumberGenerator",
")",
"RandomLocalNumberUSAreaCodes",
"(",
"acs",
"[",
"]",
"uint16",
")",
"uint64",
"{",
"ac",
":=",
"acs",
"[",
"fng",
".",
"Rand",
".",
"Intn",
"(",
"len",
"(",
"acs",
")",
")",
"]",
"\n",
"return",
"... | https://github.com/grokify/gotilla/blob/a89420864b4d1cc22c57bcc025cc960a91372b37/strconv/phonenumber/fictitiousgenerator.go#L49-L52 | 0.391655 | ||
grokify/gotilla | a89420864b4d1cc22c57bcc025cc960a91372b37 | time/timeutil/timeutil.go | go | Dt14ForInts | (yyyy, mm, dd, hr, mn, dy int) | // Dt8ForInts returns a Dt8 value for a UTC year, month, day, hour, minute and second. | Dt8ForInts returns a Dt8 value for a UTC year, month, day, hour, minute and second. | [
"Dt8ForInts",
"returns",
"a",
"Dt8",
"value",
"for",
"a",
"UTC",
"year",
"month",
"day",
"hour",
"minute",
"and",
"second",
"."
] | func Dt14ForInts(yyyy, mm, dd, hr, mn, dy int) int64 {
sDt14 := fmt.Sprintf("%04d%02d%02d%02d%02d%02d", yyyy, mm, dd, hr, mn, dy)
iDt14, err := strconv.ParseInt(sDt14, 10, 64)
if err != nil {
panic(err)
}
return int64(iDt14)
} | [
"func",
"Dt14ForInts",
"(",
"yyyy",
",",
"mm",
",",
"dd",
",",
"hr",
",",
"mn",
",",
"dy",
"int",
")",
"int64",
"{",
"sDt14",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"yyyy",
",",
"mm",
",",
"dd",
",",
"hr",
",",
"mn",
",",
"dy",
... | https://github.com/grokify/gotilla/blob/a89420864b4d1cc22c57bcc025cc960a91372b37/time/timeutil/timeutil.go#L276-L283 | 0.391655 | ||
polds/imgbase64 | cb7bf37298b7c2d13bd2451f51674d6bbdb46e44 | images.go | go | FromRemote | (url string) | // FromRemote is a better named function that
// presently calls NewImage which will be deprecated.
// Function accepts an RFC compliant URL and returns
// a base64 encoded result. | FromRemote is a better named function that
presently calls NewImage which will be deprecated.
Function accepts an RFC compliant URL and returns
a base64 encoded result. | [
"FromRemote",
"is",
"a",
"better",
"named",
"function",
"that",
"presently",
"calls",
"NewImage",
"which",
"will",
"be",
"deprecated",
".",
"Function",
"accepts",
"an",
"RFC",
"compliant",
"URL",
"and",
"returns",
"a",
"base64",
"encoded",
"result",
"."
] | func FromRemote(url string) string {
image, mime := get(cleanUrl(url))
enc := encode(image)
out := format(enc, mime)
return out
} | [
"func",
"FromRemote",
"(",
"url",
"string",
")",
"string",
"{",
"image",
",",
"mime",
":=",
"get",
"(",
"cleanUrl",
"(",
"url",
")",
")",
"\n",
"enc",
":=",
"encode",
"(",
"image",
")",
"\n\n",
"out",
":=",
"format",
"(",
"enc",
",",
"mime",
")",
... | https://github.com/polds/imgbase64/blob/cb7bf37298b7c2d13bd2451f51674d6bbdb46e44/images.go#L78-L84 | 0.391423 | ||
NebulousLabs/merkletree | 08d5d54b07f5e86a27f2d7431d0bc0300f5a9328 | fuzz.go | go | FuzzReadSubTreesNoProof | (data []byte) | // FuzzReadSubTreesNoProof can be used by go-fuzz to test creating a merkle
// tree from cached subTrees. | FuzzReadSubTreesNoProof can be used by go-fuzz to test creating a merkle
tree from cached subTrees. | [
"FuzzReadSubTreesNoProof",
"can",
"be",
"used",
"by",
"go",
"-",
"fuzz",
"to",
"test",
"creating",
"a",
"merkle",
"tree",
"from",
"cached",
"subTrees",
"."
] | func FuzzReadSubTreesNoProof(data []byte) int {
buildAndCompareTreesFromFuzz(data, math.MaxUint64)
if len(data) > 2 {
return 1
}
return 0
} | [
"func",
"FuzzReadSubTreesNoProof",
"(",
"data",
"[",
"]",
"byte",
")",
"int",
"{",
"buildAndCompareTreesFromFuzz",
"(",
"data",
",",
"math",
".",
"MaxUint64",
")",
"\n",
"if",
"len",
"(",
"data",
")",
">",
"2",
"{",
"return",
"1",
"\n",
"}",
"\n",
"ret... | https://github.com/NebulousLabs/merkletree/blob/08d5d54b07f5e86a27f2d7431d0bc0300f5a9328/fuzz.go#L70-L76 | 0.390852 | ||
TheThingsNetwork/go-utils | aa2a11bd59104d2a8609328c2b2b55da61826470 | errors/http.go | go | HTTPStatusCode | (err error) | // HTTPStatusCode returns the HTTP status code for the given error or 500 if it doesn't know | HTTPStatusCode returns the HTTP status code for the given error or 500 if it doesn't know | [
"HTTPStatusCode",
"returns",
"the",
"HTTP",
"status",
"code",
"for",
"the",
"given",
"error",
"or",
"500",
"if",
"it",
"doesn",
"t",
"know"
] | func HTTPStatusCode(err error) int {
e, ok := err.(Error)
if ok {
return e.Type().HTTPStatusCode()
}
return http.StatusInternalServerError
} | [
"func",
"HTTPStatusCode",
"(",
"err",
"error",
")",
"int",
"{",
"e",
",",
"ok",
":=",
"err",
".",
"(",
"Error",
")",
"\n",
"if",
"ok",
"{",
"return",
"e",
".",
"Type",
"(",
")",
".",
"HTTPStatusCode",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"http"... | https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/http.go#L53-L60 | 0.390291 | ||
coreos/go-omaha | e409d983eb60842452f0fb6245137458ca45201a | omaha/client/fuzzytime.go | go | FuzzyDuration | (d, fuzz time.Duration) | // FuzzyDuration randomizes the duration d within the range specified
// by fuzz. Specifically the value range is: [d-(fuzz/2), d+(fuzz/2)]
// The result will never be negative. | FuzzyDuration randomizes the duration d within the range specified
by fuzz. Specifically the value range is: [d-(fuzz/2), d+(fuzz/2)]
The result will never be negative. | [
"FuzzyDuration",
"randomizes",
"the",
"duration",
"d",
"within",
"the",
"range",
"specified",
"by",
"fuzz",
".",
"Specifically",
"the",
"value",
"range",
"is",
":",
"[",
"d",
"-",
"(",
"fuzz",
"/",
"2",
")",
"d",
"+",
"(",
"fuzz",
"/",
"2",
")",
"]",... | func FuzzyDuration(d, fuzz time.Duration) time.Duration {
if fuzz < 0 {
return d
}
// apply range [-fuzz/2, fuzz/2]
d += time.Duration(rand.Int63n(int64(fuzz)+1) - (int64(fuzz) / 2))
if d < 0 {
return 0
}
return d
} | [
"func",
"FuzzyDuration",
"(",
"d",
",",
"fuzz",
"time",
".",
"Duration",
")",
"time",
".",
"Duration",
"{",
"if",
"fuzz",
"<",
"0",
"{",
"return",
"d",
"\n",
"}",
"\n",
"// apply range [-fuzz/2, fuzz/2]",
"d",
"+=",
"time",
".",
"Duration",
"(",
"rand",
... | https://github.com/coreos/go-omaha/blob/e409d983eb60842452f0fb6245137458ca45201a/omaha/client/fuzzytime.go#L31-L41 | 0.38412 | ||
coreos/go-omaha | e409d983eb60842452f0fb6245137458ca45201a | omaha/client/fuzzytime.go | go | FuzzyAfter | (d, fuzz time.Duration) | // FuzzyAfter waits for the fuzzy duration to elapse and then sends the
// current time on the returned channel. See FuzzyDuration. | FuzzyAfter waits for the fuzzy duration to elapse and then sends the
current time on the returned channel. See FuzzyDuration. | [
"FuzzyAfter",
"waits",
"for",
"the",
"fuzzy",
"duration",
"to",
"elapse",
"and",
"then",
"sends",
"the",
"current",
"time",
"on",
"the",
"returned",
"channel",
".",
"See",
"FuzzyDuration",
"."
] | func FuzzyAfter(d, fuzz time.Duration) <-chan time.Time {
return time.After(FuzzyDuration(d, fuzz))
} | [
"func",
"FuzzyAfter",
"(",
"d",
",",
"fuzz",
"time",
".",
"Duration",
")",
"<-",
"chan",
"time",
".",
"Time",
"{",
"return",
"time",
".",
"After",
"(",
"FuzzyDuration",
"(",
"d",
",",
"fuzz",
")",
")",
"\n",
"}"
] | https://github.com/coreos/go-omaha/blob/e409d983eb60842452f0fb6245137458ca45201a/omaha/client/fuzzytime.go#L45-L47 | 0.38412 | ||
coreos/go-omaha | e409d983eb60842452f0fb6245137458ca45201a | omaha/client/fuzzytime.go | go | FuzzySleep | (d, fuzz time.Duration) | // FuzzySleep pauses the current goroutine for the fuzzy duration d.
// See FuzzyDuration. | FuzzySleep pauses the current goroutine for the fuzzy duration d.
See FuzzyDuration. | [
"FuzzySleep",
"pauses",
"the",
"current",
"goroutine",
"for",
"the",
"fuzzy",
"duration",
"d",
".",
"See",
"FuzzyDuration",
"."
] | func FuzzySleep(d, fuzz time.Duration) {
time.Sleep(FuzzyDuration(d, fuzz))
} | [
"func",
"FuzzySleep",
"(",
"d",
",",
"fuzz",
"time",
".",
"Duration",
")",
"{",
"time",
".",
"Sleep",
"(",
"FuzzyDuration",
"(",
"d",
",",
"fuzz",
")",
")",
"\n",
"}"
] | https://github.com/coreos/go-omaha/blob/e409d983eb60842452f0fb6245137458ca45201a/omaha/client/fuzzytime.go#L51-L53 | 0.38412 | ||
gobs/httpclient | a93d469d8657e74a3d5a8f72bd46b54a19c341f1 | httpfile.go | go | ReadAt | (f *HttpFile) (p []byte, off int64) | // The ReaderAt interface | The ReaderAt interface | [
"The",
"ReaderAt",
"interface"
] | func (f *HttpFile) ReadAt(p []byte, off int64) (int, error) {
DebugLog(f.Debug).Println("ReadAt", off, len(p))
if f.client == nil {
return 0, os.ErrInvalid
}
plen := len(p)
if plen <= 0 {
return plen, nil
}
bytes_range := fmt.Sprintf("bytes=%d-%d", off, off+int64(plen-1))
resp, err := f.do("GET", headers{"Range": bytes_range})
defer CloseResponse(resp)
if err != nil {
DebugLog(f.Debug).Println("ReadAt error", err)
return 0, &HttpFileError{Err: err}
}
if resp.StatusCode == http.StatusRequestedRangeNotSatisfiable {
return 0, io.EOF
}
if resp.StatusCode != http.StatusPartialContent {
return 0, &HttpFileError{Err: fmt.Errorf("Unexpected Status %s", resp.Status)}
}
content_range := resp.Header.Get("Content-Range")
var first, last, total int64
n, err := fmt.Sscanf(content_range, "bytes %d-%d/%d", &first, &last, &total)
if err != nil {
DebugLog(f.Debug).Println("Error", err)
return 0, err
}
if n != 3 {
return 0, &HttpFileError{Err: fmt.Errorf("Unexpected Content-Range %q (%d)", content_range, n)}
}
DebugLog(f.Debug).Println("Range", bytes_range, "Content-Range", content_range)
n, err = io.ReadFull(resp.Body, p)
if n > 0 && err == io.EOF {
// read reached EOF, but archive/zip doesn't like this!
DebugLog(f.Debug).Println("Read", n, "reached EOF")
err = nil
}
DebugLog(f.Debug).Println("Read", n, err)
return n, err
} | [
"func",
"(",
"f",
"*",
"HttpFile",
")",
"ReadAt",
"(",
"p",
"[",
"]",
"byte",
",",
"off",
"int64",
")",
"(",
"int",
",",
"error",
")",
"{",
"DebugLog",
"(",
"f",
".",
"Debug",
")",
".",
"Println",
"(",
"\"",
"\"",
",",
"off",
",",
"len",
"(",... | https://github.com/gobs/httpclient/blob/a93d469d8657e74a3d5a8f72bd46b54a19c341f1/httpfile.go#L78-L128 | 0.380076 | ||
Songmu/strrand | 5195340ba52ce1bb6918091f054e4c8fdc645c41 | strrand.go | go | pick | (p chrPicker) () | [] | func (p chrPicker) pick() string {
if len(p) < 1 {
return ""
}
idx := rand.Intn(len(p))
return p[idx]
} | [
"func",
"(",
"p",
"chrPicker",
")",
"pick",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"p",
")",
"<",
"1",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"idx",
":=",
"rand",
".",
"Intn",
"(",
"len",
"(",
"p",
")",
")",
"\n",
"return",
"p",
"[... | https://github.com/Songmu/strrand/blob/5195340ba52ce1bb6918091f054e4c8fdc645c41/strrand.go#L37-L43 | 0.369124 | ||||
choria-io/go-validator | 4ce2ef25983faa873cc4bcea0f1ef2a4273d42cc | regex/regex.go | go | ValidateString | (input string, regex string) | // ValidateString validates that a string matches a regex | ValidateString validates that a string matches a regex | [
"ValidateString",
"validates",
"that",
"a",
"string",
"matches",
"a",
"regex"
] | func ValidateString(input string, regex string) (bool, error) {
re, err := regexp.Compile(regex)
if err != nil {
return false, fmt.Errorf("invalid regex '%s'", regex)
}
if !re.MatchString(input) {
return false, fmt.Errorf("input does not match '%s'", regex)
}
return true, nil
} | [
"func",
"ValidateString",
"(",
"input",
"string",
",",
"regex",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"re",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"regex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"f... | https://github.com/choria-io/go-validator/blob/4ce2ef25983faa873cc4bcea0f1ef2a4273d42cc/regex/regex.go#L10-L21 | 0.361851 | ||
assertgo/assert | a3e1a2d6fd7ef7614e7f3cacb8a6c341ca978024 | string.go | go | Contains | (a *String) (substring string) | [] | func (a *String) Contains(substring string) *String {
return a.isTrue(strings.Contains(a.actual, substring),
"Expected string <%s> to contain <%s>, but didn't.", a.actual, substring)
} | [
"func",
"(",
"a",
"*",
"String",
")",
"Contains",
"(",
"substring",
"string",
")",
"*",
"String",
"{",
"return",
"a",
".",
"isTrue",
"(",
"strings",
".",
"Contains",
"(",
"a",
".",
"actual",
",",
"substring",
")",
",",
"\"",
"\"",
",",
"a",
".",
... | https://github.com/assertgo/assert/blob/a3e1a2d6fd7ef7614e7f3cacb8a6c341ca978024/string.go#L44-L47 | 0.358833 | ||||
urandom/readeef | 63b79a7bde3f3da1f4b6b3224235c346a34906f0 | content/thumbnail/extract.go | go | Generate | (t ext) (a content.Article) | [] | func (t ext) Generate(a content.Article) error {
thumbnail := content.Thumbnail{ArticleID: a.ID, Processed: true}
t.log.Debugf("Generating thumbnail for article %s from extract", a)
thumbnail.Thumbnail, thumbnail.Link =
generateThumbnailFromDescription(strings.NewReader(a.Description))
if thumbnail.Link == "" {
t.log.Debugf("%s description doesn't contain suitable link, getting extract\n", a)
extract, err := extract.Get(a, t.extractRepo, t.generator, t.processors)
if err != nil {
return errors.WithMessage(err, fmt.Sprintf("getting article extract for %s", a))
}
if extract.TopImage == "" {
t.log.Debugf("Extract for %s doesn't contain a top image", a)
} else {
t.log.Debugf("Generating thumbnail from top image %s of %s\n", extract.TopImage, a)
thumbnail.Thumbnail = generateThumbnailFromImageLink(extract.TopImage)
thumbnail.Link = extract.TopImage
}
}
if err := t.repo.Update(thumbnail); err != nil {
return errors.WithMessage(err, "saving thumbnail to repo")
}
return nil
} | [
"func",
"(",
"t",
"ext",
")",
"Generate",
"(",
"a",
"content",
".",
"Article",
")",
"error",
"{",
"thumbnail",
":=",
"content",
".",
"Thumbnail",
"{",
"ArticleID",
":",
"a",
".",
"ID",
",",
"Processed",
":",
"true",
"}",
"\n\n",
"t",
".",
"log",
".... | https://github.com/urandom/readeef/blob/63b79a7bde3f3da1f4b6b3224235c346a34906f0/content/thumbnail/extract.go#L40-L70 | 0.31276 | ||||
urandom/readeef | 63b79a7bde3f3da1f4b6b3224235c346a34906f0 | content/repo/logging/extract.go | go | Update | (r extractRepo) (extract content.Extract) | [] | func (r extractRepo) Update(extract content.Extract) error {
start := time.Now()
err := r.Extract.Update(extract)
r.log.Infof("repo.Extract.Update took %s", time.Now().Sub(start))
return err
} | [
"func",
"(",
"r",
"extractRepo",
")",
"Update",
"(",
"extract",
"content",
".",
"Extract",
")",
"error",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"err",
":=",
"r",
".",
"Extract",
".",
"Update",
"(",
"extract",
")",
"\n\n",
"r",
".... | https://github.com/urandom/readeef/blob/63b79a7bde3f3da1f4b6b3224235c346a34906f0/content/repo/logging/extract.go#L27-L35 | 0.31276 | ||||
tideland/golib | b56169c6bd620eeb7cfc4b9b4027fc10d2934c84 | sml/reader.go | go | readTextNode | (mr *mlReader) () | // readTextNode reads a text node. | readTextNode reads a text node. | [
"readTextNode",
"reads",
"a",
"text",
"node",
"."
] | func (mr *mlReader) readTextNode() error {
var buf bytes.Buffer
for {
r, rc, err := mr.readRune()
switch {
case err != nil:
return err
case rc == rcEOF:
return errors.New(ErrReader, errorMessages, "unexpected end of file while reading a text node")
case rc == rcOpen || rc == rcClose:
mr.index--
mr.reader.UnreadRune()
return mr.builder.TextNode(buf.String())
case rc == rcEscape:
r, rc, err = mr.readRune()
switch {
case err != nil:
return err
case rc == rcEOF:
return errors.New(ErrReader, errorMessages, "unexpected end of file while reading a text node")
case rc == rcOpen || rc == rcClose || rc == rcEscape:
buf.WriteRune(r)
default:
msg := fmt.Sprintf("invalid character after escaping at index %d", mr.index)
return errors.New(ErrReader, errorMessages, msg)
}
default:
buf.WriteRune(r)
}
}
} | [
"func",
"(",
"mr",
"*",
"mlReader",
")",
"readTextNode",
"(",
")",
"error",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"{",
"r",
",",
"rc",
",",
"err",
":=",
"mr",
".",
"readRune",
"(",
")",
"\n",
"switch",
"{",
"case",
"err",
"!=",
... | https://github.com/tideland/golib/blob/b56169c6bd620eeb7cfc4b9b4027fc10d2934c84/sml/reader.go#L230-L260 | 0.289797 | ||
iikira/baidu-tools | 79c93d8033cdda61dd2278f0e4a75c5ea8388f3c | tieba/tiebautil/client_signature.go | go | StringReverse | (s string) | // StringReverse 翻转字符串 | StringReverse 翻转字符串 | [
"StringReverse",
"翻转字符串"
] | func StringReverse(s string) string {
runes := []rune(s)
for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {
runes[from], runes[to] = runes[to], runes[from]
}
return string(runes)
} | [
"func",
"StringReverse",
"(",
"s",
"string",
")",
"string",
"{",
"runes",
":=",
"[",
"]",
"rune",
"(",
"s",
")",
"\n",
"for",
"from",
",",
"to",
":=",
"0",
",",
"len",
"(",
"runes",
")",
"-",
"1",
";",
"from",
"<",
"to",
";",
"from",
",",
"to... | https://github.com/iikira/baidu-tools/blob/79c93d8033cdda61dd2278f0e4a75c5ea8388f3c/tieba/tiebautil/client_signature.go#L67-L73 | 0.289784 | ||
wildducktheories/go-csv | a843eda7bf0911b9acdfd11a9a41ed87282dcbdd | cmd/csv-to-json/main.go | go | configure | (args []string) | [] | func configure(args []string) (*csv.CsvToJsonProcess, error) {
var baseObject string
var stringsOnly bool
flags := flag.NewFlagSet("csv-to-json", flag.ExitOnError)
flags.BoolVar(&stringsOnly, "strings", false, "Don't attempt to convert strings to other JSON types.")
flags.StringVar(&baseObject, "base-object-key", "", "Write the other columns into the base JSON object found in the specified column.")
if err := flags.Parse(args); err != nil {
return nil, err
}
return &csv.CsvToJsonProcess{
BaseObject: baseObject,
StringsOnly: stringsOnly,
}, nil
} | [
"func",
"configure",
"(",
"args",
"[",
"]",
"string",
")",
"(",
"*",
"csv",
".",
"CsvToJsonProcess",
",",
"error",
")",
"{",
"var",
"baseObject",
"string",
"\n",
"var",
"stringsOnly",
"bool",
"\n",
"flags",
":=",
"flag",
".",
"NewFlagSet",
"(",
"\"",
"... | https://github.com/wildducktheories/go-csv/blob/a843eda7bf0911b9acdfd11a9a41ed87282dcbdd/cmd/csv-to-json/main.go#L12-L26 | 0.288163 | ||||
badgerodon/penv | 7a4c6d64fa119b52afe2eb3f0801886bd8785318 | penv.go | go | uniquei | (arr []string) | [] | func uniquei(arr []string) []string {
u := make([]string, 0, len(arr))
h := map[string]struct{}{}
for _, str := range arr {
stri := strings.ToLower(str)
if _, ok := h[stri]; ok {
continue
}
h[stri] = struct{}{}
u = append(u, str)
}
return u
} | [
"func",
"uniquei",
"(",
"arr",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"u",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"arr",
")",
")",
"\n",
"h",
":=",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
"{",
"}... | https://github.com/badgerodon/penv/blob/7a4c6d64fa119b52afe2eb3f0801886bd8785318/penv.go#L23-L35 | 0.283525 | ||||
mc2soft/pq-types | ada769d4011a027a5385b9c4e47976fe327350a6 | int32_array.go | go | EqualWithoutOrder | (a Int32Array) (b Int32Array) | // EqualWithoutOrder returns true if two int32 arrays are equal without order, false otherwise.
// It may sort both arrays in-place to do so. | EqualWithoutOrder returns true if two int32 arrays are equal without order, false otherwise.
It may sort both arrays in-place to do so. | [
"EqualWithoutOrder",
"returns",
"true",
"if",
"two",
"int32",
"arrays",
"are",
"equal",
"without",
"order",
"false",
"otherwise",
".",
"It",
"may",
"sort",
"both",
"arrays",
"in",
"-",
"place",
"to",
"do",
"so",
"."
] | func (a Int32Array) EqualWithoutOrder(b Int32Array) bool {
if len(a) != len(b) {
return false
}
sort.Sort(a)
sort.Sort(b)
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
} | [
"func",
"(",
"a",
"Int32Array",
")",
"EqualWithoutOrder",
"(",
"b",
"Int32Array",
")",
"bool",
"{",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"sort",
".",
"Sort",
"(",
"a",
")",
"\n",
"sort... | https://github.com/mc2soft/pq-types/blob/ada769d4011a027a5385b9c4e47976fe327350a6/int32_array.go#L77-L92 | 0.282115 | ||
foolin/gocsv | d1cfc1a54940e0b038e7f221a362c8c51eacd2c9 | tools/mergecsv/mergecsv.go | go | main | () | [] | func main() {
//abs, err := filepath.Abs("./../")
//log.Printf(filepath.Base(abs))
flag.Parse()
if *csvpath == "" {
flag.Usage()
return
}
fileInfo, err := os.Stat(*csvpath)
if err != nil {
log.Panic(err)
return
}
isOutOneFile := false
if *outpath != "" && strings.ToLower(filepath.Ext(*outpath)) == ".json" {
isOutOneFile = true
}
if *outpath == "" {
*outpath = *csvpath
}
mapAllList := make(map[string]string, 0)
if fileInfo.IsDir() {
infos, err := ioutil.ReadDir(*csvpath)
if err != nil {
log.Panic(err)
return
}
if *outpath == "" {
*outpath = *csvpath
}
for _, info := range infos {
ext := filepath.Ext(info.Name())
if ext != ".csv" {
continue
}
name := filename(info.Name());
byteContent, err := readFile(path.Join(*csvpath, info.Name()), *gbk)
if err != nil {
log.Fatalf("read csv: %v, error: %v", info.Name(), err)
return
}
if isOutOneFile {
mapAllList[name] = string(byteContent)
} else {
mapOneList := map[string]string{
name : string(byteContent),
}
jsonfile := strings.Replace(info.Name(), ".csv", ".json", -1)
outFile := path.Join(*outpath, jsonfile)
err = writeJsonFile(outFile, mapOneList)
if err != nil {
log.Fatalf("write file: %v error: %v", outFile, err)
return
}
log.Printf("write file: %v", outFile)
}
}
} else {
name := upper(filename(fileInfo.Name()));
byteContent, err := readFile(path.Join(*csvpath, fileInfo.Name()), true)
if err != nil {
log.Fatalf("read csv error: %v", err)
return
}
if isOutOneFile {
mapAllList[name] = string(byteContent)
} else {
mapOneList := map[string]string{
name : string(byteContent),
}
jsonfile := strings.Replace(fileInfo.Name(), ".csv", ".json", -1)
outFile := path.Join(*outpath, jsonfile)
err = writeJsonFile(outFile, mapOneList)
if err != nil {
log.Fatalf("write file: %v error: %v", outFile, err)
return
}
log.Printf("write file: %v", outFile)
}
}
if isOutOneFile {
outFile := *outpath
err = writeJsonFile(outFile, mapAllList)
if err != nil {
log.Fatalf("write file: %v error: %v", outFile, err)
return
}
log.Printf("write file: %v", outFile)
}
log.Print("generator done!")
} | [
"func",
"main",
"(",
")",
"{",
"//abs, err := filepath.Abs(\"./../\")",
"//log.Printf(filepath.Base(abs))",
"flag",
".",
"Parse",
"(",
")",
"\n",
"if",
"*",
"csvpath",
"==",
"\"",
"\"",
"{",
"flag",
".",
"Usage",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
... | https://github.com/foolin/gocsv/blob/d1cfc1a54940e0b038e7f221a362c8c51eacd2c9/tools/mergecsv/mergecsv.go#L21-L117 | 0.281454 | ||||
otiai10/marmoset | 2adcf18928cbc73d640249eed0ac8e49ce4bdcb8 | render.go | go | JSON | (r Renderer) (status int, data interface{}) | // JSON ... | JSON ... | [
"JSON",
"..."
] | func (r Renderer) JSON(status int, data interface{}) error {
r.writer.WriteHeader(status)
r.writer.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(r.writer)
if r.Pretty {
enc.SetIndent("", "\t")
}
enc.SetEscapeHTML(r.EscapeHTML)
err := enc.Encode(data)
return err
} | [
"func",
"(",
"r",
"Renderer",
")",
"JSON",
"(",
"status",
"int",
",",
"data",
"interface",
"{",
"}",
")",
"error",
"{",
"r",
".",
"writer",
".",
"WriteHeader",
"(",
"status",
")",
"\n",
"r",
".",
"writer",
".",
"Header",
"(",
")",
".",
"Set",
"("... | https://github.com/otiai10/marmoset/blob/2adcf18928cbc73d640249eed0ac8e49ce4bdcb8/render.go#L27-L40 | 0.280111 | ||
thecodeteam/gorackhd | 66bd88ab29593b880ba59b35db2c17a4b4bab1f1 | client/nodes/nodes_client.go | go | GetNodes | (a *Client) (params *GetNodesParams, authInfo runtime.ClientAuthInfoWriter) | /*
GetNodes lists of all nodes or if there are none an empty object
List of all nodes or if there are none an empty object
*/ | /*
GetNodes lists of all nodes or if there are none an empty object | [
"/",
"*",
"GetNodes",
"lists",
"of",
"all",
"nodes",
"or",
"if",
"there",
"are",
"none",
"an",
"empty",
"object"
] | func (a *Client) GetNodes(params *GetNodesParams, authInfo runtime.ClientAuthInfoWriter) (*GetNodesOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewGetNodesParams()
}
result, err := a.transport.Submit(&runtime.ClientOperation{
ID: "GetNodes",
Method: "GET",
PathPattern: "/nodes",
ProducesMediaTypes: []string{"application/json", "application/x-gzip"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http", "https"},
Params: params,
Reader: &GetNodesReader{formats: a.formats},
AuthInfo: authInfo,
})
if err != nil {
return nil, err
}
return result.(*GetNodesOK), nil
} | [
"func",
"(",
"a",
"*",
"Client",
")",
"GetNodes",
"(",
"params",
"*",
"GetNodesParams",
",",
"authInfo",
"runtime",
".",
"ClientAuthInfoWriter",
")",
"(",
"*",
"GetNodesOK",
",",
"error",
")",
"{",
"// TODO: Validate the params before sending",
"if",
"params",
"... | https://github.com/thecodeteam/gorackhd/blob/66bd88ab29593b880ba59b35db2c17a4b4bab1f1/client/nodes/nodes_client.go#L147-L168 | 0.270742 | ||
ghetzel/diecast | 3cf4315555ad6d1e50e51ddf7778eedb91da56ca | util.go | go | xsvToArray | (data []byte, delim rune) | [] | func xsvToArray(data []byte, delim rune) (map[string]interface{}, error) {
recs := make([][]interface{}, 0)
out := map[string]interface{}{
`headers`: make([]string, 0),
`records`: recs,
}
reader := csv.NewReader(bytes.NewBuffer(data))
reader.Comma = delim
if records, err := reader.ReadAll(); err == nil {
for i, row := range records {
if i == 0 {
out[`headers`] = row
} else {
outrec := make([]interface{}, len(row))
for j, col := range row {
outrec[j] = typeutil.Auto(col)
}
if len(outrec) > 0 {
recs = append(recs, outrec)
}
}
}
out[`records`] = recs
return out, nil
} else {
return nil, err
}
} | [
"func",
"xsvToArray",
"(",
"data",
"[",
"]",
"byte",
",",
"delim",
"rune",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"recs",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"interface",
"{",
"}",
",",
"0",
")",
... | https://github.com/ghetzel/diecast/blob/3cf4315555ad6d1e50e51ddf7778eedb91da56ca/util.go#L122-L156 | 0.269499 | ||||
shutterstock/go-stockutil | 39a961cfa60878cca33570f9431c09db1600e4db | stringutil/stringutil.go | go | ConvertToString | (in string) | [] | func ConvertToString(in string) (string, error) {
if v, err := ConvertTo(String, in); err == nil {
return v.(string), nil
}else{
return ``, err
}
} | [
"func",
"ConvertToString",
"(",
"in",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"v",
",",
"err",
":=",
"ConvertTo",
"(",
"String",
",",
"in",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"v",
".",
"(",
"string",
")",
",",
"nil",... | https://github.com/shutterstock/go-stockutil/blob/39a961cfa60878cca33570f9431c09db1600e4db/stringutil/stringutil.go#L203-L209 | 0.266383 | ||||
cupcake/gokiq | ebbb02812f6826798d779fbda06921d45b2c4446 | worker.go | go | String | (q QueueConfig) () | [] | func (q QueueConfig) String() string {
str := ""
for queue, priority := range q {
str += fmt.Sprintf("%s=%d,", queue, priority)
}
return str[:len(str)-1]
} | [
"func",
"(",
"q",
"QueueConfig",
")",
"String",
"(",
")",
"string",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"for",
"queue",
",",
"priority",
":=",
"range",
"q",
"{",
"str",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"queue",
",",
"priority",
... | https://github.com/cupcake/gokiq/blob/ebbb02812f6826798d779fbda06921d45b2c4446/worker.go#L79-L85 | 0.261942 | ||||
karlseguin/expect | ecc6aa3406d03d381160d52b8a76268abdb14321 | runner.go | go | Summary | (r *result) () | [] | func (r *result) Summary() {
info := fmt.Sprintf(" %s.%-40s", r.typeName, r.method)
if r.skip {
color.Println(" @y⸚", info)
} else if r.Passed() {
color.Println(" @g✓", info)
} else {
color.Print(" @r×", info)
color.Printf("%2d\n", len(r.failures))
}
} | [
"func",
"(",
"r",
"*",
"result",
")",
"Summary",
"(",
")",
"{",
"info",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"r",
".",
"typeName",
",",
"r",
".",
"method",
")",
"\n",
"if",
"r",
".",
"skip",
"{",
"color",
".",
"Println",
"(",
"\... | https://github.com/karlseguin/expect/blob/ecc6aa3406d03d381160d52b8a76268abdb14321/runner.go#L275-L285 | 0.25891 | ||||
antongulenko/golib | 5860401d795186159946857d3d6057628e049840 | sort.go | go | Items | (r RankedSlice) () | [] | func (r RankedSlice) Items() []interface{} {
result := make([]interface{}, len(r))
for i, item := range r {
result[i] = item.Item
}
return result
} | [
"func",
"(",
"r",
"RankedSlice",
")",
"Items",
"(",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"result",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"r",
")",
")",
"\n",
"for",
"i",
",",
"item",
":=",
"range",
"r",
"{... | https://github.com/antongulenko/golib/blob/5860401d795186159946857d3d6057628e049840/sort.go#L36-L42 | 0.231372 | ||||
layer-x/layerx-commons | a9e7080c940208a2a089fd854ecf4831b3b3f78c | lxhttpclient/httpclient.go | go | postJson | (url string, path string, headers map[string]string, jsonStruct interface{}) | [] | func postJson(url string, path string, headers map[string]string, jsonStruct interface{}) (*http.Response, []byte, error) {
//err has already been caught
data, _ := json.Marshal(jsonStruct)
return postData(url, path, headers, data)
} | [
"func",
"postJson",
"(",
"url",
"string",
",",
"path",
"string",
",",
"headers",
"map",
"[",
"string",
"]",
"string",
",",
"jsonStruct",
"interface",
"{",
"}",
")",
"(",
"*",
"http",
".",
"Response",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"... | https://github.com/layer-x/layerx-commons/blob/a9e7080c940208a2a089fd854ecf4831b3b3f78c/lxhttpclient/httpclient.go#L268-L272 | 0.213029 | ||||
webx-top/com | 01419a9b4188b43cba46b7ae02136d01e4fccf9c | time.go | go | DateFormat | (format string, timestamp interface{}) | //DateFormat 将时间戳格式化为日期字符窜 | DateFormat 将时间戳格式化为日期字符窜 | [
"DateFormat",
"将时间戳格式化为日期字符窜"
] | func DateFormat(format string, timestamp interface{}) (t string) { // timestamp
switch format {
case "Y-m-d H:i:s", "":
format = "2006-01-02 15:04:05"
case "Y-m-d H:i":
format = "2006-01-02 15:04"
case "y-m-d H:i":
format = "06-01-02 15:04"
case "m-d H:i":
format = "01-02 15:04"
case "Y-m-d":
format = "2006-01-02"
case "y-m-d":
format = "06-01-02"
case "m-d":
format = "01-02"
default:
format = ConvDateFormat(format)
}
sd := Int64(timestamp)
t = time.Unix(sd, 0).Format(format)
return
} | [
"func",
"DateFormat",
"(",
"format",
"string",
",",
"timestamp",
"interface",
"{",
"}",
")",
"(",
"t",
"string",
")",
"{",
"// timestamp",
"switch",
"format",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"format",
"=",
"\"",
"\"",
"\n",
"case",
"\"... | https://github.com/webx-top/com/blob/01419a9b4188b43cba46b7ae02136d01e4fccf9c/time.go#L116-L138 | 0.213029 | ||
webx-top/com | 01419a9b4188b43cba46b7ae02136d01e4fccf9c | convert.go | go | Int2HexStr | (num int) | // Int2HexStr converts decimal number to hex format string. | Int2HexStr converts decimal number to hex format string. | [
"Int2HexStr",
"converts",
"decimal",
"number",
"to",
"hex",
"format",
"string",
"."
] | func Int2HexStr(num int) (hex string) {
if num == 0 {
return "0"
}
for num > 0 {
r := num % 16
c := "?"
if r >= 0 && r <= 9 {
c = string(r + '0')
} else {
c = string(r + 'a' - 10)
}
hex = c + hex
num = num / 16
}
return hex
} | [
"func",
"Int2HexStr",
"(",
"num",
"int",
")",
"(",
"hex",
"string",
")",
"{",
"if",
"num",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"for",
"num",
">",
"0",
"{",
"r",
":=",
"num",
"%",
"16",
"\n",
"c",
":=",
"\"",
"\"",
"\n",
"... | https://github.com/webx-top/com/blob/01419a9b4188b43cba46b7ae02136d01e4fccf9c/convert.go#L189-L205 | 0.213029 | ||
vaughan0/go-zmq | 425c333a2ab9e2615ff4ff7deced6e37730b544e | sockopts.go | go | SetRecvTimeout | (s *Socket) (timeo time.Duration) | [] | func (s *Socket) SetRecvTimeout(timeo time.Duration) {
s.setInt(C.ZMQ_RCVTIMEO, int(fromDuration(timeo, time.Millisecond)))
} | [
"func",
"(",
"s",
"*",
"Socket",
")",
"SetRecvTimeout",
"(",
"timeo",
"time",
".",
"Duration",
")",
"{",
"s",
".",
"setInt",
"(",
"C",
".",
"ZMQ_RCVTIMEO",
",",
"int",
"(",
"fromDuration",
"(",
"timeo",
",",
"time",
".",
"Millisecond",
")",
")",
")",... | https://github.com/vaughan0/go-zmq/blob/425c333a2ab9e2615ff4ff7deced6e37730b544e/sockopts.go#L112-L114 | 0.190173 | ||||
mkb218/gosndfile | e0c9ef895ee23c154b6fe25b5261daf514df9941 | sndfile/virtual.go | go | gsfWrite | (ptr unsafe.Pointer, i int64, user_data unsafe.Pointer) | //export gsfWrite | export gsfWrite | [
"export",
"gsfWrite"
] | func gsfWrite(ptr unsafe.Pointer, i int64, user_data unsafe.Pointer) int64 {
l := (*virtualIo)(user_data)
b := (*[1 << 30]byte)(ptr)[0:i]
return l.v.Write(b, l.v.UserData)
} | [
"func",
"gsfWrite",
"(",
"ptr",
"unsafe",
".",
"Pointer",
",",
"i",
"int64",
",",
"user_data",
"unsafe",
".",
"Pointer",
")",
"int64",
"{",
"l",
":=",
"(",
"*",
"virtualIo",
")",
"(",
"user_data",
")",
"\n",
"b",
":=",
"(",
"*",
"[",
"1",
"<<",
"... | https://github.com/mkb218/gosndfile/blob/e0c9ef895ee23c154b6fe25b5261daf514df9941/sndfile/virtual.go#L83-L87 | 0.181127 | ||
cuigh/auxo | 35f08384a278c4f5c01bf96896e5964611e4a05d | util/cast/try.go | go | TryToBool | (i interface{}) | // TryToBool casts an empty interface to a bool. | TryToBool casts an empty interface to a bool. | [
"TryToBool",
"casts",
"an",
"empty",
"interface",
"to",
"a",
"bool",
"."
] | func TryToBool(i interface{}) (b bool, err error) {
switch v := i.(type) {
case nil:
case bool:
b = v
case *bool:
b = *v
case string:
b, err = strconv.ParseBool(v)
case *string:
b, err = strconv.ParseBool(*v)
case int, int8, int16, int32, int64:
b = v != 0
default:
err = castError(i, "bool")
}
return
} | [
"func",
"TryToBool",
"(",
"i",
"interface",
"{",
"}",
")",
"(",
"b",
"bool",
",",
"err",
"error",
")",
"{",
"switch",
"v",
":=",
"i",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"case",
"bool",
":",
"b",
"=",
"v",
"\n",
"case",
"*",
"bool... | https://github.com/cuigh/auxo/blob/35f08384a278c4f5c01bf96896e5964611e4a05d/util/cast/try.go#L10-L27 | 0.179298 | ||
cuigh/auxo | 35f08384a278c4f5c01bf96896e5964611e4a05d | db/gsd/select.go | go | GroupBy | (c *countContext) (cols *Columns) | [] | func (c *countContext) GroupBy(cols *Columns) CountGroupByClause {
(*selectContext)(c).GroupBy(cols)
return c
} | [
"func",
"(",
"c",
"*",
"countContext",
")",
"GroupBy",
"(",
"cols",
"*",
"Columns",
")",
"CountGroupByClause",
"{",
"(",
"*",
"selectContext",
")",
"(",
"c",
")",
".",
"GroupBy",
"(",
"cols",
")",
"\n",
"return",
"c",
"\n",
"}"
] | https://github.com/cuigh/auxo/blob/35f08384a278c4f5c01bf96896e5964611e4a05d/db/gsd/select.go#L306-L309 | 0.179298 | ||||
dmiller/go-seq | 7e6f351b75cf7a8534be0b93dd1929ea5f08d86a | stm/ref.go | go | currentVal | (r *Ref) () | [] | func (r *Ref) currentVal() interface{} {
r.enterReadLock()
defer r.exitReadLock()
if r.tvals == nil {
panic(fmt.Errorf("%v is unbound", r))
}
return r.tvals.val
} | [
"func",
"(",
"r",
"*",
"Ref",
")",
"currentVal",
"(",
")",
"interface",
"{",
"}",
"{",
"r",
".",
"enterReadLock",
"(",
")",
"\n",
"defer",
"r",
".",
"exitReadLock",
"(",
")",
"\n",
"if",
"r",
".",
"tvals",
"==",
"nil",
"{",
"panic",
"(",
"fmt",
... | https://github.com/dmiller/go-seq/blob/7e6f351b75cf7a8534be0b93dd1929ea5f08d86a/stm/ref.go#L99-L106 | 0.177827 | ||||
darkhelmet/tinderizer | f46418cc7edd6695140867d40446645c428cbda2 | job/job.go | go | HTML | (j *Job) () | [] | func (j *Job) HTML() template.HTML {
var buffer bytes.Buffer
html.Render(&buffer, j.Doc)
return template.HTML(buffer.String())
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"HTML",
"(",
")",
"template",
".",
"HTML",
"{",
"var",
"buffer",
"bytes",
".",
"Buffer",
"\n",
"html",
".",
"Render",
"(",
"&",
"buffer",
",",
"j",
".",
"Doc",
")",
"\n",
"return",
"template",
".",
"HTML",
"(",
... | https://github.com/darkhelmet/tinderizer/blob/f46418cc7edd6695140867d40446645c428cbda2/job/job.go#L106-L110 | 0.166382 | ||||
webx-top/webx | 800783e939f407b66b20848589b41d2bb1aeb024 | lib/forms/fields/options.go | go | Checkbox | (name string, checked bool) | // Checkbox creates a default checkbox field with the provided name. It also makes it checked by default based
// on the checked parameter. | Checkbox creates a default checkbox field with the provided name. It also makes it checked by default based
on the checked parameter. | [
"Checkbox",
"creates",
"a",
"default",
"checkbox",
"field",
"with",
"the",
"provided",
"name",
".",
"It",
"also",
"makes",
"it",
"checked",
"by",
"default",
"based",
"on",
"the",
"checked",
"parameter",
"."
] | func Checkbox(name string, checked bool) *Field {
ret := FieldWithType(name, formcommon.CHECKBOX)
if checked {
ret.AddTag("checked")
}
return ret
} | [
"func",
"Checkbox",
"(",
"name",
"string",
",",
"checked",
"bool",
")",
"*",
"Field",
"{",
"ret",
":=",
"FieldWithType",
"(",
"name",
",",
"formcommon",
".",
"CHECKBOX",
")",
"\n",
"if",
"checked",
"{",
"ret",
".",
"AddTag",
"(",
"\"",
"\"",
")",
"\n... | https://github.com/webx-top/webx/blob/800783e939f407b66b20848589b41d2bb1aeb024/lib/forms/fields/options.go#L183-L189 | 0.157265 | ||
ghetzel/go-webfriend | 0746aa14b9afa6b488313705edf19a33d9dff469 | browser/tab.go | go | getElementFromResult | (self *Tab) (node *maputil.Map) | [] | func (self *Tab) getElementFromResult(node *maputil.Map) *dom.Element {
if remoteObjectId, err := self.resolveNode(node.Int(`backendNodeId`)); err == nil {
var element *dom.Element
var children = node.Slice(`children`)
// load the various properties from the given node map into a new elements
pair := node.String(`localName`, strings.ToLower(node.String(`nodeName`)))
ns, name := stringutil.SplitPairRightTrailing(pair, `:`)
element = &dom.Element{
ID: remoteObjectId,
Namespace: ns,
Name: name,
Attributes: make(map[string]interface{}),
}
for _, pair := range sliceutil.Chunks(node.Slice(`attributes`), 2) {
element.Attributes[typeutil.String(pair[0])] = typeutil.Auto(pair[1])
}
switch len(children) {
case 0:
element.Text = node.String(`nodeValue`)
default:
for _, child := range children {
childM := maputil.M(child)
switch childM.Int(`nodeType`) {
case 1:
if subel := self.getElementFromResult(childM); subel != nil {
element.Text += subel.Text
}
case 3:
element.Text += childM.String(`nodeValue`)
}
}
}
return element
} else {
log.Warningf("Received invalid node: %v", err)
return nil
}
} | [
"func",
"(",
"self",
"*",
"Tab",
")",
"getElementFromResult",
"(",
"node",
"*",
"maputil",
".",
"Map",
")",
"*",
"dom",
".",
"Element",
"{",
"if",
"remoteObjectId",
",",
"err",
":=",
"self",
".",
"resolveNode",
"(",
"node",
".",
"Int",
"(",
"`backendNo... | https://github.com/ghetzel/go-webfriend/blob/0746aa14b9afa6b488313705edf19a33d9dff469/browser/tab.go#L945-L988 | 0.149915 | ||||
jdxcode/gode | 46ec1874bc6dce6e90fb1583a6d5110f7bc40ae1 | zip.go | go | extractZip | (zipfile, root string) | [] | func extractZip(zipfile, root string) error {
archive, err := zip.OpenReader(zipfile)
if err != nil {
return err
}
defer archive.Close()
for _, f := range archive.File {
path := filepath.Join(root, f.Name)
switch {
case f.FileInfo().IsDir():
if err := os.Mkdir(path, f.Mode()); err != nil {
return err
}
default:
extractZipFile(path, f)
}
}
return nil
} | [
"func",
"extractZip",
"(",
"zipfile",
",",
"root",
"string",
")",
"error",
"{",
"archive",
",",
"err",
":=",
"zip",
".",
"OpenReader",
"(",
"zipfile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"archive",
"."... | https://github.com/jdxcode/gode/blob/46ec1874bc6dce6e90fb1583a6d5110f7bc40ae1/zip.go#L10-L28 | 0.085299 | ||||
pivotal-pez/pezauth | 7c01f70760da2124e6fac36b569d9130552afea8 | integrations/inventory.go | go | getDaysRemainingFromEndDate | (endDate string) | [] | func getDaysRemainingFromEndDate(endDate string) int {
// 2015-09-15 04:42:39.390008575 +0000 UTC
//t, err := time.Parse("2006-01-02", endDate)
t, err := time.Parse("2006-01-02 15:04:05.000000000 +0000 UTC", endDate)
if err != nil {
log.Println(err)
return 0
}
now := time.Now()
return diffDays(t, now)
} | [
"func",
"getDaysRemainingFromEndDate",
"(",
"endDate",
"string",
")",
"int",
"{",
"// 2015-09-15 04:42:39.390008575 +0000 UTC",
"//t, err := time.Parse(\"2006-01-02\", endDate)",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"\"",
"\"",
",",
"endDate",
")",
"\n",
... | https://github.com/pivotal-pez/pezauth/blob/7c01f70760da2124e6fac36b569d9130552afea8/integrations/inventory.go#L146-L156 | 0 | ||||
qorio/maestro | b3594982be16e2aeff0215d8d4a4d03fd563bdfb | pkg/yaml/yaml.go | go | bind_vars | (this *MaestroDoc) (c Context) | [] | func (this *MaestroDoc) bind_vars(c Context) {
for _, disk := range this.Disks {
c.bind_vars(disk)
}
for _, instance := range this.Instances {
c.bind_vars(instance)
}
for _, artifact := range this.Artifacts {
c.bind_vars(artifact)
}
for _, image := range this.Images {
c.bind_vars(image)
}
for _, container := range this.Containers {
c.bind_vars(container)
}
for _, job := range this.Jobs {
c.bind_vars(job)
}
for _, service := range this.services {
c.bind_vars(service)
}
} | [
"func",
"(",
"this",
"*",
"MaestroDoc",
")",
"bind_vars",
"(",
"c",
"Context",
")",
"{",
"for",
"_",
",",
"disk",
":=",
"range",
"this",
".",
"Disks",
"{",
"c",
".",
"bind_vars",
"(",
"disk",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"instance",
":=... | https://github.com/qorio/maestro/blob/b3594982be16e2aeff0215d8d4a4d03fd563bdfb/pkg/yaml/yaml.go#L563-L585 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.