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
AlecAivazis/survey
terminal/cursor.go
Back
func (c *Cursor) Back(n int) { fmt.Fprintf(c.Out, "\x1b[%dD", n) }
go
func (c *Cursor) Back(n int) { fmt.Fprintf(c.Out, "\x1b[%dD", n) }
[ "func", "(", "c", "*", "Cursor", ")", "Back", "(", "n", "int", ")", "{", "fmt", ".", "Fprintf", "(", "c", ".", "Out", ",", "\"", "\\x1b", "\"", ",", "n", ")", "\n", "}" ]
// Back moves the cursor n cells to left.
[ "Back", "moves", "the", "cursor", "n", "cells", "to", "left", "." ]
a84846dc69f1fbe032f4534f92e937684b9a3710
https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L38-L40
train
AlecAivazis/survey
terminal/cursor.go
NextLine
func (c *Cursor) NextLine(n int) { fmt.Fprintf(c.Out, "\x1b[%dE", n) }
go
func (c *Cursor) NextLine(n int) { fmt.Fprintf(c.Out, "\x1b[%dE", n) }
[ "func", "(", "c", "*", "Cursor", ")", "NextLine", "(", "n", "int", ")", "{", "fmt", ".", "Fprintf", "(", "c", ".", "Out", ",", "\"", "\\x1b", "\"", ",", "n", ")", "\n", "}" ]
// NextLine moves cursor to beginning of the line n lines down.
[ "NextLine", "moves", "cursor", "to", "beginning", "of", "the", "line", "n", "lines", "down", "." ]
a84846dc69f1fbe032f4534f92e937684b9a3710
https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L43-L45
train
AlecAivazis/survey
terminal/cursor.go
PreviousLine
func (c *Cursor) PreviousLine(n int) { fmt.Fprintf(c.Out, "\x1b[%dF", n) }
go
func (c *Cursor) PreviousLine(n int) { fmt.Fprintf(c.Out, "\x1b[%dF", n) }
[ "func", "(", "c", "*", "Cursor", ")", "PreviousLine", "(", "n", "int", ")", "{", "fmt", ".", "Fprintf", "(", "c", ".", "Out", ",", "\"", "\\x1b", "\"", ",", "n", ")", "\n", "}" ]
// PreviousLine moves cursor to beginning of the line n lines up.
[ "PreviousLine", "moves", "cursor", "to", "beginning", "of", "the", "line", "n", "lines", "up", "." ]
a84846dc69f1fbe032f4534f92e937684b9a3710
https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L48-L50
train
AlecAivazis/survey
terminal/cursor.go
HorizontalAbsolute
func (c *Cursor) HorizontalAbsolute(x int) { fmt.Fprintf(c.Out, "\x1b[%dG", x) }
go
func (c *Cursor) HorizontalAbsolute(x int) { fmt.Fprintf(c.Out, "\x1b[%dG", x) }
[ "func", "(", "c", "*", "Cursor", ")", "HorizontalAbsolute", "(", "x", "int", ")", "{", "fmt", ".", "Fprintf", "(", "c", ".", "Out", ",", "\"", "\\x1b", "\"", ",", "x", ")", "\n", "}" ]
// HorizontalAbsolute moves cursor horizontally to x.
[ "HorizontalAbsolute", "moves", "cursor", "horizontally", "to", "x", "." ]
a84846dc69f1fbe032f4534f92e937684b9a3710
https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L53-L55
train
AlecAivazis/survey
terminal/cursor.go
Move
func (c *Cursor) Move(x int, y int) { fmt.Fprintf(c.Out, "\x1b[%d;%df", x, y) }
go
func (c *Cursor) Move(x int, y int) { fmt.Fprintf(c.Out, "\x1b[%d;%df", x, y) }
[ "func", "(", "c", "*", "Cursor", ")", "Move", "(", "x", "int", ",", "y", "int", ")", "{", "fmt", ".", "Fprintf", "(", "c", ".", "Out", ",", "\"", "\\x1b", "\"", ",", "x", ",", "y", ")", "\n", "}" ]
// Move moves the cursor to a specific x,y location.
[ "Move", "moves", "the", "cursor", "to", "a", "specific", "x", "y", "location", "." ]
a84846dc69f1fbe032f4534f92e937684b9a3710
https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L68-L70
train
AlecAivazis/survey
terminal/cursor.go
MoveNextLine
func (c *Cursor) MoveNextLine(cur *Coord, terminalSize *Coord) { if cur.Y == terminalSize.Y { fmt.Fprintln(c.Out) } c.NextLine(1) }
go
func (c *Cursor) MoveNextLine(cur *Coord, terminalSize *Coord) { if cur.Y == terminalSize.Y { fmt.Fprintln(c.Out) } c.NextLine(1) }
[ "func", "(", "c", "*", "Cursor", ")", "MoveNextLine", "(", "cur", "*", "Coord", ",", "terminalSize", "*", "Coord", ")", "{", "if", "cur", ".", "Y", "==", "terminalSize", ".", "Y", "{", "fmt", ".", "Fprintln", "(", "c", ".", "Out", ")", "\n", "}",...
// for comparability purposes between windows // in unix we need to print out a new line on some terminals
[ "for", "comparability", "purposes", "between", "windows", "in", "unix", "we", "need", "to", "print", "out", "a", "new", "line", "on", "some", "terminals" ]
a84846dc69f1fbe032f4534f92e937684b9a3710
https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L84-L89
train
AlecAivazis/survey
terminal/cursor.go
Location
func (c *Cursor) Location(buf *bytes.Buffer) (*Coord, error) { // ANSI escape sequence for DSR - Device Status Report // https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences fmt.Fprint(c.Out, "\x1b[6n") // There may be input in Stdin prior to CursorLocation so make sure we don't // drop those bytes. var loc []int var match string for loc == nil { // Reports the cursor position (CPR) to the application as (as though typed at // the keyboard) ESC[n;mR, where n is the row and m is the column. reader := bufio.NewReader(c.In) text, err := reader.ReadSlice('R') if err != nil { return nil, err } loc = dsrPattern.FindStringIndex(string(text)) if loc == nil { // Stdin contains R that doesn't match DSR. buf.Write(text) } else { buf.Write(text[:loc[0]]) match = string(text[loc[0]:loc[1]]) } } matches := dsrPattern.FindStringSubmatch(string(match)) if len(matches) != 3 { return nil, fmt.Errorf("incorrect number of matches: %d", len(matches)) } col, err := strconv.Atoi(matches[2]) if err != nil { return nil, err } row, err := strconv.Atoi(matches[1]) if err != nil { return nil, err } return &Coord{Short(col), Short(row)}, nil }
go
func (c *Cursor) Location(buf *bytes.Buffer) (*Coord, error) { // ANSI escape sequence for DSR - Device Status Report // https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences fmt.Fprint(c.Out, "\x1b[6n") // There may be input in Stdin prior to CursorLocation so make sure we don't // drop those bytes. var loc []int var match string for loc == nil { // Reports the cursor position (CPR) to the application as (as though typed at // the keyboard) ESC[n;mR, where n is the row and m is the column. reader := bufio.NewReader(c.In) text, err := reader.ReadSlice('R') if err != nil { return nil, err } loc = dsrPattern.FindStringIndex(string(text)) if loc == nil { // Stdin contains R that doesn't match DSR. buf.Write(text) } else { buf.Write(text[:loc[0]]) match = string(text[loc[0]:loc[1]]) } } matches := dsrPattern.FindStringSubmatch(string(match)) if len(matches) != 3 { return nil, fmt.Errorf("incorrect number of matches: %d", len(matches)) } col, err := strconv.Atoi(matches[2]) if err != nil { return nil, err } row, err := strconv.Atoi(matches[1]) if err != nil { return nil, err } return &Coord{Short(col), Short(row)}, nil }
[ "func", "(", "c", "*", "Cursor", ")", "Location", "(", "buf", "*", "bytes", ".", "Buffer", ")", "(", "*", "Coord", ",", "error", ")", "{", "// ANSI escape sequence for DSR - Device Status Report", "// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences", "fmt",...
// Location returns the current location of the cursor in the terminal
[ "Location", "returns", "the", "current", "location", "of", "the", "cursor", "in", "the", "terminal" ]
a84846dc69f1fbe032f4534f92e937684b9a3710
https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L92-L136
train
AlecAivazis/survey
terminal/cursor.go
Size
func (c *Cursor) Size(buf *bytes.Buffer) (*Coord, error) { // the general approach here is to move the cursor to the very bottom // of the terminal, ask for the current location and then move the // cursor back where we started // hide the cursor (so it doesn't blink when getting the size of the terminal) c.Hide() // save the current location of the cursor c.Save() // move the cursor to the very bottom of the terminal c.Move(999, 999) // ask for the current location bottom, err := c.Location(buf) if err != nil { return nil, err } // move back where we began c.Restore() // show the cursor c.Show() // sice the bottom was calcuated in the lower right corner, it // is the dimensions we are looking for return bottom, nil }
go
func (c *Cursor) Size(buf *bytes.Buffer) (*Coord, error) { // the general approach here is to move the cursor to the very bottom // of the terminal, ask for the current location and then move the // cursor back where we started // hide the cursor (so it doesn't blink when getting the size of the terminal) c.Hide() // save the current location of the cursor c.Save() // move the cursor to the very bottom of the terminal c.Move(999, 999) // ask for the current location bottom, err := c.Location(buf) if err != nil { return nil, err } // move back where we began c.Restore() // show the cursor c.Show() // sice the bottom was calcuated in the lower right corner, it // is the dimensions we are looking for return bottom, nil }
[ "func", "(", "c", "*", "Cursor", ")", "Size", "(", "buf", "*", "bytes", ".", "Buffer", ")", "(", "*", "Coord", ",", "error", ")", "{", "// the general approach here is to move the cursor to the very bottom", "// of the terminal, ask for the current location and then move ...
// Size returns the height and width of the terminal.
[ "Size", "returns", "the", "height", "and", "width", "of", "the", "terminal", "." ]
a84846dc69f1fbe032f4534f92e937684b9a3710
https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L147-L174
train
AlecAivazis/survey
multiselect.go
Cleanup
func (m *MultiSelect) Cleanup(val interface{}) error { // execute the output summary template with the answer return m.Render( MultiSelectQuestionTemplate, MultiSelectTemplateData{ MultiSelect: *m, SelectedIndex: m.selectedIndex, Checked: m.checked, Answer: strings.Join(val.([]string), ", "), ShowAnswer: true, }, ) }
go
func (m *MultiSelect) Cleanup(val interface{}) error { // execute the output summary template with the answer return m.Render( MultiSelectQuestionTemplate, MultiSelectTemplateData{ MultiSelect: *m, SelectedIndex: m.selectedIndex, Checked: m.checked, Answer: strings.Join(val.([]string), ", "), ShowAnswer: true, }, ) }
[ "func", "(", "m", "*", "MultiSelect", ")", "Cleanup", "(", "val", "interface", "{", "}", ")", "error", "{", "// execute the output summary template with the answer", "return", "m", ".", "Render", "(", "MultiSelectQuestionTemplate", ",", "MultiSelectTemplateData", "{",...
// Cleanup removes the options section, and renders the ask like a normal question.
[ "Cleanup", "removes", "the", "options", "section", "and", "renders", "the", "ask", "like", "a", "normal", "question", "." ]
a84846dc69f1fbe032f4534f92e937684b9a3710
https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/multiselect.go#L236-L248
train
AlecAivazis/survey
terminal/runereader_posix.go
SetTermMode
func (rr *RuneReader) SetTermMode() error { if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlReadTermios, uintptr(unsafe.Pointer(&rr.state.term)), 0, 0, 0); err != 0 { return err } newState := rr.state.term newState.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 { return err } return nil }
go
func (rr *RuneReader) SetTermMode() error { if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlReadTermios, uintptr(unsafe.Pointer(&rr.state.term)), 0, 0, 0); err != 0 { return err } newState := rr.state.term newState.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 { return err } return nil }
[ "func", "(", "rr", "*", "RuneReader", ")", "SetTermMode", "(", ")", "error", "{", "if", "_", ",", "_", ",", "err", ":=", "syscall", ".", "Syscall6", "(", "syscall", ".", "SYS_IOCTL", ",", "uintptr", "(", "rr", ".", "stdio", ".", "In", ".", "Fd", ...
// For reading runes we just want to disable echo.
[ "For", "reading", "runes", "we", "just", "want", "to", "disable", "echo", "." ]
a84846dc69f1fbe032f4534f92e937684b9a3710
https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/runereader_posix.go#L41-L54
train
AlecAivazis/survey
confirm.go
Cleanup
func (c *Confirm) Cleanup(val interface{}) error { // if the value was previously true ans := yesNo(val.(bool)) // render the template return c.Render( ConfirmQuestionTemplate, ConfirmTemplateData{Confirm: *c, Answer: ans}, ) }
go
func (c *Confirm) Cleanup(val interface{}) error { // if the value was previously true ans := yesNo(val.(bool)) // render the template return c.Render( ConfirmQuestionTemplate, ConfirmTemplateData{Confirm: *c, Answer: ans}, ) }
[ "func", "(", "c", "*", "Confirm", ")", "Cleanup", "(", "val", "interface", "{", "}", ")", "error", "{", "// if the value was previously true", "ans", ":=", "yesNo", "(", "val", ".", "(", "bool", ")", ")", "\n", "// render the template", "return", "c", ".",...
// Cleanup overwrite the line with the finalized formatted version
[ "Cleanup", "overwrite", "the", "line", "with", "the", "finalized", "formatted", "version" ]
a84846dc69f1fbe032f4534f92e937684b9a3710
https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/confirm.go#L130-L138
train
golang/gddo
httputil/respbuf.go
Write
func (rb *ResponseBuffer) Write(p []byte) (int, error) { return rb.buf.Write(p) }
go
func (rb *ResponseBuffer) Write(p []byte) (int, error) { return rb.buf.Write(p) }
[ "func", "(", "rb", "*", "ResponseBuffer", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "return", "rb", ".", "buf", ".", "Write", "(", "p", ")", "\n", "}" ]
// Write implements the http.ResponseWriter interface.
[ "Write", "implements", "the", "http", ".", "ResponseWriter", "interface", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/respbuf.go#L24-L26
train
golang/gddo
httputil/respbuf.go
Header
func (rb *ResponseBuffer) Header() http.Header { if rb.header == nil { rb.header = make(http.Header) } return rb.header }
go
func (rb *ResponseBuffer) Header() http.Header { if rb.header == nil { rb.header = make(http.Header) } return rb.header }
[ "func", "(", "rb", "*", "ResponseBuffer", ")", "Header", "(", ")", "http", ".", "Header", "{", "if", "rb", ".", "header", "==", "nil", "{", "rb", ".", "header", "=", "make", "(", "http", ".", "Header", ")", "\n", "}", "\n", "return", "rb", ".", ...
// Header implements the http.ResponseWriter interface.
[ "Header", "implements", "the", "http", ".", "ResponseWriter", "interface", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/respbuf.go#L34-L39
train
golang/gddo
httputil/httputil.go
StripPort
func StripPort(s string) string { if h, _, err := net.SplitHostPort(s); err == nil { s = h } return s }
go
func StripPort(s string) string { if h, _, err := net.SplitHostPort(s); err == nil { s = h } return s }
[ "func", "StripPort", "(", "s", "string", ")", "string", "{", "if", "h", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "s", ")", ";", "err", "==", "nil", "{", "s", "=", "h", "\n", "}", "\n", "return", "s", "\n", "}" ]
// StripPort removes the port specification from an address.
[ "StripPort", "removes", "the", "port", "specification", "from", "an", "address", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/httputil.go#L16-L21
train
golang/gddo
doc/builder.go
synopsis
func synopsis(s string) string { parts := strings.SplitN(s, "\n\n", 2) s = parts[0] var buf []byte const ( other = iota period space ) last := space Loop: for i := 0; i < len(s); i++ { b := s[i] switch b { case ' ', '\t', '\r', '\n': switch last { case period: break Loop case other: buf = append(buf, ' ') last = space } case '.': last = period buf = append(buf, b) default: last = other buf = append(buf, b) } } // Ensure that synopsis fits an App Engine datastore text property. const m = 400 if len(buf) > m { buf = buf[:m] if i := bytes.LastIndex(buf, []byte{' '}); i >= 0 { buf = buf[:i] } buf = append(buf, " ..."...) } s = string(buf) r, n := utf8.DecodeRuneInString(s) if n < 0 || unicode.IsPunct(r) || unicode.IsSymbol(r) { // ignore Markdown headings, editor settings, Go build constraints, and * in poorly formatted block comments. s = "" } else { for _, prefix := range badSynopsisPrefixes { if strings.HasPrefix(s, prefix) { s = "" break } } } return s }
go
func synopsis(s string) string { parts := strings.SplitN(s, "\n\n", 2) s = parts[0] var buf []byte const ( other = iota period space ) last := space Loop: for i := 0; i < len(s); i++ { b := s[i] switch b { case ' ', '\t', '\r', '\n': switch last { case period: break Loop case other: buf = append(buf, ' ') last = space } case '.': last = period buf = append(buf, b) default: last = other buf = append(buf, b) } } // Ensure that synopsis fits an App Engine datastore text property. const m = 400 if len(buf) > m { buf = buf[:m] if i := bytes.LastIndex(buf, []byte{' '}); i >= 0 { buf = buf[:i] } buf = append(buf, " ..."...) } s = string(buf) r, n := utf8.DecodeRuneInString(s) if n < 0 || unicode.IsPunct(r) || unicode.IsSymbol(r) { // ignore Markdown headings, editor settings, Go build constraints, and * in poorly formatted block comments. s = "" } else { for _, prefix := range badSynopsisPrefixes { if strings.HasPrefix(s, prefix) { s = "" break } } } return s }
[ "func", "synopsis", "(", "s", "string", ")", "string", "{", "parts", ":=", "strings", ".", "SplitN", "(", "s", ",", "\"", "\\n", "\\n", "\"", ",", "2", ")", "\n", "s", "=", "parts", "[", "0", "]", "\n\n", "var", "buf", "[", "]", "byte", "\n", ...
// synopsis extracts the first sentence from s. All runs of whitespace are // replaced by a single space.
[ "synopsis", "extracts", "the", "first", "sentence", "from", "s", ".", "All", "runs", "of", "whitespace", "are", "replaced", "by", "a", "single", "space", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/doc/builder.go#L46-L105
train
golang/gddo
doc/builder.go
addReferences
func addReferences(references map[string]bool, s []byte) { for _, pat := range referencesPats { for _, m := range pat.FindAllSubmatch(s, -1) { p := string(m[1]) if gosrc.IsValidRemotePath(p) { references[p] = true } } } }
go
func addReferences(references map[string]bool, s []byte) { for _, pat := range referencesPats { for _, m := range pat.FindAllSubmatch(s, -1) { p := string(m[1]) if gosrc.IsValidRemotePath(p) { references[p] = true } } } }
[ "func", "addReferences", "(", "references", "map", "[", "string", "]", "bool", ",", "s", "[", "]", "byte", ")", "{", "for", "_", ",", "pat", ":=", "range", "referencesPats", "{", "for", "_", ",", "m", ":=", "range", "pat", ".", "FindAllSubmatch", "("...
// addReferences adds packages referenced in plain text s.
[ "addReferences", "adds", "packages", "referenced", "in", "plain", "text", "s", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/doc/builder.go#L121-L130
train
golang/gddo
doc/builder.go
SetDefaultGOOS
func SetDefaultGOOS(goos string) { if goos == "" { return } var i int for ; i < len(goEnvs); i++ { if goEnvs[i].GOOS == goos { break } } switch i { case 0: return case len(goEnvs): env := goEnvs[0] env.GOOS = goos goEnvs = append(goEnvs, env) } goEnvs[0], goEnvs[i] = goEnvs[i], goEnvs[0] }
go
func SetDefaultGOOS(goos string) { if goos == "" { return } var i int for ; i < len(goEnvs); i++ { if goEnvs[i].GOOS == goos { break } } switch i { case 0: return case len(goEnvs): env := goEnvs[0] env.GOOS = goos goEnvs = append(goEnvs, env) } goEnvs[0], goEnvs[i] = goEnvs[i], goEnvs[0] }
[ "func", "SetDefaultGOOS", "(", "goos", "string", ")", "{", "if", "goos", "==", "\"", "\"", "{", "return", "\n", "}", "\n", "var", "i", "int", "\n", "for", ";", "i", "<", "len", "(", "goEnvs", ")", ";", "i", "++", "{", "if", "goEnvs", "[", "i", ...
// SetDefaultGOOS sets given GOOS value as default one to use when building // package documents. SetDefaultGOOS has no effect on some windows-only // packages.
[ "SetDefaultGOOS", "sets", "given", "GOOS", "value", "as", "default", "one", "to", "use", "when", "building", "package", "documents", ".", "SetDefaultGOOS", "has", "no", "effect", "on", "some", "windows", "-", "only", "packages", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/doc/builder.go#L475-L494
train
golang/gddo
httputil/header/header.go
Copy
func Copy(header http.Header) http.Header { h := make(http.Header) for k, vs := range header { h[k] = vs } return h }
go
func Copy(header http.Header) http.Header { h := make(http.Header) for k, vs := range header { h[k] = vs } return h }
[ "func", "Copy", "(", "header", "http", ".", "Header", ")", "http", ".", "Header", "{", "h", ":=", "make", "(", "http", ".", "Header", ")", "\n", "for", "k", ",", "vs", ":=", "range", "header", "{", "h", "[", "k", "]", "=", "vs", "\n", "}", "\...
// Copy returns a shallow copy of the header.
[ "Copy", "returns", "a", "shallow", "copy", "of", "the", "header", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/header/header.go#L59-L65
train
golang/gddo
httputil/header/header.go
ParseTime
func ParseTime(header http.Header, key string) time.Time { if s := header.Get(key); s != "" { for _, layout := range timeLayouts { if t, err := time.Parse(layout, s); err == nil { return t.UTC() } } } return time.Time{} }
go
func ParseTime(header http.Header, key string) time.Time { if s := header.Get(key); s != "" { for _, layout := range timeLayouts { if t, err := time.Parse(layout, s); err == nil { return t.UTC() } } } return time.Time{} }
[ "func", "ParseTime", "(", "header", "http", ".", "Header", ",", "key", "string", ")", "time", ".", "Time", "{", "if", "s", ":=", "header", ".", "Get", "(", "key", ")", ";", "s", "!=", "\"", "\"", "{", "for", "_", ",", "layout", ":=", "range", "...
// ParseTime parses the header as time. The zero value is returned if the // header is not present or there is an error parsing the // header.
[ "ParseTime", "parses", "the", "header", "as", "time", ".", "The", "zero", "value", "is", "returned", "if", "the", "header", "is", "not", "present", "or", "there", "is", "an", "error", "parsing", "the", "header", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/header/header.go#L72-L81
train
golang/gddo
httputil/header/header.go
ParseList
func ParseList(header http.Header, key string) []string { var result []string for _, s := range header[http.CanonicalHeaderKey(key)] { begin := 0 end := 0 escape := false quote := false for i := 0; i < len(s); i++ { b := s[i] switch { case escape: escape = false end = i + 1 case quote: switch b { case '\\': escape = true case '"': quote = false } end = i + 1 case b == '"': quote = true end = i + 1 case octetTypes[b]&isSpace != 0: if begin == end { begin = i + 1 end = begin } case b == ',': if begin < end { result = append(result, s[begin:end]) } begin = i + 1 end = begin default: end = i + 1 } } if begin < end { result = append(result, s[begin:end]) } } return result }
go
func ParseList(header http.Header, key string) []string { var result []string for _, s := range header[http.CanonicalHeaderKey(key)] { begin := 0 end := 0 escape := false quote := false for i := 0; i < len(s); i++ { b := s[i] switch { case escape: escape = false end = i + 1 case quote: switch b { case '\\': escape = true case '"': quote = false } end = i + 1 case b == '"': quote = true end = i + 1 case octetTypes[b]&isSpace != 0: if begin == end { begin = i + 1 end = begin } case b == ',': if begin < end { result = append(result, s[begin:end]) } begin = i + 1 end = begin default: end = i + 1 } } if begin < end { result = append(result, s[begin:end]) } } return result }
[ "func", "ParseList", "(", "header", "http", ".", "Header", ",", "key", "string", ")", "[", "]", "string", "{", "var", "result", "[", "]", "string", "\n", "for", "_", ",", "s", ":=", "range", "header", "[", "http", ".", "CanonicalHeaderKey", "(", "key...
// ParseList parses a comma separated list of values. Commas are ignored in // quoted strings. Quoted values are not unescaped or unquoted. Whitespace is // trimmed.
[ "ParseList", "parses", "a", "comma", "separated", "list", "of", "values", ".", "Commas", "are", "ignored", "in", "quoted", "strings", ".", "Quoted", "values", "are", "not", "unescaped", "or", "unquoted", ".", "Whitespace", "is", "trimmed", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/header/header.go#L86-L130
train
golang/gddo
httputil/static.go
FileHandler
func (ss *StaticServer) FileHandler(fileName string) http.Handler { id := fileName fileName = ss.resolve(fileName) return &staticHandler{ ss: ss, id: func(_ string) string { return id }, open: func(_ string) (io.ReadCloser, int64, string, error) { return ss.openFile(fileName) }, } }
go
func (ss *StaticServer) FileHandler(fileName string) http.Handler { id := fileName fileName = ss.resolve(fileName) return &staticHandler{ ss: ss, id: func(_ string) string { return id }, open: func(_ string) (io.ReadCloser, int64, string, error) { return ss.openFile(fileName) }, } }
[ "func", "(", "ss", "*", "StaticServer", ")", "FileHandler", "(", "fileName", "string", ")", "http", ".", "Handler", "{", "id", ":=", "fileName", "\n", "fileName", "=", "ss", ".", "resolve", "(", "fileName", ")", "\n", "return", "&", "staticHandler", "{",...
// FileHandler returns a handler that serves a single file. The file is // specified by a slash separated path relative to the static server's Dir // field.
[ "FileHandler", "returns", "a", "handler", "that", "serves", "a", "single", "file", ".", "The", "file", "is", "specified", "by", "a", "slash", "separated", "path", "relative", "to", "the", "static", "server", "s", "Dir", "field", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/static.go#L96-L104
train
golang/gddo
httputil/static.go
DirectoryHandler
func (ss *StaticServer) DirectoryHandler(prefix, dirName string) http.Handler { if !strings.HasSuffix(prefix, "/") { prefix += "/" } idBase := dirName dirName = ss.resolve(dirName) return &staticHandler{ ss: ss, id: func(p string) string { if !strings.HasPrefix(p, prefix) { return "." } return path.Join(idBase, p[len(prefix):]) }, open: func(p string) (io.ReadCloser, int64, string, error) { if !strings.HasPrefix(p, prefix) { return nil, 0, "", errors.New("request url does not match directory prefix") } p = p[len(prefix):] return ss.openFile(filepath.Join(dirName, filepath.FromSlash(p))) }, } }
go
func (ss *StaticServer) DirectoryHandler(prefix, dirName string) http.Handler { if !strings.HasSuffix(prefix, "/") { prefix += "/" } idBase := dirName dirName = ss.resolve(dirName) return &staticHandler{ ss: ss, id: func(p string) string { if !strings.HasPrefix(p, prefix) { return "." } return path.Join(idBase, p[len(prefix):]) }, open: func(p string) (io.ReadCloser, int64, string, error) { if !strings.HasPrefix(p, prefix) { return nil, 0, "", errors.New("request url does not match directory prefix") } p = p[len(prefix):] return ss.openFile(filepath.Join(dirName, filepath.FromSlash(p))) }, } }
[ "func", "(", "ss", "*", "StaticServer", ")", "DirectoryHandler", "(", "prefix", ",", "dirName", "string", ")", "http", ".", "Handler", "{", "if", "!", "strings", ".", "HasSuffix", "(", "prefix", ",", "\"", "\"", ")", "{", "prefix", "+=", "\"", "\"", ...
// DirectoryHandler returns a handler that serves files from a directory tree. // The directory is specified by a slash separated path relative to the static // server's Dir field.
[ "DirectoryHandler", "returns", "a", "handler", "that", "serves", "files", "from", "a", "directory", "tree", ".", "The", "directory", "is", "specified", "by", "a", "slash", "separated", "path", "relative", "to", "the", "static", "server", "s", "Dir", "field", ...
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/static.go#L109-L131
train
golang/gddo
httputil/static.go
FilesHandler
func (ss *StaticServer) FilesHandler(fileNames ...string) http.Handler { // todo: cache concatenated files on disk and serve from there. mimeType := ss.mimeType(fileNames[0]) var buf []byte var openErr error for _, fileName := range fileNames { p, err := ioutil.ReadFile(ss.resolve(fileName)) if err != nil { openErr = err buf = nil break } buf = append(buf, p...) } id := strings.Join(fileNames, " ") return &staticHandler{ ss: ss, id: func(_ string) string { return id }, open: func(p string) (io.ReadCloser, int64, string, error) { return ioutil.NopCloser(bytes.NewReader(buf)), int64(len(buf)), mimeType, openErr }, } }
go
func (ss *StaticServer) FilesHandler(fileNames ...string) http.Handler { // todo: cache concatenated files on disk and serve from there. mimeType := ss.mimeType(fileNames[0]) var buf []byte var openErr error for _, fileName := range fileNames { p, err := ioutil.ReadFile(ss.resolve(fileName)) if err != nil { openErr = err buf = nil break } buf = append(buf, p...) } id := strings.Join(fileNames, " ") return &staticHandler{ ss: ss, id: func(_ string) string { return id }, open: func(p string) (io.ReadCloser, int64, string, error) { return ioutil.NopCloser(bytes.NewReader(buf)), int64(len(buf)), mimeType, openErr }, } }
[ "func", "(", "ss", "*", "StaticServer", ")", "FilesHandler", "(", "fileNames", "...", "string", ")", "http", ".", "Handler", "{", "// todo: cache concatenated files on disk and serve from there.", "mimeType", ":=", "ss", ".", "mimeType", "(", "fileNames", "[", "0", ...
// FilesHandler returns a handler that serves the concatentation of the // specified files. The files are specified by slash separated paths relative // to the static server's Dir field.
[ "FilesHandler", "returns", "a", "handler", "that", "serves", "the", "concatentation", "of", "the", "specified", "files", ".", "The", "files", "are", "specified", "by", "slash", "separated", "paths", "relative", "to", "the", "static", "server", "s", "Dir", "fie...
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/static.go#L136-L163
train
golang/gddo
database/database.go
New
func New(serverURI string, idleTimeout time.Duration, logConn bool, gaeEndpoint string) (*Database, error) { pool := &redis.Pool{ Dial: newDBDialer(serverURI, logConn), MaxIdle: 10, IdleTimeout: idleTimeout, } var rc *remote_api.Client if gaeEndpoint != "" { var err error if rc, err = newRemoteClient(gaeEndpoint); err != nil { return nil, err } } else { log.Println("remote_api client not setup to use App Engine search") } return &Database{Pool: pool, RemoteClient: rc}, nil }
go
func New(serverURI string, idleTimeout time.Duration, logConn bool, gaeEndpoint string) (*Database, error) { pool := &redis.Pool{ Dial: newDBDialer(serverURI, logConn), MaxIdle: 10, IdleTimeout: idleTimeout, } var rc *remote_api.Client if gaeEndpoint != "" { var err error if rc, err = newRemoteClient(gaeEndpoint); err != nil { return nil, err } } else { log.Println("remote_api client not setup to use App Engine search") } return &Database{Pool: pool, RemoteClient: rc}, nil }
[ "func", "New", "(", "serverURI", "string", ",", "idleTimeout", "time", ".", "Duration", ",", "logConn", "bool", ",", "gaeEndpoint", "string", ")", "(", "*", "Database", ",", "error", ")", "{", "pool", ":=", "&", "redis", ".", "Pool", "{", "Dial", ":", ...
// New creates a gddo database. serverURI, idleTimeout, and logConn configure // the use of redis. gaeEndpoint is the target of the App Engine remoteapi // endpoint.
[ "New", "creates", "a", "gddo", "database", ".", "serverURI", "idleTimeout", "and", "logConn", "configure", "the", "use", "of", "redis", ".", "gaeEndpoint", "is", "the", "target", "of", "the", "App", "Engine", "remoteapi", "endpoint", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L140-L158
train
golang/gddo
database/database.go
pkgIDAndImportCount
func pkgIDAndImportCount(c redis.Conn, path string) (id string, numImported int, err error) { numImported, err = redis.Int(c.Do("SCARD", "index:import:"+path)) if err != nil { return } id, err = redis.String(c.Do("HGET", "ids", path)) if err == redis.ErrNil { return "", 0, nil } else if err != nil { return "", 0, err } return id, numImported, nil }
go
func pkgIDAndImportCount(c redis.Conn, path string) (id string, numImported int, err error) { numImported, err = redis.Int(c.Do("SCARD", "index:import:"+path)) if err != nil { return } id, err = redis.String(c.Do("HGET", "ids", path)) if err == redis.ErrNil { return "", 0, nil } else if err != nil { return "", 0, err } return id, numImported, nil }
[ "func", "pkgIDAndImportCount", "(", "c", "redis", ".", "Conn", ",", "path", "string", ")", "(", "id", "string", ",", "numImported", "int", ",", "err", "error", ")", "{", "numImported", ",", "err", "=", "redis", ".", "Int", "(", "c", ".", "Do", "(", ...
// pkgIDAndImportCount returns the ID and import count of a specified package.
[ "pkgIDAndImportCount", "returns", "the", "ID", "and", "import", "count", "of", "a", "specified", "package", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L363-L375
train
golang/gddo
database/database.go
SetNextCrawl
func (db *Database) SetNextCrawl(path string, t time.Time) error { c := db.Pool.Get() defer c.Close() _, err := setNextCrawlScript.Do(c, path, t.Unix()) return err }
go
func (db *Database) SetNextCrawl(path string, t time.Time) error { c := db.Pool.Get() defer c.Close() _, err := setNextCrawlScript.Do(c, path, t.Unix()) return err }
[ "func", "(", "db", "*", "Database", ")", "SetNextCrawl", "(", "path", "string", ",", "t", "time", ".", "Time", ")", "error", "{", "c", ":=", "db", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n", "_", ",", ...
// SetNextCrawl sets the next crawl time for a package.
[ "SetNextCrawl", "sets", "the", "next", "crawl", "time", "for", "a", "package", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L422-L427
train
golang/gddo
database/database.go
Get
func (db *Database) Get(ctx context.Context, path string) (*doc.Package, []Package, time.Time, error) { c := db.Pool.Get() defer c.Close() pdoc, nextCrawl, err := db.getDoc(ctx, c, path) if err != nil { return nil, nil, time.Time{}, err } if pdoc != nil { // fixup for speclal "-" path. path = pdoc.ImportPath } subdirs, err := db.getSubdirs(c, path, pdoc) if err != nil { return nil, nil, time.Time{}, err } return pdoc, subdirs, nextCrawl, nil }
go
func (db *Database) Get(ctx context.Context, path string) (*doc.Package, []Package, time.Time, error) { c := db.Pool.Get() defer c.Close() pdoc, nextCrawl, err := db.getDoc(ctx, c, path) if err != nil { return nil, nil, time.Time{}, err } if pdoc != nil { // fixup for speclal "-" path. path = pdoc.ImportPath } subdirs, err := db.getSubdirs(c, path, pdoc) if err != nil { return nil, nil, time.Time{}, err } return pdoc, subdirs, nextCrawl, nil }
[ "func", "(", "db", "*", "Database", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "*", "doc", ".", "Package", ",", "[", "]", "Package", ",", "time", ".", "Time", ",", "error", ")", "{", "c", ":=", "db", "."...
// Get gets the package documentation and sub-directories for the the given // import path.
[ "Get", "gets", "the", "package", "documentation", "and", "sub", "-", "directories", "for", "the", "the", "given", "import", "path", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L588-L607
train
golang/gddo
database/database.go
Delete
func (db *Database) Delete(ctx context.Context, path string) error { c := db.Pool.Get() defer c.Close() id, err := redis.String(c.Do("HGET", "ids", path)) if err == redis.ErrNil { return nil } if err != nil { return err } if err := db.DeleteIndex(ctx, id); err != nil { return err } _, err = deleteScript.Do(c, path) return err }
go
func (db *Database) Delete(ctx context.Context, path string) error { c := db.Pool.Get() defer c.Close() id, err := redis.String(c.Do("HGET", "ids", path)) if err == redis.ErrNil { return nil } if err != nil { return err } if err := db.DeleteIndex(ctx, id); err != nil { return err } _, err = deleteScript.Do(c, path) return err }
[ "func", "(", "db", "*", "Database", ")", "Delete", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "error", "{", "c", ":=", "db", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n\n", "id", ",...
// Delete deletes the documentation for the given import path.
[ "Delete", "deletes", "the", "documentation", "for", "the", "given", "import", "path", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L635-L652
train
golang/gddo
database/database.go
Block
func (db *Database) Block(root string) error { c := db.Pool.Get() defer c.Close() if _, err := c.Do("SADD", "block", root); err != nil { return err } // Remove all packages under the project root. keys, err := redis.Strings(c.Do("HKEYS", "ids")) if err != nil { return err } ctx := context.Background() for _, key := range keys { if key == root || strings.HasPrefix(key, root) && key[len(root)] == '/' { id, err := redis.String(c.Do("HGET", "ids", key)) if err != nil { return fmt.Errorf("cannot get package id for %s: %v", key, err) } if _, err := deleteScript.Do(c, key); err != nil { return err } if err := db.DeleteIndex(ctx, id); err != nil && err != search.ErrNoSuchDocument { return err } } } // Remove all packages in the newCrawl set under the project root. newCrawls, err := redis.Strings(c.Do("SORT", "newCrawl", "BY", "nosort")) if err != nil { return fmt.Errorf("cannot list newCrawl: %v", err) } for _, nc := range newCrawls { if nc == root || strings.HasPrefix(nc, root) && nc[len(root)] == '/' { if _, err := deleteScript.Do(c, nc); err != nil { return err } } } return nil }
go
func (db *Database) Block(root string) error { c := db.Pool.Get() defer c.Close() if _, err := c.Do("SADD", "block", root); err != nil { return err } // Remove all packages under the project root. keys, err := redis.Strings(c.Do("HKEYS", "ids")) if err != nil { return err } ctx := context.Background() for _, key := range keys { if key == root || strings.HasPrefix(key, root) && key[len(root)] == '/' { id, err := redis.String(c.Do("HGET", "ids", key)) if err != nil { return fmt.Errorf("cannot get package id for %s: %v", key, err) } if _, err := deleteScript.Do(c, key); err != nil { return err } if err := db.DeleteIndex(ctx, id); err != nil && err != search.ErrNoSuchDocument { return err } } } // Remove all packages in the newCrawl set under the project root. newCrawls, err := redis.Strings(c.Do("SORT", "newCrawl", "BY", "nosort")) if err != nil { return fmt.Errorf("cannot list newCrawl: %v", err) } for _, nc := range newCrawls { if nc == root || strings.HasPrefix(nc, root) && nc[len(root)] == '/' { if _, err := deleteScript.Do(c, nc); err != nil { return err } } } return nil }
[ "func", "(", "db", "*", "Database", ")", "Block", "(", "root", "string", ")", "error", "{", "c", ":=", "db", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n", "if", "_", ",", "err", ":=", "c", ".", "Do", "...
// Block puts a domain, repo or package into the block set, removes all the // packages under it from the database and prevents future crawling from it.
[ "Block", "puts", "a", "domain", "repo", "or", "package", "into", "the", "block", "set", "removes", "all", "the", "packages", "under", "it", "from", "the", "database", "and", "prevents", "future", "crawling", "from", "it", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L773-L814
train
golang/gddo
database/database.go
Do
func (db *Database) Do(f func(*PackageInfo) error) error { c := db.Pool.Get() defer c.Close() cursor := 0 c.Send("SCAN", cursor, "MATCH", "pkg:*") c.Flush() for { // Receive previous SCAN. values, err := redis.Values(c.Receive()) if err != nil { return err } var keys [][]byte if _, err := redis.Scan(values, &cursor, &keys); err != nil { return err } if cursor == 0 { break } for _, key := range keys { c.Send("HMGET", key, "gob", "score", "kind", "path", "terms", "synopis") } c.Send("SCAN", cursor, "MATCH", "pkg:*") c.Flush() for _ = range keys { values, err := redis.Values(c.Receive()) if err != nil { return err } var ( pi PackageInfo p []byte path string terms string synopsis string ) if _, err := redis.Scan(values, &p, &pi.Score, &pi.Kind, &path, &terms, &synopsis); err != nil { return err } if p == nil { continue } pi.Size = len(path) + len(p) + len(terms) + len(synopsis) p, err = snappy.Decode(nil, p) if err != nil { return fmt.Errorf("snappy decoding %s: %v", path, err) } if err := gob.NewDecoder(bytes.NewReader(p)).Decode(&pi.PDoc); err != nil { return fmt.Errorf("gob decoding %s: %v", path, err) } if err := f(&pi); err != nil { return fmt.Errorf("func %s: %v", path, err) } } } return nil }
go
func (db *Database) Do(f func(*PackageInfo) error) error { c := db.Pool.Get() defer c.Close() cursor := 0 c.Send("SCAN", cursor, "MATCH", "pkg:*") c.Flush() for { // Receive previous SCAN. values, err := redis.Values(c.Receive()) if err != nil { return err } var keys [][]byte if _, err := redis.Scan(values, &cursor, &keys); err != nil { return err } if cursor == 0 { break } for _, key := range keys { c.Send("HMGET", key, "gob", "score", "kind", "path", "terms", "synopis") } c.Send("SCAN", cursor, "MATCH", "pkg:*") c.Flush() for _ = range keys { values, err := redis.Values(c.Receive()) if err != nil { return err } var ( pi PackageInfo p []byte path string terms string synopsis string ) if _, err := redis.Scan(values, &p, &pi.Score, &pi.Kind, &path, &terms, &synopsis); err != nil { return err } if p == nil { continue } pi.Size = len(path) + len(p) + len(terms) + len(synopsis) p, err = snappy.Decode(nil, p) if err != nil { return fmt.Errorf("snappy decoding %s: %v", path, err) } if err := gob.NewDecoder(bytes.NewReader(p)).Decode(&pi.PDoc); err != nil { return fmt.Errorf("gob decoding %s: %v", path, err) } if err := f(&pi); err != nil { return fmt.Errorf("func %s: %v", path, err) } } } return nil }
[ "func", "(", "db", "*", "Database", ")", "Do", "(", "f", "func", "(", "*", "PackageInfo", ")", "error", ")", "error", "{", "c", ":=", "db", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "c", ".", "Close", "(", ")", "\n", "cursor", ":=", "...
// Do executes function f for each document in the database.
[ "Do", "executes", "function", "f", "for", "each", "document", "in", "the", "database", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L927-L989
train
golang/gddo
database/database.go
Reindex
func (db *Database) Reindex(ctx context.Context) error { if db.RemoteClient == nil { return errors.New("database.Reindex: no App Engine endpoint given") } c := db.Pool.Get() defer c.Close() idx, err := search.Open("packages") if err != nil { return fmt.Errorf("database: failed to open packages: %v", err) } npkgs := 0 for { // Get 200 packages from the nextCrawl set each time. Use npkgs as a cursor // to store the current position we actually indexed. Retry from the cursor // position if we received a timeout error from app engine. values, err := redis.Values(c.Do( "SORT", "nextCrawl", "LIMIT", strconv.Itoa(npkgs), "200", "GET", "pkg:*->path", "GET", "pkg:*->synopsis", "GET", "pkg:*->score", )) if err != nil { return err } if len(values) == 0 { break // all done } // The Search API should support put in batches of up to 200 documents, // the Go version of this API does not support this yet. // TODO(shantuo): Put packages in batch operations. for ; len(values) > 0; npkgs++ { var pdoc doc.Package var score float64 values, err = redis.Scan(values, &pdoc.ImportPath, &pdoc.Synopsis, &score) if err != nil { return err } // There are some corrupted data in our current database // that causes an error when putting the package into the // search index which only supports UTF8 encoding. if !utf8.ValidString(pdoc.Synopsis) { pdoc.Synopsis = "" } id, n, err := pkgIDAndImportCount(c, pdoc.ImportPath) if err != nil { return err } if _, err := idx.Put(db.RemoteClient.NewContext(ctx), id, &Package{ Path: pdoc.ImportPath, Synopsis: pdoc.Synopsis, Score: score, ImportCount: n, }); err != nil { if appengine.IsTimeoutError(err) { log.Printf("App Engine timeout: %v. Continue...", err) break } return fmt.Errorf("Failed to put index %s: %v", id, err) } } } log.Printf("%d packages are reindexed", npkgs) return nil }
go
func (db *Database) Reindex(ctx context.Context) error { if db.RemoteClient == nil { return errors.New("database.Reindex: no App Engine endpoint given") } c := db.Pool.Get() defer c.Close() idx, err := search.Open("packages") if err != nil { return fmt.Errorf("database: failed to open packages: %v", err) } npkgs := 0 for { // Get 200 packages from the nextCrawl set each time. Use npkgs as a cursor // to store the current position we actually indexed. Retry from the cursor // position if we received a timeout error from app engine. values, err := redis.Values(c.Do( "SORT", "nextCrawl", "LIMIT", strconv.Itoa(npkgs), "200", "GET", "pkg:*->path", "GET", "pkg:*->synopsis", "GET", "pkg:*->score", )) if err != nil { return err } if len(values) == 0 { break // all done } // The Search API should support put in batches of up to 200 documents, // the Go version of this API does not support this yet. // TODO(shantuo): Put packages in batch operations. for ; len(values) > 0; npkgs++ { var pdoc doc.Package var score float64 values, err = redis.Scan(values, &pdoc.ImportPath, &pdoc.Synopsis, &score) if err != nil { return err } // There are some corrupted data in our current database // that causes an error when putting the package into the // search index which only supports UTF8 encoding. if !utf8.ValidString(pdoc.Synopsis) { pdoc.Synopsis = "" } id, n, err := pkgIDAndImportCount(c, pdoc.ImportPath) if err != nil { return err } if _, err := idx.Put(db.RemoteClient.NewContext(ctx), id, &Package{ Path: pdoc.ImportPath, Synopsis: pdoc.Synopsis, Score: score, ImportCount: n, }); err != nil { if appengine.IsTimeoutError(err) { log.Printf("App Engine timeout: %v. Continue...", err) break } return fmt.Errorf("Failed to put index %s: %v", id, err) } } } log.Printf("%d packages are reindexed", npkgs) return nil }
[ "func", "(", "db", "*", "Database", ")", "Reindex", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "db", ".", "RemoteClient", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "c", ":=", "...
// Reindex gets all the packages in database and put them into the search index. // This will update the search index with the path, synopsis, score, import counts // of all the packages in the database.
[ "Reindex", "gets", "all", "the", "packages", "in", "database", "and", "put", "them", "into", "the", "search", "index", ".", "This", "will", "update", "the", "search", "index", "with", "the", "path", "synopsis", "score", "import", "counts", "of", "all", "th...
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L1238-L1305
train
golang/gddo
database/database.go
PutIndex
func (db *Database) PutIndex(ctx context.Context, pdoc *doc.Package, id string, score float64, importCount int) error { if db.RemoteClient == nil { return nil } return putIndex(db.RemoteClient.NewContext(ctx), pdoc, id, score, importCount) }
go
func (db *Database) PutIndex(ctx context.Context, pdoc *doc.Package, id string, score float64, importCount int) error { if db.RemoteClient == nil { return nil } return putIndex(db.RemoteClient.NewContext(ctx), pdoc, id, score, importCount) }
[ "func", "(", "db", "*", "Database", ")", "PutIndex", "(", "ctx", "context", ".", "Context", ",", "pdoc", "*", "doc", ".", "Package", ",", "id", "string", ",", "score", "float64", ",", "importCount", "int", ")", "error", "{", "if", "db", ".", "RemoteC...
// PutIndex puts a package into App Engine search index. ID is the package ID in the database. // It is no-op when running locally without setting up remote_api.
[ "PutIndex", "puts", "a", "package", "into", "App", "Engine", "search", "index", ".", "ID", "is", "the", "package", "ID", "in", "the", "database", ".", "It", "is", "no", "-", "op", "when", "running", "locally", "without", "setting", "up", "remote_api", "....
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L1316-L1321
train
golang/gddo
database/database.go
DeleteIndex
func (db *Database) DeleteIndex(ctx context.Context, id string) error { if db.RemoteClient == nil { return nil } return deleteIndex(db.RemoteClient.NewContext(ctx), id) }
go
func (db *Database) DeleteIndex(ctx context.Context, id string) error { if db.RemoteClient == nil { return nil } return deleteIndex(db.RemoteClient.NewContext(ctx), id) }
[ "func", "(", "db", "*", "Database", ")", "DeleteIndex", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "error", "{", "if", "db", ".", "RemoteClient", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "deleteIndex", "(", ...
// DeleteIndex deletes a package from App Engine search index. ID is the package ID in the database. // It is no-op when running locally without setting up remote_api.
[ "DeleteIndex", "deletes", "a", "package", "from", "App", "Engine", "search", "index", ".", "ID", "is", "the", "package", "ID", "in", "the", "database", ".", "It", "is", "no", "-", "op", "when", "running", "locally", "without", "setting", "up", "remote_api"...
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/database.go#L1325-L1330
train
golang/gddo
gosrc/gosrc.go
GetPresentation
func GetPresentation(ctx context.Context, client *http.Client, importPath string) (*Presentation, error) { ext := path.Ext(importPath) if ext != ".slide" && ext != ".article" { return nil, NotFoundError{Message: "unknown file extension."} } importPath, file := path.Split(importPath) importPath = strings.TrimSuffix(importPath, "/") for _, s := range services { if s.getPresentation == nil { continue } match, err := s.match(importPath) if err != nil { return nil, err } if match != nil { match["file"] = file return s.getPresentation(ctx, client, match) } } return nil, NotFoundError{Message: "path does not match registered service"} }
go
func GetPresentation(ctx context.Context, client *http.Client, importPath string) (*Presentation, error) { ext := path.Ext(importPath) if ext != ".slide" && ext != ".article" { return nil, NotFoundError{Message: "unknown file extension."} } importPath, file := path.Split(importPath) importPath = strings.TrimSuffix(importPath, "/") for _, s := range services { if s.getPresentation == nil { continue } match, err := s.match(importPath) if err != nil { return nil, err } if match != nil { match["file"] = file return s.getPresentation(ctx, client, match) } } return nil, NotFoundError{Message: "path does not match registered service"} }
[ "func", "GetPresentation", "(", "ctx", "context", ".", "Context", ",", "client", "*", "http", ".", "Client", ",", "importPath", "string", ")", "(", "*", "Presentation", ",", "error", ")", "{", "ext", ":=", "path", ".", "Ext", "(", "importPath", ")", "\...
// GetPresentation gets a presentation from the the given path.
[ "GetPresentation", "gets", "a", "presentation", "from", "the", "the", "given", "path", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/gosrc.go#L503-L525
train
golang/gddo
gosrc/gosrc.go
GetProject
func GetProject(ctx context.Context, client *http.Client, importPath string) (*Project, error) { for _, s := range services { if s.getProject == nil { continue } match, err := s.match(importPath) if err != nil { return nil, err } if match != nil { return s.getProject(ctx, client, match) } } return nil, NotFoundError{Message: "path does not match registered service"} }
go
func GetProject(ctx context.Context, client *http.Client, importPath string) (*Project, error) { for _, s := range services { if s.getProject == nil { continue } match, err := s.match(importPath) if err != nil { return nil, err } if match != nil { return s.getProject(ctx, client, match) } } return nil, NotFoundError{Message: "path does not match registered service"} }
[ "func", "GetProject", "(", "ctx", "context", ".", "Context", ",", "client", "*", "http", ".", "Client", ",", "importPath", "string", ")", "(", "*", "Project", ",", "error", ")", "{", "for", "_", ",", "s", ":=", "range", "services", "{", "if", "s", ...
// GetProject gets information about a repository.
[ "GetProject", "gets", "information", "about", "a", "repository", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/gosrc.go#L528-L542
train
golang/gddo
gosrc/gosrc.go
MaybeRedirect
func MaybeRedirect(importPath, importComment, resolvedGitHubPath string) error { switch { case importComment != "": // Redirect to import comment, if not already there. if importPath != importComment { return NotFoundError{ Message: "not at canonical import path", Redirect: importComment, } } // Redirect to GitHub's reported canonical casing when there's no import comment, // and the import path differs from resolved GitHub path only in case. case importComment == "" && resolvedGitHubPath != "" && strings.EqualFold(importPath, resolvedGitHubPath): // Redirect to resolved GitHub path, if not already there. if importPath != resolvedGitHubPath { return NotFoundError{ Message: "not at canonical import path", Redirect: resolvedGitHubPath, } } } // No redirect. return nil }
go
func MaybeRedirect(importPath, importComment, resolvedGitHubPath string) error { switch { case importComment != "": // Redirect to import comment, if not already there. if importPath != importComment { return NotFoundError{ Message: "not at canonical import path", Redirect: importComment, } } // Redirect to GitHub's reported canonical casing when there's no import comment, // and the import path differs from resolved GitHub path only in case. case importComment == "" && resolvedGitHubPath != "" && strings.EqualFold(importPath, resolvedGitHubPath): // Redirect to resolved GitHub path, if not already there. if importPath != resolvedGitHubPath { return NotFoundError{ Message: "not at canonical import path", Redirect: resolvedGitHubPath, } } } // No redirect. return nil }
[ "func", "MaybeRedirect", "(", "importPath", ",", "importComment", ",", "resolvedGitHubPath", "string", ")", "error", "{", "switch", "{", "case", "importComment", "!=", "\"", "\"", ":", "// Redirect to import comment, if not already there.", "if", "importPath", "!=", "...
// MaybeRedirect uses the provided import path, import comment, and resolved GitHub path // to make a decision of whether to redirect to another, more canonical import path. // It returns nil error to indicate no redirect, or a NotFoundError error to redirect.
[ "MaybeRedirect", "uses", "the", "provided", "import", "path", "import", "comment", "and", "resolved", "GitHub", "path", "to", "make", "a", "decision", "of", "whether", "to", "redirect", "to", "another", "more", "canonical", "import", "path", ".", "It", "return...
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/gosrc.go#L547-L574
train
golang/gddo
gosrc/build.go
Import
func (dir *Directory) Import(ctx *build.Context, mode build.ImportMode) (*build.Package, error) { safeCopy := *ctx ctx = &safeCopy ctx.JoinPath = path.Join ctx.IsAbsPath = path.IsAbs ctx.SplitPathList = func(list string) []string { return strings.Split(list, ":") } ctx.IsDir = func(path string) bool { return path == "." } ctx.HasSubdir = func(root, dir string) (rel string, ok bool) { return "", false } ctx.ReadDir = dir.readDir ctx.OpenFile = dir.openFile return ctx.ImportDir(".", mode) }
go
func (dir *Directory) Import(ctx *build.Context, mode build.ImportMode) (*build.Package, error) { safeCopy := *ctx ctx = &safeCopy ctx.JoinPath = path.Join ctx.IsAbsPath = path.IsAbs ctx.SplitPathList = func(list string) []string { return strings.Split(list, ":") } ctx.IsDir = func(path string) bool { return path == "." } ctx.HasSubdir = func(root, dir string) (rel string, ok bool) { return "", false } ctx.ReadDir = dir.readDir ctx.OpenFile = dir.openFile return ctx.ImportDir(".", mode) }
[ "func", "(", "dir", "*", "Directory", ")", "Import", "(", "ctx", "*", "build", ".", "Context", ",", "mode", "build", ".", "ImportMode", ")", "(", "*", "build", ".", "Package", ",", "error", ")", "{", "safeCopy", ":=", "*", "ctx", "\n", "ctx", "=", ...
// Import returns details about the package in the directory.
[ "Import", "returns", "details", "about", "the", "package", "in", "the", "directory", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/build.go#L21-L32
train
golang/gddo
gddo-server/template.go
getFlashMessages
func getFlashMessages(resp http.ResponseWriter, req *http.Request) []flashMessage { c, err := req.Cookie("flash") if err == http.ErrNoCookie { return nil } http.SetCookie(resp, &http.Cookie{Name: "flash", Path: "/", MaxAge: -1, Expires: time.Now().Add(-100 * 24 * time.Hour)}) if err != nil { return nil } p, err := base64.URLEncoding.DecodeString(c.Value) if err != nil { return nil } var messages []flashMessage for _, s := range strings.Split(string(p), "\000") { idArgs := strings.Split(s, "\001") messages = append(messages, flashMessage{ID: idArgs[0], Args: idArgs[1:]}) } return messages }
go
func getFlashMessages(resp http.ResponseWriter, req *http.Request) []flashMessage { c, err := req.Cookie("flash") if err == http.ErrNoCookie { return nil } http.SetCookie(resp, &http.Cookie{Name: "flash", Path: "/", MaxAge: -1, Expires: time.Now().Add(-100 * 24 * time.Hour)}) if err != nil { return nil } p, err := base64.URLEncoding.DecodeString(c.Value) if err != nil { return nil } var messages []flashMessage for _, s := range strings.Split(string(p), "\000") { idArgs := strings.Split(s, "\001") messages = append(messages, flashMessage{ID: idArgs[0], Args: idArgs[1:]}) } return messages }
[ "func", "getFlashMessages", "(", "resp", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "[", "]", "flashMessage", "{", "c", ",", "err", ":=", "req", ".", "Cookie", "(", "\"", "\"", ")", "\n", "if", "err", "==", "http", ...
// getFlashMessages retrieves flash messages from the request and clears the flash cookie if needed.
[ "getFlashMessages", "retrieves", "flash", "messages", "from", "the", "request", "and", "clears", "the", "flash", "cookie", "if", "needed", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L41-L60
train
golang/gddo
gddo-server/template.go
setFlashMessages
func setFlashMessages(resp http.ResponseWriter, messages []flashMessage) { var buf []byte for i, message := range messages { if i > 0 { buf = append(buf, '\000') } buf = append(buf, message.ID...) for _, arg := range message.Args { buf = append(buf, '\001') buf = append(buf, arg...) } } value := base64.URLEncoding.EncodeToString(buf) http.SetCookie(resp, &http.Cookie{Name: "flash", Value: value, Path: "/"}) }
go
func setFlashMessages(resp http.ResponseWriter, messages []flashMessage) { var buf []byte for i, message := range messages { if i > 0 { buf = append(buf, '\000') } buf = append(buf, message.ID...) for _, arg := range message.Args { buf = append(buf, '\001') buf = append(buf, arg...) } } value := base64.URLEncoding.EncodeToString(buf) http.SetCookie(resp, &http.Cookie{Name: "flash", Value: value, Path: "/"}) }
[ "func", "setFlashMessages", "(", "resp", "http", ".", "ResponseWriter", ",", "messages", "[", "]", "flashMessage", ")", "{", "var", "buf", "[", "]", "byte", "\n", "for", "i", ",", "message", ":=", "range", "messages", "{", "if", "i", ">", "0", "{", "...
// setFlashMessages sets a cookie with the given flash messages.
[ "setFlashMessages", "sets", "a", "cookie", "with", "the", "given", "flash", "messages", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L63-L77
train
golang/gddo
gddo-server/template.go
UsesLink
func (pdoc *tdoc) UsesLink(title string, defParts ...string) htemp.HTML { if pdoc.sourcegraphURL == "" { return "" } var def string switch len(defParts) { case 1: // Funcs and types have one def part. def = defParts[0] case 3: // Methods have three def parts, the original receiver name, actual receiver name and method name. orig, recv, methodName := defParts[0], defParts[1], defParts[2] if orig == "" { // TODO: Remove this fallback after 2016-08-05. It's only needed temporarily to backfill data. // Actual receiver is not needed, it's only used because original receiver value // was recently added to gddo/doc package and will be blank until next package rebuild. // // Use actual receiver as fallback. orig = recv } // Trim "*" from "*T" if it's a pointer receiver method. typeName := strings.TrimPrefix(orig, "*") def = typeName + "/" + methodName default: panic(fmt.Errorf("%v defParts, want 1 or 3", len(defParts))) } q := url.Values{ "repo": {pdoc.ProjectRoot}, "pkg": {pdoc.ImportPath}, "def": {def}, } u := pdoc.sourcegraphURL + "/-/godoc/refs?" + q.Encode() return htemp.HTML(fmt.Sprintf(`<a class="uses" title="%s" href="%s">Uses</a>`, htemp.HTMLEscapeString(title), htemp.HTMLEscapeString(u))) }
go
func (pdoc *tdoc) UsesLink(title string, defParts ...string) htemp.HTML { if pdoc.sourcegraphURL == "" { return "" } var def string switch len(defParts) { case 1: // Funcs and types have one def part. def = defParts[0] case 3: // Methods have three def parts, the original receiver name, actual receiver name and method name. orig, recv, methodName := defParts[0], defParts[1], defParts[2] if orig == "" { // TODO: Remove this fallback after 2016-08-05. It's only needed temporarily to backfill data. // Actual receiver is not needed, it's only used because original receiver value // was recently added to gddo/doc package and will be blank until next package rebuild. // // Use actual receiver as fallback. orig = recv } // Trim "*" from "*T" if it's a pointer receiver method. typeName := strings.TrimPrefix(orig, "*") def = typeName + "/" + methodName default: panic(fmt.Errorf("%v defParts, want 1 or 3", len(defParts))) } q := url.Values{ "repo": {pdoc.ProjectRoot}, "pkg": {pdoc.ImportPath}, "def": {def}, } u := pdoc.sourcegraphURL + "/-/godoc/refs?" + q.Encode() return htemp.HTML(fmt.Sprintf(`<a class="uses" title="%s" href="%s">Uses</a>`, htemp.HTMLEscapeString(title), htemp.HTMLEscapeString(u))) }
[ "func", "(", "pdoc", "*", "tdoc", ")", "UsesLink", "(", "title", "string", ",", "defParts", "...", "string", ")", "htemp", ".", "HTML", "{", "if", "pdoc", ".", "sourcegraphURL", "==", "\"", "\"", "{", "return", "\"", "\"", "\n", "}", "\n\n", "var", ...
// UsesLink generates a link to uses of a symbol definition. // title is used as the tooltip. defParts are parts of the symbol definition name.
[ "UsesLink", "generates", "a", "link", "to", "uses", "of", "a", "symbol", "definition", ".", "title", "is", "used", "as", "the", "tooltip", ".", "defParts", "are", "parts", "of", "the", "symbol", "definition", "name", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L114-L153
train
golang/gddo
gddo-server/template.go
relativePathFn
func relativePathFn(path string, parentPath interface{}) string { if p, ok := parentPath.(string); ok && p != "" && strings.HasPrefix(path, p) { path = path[len(p)+1:] } return path }
go
func relativePathFn(path string, parentPath interface{}) string { if p, ok := parentPath.(string); ok && p != "" && strings.HasPrefix(path, p) { path = path[len(p)+1:] } return path }
[ "func", "relativePathFn", "(", "path", "string", ",", "parentPath", "interface", "{", "}", ")", "string", "{", "if", "p", ",", "ok", ":=", "parentPath", ".", "(", "string", ")", ";", "ok", "&&", "p", "!=", "\"", "\"", "&&", "strings", ".", "HasPrefix...
// relativePathFn formats an import path as HTML.
[ "relativePathFn", "formats", "an", "import", "path", "as", "HTML", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L321-L326
train
golang/gddo
gddo-server/template.go
importPathFn
func importPathFn(path string) htemp.HTML { path = htemp.HTMLEscapeString(path) if len(path) > 45 { // Allow long import paths to break following "/" path = strings.Replace(path, "/", "/&#8203;", -1) } return htemp.HTML(path) }
go
func importPathFn(path string) htemp.HTML { path = htemp.HTMLEscapeString(path) if len(path) > 45 { // Allow long import paths to break following "/" path = strings.Replace(path, "/", "/&#8203;", -1) } return htemp.HTML(path) }
[ "func", "importPathFn", "(", "path", "string", ")", "htemp", ".", "HTML", "{", "path", "=", "htemp", ".", "HTMLEscapeString", "(", "path", ")", "\n", "if", "len", "(", "path", ")", ">", "45", "{", "// Allow long import paths to break following \"/\"", "path", ...
// importPathFn formats an import with zero width space characters to allow for breaks.
[ "importPathFn", "formats", "an", "import", "with", "zero", "width", "space", "characters", "to", "allow", "for", "breaks", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L329-L336
train
golang/gddo
gddo-server/template.go
commentFn
func commentFn(v string) htemp.HTML { var buf bytes.Buffer godoc.ToHTML(&buf, v, nil) p := buf.Bytes() p = replaceAll(p, h3Pat, func(out, src []byte, m []int) []byte { out = append(out, `<h4 id="`...) out = append(out, src[m[2]:m[3]]...) out = append(out, `">`...) out = append(out, src[m[4]:m[5]]...) out = append(out, ` <a class="permalink" href="#`...) out = append(out, src[m[2]:m[3]]...) out = append(out, `">&para</a></h4>`...) return out }) p = replaceAll(p, rfcPat, func(out, src []byte, m []int) []byte { out = append(out, `<a href="http://tools.ietf.org/html/rfc`...) out = append(out, src[m[2]:m[3]]...) // If available, add section fragment if m[4] != -1 { out = append(out, `#section-`...) out = append(out, src[m[6]:m[7]]...) } out = append(out, `">`...) out = append(out, src[m[0]:m[1]]...) out = append(out, `</a>`...) return out }) p = replaceAll(p, packagePat, func(out, src []byte, m []int) []byte { path := bytes.TrimRight(src[m[2]:m[3]], ".!?:") if !gosrc.IsValidPath(string(path)) { return append(out, src[m[0]:m[1]]...) } out = append(out, src[m[0]:m[2]]...) out = append(out, `<a href="/`...) out = append(out, path...) out = append(out, `">`...) out = append(out, path...) out = append(out, `</a>`...) out = append(out, src[m[2]+len(path):m[1]]...) return out }) return htemp.HTML(p) }
go
func commentFn(v string) htemp.HTML { var buf bytes.Buffer godoc.ToHTML(&buf, v, nil) p := buf.Bytes() p = replaceAll(p, h3Pat, func(out, src []byte, m []int) []byte { out = append(out, `<h4 id="`...) out = append(out, src[m[2]:m[3]]...) out = append(out, `">`...) out = append(out, src[m[4]:m[5]]...) out = append(out, ` <a class="permalink" href="#`...) out = append(out, src[m[2]:m[3]]...) out = append(out, `">&para</a></h4>`...) return out }) p = replaceAll(p, rfcPat, func(out, src []byte, m []int) []byte { out = append(out, `<a href="http://tools.ietf.org/html/rfc`...) out = append(out, src[m[2]:m[3]]...) // If available, add section fragment if m[4] != -1 { out = append(out, `#section-`...) out = append(out, src[m[6]:m[7]]...) } out = append(out, `">`...) out = append(out, src[m[0]:m[1]]...) out = append(out, `</a>`...) return out }) p = replaceAll(p, packagePat, func(out, src []byte, m []int) []byte { path := bytes.TrimRight(src[m[2]:m[3]], ".!?:") if !gosrc.IsValidPath(string(path)) { return append(out, src[m[0]:m[1]]...) } out = append(out, src[m[0]:m[2]]...) out = append(out, `<a href="/`...) out = append(out, path...) out = append(out, `">`...) out = append(out, path...) out = append(out, `</a>`...) out = append(out, src[m[2]+len(path):m[1]]...) return out }) return htemp.HTML(p) }
[ "func", "commentFn", "(", "v", "string", ")", "htemp", ".", "HTML", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "godoc", ".", "ToHTML", "(", "&", "buf", ",", "v", ",", "nil", ")", "\n", "p", ":=", "buf", ".", "Bytes", "(", ")", "\n", "p", ...
// commentFn formats a source code comment as HTML.
[ "commentFn", "formats", "a", "source", "code", "comment", "as", "HTML", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L362-L406
train
golang/gddo
gddo-server/template.go
commentTextFn
func commentTextFn(v string) string { const indent = " " var buf bytes.Buffer godoc.ToText(&buf, v, indent, "\t", 80-2*len(indent)) p := buf.Bytes() return string(p) }
go
func commentTextFn(v string) string { const indent = " " var buf bytes.Buffer godoc.ToText(&buf, v, indent, "\t", 80-2*len(indent)) p := buf.Bytes() return string(p) }
[ "func", "commentTextFn", "(", "v", "string", ")", "string", "{", "const", "indent", "=", "\"", "\"", "\n", "var", "buf", "bytes", ".", "Buffer", "\n", "godoc", ".", "ToText", "(", "&", "buf", ",", "v", ",", "indent", ",", "\"", "\\t", "\"", ",", ...
// commentTextFn formats a source code comment as text.
[ "commentTextFn", "formats", "a", "source", "code", "comment", "as", "text", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/template.go#L409-L415
train
golang/gddo
httputil/transport.go
RoundTrip
func (t *AuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { var reqCopy *http.Request if t.UserAgent != "" { reqCopy = copyRequest(req) reqCopy.Header.Set("User-Agent", t.UserAgent) } if req.URL.Host == "api.github.com" && req.URL.Scheme == "https" { switch { case t.GithubClientID != "" && t.GithubClientSecret != "": if reqCopy == nil { reqCopy = copyRequest(req) } if reqCopy.URL.RawQuery == "" { reqCopy.URL.RawQuery = "client_id=" + t.GithubClientID + "&client_secret=" + t.GithubClientSecret } else { reqCopy.URL.RawQuery += "&client_id=" + t.GithubClientID + "&client_secret=" + t.GithubClientSecret } case t.GithubToken != "": if reqCopy == nil { reqCopy = copyRequest(req) } reqCopy.Header.Set("Authorization", "token "+t.GithubToken) } } if reqCopy != nil { return t.base().RoundTrip(reqCopy) } return t.base().RoundTrip(req) }
go
func (t *AuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { var reqCopy *http.Request if t.UserAgent != "" { reqCopy = copyRequest(req) reqCopy.Header.Set("User-Agent", t.UserAgent) } if req.URL.Host == "api.github.com" && req.URL.Scheme == "https" { switch { case t.GithubClientID != "" && t.GithubClientSecret != "": if reqCopy == nil { reqCopy = copyRequest(req) } if reqCopy.URL.RawQuery == "" { reqCopy.URL.RawQuery = "client_id=" + t.GithubClientID + "&client_secret=" + t.GithubClientSecret } else { reqCopy.URL.RawQuery += "&client_id=" + t.GithubClientID + "&client_secret=" + t.GithubClientSecret } case t.GithubToken != "": if reqCopy == nil { reqCopy = copyRequest(req) } reqCopy.Header.Set("Authorization", "token "+t.GithubToken) } } if reqCopy != nil { return t.base().RoundTrip(reqCopy) } return t.base().RoundTrip(req) }
[ "func", "(", "t", "*", "AuthTransport", ")", "RoundTrip", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "var", "reqCopy", "*", "http", ".", "Request", "\n", "if", "t", ".", "UserAgent", "!=...
// RoundTrip implements the http.RoundTripper interface.
[ "RoundTrip", "implements", "the", "http", ".", "RoundTripper", "interface", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/transport.go#L30-L58
train
golang/gddo
log/log.go
FromContext
func FromContext(ctx context.Context) log15.Logger { if logger, ok := ctx.Value(loggerKey).(log15.Logger); ok { return logger } return log15.Root() }
go
func FromContext(ctx context.Context) log15.Logger { if logger, ok := ctx.Value(loggerKey).(log15.Logger); ok { return logger } return log15.Root() }
[ "func", "FromContext", "(", "ctx", "context", ".", "Context", ")", "log15", ".", "Logger", "{", "if", "logger", ",", "ok", ":=", "ctx", ".", "Value", "(", "loggerKey", ")", ".", "(", "log15", ".", "Logger", ")", ";", "ok", "{", "return", "logger", ...
// FromContext always returns a logger. If there is no logger in the context, it // returns the root logger. It is not recommended for use and may be removed in // the future.
[ "FromContext", "always", "returns", "a", "logger", ".", "If", "there", "is", "no", "logger", "in", "the", "context", "it", "returns", "the", "root", "logger", ".", "It", "is", "not", "recommended", "for", "use", "and", "may", "be", "removed", "in", "the"...
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/log/log.go#L21-L27
train
golang/gddo
log/log.go
NewContext
func NewContext(ctx context.Context, l log15.Logger) context.Context { return context.WithValue(ctx, loggerKey, l) }
go
func NewContext(ctx context.Context, l log15.Logger) context.Context { return context.WithValue(ctx, loggerKey, l) }
[ "func", "NewContext", "(", "ctx", "context", ".", "Context", ",", "l", "log15", ".", "Logger", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "loggerKey", ",", "l", ")", "\n", "}" ]
// NewContext creates a new context containing the given logger. It is not // recommended for use and may be removed in the future.
[ "NewContext", "creates", "a", "new", "context", "containing", "the", "given", "logger", ".", "It", "is", "not", "recommended", "for", "use", "and", "may", "be", "removed", "in", "the", "future", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/log/log.go#L31-L33
train
golang/gddo
gosrc/client.go
get
func (c *httpClient) get(ctx context.Context, url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } // Take the trace ID to group all outbound requests together. req = req.WithContext(ctx) for k, vs := range c.header { req.Header[k] = vs } resp, err := c.client.Do(req) if err != nil { return nil, &RemoteError{req.URL.Host, err} } return resp, err }
go
func (c *httpClient) get(ctx context.Context, url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } // Take the trace ID to group all outbound requests together. req = req.WithContext(ctx) for k, vs := range c.header { req.Header[k] = vs } resp, err := c.client.Do(req) if err != nil { return nil, &RemoteError{req.URL.Host, err} } return resp, err }
[ "func", "(", "c", "*", "httpClient", ")", "get", "(", "ctx", "context", ".", "Context", ",", "url", "string", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ","...
// get issues a GET to the specified URL.
[ "get", "issues", "a", "GET", "to", "the", "specified", "URL", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/client.go#L35-L51
train
golang/gddo
gosrc/client.go
getNoFollow
func (c *httpClient) getNoFollow(url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } for k, vs := range c.header { req.Header[k] = vs } t := c.client.Transport if t == nil { t = http.DefaultTransport } resp, err := t.RoundTrip(req) if err != nil { return nil, &RemoteError{req.URL.Host, err} } return resp, err }
go
func (c *httpClient) getNoFollow(url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } for k, vs := range c.header { req.Header[k] = vs } t := c.client.Transport if t == nil { t = http.DefaultTransport } resp, err := t.RoundTrip(req) if err != nil { return nil, &RemoteError{req.URL.Host, err} } return resp, err }
[ "func", "(", "c", "*", "httpClient", ")", "getNoFollow", "(", "url", "string", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "url", ",", "nil", ")", "\n",...
// getNoFollow issues a GET to the specified URL without following redirects.
[ "getNoFollow", "issues", "a", "GET", "to", "the", "specified", "URL", "without", "following", "redirects", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/client.go#L54-L71
train
golang/gddo
database/indexae.go
putIndex
func putIndex(c context.Context, pdoc *doc.Package, id string, score float64, importCount int) error { if id == "" { return errors.New("indexae: no id assigned") } idx, err := search.Open("packages") if err != nil { return err } var pkg Package if err := idx.Get(c, id, &pkg); err != nil { if err != search.ErrNoSuchDocument { return err } else if pdoc == nil { // Cannot update a non-existing document. return errors.New("indexae: cannot create new document with nil pdoc") } // No such document in the index, fall through. } // Update document information accordingly. if pdoc != nil { pkg.Name = pdoc.Name pkg.Path = pdoc.ImportPath pkg.Synopsis = pdoc.Synopsis pkg.Stars = pdoc.Stars pkg.Fork = pdoc.Fork } if score >= 0 { pkg.Score = score } pkg.ImportCount = importCount if _, err := idx.Put(c, id, &pkg); err != nil { return err } return nil }
go
func putIndex(c context.Context, pdoc *doc.Package, id string, score float64, importCount int) error { if id == "" { return errors.New("indexae: no id assigned") } idx, err := search.Open("packages") if err != nil { return err } var pkg Package if err := idx.Get(c, id, &pkg); err != nil { if err != search.ErrNoSuchDocument { return err } else if pdoc == nil { // Cannot update a non-existing document. return errors.New("indexae: cannot create new document with nil pdoc") } // No such document in the index, fall through. } // Update document information accordingly. if pdoc != nil { pkg.Name = pdoc.Name pkg.Path = pdoc.ImportPath pkg.Synopsis = pdoc.Synopsis pkg.Stars = pdoc.Stars pkg.Fork = pdoc.Fork } if score >= 0 { pkg.Score = score } pkg.ImportCount = importCount if _, err := idx.Put(c, id, &pkg); err != nil { return err } return nil }
[ "func", "putIndex", "(", "c", "context", ".", "Context", ",", "pdoc", "*", "doc", ".", "Package", ",", "id", "string", ",", "score", "float64", ",", "importCount", "int", ")", "error", "{", "if", "id", "==", "\"", "\"", "{", "return", "errors", ".", ...
// putIndex creates or updates a package entry in the search index. id identifies the document in the index. // If pdoc is non-nil, putIndex will update the package's name, path and synopsis supplied by pdoc. // pdoc must be non-nil for a package's first call to putIndex. // putIndex updates the Score to score, if non-negative.
[ "putIndex", "creates", "or", "updates", "a", "package", "entry", "in", "the", "search", "index", ".", "id", "identifies", "the", "document", "in", "the", "index", ".", "If", "pdoc", "is", "non", "-", "nil", "putIndex", "will", "update", "the", "package", ...
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/indexae.go#L91-L128
train
golang/gddo
database/indexae.go
searchAE
func searchAE(c context.Context, q string) ([]Package, error) { index, err := search.Open("packages") if err != nil { return nil, err } var pkgs []Package opt := &search.SearchOptions{ Limit: 100, } for it := index.Search(c, parseQuery2(q), opt); ; { var p Package _, err := it.Next(&p) if err == search.Done { break } if err != nil { return nil, err } pkgs = append(pkgs, p) } return pkgs, nil }
go
func searchAE(c context.Context, q string) ([]Package, error) { index, err := search.Open("packages") if err != nil { return nil, err } var pkgs []Package opt := &search.SearchOptions{ Limit: 100, } for it := index.Search(c, parseQuery2(q), opt); ; { var p Package _, err := it.Next(&p) if err == search.Done { break } if err != nil { return nil, err } pkgs = append(pkgs, p) } return pkgs, nil }
[ "func", "searchAE", "(", "c", "context", ".", "Context", ",", "q", "string", ")", "(", "[", "]", "Package", ",", "error", ")", "{", "index", ",", "err", ":=", "search", ".", "Open", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "re...
// searchAE searches the packages index for a given query. A path-like query string // will be passed in unchanged, whereas single words will be stemmed.
[ "searchAE", "searches", "the", "packages", "index", "for", "a", "given", "query", ".", "A", "path", "-", "like", "query", "string", "will", "be", "passed", "in", "unchanged", "whereas", "single", "words", "will", "be", "stemmed", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/database/indexae.go#L132-L153
train
golang/gddo
gddo-server/crawl.go
isActivePkg
func (s *server) isActivePkg(pkg string, status gosrc.DirectoryStatus) bool { switch status { case gosrc.Active: return true case gosrc.NoRecentCommits: // It should be inactive only if it has no imports as well. n, err := s.db.ImporterCount(pkg) if err != nil { log.Printf("ERROR db.ImporterCount(%q): %v", pkg, err) } return n > 0 } return false }
go
func (s *server) isActivePkg(pkg string, status gosrc.DirectoryStatus) bool { switch status { case gosrc.Active: return true case gosrc.NoRecentCommits: // It should be inactive only if it has no imports as well. n, err := s.db.ImporterCount(pkg) if err != nil { log.Printf("ERROR db.ImporterCount(%q): %v", pkg, err) } return n > 0 } return false }
[ "func", "(", "s", "*", "server", ")", "isActivePkg", "(", "pkg", "string", ",", "status", "gosrc", ".", "DirectoryStatus", ")", "bool", "{", "switch", "status", "{", "case", "gosrc", ".", "Active", ":", "return", "true", "\n", "case", "gosrc", ".", "No...
// isActivePkg reports whether a package is considered active, // either because its directory is active or because it is imported by another package.
[ "isActivePkg", "reports", "whether", "a", "package", "is", "considered", "active", "either", "because", "its", "directory", "is", "active", "or", "because", "it", "is", "imported", "by", "another", "package", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/crawl.go#L158-L171
train
golang/gddo
internal/health/health.go
Add
func (h *Handler) Add(c Checker) { h.checkers = append(h.checkers, c) }
go
func (h *Handler) Add(c Checker) { h.checkers = append(h.checkers, c) }
[ "func", "(", "h", "*", "Handler", ")", "Add", "(", "c", "Checker", ")", "{", "h", ".", "checkers", "=", "append", "(", "h", ".", "checkers", ",", "c", ")", "\n", "}" ]
// Add adds a new check to the handler.
[ "Add", "adds", "a", "new", "check", "to", "the", "handler", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/internal/health/health.go#L22-L24
train
golang/gddo
internal/health/health.go
ServeHTTP
func (h *Handler) ServeHTTP(w http.ResponseWriter, _ *http.Request) { for _, c := range h.checkers { if err := c.CheckHealth(); err != nil { writeUnhealthy(w) return } } writeHealthy(w) }
go
func (h *Handler) ServeHTTP(w http.ResponseWriter, _ *http.Request) { for _, c := range h.checkers { if err := c.CheckHealth(); err != nil { writeUnhealthy(w) return } } writeHealthy(w) }
[ "func", "(", "h", "*", "Handler", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "_", "*", "http", ".", "Request", ")", "{", "for", "_", ",", "c", ":=", "range", "h", ".", "checkers", "{", "if", "err", ":=", "c", ".", "CheckHealt...
// ServeHTTP returns 200 if it is healthy, 500 otherwise.
[ "ServeHTTP", "returns", "200", "if", "it", "is", "healthy", "500", "otherwise", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/internal/health/health.go#L27-L35
train
golang/gddo
gddo-server/logging.go
LogEvent
func (g *GCELogger) LogEvent(w http.ResponseWriter, r *http.Request, content interface{}) { const sessionCookieName = "GODOC_ORG_SESSION_ID" cookie, err := r.Cookie(sessionCookieName) if err != nil { // Generates a random session id and sends it in response. rs, err := randomString() if err != nil { log.Println("error generating a random session id: ", err) return } // This cookie is intentionally short-lived and contains no information // that might identify the user. Its sole purpose is to tie query // terms and destination pages together to measure search quality. cookie = &http.Cookie{ Name: sessionCookieName, Value: rs, Expires: time.Now().Add(time.Hour), } http.SetCookie(w, cookie) } // We must not record the client's IP address, or any other information // that might compromise the user's privacy. payload := map[string]interface{}{ sessionCookieName: cookie.Value, "path": r.URL.RequestURI(), "method": r.Method, "referer": r.Referer(), } if pkgs, ok := content.([]database.Package); ok { payload["packages"] = pkgs } // Log queues the entry to its internal buffer, or discarding the entry // if the buffer was full. g.cli.Log(logging.Entry{ Payload: payload, }) }
go
func (g *GCELogger) LogEvent(w http.ResponseWriter, r *http.Request, content interface{}) { const sessionCookieName = "GODOC_ORG_SESSION_ID" cookie, err := r.Cookie(sessionCookieName) if err != nil { // Generates a random session id and sends it in response. rs, err := randomString() if err != nil { log.Println("error generating a random session id: ", err) return } // This cookie is intentionally short-lived and contains no information // that might identify the user. Its sole purpose is to tie query // terms and destination pages together to measure search quality. cookie = &http.Cookie{ Name: sessionCookieName, Value: rs, Expires: time.Now().Add(time.Hour), } http.SetCookie(w, cookie) } // We must not record the client's IP address, or any other information // that might compromise the user's privacy. payload := map[string]interface{}{ sessionCookieName: cookie.Value, "path": r.URL.RequestURI(), "method": r.Method, "referer": r.Referer(), } if pkgs, ok := content.([]database.Package); ok { payload["packages"] = pkgs } // Log queues the entry to its internal buffer, or discarding the entry // if the buffer was full. g.cli.Log(logging.Entry{ Payload: payload, }) }
[ "func", "(", "g", "*", "GCELogger", ")", "LogEvent", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "content", "interface", "{", "}", ")", "{", "const", "sessionCookieName", "=", "\"", "\"", "\n", "cookie", ",", ...
// LogEvent creates an entry in Cloud Logging to record user's behavior. We should only // use this to log events we are interested in. General request logs are handled by GAE // automatically in request_log and stderr.
[ "LogEvent", "creates", "an", "entry", "in", "Cloud", "Logging", "to", "record", "user", "s", "behavior", ".", "We", "should", "only", "use", "this", "to", "log", "events", "we", "are", "interested", "in", ".", "General", "request", "logs", "are", "handled"...
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/logging.go#L33-L71
train
golang/gddo
gosrc/util.go
isDocFile
func isDocFile(n string) bool { if strings.HasSuffix(n, ".go") && n[0] != '_' && n[0] != '.' { return true } return readmePat.MatchString(n) }
go
func isDocFile(n string) bool { if strings.HasSuffix(n, ".go") && n[0] != '_' && n[0] != '.' { return true } return readmePat.MatchString(n) }
[ "func", "isDocFile", "(", "n", "string", ")", "bool", "{", "if", "strings", ".", "HasSuffix", "(", "n", ",", "\"", "\"", ")", "&&", "n", "[", "0", "]", "!=", "'_'", "&&", "n", "[", "0", "]", "!=", "'.'", "{", "return", "true", "\n", "}", "\n"...
// isDocFile returns true if a file with name n should be included in the // documentation.
[ "isDocFile", "returns", "true", "if", "a", "file", "with", "name", "n", "should", "be", "included", "in", "the", "documentation", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/util.go#L55-L60
train
golang/gddo
gddo-server/main.go
getDoc
func (s *server) getDoc(ctx context.Context, path string, requestType int) (*doc.Package, []database.Package, error) { if path == "-" { // A hack in the database package uses the path "-" to represent the // next document to crawl. Block "-" here so that requests to /- always // return not found. return nil, nil, &httpError{status: http.StatusNotFound} } pdoc, pkgs, nextCrawl, err := s.db.Get(ctx, path) if err != nil { return nil, nil, err } needsCrawl := false switch requestType { case queryRequest, apiRequest: needsCrawl = nextCrawl.IsZero() && len(pkgs) == 0 case humanRequest: needsCrawl = nextCrawl.Before(time.Now()) case robotRequest: needsCrawl = nextCrawl.IsZero() && len(pkgs) > 0 } if !needsCrawl { return pdoc, pkgs, nil } c := make(chan crawlResult, 1) go func() { pdoc, err := s.crawlDoc(ctx, "web ", path, pdoc, len(pkgs) > 0, nextCrawl) c <- crawlResult{pdoc, err} }() timeout := s.v.GetDuration(ConfigGetTimeout) if pdoc == nil { timeout = s.v.GetDuration(ConfigFirstGetTimeout) } select { case cr := <-c: err = cr.err if err == nil { pdoc = cr.pdoc } case <-time.After(timeout): err = errUpdateTimeout } switch { case err == nil: return pdoc, pkgs, nil case gosrc.IsNotFound(err): return nil, nil, err case pdoc != nil: log.Printf("Serving %q from database after error getting doc: %v", path, err) return pdoc, pkgs, nil case err == errUpdateTimeout: log.Printf("Serving %q as not found after timeout getting doc", path) return nil, nil, &httpError{status: http.StatusNotFound} default: return nil, nil, err } }
go
func (s *server) getDoc(ctx context.Context, path string, requestType int) (*doc.Package, []database.Package, error) { if path == "-" { // A hack in the database package uses the path "-" to represent the // next document to crawl. Block "-" here so that requests to /- always // return not found. return nil, nil, &httpError{status: http.StatusNotFound} } pdoc, pkgs, nextCrawl, err := s.db.Get(ctx, path) if err != nil { return nil, nil, err } needsCrawl := false switch requestType { case queryRequest, apiRequest: needsCrawl = nextCrawl.IsZero() && len(pkgs) == 0 case humanRequest: needsCrawl = nextCrawl.Before(time.Now()) case robotRequest: needsCrawl = nextCrawl.IsZero() && len(pkgs) > 0 } if !needsCrawl { return pdoc, pkgs, nil } c := make(chan crawlResult, 1) go func() { pdoc, err := s.crawlDoc(ctx, "web ", path, pdoc, len(pkgs) > 0, nextCrawl) c <- crawlResult{pdoc, err} }() timeout := s.v.GetDuration(ConfigGetTimeout) if pdoc == nil { timeout = s.v.GetDuration(ConfigFirstGetTimeout) } select { case cr := <-c: err = cr.err if err == nil { pdoc = cr.pdoc } case <-time.After(timeout): err = errUpdateTimeout } switch { case err == nil: return pdoc, pkgs, nil case gosrc.IsNotFound(err): return nil, nil, err case pdoc != nil: log.Printf("Serving %q from database after error getting doc: %v", path, err) return pdoc, pkgs, nil case err == errUpdateTimeout: log.Printf("Serving %q as not found after timeout getting doc", path) return nil, nil, &httpError{status: http.StatusNotFound} default: return nil, nil, err } }
[ "func", "(", "s", "*", "server", ")", "getDoc", "(", "ctx", "context", ".", "Context", ",", "path", "string", ",", "requestType", "int", ")", "(", "*", "doc", ".", "Package", ",", "[", "]", "database", ".", "Package", ",", "error", ")", "{", "if", ...
// getDoc gets the package documentation from the database or from the version // control system as needed.
[ "getDoc", "gets", "the", "package", "documentation", "from", "the", "database", "or", "from", "the", "version", "control", "system", "as", "needed", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/main.go#L78-L140
train
golang/gddo
gddo-server/main.go
httpEtag
func (s *server) httpEtag(pdoc *doc.Package, pkgs []database.Package, importerCount int, flashMessages []flashMessage) string { b := make([]byte, 0, 128) b = strconv.AppendInt(b, pdoc.Updated.Unix(), 16) b = append(b, 0) b = append(b, pdoc.Etag...) if importerCount >= 8 { importerCount = 8 } b = append(b, 0) b = strconv.AppendInt(b, int64(importerCount), 16) for _, pkg := range pkgs { b = append(b, 0) b = append(b, pkg.Path...) b = append(b, 0) b = append(b, pkg.Synopsis...) } if s.v.GetBool(ConfigSidebar) { b = append(b, "\000xsb"...) } for _, m := range flashMessages { b = append(b, 0) b = append(b, m.ID...) for _, a := range m.Args { b = append(b, 1) b = append(b, a...) } } h := md5.New() h.Write(b) b = h.Sum(b[:0]) return fmt.Sprintf("\"%x\"", b) }
go
func (s *server) httpEtag(pdoc *doc.Package, pkgs []database.Package, importerCount int, flashMessages []flashMessage) string { b := make([]byte, 0, 128) b = strconv.AppendInt(b, pdoc.Updated.Unix(), 16) b = append(b, 0) b = append(b, pdoc.Etag...) if importerCount >= 8 { importerCount = 8 } b = append(b, 0) b = strconv.AppendInt(b, int64(importerCount), 16) for _, pkg := range pkgs { b = append(b, 0) b = append(b, pkg.Path...) b = append(b, 0) b = append(b, pkg.Synopsis...) } if s.v.GetBool(ConfigSidebar) { b = append(b, "\000xsb"...) } for _, m := range flashMessages { b = append(b, 0) b = append(b, m.ID...) for _, a := range m.Args { b = append(b, 1) b = append(b, a...) } } h := md5.New() h.Write(b) b = h.Sum(b[:0]) return fmt.Sprintf("\"%x\"", b) }
[ "func", "(", "s", "*", "server", ")", "httpEtag", "(", "pdoc", "*", "doc", ".", "Package", ",", "pkgs", "[", "]", "database", ".", "Package", ",", "importerCount", "int", ",", "flashMessages", "[", "]", "flashMessage", ")", "string", "{", "b", ":=", ...
// httpEtag returns the package entity tag used in HTTP transactions.
[ "httpEtag", "returns", "the", "package", "entity", "tag", "used", "in", "HTTP", "transactions", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/main.go#L179-L210
train
golang/gddo
gddo-server/config.go
setDefaults
func setDefaults(v *viper.Viper) { // ConfigGAERemoteAPI is based on project. project := v.GetString(ConfigProject) if project != "" { defaultEndpoint := fmt.Sprintf("serviceproxy-dot-%s.appspot.com", project) v.SetDefault(ConfigGAERemoteAPI, defaultEndpoint) } }
go
func setDefaults(v *viper.Viper) { // ConfigGAERemoteAPI is based on project. project := v.GetString(ConfigProject) if project != "" { defaultEndpoint := fmt.Sprintf("serviceproxy-dot-%s.appspot.com", project) v.SetDefault(ConfigGAERemoteAPI, defaultEndpoint) } }
[ "func", "setDefaults", "(", "v", "*", "viper", ".", "Viper", ")", "{", "// ConfigGAERemoteAPI is based on project.", "project", ":=", "v", ".", "GetString", "(", "ConfigProject", ")", "\n", "if", "project", "!=", "\"", "\"", "{", "defaultEndpoint", ":=", "fmt"...
// setDefaults sets defaults for configuration options that depend on other // configuration options. This allows for smart defaults but allows for // overrides.
[ "setDefaults", "sets", "defaults", "for", "configuration", "options", "that", "depend", "on", "other", "configuration", "options", ".", "This", "allows", "for", "smart", "defaults", "but", "allows", "for", "overrides", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/config.go#L141-L148
train
golang/gddo
gddo-server/config.go
readViperConfig
func readViperConfig(ctx context.Context, v *viper.Viper) error { v.AddConfigPath(".") v.AddConfigPath("/etc") v.SetConfigName("gddo") if v.GetString("config") != "" { v.SetConfigFile(v.GetString("config")) } if err := v.ReadInConfig(); err != nil { // If a config exists but could not be parsed, we should bail. if _, ok := err.(viper.ConfigParseError); ok { return fmt.Errorf("parse config: %v", err) } // If the user specified a config file location in flags or env and // we failed to load it, we should bail. If not, it is just a warning. if v.GetString("config") != "" { return fmt.Errorf("load config: %v", err) } log.Warn(ctx, "failed to load configuration file", "error", err) return nil } log.Info(ctx, "loaded configuration file successfully", "path", v.ConfigFileUsed()) return nil }
go
func readViperConfig(ctx context.Context, v *viper.Viper) error { v.AddConfigPath(".") v.AddConfigPath("/etc") v.SetConfigName("gddo") if v.GetString("config") != "" { v.SetConfigFile(v.GetString("config")) } if err := v.ReadInConfig(); err != nil { // If a config exists but could not be parsed, we should bail. if _, ok := err.(viper.ConfigParseError); ok { return fmt.Errorf("parse config: %v", err) } // If the user specified a config file location in flags or env and // we failed to load it, we should bail. If not, it is just a warning. if v.GetString("config") != "" { return fmt.Errorf("load config: %v", err) } log.Warn(ctx, "failed to load configuration file", "error", err) return nil } log.Info(ctx, "loaded configuration file successfully", "path", v.ConfigFileUsed()) return nil }
[ "func", "readViperConfig", "(", "ctx", "context", ".", "Context", ",", "v", "*", "viper", ".", "Viper", ")", "error", "{", "v", ".", "AddConfigPath", "(", "\"", "\"", ")", "\n", "v", ".", "AddConfigPath", "(", "\"", "\"", ")", "\n", "v", ".", "SetC...
// readViperConfig finds and then parses a config file. It will return // an error if the config file was specified or could not parse. // Otherwise it will only warn that it failed to load the config.
[ "readViperConfig", "finds", "and", "then", "parses", "a", "config", "file", ".", "It", "will", "return", "an", "error", "if", "the", "config", "file", "was", "specified", "or", "could", "not", "parse", ".", "Otherwise", "it", "will", "only", "warn", "that"...
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/config.go#L183-L207
train
golang/gddo
httputil/buster.go
Get
func (cb *CacheBusters) Get(path string) string { cb.mu.Lock() if cb.tokens == nil { cb.tokens = make(map[string]string) } token, ok := cb.tokens[path] cb.mu.Unlock() if ok { return token } w := busterWriter{ Writer: ioutil.Discard, headerMap: make(http.Header), } r := &http.Request{URL: &url.URL{Path: path}, Method: "HEAD"} cb.Handler.ServeHTTP(&w, r) if w.status == 200 { token = w.headerMap.Get("Etag") if token == "" { token = w.headerMap.Get("Last-Modified") } token = strings.Trim(token, `" `) token = strings.Map(sanitizeTokenRune, token) } cb.mu.Lock() cb.tokens[path] = token cb.mu.Unlock() return token }
go
func (cb *CacheBusters) Get(path string) string { cb.mu.Lock() if cb.tokens == nil { cb.tokens = make(map[string]string) } token, ok := cb.tokens[path] cb.mu.Unlock() if ok { return token } w := busterWriter{ Writer: ioutil.Discard, headerMap: make(http.Header), } r := &http.Request{URL: &url.URL{Path: path}, Method: "HEAD"} cb.Handler.ServeHTTP(&w, r) if w.status == 200 { token = w.headerMap.Get("Etag") if token == "" { token = w.headerMap.Get("Last-Modified") } token = strings.Trim(token, `" `) token = strings.Map(sanitizeTokenRune, token) } cb.mu.Lock() cb.tokens[path] = token cb.mu.Unlock() return token }
[ "func", "(", "cb", "*", "CacheBusters", ")", "Get", "(", "path", "string", ")", "string", "{", "cb", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "cb", ".", "tokens", "==", "nil", "{", "cb", ".", "tokens", "=", "make", "(", "map", "[", "string...
// Get returns the cache busting token for path. If the token is not already // cached, Get issues a HEAD request on handler and uses the response ETag and // Last-Modified headers to compute a token.
[ "Get", "returns", "the", "cache", "busting", "token", "for", "path", ".", "If", "the", "token", "is", "not", "already", "cached", "Get", "issues", "a", "HEAD", "request", "on", "handler", "and", "uses", "the", "response", "ETag", "and", "Last", "-", "Mod...
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/buster.go#L54-L86
train
golang/gddo
httputil/buster.go
AppendQueryParam
func (cb *CacheBusters) AppendQueryParam(path string, name string) string { token := cb.Get(path) if token == "" { return path } return path + "?" + name + "=" + token }
go
func (cb *CacheBusters) AppendQueryParam(path string, name string) string { token := cb.Get(path) if token == "" { return path } return path + "?" + name + "=" + token }
[ "func", "(", "cb", "*", "CacheBusters", ")", "AppendQueryParam", "(", "path", "string", ",", "name", "string", ")", "string", "{", "token", ":=", "cb", ".", "Get", "(", "path", ")", "\n", "if", "token", "==", "\"", "\"", "{", "return", "path", "\n", ...
// AppendQueryParam appends the token as a query parameter to path.
[ "AppendQueryParam", "appends", "the", "token", "as", "a", "query", "parameter", "to", "path", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/httputil/buster.go#L89-L95
train
golang/gddo
gddo-server/browse.go
isBrowseURL
func isBrowseURL(s string) (importPath string, ok bool) { for _, c := range browsePatterns { if m := c.pat.FindStringSubmatch(s); m != nil { return c.fn(m), true } } return "", false }
go
func isBrowseURL(s string) (importPath string, ok bool) { for _, c := range browsePatterns { if m := c.pat.FindStringSubmatch(s); m != nil { return c.fn(m), true } } return "", false }
[ "func", "isBrowseURL", "(", "s", "string", ")", "(", "importPath", "string", ",", "ok", "bool", ")", "{", "for", "_", ",", "c", ":=", "range", "browsePatterns", "{", "if", "m", ":=", "c", ".", "pat", ".", "FindStringSubmatch", "(", "s", ")", ";", "...
// isBrowserURL returns importPath and true if URL looks like a URL for a VCS // source browser.
[ "isBrowserURL", "returns", "importPath", "and", "true", "if", "URL", "looks", "like", "a", "URL", "for", "a", "VCS", "source", "browser", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gddo-server/browse.go#L90-L97
train
golang/gddo
gosrc/path.go
IsValidRemotePath
func IsValidRemotePath(importPath string) bool { parts := strings.Split(importPath, "/") if !validTLDs[path.Ext(parts[0])] { return false } if !validHost.MatchString(parts[0]) { return false } for _, part := range parts[1:] { if !isValidPathElement(part) { return false } } return true }
go
func IsValidRemotePath(importPath string) bool { parts := strings.Split(importPath, "/") if !validTLDs[path.Ext(parts[0])] { return false } if !validHost.MatchString(parts[0]) { return false } for _, part := range parts[1:] { if !isValidPathElement(part) { return false } } return true }
[ "func", "IsValidRemotePath", "(", "importPath", "string", ")", "bool", "{", "parts", ":=", "strings", ".", "Split", "(", "importPath", ",", "\"", "\"", ")", "\n\n", "if", "!", "validTLDs", "[", "path", ".", "Ext", "(", "parts", "[", "0", "]", ")", "]...
// IsValidRemotePath returns true if importPath is structurally valid for "go get".
[ "IsValidRemotePath", "returns", "true", "if", "importPath", "is", "structurally", "valid", "for", "go", "get", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/path.go#L25-L44
train
golang/gddo
gosrc/path.go
IsValidPath
func IsValidPath(importPath string) bool { return pathFlags[importPath]&packagePath != 0 || pathFlags["vendor/"+importPath]&packagePath != 0 || IsValidRemotePath(importPath) }
go
func IsValidPath(importPath string) bool { return pathFlags[importPath]&packagePath != 0 || pathFlags["vendor/"+importPath]&packagePath != 0 || IsValidRemotePath(importPath) }
[ "func", "IsValidPath", "(", "importPath", "string", ")", "bool", "{", "return", "pathFlags", "[", "importPath", "]", "&", "packagePath", "!=", "0", "||", "pathFlags", "[", "\"", "\"", "+", "importPath", "]", "&", "packagePath", "!=", "0", "||", "IsValidRem...
// IsValidPath returns true if importPath is structurally valid.
[ "IsValidPath", "returns", "true", "if", "importPath", "is", "structurally", "valid", "." ]
af0f2af80721261f4d211b2c9563f7b46b2aab06
https://github.com/golang/gddo/blob/af0f2af80721261f4d211b2c9563f7b46b2aab06/gosrc/path.go#L52-L56
train
dchest/captcha
image.go
NewImage
func NewImage(id string, digits []byte, width, height int) *Image { m := new(Image) // Initialize PRNG. m.rng.Seed(deriveSeed(imageSeedPurpose, id, digits)) m.Paletted = image.NewPaletted(image.Rect(0, 0, width, height), m.getRandomPalette()) m.calculateSizes(width, height, len(digits)) // Randomly position captcha inside the image. maxx := width - (m.numWidth+m.dotSize)*len(digits) - m.dotSize maxy := height - m.numHeight - m.dotSize*2 var border int if width > height { border = height / 5 } else { border = width / 5 } x := m.rng.Int(border, maxx-border) y := m.rng.Int(border, maxy-border) // Draw digits. for _, n := range digits { m.drawDigit(font[n], x, y) x += m.numWidth + m.dotSize } // Draw strike-through line. m.strikeThrough() // Apply wave distortion. m.distort(m.rng.Float(5, 10), m.rng.Float(100, 200)) // Fill image with random circles. m.fillWithCircles(circleCount, m.dotSize) return m }
go
func NewImage(id string, digits []byte, width, height int) *Image { m := new(Image) // Initialize PRNG. m.rng.Seed(deriveSeed(imageSeedPurpose, id, digits)) m.Paletted = image.NewPaletted(image.Rect(0, 0, width, height), m.getRandomPalette()) m.calculateSizes(width, height, len(digits)) // Randomly position captcha inside the image. maxx := width - (m.numWidth+m.dotSize)*len(digits) - m.dotSize maxy := height - m.numHeight - m.dotSize*2 var border int if width > height { border = height / 5 } else { border = width / 5 } x := m.rng.Int(border, maxx-border) y := m.rng.Int(border, maxy-border) // Draw digits. for _, n := range digits { m.drawDigit(font[n], x, y) x += m.numWidth + m.dotSize } // Draw strike-through line. m.strikeThrough() // Apply wave distortion. m.distort(m.rng.Float(5, 10), m.rng.Float(100, 200)) // Fill image with random circles. m.fillWithCircles(circleCount, m.dotSize) return m }
[ "func", "NewImage", "(", "id", "string", ",", "digits", "[", "]", "byte", ",", "width", ",", "height", "int", ")", "*", "Image", "{", "m", ":=", "new", "(", "Image", ")", "\n\n", "// Initialize PRNG.", "m", ".", "rng", ".", "Seed", "(", "deriveSeed",...
// NewImage returns a new captcha image of the given width and height with the // given digits, where each digit must be in range 0-9.
[ "NewImage", "returns", "a", "new", "captcha", "image", "of", "the", "given", "width", "and", "height", "with", "the", "given", "digits", "where", "each", "digit", "must", "be", "in", "range", "0", "-", "9", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/image.go#L36-L67
train
dchest/captcha
image.go
encodedPNG
func (m *Image) encodedPNG() []byte { var buf bytes.Buffer if err := png.Encode(&buf, m.Paletted); err != nil { panic(err.Error()) } return buf.Bytes() }
go
func (m *Image) encodedPNG() []byte { var buf bytes.Buffer if err := png.Encode(&buf, m.Paletted); err != nil { panic(err.Error()) } return buf.Bytes() }
[ "func", "(", "m", "*", "Image", ")", "encodedPNG", "(", ")", "[", "]", "byte", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "png", ".", "Encode", "(", "&", "buf", ",", "m", ".", "Paletted", ")", ";", "err", "!=", "nil", ...
// encodedPNG encodes an image to PNG and returns // the result as a byte slice.
[ "encodedPNG", "encodes", "an", "image", "to", "PNG", "and", "returns", "the", "result", "as", "a", "byte", "slice", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/image.go#L90-L96
train
dchest/captcha
image.go
WriteTo
func (m *Image) WriteTo(w io.Writer) (int64, error) { n, err := w.Write(m.encodedPNG()) return int64(n), err }
go
func (m *Image) WriteTo(w io.Writer) (int64, error) { n, err := w.Write(m.encodedPNG()) return int64(n), err }
[ "func", "(", "m", "*", "Image", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "int64", ",", "error", ")", "{", "n", ",", "err", ":=", "w", ".", "Write", "(", "m", ".", "encodedPNG", "(", ")", ")", "\n", "return", "int64", "(", "n",...
// WriteTo writes captcha image in PNG format into the given writer.
[ "WriteTo", "writes", "captcha", "image", "in", "PNG", "format", "into", "the", "given", "writer", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/image.go#L99-L102
train
dchest/captcha
random.go
randomBytesMod
func randomBytesMod(length int, mod byte) (b []byte) { if length == 0 { return nil } if mod == 0 { panic("captcha: bad mod argument for randomBytesMod") } maxrb := 255 - byte(256%int(mod)) b = make([]byte, length) i := 0 for { r := randomBytes(length + (length / 4)) for _, c := range r { if c > maxrb { // Skip this number to avoid modulo bias. continue } b[i] = c % mod i++ if i == length { return } } } }
go
func randomBytesMod(length int, mod byte) (b []byte) { if length == 0 { return nil } if mod == 0 { panic("captcha: bad mod argument for randomBytesMod") } maxrb := 255 - byte(256%int(mod)) b = make([]byte, length) i := 0 for { r := randomBytes(length + (length / 4)) for _, c := range r { if c > maxrb { // Skip this number to avoid modulo bias. continue } b[i] = c % mod i++ if i == length { return } } } }
[ "func", "randomBytesMod", "(", "length", "int", ",", "mod", "byte", ")", "(", "b", "[", "]", "byte", ")", "{", "if", "length", "==", "0", "{", "return", "nil", "\n", "}", "\n", "if", "mod", "==", "0", "{", "panic", "(", "\"", "\"", ")", "\n", ...
// randomBytesMod returns a byte slice of the given length, where each byte is // a random number modulo mod.
[ "randomBytesMod", "returns", "a", "byte", "slice", "of", "the", "given", "length", "where", "each", "byte", "is", "a", "random", "number", "modulo", "mod", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/random.go#L74-L99
train
dchest/captcha
random.go
randomId
func randomId() string { b := randomBytesMod(idLen, byte(len(idChars))) for i, c := range b { b[i] = idChars[c] } return string(b) }
go
func randomId() string { b := randomBytesMod(idLen, byte(len(idChars))) for i, c := range b { b[i] = idChars[c] } return string(b) }
[ "func", "randomId", "(", ")", "string", "{", "b", ":=", "randomBytesMod", "(", "idLen", ",", "byte", "(", "len", "(", "idChars", ")", ")", ")", "\n", "for", "i", ",", "c", ":=", "range", "b", "{", "b", "[", "i", "]", "=", "idChars", "[", "c", ...
// randomId returns a new random id string.
[ "randomId", "returns", "a", "new", "random", "id", "string", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/random.go#L102-L108
train
dchest/captcha
siprng.go
Seed
func (p *siprng) Seed(k [16]byte) { p.k0 = binary.LittleEndian.Uint64(k[0:8]) p.k1 = binary.LittleEndian.Uint64(k[8:16]) p.ctr = 1 }
go
func (p *siprng) Seed(k [16]byte) { p.k0 = binary.LittleEndian.Uint64(k[0:8]) p.k1 = binary.LittleEndian.Uint64(k[8:16]) p.ctr = 1 }
[ "func", "(", "p", "*", "siprng", ")", "Seed", "(", "k", "[", "16", "]", "byte", ")", "{", "p", ".", "k0", "=", "binary", ".", "LittleEndian", ".", "Uint64", "(", "k", "[", "0", ":", "8", "]", ")", "\n", "p", ".", "k1", "=", "binary", ".", ...
// Seed sets a new secret seed for PRNG.
[ "Seed", "sets", "a", "new", "secret", "seed", "for", "PRNG", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/siprng.go#L193-L197
train
dchest/captcha
siprng.go
Uint64
func (p *siprng) Uint64() uint64 { v := siphash(p.k0, p.k1, p.ctr) p.ctr++ return v }
go
func (p *siprng) Uint64() uint64 { v := siphash(p.k0, p.k1, p.ctr) p.ctr++ return v }
[ "func", "(", "p", "*", "siprng", ")", "Uint64", "(", ")", "uint64", "{", "v", ":=", "siphash", "(", "p", ".", "k0", ",", "p", ".", "k1", ",", "p", ".", "ctr", ")", "\n", "p", ".", "ctr", "++", "\n", "return", "v", "\n", "}" ]
// Uint64 returns a new pseudorandom uint64.
[ "Uint64", "returns", "a", "new", "pseudorandom", "uint64", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/siprng.go#L200-L204
train
dchest/captcha
captcha.go
NewLen
func NewLen(length int) (id string) { id = randomId() globalStore.Set(id, RandomDigits(length)) return }
go
func NewLen(length int) (id string) { id = randomId() globalStore.Set(id, RandomDigits(length)) return }
[ "func", "NewLen", "(", "length", "int", ")", "(", "id", "string", ")", "{", "id", "=", "randomId", "(", ")", "\n", "globalStore", ".", "Set", "(", "id", ",", "RandomDigits", "(", "length", ")", ")", "\n", "return", "\n", "}" ]
// NewLen is just like New, but accepts length of a captcha solution as the // argument.
[ "NewLen", "is", "just", "like", "New", "but", "accepts", "length", "of", "a", "captcha", "solution", "as", "the", "argument", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/captcha.go#L85-L89
train
dchest/captcha
captcha.go
WriteImage
func WriteImage(w io.Writer, id string, width, height int) error { d := globalStore.Get(id, false) if d == nil { return ErrNotFound } _, err := NewImage(id, d, width, height).WriteTo(w) return err }
go
func WriteImage(w io.Writer, id string, width, height int) error { d := globalStore.Get(id, false) if d == nil { return ErrNotFound } _, err := NewImage(id, d, width, height).WriteTo(w) return err }
[ "func", "WriteImage", "(", "w", "io", ".", "Writer", ",", "id", "string", ",", "width", ",", "height", "int", ")", "error", "{", "d", ":=", "globalStore", ".", "Get", "(", "id", ",", "false", ")", "\n", "if", "d", "==", "nil", "{", "return", "Err...
// WriteImage writes PNG-encoded image representation of the captcha with the // given id. The image will have the given width and height.
[ "WriteImage", "writes", "PNG", "-", "encoded", "image", "representation", "of", "the", "captcha", "with", "the", "given", "id", ".", "The", "image", "will", "have", "the", "given", "width", "and", "height", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/captcha.go#L108-L115
train
dchest/captcha
captcha.go
Verify
func Verify(id string, digits []byte) bool { if digits == nil || len(digits) == 0 { return false } reald := globalStore.Get(id, true) if reald == nil { return false } return bytes.Equal(digits, reald) }
go
func Verify(id string, digits []byte) bool { if digits == nil || len(digits) == 0 { return false } reald := globalStore.Get(id, true) if reald == nil { return false } return bytes.Equal(digits, reald) }
[ "func", "Verify", "(", "id", "string", ",", "digits", "[", "]", "byte", ")", "bool", "{", "if", "digits", "==", "nil", "||", "len", "(", "digits", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "reald", ":=", "globalStore", ".", "Get", ...
// Verify returns true if the given digits are the ones that were used to // create the given captcha id. // // The function deletes the captcha with the given id from the internal // storage, so that the same captcha can't be verified anymore.
[ "Verify", "returns", "true", "if", "the", "given", "digits", "are", "the", "ones", "that", "were", "used", "to", "create", "the", "given", "captcha", "id", ".", "The", "function", "deletes", "the", "captcha", "with", "the", "given", "id", "from", "the", ...
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/captcha.go#L134-L143
train
dchest/captcha
captcha.go
VerifyString
func VerifyString(id string, digits string) bool { if digits == "" { return false } ns := make([]byte, len(digits)) for i := range ns { d := digits[i] switch { case '0' <= d && d <= '9': ns[i] = d - '0' case d == ' ' || d == ',': // ignore default: return false } } return Verify(id, ns) }
go
func VerifyString(id string, digits string) bool { if digits == "" { return false } ns := make([]byte, len(digits)) for i := range ns { d := digits[i] switch { case '0' <= d && d <= '9': ns[i] = d - '0' case d == ' ' || d == ',': // ignore default: return false } } return Verify(id, ns) }
[ "func", "VerifyString", "(", "id", "string", ",", "digits", "string", ")", "bool", "{", "if", "digits", "==", "\"", "\"", "{", "return", "false", "\n", "}", "\n", "ns", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "digits", ")", ")", "\n...
// VerifyString is like Verify, but accepts a string of digits. It removes // spaces and commas from the string, but any other characters, apart from // digits and listed above, will cause the function to return false.
[ "VerifyString", "is", "like", "Verify", "but", "accepts", "a", "string", "of", "digits", ".", "It", "removes", "spaces", "and", "commas", "from", "the", "string", "but", "any", "other", "characters", "apart", "from", "digits", "and", "listed", "above", "will...
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/captcha.go#L148-L165
train
dchest/captcha
audio.go
WriteTo
func (a *Audio) WriteTo(w io.Writer) (n int64, err error) { // Calculate padded length of PCM chunk data. bodyLen := uint32(a.body.Len()) paddedBodyLen := bodyLen if bodyLen%2 != 0 { paddedBodyLen++ } totalLen := uint32(len(waveHeader)) - 4 + paddedBodyLen // Header. header := make([]byte, len(waveHeader)+4) // includes 4 bytes for chunk size copy(header, waveHeader) // Put the length of whole RIFF chunk. binary.LittleEndian.PutUint32(header[4:], totalLen) // Put the length of WAVE chunk. binary.LittleEndian.PutUint32(header[len(waveHeader):], bodyLen) // Write header. nn, err := w.Write(header) n = int64(nn) if err != nil { return } // Write data. n, err = a.body.WriteTo(w) n += int64(nn) if err != nil { return } // Pad byte if chunk length is odd. // (As header has even length, we can check if n is odd, not chunk). if bodyLen != paddedBodyLen { w.Write([]byte{0}) n++ } return }
go
func (a *Audio) WriteTo(w io.Writer) (n int64, err error) { // Calculate padded length of PCM chunk data. bodyLen := uint32(a.body.Len()) paddedBodyLen := bodyLen if bodyLen%2 != 0 { paddedBodyLen++ } totalLen := uint32(len(waveHeader)) - 4 + paddedBodyLen // Header. header := make([]byte, len(waveHeader)+4) // includes 4 bytes for chunk size copy(header, waveHeader) // Put the length of whole RIFF chunk. binary.LittleEndian.PutUint32(header[4:], totalLen) // Put the length of WAVE chunk. binary.LittleEndian.PutUint32(header[len(waveHeader):], bodyLen) // Write header. nn, err := w.Write(header) n = int64(nn) if err != nil { return } // Write data. n, err = a.body.WriteTo(w) n += int64(nn) if err != nil { return } // Pad byte if chunk length is odd. // (As header has even length, we can check if n is odd, not chunk). if bodyLen != paddedBodyLen { w.Write([]byte{0}) n++ } return }
[ "func", "(", "a", "*", "Audio", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "n", "int64", ",", "err", "error", ")", "{", "// Calculate padded length of PCM chunk data.", "bodyLen", ":=", "uint32", "(", "a", ".", "body", ".", "Len", "(", ")...
// WriteTo writes captcha audio in WAVE format into the given io.Writer, and // returns the number of bytes written and an error if any.
[ "WriteTo", "writes", "captcha", "audio", "in", "WAVE", "format", "into", "the", "given", "io", ".", "Writer", "and", "returns", "the", "number", "of", "bytes", "written", "and", "an", "error", "if", "any", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/audio.go#L85-L119
train
dchest/captcha
audio.go
mixSound
func mixSound(dst, src []byte) { for i, v := range src { av := int(v) bv := int(dst[i]) if av < 128 && bv < 128 { dst[i] = byte(av * bv / 128) } else { dst[i] = byte(2*(av+bv) - av*bv/128 - 256) } } }
go
func mixSound(dst, src []byte) { for i, v := range src { av := int(v) bv := int(dst[i]) if av < 128 && bv < 128 { dst[i] = byte(av * bv / 128) } else { dst[i] = byte(2*(av+bv) - av*bv/128 - 256) } } }
[ "func", "mixSound", "(", "dst", ",", "src", "[", "]", "byte", ")", "{", "for", "i", ",", "v", ":=", "range", "src", "{", "av", ":=", "int", "(", "v", ")", "\n", "bv", ":=", "int", "(", "dst", "[", "i", "]", ")", "\n", "if", "av", "<", "12...
// mixSound mixes src into dst. Dst must have length equal to or greater than // src length.
[ "mixSound", "mixes", "src", "into", "dst", ".", "Dst", "must", "have", "length", "equal", "to", "or", "greater", "than", "src", "length", "." ]
6a29415a8364ec2971fdc62d9e415ed53fc20410
https://github.com/dchest/captcha/blob/6a29415a8364ec2971fdc62d9e415ed53fc20410/audio.go#L172-L182
train
google/go-genproto
regen.go
goPkg
func goPkg(fname string) (string, error) { content, err := ioutil.ReadFile(fname) if err != nil { return "", err } var pkgName string if match := goPkgOptRe.FindSubmatch(content); len(match) > 0 { pn, err := strconv.Unquote(string(match[1])) if err != nil { return "", err } pkgName = pn } if p := strings.IndexRune(pkgName, ';'); p > 0 { pkgName = pkgName[:p] } return pkgName, nil }
go
func goPkg(fname string) (string, error) { content, err := ioutil.ReadFile(fname) if err != nil { return "", err } var pkgName string if match := goPkgOptRe.FindSubmatch(content); len(match) > 0 { pn, err := strconv.Unquote(string(match[1])) if err != nil { return "", err } pkgName = pn } if p := strings.IndexRune(pkgName, ';'); p > 0 { pkgName = pkgName[:p] } return pkgName, nil }
[ "func", "goPkg", "(", "fname", "string", ")", "(", "string", ",", "error", ")", "{", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "fname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\...
// goPkg reports the import path declared in the given file's // `go_package` option. If the option is missing, goPkg returns empty string.
[ "goPkg", "reports", "the", "import", "path", "declared", "in", "the", "given", "file", "s", "go_package", "option", ".", "If", "the", "option", "is", "missing", "goPkg", "returns", "empty", "string", "." ]
54afdca5d873f7b529e2ce3def1a99df16feda90
https://github.com/google/go-genproto/blob/54afdca5d873f7b529e2ce3def1a99df16feda90/regen.go#L107-L125
train
google/go-genproto
regen.go
protoc
func protoc(goOut string, includes, fnames []string) ([]byte, error) { args := []string{"--go_out=plugins=grpc:" + goOut} for _, inc := range includes { args = append(args, "-I", inc) } args = append(args, fnames...) return exec.Command("protoc", args...).CombinedOutput() }
go
func protoc(goOut string, includes, fnames []string) ([]byte, error) { args := []string{"--go_out=plugins=grpc:" + goOut} for _, inc := range includes { args = append(args, "-I", inc) } args = append(args, fnames...) return exec.Command("protoc", args...).CombinedOutput() }
[ "func", "protoc", "(", "goOut", "string", ",", "includes", ",", "fnames", "[", "]", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "args", ":=", "[", "]", "string", "{", "\"", "\"", "+", "goOut", "}", "\n", "for", "_", ",", "inc"...
// protoc executes the "protoc" command on files named in fnames, // passing go_out and include flags specified in goOut and includes respectively. // protoc returns combined output from stdout and stderr.
[ "protoc", "executes", "the", "protoc", "command", "on", "files", "named", "in", "fnames", "passing", "go_out", "and", "include", "flags", "specified", "in", "goOut", "and", "includes", "respectively", ".", "protoc", "returns", "combined", "output", "from", "stdo...
54afdca5d873f7b529e2ce3def1a99df16feda90
https://github.com/google/go-genproto/blob/54afdca5d873f7b529e2ce3def1a99df16feda90/regen.go#L130-L137
train
gopherjs/vecty
example/todomvc/store/storeutil/storeutil.go
Add
func (r *ListenerRegistry) Add(key interface{}, listener func()) { if key == nil { key = new(int) } if _, ok := r.listeners[key]; ok { panic("duplicate listener key") } r.listeners[key] = listener }
go
func (r *ListenerRegistry) Add(key interface{}, listener func()) { if key == nil { key = new(int) } if _, ok := r.listeners[key]; ok { panic("duplicate listener key") } r.listeners[key] = listener }
[ "func", "(", "r", "*", "ListenerRegistry", ")", "Add", "(", "key", "interface", "{", "}", ",", "listener", "func", "(", ")", ")", "{", "if", "key", "==", "nil", "{", "key", "=", "new", "(", "int", ")", "\n", "}", "\n", "if", "_", ",", "ok", "...
// Add adds listener with key to the registry. // key may be nil, then an arbitrary unused key is assigned. // It panics if a listener with same key is already present.
[ "Add", "adds", "listener", "with", "key", "to", "the", "registry", ".", "key", "may", "be", "nil", "then", "an", "arbitrary", "unused", "key", "is", "assigned", ".", "It", "panics", "if", "a", "listener", "with", "same", "key", "is", "already", "present"...
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/example/todomvc/store/storeutil/storeutil.go#L20-L28
train
gopherjs/vecty
dom.go
Node
func (h *HTML) Node() *js.Object { if h.node == nil { panic("vecty: cannot call (*HTML).Node() before DOM node creation / component mount") } return h.node.(wrappedObject).j }
go
func (h *HTML) Node() *js.Object { if h.node == nil { panic("vecty: cannot call (*HTML).Node() before DOM node creation / component mount") } return h.node.(wrappedObject).j }
[ "func", "(", "h", "*", "HTML", ")", "Node", "(", ")", "*", "js", ".", "Object", "{", "if", "h", ".", "node", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "h", ".", "node", ".", "(", "wrappedObject", ")", ".", ...
// Node returns the underlying JavaScript Element or TextNode. // // It panics if it is called before the DOM node has been attached, i.e. before // the associated component's Mounter interface would be invoked.
[ "Node", "returns", "the", "underlying", "JavaScript", "Element", "or", "TextNode", ".", "It", "panics", "if", "it", "is", "called", "before", "the", "DOM", "node", "has", "been", "attached", "i", ".", "e", ".", "before", "the", "associated", "component", "...
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L156-L161
train
gopherjs/vecty
dom.go
createNode
func (h *HTML) createNode() { switch { case h.tag != "" && h.text != "": panic("vecty: internal error (only one of HTML.tag or HTML.text may be set)") case h.tag == "" && h.innerHTML != "": panic("vecty: only HTML may have UnsafeHTML attribute") case h.tag != "" && h.namespace == "": h.node = global.Get("document").Call("createElement", h.tag) case h.tag != "" && h.namespace != "": h.node = global.Get("document").Call("createElementNS", h.namespace, h.tag) default: h.node = global.Get("document").Call("createTextNode", h.text) } }
go
func (h *HTML) createNode() { switch { case h.tag != "" && h.text != "": panic("vecty: internal error (only one of HTML.tag or HTML.text may be set)") case h.tag == "" && h.innerHTML != "": panic("vecty: only HTML may have UnsafeHTML attribute") case h.tag != "" && h.namespace == "": h.node = global.Get("document").Call("createElement", h.tag) case h.tag != "" && h.namespace != "": h.node = global.Get("document").Call("createElementNS", h.namespace, h.tag) default: h.node = global.Get("document").Call("createTextNode", h.text) } }
[ "func", "(", "h", "*", "HTML", ")", "createNode", "(", ")", "{", "switch", "{", "case", "h", ".", "tag", "!=", "\"", "\"", "&&", "h", ".", "text", "!=", "\"", "\"", ":", "panic", "(", "\"", "\"", ")", "\n", "case", "h", ".", "tag", "==", "\...
// createNode creates a HTML node of the appropriate type and namespace.
[ "createNode", "creates", "a", "HTML", "node", "of", "the", "appropriate", "type", "and", "namespace", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L175-L188
train
gopherjs/vecty
dom.go
reconcileText
func (h *HTML) reconcileText(prev *HTML) { h.node = prev.node // Text modifications. if h.text != prev.text { h.node.Set("nodeValue", h.text) } }
go
func (h *HTML) reconcileText(prev *HTML) { h.node = prev.node // Text modifications. if h.text != prev.text { h.node.Set("nodeValue", h.text) } }
[ "func", "(", "h", "*", "HTML", ")", "reconcileText", "(", "prev", "*", "HTML", ")", "{", "h", ".", "node", "=", "prev", ".", "node", "\n\n", "// Text modifications.", "if", "h", ".", "text", "!=", "prev", ".", "text", "{", "h", ".", "node", ".", ...
// reconcileText replaces the content of a text node.
[ "reconcileText", "replaces", "the", "content", "of", "a", "text", "node", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L191-L198
train
gopherjs/vecty
dom.go
removeChildren
func (h *HTML) removeChildren(prevChildren []ComponentOrHTML) { for _, prevChild := range prevChildren { if prevChildList, ok := prevChild.(KeyedList); ok { // Previous child was a list, so remove all DOM nodes in it. prevChildList.remove(h) continue } prevChildRender := extractHTML(prevChild) if prevChildRender == nil { continue } h.removeChild(prevChildRender) } }
go
func (h *HTML) removeChildren(prevChildren []ComponentOrHTML) { for _, prevChild := range prevChildren { if prevChildList, ok := prevChild.(KeyedList); ok { // Previous child was a list, so remove all DOM nodes in it. prevChildList.remove(h) continue } prevChildRender := extractHTML(prevChild) if prevChildRender == nil { continue } h.removeChild(prevChildRender) } }
[ "func", "(", "h", "*", "HTML", ")", "removeChildren", "(", "prevChildren", "[", "]", "ComponentOrHTML", ")", "{", "for", "_", ",", "prevChild", ":=", "range", "prevChildren", "{", "if", "prevChildList", ",", "ok", ":=", "prevChild", ".", "(", "KeyedList", ...
// removeChildren removes child elements from the previous render pass that no // longer exist on the current HTML children.
[ "removeChildren", "removes", "child", "elements", "from", "the", "previous", "render", "pass", "that", "no", "longer", "exist", "on", "the", "current", "HTML", "children", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L605-L618
train
gopherjs/vecty
dom.go
firstChild
func (h *HTML) firstChild() jsObject { if h == nil || h.node == nil { return nil } return h.node.Get("firstChild") }
go
func (h *HTML) firstChild() jsObject { if h == nil || h.node == nil { return nil } return h.node.Get("firstChild") }
[ "func", "(", "h", "*", "HTML", ")", "firstChild", "(", ")", "jsObject", "{", "if", "h", "==", "nil", "||", "h", ".", "node", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "h", ".", "node", ".", "Get", "(", "\"", "\"", ")", "\n...
// firstChild returns the first child DOM node of this element.
[ "firstChild", "returns", "the", "first", "child", "DOM", "node", "of", "this", "element", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L621-L626
train
gopherjs/vecty
dom.go
nextSibling
func (h *HTML) nextSibling() jsObject { if h == nil || h.node == nil { return nil } return h.node.Get("nextSibling") }
go
func (h *HTML) nextSibling() jsObject { if h == nil || h.node == nil { return nil } return h.node.Get("nextSibling") }
[ "func", "(", "h", "*", "HTML", ")", "nextSibling", "(", ")", "jsObject", "{", "if", "h", "==", "nil", "||", "h", ".", "node", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "h", ".", "node", ".", "Get", "(", "\"", "\"", ")", "\...
// nextSibling returns the next sibling DOM node for this element.
[ "nextSibling", "returns", "the", "next", "sibling", "DOM", "node", "for", "this", "element", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L629-L634
train
gopherjs/vecty
dom.go
removeChild
func (h *HTML) removeChild(child *HTML) { // If we're removing the current insert target, use the next // sibling, if any. if h.insertBeforeNode != nil && h.insertBeforeNode == child.node { h.insertBeforeNode = h.insertBeforeNode.Get("nextSibling") } unmount(child) if child.node == nil { return } // Use the child's parent node here, in case our node is not a valid // target by the time we're called. child.node.Get("parentNode").Call("removeChild", child.node) }
go
func (h *HTML) removeChild(child *HTML) { // If we're removing the current insert target, use the next // sibling, if any. if h.insertBeforeNode != nil && h.insertBeforeNode == child.node { h.insertBeforeNode = h.insertBeforeNode.Get("nextSibling") } unmount(child) if child.node == nil { return } // Use the child's parent node here, in case our node is not a valid // target by the time we're called. child.node.Get("parentNode").Call("removeChild", child.node) }
[ "func", "(", "h", "*", "HTML", ")", "removeChild", "(", "child", "*", "HTML", ")", "{", "// If we're removing the current insert target, use the next", "// sibling, if any.", "if", "h", ".", "insertBeforeNode", "!=", "nil", "&&", "h", ".", "insertBeforeNode", "==", ...
// removeChild removes the provided child element from this element, and // triggers unmount handlers.
[ "removeChild", "removes", "the", "provided", "child", "element", "from", "this", "element", "and", "triggers", "unmount", "handlers", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L638-L651
train
gopherjs/vecty
dom.go
appendChild
func (h *HTML) appendChild(child *HTML) { h.node.Call("appendChild", child.node) }
go
func (h *HTML) appendChild(child *HTML) { h.node.Call("appendChild", child.node) }
[ "func", "(", "h", "*", "HTML", ")", "appendChild", "(", "child", "*", "HTML", ")", "{", "h", ".", "node", ".", "Call", "(", "\"", "\"", ",", "child", ".", "node", ")", "\n", "}" ]
// appendChild appends a new child to this element.
[ "appendChild", "appends", "a", "new", "child", "to", "this", "element", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L654-L656
train
gopherjs/vecty
dom.go
insertBefore
func (h *HTML) insertBefore(node jsObject, child *HTML) { if node == nil { h.appendChild(child) return } h.node.Call("insertBefore", child.node, node) }
go
func (h *HTML) insertBefore(node jsObject, child *HTML) { if node == nil { h.appendChild(child) return } h.node.Call("insertBefore", child.node, node) }
[ "func", "(", "h", "*", "HTML", ")", "insertBefore", "(", "node", "jsObject", ",", "child", "*", "HTML", ")", "{", "if", "node", "==", "nil", "{", "h", ".", "appendChild", "(", "child", ")", "\n", "return", "\n", "}", "\n", "h", ".", "node", ".", ...
// insertBefore inserts the provided child before the provided DOM node. If the // DOM node is nil, the child will be appended instead.
[ "insertBefore", "inserts", "the", "provided", "child", "before", "the", "provided", "DOM", "node", ".", "If", "the", "DOM", "node", "is", "nil", "the", "child", "will", "be", "appended", "instead", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L660-L666
train
gopherjs/vecty
dom.go
WithKey
func (l List) WithKey(key interface{}) KeyedList { return KeyedList{key: key, html: &HTML{children: l}} }
go
func (l List) WithKey(key interface{}) KeyedList { return KeyedList{key: key, html: &HTML{children: l}} }
[ "func", "(", "l", "List", ")", "WithKey", "(", "key", "interface", "{", "}", ")", "KeyedList", "{", "return", "KeyedList", "{", "key", ":", "key", ",", "html", ":", "&", "HTML", "{", "children", ":", "l", "}", "}", "\n", "}" ]
// WithKey wraps the List in a Keyer using the given key. List members are // inaccessible within the returned value.
[ "WithKey", "wraps", "the", "List", "in", "a", "Keyer", "using", "the", "given", "key", ".", "List", "members", "are", "inaccessible", "within", "the", "returned", "value", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L679-L681
train
gopherjs/vecty
dom.go
reconcile
func (l KeyedList) reconcile(parent *HTML, prevChild ComponentOrHTML) (pendingMounts []Mounter) { // Effectively become the parent (copy its scope) so that we can reconcile // our children against the prev child. l.html.node = parent.node l.html.insertBeforeNode = parent.insertBeforeNode l.html.lastRenderedChild = parent.lastRenderedChild switch v := prevChild.(type) { case KeyedList: pendingMounts = l.html.reconcileChildren(v.html) case *HTML, Component, nil: if v == nil { // No previous element, so reconcile against a parent with no // children so all of our elements are added. pendingMounts = l.html.reconcileChildren(&HTML{node: parent.node}) } else { // Build a previous render containing just the prevChild to be // replaced by this list prev := &HTML{node: parent.node, children: []ComponentOrHTML{prevChild}} if keyer, ok := prevChild.(Keyer); ok && keyer.Key() != nil { prev.keyedChildren = map[interface{}]ComponentOrHTML{keyer.Key(): prevChild} } pendingMounts = l.html.reconcileChildren(prev) } default: panic("vecty: internal error (unexpected ComponentOrHTML type " + reflect.TypeOf(v).String() + ")") } // Update the parent insertBeforeNode and lastRenderedChild values to be // ours, since we acted as the parent and ours is now updated / theirs is // outdated. if parent.insertBeforeNode != nil { parent.insertBeforeNode = l.html.insertBeforeNode } if l.html.lastRenderedChild != nil { parent.lastRenderedChild = l.html.lastRenderedChild } return pendingMounts }
go
func (l KeyedList) reconcile(parent *HTML, prevChild ComponentOrHTML) (pendingMounts []Mounter) { // Effectively become the parent (copy its scope) so that we can reconcile // our children against the prev child. l.html.node = parent.node l.html.insertBeforeNode = parent.insertBeforeNode l.html.lastRenderedChild = parent.lastRenderedChild switch v := prevChild.(type) { case KeyedList: pendingMounts = l.html.reconcileChildren(v.html) case *HTML, Component, nil: if v == nil { // No previous element, so reconcile against a parent with no // children so all of our elements are added. pendingMounts = l.html.reconcileChildren(&HTML{node: parent.node}) } else { // Build a previous render containing just the prevChild to be // replaced by this list prev := &HTML{node: parent.node, children: []ComponentOrHTML{prevChild}} if keyer, ok := prevChild.(Keyer); ok && keyer.Key() != nil { prev.keyedChildren = map[interface{}]ComponentOrHTML{keyer.Key(): prevChild} } pendingMounts = l.html.reconcileChildren(prev) } default: panic("vecty: internal error (unexpected ComponentOrHTML type " + reflect.TypeOf(v).String() + ")") } // Update the parent insertBeforeNode and lastRenderedChild values to be // ours, since we acted as the parent and ours is now updated / theirs is // outdated. if parent.insertBeforeNode != nil { parent.insertBeforeNode = l.html.insertBeforeNode } if l.html.lastRenderedChild != nil { parent.lastRenderedChild = l.html.lastRenderedChild } return pendingMounts }
[ "func", "(", "l", "KeyedList", ")", "reconcile", "(", "parent", "*", "HTML", ",", "prevChild", "ComponentOrHTML", ")", "(", "pendingMounts", "[", "]", "Mounter", ")", "{", "// Effectively become the parent (copy its scope) so that we can reconcile", "// our children again...
// reconcile reconciles the keyedList against the DOM node in a separate // context, unless keyed. Uses the currently known insertion point from the // parent to insert children at the correct position.
[ "reconcile", "reconciles", "the", "keyedList", "against", "the", "DOM", "node", "in", "a", "separate", "context", "unless", "keyed", ".", "Uses", "the", "currently", "known", "insertion", "point", "from", "the", "parent", "to", "insert", "children", "at", "the...
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L708-L746
train
gopherjs/vecty
dom.go
remove
func (l KeyedList) remove(parent *HTML) { // Become the parent so that we can remove all of our children and get an // updated insertBeforeNode value. l.html.node = parent.node l.html.insertBeforeNode = parent.insertBeforeNode l.html.removeChildren(l.html.children) // Now that the children are removed, and our insertBeforeNode value has // been updated, update the parent's insertBeforeNode value since it is now // invalid and ours is correct. if parent.insertBeforeNode != nil { parent.insertBeforeNode = l.html.insertBeforeNode } }
go
func (l KeyedList) remove(parent *HTML) { // Become the parent so that we can remove all of our children and get an // updated insertBeforeNode value. l.html.node = parent.node l.html.insertBeforeNode = parent.insertBeforeNode l.html.removeChildren(l.html.children) // Now that the children are removed, and our insertBeforeNode value has // been updated, update the parent's insertBeforeNode value since it is now // invalid and ours is correct. if parent.insertBeforeNode != nil { parent.insertBeforeNode = l.html.insertBeforeNode } }
[ "func", "(", "l", "KeyedList", ")", "remove", "(", "parent", "*", "HTML", ")", "{", "// Become the parent so that we can remove all of our children and get an", "// updated insertBeforeNode value.", "l", ".", "html", ".", "node", "=", "parent", ".", "node", "\n", "l",...
// remove keyedList elements from the parent.
[ "remove", "keyedList", "elements", "from", "the", "parent", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L749-L762
train
gopherjs/vecty
dom.go
add
func (b *batchRenderer) add(c Component) { if i, ok := b.idx[c]; ok { // Shift idx for delete. for j, c := range b.batch[i+1:] { b.idx[c] = i + j } // Delete previously queued render. copy(b.batch[i:], b.batch[i+1:]) b.batch[len(b.batch)-1] = nil b.batch = b.batch[:len(b.batch)-1] } // Append and index component. b.batch = append(b.batch, c) b.idx[c] = len(b.batch) - 1 // If we're not already scheduled for a render batch, request a render on // the next frame. if !b.scheduled { b.scheduled = true requestAnimationFrame(b.render) } }
go
func (b *batchRenderer) add(c Component) { if i, ok := b.idx[c]; ok { // Shift idx for delete. for j, c := range b.batch[i+1:] { b.idx[c] = i + j } // Delete previously queued render. copy(b.batch[i:], b.batch[i+1:]) b.batch[len(b.batch)-1] = nil b.batch = b.batch[:len(b.batch)-1] } // Append and index component. b.batch = append(b.batch, c) b.idx[c] = len(b.batch) - 1 // If we're not already scheduled for a render batch, request a render on // the next frame. if !b.scheduled { b.scheduled = true requestAnimationFrame(b.render) } }
[ "func", "(", "b", "*", "batchRenderer", ")", "add", "(", "c", "Component", ")", "{", "if", "i", ",", "ok", ":=", "b", ".", "idx", "[", "c", "]", ";", "ok", "{", "// Shift idx for delete.", "for", "j", ",", "c", ":=", "range", "b", ".", "batch", ...
// add a Component to the pending batch.
[ "add", "a", "Component", "to", "the", "pending", "batch", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L825-L845
train
gopherjs/vecty
dom.go
sameType
func sameType(first, second ComponentOrHTML) bool { return reflect.TypeOf(first) == reflect.TypeOf(second) }
go
func sameType(first, second ComponentOrHTML) bool { return reflect.TypeOf(first) == reflect.TypeOf(second) }
[ "func", "sameType", "(", "first", ",", "second", "ComponentOrHTML", ")", "bool", "{", "return", "reflect", ".", "TypeOf", "(", "first", ")", "==", "reflect", ".", "TypeOf", "(", "second", ")", "\n", "}" ]
// sameType returns whether first and second ComponentOrHTML are of the same // underlying type.
[ "sameType", "returns", "whether", "first", "and", "second", "ComponentOrHTML", "are", "of", "the", "same", "underlying", "type", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L915-L917
train
gopherjs/vecty
dom.go
copyComponent
func copyComponent(c Component) Component { if c == nil { panic("vecty: internal error (cannot copy nil Component)") } // If the Component implements the Copier interface, then use that to // perform the copy. if copier, ok := c.(Copier); ok { cpy := copier.Copy() if cpy == c { panic("vecty: Component.Copy illegally returned an identical *MyComponent pointer") } return cpy } // Component does not implement the Copier interface, so perform a shallow // copy. v := reflect.ValueOf(c) if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { panic("vecty: Component must be pointer to struct, found " + reflect.TypeOf(c).String()) } cpy := reflect.New(v.Elem().Type()) cpy.Elem().Set(v.Elem()) return cpy.Interface().(Component) }
go
func copyComponent(c Component) Component { if c == nil { panic("vecty: internal error (cannot copy nil Component)") } // If the Component implements the Copier interface, then use that to // perform the copy. if copier, ok := c.(Copier); ok { cpy := copier.Copy() if cpy == c { panic("vecty: Component.Copy illegally returned an identical *MyComponent pointer") } return cpy } // Component does not implement the Copier interface, so perform a shallow // copy. v := reflect.ValueOf(c) if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { panic("vecty: Component must be pointer to struct, found " + reflect.TypeOf(c).String()) } cpy := reflect.New(v.Elem().Type()) cpy.Elem().Set(v.Elem()) return cpy.Interface().(Component) }
[ "func", "copyComponent", "(", "c", "Component", ")", "Component", "{", "if", "c", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// If the Component implements the Copier interface, then use that to", "// perform the copy.", "if", "copier", ","...
// copyComponent makes a copy of the given component.
[ "copyComponent", "makes", "a", "copy", "of", "the", "given", "component", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L920-L944
train
gopherjs/vecty
dom.go
mountUnmount
func mountUnmount(next, prev ComponentOrHTML) Mounter { if next == prev { return nil } if !sameType(next, prev) { if prev != nil { unmount(prev) } if m, ok := next.(Mounter); ok { return m } return nil } if prevHTML := extractHTML(prev); prevHTML != nil { if nextHTML := extractHTML(next); nextHTML == nil || prevHTML.node != nextHTML.node { for _, child := range prevHTML.children { unmount(child) } } } if u, ok := prev.(Unmounter); ok { u.Unmount() } if m, ok := next.(Mounter); ok { return m } return nil }
go
func mountUnmount(next, prev ComponentOrHTML) Mounter { if next == prev { return nil } if !sameType(next, prev) { if prev != nil { unmount(prev) } if m, ok := next.(Mounter); ok { return m } return nil } if prevHTML := extractHTML(prev); prevHTML != nil { if nextHTML := extractHTML(next); nextHTML == nil || prevHTML.node != nextHTML.node { for _, child := range prevHTML.children { unmount(child) } } } if u, ok := prev.(Unmounter); ok { u.Unmount() } if m, ok := next.(Mounter); ok { return m } return nil }
[ "func", "mountUnmount", "(", "next", ",", "prev", "ComponentOrHTML", ")", "Mounter", "{", "if", "next", "==", "prev", "{", "return", "nil", "\n", "}", "\n", "if", "!", "sameType", "(", "next", ",", "prev", ")", "{", "if", "prev", "!=", "nil", "{", ...
// mountUnmount determines whether a mount or unmount event should occur, // actions unmounts recursively if appropriate, and returns either a Mounter, // or nil.
[ "mountUnmount", "determines", "whether", "a", "mount", "or", "unmount", "event", "should", "occur", "actions", "unmounts", "recursively", "if", "appropriate", "and", "returns", "either", "a", "Mounter", "or", "nil", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L1076-L1103
train
gopherjs/vecty
dom.go
mount
func mount(pendingMounts ...Mounter) { for _, mounter := range pendingMounts { if mounter == nil { continue } if c, ok := mounter.(Component); ok { if c.Context().mounted { continue } c.Context().mounted = true c.Context().unmounted = false } mounter.Mount() } }
go
func mount(pendingMounts ...Mounter) { for _, mounter := range pendingMounts { if mounter == nil { continue } if c, ok := mounter.(Component); ok { if c.Context().mounted { continue } c.Context().mounted = true c.Context().unmounted = false } mounter.Mount() } }
[ "func", "mount", "(", "pendingMounts", "...", "Mounter", ")", "{", "for", "_", ",", "mounter", ":=", "range", "pendingMounts", "{", "if", "mounter", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "c", ",", "ok", ":=", "mounter", ".", "(", "Comp...
// mount all pending Mounters
[ "mount", "all", "pending", "Mounters" ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L1106-L1120
train
gopherjs/vecty
dom.go
unmount
func unmount(e ComponentOrHTML) { if c, ok := e.(Component); ok { if c.Context().unmounted { return } c.Context().unmounted = true c.Context().mounted = false if prevRenderComponent, ok := c.Context().prevRender.(Component); ok { unmount(prevRenderComponent) } } if l, ok := e.(KeyedList); ok { for _, child := range l.html.children { unmount(child) } return } if h := extractHTML(e); h != nil { for _, child := range h.children { unmount(child) } } if u, ok := e.(Unmounter); ok { u.Unmount() } }
go
func unmount(e ComponentOrHTML) { if c, ok := e.(Component); ok { if c.Context().unmounted { return } c.Context().unmounted = true c.Context().mounted = false if prevRenderComponent, ok := c.Context().prevRender.(Component); ok { unmount(prevRenderComponent) } } if l, ok := e.(KeyedList); ok { for _, child := range l.html.children { unmount(child) } return } if h := extractHTML(e); h != nil { for _, child := range h.children { unmount(child) } } if u, ok := e.(Unmounter); ok { u.Unmount() } }
[ "func", "unmount", "(", "e", "ComponentOrHTML", ")", "{", "if", "c", ",", "ok", ":=", "e", ".", "(", "Component", ")", ";", "ok", "{", "if", "c", ".", "Context", "(", ")", ".", "unmounted", "{", "return", "\n", "}", "\n", "c", ".", "Context", "...
// unmount recursively unmounts the provided ComponentOrHTML, and any children // that satisfy the Unmounter interface.
[ "unmount", "recursively", "unmounts", "the", "provided", "ComponentOrHTML", "and", "any", "children", "that", "satisfy", "the", "Unmounter", "interface", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L1124-L1152
train
gopherjs/vecty
dom.go
RenderBody
func RenderBody(body Component) { // block batch until we're done batch.scheduled = true defer func() { requestAnimationFrame(batch.render) }() nextRender, skip, pendingMounts := renderComponent(body, nil) if skip { panic("vecty: RenderBody Component.SkipRender illegally returned true") } if nextRender.tag != "body" { panic("vecty: RenderBody expected Component.Render to return a body tag, found \"" + nextRender.tag + "\"") } doc := global.Get("document") if doc.Get("readyState").String() == "loading" { doc.Call("addEventListener", "DOMContentLoaded", func() { // avoid duplicate body doc.Set("body", nextRender.node) mount(pendingMounts...) if m, ok := body.(Mounter); ok { mount(m) } }) return } doc.Set("body", nextRender.node) mount(pendingMounts...) if m, ok := body.(Mounter); ok { mount(m) } }
go
func RenderBody(body Component) { // block batch until we're done batch.scheduled = true defer func() { requestAnimationFrame(batch.render) }() nextRender, skip, pendingMounts := renderComponent(body, nil) if skip { panic("vecty: RenderBody Component.SkipRender illegally returned true") } if nextRender.tag != "body" { panic("vecty: RenderBody expected Component.Render to return a body tag, found \"" + nextRender.tag + "\"") } doc := global.Get("document") if doc.Get("readyState").String() == "loading" { doc.Call("addEventListener", "DOMContentLoaded", func() { // avoid duplicate body doc.Set("body", nextRender.node) mount(pendingMounts...) if m, ok := body.(Mounter); ok { mount(m) } }) return } doc.Set("body", nextRender.node) mount(pendingMounts...) if m, ok := body.(Mounter); ok { mount(m) } }
[ "func", "RenderBody", "(", "body", "Component", ")", "{", "// block batch until we're done", "batch", ".", "scheduled", "=", "true", "\n", "defer", "func", "(", ")", "{", "requestAnimationFrame", "(", "batch", ".", "render", ")", "\n", "}", "(", ")", "\n", ...
// RenderBody renders the given component as the document body. The given // Component's Render method must return a "body" element.
[ "RenderBody", "renders", "the", "given", "component", "as", "the", "document", "body", ".", "The", "given", "Component", "s", "Render", "method", "must", "return", "a", "body", "element", "." ]
d00da0c86b426642cf5acc29133d33491a711209
https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L1161-L1190
train