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 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
dave/jennifer | jen/file.go | NewFilePathName | func NewFilePathName(packagePath, packageName string) *File {
return &File{
Group: &Group{
multi: true,
},
name: packageName,
path: packagePath,
imports: map[string]importdef{},
hints: map[string]importdef{},
}
} | go | func NewFilePathName(packagePath, packageName string) *File {
return &File{
Group: &Group{
multi: true,
},
name: packageName,
path: packagePath,
imports: map[string]importdef{},
hints: map[string]importdef{},
}
} | [
"func",
"NewFilePathName",
"(",
"packagePath",
",",
"packageName",
"string",
")",
"*",
"File",
"{",
"return",
"&",
"File",
"{",
"Group",
":",
"&",
"Group",
"{",
"multi",
":",
"true",
",",
"}",
",",
"name",
":",
"packageName",
",",
"path",
":",
"package... | // NewFilePathName creates a new file with the specified package path and name. | [
"NewFilePathName",
"creates",
"a",
"new",
"file",
"with",
"the",
"specified",
"package",
"path",
"and",
"name",
"."
] | 14e399b6b5e8456c66c45c955fc27b568bacb5c9 | https://github.com/dave/jennifer/blob/14e399b6b5e8456c66c45c955fc27b568bacb5c9/jen/file.go#L37-L47 | train |
dave/jennifer | jen/file.go | HeaderComment | func (f *File) HeaderComment(comment string) {
f.headers = append(f.headers, comment)
} | go | func (f *File) HeaderComment(comment string) {
f.headers = append(f.headers, comment)
} | [
"func",
"(",
"f",
"*",
"File",
")",
"HeaderComment",
"(",
"comment",
"string",
")",
"{",
"f",
".",
"headers",
"=",
"append",
"(",
"f",
".",
"headers",
",",
"comment",
")",
"\n",
"}"
] | // HeaderComment adds a comment to the top of the file, above any package
// comments. A blank line is rendered below the header comments, ensuring
// header comments are not included in the package doc. | [
"HeaderComment",
"adds",
"a",
"comment",
"to",
"the",
"top",
"of",
"the",
"file",
"above",
"any",
"package",
"comments",
".",
"A",
"blank",
"line",
"is",
"rendered",
"below",
"the",
"header",
"comments",
"ensuring",
"header",
"comments",
"are",
"not",
"inclu... | 14e399b6b5e8456c66c45c955fc27b568bacb5c9 | https://github.com/dave/jennifer/blob/14e399b6b5e8456c66c45c955fc27b568bacb5c9/jen/file.go#L79-L81 | train |
dave/jennifer | jen/file.go | PackageComment | func (f *File) PackageComment(comment string) {
f.comments = append(f.comments, comment)
} | go | func (f *File) PackageComment(comment string) {
f.comments = append(f.comments, comment)
} | [
"func",
"(",
"f",
"*",
"File",
")",
"PackageComment",
"(",
"comment",
"string",
")",
"{",
"f",
".",
"comments",
"=",
"append",
"(",
"f",
".",
"comments",
",",
"comment",
")",
"\n",
"}"
] | // PackageComment adds a comment to the top of the file, above the package
// keyword. | [
"PackageComment",
"adds",
"a",
"comment",
"to",
"the",
"top",
"of",
"the",
"file",
"above",
"the",
"package",
"keyword",
"."
] | 14e399b6b5e8456c66c45c955fc27b568bacb5c9 | https://github.com/dave/jennifer/blob/14e399b6b5e8456c66c45c955fc27b568bacb5c9/jen/file.go#L85-L87 | train |
dave/jennifer | jen/file.go | CgoPreamble | func (f *File) CgoPreamble(comment string) {
f.cgoPreamble = append(f.cgoPreamble, comment)
} | go | func (f *File) CgoPreamble(comment string) {
f.cgoPreamble = append(f.cgoPreamble, comment)
} | [
"func",
"(",
"f",
"*",
"File",
")",
"CgoPreamble",
"(",
"comment",
"string",
")",
"{",
"f",
".",
"cgoPreamble",
"=",
"append",
"(",
"f",
".",
"cgoPreamble",
",",
"comment",
")",
"\n",
"}"
] | // CgoPreamble adds a cgo preamble comment that is rendered directly before the "C" pseudo-package
// import. | [
"CgoPreamble",
"adds",
"a",
"cgo",
"preamble",
"comment",
"that",
"is",
"rendered",
"directly",
"before",
"the",
"C",
"pseudo",
"-",
"package",
"import",
"."
] | 14e399b6b5e8456c66c45c955fc27b568bacb5c9 | https://github.com/dave/jennifer/blob/14e399b6b5e8456c66c45c955fc27b568bacb5c9/jen/file.go#L91-L93 | train |
dave/jennifer | jen/file.go | Anon | func (f *File) Anon(paths ...string) {
for _, p := range paths {
f.imports[p] = importdef{name: "_", alias: true}
}
} | go | func (f *File) Anon(paths ...string) {
for _, p := range paths {
f.imports[p] = importdef{name: "_", alias: true}
}
} | [
"func",
"(",
"f",
"*",
"File",
")",
"Anon",
"(",
"paths",
"...",
"string",
")",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"paths",
"{",
"f",
".",
"imports",
"[",
"p",
"]",
"=",
"importdef",
"{",
"name",
":",
"\"",
"\"",
",",
"alias",
":",
"tr... | // Anon adds an anonymous import. | [
"Anon",
"adds",
"an",
"anonymous",
"import",
"."
] | 14e399b6b5e8456c66c45c955fc27b568bacb5c9 | https://github.com/dave/jennifer/blob/14e399b6b5e8456c66c45c955fc27b568bacb5c9/jen/file.go#L96-L100 | train |
dave/jennifer | jen/file.go | ImportName | func (f *File) ImportName(path, name string) {
f.hints[path] = importdef{name: name, alias: false}
} | go | func (f *File) ImportName(path, name string) {
f.hints[path] = importdef{name: name, alias: false}
} | [
"func",
"(",
"f",
"*",
"File",
")",
"ImportName",
"(",
"path",
",",
"name",
"string",
")",
"{",
"f",
".",
"hints",
"[",
"path",
"]",
"=",
"importdef",
"{",
"name",
":",
"name",
",",
"alias",
":",
"false",
"}",
"\n",
"}"
] | // ImportName provides the package name for a path. If specified, the alias will be omitted from the
// import block. This is optional. If not specified, a sensible package name is used based on the path
// and this is added as an alias in the import block. | [
"ImportName",
"provides",
"the",
"package",
"name",
"for",
"a",
"path",
".",
"If",
"specified",
"the",
"alias",
"will",
"be",
"omitted",
"from",
"the",
"import",
"block",
".",
"This",
"is",
"optional",
".",
"If",
"not",
"specified",
"a",
"sensible",
"packa... | 14e399b6b5e8456c66c45c955fc27b568bacb5c9 | https://github.com/dave/jennifer/blob/14e399b6b5e8456c66c45c955fc27b568bacb5c9/jen/file.go#L105-L107 | train |
dave/jennifer | jen/file.go | ImportAlias | func (f *File) ImportAlias(path, alias string) {
f.hints[path] = importdef{name: alias, alias: true}
} | go | func (f *File) ImportAlias(path, alias string) {
f.hints[path] = importdef{name: alias, alias: true}
} | [
"func",
"(",
"f",
"*",
"File",
")",
"ImportAlias",
"(",
"path",
",",
"alias",
"string",
")",
"{",
"f",
".",
"hints",
"[",
"path",
"]",
"=",
"importdef",
"{",
"name",
":",
"alias",
",",
"alias",
":",
"true",
"}",
"\n",
"}"
] | // ImportAlias provides the alias for a package path that should be used in the import block. A
// period can be used to force a dot-import. | [
"ImportAlias",
"provides",
"the",
"alias",
"for",
"a",
"package",
"path",
"that",
"should",
"be",
"used",
"in",
"the",
"import",
"block",
".",
"A",
"period",
"can",
"be",
"used",
"to",
"force",
"a",
"dot",
"-",
"import",
"."
] | 14e399b6b5e8456c66c45c955fc27b568bacb5c9 | https://github.com/dave/jennifer/blob/14e399b6b5e8456c66c45c955fc27b568bacb5c9/jen/file.go#L119-L121 | train |
dave/jennifer | jen/file.go | GoString | func (f *File) GoString() string {
buf := &bytes.Buffer{}
if err := f.Render(buf); err != nil {
panic(err)
}
return buf.String()
} | go | func (f *File) GoString() string {
buf := &bytes.Buffer{}
if err := f.Render(buf); err != nil {
panic(err)
}
return buf.String()
} | [
"func",
"(",
"f",
"*",
"File",
")",
"GoString",
"(",
")",
"string",
"{",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"if",
"err",
":=",
"f",
".",
"Render",
"(",
"buf",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",... | // GoString renders the File for testing. Any error will cause a panic. | [
"GoString",
"renders",
"the",
"File",
"for",
"testing",
".",
"Any",
"error",
"will",
"cause",
"a",
"panic",
"."
] | 14e399b6b5e8456c66c45c955fc27b568bacb5c9 | https://github.com/dave/jennifer/blob/14e399b6b5e8456c66c45c955fc27b568bacb5c9/jen/file.go#L232-L238 | train |
dave/jennifer | jen/do.go | Do | func (g *Group) Do(f func(*Statement)) *Statement {
s := Do(f)
g.items = append(g.items, s)
return s
} | go | func (g *Group) Do(f func(*Statement)) *Statement {
s := Do(f)
g.items = append(g.items, s)
return s
} | [
"func",
"(",
"g",
"*",
"Group",
")",
"Do",
"(",
"f",
"func",
"(",
"*",
"Statement",
")",
")",
"*",
"Statement",
"{",
"s",
":=",
"Do",
"(",
"f",
")",
"\n",
"g",
".",
"items",
"=",
"append",
"(",
"g",
".",
"items",
",",
"s",
")",
"\n",
"retur... | // Do calls the provided function with the statement as a parameter. Use for
// embedding logic. | [
"Do",
"calls",
"the",
"provided",
"function",
"with",
"the",
"statement",
"as",
"a",
"parameter",
".",
"Use",
"for",
"embedding",
"logic",
"."
] | 14e399b6b5e8456c66c45c955fc27b568bacb5c9 | https://github.com/dave/jennifer/blob/14e399b6b5e8456c66c45c955fc27b568bacb5c9/jen/do.go#L11-L15 | train |
anaskhan96/soup | soup.go | GetWithClient | func GetWithClient(url string, client *http.Client) (string, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
if debug {
panic("Couldn't perform GET request to " + url)
}
return "", errors.New("couldn't perform GET request to " + url)
}
// Set headers
for hName, hValue := range Headers {
req.Header.Set(hName, hValue)
}
// Set cookies
for cName, cValue := range Cookies {
req.AddCookie(&http.Cookie{
Name: cName,
Value: cValue,
})
}
// Perform request
resp, err := client.Do(req)
if err != nil {
if debug {
panic("Couldn't perform GET request to " + url)
}
return "", errors.New("couldn't perform GET request to " + url)
}
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
if debug {
panic("Unable to read the response body")
}
return "", errors.New("unable to read the response body")
}
return string(bytes), nil
} | go | func GetWithClient(url string, client *http.Client) (string, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
if debug {
panic("Couldn't perform GET request to " + url)
}
return "", errors.New("couldn't perform GET request to " + url)
}
// Set headers
for hName, hValue := range Headers {
req.Header.Set(hName, hValue)
}
// Set cookies
for cName, cValue := range Cookies {
req.AddCookie(&http.Cookie{
Name: cName,
Value: cValue,
})
}
// Perform request
resp, err := client.Do(req)
if err != nil {
if debug {
panic("Couldn't perform GET request to " + url)
}
return "", errors.New("couldn't perform GET request to " + url)
}
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
if debug {
panic("Unable to read the response body")
}
return "", errors.New("unable to read the response body")
}
return string(bytes), nil
} | [
"func",
"GetWithClient",
"(",
"url",
"string",
",",
"client",
"*",
"http",
".",
"Client",
")",
"(",
"string",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"url",
",",
"nil",
")",
"\n",
"if",
"e... | // GetWithClient returns the HTML returned by the url using a provided HTTP client | [
"GetWithClient",
"returns",
"the",
"HTML",
"returned",
"by",
"the",
"url",
"using",
"a",
"provided",
"HTTP",
"client"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L50-L86 | train |
anaskhan96/soup | soup.go | Get | func Get(url string) (string, error) {
// Init a new HTTP client
client := &http.Client{}
return GetWithClient(url, client)
} | go | func Get(url string) (string, error) {
// Init a new HTTP client
client := &http.Client{}
return GetWithClient(url, client)
} | [
"func",
"Get",
"(",
"url",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Init a new HTTP client",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"}",
"\n",
"return",
"GetWithClient",
"(",
"url",
",",
"client",
")",
"\n",
"}"
] | // Get returns the HTML returned by the url in string using the default HTTP client | [
"Get",
"returns",
"the",
"HTML",
"returned",
"by",
"the",
"url",
"in",
"string",
"using",
"the",
"default",
"HTTP",
"client"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L89-L93 | train |
anaskhan96/soup | soup.go | HTMLParse | func HTMLParse(s string) Root {
r, err := html.Parse(strings.NewReader(s))
if err != nil {
if debug {
panic("Unable to parse the HTML")
}
return Root{nil, "", errors.New("unable to parse the HTML")}
}
for r.Type != html.ElementNode {
switch r.Type {
case html.DocumentNode:
r = r.FirstChild
case html.DoctypeNode:
r = r.NextSibling
case html.CommentNode:
r = r.NextSibling
}
}
return Root{r, r.Data, nil}
} | go | func HTMLParse(s string) Root {
r, err := html.Parse(strings.NewReader(s))
if err != nil {
if debug {
panic("Unable to parse the HTML")
}
return Root{nil, "", errors.New("unable to parse the HTML")}
}
for r.Type != html.ElementNode {
switch r.Type {
case html.DocumentNode:
r = r.FirstChild
case html.DoctypeNode:
r = r.NextSibling
case html.CommentNode:
r = r.NextSibling
}
}
return Root{r, r.Data, nil}
} | [
"func",
"HTMLParse",
"(",
"s",
"string",
")",
"Root",
"{",
"r",
",",
"err",
":=",
"html",
".",
"Parse",
"(",
"strings",
".",
"NewReader",
"(",
"s",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"debug",
"{",
"panic",
"(",
"\"",
"\"",
")"... | // HTMLParse parses the HTML returning a start pointer to the DOM | [
"HTMLParse",
"parses",
"the",
"HTML",
"returning",
"a",
"start",
"pointer",
"to",
"the",
"DOM"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L96-L115 | train |
anaskhan96/soup | soup.go | Find | func (r Root) Find(args ...string) Root {
temp, ok := findOnce(r.Pointer, args, false, false)
if ok == false {
if debug {
panic("Element `" + args[0] + "` with attributes `" + strings.Join(args[1:], " ") + "` not found")
}
return Root{nil, "", errors.New("element `" + args[0] + "` with attributes `" + strings.Join(args[1:], " ") + "` not found")}
}
return Root{temp, temp.Data, nil}
} | go | func (r Root) Find(args ...string) Root {
temp, ok := findOnce(r.Pointer, args, false, false)
if ok == false {
if debug {
panic("Element `" + args[0] + "` with attributes `" + strings.Join(args[1:], " ") + "` not found")
}
return Root{nil, "", errors.New("element `" + args[0] + "` with attributes `" + strings.Join(args[1:], " ") + "` not found")}
}
return Root{temp, temp.Data, nil}
} | [
"func",
"(",
"r",
"Root",
")",
"Find",
"(",
"args",
"...",
"string",
")",
"Root",
"{",
"temp",
",",
"ok",
":=",
"findOnce",
"(",
"r",
".",
"Pointer",
",",
"args",
",",
"false",
",",
"false",
")",
"\n",
"if",
"ok",
"==",
"false",
"{",
"if",
"deb... | // Find finds the first occurrence of the given tag name,
// with or without attribute key and value specified,
// and returns a struct with a pointer to it | [
"Find",
"finds",
"the",
"first",
"occurrence",
"of",
"the",
"given",
"tag",
"name",
"with",
"or",
"without",
"attribute",
"key",
"and",
"value",
"specified",
"and",
"returns",
"a",
"struct",
"with",
"a",
"pointer",
"to",
"it"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L120-L129 | train |
anaskhan96/soup | soup.go | FindAll | func (r Root) FindAll(args ...string) []Root {
temp := findAllofem(r.Pointer, args, false)
if len(temp) == 0 {
if debug {
panic("Element `" + args[0] + "` with attributes `" + strings.Join(args[1:], " ") + "` not found")
}
return []Root{}
}
pointers := make([]Root, 0, len(temp))
for i := 0; i < len(temp); i++ {
pointers = append(pointers, Root{temp[i], temp[i].Data, nil})
}
return pointers
} | go | func (r Root) FindAll(args ...string) []Root {
temp := findAllofem(r.Pointer, args, false)
if len(temp) == 0 {
if debug {
panic("Element `" + args[0] + "` with attributes `" + strings.Join(args[1:], " ") + "` not found")
}
return []Root{}
}
pointers := make([]Root, 0, len(temp))
for i := 0; i < len(temp); i++ {
pointers = append(pointers, Root{temp[i], temp[i].Data, nil})
}
return pointers
} | [
"func",
"(",
"r",
"Root",
")",
"FindAll",
"(",
"args",
"...",
"string",
")",
"[",
"]",
"Root",
"{",
"temp",
":=",
"findAllofem",
"(",
"r",
".",
"Pointer",
",",
"args",
",",
"false",
")",
"\n",
"if",
"len",
"(",
"temp",
")",
"==",
"0",
"{",
"if"... | // FindAll finds all occurrences of the given tag name,
// with or without key and value specified,
// and returns an array of structs, each having
// the respective pointers | [
"FindAll",
"finds",
"all",
"occurrences",
"of",
"the",
"given",
"tag",
"name",
"with",
"or",
"without",
"key",
"and",
"value",
"specified",
"and",
"returns",
"an",
"array",
"of",
"structs",
"each",
"having",
"the",
"respective",
"pointers"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L135-L148 | train |
anaskhan96/soup | soup.go | FindNextSibling | func (r Root) FindNextSibling() Root {
nextSibling := r.Pointer.NextSibling
if nextSibling == nil {
if debug {
panic("No next sibling found")
}
return Root{nil, "", errors.New("no next sibling found")}
}
return Root{nextSibling, nextSibling.Data, nil}
} | go | func (r Root) FindNextSibling() Root {
nextSibling := r.Pointer.NextSibling
if nextSibling == nil {
if debug {
panic("No next sibling found")
}
return Root{nil, "", errors.New("no next sibling found")}
}
return Root{nextSibling, nextSibling.Data, nil}
} | [
"func",
"(",
"r",
"Root",
")",
"FindNextSibling",
"(",
")",
"Root",
"{",
"nextSibling",
":=",
"r",
".",
"Pointer",
".",
"NextSibling",
"\n",
"if",
"nextSibling",
"==",
"nil",
"{",
"if",
"debug",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
... | // FindNextSibling finds the next sibling of the pointer in the DOM
// returning a struct with a pointer to it | [
"FindNextSibling",
"finds",
"the",
"next",
"sibling",
"of",
"the",
"pointer",
"in",
"the",
"DOM",
"returning",
"a",
"struct",
"with",
"a",
"pointer",
"to",
"it"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L182-L191 | train |
anaskhan96/soup | soup.go | FindPrevSibling | func (r Root) FindPrevSibling() Root {
prevSibling := r.Pointer.PrevSibling
if prevSibling == nil {
if debug {
panic("No previous sibling found")
}
return Root{nil, "", errors.New("no previous sibling found")}
}
return Root{prevSibling, prevSibling.Data, nil}
} | go | func (r Root) FindPrevSibling() Root {
prevSibling := r.Pointer.PrevSibling
if prevSibling == nil {
if debug {
panic("No previous sibling found")
}
return Root{nil, "", errors.New("no previous sibling found")}
}
return Root{prevSibling, prevSibling.Data, nil}
} | [
"func",
"(",
"r",
"Root",
")",
"FindPrevSibling",
"(",
")",
"Root",
"{",
"prevSibling",
":=",
"r",
".",
"Pointer",
".",
"PrevSibling",
"\n",
"if",
"prevSibling",
"==",
"nil",
"{",
"if",
"debug",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
... | // FindPrevSibling finds the previous sibling of the pointer in the DOM
// returning a struct with a pointer to it | [
"FindPrevSibling",
"finds",
"the",
"previous",
"sibling",
"of",
"the",
"pointer",
"in",
"the",
"DOM",
"returning",
"a",
"struct",
"with",
"a",
"pointer",
"to",
"it"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L195-L204 | train |
anaskhan96/soup | soup.go | FindNextElementSibling | func (r Root) FindNextElementSibling() Root {
nextSibling := r.Pointer.NextSibling
if nextSibling == nil {
if debug {
panic("No next element sibling found")
}
return Root{nil, "", errors.New("no next element sibling found")}
}
if nextSibling.Type == html.ElementNode {
return Root{nextSibling, nextSibling.Data, nil}
}
p := Root{nextSibling, nextSibling.Data, nil}
return p.FindNextElementSibling()
} | go | func (r Root) FindNextElementSibling() Root {
nextSibling := r.Pointer.NextSibling
if nextSibling == nil {
if debug {
panic("No next element sibling found")
}
return Root{nil, "", errors.New("no next element sibling found")}
}
if nextSibling.Type == html.ElementNode {
return Root{nextSibling, nextSibling.Data, nil}
}
p := Root{nextSibling, nextSibling.Data, nil}
return p.FindNextElementSibling()
} | [
"func",
"(",
"r",
"Root",
")",
"FindNextElementSibling",
"(",
")",
"Root",
"{",
"nextSibling",
":=",
"r",
".",
"Pointer",
".",
"NextSibling",
"\n",
"if",
"nextSibling",
"==",
"nil",
"{",
"if",
"debug",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"... | // FindNextElementSibling finds the next element sibling of the pointer in the DOM
// returning a struct with a pointer to it | [
"FindNextElementSibling",
"finds",
"the",
"next",
"element",
"sibling",
"of",
"the",
"pointer",
"in",
"the",
"DOM",
"returning",
"a",
"struct",
"with",
"a",
"pointer",
"to",
"it"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L208-L221 | train |
anaskhan96/soup | soup.go | FindPrevElementSibling | func (r Root) FindPrevElementSibling() Root {
prevSibling := r.Pointer.PrevSibling
if prevSibling == nil {
if debug {
panic("No previous element sibling found")
}
return Root{nil, "", errors.New("no previous element sibling found")}
}
if prevSibling.Type == html.ElementNode {
return Root{prevSibling, prevSibling.Data, nil}
}
p := Root{prevSibling, prevSibling.Data, nil}
return p.FindPrevElementSibling()
} | go | func (r Root) FindPrevElementSibling() Root {
prevSibling := r.Pointer.PrevSibling
if prevSibling == nil {
if debug {
panic("No previous element sibling found")
}
return Root{nil, "", errors.New("no previous element sibling found")}
}
if prevSibling.Type == html.ElementNode {
return Root{prevSibling, prevSibling.Data, nil}
}
p := Root{prevSibling, prevSibling.Data, nil}
return p.FindPrevElementSibling()
} | [
"func",
"(",
"r",
"Root",
")",
"FindPrevElementSibling",
"(",
")",
"Root",
"{",
"prevSibling",
":=",
"r",
".",
"Pointer",
".",
"PrevSibling",
"\n",
"if",
"prevSibling",
"==",
"nil",
"{",
"if",
"debug",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"... | // FindPrevElementSibling finds the previous element sibling of the pointer in the DOM
// returning a struct with a pointer to it | [
"FindPrevElementSibling",
"finds",
"the",
"previous",
"element",
"sibling",
"of",
"the",
"pointer",
"in",
"the",
"DOM",
"returning",
"a",
"struct",
"with",
"a",
"pointer",
"to",
"it"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L225-L238 | train |
anaskhan96/soup | soup.go | Children | func (r Root) Children() []Root {
child := r.Pointer.FirstChild
var children []Root
for child != nil {
children = append(children, Root{child, child.Data, nil})
child = child.NextSibling
}
return children
} | go | func (r Root) Children() []Root {
child := r.Pointer.FirstChild
var children []Root
for child != nil {
children = append(children, Root{child, child.Data, nil})
child = child.NextSibling
}
return children
} | [
"func",
"(",
"r",
"Root",
")",
"Children",
"(",
")",
"[",
"]",
"Root",
"{",
"child",
":=",
"r",
".",
"Pointer",
".",
"FirstChild",
"\n",
"var",
"children",
"[",
"]",
"Root",
"\n",
"for",
"child",
"!=",
"nil",
"{",
"children",
"=",
"append",
"(",
... | // Children retuns all direct children of this DOME element. | [
"Children",
"retuns",
"all",
"direct",
"children",
"of",
"this",
"DOME",
"element",
"."
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L241-L249 | train |
anaskhan96/soup | soup.go | Attrs | func (r Root) Attrs() map[string]string {
if r.Pointer.Type != html.ElementNode {
if debug {
panic("Not an ElementNode")
}
return nil
}
if len(r.Pointer.Attr) == 0 {
return nil
}
return getKeyValue(r.Pointer.Attr)
} | go | func (r Root) Attrs() map[string]string {
if r.Pointer.Type != html.ElementNode {
if debug {
panic("Not an ElementNode")
}
return nil
}
if len(r.Pointer.Attr) == 0 {
return nil
}
return getKeyValue(r.Pointer.Attr)
} | [
"func",
"(",
"r",
"Root",
")",
"Attrs",
"(",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"if",
"r",
".",
"Pointer",
".",
"Type",
"!=",
"html",
".",
"ElementNode",
"{",
"if",
"debug",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"retu... | // Attrs returns a map containing all attributes | [
"Attrs",
"returns",
"a",
"map",
"containing",
"all",
"attributes"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L252-L263 | train |
anaskhan96/soup | soup.go | Text | func (r Root) Text() string {
k := r.Pointer.FirstChild
checkNode:
if k != nil && k.Type != html.TextNode {
k = k.NextSibling
if k == nil {
if debug {
panic("No text node found")
}
return ""
}
goto checkNode
}
if k != nil {
r, _ := regexp.Compile(`^\s+$`)
if ok := r.MatchString(k.Data); ok {
k = k.NextSibling
if k == nil {
if debug {
panic("No text node found")
}
return ""
}
goto checkNode
}
return k.Data
}
return ""
} | go | func (r Root) Text() string {
k := r.Pointer.FirstChild
checkNode:
if k != nil && k.Type != html.TextNode {
k = k.NextSibling
if k == nil {
if debug {
panic("No text node found")
}
return ""
}
goto checkNode
}
if k != nil {
r, _ := regexp.Compile(`^\s+$`)
if ok := r.MatchString(k.Data); ok {
k = k.NextSibling
if k == nil {
if debug {
panic("No text node found")
}
return ""
}
goto checkNode
}
return k.Data
}
return ""
} | [
"func",
"(",
"r",
"Root",
")",
"Text",
"(",
")",
"string",
"{",
"k",
":=",
"r",
".",
"Pointer",
".",
"FirstChild",
"\n",
"checkNode",
":",
"if",
"k",
"!=",
"nil",
"&&",
"k",
".",
"Type",
"!=",
"html",
".",
"TextNode",
"{",
"k",
"=",
"k",
".",
... | // Text returns the string inside a non-nested element | [
"Text",
"returns",
"the",
"string",
"inside",
"a",
"non",
"-",
"nested",
"element"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L266-L294 | train |
anaskhan96/soup | soup.go | FullText | func (r Root) FullText() string {
var buf bytes.Buffer
var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.TextNode {
buf.WriteString(n.Data)
}
if n.Type == html.ElementNode {
f(n.FirstChild)
}
if n.NextSibling != nil {
f(n.NextSibling)
}
}
f(r.Pointer.FirstChild)
return buf.String()
} | go | func (r Root) FullText() string {
var buf bytes.Buffer
var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.TextNode {
buf.WriteString(n.Data)
}
if n.Type == html.ElementNode {
f(n.FirstChild)
}
if n.NextSibling != nil {
f(n.NextSibling)
}
}
f(r.Pointer.FirstChild)
return buf.String()
} | [
"func",
"(",
"r",
"Root",
")",
"FullText",
"(",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n\n",
"var",
"f",
"func",
"(",
"*",
"html",
".",
"Node",
")",
"\n",
"f",
"=",
"func",
"(",
"n",
"*",
"html",
".",
"Node",
")",
"{",
"i... | // FullText returns the string inside even a nested element | [
"FullText",
"returns",
"the",
"string",
"inside",
"even",
"a",
"nested",
"element"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L297-L316 | train |
anaskhan96/soup | soup.go | findOnce | func findOnce(n *html.Node, args []string, uni bool, strict bool) (*html.Node, bool) {
if uni == true {
if n.Type == html.ElementNode && n.Data == args[0] {
if len(args) > 1 && len(args) < 4 {
for i := 0; i < len(n.Attr); i++ {
attr := n.Attr[i]
searchAttrName := args[1]
searchAttrVal := args[2]
if (strict && attributeAndValueEquals(attr, searchAttrName, searchAttrVal)) ||
(!strict && attributeContainsValue(attr, searchAttrName, searchAttrVal)) {
return n, true
}
}
} else if len(args) == 1 {
return n, true
}
}
}
uni = true
for c := n.FirstChild; c != nil; c = c.NextSibling {
p, q := findOnce(c, args, true, strict)
if q != false {
return p, q
}
}
return nil, false
} | go | func findOnce(n *html.Node, args []string, uni bool, strict bool) (*html.Node, bool) {
if uni == true {
if n.Type == html.ElementNode && n.Data == args[0] {
if len(args) > 1 && len(args) < 4 {
for i := 0; i < len(n.Attr); i++ {
attr := n.Attr[i]
searchAttrName := args[1]
searchAttrVal := args[2]
if (strict && attributeAndValueEquals(attr, searchAttrName, searchAttrVal)) ||
(!strict && attributeContainsValue(attr, searchAttrName, searchAttrVal)) {
return n, true
}
}
} else if len(args) == 1 {
return n, true
}
}
}
uni = true
for c := n.FirstChild; c != nil; c = c.NextSibling {
p, q := findOnce(c, args, true, strict)
if q != false {
return p, q
}
}
return nil, false
} | [
"func",
"findOnce",
"(",
"n",
"*",
"html",
".",
"Node",
",",
"args",
"[",
"]",
"string",
",",
"uni",
"bool",
",",
"strict",
"bool",
")",
"(",
"*",
"html",
".",
"Node",
",",
"bool",
")",
"{",
"if",
"uni",
"==",
"true",
"{",
"if",
"n",
".",
"Ty... | // Using depth first search to find the first occurrence and return | [
"Using",
"depth",
"first",
"search",
"to",
"find",
"the",
"first",
"occurrence",
"and",
"return"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L319-L345 | train |
anaskhan96/soup | soup.go | findAllofem | func findAllofem(n *html.Node, args []string, strict bool) []*html.Node {
var nodeLinks = make([]*html.Node, 0, 10)
var f func(*html.Node, []string, bool)
f = func(n *html.Node, args []string, uni bool) {
if uni == true {
if n.Data == args[0] {
if len(args) > 1 && len(args) < 4 {
for i := 0; i < len(n.Attr); i++ {
attr := n.Attr[i]
searchAttrName := args[1]
searchAttrVal := args[2]
if (strict && attributeAndValueEquals(attr, searchAttrName, searchAttrVal)) ||
(!strict && attributeContainsValue(attr, searchAttrName, searchAttrVal)) {
nodeLinks = append(nodeLinks, n)
}
}
} else if len(args) == 1 {
nodeLinks = append(nodeLinks, n)
}
}
}
uni = true
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c, args, true)
}
}
f(n, args, false)
return nodeLinks
} | go | func findAllofem(n *html.Node, args []string, strict bool) []*html.Node {
var nodeLinks = make([]*html.Node, 0, 10)
var f func(*html.Node, []string, bool)
f = func(n *html.Node, args []string, uni bool) {
if uni == true {
if n.Data == args[0] {
if len(args) > 1 && len(args) < 4 {
for i := 0; i < len(n.Attr); i++ {
attr := n.Attr[i]
searchAttrName := args[1]
searchAttrVal := args[2]
if (strict && attributeAndValueEquals(attr, searchAttrName, searchAttrVal)) ||
(!strict && attributeContainsValue(attr, searchAttrName, searchAttrVal)) {
nodeLinks = append(nodeLinks, n)
}
}
} else if len(args) == 1 {
nodeLinks = append(nodeLinks, n)
}
}
}
uni = true
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c, args, true)
}
}
f(n, args, false)
return nodeLinks
} | [
"func",
"findAllofem",
"(",
"n",
"*",
"html",
".",
"Node",
",",
"args",
"[",
"]",
"string",
",",
"strict",
"bool",
")",
"[",
"]",
"*",
"html",
".",
"Node",
"{",
"var",
"nodeLinks",
"=",
"make",
"(",
"[",
"]",
"*",
"html",
".",
"Node",
",",
"0",... | // Using depth first search to find all occurrences and return | [
"Using",
"depth",
"first",
"search",
"to",
"find",
"all",
"occurrences",
"and",
"return"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L348-L376 | train |
anaskhan96/soup | soup.go | attributeAndValueEquals | func attributeAndValueEquals(attr html.Attribute, attribute, value string) bool {
return attr.Key == attribute && attr.Val == value
} | go | func attributeAndValueEquals(attr html.Attribute, attribute, value string) bool {
return attr.Key == attribute && attr.Val == value
} | [
"func",
"attributeAndValueEquals",
"(",
"attr",
"html",
".",
"Attribute",
",",
"attribute",
",",
"value",
"string",
")",
"bool",
"{",
"return",
"attr",
".",
"Key",
"==",
"attribute",
"&&",
"attr",
".",
"Val",
"==",
"value",
"\n",
"}"
] | // attributeAndValueEquals reports when the html.Attribute attr has the same attribute name and value as from
// provided arguments | [
"attributeAndValueEquals",
"reports",
"when",
"the",
"html",
".",
"Attribute",
"attr",
"has",
"the",
"same",
"attribute",
"name",
"and",
"value",
"as",
"from",
"provided",
"arguments"
] | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L380-L382 | train |
anaskhan96/soup | soup.go | attributeContainsValue | func attributeContainsValue(attr html.Attribute, attribute, value string) bool {
if attr.Key == attribute {
for _, attrVal := range strings.Fields(attr.Val) {
if attrVal == value {
return true
}
}
}
return false
} | go | func attributeContainsValue(attr html.Attribute, attribute, value string) bool {
if attr.Key == attribute {
for _, attrVal := range strings.Fields(attr.Val) {
if attrVal == value {
return true
}
}
}
return false
} | [
"func",
"attributeContainsValue",
"(",
"attr",
"html",
".",
"Attribute",
",",
"attribute",
",",
"value",
"string",
")",
"bool",
"{",
"if",
"attr",
".",
"Key",
"==",
"attribute",
"{",
"for",
"_",
",",
"attrVal",
":=",
"range",
"strings",
".",
"Fields",
"(... | // attributeContainsValue reports when the html.Attribute attr has the same attribute name as from provided
// attribute argument and compares if it has the same value in its values parameter | [
"attributeContainsValue",
"reports",
"when",
"the",
"html",
".",
"Attribute",
"attr",
"has",
"the",
"same",
"attribute",
"name",
"as",
"from",
"provided",
"attribute",
"argument",
"and",
"compares",
"if",
"it",
"has",
"the",
"same",
"value",
"in",
"its",
"valu... | 50123c340ba50505026229a3fb7e0bc5343e7e4d | https://github.com/anaskhan96/soup/blob/50123c340ba50505026229a3fb7e0bc5343e7e4d/soup.go#L386-L395 | train |
ccding/go-stun | stun/log.go | NewLogger | func NewLogger() *Logger {
logger := &Logger{*log.New(os.Stdout, "", log.LstdFlags), false, false}
return logger
} | go | func NewLogger() *Logger {
logger := &Logger{*log.New(os.Stdout, "", log.LstdFlags), false, false}
return logger
} | [
"func",
"NewLogger",
"(",
")",
"*",
"Logger",
"{",
"logger",
":=",
"&",
"Logger",
"{",
"*",
"log",
".",
"New",
"(",
"os",
".",
"Stdout",
",",
"\"",
"\"",
",",
"log",
".",
"LstdFlags",
")",
",",
"false",
",",
"false",
"}",
"\n",
"return",
"logger"... | // NewLogger creates a default logger. | [
"NewLogger",
"creates",
"a",
"default",
"logger",
"."
] | be486d185f3dfcb2dbf8429332da50a0da7f95a6 | https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/log.go#L32-L35 | train |
ccding/go-stun | stun/log.go | Debugf | func (l *Logger) Debugf(format string, v ...interface{}) {
if l.debug {
l.Printf(format, v...)
}
} | go | func (l *Logger) Debugf(format string, v ...interface{}) {
if l.debug {
l.Printf(format, v...)
}
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Debugf",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"l",
".",
"debug",
"{",
"l",
".",
"Printf",
"(",
"format",
",",
"v",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // Debugf outputs the log in the format of log.Printf. | [
"Debugf",
"outputs",
"the",
"log",
"in",
"the",
"format",
"of",
"log",
".",
"Printf",
"."
] | be486d185f3dfcb2dbf8429332da50a0da7f95a6 | https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/log.go#L55-L59 | train |
ccding/go-stun | stun/log.go | Infof | func (l *Logger) Infof(format string, v ...interface{}) {
if l.info {
l.Printf(format, v...)
}
} | go | func (l *Logger) Infof(format string, v ...interface{}) {
if l.info {
l.Printf(format, v...)
}
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Infof",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"l",
".",
"info",
"{",
"l",
".",
"Printf",
"(",
"format",
",",
"v",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // Infof outputs the log in the format of log.Printf. | [
"Infof",
"outputs",
"the",
"log",
"in",
"the",
"format",
"of",
"log",
".",
"Printf",
"."
] | be486d185f3dfcb2dbf8429332da50a0da7f95a6 | https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/log.go#L76-L80 | train |
ccding/go-stun | stun/response.go | String | func (r *response) String() string {
if r == nil {
return "Nil"
}
return fmt.Sprintf("{packet nil: %v, local: %v, remote: %v, changed: %v, other: %v, identical: %v}",
r.packet == nil,
r.mappedAddr,
r.serverAddr,
r.changedAddr,
r.otherAddr,
r.identical)
} | go | func (r *response) String() string {
if r == nil {
return "Nil"
}
return fmt.Sprintf("{packet nil: %v, local: %v, remote: %v, changed: %v, other: %v, identical: %v}",
r.packet == nil,
r.mappedAddr,
r.serverAddr,
r.changedAddr,
r.otherAddr,
r.identical)
} | [
"func",
"(",
"r",
"*",
"response",
")",
"String",
"(",
")",
"string",
"{",
"if",
"r",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"r",
".",
"packet",
"==",
"nil",
",",
"r",
"... | // String is only used for verbose mode output. | [
"String",
"is",
"only",
"used",
"for",
"verbose",
"mode",
"output",
"."
] | be486d185f3dfcb2dbf8429332da50a0da7f95a6 | https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/response.go#L67-L78 | train |
ccding/go-stun | stun/client.go | NewClient | func NewClient() *Client {
c := new(Client)
c.SetSoftwareName(DefaultSoftwareName)
c.logger = NewLogger()
return c
} | go | func NewClient() *Client {
c := new(Client)
c.SetSoftwareName(DefaultSoftwareName)
c.logger = NewLogger()
return c
} | [
"func",
"NewClient",
"(",
")",
"*",
"Client",
"{",
"c",
":=",
"new",
"(",
"Client",
")",
"\n",
"c",
".",
"SetSoftwareName",
"(",
"DefaultSoftwareName",
")",
"\n",
"c",
".",
"logger",
"=",
"NewLogger",
"(",
")",
"\n",
"return",
"c",
"\n",
"}"
] | // NewClient returns a client without network connection. The network
// connection will be build when calling Discover function. | [
"NewClient",
"returns",
"a",
"client",
"without",
"network",
"connection",
".",
"The",
"network",
"connection",
"will",
"be",
"build",
"when",
"calling",
"Discover",
"function",
"."
] | be486d185f3dfcb2dbf8429332da50a0da7f95a6 | https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/client.go#L36-L41 | train |
ccding/go-stun | stun/client.go | SetServerHost | func (c *Client) SetServerHost(host string, port int) {
c.serverAddr = net.JoinHostPort(host, strconv.Itoa(port))
} | go | func (c *Client) SetServerHost(host string, port int) {
c.serverAddr = net.JoinHostPort(host, strconv.Itoa(port))
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SetServerHost",
"(",
"host",
"string",
",",
"port",
"int",
")",
"{",
"c",
".",
"serverAddr",
"=",
"net",
".",
"JoinHostPort",
"(",
"host",
",",
"strconv",
".",
"Itoa",
"(",
"port",
")",
")",
"\n",
"}"
] | // SetServerHost allows user to set the STUN hostname and port. | [
"SetServerHost",
"allows",
"user",
"to",
"set",
"the",
"STUN",
"hostname",
"and",
"port",
"."
] | be486d185f3dfcb2dbf8429332da50a0da7f95a6 | https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/client.go#L66-L68 | train |
ccding/go-stun | stun/client.go | Discover | func (c *Client) Discover() (NATType, *Host, error) {
if c.serverAddr == "" {
c.SetServerAddr(DefaultServerAddr)
}
serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr)
if err != nil {
return NATError, nil, err
}
// Use the connection passed to the client if it is not nil, otherwise
// create a connection and close it at the end.
conn := c.conn
if conn == nil {
conn, err = net.ListenUDP("udp", nil)
if err != nil {
return NATError, nil, err
}
defer conn.Close()
}
return c.discover(conn, serverUDPAddr)
} | go | func (c *Client) Discover() (NATType, *Host, error) {
if c.serverAddr == "" {
c.SetServerAddr(DefaultServerAddr)
}
serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr)
if err != nil {
return NATError, nil, err
}
// Use the connection passed to the client if it is not nil, otherwise
// create a connection and close it at the end.
conn := c.conn
if conn == nil {
conn, err = net.ListenUDP("udp", nil)
if err != nil {
return NATError, nil, err
}
defer conn.Close()
}
return c.discover(conn, serverUDPAddr)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Discover",
"(",
")",
"(",
"NATType",
",",
"*",
"Host",
",",
"error",
")",
"{",
"if",
"c",
".",
"serverAddr",
"==",
"\"",
"\"",
"{",
"c",
".",
"SetServerAddr",
"(",
"DefaultServerAddr",
")",
"\n",
"}",
"\n",
... | // Discover contacts the STUN server and gets the response of NAT type, host
// for UDP punching. | [
"Discover",
"contacts",
"the",
"STUN",
"server",
"and",
"gets",
"the",
"response",
"of",
"NAT",
"type",
"host",
"for",
"UDP",
"punching",
"."
] | be486d185f3dfcb2dbf8429332da50a0da7f95a6 | https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/client.go#L83-L102 | train |
ccding/go-stun | stun/client.go | Keepalive | func (c *Client) Keepalive() (*Host, error) {
if c.conn == nil {
return nil, errors.New("no connection available")
}
if c.serverAddr == "" {
c.SetServerAddr(DefaultServerAddr)
}
serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr)
if err != nil {
return nil, err
}
resp, err := c.test1(c.conn, serverUDPAddr)
if err != nil {
return nil, err
}
if resp == nil || resp.packet == nil {
return nil, errors.New("failed to contact")
}
return resp.mappedAddr, nil
} | go | func (c *Client) Keepalive() (*Host, error) {
if c.conn == nil {
return nil, errors.New("no connection available")
}
if c.serverAddr == "" {
c.SetServerAddr(DefaultServerAddr)
}
serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr)
if err != nil {
return nil, err
}
resp, err := c.test1(c.conn, serverUDPAddr)
if err != nil {
return nil, err
}
if resp == nil || resp.packet == nil {
return nil, errors.New("failed to contact")
}
return resp.mappedAddr, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Keepalive",
"(",
")",
"(",
"*",
"Host",
",",
"error",
")",
"{",
"if",
"c",
".",
"conn",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
"... | // Keepalive sends and receives a bind request, which ensures the mapping stays open
// Only applicable when client was created with a connection. | [
"Keepalive",
"sends",
"and",
"receives",
"a",
"bind",
"request",
"which",
"ensures",
"the",
"mapping",
"stays",
"open",
"Only",
"applicable",
"when",
"client",
"was",
"created",
"with",
"a",
"connection",
"."
] | be486d185f3dfcb2dbf8429332da50a0da7f95a6 | https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/client.go#L106-L126 | train |
ccding/go-stun | stun/utils.go | padding | func padding(bytes []byte) []byte {
length := uint16(len(bytes))
return append(bytes, make([]byte, align(length)-length)...)
} | go | func padding(bytes []byte) []byte {
length := uint16(len(bytes))
return append(bytes, make([]byte, align(length)-length)...)
} | [
"func",
"padding",
"(",
"bytes",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"length",
":=",
"uint16",
"(",
"len",
"(",
"bytes",
")",
")",
"\n",
"return",
"append",
"(",
"bytes",
",",
"make",
"(",
"[",
"]",
"byte",
",",
"align",
"(",
"length",
... | // Padding the length of the byte slice to multiple of 4. | [
"Padding",
"the",
"length",
"of",
"the",
"byte",
"slice",
"to",
"multiple",
"of",
"4",
"."
] | be486d185f3dfcb2dbf8429332da50a0da7f95a6 | https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/utils.go#L24-L27 | train |
ccding/go-stun | stun/utils.go | isLocalAddress | func isLocalAddress(local, localRemote string) bool {
// Resolve the IP returned by the STUN server first.
localRemoteAddr, err := net.ResolveUDPAddr("udp", localRemote)
if err != nil {
return false
}
// Try comparing with the local address on the socket first, but only if
// it's actually specified.
addr, err := net.ResolveUDPAddr("udp", local)
if err == nil && addr.IP != nil && !addr.IP.IsUnspecified() {
return addr.IP.Equal(localRemoteAddr.IP)
}
// Fallback to checking IPs of all interfaces
addrs, err := net.InterfaceAddrs()
if err != nil {
return false
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
if ip.Equal(localRemoteAddr.IP) {
return true
}
}
return false
} | go | func isLocalAddress(local, localRemote string) bool {
// Resolve the IP returned by the STUN server first.
localRemoteAddr, err := net.ResolveUDPAddr("udp", localRemote)
if err != nil {
return false
}
// Try comparing with the local address on the socket first, but only if
// it's actually specified.
addr, err := net.ResolveUDPAddr("udp", local)
if err == nil && addr.IP != nil && !addr.IP.IsUnspecified() {
return addr.IP.Equal(localRemoteAddr.IP)
}
// Fallback to checking IPs of all interfaces
addrs, err := net.InterfaceAddrs()
if err != nil {
return false
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
if ip.Equal(localRemoteAddr.IP) {
return true
}
}
return false
} | [
"func",
"isLocalAddress",
"(",
"local",
",",
"localRemote",
"string",
")",
"bool",
"{",
"// Resolve the IP returned by the STUN server first.",
"localRemoteAddr",
",",
"err",
":=",
"net",
".",
"ResolveUDPAddr",
"(",
"\"",
"\"",
",",
"localRemote",
")",
"\n",
"if",
... | // isLocalAddress check if localRemote is a local address. | [
"isLocalAddress",
"check",
"if",
"localRemote",
"is",
"a",
"local",
"address",
"."
] | be486d185f3dfcb2dbf8429332da50a0da7f95a6 | https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/utils.go#L36-L63 | train |
ccding/go-stun | stun/host.go | TransportAddr | func (h *Host) TransportAddr() string {
return net.JoinHostPort(h.ip, strconv.Itoa(int(h.port)))
} | go | func (h *Host) TransportAddr() string {
return net.JoinHostPort(h.ip, strconv.Itoa(int(h.port)))
} | [
"func",
"(",
"h",
"*",
"Host",
")",
"TransportAddr",
"(",
")",
"string",
"{",
"return",
"net",
".",
"JoinHostPort",
"(",
"h",
".",
"ip",
",",
"strconv",
".",
"Itoa",
"(",
"int",
"(",
"h",
".",
"port",
")",
")",
")",
"\n",
"}"
] | // TransportAddr returns the transport layer address of the host. | [
"TransportAddr",
"returns",
"the",
"transport",
"layer",
"address",
"of",
"the",
"host",
"."
] | be486d185f3dfcb2dbf8429332da50a0da7f95a6 | https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/host.go#L63-L65 | train |
zalando/go-keyring | keyring_windows.go | Set | func (k windowsKeychain) Set(service, username, password string) error {
cred := wincred.NewGenericCredential(k.credName(service, username))
cred.UserName = username
cred.CredentialBlob = []byte(password)
return cred.Write()
} | go | func (k windowsKeychain) Set(service, username, password string) error {
cred := wincred.NewGenericCredential(k.credName(service, username))
cred.UserName = username
cred.CredentialBlob = []byte(password)
return cred.Write()
} | [
"func",
"(",
"k",
"windowsKeychain",
")",
"Set",
"(",
"service",
",",
"username",
",",
"password",
"string",
")",
"error",
"{",
"cred",
":=",
"wincred",
".",
"NewGenericCredential",
"(",
"k",
".",
"credName",
"(",
"service",
",",
"username",
")",
")",
"\... | // Set stores stores user and pass in the keyring under the defined service
// name. | [
"Set",
"stores",
"stores",
"user",
"and",
"pass",
"in",
"the",
"keyring",
"under",
"the",
"defined",
"service",
"name",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/keyring_windows.go#L24-L29 | train |
zalando/go-keyring | secret_service/secret_service.go | NewSecret | func NewSecret(session dbus.ObjectPath, secret string) Secret {
return Secret{
Session: session,
Parameters: []byte{},
Value: []byte(secret),
ContentType: "text/plain; charset=utf8",
}
} | go | func NewSecret(session dbus.ObjectPath, secret string) Secret {
return Secret{
Session: session,
Parameters: []byte{},
Value: []byte(secret),
ContentType: "text/plain; charset=utf8",
}
} | [
"func",
"NewSecret",
"(",
"session",
"dbus",
".",
"ObjectPath",
",",
"secret",
"string",
")",
"Secret",
"{",
"return",
"Secret",
"{",
"Session",
":",
"session",
",",
"Parameters",
":",
"[",
"]",
"byte",
"{",
"}",
",",
"Value",
":",
"[",
"]",
"byte",
... | // NewSecret initializes a new Secret. | [
"NewSecret",
"initializes",
"a",
"new",
"Secret",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L33-L40 | train |
zalando/go-keyring | secret_service/secret_service.go | NewSecretService | func NewSecretService() (*SecretService, error) {
conn, err := dbus.SessionBus()
if err != nil {
return nil, err
}
return &SecretService{
conn,
conn.Object(serviceName, servicePath),
}, nil
} | go | func NewSecretService() (*SecretService, error) {
conn, err := dbus.SessionBus()
if err != nil {
return nil, err
}
return &SecretService{
conn,
conn.Object(serviceName, servicePath),
}, nil
} | [
"func",
"NewSecretService",
"(",
")",
"(",
"*",
"SecretService",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"dbus",
".",
"SessionBus",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"... | // NewSecretService inializes a new SecretService object. | [
"NewSecretService",
"inializes",
"a",
"new",
"SecretService",
"object",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L49-L59 | train |
zalando/go-keyring | secret_service/secret_service.go | OpenSession | func (s *SecretService) OpenSession() (dbus.BusObject, error) {
var disregard dbus.Variant
var sessionPath dbus.ObjectPath
err := s.object.Call(serviceInterface+".OpenSession", 0, "plain", dbus.MakeVariant("")).Store(&disregard, &sessionPath)
if err != nil {
return nil, err
}
return s.Object(serviceName, sessionPath), nil
} | go | func (s *SecretService) OpenSession() (dbus.BusObject, error) {
var disregard dbus.Variant
var sessionPath dbus.ObjectPath
err := s.object.Call(serviceInterface+".OpenSession", 0, "plain", dbus.MakeVariant("")).Store(&disregard, &sessionPath)
if err != nil {
return nil, err
}
return s.Object(serviceName, sessionPath), nil
} | [
"func",
"(",
"s",
"*",
"SecretService",
")",
"OpenSession",
"(",
")",
"(",
"dbus",
".",
"BusObject",
",",
"error",
")",
"{",
"var",
"disregard",
"dbus",
".",
"Variant",
"\n",
"var",
"sessionPath",
"dbus",
".",
"ObjectPath",
"\n",
"err",
":=",
"s",
".",... | // OpenSession opens a secret service session. | [
"OpenSession",
"opens",
"a",
"secret",
"service",
"session",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L62-L71 | train |
zalando/go-keyring | secret_service/secret_service.go | GetCollection | func (s *SecretService) GetCollection(name string) dbus.BusObject {
return s.Object(serviceName, dbus.ObjectPath(collectionBasePath+name))
} | go | func (s *SecretService) GetCollection(name string) dbus.BusObject {
return s.Object(serviceName, dbus.ObjectPath(collectionBasePath+name))
} | [
"func",
"(",
"s",
"*",
"SecretService",
")",
"GetCollection",
"(",
"name",
"string",
")",
"dbus",
".",
"BusObject",
"{",
"return",
"s",
".",
"Object",
"(",
"serviceName",
",",
"dbus",
".",
"ObjectPath",
"(",
"collectionBasePath",
"+",
"name",
")",
")",
"... | // GetCollection returns a collection from a name. | [
"GetCollection",
"returns",
"a",
"collection",
"from",
"a",
"name",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L91-L93 | train |
zalando/go-keyring | secret_service/secret_service.go | GetLoginCollection | func (s *SecretService) GetLoginCollection() dbus.BusObject {
path := dbus.ObjectPath(collectionBasePath + "login")
if err := s.CheckCollectionPath(path); err != nil {
path = dbus.ObjectPath(loginCollectionAlias)
}
return s.Object(serviceName, path)
} | go | func (s *SecretService) GetLoginCollection() dbus.BusObject {
path := dbus.ObjectPath(collectionBasePath + "login")
if err := s.CheckCollectionPath(path); err != nil {
path = dbus.ObjectPath(loginCollectionAlias)
}
return s.Object(serviceName, path)
} | [
"func",
"(",
"s",
"*",
"SecretService",
")",
"GetLoginCollection",
"(",
")",
"dbus",
".",
"BusObject",
"{",
"path",
":=",
"dbus",
".",
"ObjectPath",
"(",
"collectionBasePath",
"+",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"CheckCollectionPath",
... | // GetLoginCollection decides and returns the dbus collection to be used for login. | [
"GetLoginCollection",
"decides",
"and",
"returns",
"the",
"dbus",
"collection",
"to",
"be",
"used",
"for",
"login",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L96-L102 | train |
zalando/go-keyring | secret_service/secret_service.go | Unlock | func (s *SecretService) Unlock(collection dbus.ObjectPath) error {
var unlocked []dbus.ObjectPath
var prompt dbus.ObjectPath
err := s.object.Call(serviceInterface+".Unlock", 0, []dbus.ObjectPath{collection}).Store(&unlocked, &prompt)
if err != nil {
return err
}
_, v, err := s.handlePrompt(prompt)
if err != nil {
return err
}
collections := v.Value()
switch c := collections.(type) {
case []dbus.ObjectPath:
unlocked = append(unlocked, c...)
}
if len(unlocked) != 1 || unlocked[0] != collection {
return fmt.Errorf("failed to unlock correct collection '%v'", collection)
}
return nil
} | go | func (s *SecretService) Unlock(collection dbus.ObjectPath) error {
var unlocked []dbus.ObjectPath
var prompt dbus.ObjectPath
err := s.object.Call(serviceInterface+".Unlock", 0, []dbus.ObjectPath{collection}).Store(&unlocked, &prompt)
if err != nil {
return err
}
_, v, err := s.handlePrompt(prompt)
if err != nil {
return err
}
collections := v.Value()
switch c := collections.(type) {
case []dbus.ObjectPath:
unlocked = append(unlocked, c...)
}
if len(unlocked) != 1 || unlocked[0] != collection {
return fmt.Errorf("failed to unlock correct collection '%v'", collection)
}
return nil
} | [
"func",
"(",
"s",
"*",
"SecretService",
")",
"Unlock",
"(",
"collection",
"dbus",
".",
"ObjectPath",
")",
"error",
"{",
"var",
"unlocked",
"[",
"]",
"dbus",
".",
"ObjectPath",
"\n",
"var",
"prompt",
"dbus",
".",
"ObjectPath",
"\n",
"err",
":=",
"s",
".... | // Unlock unlocks a collection. | [
"Unlock",
"unlocks",
"a",
"collection",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L105-L129 | train |
zalando/go-keyring | secret_service/secret_service.go | Close | func (s *SecretService) Close(session dbus.BusObject) error {
return session.Call(sessionInterface+".Close", 0).Err
} | go | func (s *SecretService) Close(session dbus.BusObject) error {
return session.Call(sessionInterface+".Close", 0).Err
} | [
"func",
"(",
"s",
"*",
"SecretService",
")",
"Close",
"(",
"session",
"dbus",
".",
"BusObject",
")",
"error",
"{",
"return",
"session",
".",
"Call",
"(",
"sessionInterface",
"+",
"\"",
"\"",
",",
"0",
")",
".",
"Err",
"\n",
"}"
] | // Close closes a secret service dbus session. | [
"Close",
"closes",
"a",
"secret",
"service",
"dbus",
"session",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L132-L134 | train |
zalando/go-keyring | secret_service/secret_service.go | CreateCollection | func (s *SecretService) CreateCollection(label string) (dbus.BusObject, error) {
properties := map[string]dbus.Variant{
collectionInterface + ".Label": dbus.MakeVariant(label),
}
var collection, prompt dbus.ObjectPath
err := s.object.Call(serviceInterface+".CreateCollection", 0, properties, "").
Store(&collection, &prompt)
if err != nil {
return nil, err
}
_, v, err := s.handlePrompt(prompt)
if err != nil {
return nil, err
}
if v.String() != "" {
collection = dbus.ObjectPath(v.String())
}
return s.Object(serviceName, collection), nil
} | go | func (s *SecretService) CreateCollection(label string) (dbus.BusObject, error) {
properties := map[string]dbus.Variant{
collectionInterface + ".Label": dbus.MakeVariant(label),
}
var collection, prompt dbus.ObjectPath
err := s.object.Call(serviceInterface+".CreateCollection", 0, properties, "").
Store(&collection, &prompt)
if err != nil {
return nil, err
}
_, v, err := s.handlePrompt(prompt)
if err != nil {
return nil, err
}
if v.String() != "" {
collection = dbus.ObjectPath(v.String())
}
return s.Object(serviceName, collection), nil
} | [
"func",
"(",
"s",
"*",
"SecretService",
")",
"CreateCollection",
"(",
"label",
"string",
")",
"(",
"dbus",
".",
"BusObject",
",",
"error",
")",
"{",
"properties",
":=",
"map",
"[",
"string",
"]",
"dbus",
".",
"Variant",
"{",
"collectionInterface",
"+",
"... | // CreateCollection with the supplied label. | [
"CreateCollection",
"with",
"the",
"supplied",
"label",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L137-L158 | train |
zalando/go-keyring | secret_service/secret_service.go | CreateItem | func (s *SecretService) CreateItem(collection dbus.BusObject, label string, attributes map[string]string, secret Secret) error {
properties := map[string]dbus.Variant{
itemInterface + ".Label": dbus.MakeVariant(label),
itemInterface + ".Attributes": dbus.MakeVariant(attributes),
}
var item, prompt dbus.ObjectPath
err := collection.Call(collectionInterface+".CreateItem", 0,
properties, secret, true).Store(&item, &prompt)
if err != nil {
return err
}
_, _, err = s.handlePrompt(prompt)
if err != nil {
return err
}
return nil
} | go | func (s *SecretService) CreateItem(collection dbus.BusObject, label string, attributes map[string]string, secret Secret) error {
properties := map[string]dbus.Variant{
itemInterface + ".Label": dbus.MakeVariant(label),
itemInterface + ".Attributes": dbus.MakeVariant(attributes),
}
var item, prompt dbus.ObjectPath
err := collection.Call(collectionInterface+".CreateItem", 0,
properties, secret, true).Store(&item, &prompt)
if err != nil {
return err
}
_, _, err = s.handlePrompt(prompt)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"SecretService",
")",
"CreateItem",
"(",
"collection",
"dbus",
".",
"BusObject",
",",
"label",
"string",
",",
"attributes",
"map",
"[",
"string",
"]",
"string",
",",
"secret",
"Secret",
")",
"error",
"{",
"properties",
":=",
"map",
... | // CreateItem creates an item in a collection, with label, attributes and a
// related secret. | [
"CreateItem",
"creates",
"an",
"item",
"in",
"a",
"collection",
"with",
"label",
"attributes",
"and",
"a",
"related",
"secret",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L162-L181 | train |
zalando/go-keyring | secret_service/secret_service.go | handlePrompt | func (s *SecretService) handlePrompt(prompt dbus.ObjectPath) (bool, dbus.Variant, error) {
if prompt != dbus.ObjectPath("/") {
err := s.Object(serviceName, prompt).Call(promptInterface+".Prompt", 0, "").Err
if err != nil {
return false, dbus.MakeVariant(""), err
}
promptSignal := make(chan *dbus.Signal, 1)
s.Signal(promptSignal)
signal := <-promptSignal
switch signal.Name {
case promptInterface + ".Completed":
dismissed := signal.Body[0].(bool)
result := signal.Body[1].(dbus.Variant)
return dismissed, result, nil
}
}
return false, dbus.MakeVariant(""), nil
} | go | func (s *SecretService) handlePrompt(prompt dbus.ObjectPath) (bool, dbus.Variant, error) {
if prompt != dbus.ObjectPath("/") {
err := s.Object(serviceName, prompt).Call(promptInterface+".Prompt", 0, "").Err
if err != nil {
return false, dbus.MakeVariant(""), err
}
promptSignal := make(chan *dbus.Signal, 1)
s.Signal(promptSignal)
signal := <-promptSignal
switch signal.Name {
case promptInterface + ".Completed":
dismissed := signal.Body[0].(bool)
result := signal.Body[1].(dbus.Variant)
return dismissed, result, nil
}
}
return false, dbus.MakeVariant(""), nil
} | [
"func",
"(",
"s",
"*",
"SecretService",
")",
"handlePrompt",
"(",
"prompt",
"dbus",
".",
"ObjectPath",
")",
"(",
"bool",
",",
"dbus",
".",
"Variant",
",",
"error",
")",
"{",
"if",
"prompt",
"!=",
"dbus",
".",
"ObjectPath",
"(",
"\"",
"\"",
")",
"{",
... | // handlePrompt checks if a prompt should be handles and handles it by
// triggering the prompt and waiting for the Sercret service daemon to display
// the prompt to the user. | [
"handlePrompt",
"checks",
"if",
"a",
"prompt",
"should",
"be",
"handles",
"and",
"handles",
"it",
"by",
"triggering",
"the",
"prompt",
"and",
"waiting",
"for",
"the",
"Sercret",
"service",
"daemon",
"to",
"display",
"the",
"prompt",
"to",
"the",
"user",
"."
... | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L186-L207 | train |
zalando/go-keyring | secret_service/secret_service.go | SearchItems | func (s *SecretService) SearchItems(collection dbus.BusObject, search interface{}) ([]dbus.ObjectPath, error) {
var results []dbus.ObjectPath
err := collection.Call(collectionInterface+".SearchItems", 0, search).Store(&results)
if err != nil {
return nil, err
}
return results, nil
} | go | func (s *SecretService) SearchItems(collection dbus.BusObject, search interface{}) ([]dbus.ObjectPath, error) {
var results []dbus.ObjectPath
err := collection.Call(collectionInterface+".SearchItems", 0, search).Store(&results)
if err != nil {
return nil, err
}
return results, nil
} | [
"func",
"(",
"s",
"*",
"SecretService",
")",
"SearchItems",
"(",
"collection",
"dbus",
".",
"BusObject",
",",
"search",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"dbus",
".",
"ObjectPath",
",",
"error",
")",
"{",
"var",
"results",
"[",
"]",
"dbus",
... | // SearchItems returns a list of items matching the search object. | [
"SearchItems",
"returns",
"a",
"list",
"of",
"items",
"matching",
"the",
"search",
"object",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L210-L218 | train |
zalando/go-keyring | secret_service/secret_service.go | GetSecret | func (s *SecretService) GetSecret(itemPath dbus.ObjectPath, session dbus.ObjectPath) (*Secret, error) {
var secret Secret
err := s.Object(serviceName, itemPath).Call(itemInterface+".GetSecret", 0, session).Store(&secret)
if err != nil {
return nil, err
}
return &secret, nil
} | go | func (s *SecretService) GetSecret(itemPath dbus.ObjectPath, session dbus.ObjectPath) (*Secret, error) {
var secret Secret
err := s.Object(serviceName, itemPath).Call(itemInterface+".GetSecret", 0, session).Store(&secret)
if err != nil {
return nil, err
}
return &secret, nil
} | [
"func",
"(",
"s",
"*",
"SecretService",
")",
"GetSecret",
"(",
"itemPath",
"dbus",
".",
"ObjectPath",
",",
"session",
"dbus",
".",
"ObjectPath",
")",
"(",
"*",
"Secret",
",",
"error",
")",
"{",
"var",
"secret",
"Secret",
"\n",
"err",
":=",
"s",
".",
... | // GetSecret gets secret from an item in a given session. | [
"GetSecret",
"gets",
"secret",
"from",
"an",
"item",
"in",
"a",
"given",
"session",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L221-L229 | train |
zalando/go-keyring | secret_service/secret_service.go | Delete | func (s *SecretService) Delete(itemPath dbus.ObjectPath) error {
var prompt dbus.ObjectPath
err := s.Object(serviceName, itemPath).Call(itemInterface+".Delete", 0).Store(&prompt)
if err != nil {
return err
}
_, _, err = s.handlePrompt(prompt)
if err != nil {
return err
}
return nil
} | go | func (s *SecretService) Delete(itemPath dbus.ObjectPath) error {
var prompt dbus.ObjectPath
err := s.Object(serviceName, itemPath).Call(itemInterface+".Delete", 0).Store(&prompt)
if err != nil {
return err
}
_, _, err = s.handlePrompt(prompt)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"SecretService",
")",
"Delete",
"(",
"itemPath",
"dbus",
".",
"ObjectPath",
")",
"error",
"{",
"var",
"prompt",
"dbus",
".",
"ObjectPath",
"\n",
"err",
":=",
"s",
".",
"Object",
"(",
"serviceName",
",",
"itemPath",
")",
".",
"Cal... | // Delete deletes an item from the collection. | [
"Delete",
"deletes",
"an",
"item",
"from",
"the",
"collection",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L232-L245 | train |
zalando/go-keyring | keyring_linux.go | findItem | func (s secretServiceProvider) findItem(svc *ss.SecretService, service, user string) (dbus.ObjectPath, error) {
collection := svc.GetLoginCollection()
search := map[string]string{
"username": user,
"service": service,
}
err := svc.Unlock(collection.Path())
if err != nil {
return "", err
}
results, err := svc.SearchItems(collection, search)
if err != nil {
return "", err
}
if len(results) == 0 {
return "", ErrNotFound
}
return results[0], nil
} | go | func (s secretServiceProvider) findItem(svc *ss.SecretService, service, user string) (dbus.ObjectPath, error) {
collection := svc.GetLoginCollection()
search := map[string]string{
"username": user,
"service": service,
}
err := svc.Unlock(collection.Path())
if err != nil {
return "", err
}
results, err := svc.SearchItems(collection, search)
if err != nil {
return "", err
}
if len(results) == 0 {
return "", ErrNotFound
}
return results[0], nil
} | [
"func",
"(",
"s",
"secretServiceProvider",
")",
"findItem",
"(",
"svc",
"*",
"ss",
".",
"SecretService",
",",
"service",
",",
"user",
"string",
")",
"(",
"dbus",
".",
"ObjectPath",
",",
"error",
")",
"{",
"collection",
":=",
"svc",
".",
"GetLoginCollection... | // findItem looksup an item by service and user. | [
"findItem",
"looksup",
"an",
"item",
"by",
"service",
"and",
"user",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/keyring_linux.go#L51-L74 | train |
zalando/go-keyring | keyring_darwin.go | Set | func (k macOSXKeychain) Set(service, username, password string) error {
return exec.Command(
execPathKeychain,
"add-generic-password",
"-U", //update if exists
"-s", service,
"-a", username,
"-w", password).Run()
} | go | func (k macOSXKeychain) Set(service, username, password string) error {
return exec.Command(
execPathKeychain,
"add-generic-password",
"-U", //update if exists
"-s", service,
"-a", username,
"-w", password).Run()
} | [
"func",
"(",
"k",
"macOSXKeychain",
")",
"Set",
"(",
"service",
",",
"username",
",",
"password",
"string",
")",
"error",
"{",
"return",
"exec",
".",
"Command",
"(",
"execPathKeychain",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"//update if exists",
"\"",
"... | // Set stores a secret in the keyring given a service name and a user. | [
"Set",
"stores",
"a",
"secret",
"in",
"the",
"keyring",
"given",
"a",
"service",
"name",
"and",
"a",
"user",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/keyring_darwin.go#L59-L67 | train |
zalando/go-keyring | keyring.go | Set | func Set(service, user, password string) error {
return provider.Set(service, user, password)
} | go | func Set(service, user, password string) error {
return provider.Set(service, user, password)
} | [
"func",
"Set",
"(",
"service",
",",
"user",
",",
"password",
"string",
")",
"error",
"{",
"return",
"provider",
".",
"Set",
"(",
"service",
",",
"user",
",",
"password",
")",
"\n",
"}"
] | // Set password in keyring for user. | [
"Set",
"password",
"in",
"keyring",
"for",
"user",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/keyring.go#L26-L28 | train |
zalando/go-keyring | keyring.go | Get | func Get(service, user string) (string, error) {
return provider.Get(service, user)
} | go | func Get(service, user string) (string, error) {
return provider.Get(service, user)
} | [
"func",
"Get",
"(",
"service",
",",
"user",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"provider",
".",
"Get",
"(",
"service",
",",
"user",
")",
"\n",
"}"
] | // Get password from keyring given service and user name. | [
"Get",
"password",
"from",
"keyring",
"given",
"service",
"and",
"user",
"name",
"."
] | a1018b80916574299c108cae7fd6c87f481b5265 | https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/keyring.go#L31-L33 | train |
tdewolff/minify | json/json.go | Minify | func (o *Minifier) Minify(_ *minify.M, w io.Writer, r io.Reader, _ map[string]string) error {
skipComma := true
p := json.NewParser(r)
defer p.Restore()
for {
state := p.State()
gt, text := p.Next()
if gt == json.ErrorGrammar {
if p.Err() != io.EOF {
return p.Err()
}
return nil
}
if !skipComma && gt != json.EndObjectGrammar && gt != json.EndArrayGrammar {
if state == json.ObjectKeyState || state == json.ArrayState {
if _, err := w.Write(commaBytes); err != nil {
return err
}
} else if state == json.ObjectValueState {
if _, err := w.Write(colonBytes); err != nil {
return err
}
}
}
skipComma = gt == json.StartObjectGrammar || gt == json.StartArrayGrammar
if _, err := w.Write(text); err != nil {
return err
}
}
} | go | func (o *Minifier) Minify(_ *minify.M, w io.Writer, r io.Reader, _ map[string]string) error {
skipComma := true
p := json.NewParser(r)
defer p.Restore()
for {
state := p.State()
gt, text := p.Next()
if gt == json.ErrorGrammar {
if p.Err() != io.EOF {
return p.Err()
}
return nil
}
if !skipComma && gt != json.EndObjectGrammar && gt != json.EndArrayGrammar {
if state == json.ObjectKeyState || state == json.ArrayState {
if _, err := w.Write(commaBytes); err != nil {
return err
}
} else if state == json.ObjectValueState {
if _, err := w.Write(colonBytes); err != nil {
return err
}
}
}
skipComma = gt == json.StartObjectGrammar || gt == json.StartArrayGrammar
if _, err := w.Write(text); err != nil {
return err
}
}
} | [
"func",
"(",
"o",
"*",
"Minifier",
")",
"Minify",
"(",
"_",
"*",
"minify",
".",
"M",
",",
"w",
"io",
".",
"Writer",
",",
"r",
"io",
".",
"Reader",
",",
"_",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"skipComma",
":=",
"true",
"\n\... | // Minify minifies JSON data, it reads from r and writes to w. | [
"Minify",
"minifies",
"JSON",
"data",
"it",
"reads",
"from",
"r",
"and",
"writes",
"to",
"w",
"."
] | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/json/json.go#L30-L63 | train |
tdewolff/minify | minify.go | Match | func (m *M) Match(mediatype string) (string, map[string]string, MinifierFunc) {
m.mutex.RLock()
defer m.mutex.RUnlock()
mimetype, params := parse.Mediatype([]byte(mediatype))
if minifier, ok := m.literal[string(mimetype)]; ok { // string conversion is optimized away
return string(mimetype), params, minifier.Minify
}
for _, minifier := range m.pattern {
if minifier.pattern.Match(mimetype) {
return minifier.pattern.String(), params, minifier.Minify
}
}
return string(mimetype), params, nil
} | go | func (m *M) Match(mediatype string) (string, map[string]string, MinifierFunc) {
m.mutex.RLock()
defer m.mutex.RUnlock()
mimetype, params := parse.Mediatype([]byte(mediatype))
if minifier, ok := m.literal[string(mimetype)]; ok { // string conversion is optimized away
return string(mimetype), params, minifier.Minify
}
for _, minifier := range m.pattern {
if minifier.pattern.Match(mimetype) {
return minifier.pattern.String(), params, minifier.Minify
}
}
return string(mimetype), params, nil
} | [
"func",
"(",
"m",
"*",
"M",
")",
"Match",
"(",
"mediatype",
"string",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"MinifierFunc",
")",
"{",
"m",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"mutex",
".",
... | // Match returns the pattern and minifier that gets matched with the mediatype.
// It returns nil when no matching minifier exists.
// It has the same matching algorithm as Minify. | [
"Match",
"returns",
"the",
"pattern",
"and",
"minifier",
"that",
"gets",
"matched",
"with",
"the",
"mediatype",
".",
"It",
"returns",
"nil",
"when",
"no",
"matching",
"minifier",
"exists",
".",
"It",
"has",
"the",
"same",
"matching",
"algorithm",
"as",
"Mini... | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L125-L140 | train |
tdewolff/minify | minify.go | Reader | func (m *M) Reader(mediatype string, r io.Reader) io.Reader {
pr, pw := io.Pipe()
go func() {
if err := m.Minify(mediatype, pw, r); err != nil {
pw.CloseWithError(err)
} else {
pw.Close()
}
}()
return pr
} | go | func (m *M) Reader(mediatype string, r io.Reader) io.Reader {
pr, pw := io.Pipe()
go func() {
if err := m.Minify(mediatype, pw, r); err != nil {
pw.CloseWithError(err)
} else {
pw.Close()
}
}()
return pr
} | [
"func",
"(",
"m",
"*",
"M",
")",
"Reader",
"(",
"mediatype",
"string",
",",
"r",
"io",
".",
"Reader",
")",
"io",
".",
"Reader",
"{",
"pr",
",",
"pw",
":=",
"io",
".",
"Pipe",
"(",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"... | // Reader wraps a Reader interface and minifies the stream.
// Errors from the minifier are returned by the reader. | [
"Reader",
"wraps",
"a",
"Reader",
"interface",
"and",
"minifies",
"the",
"stream",
".",
"Errors",
"from",
"the",
"minifier",
"are",
"returned",
"by",
"the",
"reader",
"."
] | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L193-L203 | train |
tdewolff/minify | minify.go | Write | func (w *minifyWriter) Write(b []byte) (int, error) {
return w.pw.Write(b)
} | go | func (w *minifyWriter) Write(b []byte) (int, error) {
return w.pw.Write(b)
} | [
"func",
"(",
"w",
"*",
"minifyWriter",
")",
"Write",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"w",
".",
"pw",
".",
"Write",
"(",
"b",
")",
"\n",
"}"
] | // Write intercepts any writes to the writer. | [
"Write",
"intercepts",
"any",
"writes",
"to",
"the",
"writer",
"."
] | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L213-L215 | train |
tdewolff/minify | minify.go | Writer | func (m *M) Writer(mediatype string, w io.Writer) *minifyWriter {
pr, pw := io.Pipe()
mw := &minifyWriter{pw, sync.WaitGroup{}, nil}
mw.wg.Add(1)
go func() {
defer mw.wg.Done()
if err := m.Minify(mediatype, w, pr); err != nil {
io.Copy(w, pr)
mw.err = err
}
pr.Close()
}()
return mw
} | go | func (m *M) Writer(mediatype string, w io.Writer) *minifyWriter {
pr, pw := io.Pipe()
mw := &minifyWriter{pw, sync.WaitGroup{}, nil}
mw.wg.Add(1)
go func() {
defer mw.wg.Done()
if err := m.Minify(mediatype, w, pr); err != nil {
io.Copy(w, pr)
mw.err = err
}
pr.Close()
}()
return mw
} | [
"func",
"(",
"m",
"*",
"M",
")",
"Writer",
"(",
"mediatype",
"string",
",",
"w",
"io",
".",
"Writer",
")",
"*",
"minifyWriter",
"{",
"pr",
",",
"pw",
":=",
"io",
".",
"Pipe",
"(",
")",
"\n",
"mw",
":=",
"&",
"minifyWriter",
"{",
"pw",
",",
"syn... | // Writer wraps a Writer interface and minifies the stream.
// Errors from the minifier are returned by Close on the writer.
// The writer must be closed explicitly. | [
"Writer",
"wraps",
"a",
"Writer",
"interface",
"and",
"minifies",
"the",
"stream",
".",
"Errors",
"from",
"the",
"minifier",
"are",
"returned",
"by",
"Close",
"on",
"the",
"writer",
".",
"The",
"writer",
"must",
"be",
"closed",
"explicitly",
"."
] | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L227-L241 | train |
tdewolff/minify | minify.go | WriteHeader | func (w *minifyResponseWriter) WriteHeader(status int) {
w.ResponseWriter.Header().Del("Content-Length")
w.ResponseWriter.WriteHeader(status)
} | go | func (w *minifyResponseWriter) WriteHeader(status int) {
w.ResponseWriter.Header().Del("Content-Length")
w.ResponseWriter.WriteHeader(status)
} | [
"func",
"(",
"w",
"*",
"minifyResponseWriter",
")",
"WriteHeader",
"(",
"status",
"int",
")",
"{",
"w",
".",
"ResponseWriter",
".",
"Header",
"(",
")",
".",
"Del",
"(",
"\"",
"\"",
")",
"\n",
"w",
".",
"ResponseWriter",
".",
"WriteHeader",
"(",
"status... | // WriteHeader intercepts any header writes and removes the Content-Length header. | [
"WriteHeader",
"intercepts",
"any",
"header",
"writes",
"and",
"removes",
"the",
"Content",
"-",
"Length",
"header",
"."
] | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L255-L258 | train |
tdewolff/minify | minify.go | Write | func (w *minifyResponseWriter) Write(b []byte) (int, error) {
if w.writer == nil {
// first write
if mediatype := w.ResponseWriter.Header().Get("Content-Type"); mediatype != "" {
w.mediatype = mediatype
}
w.writer = w.m.Writer(w.mediatype, w.ResponseWriter)
}
return w.writer.Write(b)
} | go | func (w *minifyResponseWriter) Write(b []byte) (int, error) {
if w.writer == nil {
// first write
if mediatype := w.ResponseWriter.Header().Get("Content-Type"); mediatype != "" {
w.mediatype = mediatype
}
w.writer = w.m.Writer(w.mediatype, w.ResponseWriter)
}
return w.writer.Write(b)
} | [
"func",
"(",
"w",
"*",
"minifyResponseWriter",
")",
"Write",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"w",
".",
"writer",
"==",
"nil",
"{",
"// first write",
"if",
"mediatype",
":=",
"w",
".",
"ResponseWriter",
".",
... | // Write intercepts any writes to the response writer.
// The first write will extract the Content-Type as the mediatype. Otherwise it falls back to the RequestURI extension. | [
"Write",
"intercepts",
"any",
"writes",
"to",
"the",
"response",
"writer",
".",
"The",
"first",
"write",
"will",
"extract",
"the",
"Content",
"-",
"Type",
"as",
"the",
"mediatype",
".",
"Otherwise",
"it",
"falls",
"back",
"to",
"the",
"RequestURI",
"extensio... | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L262-L271 | train |
tdewolff/minify | minify.go | ResponseWriter | func (m *M) ResponseWriter(w http.ResponseWriter, r *http.Request) *minifyResponseWriter {
mediatype := mime.TypeByExtension(path.Ext(r.RequestURI))
return &minifyResponseWriter{w, nil, m, mediatype}
} | go | func (m *M) ResponseWriter(w http.ResponseWriter, r *http.Request) *minifyResponseWriter {
mediatype := mime.TypeByExtension(path.Ext(r.RequestURI))
return &minifyResponseWriter{w, nil, m, mediatype}
} | [
"func",
"(",
"m",
"*",
"M",
")",
"ResponseWriter",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"*",
"minifyResponseWriter",
"{",
"mediatype",
":=",
"mime",
".",
"TypeByExtension",
"(",
"path",
".",
"Ext",
"(",
"... | // ResponseWriter minifies any writes to the http.ResponseWriter.
// http.ResponseWriter loses all functionality such as Pusher, Hijacker, Flusher, ...
// Minification might be slower than just sending the original file! Caching is advised. | [
"ResponseWriter",
"minifies",
"any",
"writes",
"to",
"the",
"http",
".",
"ResponseWriter",
".",
"http",
".",
"ResponseWriter",
"loses",
"all",
"functionality",
"such",
"as",
"Pusher",
"Hijacker",
"Flusher",
"...",
"Minification",
"might",
"be",
"slower",
"than",
... | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L284-L287 | train |
tdewolff/minify | minify.go | Middleware | func (m *M) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mw := m.ResponseWriter(w, r)
defer mw.Close()
next.ServeHTTP(mw, r)
})
} | go | func (m *M) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mw := m.ResponseWriter(w, r)
defer mw.Close()
next.ServeHTTP(mw, r)
})
} | [
"func",
"(",
"m",
"*",
"M",
")",
"Middleware",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
... | // Middleware provides a middleware function that minifies content on the fly by intercepting writes to http.ResponseWriter.
// http.ResponseWriter loses all functionality such as Pusher, Hijacker, Flusher, ...
// Minification might be slower than just sending the original file! Caching is advised. | [
"Middleware",
"provides",
"a",
"middleware",
"function",
"that",
"minifies",
"content",
"on",
"the",
"fly",
"by",
"intercepting",
"writes",
"to",
"http",
".",
"ResponseWriter",
".",
"http",
".",
"ResponseWriter",
"loses",
"all",
"functionality",
"such",
"as",
"P... | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L292-L299 | train |
tdewolff/minify | xml/buffer.go | Peek | func (z *TokenBuffer) Peek(pos int) *Token {
pos += z.pos
if pos >= len(z.buf) {
if len(z.buf) > 0 && z.buf[len(z.buf)-1].TokenType == xml.ErrorToken {
return &z.buf[len(z.buf)-1]
}
c := cap(z.buf)
d := len(z.buf) - z.pos
p := pos - z.pos + 1 // required peek length
var buf []Token
if 2*p > c {
buf = make([]Token, 0, 2*c+p)
} else {
buf = z.buf
}
copy(buf[:d], z.buf[z.pos:])
buf = buf[:p]
pos -= z.pos
for i := d; i < p; i++ {
z.read(&buf[i])
if buf[i].TokenType == xml.ErrorToken {
buf = buf[:i+1]
pos = i
break
}
}
z.pos, z.buf = 0, buf
}
return &z.buf[pos]
} | go | func (z *TokenBuffer) Peek(pos int) *Token {
pos += z.pos
if pos >= len(z.buf) {
if len(z.buf) > 0 && z.buf[len(z.buf)-1].TokenType == xml.ErrorToken {
return &z.buf[len(z.buf)-1]
}
c := cap(z.buf)
d := len(z.buf) - z.pos
p := pos - z.pos + 1 // required peek length
var buf []Token
if 2*p > c {
buf = make([]Token, 0, 2*c+p)
} else {
buf = z.buf
}
copy(buf[:d], z.buf[z.pos:])
buf = buf[:p]
pos -= z.pos
for i := d; i < p; i++ {
z.read(&buf[i])
if buf[i].TokenType == xml.ErrorToken {
buf = buf[:i+1]
pos = i
break
}
}
z.pos, z.buf = 0, buf
}
return &z.buf[pos]
} | [
"func",
"(",
"z",
"*",
"TokenBuffer",
")",
"Peek",
"(",
"pos",
"int",
")",
"*",
"Token",
"{",
"pos",
"+=",
"z",
".",
"pos",
"\n",
"if",
"pos",
">=",
"len",
"(",
"z",
".",
"buf",
")",
"{",
"if",
"len",
"(",
"z",
".",
"buf",
")",
">",
"0",
... | // Peek returns the ith element and possibly does an allocation.
// Peeking past an error will panic. | [
"Peek",
"returns",
"the",
"ith",
"element",
"and",
"possibly",
"does",
"an",
"allocation",
".",
"Peeking",
"past",
"an",
"error",
"will",
"panic",
"."
] | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/xml/buffer.go#L41-L72 | train |
tdewolff/minify | xml/buffer.go | Shift | func (z *TokenBuffer) Shift() *Token {
if z.pos >= len(z.buf) {
t := &z.buf[:1][0]
z.read(t)
return t
}
t := &z.buf[z.pos]
z.pos++
return t
} | go | func (z *TokenBuffer) Shift() *Token {
if z.pos >= len(z.buf) {
t := &z.buf[:1][0]
z.read(t)
return t
}
t := &z.buf[z.pos]
z.pos++
return t
} | [
"func",
"(",
"z",
"*",
"TokenBuffer",
")",
"Shift",
"(",
")",
"*",
"Token",
"{",
"if",
"z",
".",
"pos",
">=",
"len",
"(",
"z",
".",
"buf",
")",
"{",
"t",
":=",
"&",
"z",
".",
"buf",
"[",
":",
"1",
"]",
"[",
"0",
"]",
"\n",
"z",
".",
"re... | // Shift returns the first element and advances position. | [
"Shift",
"returns",
"the",
"first",
"element",
"and",
"advances",
"position",
"."
] | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/xml/buffer.go#L75-L84 | train |
tdewolff/minify | common.go | Mediatype | func Mediatype(b []byte) []byte {
j := 0
start := 0
inString := false
for i, c := range b {
if !inString && parse.IsWhitespace(c) {
if start != 0 {
j += copy(b[j:], b[start:i])
} else {
j += i
}
start = i + 1
} else if c == '"' {
inString = !inString
}
}
if start != 0 {
j += copy(b[j:], b[start:])
return parse.ToLower(b[:j])
}
return parse.ToLower(b)
} | go | func Mediatype(b []byte) []byte {
j := 0
start := 0
inString := false
for i, c := range b {
if !inString && parse.IsWhitespace(c) {
if start != 0 {
j += copy(b[j:], b[start:i])
} else {
j += i
}
start = i + 1
} else if c == '"' {
inString = !inString
}
}
if start != 0 {
j += copy(b[j:], b[start:])
return parse.ToLower(b[:j])
}
return parse.ToLower(b)
} | [
"func",
"Mediatype",
"(",
"b",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"j",
":=",
"0",
"\n",
"start",
":=",
"0",
"\n",
"inString",
":=",
"false",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
"b",
"{",
"if",
"!",
"inString",
"&&",
"parse",
... | // Mediatype minifies a given mediatype by removing all whitespace. | [
"Mediatype",
"minifies",
"a",
"given",
"mediatype",
"by",
"removing",
"all",
"whitespace",
"."
] | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/common.go#L16-L37 | train |
tdewolff/minify | svg/buffer.go | Attributes | func (z *TokenBuffer) Attributes(hashes ...svg.Hash) ([]*Token, *Token) {
n := 0
for {
if t := z.Peek(n); t.TokenType != xml.AttributeToken {
break
}
n++
}
if len(hashes) > cap(z.attrBuffer) {
z.attrBuffer = make([]*Token, len(hashes))
} else {
z.attrBuffer = z.attrBuffer[:len(hashes)]
for i := range z.attrBuffer {
z.attrBuffer[i] = nil
}
}
var replacee *Token
for i := z.pos; i < z.pos+n; i++ {
attr := &z.buf[i]
for j, hash := range hashes {
if hash == attr.Hash {
z.attrBuffer[j] = attr
replacee = attr
}
}
}
return z.attrBuffer, replacee
} | go | func (z *TokenBuffer) Attributes(hashes ...svg.Hash) ([]*Token, *Token) {
n := 0
for {
if t := z.Peek(n); t.TokenType != xml.AttributeToken {
break
}
n++
}
if len(hashes) > cap(z.attrBuffer) {
z.attrBuffer = make([]*Token, len(hashes))
} else {
z.attrBuffer = z.attrBuffer[:len(hashes)]
for i := range z.attrBuffer {
z.attrBuffer[i] = nil
}
}
var replacee *Token
for i := z.pos; i < z.pos+n; i++ {
attr := &z.buf[i]
for j, hash := range hashes {
if hash == attr.Hash {
z.attrBuffer[j] = attr
replacee = attr
}
}
}
return z.attrBuffer, replacee
} | [
"func",
"(",
"z",
"*",
"TokenBuffer",
")",
"Attributes",
"(",
"hashes",
"...",
"svg",
".",
"Hash",
")",
"(",
"[",
"]",
"*",
"Token",
",",
"*",
"Token",
")",
"{",
"n",
":=",
"0",
"\n",
"for",
"{",
"if",
"t",
":=",
"z",
".",
"Peek",
"(",
"n",
... | // Attributes extracts the gives attribute hashes from a tag.
// It returns in the same order pointers to the requested token data or nil. | [
"Attributes",
"extracts",
"the",
"gives",
"attribute",
"hashes",
"from",
"a",
"tag",
".",
"It",
"returns",
"in",
"the",
"same",
"order",
"pointers",
"to",
"the",
"requested",
"token",
"data",
"or",
"nil",
"."
] | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/svg/buffer.go#L103-L130 | train |
tdewolff/minify | svg/pathdata.go | shortenCurPosInstruction | func (p *PathData) shortenCurPosInstruction(cmd byte, coords [][]byte) PathDataState {
state := p.state
p.curBuffer = p.curBuffer[:0]
if cmd != state.cmd && !(state.cmd == 'M' && cmd == 'L' || state.cmd == 'm' && cmd == 'l') {
p.curBuffer = append(p.curBuffer, cmd)
state.cmd = cmd
state.prevDigit = false
state.prevDigitIsInt = false
}
for i, coord := range coords {
isFlag := false
// Arc has boolean flags that can only be 0 or 1. Setting isFlag prevents from adding a dot before a zero (instead of a space). However, when the dot already was there, the command is malformed and could make the path longer than before, introducing bugs.
if (cmd == 'A' || cmd == 'a') && (i%7 == 3 || i%7 == 4) && coord[0] != '.' {
isFlag = true
}
coord = minify.Number(coord, p.o.Decimals)
state.copyNumber(&p.curBuffer, coord, isFlag)
}
return state
} | go | func (p *PathData) shortenCurPosInstruction(cmd byte, coords [][]byte) PathDataState {
state := p.state
p.curBuffer = p.curBuffer[:0]
if cmd != state.cmd && !(state.cmd == 'M' && cmd == 'L' || state.cmd == 'm' && cmd == 'l') {
p.curBuffer = append(p.curBuffer, cmd)
state.cmd = cmd
state.prevDigit = false
state.prevDigitIsInt = false
}
for i, coord := range coords {
isFlag := false
// Arc has boolean flags that can only be 0 or 1. Setting isFlag prevents from adding a dot before a zero (instead of a space). However, when the dot already was there, the command is malformed and could make the path longer than before, introducing bugs.
if (cmd == 'A' || cmd == 'a') && (i%7 == 3 || i%7 == 4) && coord[0] != '.' {
isFlag = true
}
coord = minify.Number(coord, p.o.Decimals)
state.copyNumber(&p.curBuffer, coord, isFlag)
}
return state
} | [
"func",
"(",
"p",
"*",
"PathData",
")",
"shortenCurPosInstruction",
"(",
"cmd",
"byte",
",",
"coords",
"[",
"]",
"[",
"]",
"byte",
")",
"PathDataState",
"{",
"state",
":=",
"p",
".",
"state",
"\n",
"p",
".",
"curBuffer",
"=",
"p",
".",
"curBuffer",
"... | // shortenCurPosInstruction only minifies the coordinates. | [
"shortenCurPosInstruction",
"only",
"minifies",
"the",
"coordinates",
"."
] | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/svg/pathdata.go#L297-L317 | train |
tdewolff/minify | svg/pathdata.go | copyNumber | func (state *PathDataState) copyNumber(buffer *[]byte, coord []byte, isFlag bool) {
if state.prevDigit && (coord[0] >= '0' && coord[0] <= '9' || coord[0] == '.' && state.prevDigitIsInt) {
if coord[0] == '0' && !state.prevDigitIsInt {
if isFlag {
*buffer = append(*buffer, ' ', '0')
state.prevDigitIsInt = true
} else {
*buffer = append(*buffer, '.', '0') // aggresively add dot so subsequent numbers could drop leading space
// prevDigit stays true and prevDigitIsInt stays false
}
return
}
*buffer = append(*buffer, ' ')
}
state.prevDigit = true
state.prevDigitIsInt = true
if len(coord) > 2 && coord[len(coord)-2] == '0' && coord[len(coord)-1] == '0' {
coord[len(coord)-2] = 'e'
coord[len(coord)-1] = '2'
state.prevDigitIsInt = false
} else {
for _, c := range coord {
if c == '.' || c == 'e' || c == 'E' {
state.prevDigitIsInt = false
break
}
}
}
*buffer = append(*buffer, coord...)
} | go | func (state *PathDataState) copyNumber(buffer *[]byte, coord []byte, isFlag bool) {
if state.prevDigit && (coord[0] >= '0' && coord[0] <= '9' || coord[0] == '.' && state.prevDigitIsInt) {
if coord[0] == '0' && !state.prevDigitIsInt {
if isFlag {
*buffer = append(*buffer, ' ', '0')
state.prevDigitIsInt = true
} else {
*buffer = append(*buffer, '.', '0') // aggresively add dot so subsequent numbers could drop leading space
// prevDigit stays true and prevDigitIsInt stays false
}
return
}
*buffer = append(*buffer, ' ')
}
state.prevDigit = true
state.prevDigitIsInt = true
if len(coord) > 2 && coord[len(coord)-2] == '0' && coord[len(coord)-1] == '0' {
coord[len(coord)-2] = 'e'
coord[len(coord)-1] = '2'
state.prevDigitIsInt = false
} else {
for _, c := range coord {
if c == '.' || c == 'e' || c == 'E' {
state.prevDigitIsInt = false
break
}
}
}
*buffer = append(*buffer, coord...)
} | [
"func",
"(",
"state",
"*",
"PathDataState",
")",
"copyNumber",
"(",
"buffer",
"*",
"[",
"]",
"byte",
",",
"coord",
"[",
"]",
"byte",
",",
"isFlag",
"bool",
")",
"{",
"if",
"state",
".",
"prevDigit",
"&&",
"(",
"coord",
"[",
"0",
"]",
">=",
"'0'",
... | // copyNumber will copy a number to the destination buffer, taking into account space or dot insertion to guarantee the shortest pathdata. | [
"copyNumber",
"will",
"copy",
"a",
"number",
"to",
"the",
"destination",
"buffer",
"taking",
"into",
"account",
"space",
"or",
"dot",
"insertion",
"to",
"guarantee",
"the",
"shortest",
"pathdata",
"."
] | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/svg/pathdata.go#L359-L388 | train |
tdewolff/minify | cmd/minify/util.go | NewConcatFileReader | func NewConcatFileReader(filenames []string, opener func(string) (io.ReadCloser, error)) (*concatFileReader, error) {
var cur io.ReadCloser
if len(filenames) > 0 {
var filename string
filename, filenames = filenames[0], filenames[1:]
var err error
if cur, err = opener(filename); err != nil {
return nil, err
}
} else {
cur = eofReader{}
}
return &concatFileReader{filenames, opener, nil, cur, 0}, nil
} | go | func NewConcatFileReader(filenames []string, opener func(string) (io.ReadCloser, error)) (*concatFileReader, error) {
var cur io.ReadCloser
if len(filenames) > 0 {
var filename string
filename, filenames = filenames[0], filenames[1:]
var err error
if cur, err = opener(filename); err != nil {
return nil, err
}
} else {
cur = eofReader{}
}
return &concatFileReader{filenames, opener, nil, cur, 0}, nil
} | [
"func",
"NewConcatFileReader",
"(",
"filenames",
"[",
"]",
"string",
",",
"opener",
"func",
"(",
"string",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
")",
"(",
"*",
"concatFileReader",
",",
"error",
")",
"{",
"var",
"cur",
"io",
".",
"ReadCl... | // NewConcatFileReader reads from a list of filenames, and lazily loads files as it needs it.
// It is a reader that reads a concatenation of those files separated by the separator.
// You must call Close to close the last file in the list. | [
"NewConcatFileReader",
"reads",
"from",
"a",
"list",
"of",
"filenames",
"and",
"lazily",
"loads",
"files",
"as",
"it",
"needs",
"it",
".",
"It",
"is",
"a",
"reader",
"that",
"reads",
"a",
"concatenation",
"of",
"those",
"files",
"separated",
"by",
"the",
"... | 2524af8f5589b64967cb0dd441af44b9b3bc02a8 | https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/cmd/minify/util.go#L59-L73 | train |
heetch/confita | backend/etcd/etcd.go | NewBackend | func NewBackend(client *clientv3.Client, opts ...Option) *Backend {
b := Backend{
client: client,
}
for _, opt := range opts {
opt(&b)
}
return &b
} | go | func NewBackend(client *clientv3.Client, opts ...Option) *Backend {
b := Backend{
client: client,
}
for _, opt := range opts {
opt(&b)
}
return &b
} | [
"func",
"NewBackend",
"(",
"client",
"*",
"clientv3",
".",
"Client",
",",
"opts",
"...",
"Option",
")",
"*",
"Backend",
"{",
"b",
":=",
"Backend",
"{",
"client",
":",
"client",
",",
"}",
"\n\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"... | // NewBackend creates a configuration loader that loads from etcd. | [
"NewBackend",
"creates",
"a",
"configuration",
"loader",
"that",
"loads",
"from",
"etcd",
"."
] | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/etcd/etcd.go#L21-L31 | train |
heetch/confita | backend/etcd/etcd.go | Get | func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) {
if b.cache == nil && b.prefetch {
err := b.fetchTree(ctx)
if err != nil {
return nil, err
}
}
if b.cache != nil {
return b.fromCache(ctx, key)
}
resp, err := b.client.Get(ctx, path.Join(b.prefix, key))
if err != nil {
return nil, err
}
if len(resp.Kvs) == 0 {
return nil, backend.ErrNotFound
}
return resp.Kvs[0].Value, nil
} | go | func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) {
if b.cache == nil && b.prefetch {
err := b.fetchTree(ctx)
if err != nil {
return nil, err
}
}
if b.cache != nil {
return b.fromCache(ctx, key)
}
resp, err := b.client.Get(ctx, path.Join(b.prefix, key))
if err != nil {
return nil, err
}
if len(resp.Kvs) == 0 {
return nil, backend.ErrNotFound
}
return resp.Kvs[0].Value, nil
} | [
"func",
"(",
"b",
"*",
"Backend",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"b",
".",
"cache",
"==",
"nil",
"&&",
"b",
".",
"prefetch",
"{",
"err",
":=",
... | // Get loads the given key from etcd. | [
"Get",
"loads",
"the",
"given",
"key",
"from",
"etcd",
"."
] | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/etcd/etcd.go#L34-L56 | train |
heetch/confita | backend/backend.go | Func | func Func(name string, fn func(context.Context, string) ([]byte, error)) Backend {
return &backendFunc{fn: fn, name: name}
} | go | func Func(name string, fn func(context.Context, string) ([]byte, error)) Backend {
return &backendFunc{fn: fn, name: name}
} | [
"func",
"Func",
"(",
"name",
"string",
",",
"fn",
"func",
"(",
"context",
".",
"Context",
",",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
")",
"Backend",
"{",
"return",
"&",
"backendFunc",
"{",
"fn",
":",
"fn",
",",
"name",
":",
"na... | // Func creates a Backend from a function. | [
"Func",
"creates",
"a",
"Backend",
"from",
"a",
"function",
"."
] | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/backend.go#L20-L22 | train |
heetch/confita | backend/flags/flags.go | LoadStruct | func (b *Backend) LoadStruct(ctx context.Context, cfg *confita.StructConfig) error {
for _, field := range cfg.Fields {
f := field
if f.Backend != "" && f.Backend != b.Name() {
continue
}
// Display all the flags and their default values but override the field only if the user has explicitely
// set the flag.
k := f.Value.Kind()
switch {
case f.Value.Type().String() == "time.Duration":
// define the flag and its default value
v := flag.Duration(f.Key, time.Duration(f.Default.Int()), "")
// this function must be executed after the flag.Parse call.
defer func() {
// if the user has set the flag, save the value in the field.
if isFlagSet(f.Key) {
f.Value.SetInt(int64(*v))
}
}()
case k == reflect.Bool:
v := flag.Bool(f.Key, f.Default.Bool(), "")
defer func() {
if isFlagSet(f.Key) {
f.Value.SetBool(*v)
}
}()
case k >= reflect.Int && k <= reflect.Int64:
v := flag.Int(f.Key, int(f.Default.Int()), "")
defer func() {
if isFlagSet(f.Key) {
f.Value.SetInt(int64(*v))
}
}()
case k >= reflect.Uint && k <= reflect.Uint64:
v := flag.Uint(f.Key, uint(f.Default.Uint()), "")
defer func() {
if isFlagSet(f.Key) {
f.Value.SetUint(uint64(*v))
}
}()
case k >= reflect.Float32 && k <= reflect.Float64:
v := flag.Float64(f.Key, f.Default.Float(), "")
defer func() {
if isFlagSet(f.Key) {
f.Value.SetFloat(*v)
}
}()
case k == reflect.String:
v := flag.String(f.Key, f.Default.String(), "")
defer func() {
if isFlagSet(f.Key) {
f.Value.SetString(*v)
}
}()
default:
flag.Var(&flagValue{f}, f.Key, "")
}
}
flag.Parse()
return nil
} | go | func (b *Backend) LoadStruct(ctx context.Context, cfg *confita.StructConfig) error {
for _, field := range cfg.Fields {
f := field
if f.Backend != "" && f.Backend != b.Name() {
continue
}
// Display all the flags and their default values but override the field only if the user has explicitely
// set the flag.
k := f.Value.Kind()
switch {
case f.Value.Type().String() == "time.Duration":
// define the flag and its default value
v := flag.Duration(f.Key, time.Duration(f.Default.Int()), "")
// this function must be executed after the flag.Parse call.
defer func() {
// if the user has set the flag, save the value in the field.
if isFlagSet(f.Key) {
f.Value.SetInt(int64(*v))
}
}()
case k == reflect.Bool:
v := flag.Bool(f.Key, f.Default.Bool(), "")
defer func() {
if isFlagSet(f.Key) {
f.Value.SetBool(*v)
}
}()
case k >= reflect.Int && k <= reflect.Int64:
v := flag.Int(f.Key, int(f.Default.Int()), "")
defer func() {
if isFlagSet(f.Key) {
f.Value.SetInt(int64(*v))
}
}()
case k >= reflect.Uint && k <= reflect.Uint64:
v := flag.Uint(f.Key, uint(f.Default.Uint()), "")
defer func() {
if isFlagSet(f.Key) {
f.Value.SetUint(uint64(*v))
}
}()
case k >= reflect.Float32 && k <= reflect.Float64:
v := flag.Float64(f.Key, f.Default.Float(), "")
defer func() {
if isFlagSet(f.Key) {
f.Value.SetFloat(*v)
}
}()
case k == reflect.String:
v := flag.String(f.Key, f.Default.String(), "")
defer func() {
if isFlagSet(f.Key) {
f.Value.SetString(*v)
}
}()
default:
flag.Var(&flagValue{f}, f.Key, "")
}
}
flag.Parse()
return nil
} | [
"func",
"(",
"b",
"*",
"Backend",
")",
"LoadStruct",
"(",
"ctx",
"context",
".",
"Context",
",",
"cfg",
"*",
"confita",
".",
"StructConfig",
")",
"error",
"{",
"for",
"_",
",",
"field",
":=",
"range",
"cfg",
".",
"Fields",
"{",
"f",
":=",
"field",
... | // LoadStruct takes a struct config, define flags based on it and parse the command line args. | [
"LoadStruct",
"takes",
"a",
"struct",
"config",
"define",
"flags",
"based",
"on",
"it",
"and",
"parse",
"the",
"command",
"line",
"args",
"."
] | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/flags/flags.go#L22-L87 | train |
heetch/confita | backend/flags/flags.go | Get | func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) {
return nil, errors.New("not implemented")
} | go | func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) {
return nil, errors.New("not implemented")
} | [
"func",
"(",
"b",
"*",
"Backend",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Get is not implemented. | [
"Get",
"is",
"not",
"implemented",
"."
] | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/flags/flags.go#L106-L108 | train |
heetch/confita | backend/consul/consul.go | Get | func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) {
if b.cache == nil && b.prefetch {
err := b.fetchTree(ctx)
if err != nil {
return nil, err
}
}
if b.cache != nil {
return b.fromCache(ctx, key)
}
var opt api.QueryOptions
kv, _, err := b.client.KV().Get(path.Join(b.prefix, key), opt.WithContext(ctx))
if err != nil {
return nil, err
}
if kv == nil {
return nil, backend.ErrNotFound
}
return kv.Value, nil
} | go | func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) {
if b.cache == nil && b.prefetch {
err := b.fetchTree(ctx)
if err != nil {
return nil, err
}
}
if b.cache != nil {
return b.fromCache(ctx, key)
}
var opt api.QueryOptions
kv, _, err := b.client.KV().Get(path.Join(b.prefix, key), opt.WithContext(ctx))
if err != nil {
return nil, err
}
if kv == nil {
return nil, backend.ErrNotFound
}
return kv.Value, nil
} | [
"func",
"(",
"b",
"*",
"Backend",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"b",
".",
"cache",
"==",
"nil",
"&&",
"b",
".",
"prefetch",
"{",
"err",
":=",
... | // Get loads the given key from Consul. | [
"Get",
"loads",
"the",
"given",
"key",
"from",
"Consul",
"."
] | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/consul/consul.go#L34-L58 | train |
heetch/confita | backend/env/env.go | NewBackend | func NewBackend() backend.Backend {
return backend.Func("env", func(ctx context.Context, key string) ([]byte, error) {
val, ok := os.LookupEnv(key)
if ok {
return []byte(val), nil
}
key = strings.Replace(strings.ToUpper(key), "-", "_", -1)
val, ok = os.LookupEnv(key)
if ok {
return []byte(val), nil
}
return nil, backend.ErrNotFound
})
} | go | func NewBackend() backend.Backend {
return backend.Func("env", func(ctx context.Context, key string) ([]byte, error) {
val, ok := os.LookupEnv(key)
if ok {
return []byte(val), nil
}
key = strings.Replace(strings.ToUpper(key), "-", "_", -1)
val, ok = os.LookupEnv(key)
if ok {
return []byte(val), nil
}
return nil, backend.ErrNotFound
})
} | [
"func",
"NewBackend",
"(",
")",
"backend",
".",
"Backend",
"{",
"return",
"backend",
".",
"Func",
"(",
"\"",
"\"",
",",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"val",
... | // NewBackend creates a configuration loader that loads from the environment.
// If the key is not found, this backend tries again by turning any kebabcase key to snakecase and
// lowercase letters to uppercase. | [
"NewBackend",
"creates",
"a",
"configuration",
"loader",
"that",
"loads",
"from",
"the",
"environment",
".",
"If",
"the",
"key",
"is",
"not",
"found",
"this",
"backend",
"tries",
"again",
"by",
"turning",
"any",
"kebabcase",
"key",
"to",
"snakecase",
"and",
... | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/env/env.go#L14-L30 | train |
heetch/confita | config.go | NewLoader | func NewLoader(backends ...backend.Backend) *Loader {
l := Loader{
backends: backends,
}
if len(l.backends) == 0 {
l.backends = append(l.backends, env.NewBackend())
}
return &l
} | go | func NewLoader(backends ...backend.Backend) *Loader {
l := Loader{
backends: backends,
}
if len(l.backends) == 0 {
l.backends = append(l.backends, env.NewBackend())
}
return &l
} | [
"func",
"NewLoader",
"(",
"backends",
"...",
"backend",
".",
"Backend",
")",
"*",
"Loader",
"{",
"l",
":=",
"Loader",
"{",
"backends",
":",
"backends",
",",
"}",
"\n\n",
"if",
"len",
"(",
"l",
".",
"backends",
")",
"==",
"0",
"{",
"l",
".",
"backen... | // NewLoader creates a Loader. If no backend is specified, the loader uses the environment. | [
"NewLoader",
"creates",
"a",
"Loader",
".",
"If",
"no",
"backend",
"is",
"specified",
"the",
"loader",
"uses",
"the",
"environment",
"."
] | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/config.go#L27-L37 | train |
heetch/confita | config.go | Load | func (l *Loader) Load(ctx context.Context, to interface{}) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
ref := reflect.ValueOf(to)
if !ref.IsValid() || ref.Kind() != reflect.Ptr || ref.Elem().Kind() != reflect.Struct {
return errors.New("provided target must be a pointer to struct")
}
ref = ref.Elem()
s := l.parseStruct(&ref)
s.S = to
return l.resolve(ctx, s)
} | go | func (l *Loader) Load(ctx context.Context, to interface{}) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
ref := reflect.ValueOf(to)
if !ref.IsValid() || ref.Kind() != reflect.Ptr || ref.Elem().Kind() != reflect.Struct {
return errors.New("provided target must be a pointer to struct")
}
ref = ref.Elem()
s := l.parseStruct(&ref)
s.S = to
return l.resolve(ctx, s)
} | [
"func",
"(",
"l",
"*",
"Loader",
")",
"Load",
"(",
"ctx",
"context",
".",
"Context",
",",
"to",
"interface",
"{",
"}",
")",
"error",
"{",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"ctx",
".",
"Err",
"(",
")",
"\n... | // Load analyses all the Fields of the given struct for a "config" tag and queries each backend
// in order for the corresponding key. The given context can be used for timeout and cancelation. | [
"Load",
"analyses",
"all",
"the",
"Fields",
"of",
"the",
"given",
"struct",
"for",
"a",
"config",
"tag",
"and",
"queries",
"each",
"backend",
"in",
"order",
"for",
"the",
"corresponding",
"key",
".",
"The",
"given",
"context",
"can",
"be",
"used",
"for",
... | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/config.go#L41-L59 | train |
heetch/confita | config.go | Set | func (f *FieldConfig) Set(data string) error {
return convert(data, f.Value)
} | go | func (f *FieldConfig) Set(data string) error {
return convert(data, f.Value)
} | [
"func",
"(",
"f",
"*",
"FieldConfig",
")",
"Set",
"(",
"data",
"string",
")",
"error",
"{",
"return",
"convert",
"(",
"data",
",",
"f",
".",
"Value",
")",
"\n",
"}"
] | // Set converts data into f.Value. | [
"Set",
"converts",
"data",
"into",
"f",
".",
"Value",
"."
] | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/config.go#L226-L228 | train |
heetch/confita | backend/vault/vault.go | NewBackend | func NewBackend(client *api.Logical, path string) *Backend {
return &Backend{
client: client,
path: path,
}
} | go | func NewBackend(client *api.Logical, path string) *Backend {
return &Backend{
client: client,
path: path,
}
} | [
"func",
"NewBackend",
"(",
"client",
"*",
"api",
".",
"Logical",
",",
"path",
"string",
")",
"*",
"Backend",
"{",
"return",
"&",
"Backend",
"{",
"client",
":",
"client",
",",
"path",
":",
"path",
",",
"}",
"\n",
"}"
] | // NewBackend creates a configuration loader that loads from Vault
// all the keys from the given path and holds them in memory. | [
"NewBackend",
"creates",
"a",
"configuration",
"loader",
"that",
"loads",
"from",
"Vault",
"all",
"the",
"keys",
"from",
"the",
"given",
"path",
"and",
"holds",
"them",
"in",
"memory",
"."
] | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/vault/vault.go#L20-L25 | train |
heetch/confita | backend/vault/vault.go | Get | func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) {
var err error
if b.secret == nil {
b.secret, err = b.client.Read(b.path)
if err != nil {
return nil, err
}
if b.secret == nil {
return nil, fmt.Errorf("secret not found at the following path: %s", b.path)
}
}
if v, ok := b.secret.Data[key]; ok {
return []byte(v.(string)), nil
}
return nil, backend.ErrNotFound
} | go | func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) {
var err error
if b.secret == nil {
b.secret, err = b.client.Read(b.path)
if err != nil {
return nil, err
}
if b.secret == nil {
return nil, fmt.Errorf("secret not found at the following path: %s", b.path)
}
}
if v, ok := b.secret.Data[key]; ok {
return []byte(v.(string)), nil
}
return nil, backend.ErrNotFound
} | [
"func",
"(",
"b",
"*",
"Backend",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n\n",
"if",
"b",
".",
"secret",
"==",
"nil",
"{",
"b",
".",
... | // Get loads the given key from Vault. | [
"Get",
"loads",
"the",
"given",
"key",
"from",
"Vault",
"."
] | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/vault/vault.go#L28-L47 | train |
heetch/confita | backend/file/file.go | NewBackend | func NewBackend(path string) *Backend {
name := filepath.Ext(path)
if name != "" {
name = name[1:]
}
return &Backend{
path: path,
name: name,
}
} | go | func NewBackend(path string) *Backend {
name := filepath.Ext(path)
if name != "" {
name = name[1:]
}
return &Backend{
path: path,
name: name,
}
} | [
"func",
"NewBackend",
"(",
"path",
"string",
")",
"*",
"Backend",
"{",
"name",
":=",
"filepath",
".",
"Ext",
"(",
"path",
")",
"\n",
"if",
"name",
"!=",
"\"",
"\"",
"{",
"name",
"=",
"name",
"[",
"1",
":",
"]",
"\n",
"}",
"\n\n",
"return",
"&",
... | // NewBackend creates a configuration loader that loads from a file.
// The content will get decoded based on the file extension. | [
"NewBackend",
"creates",
"a",
"configuration",
"loader",
"that",
"loads",
"from",
"a",
"file",
".",
"The",
"content",
"will",
"get",
"decoded",
"based",
"on",
"the",
"file",
"extension",
"."
] | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/file/file.go#L23-L33 | train |
heetch/confita | backend/file/file.go | Unmarshal | func (b *Backend) Unmarshal(ctx context.Context, to interface{}) error {
f, err := os.Open(b.path)
if err != nil {
return errors.Wrapf(err, "failed to open file at path \"%s\"", b.path)
}
defer f.Close()
switch ext := filepath.Ext(b.path); ext {
case ".json":
err = json.NewDecoder(f).Decode(to)
case ".yml":
fallthrough
case ".yaml":
err = yaml.NewDecoder(f).Decode(to)
case ".toml":
_, err = toml.DecodeReader(f, to)
default:
err = errors.Errorf("unsupported extension \"%s\"", ext)
}
return errors.Wrapf(err, "failed to decode file \"%s\"", b.path)
} | go | func (b *Backend) Unmarshal(ctx context.Context, to interface{}) error {
f, err := os.Open(b.path)
if err != nil {
return errors.Wrapf(err, "failed to open file at path \"%s\"", b.path)
}
defer f.Close()
switch ext := filepath.Ext(b.path); ext {
case ".json":
err = json.NewDecoder(f).Decode(to)
case ".yml":
fallthrough
case ".yaml":
err = yaml.NewDecoder(f).Decode(to)
case ".toml":
_, err = toml.DecodeReader(f, to)
default:
err = errors.Errorf("unsupported extension \"%s\"", ext)
}
return errors.Wrapf(err, "failed to decode file \"%s\"", b.path)
} | [
"func",
"(",
"b",
"*",
"Backend",
")",
"Unmarshal",
"(",
"ctx",
"context",
".",
"Context",
",",
"to",
"interface",
"{",
"}",
")",
"error",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"b",
".",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil"... | // Unmarshal takes a struct pointer and unmarshals the file into it,
// using either json or yaml based on the file extention. | [
"Unmarshal",
"takes",
"a",
"struct",
"pointer",
"and",
"unmarshals",
"the",
"file",
"into",
"it",
"using",
"either",
"json",
"or",
"yaml",
"based",
"on",
"the",
"file",
"extention",
"."
] | ce4cc839aad348e349f27cda473af1f98ff74523 | https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/file/file.go#L37-L58 | train |
hajimehoshi/oto | internal/mux/mux.go | New | func New(channelNum, bitDepthInBytes int) *Mux {
m := &Mux{
channelNum: channelNum,
bitDepthInBytes: bitDepthInBytes,
readers: map[io.Reader]*bufio.Reader{},
}
runtime.SetFinalizer(m, (*Mux).Close)
return m
} | go | func New(channelNum, bitDepthInBytes int) *Mux {
m := &Mux{
channelNum: channelNum,
bitDepthInBytes: bitDepthInBytes,
readers: map[io.Reader]*bufio.Reader{},
}
runtime.SetFinalizer(m, (*Mux).Close)
return m
} | [
"func",
"New",
"(",
"channelNum",
",",
"bitDepthInBytes",
"int",
")",
"*",
"Mux",
"{",
"m",
":=",
"&",
"Mux",
"{",
"channelNum",
":",
"channelNum",
",",
"bitDepthInBytes",
":",
"bitDepthInBytes",
",",
"readers",
":",
"map",
"[",
"io",
".",
"Reader",
"]",... | // New creates a new Mux with the specified number of channels and bit depth. | [
"New",
"creates",
"a",
"new",
"Mux",
"with",
"the",
"specified",
"number",
"of",
"channels",
"and",
"bit",
"depth",
"."
] | ac73e202da9bf0b5596c1a6d4cd12fad992987d3 | https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/internal/mux/mux.go#L35-L43 | train |
hajimehoshi/oto | internal/mux/mux.go | Close | func (m *Mux) Close() error {
m.m.Lock()
runtime.SetFinalizer(m, nil)
m.readers = nil
m.closed = true
m.m.Unlock()
return nil
} | go | func (m *Mux) Close() error {
m.m.Lock()
runtime.SetFinalizer(m, nil)
m.readers = nil
m.closed = true
m.m.Unlock()
return nil
} | [
"func",
"(",
"m",
"*",
"Mux",
")",
"Close",
"(",
")",
"error",
"{",
"m",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"runtime",
".",
"SetFinalizer",
"(",
"m",
",",
"nil",
")",
"\n",
"m",
".",
"readers",
"=",
"nil",
"\n",
"m",
".",
"closed",
"=",
... | // Close invalidates the Mux. It doesn't close its readers. | [
"Close",
"invalidates",
"the",
"Mux",
".",
"It",
"doesn",
"t",
"close",
"its",
"readers",
"."
] | ac73e202da9bf0b5596c1a6d4cd12fad992987d3 | https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/internal/mux/mux.go#L145-L152 | train |
hajimehoshi/oto | internal/mux/mux.go | AddSource | func (m *Mux) AddSource(source io.Reader) {
m.m.Lock()
if m.closed {
panic("mux: already closed")
}
if _, ok := m.readers[source]; ok {
panic("mux: the io.Reader cannot be added multiple times")
}
m.readers[source] = bufio.NewReaderSize(source, 256)
m.m.Unlock()
} | go | func (m *Mux) AddSource(source io.Reader) {
m.m.Lock()
if m.closed {
panic("mux: already closed")
}
if _, ok := m.readers[source]; ok {
panic("mux: the io.Reader cannot be added multiple times")
}
m.readers[source] = bufio.NewReaderSize(source, 256)
m.m.Unlock()
} | [
"func",
"(",
"m",
"*",
"Mux",
")",
"AddSource",
"(",
"source",
"io",
".",
"Reader",
")",
"{",
"m",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"if",
"m",
".",
"closed",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
... | // AddSource adds a reader to the Mux. | [
"AddSource",
"adds",
"a",
"reader",
"to",
"the",
"Mux",
"."
] | ac73e202da9bf0b5596c1a6d4cd12fad992987d3 | https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/internal/mux/mux.go#L155-L165 | train |
hajimehoshi/oto | internal/mux/mux.go | RemoveSource | func (m *Mux) RemoveSource(source io.Reader) {
m.m.Lock()
if m.closed {
panic("mux: already closed")
}
if _, ok := m.readers[source]; !ok {
panic("mux: the io.Reader is already removed")
}
delete(m.readers, source)
m.m.Unlock()
} | go | func (m *Mux) RemoveSource(source io.Reader) {
m.m.Lock()
if m.closed {
panic("mux: already closed")
}
if _, ok := m.readers[source]; !ok {
panic("mux: the io.Reader is already removed")
}
delete(m.readers, source)
m.m.Unlock()
} | [
"func",
"(",
"m",
"*",
"Mux",
")",
"RemoveSource",
"(",
"source",
"io",
".",
"Reader",
")",
"{",
"m",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"if",
"m",
".",
"closed",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok"... | // RemoveSource removes a reader from the Mux. | [
"RemoveSource",
"removes",
"a",
"reader",
"from",
"the",
"Mux",
"."
] | ac73e202da9bf0b5596c1a6d4cd12fad992987d3 | https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/internal/mux/mux.go#L168-L178 | train |
hajimehoshi/oto | pipe_js.go | pipe | func pipe() (io.ReadCloser, io.WriteCloser) {
w := &pipeWriter{
consumed: make(chan struct{}),
provided: make(chan struct{}),
closed: make(chan struct{}),
}
r := &pipeReader{
w: w,
closed: make(chan struct{}),
}
w.r = r
return r, w
} | go | func pipe() (io.ReadCloser, io.WriteCloser) {
w := &pipeWriter{
consumed: make(chan struct{}),
provided: make(chan struct{}),
closed: make(chan struct{}),
}
r := &pipeReader{
w: w,
closed: make(chan struct{}),
}
w.r = r
return r, w
} | [
"func",
"pipe",
"(",
")",
"(",
"io",
".",
"ReadCloser",
",",
"io",
".",
"WriteCloser",
")",
"{",
"w",
":=",
"&",
"pipeWriter",
"{",
"consumed",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"provided",
":",
"make",
"(",
"chan",
"struct",
... | // pipe returns a set of an io.ReadCloser and an io.WriteCloser.
//
// This is basically same as io.Pipe, but is implemented in more effient way under the assumption that
// this works on a single thread environment so that locks are not required. | [
"pipe",
"returns",
"a",
"set",
"of",
"an",
"io",
".",
"ReadCloser",
"and",
"an",
"io",
".",
"WriteCloser",
".",
"This",
"is",
"basically",
"same",
"as",
"io",
".",
"Pipe",
"but",
"is",
"implemented",
"in",
"more",
"effient",
"way",
"under",
"the",
"ass... | ac73e202da9bf0b5596c1a6d4cd12fad992987d3 | https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/pipe_js.go#L29-L41 | train |
hajimehoshi/oto | player.go | Close | func (p *Player) Close() error {
runtime.SetFinalizer(p, nil)
// Already closed
if p.context == nil {
return nil
}
// Close the pipe writer before RemoveSource, or Read-ing in the mux takes forever.
if err := p.w.Close(); err != nil {
return err
}
p.context.mux.RemoveSource(p.r)
p.context = nil
// Close the pipe reader after RemoveSource, or ErrClosedPipe happens at Read-ing.
return p.r.Close()
} | go | func (p *Player) Close() error {
runtime.SetFinalizer(p, nil)
// Already closed
if p.context == nil {
return nil
}
// Close the pipe writer before RemoveSource, or Read-ing in the mux takes forever.
if err := p.w.Close(); err != nil {
return err
}
p.context.mux.RemoveSource(p.r)
p.context = nil
// Close the pipe reader after RemoveSource, or ErrClosedPipe happens at Read-ing.
return p.r.Close()
} | [
"func",
"(",
"p",
"*",
"Player",
")",
"Close",
"(",
")",
"error",
"{",
"runtime",
".",
"SetFinalizer",
"(",
"p",
",",
"nil",
")",
"\n\n",
"// Already closed",
"if",
"p",
".",
"context",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Close ... | // Close closes the Player and frees any resources associated with it. The Player is no longer
// usable after calling Close. | [
"Close",
"closes",
"the",
"Player",
"and",
"frees",
"any",
"resources",
"associated",
"with",
"it",
".",
"The",
"Player",
"is",
"no",
"longer",
"usable",
"after",
"calling",
"Close",
"."
] | ac73e202da9bf0b5596c1a6d4cd12fad992987d3 | https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/player.go#L65-L83 | train |
hajimehoshi/oto | context.go | NewContext | func NewContext(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes int) (*Context, error) {
contextM.Lock()
defer contextM.Unlock()
if theContext != nil {
panic("oto: NewContext can be called only once")
}
d, err := newDriver(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes)
if err != nil {
return nil, err
}
dw := &driverWriter{
driver: d,
bufferSize: bufferSizeInBytes,
bytesPerSecond: sampleRate * channelNum * bitDepthInBytes,
}
c := &Context{
driverWriter: dw,
mux: mux.New(channelNum, bitDepthInBytes),
errCh: make(chan error),
}
theContext = c
go func() {
if _, err := io.Copy(c.driverWriter, c.mux); err != nil {
c.errCh <- err
}
close(c.errCh)
}()
return c, nil
} | go | func NewContext(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes int) (*Context, error) {
contextM.Lock()
defer contextM.Unlock()
if theContext != nil {
panic("oto: NewContext can be called only once")
}
d, err := newDriver(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes)
if err != nil {
return nil, err
}
dw := &driverWriter{
driver: d,
bufferSize: bufferSizeInBytes,
bytesPerSecond: sampleRate * channelNum * bitDepthInBytes,
}
c := &Context{
driverWriter: dw,
mux: mux.New(channelNum, bitDepthInBytes),
errCh: make(chan error),
}
theContext = c
go func() {
if _, err := io.Copy(c.driverWriter, c.mux); err != nil {
c.errCh <- err
}
close(c.errCh)
}()
return c, nil
} | [
"func",
"NewContext",
"(",
"sampleRate",
",",
"channelNum",
",",
"bitDepthInBytes",
",",
"bufferSizeInBytes",
"int",
")",
"(",
"*",
"Context",
",",
"error",
")",
"{",
"contextM",
".",
"Lock",
"(",
")",
"\n",
"defer",
"contextM",
".",
"Unlock",
"(",
")",
... | // NewContext creates a new context, that creates and holds ready-to-use Player objects.
//
// The sampleRate argument specifies the number of samples that should be played during one second.
// Usual numbers are 44100 or 48000.
//
// The channelNum argument specifies the number of channels. One channel is mono playback. Two
// channels are stereo playback. No other values are supported.
//
// The bitDepthInBytes argument specifies the number of bytes per sample per channel. The usual value
// is 2. Only values 1 and 2 are supported.
//
// The bufferSizeInBytes argument specifies the size of the buffer of the Context. This means, how
// many bytes can Context remember before actually playing them. Bigger buffer can reduce the number
// of Player's Write calls, thus reducing CPU time. Smaller buffer enables more precise timing. The
// longest delay between when samples were written and when they started playing is equal to the size
// of the buffer. | [
"NewContext",
"creates",
"a",
"new",
"context",
"that",
"creates",
"and",
"holds",
"ready",
"-",
"to",
"-",
"use",
"Player",
"objects",
".",
"The",
"sampleRate",
"argument",
"specifies",
"the",
"number",
"of",
"samples",
"that",
"should",
"be",
"played",
"du... | ac73e202da9bf0b5596c1a6d4cd12fad992987d3 | https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/context.go#L61-L91 | train |
hajimehoshi/oto | context.go | NewPlayer | func NewPlayer(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes int) (*Player, error) {
c, err := NewContext(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes)
if err != nil {
return nil, err
}
return c.NewPlayer(), nil
} | go | func NewPlayer(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes int) (*Player, error) {
c, err := NewContext(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes)
if err != nil {
return nil, err
}
return c.NewPlayer(), nil
} | [
"func",
"NewPlayer",
"(",
"sampleRate",
",",
"channelNum",
",",
"bitDepthInBytes",
",",
"bufferSizeInBytes",
"int",
")",
"(",
"*",
"Player",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"NewContext",
"(",
"sampleRate",
",",
"channelNum",
",",
"bitDepthInBy... | // NewPlayer is a short-hand of creating a Context by NewContext and a Player by the context's NewPlayer. | [
"NewPlayer",
"is",
"a",
"short",
"-",
"hand",
"of",
"creating",
"a",
"Context",
"by",
"NewContext",
"and",
"a",
"Player",
"by",
"the",
"context",
"s",
"NewPlayer",
"."
] | ac73e202da9bf0b5596c1a6d4cd12fad992987d3 | https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/context.go#L94-L100 | train |
hajimehoshi/oto | context.go | NewPlayer | func (c *Context) NewPlayer() *Player {
p := newPlayer(c)
c.mux.AddSource(p.r)
return p
} | go | func (c *Context) NewPlayer() *Player {
p := newPlayer(c)
c.mux.AddSource(p.r)
return p
} | [
"func",
"(",
"c",
"*",
"Context",
")",
"NewPlayer",
"(",
")",
"*",
"Player",
"{",
"p",
":=",
"newPlayer",
"(",
"c",
")",
"\n",
"c",
".",
"mux",
".",
"AddSource",
"(",
"p",
".",
"r",
")",
"\n",
"return",
"p",
"\n",
"}"
] | // NewPlayer creates a new, ready-to-use Player belonging to the Context. | [
"NewPlayer",
"creates",
"a",
"new",
"ready",
"-",
"to",
"-",
"use",
"Player",
"belonging",
"to",
"the",
"Context",
"."
] | ac73e202da9bf0b5596c1a6d4cd12fad992987d3 | https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/context.go#L103-L107 | train |
hajimehoshi/oto | context.go | Close | func (c *Context) Close() error {
contextM.Lock()
theContext = nil
contextM.Unlock()
if err := c.driverWriter.Close(); err != nil {
return err
}
if err := c.mux.Close(); err != nil {
return err
}
return <-c.errCh
} | go | func (c *Context) Close() error {
contextM.Lock()
theContext = nil
contextM.Unlock()
if err := c.driverWriter.Close(); err != nil {
return err
}
if err := c.mux.Close(); err != nil {
return err
}
return <-c.errCh
} | [
"func",
"(",
"c",
"*",
"Context",
")",
"Close",
"(",
")",
"error",
"{",
"contextM",
".",
"Lock",
"(",
")",
"\n",
"theContext",
"=",
"nil",
"\n",
"contextM",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"err",
":=",
"c",
".",
"driverWriter",
".",
"Close",... | // Close closes the Context and its Players and frees any resources associated with it. The Context is no longer
// usable after calling Close. | [
"Close",
"closes",
"the",
"Context",
"and",
"its",
"Players",
"and",
"frees",
"any",
"resources",
"associated",
"with",
"it",
".",
"The",
"Context",
"is",
"no",
"longer",
"usable",
"after",
"calling",
"Close",
"."
] | ac73e202da9bf0b5596c1a6d4cd12fad992987d3 | https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/context.go#L111-L123 | train |
yinqiwen/gsnova | common/protector/resolver.go | PickRandomIP | func (response *DnsResponse) PickRandomIP() (net.IP, error) {
length := int64(len(response.records))
if length < 1 {
return nil, errors.New("no IP address")
}
index, err := rand.Int(rand.Reader, big.NewInt(length))
if err != nil {
return nil, err
}
record := response.records[index.Int64()]
return record.IP, nil
} | go | func (response *DnsResponse) PickRandomIP() (net.IP, error) {
length := int64(len(response.records))
if length < 1 {
return nil, errors.New("no IP address")
}
index, err := rand.Int(rand.Reader, big.NewInt(length))
if err != nil {
return nil, err
}
record := response.records[index.Int64()]
return record.IP, nil
} | [
"func",
"(",
"response",
"*",
"DnsResponse",
")",
"PickRandomIP",
"(",
")",
"(",
"net",
".",
"IP",
",",
"error",
")",
"{",
"length",
":=",
"int64",
"(",
"len",
"(",
"response",
".",
"records",
")",
")",
"\n",
"if",
"length",
"<",
"1",
"{",
"return"... | // PickRandomIP picks a random IP address from a DNS response | [
"PickRandomIP",
"picks",
"a",
"random",
"IP",
"address",
"from",
"a",
"DNS",
"response"
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/resolver.go#L24-L37 | train |
yinqiwen/gsnova | common/protector/resolver.go | DnsLookup | func DnsLookup(addr string, conn net.Conn) (*DnsResponse, error) {
//log.Printf("Doing a DNS lookup on %s", addr)
dnsResponse := &DnsResponse{
records: make([]DNSRecord, 0),
}
// create the connection to the DNS server
dnsConn := &dns.Conn{Conn: conn}
defer dnsConn.Close()
m := new(dns.Msg)
m.Id = dns.Id()
// set the question section in the dns query
// Fqdn returns the fully qualified domain name
m.SetQuestion(dns.Fqdn(addr), dns.TypeA)
m.RecursionDesired = true
dnsConn.WriteMsg(m)
response, err := dnsConn.ReadMsg()
if err != nil {
log.Printf("Could not process DNS response: %v", err)
return nil, err
}
now := time.Now()
// iterate over RRs containing the DNS answer
for _, answer := range response.Answer {
if a, ok := answer.(*dns.A); ok {
// append the result to our list of records
// the A records in the RDATA section of the DNS answer
// contains the actual IP address
dnsResponse.records = append(dnsResponse.records,
DNSRecord{
IP: a.A,
ExpireAt: now.Add(time.Duration(a.Hdr.Ttl) * time.Second),
})
//log.Printf("###TTL:%d", a.Hdr.Ttl)
}
}
return dnsResponse, nil
} | go | func DnsLookup(addr string, conn net.Conn) (*DnsResponse, error) {
//log.Printf("Doing a DNS lookup on %s", addr)
dnsResponse := &DnsResponse{
records: make([]DNSRecord, 0),
}
// create the connection to the DNS server
dnsConn := &dns.Conn{Conn: conn}
defer dnsConn.Close()
m := new(dns.Msg)
m.Id = dns.Id()
// set the question section in the dns query
// Fqdn returns the fully qualified domain name
m.SetQuestion(dns.Fqdn(addr), dns.TypeA)
m.RecursionDesired = true
dnsConn.WriteMsg(m)
response, err := dnsConn.ReadMsg()
if err != nil {
log.Printf("Could not process DNS response: %v", err)
return nil, err
}
now := time.Now()
// iterate over RRs containing the DNS answer
for _, answer := range response.Answer {
if a, ok := answer.(*dns.A); ok {
// append the result to our list of records
// the A records in the RDATA section of the DNS answer
// contains the actual IP address
dnsResponse.records = append(dnsResponse.records,
DNSRecord{
IP: a.A,
ExpireAt: now.Add(time.Duration(a.Hdr.Ttl) * time.Second),
})
//log.Printf("###TTL:%d", a.Hdr.Ttl)
}
}
return dnsResponse, nil
} | [
"func",
"DnsLookup",
"(",
"addr",
"string",
",",
"conn",
"net",
".",
"Conn",
")",
"(",
"*",
"DnsResponse",
",",
"error",
")",
"{",
"//log.Printf(\"Doing a DNS lookup on %s\", addr)",
"dnsResponse",
":=",
"&",
"DnsResponse",
"{",
"records",
":",
"make",
"(",
"[... | // dnsLookup is used whenever we need to conduct a DNS query over a given TCP connection | [
"dnsLookup",
"is",
"used",
"whenever",
"we",
"need",
"to",
"conduct",
"a",
"DNS",
"query",
"over",
"a",
"given",
"TCP",
"connection"
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/resolver.go#L48-L89 | train |
yinqiwen/gsnova | common/helper/bytes.go | PKCS7Unpad | func PKCS7Unpad(in []byte) []byte {
if len(in) == 0 {
return nil
}
padding := in[len(in)-1]
if int(padding) > len(in) || padding > aes.BlockSize {
return nil
} else if padding == 0 {
return nil
}
for i := len(in) - 1; i > len(in)-int(padding)-1; i-- {
if in[i] != padding {
return nil
}
}
return in[:len(in)-int(padding)]
} | go | func PKCS7Unpad(in []byte) []byte {
if len(in) == 0 {
return nil
}
padding := in[len(in)-1]
if int(padding) > len(in) || padding > aes.BlockSize {
return nil
} else if padding == 0 {
return nil
}
for i := len(in) - 1; i > len(in)-int(padding)-1; i-- {
if in[i] != padding {
return nil
}
}
return in[:len(in)-int(padding)]
} | [
"func",
"PKCS7Unpad",
"(",
"in",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"if",
"len",
"(",
"in",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"padding",
":=",
"in",
"[",
"len",
"(",
"in",
")",
"-",
"1",
"]",
"\n",
"if",
"i... | // Returns slice of the original data without padding. | [
"Returns",
"slice",
"of",
"the",
"original",
"data",
"without",
"padding",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/helper/bytes.go#L21-L39 | train |
yinqiwen/gsnova | common/helper/bytes.go | ToBytes | func ToBytes(s string) (uint64, error) {
parts := bytesPattern.FindStringSubmatch(strings.TrimSpace(s))
if len(parts) < 3 {
return 0, invalidByteQuantityError
}
value, err := strconv.ParseFloat(parts[1], 64)
if err != nil || value <= 0 {
return 0, invalidByteQuantityError
}
var bytes uint64
unit := strings.ToUpper(parts[2])
switch unit[:1] {
case "T":
bytes = uint64(value * TERABYTE)
case "G":
bytes = uint64(value * GIGABYTE)
case "M":
bytes = uint64(value * MEGABYTE)
case "K":
bytes = uint64(value * KILOBYTE)
case "B":
bytes = uint64(value * BYTE)
}
return bytes, nil
} | go | func ToBytes(s string) (uint64, error) {
parts := bytesPattern.FindStringSubmatch(strings.TrimSpace(s))
if len(parts) < 3 {
return 0, invalidByteQuantityError
}
value, err := strconv.ParseFloat(parts[1], 64)
if err != nil || value <= 0 {
return 0, invalidByteQuantityError
}
var bytes uint64
unit := strings.ToUpper(parts[2])
switch unit[:1] {
case "T":
bytes = uint64(value * TERABYTE)
case "G":
bytes = uint64(value * GIGABYTE)
case "M":
bytes = uint64(value * MEGABYTE)
case "K":
bytes = uint64(value * KILOBYTE)
case "B":
bytes = uint64(value * BYTE)
}
return bytes, nil
} | [
"func",
"ToBytes",
"(",
"s",
"string",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"parts",
":=",
"bytesPattern",
".",
"FindStringSubmatch",
"(",
"strings",
".",
"TrimSpace",
"(",
"s",
")",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"<",
"3",
"{",
... | // ToBytes parses a string formatted by ByteSize as bytes. | [
"ToBytes",
"parses",
"a",
"string",
"formatted",
"by",
"ByteSize",
"as",
"bytes",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/helper/bytes.go#L100-L127 | train |
yinqiwen/gsnova | common/channel/kcp/local.go | WriteTo | func (c *connectedUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
writer, ok := c.PacketConn.(io.Writer)
if ok {
return writer.Write(b)
}
return c.PacketConn.WriteTo(b, addr)
} | go | func (c *connectedUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
writer, ok := c.PacketConn.(io.Writer)
if ok {
return writer.Write(b)
}
return c.PacketConn.WriteTo(b, addr)
} | [
"func",
"(",
"c",
"*",
"connectedUDPConn",
")",
"WriteTo",
"(",
"b",
"[",
"]",
"byte",
",",
"addr",
"net",
".",
"Addr",
")",
"(",
"int",
",",
"error",
")",
"{",
"writer",
",",
"ok",
":=",
"c",
".",
"PacketConn",
".",
"(",
"io",
".",
"Writer",
"... | // WriteTo redirects all writes to the Write syscall, which is 4 times faster. | [
"WriteTo",
"redirects",
"all",
"writes",
"to",
"the",
"Write",
"syscall",
"which",
"is",
"4",
"times",
"faster",
"."
] | c6d0717839536ff88524feba6123ac37ea5fcf4e | https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/channel/kcp/local.go#L23-L29 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.