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
tebeka/selenium
chrome/capabilities.go
AddUnpackedExtension
func (c *Capabilities) AddUnpackedExtension(basePath string) error { buf, _, err := NewExtension(basePath) if err != nil { return err } return c.addExtension(bytes.NewBuffer(buf)) }
go
func (c *Capabilities) AddUnpackedExtension(basePath string) error { buf, _, err := NewExtension(basePath) if err != nil { return err } return c.addExtension(bytes.NewBuffer(buf)) }
[ "func", "(", "c", "*", "Capabilities", ")", "AddUnpackedExtension", "(", "basePath", "string", ")", "error", "{", "buf", ",", "_", ",", "err", ":=", "NewExtension", "(", "basePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", ...
// AddUnpackedExtension creates a packaged Chrome extension with the files // below the provided directory path and causes the browser to load that // extension at startup.
[ "AddUnpackedExtension", "creates", "a", "packaged", "Chrome", "extension", "with", "the", "files", "below", "the", "provided", "directory", "path", "and", "causes", "the", "browser", "to", "load", "that", "extension", "at", "startup", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/chrome/capabilities.go#L153-L159
train
tebeka/selenium
chrome/capabilities.go
NewExtension
func NewExtension(basePath string) ([]byte, *rsa.PrivateKey, error) { key, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return nil, nil, err } data, err := NewExtensionWithKey(basePath, key) if err != nil { return nil, nil, err } return data, key, nil }
go
func NewExtension(basePath string) ([]byte, *rsa.PrivateKey, error) { key, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return nil, nil, err } data, err := NewExtensionWithKey(basePath, key) if err != nil { return nil, nil, err } return data, key, nil }
[ "func", "NewExtension", "(", "basePath", "string", ")", "(", "[", "]", "byte", ",", "*", "rsa", ".", "PrivateKey", ",", "error", ")", "{", "key", ",", "err", ":=", "rsa", ".", "GenerateKey", "(", "rand", ".", "Reader", ",", "2048", ")", "\n", "if",...
// NewExtension creates the payload of a Chrome extension file which is signed // using the returned private key.
[ "NewExtension", "creates", "the", "payload", "of", "a", "Chrome", "extension", "file", "which", "is", "signed", "using", "the", "returned", "private", "key", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/chrome/capabilities.go#L163-L173
train
tebeka/selenium
chrome/capabilities.go
NewExtensionWithKey
func NewExtensionWithKey(basePath string, key *rsa.PrivateKey) ([]byte, error) { zip, err := zip.New(basePath) if err != nil { return nil, err } h := sha1.New() if _, err := io.Copy(h, bytes.NewReader(zip.Bytes())); err != nil { return nil, err } hashed := h.Sum(nil) signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA1, hashed[:]) if err != nil { return nil, err } pubKey, err := x509.MarshalPKIXPublicKey(key.Public()) if err != nil { return nil, err } // This format is documented at https://developer.chrome.com/extensions/crx . buf := new(bytes.Buffer) if _, err := buf.Write([]byte("Cr24")); err != nil { // Magic number. return nil, err } // Version. if err := binary.Write(buf, binary.LittleEndian, uint32(2)); err != nil { return nil, err } // Public key length. if err := binary.Write(buf, binary.LittleEndian, uint32(len(pubKey))); err != nil { return nil, err } // Signature length. if err := binary.Write(buf, binary.LittleEndian, uint32(len(signature))); err != nil { return nil, err } // Public key payload. if err := binary.Write(buf, binary.LittleEndian, pubKey); err != nil { return nil, err } // Signature payload. if err := binary.Write(buf, binary.LittleEndian, signature); err != nil { return nil, err } // Zipped extension directory payload. if err := binary.Write(buf, binary.LittleEndian, zip.Bytes()); err != nil { return nil, err } return buf.Bytes(), nil }
go
func NewExtensionWithKey(basePath string, key *rsa.PrivateKey) ([]byte, error) { zip, err := zip.New(basePath) if err != nil { return nil, err } h := sha1.New() if _, err := io.Copy(h, bytes.NewReader(zip.Bytes())); err != nil { return nil, err } hashed := h.Sum(nil) signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA1, hashed[:]) if err != nil { return nil, err } pubKey, err := x509.MarshalPKIXPublicKey(key.Public()) if err != nil { return nil, err } // This format is documented at https://developer.chrome.com/extensions/crx . buf := new(bytes.Buffer) if _, err := buf.Write([]byte("Cr24")); err != nil { // Magic number. return nil, err } // Version. if err := binary.Write(buf, binary.LittleEndian, uint32(2)); err != nil { return nil, err } // Public key length. if err := binary.Write(buf, binary.LittleEndian, uint32(len(pubKey))); err != nil { return nil, err } // Signature length. if err := binary.Write(buf, binary.LittleEndian, uint32(len(signature))); err != nil { return nil, err } // Public key payload. if err := binary.Write(buf, binary.LittleEndian, pubKey); err != nil { return nil, err } // Signature payload. if err := binary.Write(buf, binary.LittleEndian, signature); err != nil { return nil, err } // Zipped extension directory payload. if err := binary.Write(buf, binary.LittleEndian, zip.Bytes()); err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "NewExtensionWithKey", "(", "basePath", "string", ",", "key", "*", "rsa", ".", "PrivateKey", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "zip", ",", "err", ":=", "zip", ".", "New", "(", "basePath", ")", "\n", "if", "err", "!=", "nil...
// NewExtensionWithKey creates the payload of a Chrome extension file which is // signed by the provided private key.
[ "NewExtensionWithKey", "creates", "the", "payload", "of", "a", "Chrome", "extension", "file", "which", "is", "signed", "by", "the", "provided", "private", "key", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/chrome/capabilities.go#L177-L235
train
tebeka/selenium
remote.go
execute
func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) { debugLog("-> %s %s\n%s", method, filteredURL(url), data) request, err := newRequest(method, url, data) if err != nil { return nil, err } response, err := HTTPClient.Do(request) if err != nil { return nil, err } buf, err := ioutil.ReadAll(response.Body) if debugFlag { if err == nil { // Pretty print the JSON response var prettyBuf bytes.Buffer if err = json.Indent(&prettyBuf, buf, "", " "); err == nil && prettyBuf.Len() > 0 { buf = prettyBuf.Bytes() } } debugLog("<- %s [%s]\n%s", response.Status, response.Header["Content-Type"], buf) } if err != nil { return nil, errors.New(response.Status) } fullCType := response.Header.Get("Content-Type") cType, _, err := mime.ParseMediaType(fullCType) if err != nil { return nil, fmt.Errorf("got content type header %q, expected %q", fullCType, jsonContentType) } if cType != jsonContentType { return nil, fmt.Errorf("got content type %q, expected %q", cType, jsonContentType) } reply := new(serverReply) if err := json.Unmarshal(buf, reply); err != nil { if response.StatusCode != http.StatusOK { return nil, fmt.Errorf("bad server reply status: %s", response.Status) } return nil, err } if reply.Err != "" { return nil, &reply.Error } // Handle the W3C-compliant error format. In the W3C spec, the error is // embedded in the 'value' field. if len(reply.Value) > 0 { respErr := new(Error) if err := json.Unmarshal(reply.Value, respErr); err == nil && respErr.Err != "" { respErr.HTTPCode = response.StatusCode return nil, respErr } } // Handle the legacy error format. const success = 0 if reply.Status != success { shortMsg, ok := remoteErrors[reply.Status] if !ok { shortMsg = fmt.Sprintf("unknown error - %d", reply.Status) } longMsg := new(struct { Message string }) if err := json.Unmarshal(reply.Value, longMsg); err != nil { return nil, errors.New(shortMsg) } return nil, &Error{ Err: shortMsg, Message: longMsg.Message, HTTPCode: response.StatusCode, LegacyCode: reply.Status, } } return buf, nil }
go
func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) { debugLog("-> %s %s\n%s", method, filteredURL(url), data) request, err := newRequest(method, url, data) if err != nil { return nil, err } response, err := HTTPClient.Do(request) if err != nil { return nil, err } buf, err := ioutil.ReadAll(response.Body) if debugFlag { if err == nil { // Pretty print the JSON response var prettyBuf bytes.Buffer if err = json.Indent(&prettyBuf, buf, "", " "); err == nil && prettyBuf.Len() > 0 { buf = prettyBuf.Bytes() } } debugLog("<- %s [%s]\n%s", response.Status, response.Header["Content-Type"], buf) } if err != nil { return nil, errors.New(response.Status) } fullCType := response.Header.Get("Content-Type") cType, _, err := mime.ParseMediaType(fullCType) if err != nil { return nil, fmt.Errorf("got content type header %q, expected %q", fullCType, jsonContentType) } if cType != jsonContentType { return nil, fmt.Errorf("got content type %q, expected %q", cType, jsonContentType) } reply := new(serverReply) if err := json.Unmarshal(buf, reply); err != nil { if response.StatusCode != http.StatusOK { return nil, fmt.Errorf("bad server reply status: %s", response.Status) } return nil, err } if reply.Err != "" { return nil, &reply.Error } // Handle the W3C-compliant error format. In the W3C spec, the error is // embedded in the 'value' field. if len(reply.Value) > 0 { respErr := new(Error) if err := json.Unmarshal(reply.Value, respErr); err == nil && respErr.Err != "" { respErr.HTTPCode = response.StatusCode return nil, respErr } } // Handle the legacy error format. const success = 0 if reply.Status != success { shortMsg, ok := remoteErrors[reply.Status] if !ok { shortMsg = fmt.Sprintf("unknown error - %d", reply.Status) } longMsg := new(struct { Message string }) if err := json.Unmarshal(reply.Value, longMsg); err != nil { return nil, errors.New(shortMsg) } return nil, &Error{ Err: shortMsg, Message: longMsg.Message, HTTPCode: response.StatusCode, LegacyCode: reply.Status, } } return buf, nil }
[ "func", "(", "wd", "*", "remoteWD", ")", "execute", "(", "method", ",", "url", "string", ",", "data", "[", "]", "byte", ")", "(", "json", ".", "RawMessage", ",", "error", ")", "{", "debugLog", "(", "\"", "\\n", "\"", ",", "method", ",", "filteredUR...
// execute performs an HTTP request and inspects the returned data for an error // encoded by the remote end in a JSON structure. If no error is present, the // entire, raw request payload is returned.
[ "execute", "performs", "an", "HTTP", "request", "and", "inspects", "the", "returned", "data", "for", "an", "error", "encoded", "by", "the", "remote", "end", "in", "a", "JSON", "structure", ".", "If", "no", "error", "is", "present", "the", "entire", "raw", ...
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/remote.go#L124-L204
train
tebeka/selenium
remote.go
parseVersion
func parseVersion(v string) (semver.Version, error) { parts := strings.Split(v, ".") var err error for i := len(parts); i > 0; i-- { var ver semver.Version ver, err = semver.ParseTolerant(strings.Join(parts[:i], ".")) if err == nil { return ver, nil } } return semver.Version{}, err }
go
func parseVersion(v string) (semver.Version, error) { parts := strings.Split(v, ".") var err error for i := len(parts); i > 0; i-- { var ver semver.Version ver, err = semver.ParseTolerant(strings.Join(parts[:i], ".")) if err == nil { return ver, nil } } return semver.Version{}, err }
[ "func", "parseVersion", "(", "v", "string", ")", "(", "semver", ".", "Version", ",", "error", ")", "{", "parts", ":=", "strings", ".", "Split", "(", "v", ",", "\"", "\"", ")", "\n", "var", "err", "error", "\n", "for", "i", ":=", "len", "(", "part...
// parseVersion sanitizes the browser version enough for semver.ParseTolerant // to parse it.
[ "parseVersion", "sanitizes", "the", "browser", "version", "enough", "for", "semver", ".", "ParseTolerant", "to", "parse", "it", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/remote.go#L311-L322
train
tebeka/selenium
remote.go
newW3CCapabilities
func newW3CCapabilities(caps Capabilities) Capabilities { alwaysMatch := make(Capabilities) for name, value := range caps { if isValidW3CCapability[name] || strings.Contains(name, ":") { alwaysMatch[name] = value } } // Move the Firefox profile setting from the old location to the new // location. if prof, ok := caps["firefox_profile"]; ok { if c, ok := alwaysMatch[firefox.CapabilitiesKey]; ok { firefoxCaps := c.(firefox.Capabilities) if firefoxCaps.Profile == "" { firefoxCaps.Profile = prof.(string) } } else { alwaysMatch[firefox.CapabilitiesKey] = firefox.Capabilities{ Profile: prof.(string), } } } return Capabilities{ "alwaysMatch": alwaysMatch, } }
go
func newW3CCapabilities(caps Capabilities) Capabilities { alwaysMatch := make(Capabilities) for name, value := range caps { if isValidW3CCapability[name] || strings.Contains(name, ":") { alwaysMatch[name] = value } } // Move the Firefox profile setting from the old location to the new // location. if prof, ok := caps["firefox_profile"]; ok { if c, ok := alwaysMatch[firefox.CapabilitiesKey]; ok { firefoxCaps := c.(firefox.Capabilities) if firefoxCaps.Profile == "" { firefoxCaps.Profile = prof.(string) } } else { alwaysMatch[firefox.CapabilitiesKey] = firefox.Capabilities{ Profile: prof.(string), } } } return Capabilities{ "alwaysMatch": alwaysMatch, } }
[ "func", "newW3CCapabilities", "(", "caps", "Capabilities", ")", "Capabilities", "{", "alwaysMatch", ":=", "make", "(", "Capabilities", ")", "\n", "for", "name", ",", "value", ":=", "range", "caps", "{", "if", "isValidW3CCapability", "[", "name", "]", "||", "...
// Create a W3C-compatible capabilities instance.
[ "Create", "a", "W3C", "-", "compatible", "capabilities", "instance", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/remote.go#L350-L376
train
tebeka/selenium
remote.go
rect
func (elem *remoteWE) rect() (*rect, error) { wd := elem.parent url := wd.requestURL("/session/%s/element/%s/rect", wd.id, elem.id) response, err := wd.execute("GET", url, nil) if err != nil { return nil, err } r := new(struct{ Value rect }) if err := json.Unmarshal(response, r); err != nil { return nil, err } return &r.Value, nil }
go
func (elem *remoteWE) rect() (*rect, error) { wd := elem.parent url := wd.requestURL("/session/%s/element/%s/rect", wd.id, elem.id) response, err := wd.execute("GET", url, nil) if err != nil { return nil, err } r := new(struct{ Value rect }) if err := json.Unmarshal(response, r); err != nil { return nil, err } return &r.Value, nil }
[ "func", "(", "elem", "*", "remoteWE", ")", "rect", "(", ")", "(", "*", "rect", ",", "error", ")", "{", "wd", ":=", "elem", ".", "parent", "\n", "url", ":=", "wd", ".", "requestURL", "(", "\"", "\"", ",", "wd", ".", "id", ",", "elem", ".", "id...
// rect implements the "Get Element Rect" method of the W3C standard.
[ "rect", "implements", "the", "Get", "Element", "Rect", "method", "of", "the", "W3C", "standard", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/remote.go#L1416-L1428
train
tebeka/selenium
internal/zip/zip.go
New
func New(basePath string) (*bytes.Buffer, error) { fi, err := os.Stat(basePath) if err != nil { return nil, err } if !fi.IsDir() { return nil, fmt.Errorf("path %q is not a directory, which is required for a Firefox profile", basePath) } buf := new(bytes.Buffer) w := zip.NewWriter(buf) err = filepath.Walk(basePath, func(filePath string, info os.FileInfo, err error) error { if err != nil { return err } if !info.Mode().IsRegular() { return nil } zipFI, err := zip.FileInfoHeader(info) if err != nil { return err } // Strip the prefix from the filename (and the trailing directory // separator) so that the files are at the root of the zip file. zipFI.Name = filePath[len(basePath)+1:] // Without this, the Java zip reader throws a java.util.zip.ZipException: // "only DEFLATED entries can have EXT descriptor". zipFI.Method = zip.Deflate w, err := w.CreateHeader(zipFI) if err != nil { return err } f, err := os.Open(filePath) if err != nil { return err } defer f.Close() _, err = io.Copy(w, bufio.NewReader(f)) return err }) if err != nil { return nil, err } if err := w.Close(); err != nil { return nil, err } return buf, nil }
go
func New(basePath string) (*bytes.Buffer, error) { fi, err := os.Stat(basePath) if err != nil { return nil, err } if !fi.IsDir() { return nil, fmt.Errorf("path %q is not a directory, which is required for a Firefox profile", basePath) } buf := new(bytes.Buffer) w := zip.NewWriter(buf) err = filepath.Walk(basePath, func(filePath string, info os.FileInfo, err error) error { if err != nil { return err } if !info.Mode().IsRegular() { return nil } zipFI, err := zip.FileInfoHeader(info) if err != nil { return err } // Strip the prefix from the filename (and the trailing directory // separator) so that the files are at the root of the zip file. zipFI.Name = filePath[len(basePath)+1:] // Without this, the Java zip reader throws a java.util.zip.ZipException: // "only DEFLATED entries can have EXT descriptor". zipFI.Method = zip.Deflate w, err := w.CreateHeader(zipFI) if err != nil { return err } f, err := os.Open(filePath) if err != nil { return err } defer f.Close() _, err = io.Copy(w, bufio.NewReader(f)) return err }) if err != nil { return nil, err } if err := w.Close(); err != nil { return nil, err } return buf, nil }
[ "func", "New", "(", "basePath", "string", ")", "(", "*", "bytes", ".", "Buffer", ",", "error", ")", "{", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "basePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}...
// New returns a buffer that contains the payload of a Zip file.
[ "New", "returns", "a", "buffer", "that", "contains", "the", "payload", "of", "a", "Zip", "file", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/internal/zip/zip.go#L15-L68
train
cheggaaa/pb
pool.go
NewPool
func NewPool(pbs ...*ProgressBar) (pool *Pool) { pool = new(Pool) pool.Add(pbs...) return }
go
func NewPool(pbs ...*ProgressBar) (pool *Pool) { pool = new(Pool) pool.Add(pbs...) return }
[ "func", "NewPool", "(", "pbs", "...", "*", "ProgressBar", ")", "(", "pool", "*", "Pool", ")", "{", "pool", "=", "new", "(", "Pool", ")", "\n", "pool", ".", "Add", "(", "pbs", "...", ")", "\n", "return", "\n", "}" ]
// NewPool initialises a pool with progress bars, but // doesn't start it. You need to call Start manually
[ "NewPool", "initialises", "a", "pool", "with", "progress", "bars", "but", "doesn", "t", "start", "it", ".", "You", "need", "to", "call", "Start", "manually" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pool.go#L24-L28
train
cheggaaa/pb
pool.go
Add
func (p *Pool) Add(pbs ...*ProgressBar) { p.m.Lock() defer p.m.Unlock() for _, bar := range pbs { bar.ManualUpdate = true bar.NotPrint = true bar.Start() p.bars = append(p.bars, bar) } }
go
func (p *Pool) Add(pbs ...*ProgressBar) { p.m.Lock() defer p.m.Unlock() for _, bar := range pbs { bar.ManualUpdate = true bar.NotPrint = true bar.Start() p.bars = append(p.bars, bar) } }
[ "func", "(", "p", "*", "Pool", ")", "Add", "(", "pbs", "...", "*", "ProgressBar", ")", "{", "p", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "m", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "bar", ":=", "range", "pbs", "{"...
// Add progress bars.
[ "Add", "progress", "bars", "." ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pool.go#L42-L51
train
cheggaaa/pb
pool.go
Stop
func (p *Pool) Stop() error { p.finishOnce.Do(func() { if p.shutdownCh != nil { close(p.shutdownCh) } }) // Wait for the worker to complete select { case <-p.workerCh: } return unlockEcho() }
go
func (p *Pool) Stop() error { p.finishOnce.Do(func() { if p.shutdownCh != nil { close(p.shutdownCh) } }) // Wait for the worker to complete select { case <-p.workerCh: } return unlockEcho() }
[ "func", "(", "p", "*", "Pool", ")", "Stop", "(", ")", "error", "{", "p", ".", "finishOnce", ".", "Do", "(", "func", "(", ")", "{", "if", "p", ".", "shutdownCh", "!=", "nil", "{", "close", "(", "p", ".", "shutdownCh", ")", "\n", "}", "\n", "}"...
// Restore terminal state and close pool
[ "Restore", "terminal", "state", "and", "close", "pool" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pool.go#L91-L104
train
cheggaaa/pb
format.go
formatBytes
func formatBytes(i int64) (result string) { switch { case i >= TiB: result = fmt.Sprintf("%.02f TiB", float64(i)/TiB) case i >= GiB: result = fmt.Sprintf("%.02f GiB", float64(i)/GiB) case i >= MiB: result = fmt.Sprintf("%.02f MiB", float64(i)/MiB) case i >= KiB: result = fmt.Sprintf("%.02f KiB", float64(i)/KiB) default: result = fmt.Sprintf("%d B", i) } return }
go
func formatBytes(i int64) (result string) { switch { case i >= TiB: result = fmt.Sprintf("%.02f TiB", float64(i)/TiB) case i >= GiB: result = fmt.Sprintf("%.02f GiB", float64(i)/GiB) case i >= MiB: result = fmt.Sprintf("%.02f MiB", float64(i)/MiB) case i >= KiB: result = fmt.Sprintf("%.02f KiB", float64(i)/KiB) default: result = fmt.Sprintf("%d B", i) } return }
[ "func", "formatBytes", "(", "i", "int64", ")", "(", "result", "string", ")", "{", "switch", "{", "case", "i", ">=", "TiB", ":", "result", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "float64", "(", "i", ")", "/", "TiB", ")", "\n", "case", ...
// Convert bytes to human readable string. Like 2 MiB, 64.2 KiB, 52 B
[ "Convert", "bytes", "to", "human", "readable", "string", ".", "Like", "2", "MiB", "64", ".", "2", "KiB", "52", "B" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/format.go#L77-L91
train
cheggaaa/pb
format.go
formatBytesDec
func formatBytesDec(i int64) (result string) { switch { case i >= TB: result = fmt.Sprintf("%.02f TB", float64(i)/TB) case i >= GB: result = fmt.Sprintf("%.02f GB", float64(i)/GB) case i >= MB: result = fmt.Sprintf("%.02f MB", float64(i)/MB) case i >= KB: result = fmt.Sprintf("%.02f KB", float64(i)/KB) default: result = fmt.Sprintf("%d B", i) } return }
go
func formatBytesDec(i int64) (result string) { switch { case i >= TB: result = fmt.Sprintf("%.02f TB", float64(i)/TB) case i >= GB: result = fmt.Sprintf("%.02f GB", float64(i)/GB) case i >= MB: result = fmt.Sprintf("%.02f MB", float64(i)/MB) case i >= KB: result = fmt.Sprintf("%.02f KB", float64(i)/KB) default: result = fmt.Sprintf("%d B", i) } return }
[ "func", "formatBytesDec", "(", "i", "int64", ")", "(", "result", "string", ")", "{", "switch", "{", "case", "i", ">=", "TB", ":", "result", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "float64", "(", "i", ")", "/", "TB", ")", "\n", "case", ...
// Convert bytes to base-10 human readable string. Like 2 MB, 64.2 KB, 52 B
[ "Convert", "bytes", "to", "base", "-", "10", "human", "readable", "string", ".", "Like", "2", "MB", "64", ".", "2", "KB", "52", "B" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/format.go#L94-L108
train
cheggaaa/pb
pb.go
Get
func (pb *ProgressBar) Get() int64 { c := atomic.LoadInt64(&pb.current) return c }
go
func (pb *ProgressBar) Get() int64 { c := atomic.LoadInt64(&pb.current) return c }
[ "func", "(", "pb", "*", "ProgressBar", ")", "Get", "(", ")", "int64", "{", "c", ":=", "atomic", ".", "LoadInt64", "(", "&", "pb", ".", "current", ")", "\n", "return", "c", "\n", "}" ]
// Get current value
[ "Get", "current", "value" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L135-L138
train
cheggaaa/pb
pb.go
Set
func (pb *ProgressBar) Set(current int) *ProgressBar { return pb.Set64(int64(current)) }
go
func (pb *ProgressBar) Set(current int) *ProgressBar { return pb.Set64(int64(current)) }
[ "func", "(", "pb", "*", "ProgressBar", ")", "Set", "(", "current", "int", ")", "*", "ProgressBar", "{", "return", "pb", ".", "Set64", "(", "int64", "(", "current", ")", ")", "\n", "}" ]
// Set current value
[ "Set", "current", "value" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L141-L143
train
cheggaaa/pb
pb.go
Add
func (pb *ProgressBar) Add(add int) int { return int(pb.Add64(int64(add))) }
go
func (pb *ProgressBar) Add(add int) int { return int(pb.Add64(int64(add))) }
[ "func", "(", "pb", "*", "ProgressBar", ")", "Add", "(", "add", "int", ")", "int", "{", "return", "int", "(", "pb", ".", "Add64", "(", "int64", "(", "add", ")", ")", ")", "\n", "}" ]
// Add to current value
[ "Add", "to", "current", "value" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L152-L154
train
cheggaaa/pb
pb.go
IsFinished
func (pb *ProgressBar) IsFinished() bool { pb.mu.Lock() defer pb.mu.Unlock() return pb.isFinish }
go
func (pb *ProgressBar) IsFinished() bool { pb.mu.Lock() defer pb.mu.Unlock() return pb.isFinish }
[ "func", "(", "pb", "*", "ProgressBar", ")", "IsFinished", "(", ")", "bool", "{", "pb", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "pb", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "pb", ".", "isFinish", "\n", "}" ]
// IsFinished return boolean
[ "IsFinished", "return", "boolean" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L243-L247
train
cheggaaa/pb
pb.go
FinishPrint
func (pb *ProgressBar) FinishPrint(str string) { pb.Finish() if pb.Output != nil { fmt.Fprintln(pb.Output, str) } else { fmt.Println(str) } }
go
func (pb *ProgressBar) FinishPrint(str string) { pb.Finish() if pb.Output != nil { fmt.Fprintln(pb.Output, str) } else { fmt.Println(str) } }
[ "func", "(", "pb", "*", "ProgressBar", ")", "FinishPrint", "(", "str", "string", ")", "{", "pb", ".", "Finish", "(", ")", "\n", "if", "pb", ".", "Output", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "pb", ".", "Output", ",", "str", ")", "\n", ...
// End print and write string 'str'
[ "End", "print", "and", "write", "string", "str" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L250-L257
train
cheggaaa/pb
pb.go
Write
func (pb *ProgressBar) Write(p []byte) (n int, err error) { n = len(p) pb.Add(n) return }
go
func (pb *ProgressBar) Write(p []byte) (n int, err error) { n = len(p) pb.Add(n) return }
[ "func", "(", "pb", "*", "ProgressBar", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "n", "=", "len", "(", "p", ")", "\n", "pb", ".", "Add", "(", "n", ")", "\n", "return", "\n", "}" ]
// implement io.Writer
[ "implement", "io", ".", "Writer" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L260-L264
train
cheggaaa/pb
pb.go
NewProxyReader
func (pb *ProgressBar) NewProxyReader(r io.Reader) *Reader { return &Reader{r, pb} }
go
func (pb *ProgressBar) NewProxyReader(r io.Reader) *Reader { return &Reader{r, pb} }
[ "func", "(", "pb", "*", "ProgressBar", ")", "NewProxyReader", "(", "r", "io", ".", "Reader", ")", "*", "Reader", "{", "return", "&", "Reader", "{", "r", ",", "pb", "}", "\n", "}" ]
// Create new proxy reader over bar // Takes io.Reader or io.ReadCloser
[ "Create", "new", "proxy", "reader", "over", "bar", "Takes", "io", ".", "Reader", "or", "io", ".", "ReadCloser" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L275-L277
train
cheggaaa/pb
pb.go
String
func (pb *ProgressBar) String() string { pb.mu.Lock() defer pb.mu.Unlock() return pb.lastPrint }
go
func (pb *ProgressBar) String() string { pb.mu.Lock() defer pb.mu.Unlock() return pb.lastPrint }
[ "func", "(", "pb", "*", "ProgressBar", ")", "String", "(", ")", "string", "{", "pb", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "pb", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "pb", ".", "lastPrint", "\n", "}" ]
// String return the last bar print
[ "String", "return", "the", "last", "bar", "print" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L461-L465
train
cheggaaa/pb
pb.go
SetTotal
func (pb *ProgressBar) SetTotal(total int) *ProgressBar { return pb.SetTotal64(int64(total)) }
go
func (pb *ProgressBar) SetTotal(total int) *ProgressBar { return pb.SetTotal64(int64(total)) }
[ "func", "(", "pb", "*", "ProgressBar", ")", "SetTotal", "(", "total", "int", ")", "*", "ProgressBar", "{", "return", "pb", ".", "SetTotal64", "(", "int64", "(", "total", ")", ")", "\n", "}" ]
// SetTotal atomically sets new total count
[ "SetTotal", "atomically", "sets", "new", "total", "count" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L468-L470
train
cheggaaa/pb
pb.go
SetTotal64
func (pb *ProgressBar) SetTotal64(total int64) *ProgressBar { atomic.StoreInt64(&pb.Total, total) return pb }
go
func (pb *ProgressBar) SetTotal64(total int64) *ProgressBar { atomic.StoreInt64(&pb.Total, total) return pb }
[ "func", "(", "pb", "*", "ProgressBar", ")", "SetTotal64", "(", "total", "int64", ")", "*", "ProgressBar", "{", "atomic", ".", "StoreInt64", "(", "&", "pb", ".", "Total", ",", "total", ")", "\n", "return", "pb", "\n", "}" ]
// SetTotal64 atomically sets new total count
[ "SetTotal64", "atomically", "sets", "new", "total", "count" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L473-L476
train
cheggaaa/pb
pb.go
Reset
func (pb *ProgressBar) Reset(total int) *ProgressBar { pb.mu.Lock() defer pb.mu.Unlock() if pb.isFinish { pb.SetTotal(total).Set(0) atomic.StoreInt64(&pb.previous, 0) } return pb }
go
func (pb *ProgressBar) Reset(total int) *ProgressBar { pb.mu.Lock() defer pb.mu.Unlock() if pb.isFinish { pb.SetTotal(total).Set(0) atomic.StoreInt64(&pb.previous, 0) } return pb }
[ "func", "(", "pb", "*", "ProgressBar", ")", "Reset", "(", "total", "int", ")", "*", "ProgressBar", "{", "pb", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "pb", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "pb", ".", "isFinish", "{", "pb...
// Reset bar and set new total count // Does effect only on finished bar
[ "Reset", "bar", "and", "set", "new", "total", "count", "Does", "effect", "only", "on", "finished", "bar" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L480-L488
train
cheggaaa/pb
pb.go
refresher
func (pb *ProgressBar) refresher() { for { select { case <-pb.finish: return case <-time.After(pb.RefreshRate): pb.Update() } } }
go
func (pb *ProgressBar) refresher() { for { select { case <-pb.finish: return case <-time.After(pb.RefreshRate): pb.Update() } } }
[ "func", "(", "pb", "*", "ProgressBar", ")", "refresher", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "pb", ".", "finish", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "pb", ".", "RefreshRate", ")", ":", "pb", ".", "Up...
// Internal loop for refreshing the progressbar
[ "Internal", "loop", "for", "refreshing", "the", "progressbar" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L491-L500
train
cheggaaa/pb
pb_x.go
catchTerminate
func catchTerminate(shutdownCh chan struct{}) { sig := make(chan os.Signal, 1) signal.Notify(sig, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGKILL) defer signal.Stop(sig) select { case <-shutdownCh: unlockEcho() case <-sig: unlockEcho() } }
go
func catchTerminate(shutdownCh chan struct{}) { sig := make(chan os.Signal, 1) signal.Notify(sig, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGKILL) defer signal.Stop(sig) select { case <-shutdownCh: unlockEcho() case <-sig: unlockEcho() } }
[ "func", "catchTerminate", "(", "shutdownCh", "chan", "struct", "{", "}", ")", "{", "sig", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "sig", ",", "os", ".", "Interrupt", ",", "syscall", ".", "S...
// listen exit signals and restore terminal state
[ "listen", "exit", "signals", "and", "restore", "terminal", "state" ]
f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11
https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb_x.go#L108-L118
train
coocood/freecache
iterator.go
Next
func (it *Iterator) Next() *Entry { for it.segmentIdx < 256 { entry := it.nextForSegment(it.segmentIdx) if entry != nil { return entry } it.segmentIdx++ it.slotIdx = 0 it.entryIdx = 0 } return nil }
go
func (it *Iterator) Next() *Entry { for it.segmentIdx < 256 { entry := it.nextForSegment(it.segmentIdx) if entry != nil { return entry } it.segmentIdx++ it.slotIdx = 0 it.entryIdx = 0 } return nil }
[ "func", "(", "it", "*", "Iterator", ")", "Next", "(", ")", "*", "Entry", "{", "for", "it", ".", "segmentIdx", "<", "256", "{", "entry", ":=", "it", ".", "nextForSegment", "(", "it", ".", "segmentIdx", ")", "\n", "if", "entry", "!=", "nil", "{", "...
// Next returns the next entry for the iterator. // The order of the entries is not guaranteed. // If there is no more entries to return, nil will be returned.
[ "Next", "returns", "the", "next", "entry", "for", "the", "iterator", ".", "The", "order", "of", "the", "entries", "is", "not", "guaranteed", ".", "If", "there", "is", "no", "more", "entries", "to", "return", "nil", "will", "be", "returned", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/iterator.go#L25-L36
train
coocood/freecache
cache.go
Get
func (cache *Cache) Get(key []byte) (value []byte, err error) { hashVal := hashFunc(key) segID := hashVal & segmentAndOpVal cache.locks[segID].Lock() value, _, err = cache.segments[segID].get(key, nil, hashVal) cache.locks[segID].Unlock() return }
go
func (cache *Cache) Get(key []byte) (value []byte, err error) { hashVal := hashFunc(key) segID := hashVal & segmentAndOpVal cache.locks[segID].Lock() value, _, err = cache.segments[segID].get(key, nil, hashVal) cache.locks[segID].Unlock() return }
[ "func", "(", "cache", "*", "Cache", ")", "Get", "(", "key", "[", "]", "byte", ")", "(", "value", "[", "]", "byte", ",", "err", "error", ")", "{", "hashVal", ":=", "hashFunc", "(", "key", ")", "\n", "segID", ":=", "hashVal", "&", "segmentAndOpVal", ...
// Get returns the value or not found error.
[ "Get", "returns", "the", "value", "or", "not", "found", "error", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L59-L66
train
coocood/freecache
cache.go
GetWithExpiration
func (cache *Cache) GetWithExpiration(key []byte) (value []byte, expireAt uint32, err error) { hashVal := hashFunc(key) segID := hashVal & segmentAndOpVal cache.locks[segID].Lock() value, expireAt, err = cache.segments[segID].get(key, nil, hashVal) cache.locks[segID].Unlock() return }
go
func (cache *Cache) GetWithExpiration(key []byte) (value []byte, expireAt uint32, err error) { hashVal := hashFunc(key) segID := hashVal & segmentAndOpVal cache.locks[segID].Lock() value, expireAt, err = cache.segments[segID].get(key, nil, hashVal) cache.locks[segID].Unlock() return }
[ "func", "(", "cache", "*", "Cache", ")", "GetWithExpiration", "(", "key", "[", "]", "byte", ")", "(", "value", "[", "]", "byte", ",", "expireAt", "uint32", ",", "err", "error", ")", "{", "hashVal", ":=", "hashFunc", "(", "key", ")", "\n", "segID", ...
// GetWithExpiration returns the value with expiration or not found error.
[ "GetWithExpiration", "returns", "the", "value", "with", "expiration", "or", "not", "found", "error", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L80-L87
train
coocood/freecache
cache.go
TTL
func (cache *Cache) TTL(key []byte) (timeLeft uint32, err error) { hashVal := hashFunc(key) segID := hashVal & segmentAndOpVal cache.locks[segID].Lock() timeLeft, err = cache.segments[segID].ttl(key, hashVal) cache.locks[segID].Unlock() return }
go
func (cache *Cache) TTL(key []byte) (timeLeft uint32, err error) { hashVal := hashFunc(key) segID := hashVal & segmentAndOpVal cache.locks[segID].Lock() timeLeft, err = cache.segments[segID].ttl(key, hashVal) cache.locks[segID].Unlock() return }
[ "func", "(", "cache", "*", "Cache", ")", "TTL", "(", "key", "[", "]", "byte", ")", "(", "timeLeft", "uint32", ",", "err", "error", ")", "{", "hashVal", ":=", "hashFunc", "(", "key", ")", "\n", "segID", ":=", "hashVal", "&", "segmentAndOpVal", "\n", ...
// TTL returns the TTL time left for a given key or a not found error.
[ "TTL", "returns", "the", "TTL", "time", "left", "for", "a", "given", "key", "or", "a", "not", "found", "error", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L90-L97
train
coocood/freecache
cache.go
Del
func (cache *Cache) Del(key []byte) (affected bool) { hashVal := hashFunc(key) segID := hashVal & segmentAndOpVal cache.locks[segID].Lock() affected = cache.segments[segID].del(key, hashVal) cache.locks[segID].Unlock() return }
go
func (cache *Cache) Del(key []byte) (affected bool) { hashVal := hashFunc(key) segID := hashVal & segmentAndOpVal cache.locks[segID].Lock() affected = cache.segments[segID].del(key, hashVal) cache.locks[segID].Unlock() return }
[ "func", "(", "cache", "*", "Cache", ")", "Del", "(", "key", "[", "]", "byte", ")", "(", "affected", "bool", ")", "{", "hashVal", ":=", "hashFunc", "(", "key", ")", "\n", "segID", ":=", "hashVal", "&", "segmentAndOpVal", "\n", "cache", ".", "locks", ...
// Del deletes an item in the cache by key and returns true or false if a delete occurred.
[ "Del", "deletes", "an", "item", "in", "the", "cache", "by", "key", "and", "returns", "true", "or", "false", "if", "a", "delete", "occurred", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L100-L107
train
coocood/freecache
cache.go
SetInt
func (cache *Cache) SetInt(key int64, value []byte, expireSeconds int) (err error) { var bKey [8]byte binary.LittleEndian.PutUint64(bKey[:], uint64(key)) return cache.Set(bKey[:], value, expireSeconds) }
go
func (cache *Cache) SetInt(key int64, value []byte, expireSeconds int) (err error) { var bKey [8]byte binary.LittleEndian.PutUint64(bKey[:], uint64(key)) return cache.Set(bKey[:], value, expireSeconds) }
[ "func", "(", "cache", "*", "Cache", ")", "SetInt", "(", "key", "int64", ",", "value", "[", "]", "byte", ",", "expireSeconds", "int", ")", "(", "err", "error", ")", "{", "var", "bKey", "[", "8", "]", "byte", "\n", "binary", ".", "LittleEndian", ".",...
// SetInt stores in integer value in the cache.
[ "SetInt", "stores", "in", "integer", "value", "in", "the", "cache", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L110-L114
train
coocood/freecache
cache.go
GetInt
func (cache *Cache) GetInt(key int64) (value []byte, err error) { var bKey [8]byte binary.LittleEndian.PutUint64(bKey[:], uint64(key)) return cache.Get(bKey[:]) }
go
func (cache *Cache) GetInt(key int64) (value []byte, err error) { var bKey [8]byte binary.LittleEndian.PutUint64(bKey[:], uint64(key)) return cache.Get(bKey[:]) }
[ "func", "(", "cache", "*", "Cache", ")", "GetInt", "(", "key", "int64", ")", "(", "value", "[", "]", "byte", ",", "err", "error", ")", "{", "var", "bKey", "[", "8", "]", "byte", "\n", "binary", ".", "LittleEndian", ".", "PutUint64", "(", "bKey", ...
// GetInt returns the value for an integer within the cache or a not found error.
[ "GetInt", "returns", "the", "value", "for", "an", "integer", "within", "the", "cache", "or", "a", "not", "found", "error", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L117-L121
train
coocood/freecache
cache.go
GetIntWithExpiration
func (cache *Cache) GetIntWithExpiration(key int64) (value []byte, expireAt uint32, err error) { var bKey [8]byte binary.LittleEndian.PutUint64(bKey[:], uint64(key)) return cache.GetWithExpiration(bKey[:]) }
go
func (cache *Cache) GetIntWithExpiration(key int64) (value []byte, expireAt uint32, err error) { var bKey [8]byte binary.LittleEndian.PutUint64(bKey[:], uint64(key)) return cache.GetWithExpiration(bKey[:]) }
[ "func", "(", "cache", "*", "Cache", ")", "GetIntWithExpiration", "(", "key", "int64", ")", "(", "value", "[", "]", "byte", ",", "expireAt", "uint32", ",", "err", "error", ")", "{", "var", "bKey", "[", "8", "]", "byte", "\n", "binary", ".", "LittleEnd...
// GetIntWithExpiration returns the value and expiration or a not found error.
[ "GetIntWithExpiration", "returns", "the", "value", "and", "expiration", "or", "a", "not", "found", "error", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L124-L128
train
coocood/freecache
cache.go
DelInt
func (cache *Cache) DelInt(key int64) (affected bool) { var bKey [8]byte binary.LittleEndian.PutUint64(bKey[:], uint64(key)) return cache.Del(bKey[:]) }
go
func (cache *Cache) DelInt(key int64) (affected bool) { var bKey [8]byte binary.LittleEndian.PutUint64(bKey[:], uint64(key)) return cache.Del(bKey[:]) }
[ "func", "(", "cache", "*", "Cache", ")", "DelInt", "(", "key", "int64", ")", "(", "affected", "bool", ")", "{", "var", "bKey", "[", "8", "]", "byte", "\n", "binary", ".", "LittleEndian", ".", "PutUint64", "(", "bKey", "[", ":", "]", ",", "uint64", ...
// DelInt deletes an item in the cache by int key and returns true or false if a delete occurred.
[ "DelInt", "deletes", "an", "item", "in", "the", "cache", "by", "int", "key", "and", "returns", "true", "or", "false", "if", "a", "delete", "occurred", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L131-L135
train
coocood/freecache
cache.go
EvacuateCount
func (cache *Cache) EvacuateCount() (count int64) { for i := range cache.segments { count += atomic.LoadInt64(&cache.segments[i].totalEvacuate) } return }
go
func (cache *Cache) EvacuateCount() (count int64) { for i := range cache.segments { count += atomic.LoadInt64(&cache.segments[i].totalEvacuate) } return }
[ "func", "(", "cache", "*", "Cache", ")", "EvacuateCount", "(", ")", "(", "count", "int64", ")", "{", "for", "i", ":=", "range", "cache", ".", "segments", "{", "count", "+=", "atomic", ".", "LoadInt64", "(", "&", "cache", ".", "segments", "[", "i", ...
// EvacuateCount is a metric indicating the number of times an eviction occurred.
[ "EvacuateCount", "is", "a", "metric", "indicating", "the", "number", "of", "times", "an", "eviction", "occurred", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L138-L143
train
coocood/freecache
cache.go
ExpiredCount
func (cache *Cache) ExpiredCount() (count int64) { for i := range cache.segments { count += atomic.LoadInt64(&cache.segments[i].totalExpired) } return }
go
func (cache *Cache) ExpiredCount() (count int64) { for i := range cache.segments { count += atomic.LoadInt64(&cache.segments[i].totalExpired) } return }
[ "func", "(", "cache", "*", "Cache", ")", "ExpiredCount", "(", ")", "(", "count", "int64", ")", "{", "for", "i", ":=", "range", "cache", ".", "segments", "{", "count", "+=", "atomic", ".", "LoadInt64", "(", "&", "cache", ".", "segments", "[", "i", "...
// ExpiredCount is a metric indicating the number of times an expire occurred.
[ "ExpiredCount", "is", "a", "metric", "indicating", "the", "number", "of", "times", "an", "expire", "occurred", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L146-L151
train
coocood/freecache
cache.go
EntryCount
func (cache *Cache) EntryCount() (entryCount int64) { for i := range cache.segments { entryCount += atomic.LoadInt64(&cache.segments[i].entryCount) } return }
go
func (cache *Cache) EntryCount() (entryCount int64) { for i := range cache.segments { entryCount += atomic.LoadInt64(&cache.segments[i].entryCount) } return }
[ "func", "(", "cache", "*", "Cache", ")", "EntryCount", "(", ")", "(", "entryCount", "int64", ")", "{", "for", "i", ":=", "range", "cache", ".", "segments", "{", "entryCount", "+=", "atomic", ".", "LoadInt64", "(", "&", "cache", ".", "segments", "[", ...
// EntryCount returns the number of items currently in the cache.
[ "EntryCount", "returns", "the", "number", "of", "items", "currently", "in", "the", "cache", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L154-L159
train
coocood/freecache
cache.go
AverageAccessTime
func (cache *Cache) AverageAccessTime() int64 { var entryCount, totalTime int64 for i := range cache.segments { totalTime += atomic.LoadInt64(&cache.segments[i].totalTime) entryCount += atomic.LoadInt64(&cache.segments[i].totalCount) } if entryCount == 0 { return 0 } else { return totalTime / entryCount } }
go
func (cache *Cache) AverageAccessTime() int64 { var entryCount, totalTime int64 for i := range cache.segments { totalTime += atomic.LoadInt64(&cache.segments[i].totalTime) entryCount += atomic.LoadInt64(&cache.segments[i].totalCount) } if entryCount == 0 { return 0 } else { return totalTime / entryCount } }
[ "func", "(", "cache", "*", "Cache", ")", "AverageAccessTime", "(", ")", "int64", "{", "var", "entryCount", ",", "totalTime", "int64", "\n", "for", "i", ":=", "range", "cache", ".", "segments", "{", "totalTime", "+=", "atomic", ".", "LoadInt64", "(", "&",...
// AverageAccessTime returns the average unix timestamp when a entry being accessed. // Entries have greater access time will be evacuated when it // is about to be overwritten by new value.
[ "AverageAccessTime", "returns", "the", "average", "unix", "timestamp", "when", "a", "entry", "being", "accessed", ".", "Entries", "have", "greater", "access", "time", "will", "be", "evacuated", "when", "it", "is", "about", "to", "be", "overwritten", "by", "new...
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L164-L175
train
coocood/freecache
cache.go
HitCount
func (cache *Cache) HitCount() (count int64) { for i := range cache.segments { count += atomic.LoadInt64(&cache.segments[i].hitCount) } return }
go
func (cache *Cache) HitCount() (count int64) { for i := range cache.segments { count += atomic.LoadInt64(&cache.segments[i].hitCount) } return }
[ "func", "(", "cache", "*", "Cache", ")", "HitCount", "(", ")", "(", "count", "int64", ")", "{", "for", "i", ":=", "range", "cache", ".", "segments", "{", "count", "+=", "atomic", ".", "LoadInt64", "(", "&", "cache", ".", "segments", "[", "i", "]", ...
// HitCount is a metric that returns number of times a key was found in the cache.
[ "HitCount", "is", "a", "metric", "that", "returns", "number", "of", "times", "a", "key", "was", "found", "in", "the", "cache", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L178-L183
train
coocood/freecache
cache.go
MissCount
func (cache *Cache) MissCount() (count int64) { for i := range cache.segments { count += atomic.LoadInt64(&cache.segments[i].missCount) } return }
go
func (cache *Cache) MissCount() (count int64) { for i := range cache.segments { count += atomic.LoadInt64(&cache.segments[i].missCount) } return }
[ "func", "(", "cache", "*", "Cache", ")", "MissCount", "(", ")", "(", "count", "int64", ")", "{", "for", "i", ":=", "range", "cache", ".", "segments", "{", "count", "+=", "atomic", ".", "LoadInt64", "(", "&", "cache", ".", "segments", "[", "i", "]",...
// MissCount is a metric that returns the number of times a miss occurred in the cache.
[ "MissCount", "is", "a", "metric", "that", "returns", "the", "number", "of", "times", "a", "miss", "occurred", "in", "the", "cache", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L186-L191
train
coocood/freecache
cache.go
HitRate
func (cache *Cache) HitRate() float64 { hitCount, missCount := cache.HitCount(), cache.MissCount() lookupCount := hitCount + missCount if lookupCount == 0 { return 0 } else { return float64(hitCount) / float64(lookupCount) } }
go
func (cache *Cache) HitRate() float64 { hitCount, missCount := cache.HitCount(), cache.MissCount() lookupCount := hitCount + missCount if lookupCount == 0 { return 0 } else { return float64(hitCount) / float64(lookupCount) } }
[ "func", "(", "cache", "*", "Cache", ")", "HitRate", "(", ")", "float64", "{", "hitCount", ",", "missCount", ":=", "cache", ".", "HitCount", "(", ")", ",", "cache", ".", "MissCount", "(", ")", "\n", "lookupCount", ":=", "hitCount", "+", "missCount", "\n...
// HitRate is the ratio of hits over lookups.
[ "HitRate", "is", "the", "ratio", "of", "hits", "over", "lookups", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L199-L207
train
coocood/freecache
cache.go
OverwriteCount
func (cache *Cache) OverwriteCount() (overwriteCount int64) { for i := range cache.segments { overwriteCount += atomic.LoadInt64(&cache.segments[i].overwrites) } return }
go
func (cache *Cache) OverwriteCount() (overwriteCount int64) { for i := range cache.segments { overwriteCount += atomic.LoadInt64(&cache.segments[i].overwrites) } return }
[ "func", "(", "cache", "*", "Cache", ")", "OverwriteCount", "(", ")", "(", "overwriteCount", "int64", ")", "{", "for", "i", ":=", "range", "cache", ".", "segments", "{", "overwriteCount", "+=", "atomic", ".", "LoadInt64", "(", "&", "cache", ".", "segments...
// OverwriteCount indicates the number of times entries have been overriden.
[ "OverwriteCount", "indicates", "the", "number", "of", "times", "entries", "have", "been", "overriden", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L210-L215
train
coocood/freecache
cache.go
ResetStatistics
func (cache *Cache) ResetStatistics() { for i := range cache.segments { cache.locks[i].Lock() cache.segments[i].resetStatistics() cache.locks[i].Unlock() } }
go
func (cache *Cache) ResetStatistics() { for i := range cache.segments { cache.locks[i].Lock() cache.segments[i].resetStatistics() cache.locks[i].Unlock() } }
[ "func", "(", "cache", "*", "Cache", ")", "ResetStatistics", "(", ")", "{", "for", "i", ":=", "range", "cache", ".", "segments", "{", "cache", ".", "locks", "[", "i", "]", ".", "Lock", "(", ")", "\n", "cache", ".", "segments", "[", "i", "]", ".", ...
// ResetStatistics refreshes the current state of the statistics.
[ "ResetStatistics", "refreshes", "the", "current", "state", "of", "the", "statistics", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/cache.go#L227-L233
train
coocood/freecache
ringbuf.go
Dump
func (rb *RingBuf) Dump() []byte { dump := make([]byte, len(rb.data)) copy(dump, rb.data) return dump }
go
func (rb *RingBuf) Dump() []byte { dump := make([]byte, len(rb.data)) copy(dump, rb.data) return dump }
[ "func", "(", "rb", "*", "RingBuf", ")", "Dump", "(", ")", "[", "]", "byte", "{", "dump", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "rb", ".", "data", ")", ")", "\n", "copy", "(", "dump", ",", "rb", ".", "data", ")", "\n", "retur...
// Create a copy of the buffer.
[ "Create", "a", "copy", "of", "the", "buffer", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/ringbuf.go#L31-L35
train
coocood/freecache
ringbuf.go
Evacuate
func (rb *RingBuf) Evacuate(off int64, length int) (newOff int64) { if off+int64(length) > rb.end || off < rb.begin { return -1 } var readOff int if rb.end-rb.begin < int64(len(rb.data)) { readOff = int(off - rb.begin) } else { readOff = rb.index + int(off-rb.begin) } if readOff >= len(rb.data) { readOff -= len(rb.data) } if readOff == rb.index { // no copy evacuate rb.index += length if rb.index >= len(rb.data) { rb.index -= len(rb.data) } } else if readOff < rb.index { var n = copy(rb.data[rb.index:], rb.data[readOff:readOff+length]) rb.index += n if rb.index == len(rb.data) { rb.index = copy(rb.data, rb.data[readOff+n:readOff+length]) } } else { var readEnd = readOff + length var n int if readEnd <= len(rb.data) { n = copy(rb.data[rb.index:], rb.data[readOff:readEnd]) rb.index += n } else { n = copy(rb.data[rb.index:], rb.data[readOff:]) rb.index += n var tail = length - n n = copy(rb.data[rb.index:], rb.data[:tail]) rb.index += n if rb.index == len(rb.data) { rb.index = copy(rb.data, rb.data[n:tail]) } } } newOff = rb.end rb.end += int64(length) if rb.begin < rb.end-int64(len(rb.data)) { rb.begin = rb.end - int64(len(rb.data)) } return }
go
func (rb *RingBuf) Evacuate(off int64, length int) (newOff int64) { if off+int64(length) > rb.end || off < rb.begin { return -1 } var readOff int if rb.end-rb.begin < int64(len(rb.data)) { readOff = int(off - rb.begin) } else { readOff = rb.index + int(off-rb.begin) } if readOff >= len(rb.data) { readOff -= len(rb.data) } if readOff == rb.index { // no copy evacuate rb.index += length if rb.index >= len(rb.data) { rb.index -= len(rb.data) } } else if readOff < rb.index { var n = copy(rb.data[rb.index:], rb.data[readOff:readOff+length]) rb.index += n if rb.index == len(rb.data) { rb.index = copy(rb.data, rb.data[readOff+n:readOff+length]) } } else { var readEnd = readOff + length var n int if readEnd <= len(rb.data) { n = copy(rb.data[rb.index:], rb.data[readOff:readEnd]) rb.index += n } else { n = copy(rb.data[rb.index:], rb.data[readOff:]) rb.index += n var tail = length - n n = copy(rb.data[rb.index:], rb.data[:tail]) rb.index += n if rb.index == len(rb.data) { rb.index = copy(rb.data, rb.data[n:tail]) } } } newOff = rb.end rb.end += int64(length) if rb.begin < rb.end-int64(len(rb.data)) { rb.begin = rb.end - int64(len(rb.data)) } return }
[ "func", "(", "rb", "*", "RingBuf", ")", "Evacuate", "(", "off", "int64", ",", "length", "int", ")", "(", "newOff", "int64", ")", "{", "if", "off", "+", "int64", "(", "length", ")", ">", "rb", ".", "end", "||", "off", "<", "rb", ".", "begin", "{...
// Evacuate read the data at off, then write it to the the data stream, // Keep it from being overwritten by new data.
[ "Evacuate", "read", "the", "data", "at", "off", "then", "write", "it", "to", "the", "the", "data", "stream", "Keep", "it", "from", "being", "overwritten", "by", "new", "data", "." ]
142b9e1225b0ecdbe420d8fe6cef33f268670c42
https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/ringbuf.go#L158-L207
train
huandu/facebook
paging_result.go
Previous
func (pr *PagingResult) Previous() (noMore bool, err error) { if !pr.HasPrevious() { noMore = true return } return pr.navigate(&pr.previous) }
go
func (pr *PagingResult) Previous() (noMore bool, err error) { if !pr.HasPrevious() { noMore = true return } return pr.navigate(&pr.previous) }
[ "func", "(", "pr", "*", "PagingResult", ")", "Previous", "(", ")", "(", "noMore", "bool", ",", "err", "error", ")", "{", "if", "!", "pr", ".", "HasPrevious", "(", ")", "{", "noMore", "=", "true", "\n", "return", "\n", "}", "\n\n", "return", "pr", ...
// Previous reads previous page.
[ "Previous", "reads", "previous", "page", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/paging_result.go#L64-L71
train
huandu/facebook
paging_result.go
Next
func (pr *PagingResult) Next() (noMore bool, err error) { if !pr.HasNext() { noMore = true return } return pr.navigate(&pr.next) }
go
func (pr *PagingResult) Next() (noMore bool, err error) { if !pr.HasNext() { noMore = true return } return pr.navigate(&pr.next) }
[ "func", "(", "pr", "*", "PagingResult", ")", "Next", "(", ")", "(", "noMore", "bool", ",", "err", "error", ")", "{", "if", "!", "pr", ".", "HasNext", "(", ")", "{", "noMore", "=", "true", "\n", "return", "\n", "}", "\n\n", "return", "pr", ".", ...
// Next reads next page.
[ "Next", "reads", "next", "page", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/paging_result.go#L74-L81
train
huandu/facebook
filedata.go
Data
func Data(filename string, source io.Reader) *BinaryData { return &BinaryData{ Filename: filename, Source: source, } }
go
func Data(filename string, source io.Reader) *BinaryData { return &BinaryData{ Filename: filename, Source: source, } }
[ "func", "Data", "(", "filename", "string", ",", "source", "io", ".", "Reader", ")", "*", "BinaryData", "{", "return", "&", "BinaryData", "{", "Filename", ":", "filename", ",", "Source", ":", "source", ",", "}", "\n", "}" ]
// Data creates new binary data holder.
[ "Data", "creates", "new", "binary", "data", "holder", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/filedata.go#L29-L34
train
huandu/facebook
filedata.go
DataWithContentType
func DataWithContentType(filename string, source io.Reader, contentType string) *BinaryData { return &BinaryData{ Filename: filename, Source: source, ContentType: contentType, } }
go
func DataWithContentType(filename string, source io.Reader, contentType string) *BinaryData { return &BinaryData{ Filename: filename, Source: source, ContentType: contentType, } }
[ "func", "DataWithContentType", "(", "filename", "string", ",", "source", "io", ".", "Reader", ",", "contentType", "string", ")", "*", "BinaryData", "{", "return", "&", "BinaryData", "{", "Filename", ":", "filename", ",", "Source", ":", "source", ",", "Conten...
// DataWithContentType creates new binary data holder with arbitrary content type.
[ "DataWithContentType", "creates", "new", "binary", "data", "holder", "with", "arbitrary", "content", "type", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/filedata.go#L37-L43
train
huandu/facebook
filedata.go
FileAlias
func FileAlias(filename, path string) *BinaryFile { return &BinaryFile{ Filename: filename, Path: path, } }
go
func FileAlias(filename, path string) *BinaryFile { return &BinaryFile{ Filename: filename, Path: path, } }
[ "func", "FileAlias", "(", "filename", ",", "path", "string", ")", "*", "BinaryFile", "{", "return", "&", "BinaryFile", "{", "Filename", ":", "filename", ",", "Path", ":", "path", ",", "}", "\n", "}" ]
// FileAlias creates a binary file holder and specific a different path for reading.
[ "FileAlias", "creates", "a", "binary", "file", "holder", "and", "specific", "a", "different", "path", "for", "reading", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/filedata.go#L53-L58
train
huandu/facebook
filedata.go
FileAliasWithContentType
func FileAliasWithContentType(filename, path, contentType string) *BinaryFile { if path == "" { path = filename } return &BinaryFile{ Filename: filename, Path: path, ContentType: contentType, } }
go
func FileAliasWithContentType(filename, path, contentType string) *BinaryFile { if path == "" { path = filename } return &BinaryFile{ Filename: filename, Path: path, ContentType: contentType, } }
[ "func", "FileAliasWithContentType", "(", "filename", ",", "path", ",", "contentType", "string", ")", "*", "BinaryFile", "{", "if", "path", "==", "\"", "\"", "{", "path", "=", "filename", "\n", "}", "\n\n", "return", "&", "BinaryFile", "{", "Filename", ":",...
// FileAliasWithContentType creates a new binary file holder with arbitrary content type.
[ "FileAliasWithContentType", "creates", "a", "new", "binary", "file", "holder", "with", "arbitrary", "content", "type", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/filedata.go#L61-L71
train
huandu/facebook
app.go
New
func New(appID, appSecret string) *App { return &App{ AppId: appID, AppSecret: appSecret, } }
go
func New(appID, appSecret string) *App { return &App{ AppId: appID, AppSecret: appSecret, } }
[ "func", "New", "(", "appID", ",", "appSecret", "string", ")", "*", "App", "{", "return", "&", "App", "{", "AppId", ":", "appID", ",", "AppSecret", ":", "appSecret", ",", "}", "\n", "}" ]
// New creates a new App and sets app id and secret.
[ "New", "creates", "a", "new", "App", "and", "sets", "app", "id", "and", "secret", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/app.go#L36-L41
train
huandu/facebook
app.go
ParseSignedRequest
func (app *App) ParseSignedRequest(signedRequest string) (res Result, err error) { strs := strings.SplitN(signedRequest, ".", 2) if len(strs) != 2 { err = fmt.Errorf("invalid signed request format") return } sig, e1 := base64.RawURLEncoding.DecodeString(strs[0]) if e1 != nil { err = fmt.Errorf("fail to decode signed request sig with error %v", e1) return } payload, e2 := base64.RawURLEncoding.DecodeString(strs[1]) if e2 != nil { err = fmt.Errorf("fail to decode signed request payload with error is %v", e2) return } err = json.Unmarshal(payload, &res) if err != nil { err = fmt.Errorf("signed request payload is not a valid json string with error %v", err) return } var hashMethod string err = res.DecodeField("algorithm", &hashMethod) if err != nil { err = fmt.Errorf("signed request payload doesn't contains a valid 'algorithm' field") return } hashMethod = strings.ToUpper(hashMethod) if hashMethod != "HMAC-SHA256" { err = fmt.Errorf("signed request payload uses an unknown HMAC method; expect 'HMAC-SHA256' but actual is '%v'", hashMethod) return } hash := hmac.New(sha256.New, []byte(app.AppSecret)) hash.Write([]byte(strs[1])) // note: here uses the payload base64 string, not decoded bytes expectedSig := hash.Sum(nil) if !hmac.Equal(sig, expectedSig) { err = fmt.Errorf("bad signed request signiture") return } return }
go
func (app *App) ParseSignedRequest(signedRequest string) (res Result, err error) { strs := strings.SplitN(signedRequest, ".", 2) if len(strs) != 2 { err = fmt.Errorf("invalid signed request format") return } sig, e1 := base64.RawURLEncoding.DecodeString(strs[0]) if e1 != nil { err = fmt.Errorf("fail to decode signed request sig with error %v", e1) return } payload, e2 := base64.RawURLEncoding.DecodeString(strs[1]) if e2 != nil { err = fmt.Errorf("fail to decode signed request payload with error is %v", e2) return } err = json.Unmarshal(payload, &res) if err != nil { err = fmt.Errorf("signed request payload is not a valid json string with error %v", err) return } var hashMethod string err = res.DecodeField("algorithm", &hashMethod) if err != nil { err = fmt.Errorf("signed request payload doesn't contains a valid 'algorithm' field") return } hashMethod = strings.ToUpper(hashMethod) if hashMethod != "HMAC-SHA256" { err = fmt.Errorf("signed request payload uses an unknown HMAC method; expect 'HMAC-SHA256' but actual is '%v'", hashMethod) return } hash := hmac.New(sha256.New, []byte(app.AppSecret)) hash.Write([]byte(strs[1])) // note: here uses the payload base64 string, not decoded bytes expectedSig := hash.Sum(nil) if !hmac.Equal(sig, expectedSig) { err = fmt.Errorf("bad signed request signiture") return } return }
[ "func", "(", "app", "*", "App", ")", "ParseSignedRequest", "(", "signedRequest", "string", ")", "(", "res", "Result", ",", "err", "error", ")", "{", "strs", ":=", "strings", ".", "SplitN", "(", "signedRequest", ",", "\"", "\"", ",", "2", ")", "\n\n", ...
// ParseSignedRequest parses signed request.
[ "ParseSignedRequest", "parses", "signed", "request", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/app.go#L49-L103
train
huandu/facebook
app.go
ExchangeToken
func (app *App) ExchangeToken(accessToken string) (token string, expires int, err error) { if accessToken == "" { err = fmt.Errorf("short lived accessToken is empty") return } var res Result res, err = defaultSession.sendOauthRequest("/oauth/access_token", Params{ "grant_type": "fb_exchange_token", "client_id": app.AppId, "client_secret": app.AppSecret, "fb_exchange_token": accessToken, }) if err != nil { err = fmt.Errorf("fail to parse facebook response with error %v", err) return } err = res.DecodeField("access_token", &token) if err != nil { return } expiresKey := "expires_in" if _, ok := res["expires"]; ok { expiresKey = "expires" } if _, ok := res[expiresKey]; ok { err = res.DecodeField(expiresKey, &expires) } return }
go
func (app *App) ExchangeToken(accessToken string) (token string, expires int, err error) { if accessToken == "" { err = fmt.Errorf("short lived accessToken is empty") return } var res Result res, err = defaultSession.sendOauthRequest("/oauth/access_token", Params{ "grant_type": "fb_exchange_token", "client_id": app.AppId, "client_secret": app.AppSecret, "fb_exchange_token": accessToken, }) if err != nil { err = fmt.Errorf("fail to parse facebook response with error %v", err) return } err = res.DecodeField("access_token", &token) if err != nil { return } expiresKey := "expires_in" if _, ok := res["expires"]; ok { expiresKey = "expires" } if _, ok := res[expiresKey]; ok { err = res.DecodeField(expiresKey, &expires) } return }
[ "func", "(", "app", "*", "App", ")", "ExchangeToken", "(", "accessToken", "string", ")", "(", "token", "string", ",", "expires", "int", ",", "err", "error", ")", "{", "if", "accessToken", "==", "\"", "\"", "{", "err", "=", "fmt", ".", "Errorf", "(", ...
// ExchangeToken exchanges a short-lived access token to a long-lived access token. // Return new access token and its expires time.
[ "ExchangeToken", "exchanges", "a", "short", "-", "lived", "access", "token", "to", "a", "long", "-", "lived", "access", "token", ".", "Return", "new", "access", "token", "and", "its", "expires", "time", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/app.go#L168-L204
train
huandu/facebook
app.go
GetCode
func (app *App) GetCode(accessToken string) (code string, err error) { if accessToken == "" { err = fmt.Errorf("long lived accessToken is empty") return } var res Result res, err = defaultSession.sendOauthRequest("/oauth/client_code", Params{ "client_id": app.AppId, "client_secret": app.AppSecret, "redirect_uri": app.RedirectUri, "access_token": accessToken, }) if err != nil { err = fmt.Errorf("fail to get code from facebook with error %v", err) return } err = res.DecodeField("code", &code) return }
go
func (app *App) GetCode(accessToken string) (code string, err error) { if accessToken == "" { err = fmt.Errorf("long lived accessToken is empty") return } var res Result res, err = defaultSession.sendOauthRequest("/oauth/client_code", Params{ "client_id": app.AppId, "client_secret": app.AppSecret, "redirect_uri": app.RedirectUri, "access_token": accessToken, }) if err != nil { err = fmt.Errorf("fail to get code from facebook with error %v", err) return } err = res.DecodeField("code", &code) return }
[ "func", "(", "app", "*", "App", ")", "GetCode", "(", "accessToken", "string", ")", "(", "code", "string", ",", "err", "error", ")", "{", "if", "accessToken", "==", "\"", "\"", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "re...
// GetCode gets code from a long lived access token. // Return the code retrieved from facebook.
[ "GetCode", "gets", "code", "from", "a", "long", "lived", "access", "token", ".", "Return", "the", "code", "retrieved", "from", "facebook", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/app.go#L208-L229
train
huandu/facebook
app.go
Session
func (app *App) Session(accessToken string) *Session { return &Session{ accessToken: accessToken, app: app, enableAppsecretProof: app.EnableAppsecretProof, } }
go
func (app *App) Session(accessToken string) *Session { return &Session{ accessToken: accessToken, app: app, enableAppsecretProof: app.EnableAppsecretProof, } }
[ "func", "(", "app", "*", "App", ")", "Session", "(", "accessToken", "string", ")", "*", "Session", "{", "return", "&", "Session", "{", "accessToken", ":", "accessToken", ",", "app", ":", "app", ",", "enableAppsecretProof", ":", "app", ".", "EnableAppsecret...
// Session creates a session based on current App setting.
[ "Session", "creates", "a", "session", "based", "on", "current", "App", "setting", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/app.go#L232-L238
train
huandu/facebook
app.go
SessionFromSignedRequest
func (app *App) SessionFromSignedRequest(signedRequest string) (session *Session, err error) { var res Result res, err = app.ParseSignedRequest(signedRequest) if err != nil { return } var id, token string res.DecodeField("user_id", &id) // it's ok without user id. err = res.DecodeField("oauth_token", &token) if err == nil { session = &Session{ accessToken: token, app: app, id: id, enableAppsecretProof: app.EnableAppsecretProof, } return } // cannot get "oauth_token"? try to get "code". err = res.DecodeField("code", &token) if err != nil { // no code? no way to continue. err = fmt.Errorf("cannot find 'oauth_token' and 'code'; unable to continue") return } token, err = app.ParseCode(token) if err != nil { return } session = &Session{ accessToken: token, app: app, id: id, enableAppsecretProof: app.EnableAppsecretProof, } return }
go
func (app *App) SessionFromSignedRequest(signedRequest string) (session *Session, err error) { var res Result res, err = app.ParseSignedRequest(signedRequest) if err != nil { return } var id, token string res.DecodeField("user_id", &id) // it's ok without user id. err = res.DecodeField("oauth_token", &token) if err == nil { session = &Session{ accessToken: token, app: app, id: id, enableAppsecretProof: app.EnableAppsecretProof, } return } // cannot get "oauth_token"? try to get "code". err = res.DecodeField("code", &token) if err != nil { // no code? no way to continue. err = fmt.Errorf("cannot find 'oauth_token' and 'code'; unable to continue") return } token, err = app.ParseCode(token) if err != nil { return } session = &Session{ accessToken: token, app: app, id: id, enableAppsecretProof: app.EnableAppsecretProof, } return }
[ "func", "(", "app", "*", "App", ")", "SessionFromSignedRequest", "(", "signedRequest", "string", ")", "(", "session", "*", "Session", ",", "err", "error", ")", "{", "var", "res", "Result", "\n\n", "res", ",", "err", "=", "app", ".", "ParseSignedRequest", ...
// SessionFromSignedRequest creates a session from a signed request. // If signed request contains a code, it will automatically use this code // to exchange a valid access token.
[ "SessionFromSignedRequest", "creates", "a", "session", "from", "a", "signed", "request", ".", "If", "signed", "request", "contains", "a", "code", "it", "will", "automatically", "use", "this", "code", "to", "exchange", "a", "valid", "access", "token", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/app.go#L243-L289
train
huandu/facebook
session.go
Api
func (session *Session) Api(path string, method Method, params Params) (Result, error) { return session.graph(path, method, params) }
go
func (session *Session) Api(path string, method Method, params Params) (Result, error) { return session.graph(path, method, params) }
[ "func", "(", "session", "*", "Session", ")", "Api", "(", "path", "string", ",", "method", "Method", ",", "params", "Params", ")", "(", "Result", ",", "error", ")", "{", "return", "session", ".", "graph", "(", "path", ",", "method", ",", "params", ")"...
// Api makes a facebook graph api call. // // If session access token is set, "access_token" in params will be set to the token value. // // Returns facebook graph api call result. // If facebook returns error in response, returns error details in res and set err.
[ "Api", "makes", "a", "facebook", "graph", "api", "call", ".", "If", "session", "access", "token", "is", "set", "access_token", "in", "params", "will", "be", "set", "to", "the", "token", "value", ".", "Returns", "facebook", "graph", "api", "call", "result",...
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/session.go#L84-L86
train
huandu/facebook
session.go
User
func (session *Session) User() (id string, err error) { if session.id != "" { id = session.id return } if session.accessToken == "" && session.HttpClient == nil { err = fmt.Errorf("access token is not set") return } var result Result result, err = session.Api("/me", GET, Params{"fields": "id"}) if err != nil { return } err = result.DecodeField("id", &id) if err != nil { return } return }
go
func (session *Session) User() (id string, err error) { if session.id != "" { id = session.id return } if session.accessToken == "" && session.HttpClient == nil { err = fmt.Errorf("access token is not set") return } var result Result result, err = session.Api("/me", GET, Params{"fields": "id"}) if err != nil { return } err = result.DecodeField("id", &id) if err != nil { return } return }
[ "func", "(", "session", "*", "Session", ")", "User", "(", ")", "(", "id", "string", ",", "err", "error", ")", "{", "if", "session", ".", "id", "!=", "\"", "\"", "{", "id", "=", "session", ".", "id", "\n", "return", "\n", "}", "\n\n", "if", "ses...
// User gets current user id from access token. // // Returns error if access token is not set or invalid. // // It's a standard way to validate a facebook access token.
[ "User", "gets", "current", "user", "id", "from", "access", "token", ".", "Returns", "error", "if", "access", "token", "is", "not", "set", "or", "invalid", ".", "It", "s", "a", "standard", "way", "to", "validate", "a", "facebook", "access", "token", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/session.go#L163-L188
train
huandu/facebook
session.go
Validate
func (session *Session) Validate() (err error) { if session.accessToken == "" && session.HttpClient == nil { err = fmt.Errorf("access token is not set") return } var result Result result, err = session.Api("/me", GET, Params{"fields": "id"}) if err != nil { return } if f := result.Get("id"); f == nil { err = fmt.Errorf("invalid access token") return } return }
go
func (session *Session) Validate() (err error) { if session.accessToken == "" && session.HttpClient == nil { err = fmt.Errorf("access token is not set") return } var result Result result, err = session.Api("/me", GET, Params{"fields": "id"}) if err != nil { return } if f := result.Get("id"); f == nil { err = fmt.Errorf("invalid access token") return } return }
[ "func", "(", "session", "*", "Session", ")", "Validate", "(", ")", "(", "err", "error", ")", "{", "if", "session", ".", "accessToken", "==", "\"", "\"", "&&", "session", ".", "HttpClient", "==", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\...
// Validate validates Session access token. // Returns nil if access token is valid.
[ "Validate", "validates", "Session", "access", "token", ".", "Returns", "nil", "if", "access", "token", "is", "valid", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/session.go#L192-L211
train
huandu/facebook
session.go
SetAccessToken
func (session *Session) SetAccessToken(token string) { if token != session.accessToken { session.id = "" session.accessToken = token session.appsecretProof = "" } }
go
func (session *Session) SetAccessToken(token string) { if token != session.accessToken { session.id = "" session.accessToken = token session.appsecretProof = "" } }
[ "func", "(", "session", "*", "Session", ")", "SetAccessToken", "(", "token", "string", ")", "{", "if", "token", "!=", "session", ".", "accessToken", "{", "session", ".", "id", "=", "\"", "\"", "\n", "session", ".", "accessToken", "=", "token", "\n", "s...
// SetAccessToken sets a new access token.
[ "SetAccessToken", "sets", "a", "new", "access", "token", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/session.go#L263-L269
train
huandu/facebook
session.go
AppsecretProof
func (session *Session) AppsecretProof() string { if !session.enableAppsecretProof { return "" } if session.accessToken == "" || session.app == nil { return "" } if session.appsecretProof == "" { hash := hmac.New(sha256.New, []byte(session.app.AppSecret)) hash.Write([]byte(session.accessToken)) session.appsecretProof = hex.EncodeToString(hash.Sum(nil)) } return session.appsecretProof }
go
func (session *Session) AppsecretProof() string { if !session.enableAppsecretProof { return "" } if session.accessToken == "" || session.app == nil { return "" } if session.appsecretProof == "" { hash := hmac.New(sha256.New, []byte(session.app.AppSecret)) hash.Write([]byte(session.accessToken)) session.appsecretProof = hex.EncodeToString(hash.Sum(nil)) } return session.appsecretProof }
[ "func", "(", "session", "*", "Session", ")", "AppsecretProof", "(", ")", "string", "{", "if", "!", "session", ".", "enableAppsecretProof", "{", "return", "\"", "\"", "\n", "}", "\n\n", "if", "session", ".", "accessToken", "==", "\"", "\"", "||", "session...
// AppsecretProof checks appsecret proof is enabled or not.
[ "AppsecretProof", "checks", "appsecret", "proof", "is", "enabled", "or", "not", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/session.go#L272-L288
train
huandu/facebook
session.go
EnableAppsecretProof
func (session *Session) EnableAppsecretProof(enabled bool) error { if session.app == nil { return fmt.Errorf("cannot change appsecret proof status without an associated App") } if session.enableAppsecretProof != enabled { session.enableAppsecretProof = enabled // reset pre-calculated proof here to give caller a way to do so in some rare case, // e.g. associated app's secret is changed. session.appsecretProof = "" } return nil }
go
func (session *Session) EnableAppsecretProof(enabled bool) error { if session.app == nil { return fmt.Errorf("cannot change appsecret proof status without an associated App") } if session.enableAppsecretProof != enabled { session.enableAppsecretProof = enabled // reset pre-calculated proof here to give caller a way to do so in some rare case, // e.g. associated app's secret is changed. session.appsecretProof = "" } return nil }
[ "func", "(", "session", "*", "Session", ")", "EnableAppsecretProof", "(", "enabled", "bool", ")", "error", "{", "if", "session", ".", "app", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "session", "...
// EnableAppsecretProof enables or disable appsecret proof status. // Returns error if there is no App associated with this Session.
[ "EnableAppsecretProof", "enables", "or", "disable", "appsecret", "proof", "status", ".", "Returns", "error", "if", "there", "is", "no", "App", "associated", "with", "this", "Session", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/session.go#L292-L306
train
huandu/facebook
session.go
Debug
func (session *Session) Debug() DebugMode { if session.debug != DEBUG_OFF { return session.debug } return Debug }
go
func (session *Session) Debug() DebugMode { if session.debug != DEBUG_OFF { return session.debug } return Debug }
[ "func", "(", "session", "*", "Session", ")", "Debug", "(", ")", "DebugMode", "{", "if", "session", ".", "debug", "!=", "DEBUG_OFF", "{", "return", "session", ".", "debug", "\n", "}", "\n\n", "return", "Debug", "\n", "}" ]
// Debug returns current debug mode.
[ "Debug", "returns", "current", "debug", "mode", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/session.go#L314-L320
train
huandu/facebook
session.go
SetDebug
func (session *Session) SetDebug(debug DebugMode) DebugMode { old := session.debug session.debug = debug return old }
go
func (session *Session) SetDebug(debug DebugMode) DebugMode { old := session.debug session.debug = debug return old }
[ "func", "(", "session", "*", "Session", ")", "SetDebug", "(", "debug", "DebugMode", ")", "DebugMode", "{", "old", ":=", "session", ".", "debug", "\n", "session", ".", "debug", "=", "debug", "\n", "return", "old", "\n", "}" ]
// SetDebug updates per session debug mode and returns old mode. // If per session debug mode is DEBUG_OFF, session will use global // Debug mode.
[ "SetDebug", "updates", "per", "session", "debug", "mode", "and", "returns", "old", "mode", ".", "If", "per", "session", "debug", "mode", "is", "DEBUG_OFF", "session", "will", "use", "global", "Debug", "mode", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/session.go#L325-L329
train
huandu/facebook
session.go
WithContext
func (session *Session) WithContext(ctx context.Context) *Session { s := *session s.context = ctx return &s }
go
func (session *Session) WithContext(ctx context.Context) *Session { s := *session s.context = ctx return &s }
[ "func", "(", "session", "*", "Session", ")", "WithContext", "(", "ctx", "context", ".", "Context", ")", "*", "Session", "{", "s", ":=", "*", "session", "\n", "s", ".", "context", "=", "ctx", "\n", "return", "&", "s", "\n", "}" ]
// WithContext returns a shallow copy of session with its context changed to ctx. // The provided ctx must be non-nil.
[ "WithContext", "returns", "a", "shallow", "copy", "of", "session", "with", "its", "context", "changed", "to", "ctx", ".", "The", "provided", "ctx", "must", "be", "non", "-", "nil", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/session.go#L656-L660
train
huandu/facebook
result.go
MakeResult
func MakeResult(jsonBytes []byte) (Result, error) { res := Result{} err := makeResult(jsonBytes, &res) if err != nil { return nil, err } // facebook may return an error return res, res.Err() }
go
func MakeResult(jsonBytes []byte) (Result, error) { res := Result{} err := makeResult(jsonBytes, &res) if err != nil { return nil, err } // facebook may return an error return res, res.Err() }
[ "func", "MakeResult", "(", "jsonBytes", "[", "]", "byte", ")", "(", "Result", ",", "error", ")", "{", "res", ":=", "Result", "{", "}", "\n", "err", ":=", "makeResult", "(", "jsonBytes", ",", "&", "res", ")", "\n\n", "if", "err", "!=", "nil", "{", ...
// MakeResult makes a Result from facebook Graph API response.
[ "MakeResult", "makes", "a", "Result", "from", "facebook", "Graph", "API", "response", "." ]
2d3753b3eead5325f72a52b940da5d36ed611aa4
https://github.com/huandu/facebook/blob/2d3753b3eead5325f72a52b940da5d36ed611aa4/result.go#L129-L139
train
alecthomas/kingpin
app.go
New
func New(name, help string) *Application { a := &Application{ Name: name, Help: help, errorWriter: os.Stderr, // Left for backwards compatibility purposes. usageWriter: os.Stderr, usageTemplate: DefaultUsageTemplate, terminate: os.Exit, } a.flagGroup = newFlagGroup() a.argGroup = newArgGroup() a.cmdGroup = newCmdGroup(a) a.HelpFlag = a.Flag("help", "Show context-sensitive help (also try --help-long and --help-man).") a.HelpFlag.Bool() a.Flag("help-long", "Generate long help.").Hidden().PreAction(a.generateLongHelp).Bool() a.Flag("help-man", "Generate a man page.").Hidden().PreAction(a.generateManPage).Bool() a.Flag("completion-bash", "Output possible completions for the given args.").Hidden().BoolVar(&a.completion) a.Flag("completion-script-bash", "Generate completion script for bash.").Hidden().PreAction(a.generateBashCompletionScript).Bool() a.Flag("completion-script-zsh", "Generate completion script for ZSH.").Hidden().PreAction(a.generateZSHCompletionScript).Bool() return a }
go
func New(name, help string) *Application { a := &Application{ Name: name, Help: help, errorWriter: os.Stderr, // Left for backwards compatibility purposes. usageWriter: os.Stderr, usageTemplate: DefaultUsageTemplate, terminate: os.Exit, } a.flagGroup = newFlagGroup() a.argGroup = newArgGroup() a.cmdGroup = newCmdGroup(a) a.HelpFlag = a.Flag("help", "Show context-sensitive help (also try --help-long and --help-man).") a.HelpFlag.Bool() a.Flag("help-long", "Generate long help.").Hidden().PreAction(a.generateLongHelp).Bool() a.Flag("help-man", "Generate a man page.").Hidden().PreAction(a.generateManPage).Bool() a.Flag("completion-bash", "Output possible completions for the given args.").Hidden().BoolVar(&a.completion) a.Flag("completion-script-bash", "Generate completion script for bash.").Hidden().PreAction(a.generateBashCompletionScript).Bool() a.Flag("completion-script-zsh", "Generate completion script for ZSH.").Hidden().PreAction(a.generateZSHCompletionScript).Bool() return a }
[ "func", "New", "(", "name", ",", "help", "string", ")", "*", "Application", "{", "a", ":=", "&", "Application", "{", "Name", ":", "name", ",", "Help", ":", "help", ",", "errorWriter", ":", "os", ".", "Stderr", ",", "// Left for backwards compatibility purp...
// New creates a new Kingpin application instance.
[ "New", "creates", "a", "new", "Kingpin", "application", "instance", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L50-L71
train
alecthomas/kingpin
app.go
ErrorWriter
func (a *Application) ErrorWriter(w io.Writer) *Application { a.errorWriter = w return a }
go
func (a *Application) ErrorWriter(w io.Writer) *Application { a.errorWriter = w return a }
[ "func", "(", "a", "*", "Application", ")", "ErrorWriter", "(", "w", "io", ".", "Writer", ")", "*", "Application", "{", "a", ".", "errorWriter", "=", "w", "\n", "return", "a", "\n", "}" ]
// ErrorWriter sets the io.Writer to use for errors.
[ "ErrorWriter", "sets", "the", "io", ".", "Writer", "to", "use", "for", "errors", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L138-L141
train
alecthomas/kingpin
app.go
UsageWriter
func (a *Application) UsageWriter(w io.Writer) *Application { a.usageWriter = w return a }
go
func (a *Application) UsageWriter(w io.Writer) *Application { a.usageWriter = w return a }
[ "func", "(", "a", "*", "Application", ")", "UsageWriter", "(", "w", "io", ".", "Writer", ")", "*", "Application", "{", "a", ".", "usageWriter", "=", "w", "\n", "return", "a", "\n", "}" ]
// UsageWriter sets the io.Writer to use for errors.
[ "UsageWriter", "sets", "the", "io", ".", "Writer", "to", "use", "for", "errors", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L144-L147
train
alecthomas/kingpin
app.go
UsageTemplate
func (a *Application) UsageTemplate(template string) *Application { a.usageTemplate = template return a }
go
func (a *Application) UsageTemplate(template string) *Application { a.usageTemplate = template return a }
[ "func", "(", "a", "*", "Application", ")", "UsageTemplate", "(", "template", "string", ")", "*", "Application", "{", "a", ".", "usageTemplate", "=", "template", "\n", "return", "a", "\n", "}" ]
// UsageTemplate specifies the text template to use when displaying usage // information. The default is UsageTemplate.
[ "UsageTemplate", "specifies", "the", "text", "template", "to", "use", "when", "displaying", "usage", "information", ".", "The", "default", "is", "UsageTemplate", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L151-L154
train
alecthomas/kingpin
app.go
ParseContext
func (a *Application) ParseContext(args []string) (*ParseContext, error) { return a.parseContext(false, args) }
go
func (a *Application) ParseContext(args []string) (*ParseContext, error) { return a.parseContext(false, args) }
[ "func", "(", "a", "*", "Application", ")", "ParseContext", "(", "args", "[", "]", "string", ")", "(", "*", "ParseContext", ",", "error", ")", "{", "return", "a", ".", "parseContext", "(", "false", ",", "args", ")", "\n", "}" ]
// ParseContext parses the given command line and returns the fully populated // ParseContext.
[ "ParseContext", "parses", "the", "given", "command", "line", "and", "returns", "the", "fully", "populated", "ParseContext", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L164-L166
train
alecthomas/kingpin
app.go
Parse
func (a *Application) Parse(args []string) (command string, err error) { context, parseErr := a.ParseContext(args) selected := []string{} var setValuesErr error if context == nil { // Since we do not throw error immediately, there could be a case // where a context returns nil. Protect against that. return "", parseErr } if err = a.setDefaults(context); err != nil { return "", err } selected, setValuesErr = a.setValues(context) if err = a.applyPreActions(context, !a.completion); err != nil { return "", err } if a.completion { a.generateBashCompletion(context) a.terminate(0) } else { if parseErr != nil { return "", parseErr } a.maybeHelp(context) if !context.EOL() { return "", fmt.Errorf("unexpected argument '%s'", context.Peek()) } if setValuesErr != nil { return "", setValuesErr } command, err = a.execute(context, selected) if err == ErrCommandNotSpecified { a.writeUsage(context, nil) } } return command, err }
go
func (a *Application) Parse(args []string) (command string, err error) { context, parseErr := a.ParseContext(args) selected := []string{} var setValuesErr error if context == nil { // Since we do not throw error immediately, there could be a case // where a context returns nil. Protect against that. return "", parseErr } if err = a.setDefaults(context); err != nil { return "", err } selected, setValuesErr = a.setValues(context) if err = a.applyPreActions(context, !a.completion); err != nil { return "", err } if a.completion { a.generateBashCompletion(context) a.terminate(0) } else { if parseErr != nil { return "", parseErr } a.maybeHelp(context) if !context.EOL() { return "", fmt.Errorf("unexpected argument '%s'", context.Peek()) } if setValuesErr != nil { return "", setValuesErr } command, err = a.execute(context, selected) if err == ErrCommandNotSpecified { a.writeUsage(context, nil) } } return command, err }
[ "func", "(", "a", "*", "Application", ")", "Parse", "(", "args", "[", "]", "string", ")", "(", "command", "string", ",", "err", "error", ")", "{", "context", ",", "parseErr", ":=", "a", ".", "ParseContext", "(", "args", ")", "\n", "selected", ":=", ...
// Parse parses command-line arguments. It returns the selected command and an // error. The selected command will be a space separated subcommand, if // subcommands have been configured. // // This will populate all flag and argument values, call all callbacks, and so // on.
[ "Parse", "parses", "command", "-", "line", "arguments", ".", "It", "returns", "the", "selected", "command", "and", "an", "error", ".", "The", "selected", "command", "will", "be", "a", "space", "separated", "subcommand", "if", "subcommands", "have", "been", "...
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L183-L228
train
alecthomas/kingpin
app.go
Author
func (a *Application) Author(author string) *Application { a.author = author return a }
go
func (a *Application) Author(author string) *Application { a.author = author return a }
[ "func", "(", "a", "*", "Application", ")", "Author", "(", "author", "string", ")", "*", "Application", "{", "a", ".", "author", "=", "author", "\n", "return", "a", "\n", "}" ]
// Author sets the author output by some help templates.
[ "Author", "sets", "the", "author", "output", "by", "some", "help", "templates", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L267-L270
train
alecthomas/kingpin
app.go
PreAction
func (a *Application) PreAction(action Action) *Application { a.addPreAction(action) return a }
go
func (a *Application) PreAction(action Action) *Application { a.addPreAction(action) return a }
[ "func", "(", "a", "*", "Application", ")", "PreAction", "(", "action", "Action", ")", "*", "Application", "{", "a", ".", "addPreAction", "(", "action", ")", "\n", "return", "a", "\n", "}" ]
// Action called after parsing completes but before validation and execution.
[ "Action", "called", "after", "parsing", "completes", "but", "before", "validation", "and", "execution", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L283-L286
train
alecthomas/kingpin
app.go
Command
func (a *Application) Command(name, help string) *CmdClause { return a.addCommand(name, help) }
go
func (a *Application) Command(name, help string) *CmdClause { return a.addCommand(name, help) }
[ "func", "(", "a", "*", "Application", ")", "Command", "(", "name", ",", "help", "string", ")", "*", "CmdClause", "{", "return", "a", ".", "addCommand", "(", "name", ",", "help", ")", "\n", "}" ]
// Command adds a new top-level command.
[ "Command", "adds", "a", "new", "top", "-", "level", "command", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L289-L291
train
alecthomas/kingpin
app.go
checkDuplicateFlags
func checkDuplicateFlags(current *CmdClause, flagGroups []*flagGroup) error { // Check for duplicates. for _, flags := range flagGroups { for _, flag := range current.flagOrder { if flag.shorthand != 0 { if _, ok := flags.short[string(flag.shorthand)]; ok { return fmt.Errorf("duplicate short flag -%c", flag.shorthand) } } if _, ok := flags.long[flag.name]; ok { return fmt.Errorf("duplicate long flag --%s", flag.name) } } } flagGroups = append(flagGroups, current.flagGroup) // Check subcommands. for _, subcmd := range current.commandOrder { if err := checkDuplicateFlags(subcmd, flagGroups); err != nil { return err } } return nil }
go
func checkDuplicateFlags(current *CmdClause, flagGroups []*flagGroup) error { // Check for duplicates. for _, flags := range flagGroups { for _, flag := range current.flagOrder { if flag.shorthand != 0 { if _, ok := flags.short[string(flag.shorthand)]; ok { return fmt.Errorf("duplicate short flag -%c", flag.shorthand) } } if _, ok := flags.long[flag.name]; ok { return fmt.Errorf("duplicate long flag --%s", flag.name) } } } flagGroups = append(flagGroups, current.flagGroup) // Check subcommands. for _, subcmd := range current.commandOrder { if err := checkDuplicateFlags(subcmd, flagGroups); err != nil { return err } } return nil }
[ "func", "checkDuplicateFlags", "(", "current", "*", "CmdClause", ",", "flagGroups", "[", "]", "*", "flagGroup", ")", "error", "{", "// Check for duplicates.", "for", "_", ",", "flags", ":=", "range", "flagGroups", "{", "for", "_", ",", "flag", ":=", "range",...
// Recursively check commands for duplicate flags.
[ "Recursively", "check", "commands", "for", "duplicate", "flags", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L355-L377
train
alecthomas/kingpin
app.go
Fatalf
func (a *Application) Fatalf(format string, args ...interface{}) { a.Errorf(format, args...) a.terminate(1) }
go
func (a *Application) Fatalf(format string, args ...interface{}) { a.Errorf(format, args...) a.terminate(1) }
[ "func", "(", "a", "*", "Application", ")", "Fatalf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "a", ".", "Errorf", "(", "format", ",", "args", "...", ")", "\n", "a", ".", "terminate", "(", "1", ")", "\n", "}" ]
// Fatalf writes a formatted error to w then terminates with exit status 1.
[ "Fatalf", "writes", "a", "formatted", "error", "to", "w", "then", "terminates", "with", "exit", "status", "1", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L571-L574
train
alecthomas/kingpin
app.go
FatalUsage
func (a *Application) FatalUsage(format string, args ...interface{}) { a.Errorf(format, args...) // Force usage to go to error output. a.usageWriter = a.errorWriter a.Usage([]string{}) a.terminate(1) }
go
func (a *Application) FatalUsage(format string, args ...interface{}) { a.Errorf(format, args...) // Force usage to go to error output. a.usageWriter = a.errorWriter a.Usage([]string{}) a.terminate(1) }
[ "func", "(", "a", "*", "Application", ")", "FatalUsage", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "a", ".", "Errorf", "(", "format", ",", "args", "...", ")", "\n", "// Force usage to go to error output.", "a", ".", "u...
// FatalUsage prints an error message followed by usage information, then // exits with a non-zero status.
[ "FatalUsage", "prints", "an", "error", "message", "followed", "by", "usage", "information", "then", "exits", "with", "a", "non", "-", "zero", "status", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L578-L584
train
alecthomas/kingpin
app.go
FatalUsageContext
func (a *Application) FatalUsageContext(context *ParseContext, format string, args ...interface{}) { a.Errorf(format, args...) if err := a.UsageForContext(context); err != nil { panic(err) } a.terminate(1) }
go
func (a *Application) FatalUsageContext(context *ParseContext, format string, args ...interface{}) { a.Errorf(format, args...) if err := a.UsageForContext(context); err != nil { panic(err) } a.terminate(1) }
[ "func", "(", "a", "*", "Application", ")", "FatalUsageContext", "(", "context", "*", "ParseContext", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "a", ".", "Errorf", "(", "format", ",", "args", "...", ")", "\n", "if", ...
// FatalUsageContext writes a printf formatted error message to w, then usage // information for the given ParseContext, before exiting.
[ "FatalUsageContext", "writes", "a", "printf", "formatted", "error", "message", "to", "w", "then", "usage", "information", "for", "the", "given", "ParseContext", "before", "exiting", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L588-L594
train
alecthomas/kingpin
app.go
FatalIfError
func (a *Application) FatalIfError(err error, format string, args ...interface{}) { if err != nil { prefix := "" if format != "" { prefix = fmt.Sprintf(format, args...) + ": " } a.Errorf(prefix+"%s", err) a.terminate(1) } }
go
func (a *Application) FatalIfError(err error, format string, args ...interface{}) { if err != nil { prefix := "" if format != "" { prefix = fmt.Sprintf(format, args...) + ": " } a.Errorf(prefix+"%s", err) a.terminate(1) } }
[ "func", "(", "a", "*", "Application", ")", "FatalIfError", "(", "err", "error", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "err", "!=", "nil", "{", "prefix", ":=", "\"", "\"", "\n", "if", "format", "!=", "\"...
// FatalIfError prints an error and exits if err is not nil. The error is printed // with the given formatted string, if any.
[ "FatalIfError", "prints", "an", "error", "and", "exits", "if", "err", "is", "not", "nil", ".", "The", "error", "is", "printed", "with", "the", "given", "formatted", "string", "if", "any", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/app.go#L598-L607
train
alecthomas/kingpin
flags.go
Flag
func (f *flagGroup) Flag(name, help string) *FlagClause { flag := newFlag(name, help) f.long[name] = flag f.flagOrder = append(f.flagOrder, flag) return flag }
go
func (f *flagGroup) Flag(name, help string) *FlagClause { flag := newFlag(name, help) f.long[name] = flag f.flagOrder = append(f.flagOrder, flag) return flag }
[ "func", "(", "f", "*", "flagGroup", ")", "Flag", "(", "name", ",", "help", "string", ")", "*", "FlagClause", "{", "flag", ":=", "newFlag", "(", "name", ",", "help", ")", "\n", "f", ".", "long", "[", "name", "]", "=", "flag", "\n", "f", ".", "fl...
// Flag defines a new flag with the given long name and help.
[ "Flag", "defines", "a", "new", "flag", "with", "the", "given", "long", "name", "and", "help", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/flags.go#L30-L35
train
alecthomas/kingpin
flags.go
Action
func (f *FlagClause) Action(action Action) *FlagClause { f.addAction(action) return f }
go
func (f *FlagClause) Action(action Action) *FlagClause { f.addAction(action) return f }
[ "func", "(", "f", "*", "FlagClause", ")", "Action", "(", "action", "Action", ")", "*", "FlagClause", "{", "f", ".", "addAction", "(", "action", ")", "\n", "return", "f", "\n", "}" ]
// Dispatch to the given function after the flag is parsed and validated.
[ "Dispatch", "to", "the", "given", "function", "after", "the", "flag", "is", "parsed", "and", "validated", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/flags.go#L220-L223
train
alecthomas/kingpin
flags.go
IsSetByUser
func (f *FlagClause) IsSetByUser(setByUser *bool) *FlagClause { if setByUser != nil { *setByUser = false } f.setByUser = setByUser return f }
go
func (f *FlagClause) IsSetByUser(setByUser *bool) *FlagClause { if setByUser != nil { *setByUser = false } f.setByUser = setByUser return f }
[ "func", "(", "f", "*", "FlagClause", ")", "IsSetByUser", "(", "setByUser", "*", "bool", ")", "*", "FlagClause", "{", "if", "setByUser", "!=", "nil", "{", "*", "setByUser", "=", "false", "\n", "}", "\n", "f", ".", "setByUser", "=", "setByUser", "\n", ...
// IsSetByUser let to know if the flag was set by the user
[ "IsSetByUser", "let", "to", "know", "if", "the", "flag", "was", "set", "by", "the", "user" ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/flags.go#L259-L265
train
alecthomas/kingpin
flags.go
Short
func (f *FlagClause) Short(name rune) *FlagClause { f.shorthand = name return f }
go
func (f *FlagClause) Short(name rune) *FlagClause { f.shorthand = name return f }
[ "func", "(", "f", "*", "FlagClause", ")", "Short", "(", "name", "rune", ")", "*", "FlagClause", "{", "f", ".", "shorthand", "=", "name", "\n", "return", "f", "\n", "}" ]
// Short sets the short flag name.
[ "Short", "sets", "the", "short", "flag", "name", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/flags.go#L316-L319
train
alecthomas/kingpin
flags.go
Bool
func (f *FlagClause) Bool() (target *bool) { target = new(bool) f.SetValue(newBoolValue(target)) return }
go
func (f *FlagClause) Bool() (target *bool) { target = new(bool) f.SetValue(newBoolValue(target)) return }
[ "func", "(", "f", "*", "FlagClause", ")", "Bool", "(", ")", "(", "target", "*", "bool", ")", "{", "target", "=", "new", "(", "bool", ")", "\n", "f", ".", "SetValue", "(", "newBoolValue", "(", "target", ")", ")", "\n", "return", "\n", "}" ]
// Bool makes this flag a boolean flag.
[ "Bool", "makes", "this", "flag", "a", "boolean", "flag", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/flags.go#L322-L326
train
alecthomas/kingpin
parsers.go
Bytes
func (p *parserMixin) Bytes() (target *units.Base2Bytes) { target = new(units.Base2Bytes) p.BytesVar(target) return }
go
func (p *parserMixin) Bytes() (target *units.Base2Bytes) { target = new(units.Base2Bytes) p.BytesVar(target) return }
[ "func", "(", "p", "*", "parserMixin", ")", "Bytes", "(", ")", "(", "target", "*", "units", ".", "Base2Bytes", ")", "{", "target", "=", "new", "(", "units", ".", "Base2Bytes", ")", "\n", "p", ".", "BytesVar", "(", "target", ")", "\n", "return", "\n"...
// Bytes parses numeric byte units. eg. 1.5KB
[ "Bytes", "parses", "numeric", "byte", "units", ".", "eg", ".", "1", ".", "5KB" ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/parsers.go#L40-L44
train
alecthomas/kingpin
parsers.go
ExistingFile
func (p *parserMixin) ExistingFile() (target *string) { target = new(string) p.ExistingFileVar(target) return }
go
func (p *parserMixin) ExistingFile() (target *string) { target = new(string) p.ExistingFileVar(target) return }
[ "func", "(", "p", "*", "parserMixin", ")", "ExistingFile", "(", ")", "(", "target", "*", "string", ")", "{", "target", "=", "new", "(", "string", ")", "\n", "p", ".", "ExistingFileVar", "(", "target", ")", "\n", "return", "\n", "}" ]
// ExistingFile sets the parser to one that requires and returns an existing file.
[ "ExistingFile", "sets", "the", "parser", "to", "one", "that", "requires", "and", "returns", "an", "existing", "file", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/parsers.go#L66-L70
train
alecthomas/kingpin
parsers.go
ExistingDir
func (p *parserMixin) ExistingDir() (target *string) { target = new(string) p.ExistingDirVar(target) return }
go
func (p *parserMixin) ExistingDir() (target *string) { target = new(string) p.ExistingDirVar(target) return }
[ "func", "(", "p", "*", "parserMixin", ")", "ExistingDir", "(", ")", "(", "target", "*", "string", ")", "{", "target", "=", "new", "(", "string", ")", "\n", "p", ".", "ExistingDirVar", "(", "target", ")", "\n", "return", "\n", "}" ]
// ExistingDir sets the parser to one that requires and returns an existing directory.
[ "ExistingDir", "sets", "the", "parser", "to", "one", "that", "requires", "and", "returns", "an", "existing", "directory", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/parsers.go#L73-L77
train
alecthomas/kingpin
parsers.go
ExistingFileOrDir
func (p *parserMixin) ExistingFileOrDir() (target *string) { target = new(string) p.ExistingFileOrDirVar(target) return }
go
func (p *parserMixin) ExistingFileOrDir() (target *string) { target = new(string) p.ExistingFileOrDirVar(target) return }
[ "func", "(", "p", "*", "parserMixin", ")", "ExistingFileOrDir", "(", ")", "(", "target", "*", "string", ")", "{", "target", "=", "new", "(", "string", ")", "\n", "p", ".", "ExistingFileOrDirVar", "(", "target", ")", "\n", "return", "\n", "}" ]
// ExistingFileOrDir sets the parser to one that requires and returns an existing file OR directory.
[ "ExistingFileOrDir", "sets", "the", "parser", "to", "one", "that", "requires", "and", "returns", "an", "existing", "file", "OR", "directory", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/parsers.go#L80-L84
train
alecthomas/kingpin
parsers.go
File
func (p *parserMixin) File() (target **os.File) { target = new(*os.File) p.FileVar(target) return }
go
func (p *parserMixin) File() (target **os.File) { target = new(*os.File) p.FileVar(target) return }
[ "func", "(", "p", "*", "parserMixin", ")", "File", "(", ")", "(", "target", "*", "*", "os", ".", "File", ")", "{", "target", "=", "new", "(", "*", "os", ".", "File", ")", "\n", "p", ".", "FileVar", "(", "target", ")", "\n", "return", "\n", "}...
// File returns an os.File against an existing file.
[ "File", "returns", "an", "os", ".", "File", "against", "an", "existing", "file", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/parsers.go#L87-L91
train
alecthomas/kingpin
parsers.go
BytesVar
func (p *parserMixin) BytesVar(target *units.Base2Bytes) { p.SetValue(newBytesValue(target)) }
go
func (p *parserMixin) BytesVar(target *units.Base2Bytes) { p.SetValue(newBytesValue(target)) }
[ "func", "(", "p", "*", "parserMixin", ")", "BytesVar", "(", "target", "*", "units", ".", "Base2Bytes", ")", "{", "p", ".", "SetValue", "(", "newBytesValue", "(", "target", ")", ")", "\n", "}" ]
// BytesVar parses numeric byte units. eg. 1.5KB
[ "BytesVar", "parses", "numeric", "byte", "units", ".", "eg", ".", "1", ".", "5KB" ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/parsers.go#L128-L130
train
alecthomas/kingpin
parsers.go
FileVar
func (p *parserMixin) FileVar(target **os.File) { p.SetValue(newFileValue(target, os.O_RDONLY, 0)) }
go
func (p *parserMixin) FileVar(target **os.File) { p.SetValue(newFileValue(target, os.O_RDONLY, 0)) }
[ "func", "(", "p", "*", "parserMixin", ")", "FileVar", "(", "target", "*", "*", "os", ".", "File", ")", "{", "p", ".", "SetValue", "(", "newFileValue", "(", "target", ",", "os", ".", "O_RDONLY", ",", "0", ")", ")", "\n", "}" ]
// FileVar opens an existing file.
[ "FileVar", "opens", "an", "existing", "file", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/parsers.go#L153-L155
train
alecthomas/kingpin
parsers.go
URLList
func (p *parserMixin) URLList() (target *[]*url.URL) { target = new([]*url.URL) p.URLListVar(target) return }
go
func (p *parserMixin) URLList() (target *[]*url.URL) { target = new([]*url.URL) p.URLListVar(target) return }
[ "func", "(", "p", "*", "parserMixin", ")", "URLList", "(", ")", "(", "target", "*", "[", "]", "*", "url", ".", "URL", ")", "{", "target", "=", "new", "(", "[", "]", "*", "url", ".", "URL", ")", "\n", "p", ".", "URLListVar", "(", "target", ")"...
// URLList provides a parsed list of url.URL values.
[ "URLList", "provides", "a", "parsed", "list", "of", "url", ".", "URL", "values", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/parsers.go#L168-L172
train
alecthomas/kingpin
parsers.go
URLListVar
func (p *parserMixin) URLListVar(target *[]*url.URL) { p.SetValue(newURLListValue(target)) }
go
func (p *parserMixin) URLListVar(target *[]*url.URL) { p.SetValue(newURLListValue(target)) }
[ "func", "(", "p", "*", "parserMixin", ")", "URLListVar", "(", "target", "*", "[", "]", "*", "url", ".", "URL", ")", "{", "p", ".", "SetValue", "(", "newURLListValue", "(", "target", ")", ")", "\n", "}" ]
// URLListVar provides a parsed list of url.URL values.
[ "URLListVar", "provides", "a", "parsed", "list", "of", "url", ".", "URL", "values", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/parsers.go#L175-L177
train
alecthomas/kingpin
parsers.go
Enum
func (p *parserMixin) Enum(options ...string) (target *string) { target = new(string) p.EnumVar(target, options...) return }
go
func (p *parserMixin) Enum(options ...string) (target *string) { target = new(string) p.EnumVar(target, options...) return }
[ "func", "(", "p", "*", "parserMixin", ")", "Enum", "(", "options", "...", "string", ")", "(", "target", "*", "string", ")", "{", "target", "=", "new", "(", "string", ")", "\n", "p", ".", "EnumVar", "(", "target", ",", "options", "...", ")", "\n", ...
// Enum allows a value from a set of options.
[ "Enum", "allows", "a", "value", "from", "a", "set", "of", "options", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/parsers.go#L180-L184
train
alecthomas/kingpin
parsers.go
Enums
func (p *parserMixin) Enums(options ...string) (target *[]string) { target = new([]string) p.EnumsVar(target, options...) return }
go
func (p *parserMixin) Enums(options ...string) (target *[]string) { target = new([]string) p.EnumsVar(target, options...) return }
[ "func", "(", "p", "*", "parserMixin", ")", "Enums", "(", "options", "...", "string", ")", "(", "target", "*", "[", "]", "string", ")", "{", "target", "=", "new", "(", "[", "]", "string", ")", "\n", "p", ".", "EnumsVar", "(", "target", ",", "optio...
// Enums allows a set of values from a set of options.
[ "Enums", "allows", "a", "set", "of", "values", "from", "a", "set", "of", "options", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/parsers.go#L192-L196
train
alecthomas/kingpin
parsers.go
Counter
func (p *parserMixin) Counter() (target *int) { target = new(int) p.CounterVar(target) return }
go
func (p *parserMixin) Counter() (target *int) { target = new(int) p.CounterVar(target) return }
[ "func", "(", "p", "*", "parserMixin", ")", "Counter", "(", ")", "(", "target", "*", "int", ")", "{", "target", "=", "new", "(", "int", ")", "\n", "p", ".", "CounterVar", "(", "target", ")", "\n", "return", "\n", "}" ]
// A Counter increments a number each time it is encountered.
[ "A", "Counter", "increments", "a", "number", "each", "time", "it", "is", "encountered", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/parsers.go#L204-L208
train
alecthomas/kingpin
values_generated.go
Bool
func (p *parserMixin) Bool() (target *bool) { target = new(bool) p.BoolVar(target) return }
go
func (p *parserMixin) Bool() (target *bool) { target = new(bool) p.BoolVar(target) return }
[ "func", "(", "p", "*", "parserMixin", ")", "Bool", "(", ")", "(", "target", "*", "bool", ")", "{", "target", "=", "new", "(", "bool", ")", "\n", "p", ".", "BoolVar", "(", "target", ")", "\n", "return", "\n", "}" ]
// Bool parses the next command-line value as bool.
[ "Bool", "parses", "the", "next", "command", "-", "line", "value", "as", "bool", "." ]
ef6e7c151c4fdbd3fe78aad001729fee08fa0932
https://github.com/alecthomas/kingpin/blob/ef6e7c151c4fdbd3fe78aad001729fee08fa0932/values_generated.go#L34-L38
train