_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3
values | text stringlengths 52 85.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q21700 | lintPackageComment | train | func (f *file) lintPackageComment() {
if f.isTest() {
return
}
const ref = styleGuideBase + "#package-comments"
prefix := "Package " + f.f.Name.Name + " "
// Look for a detached package comment.
// First, scan for the last comment that occurs before the "package" keyword.
var lastCG *ast.CommentGroup
for _,... | go | {
"resource": ""
} |
q21701 | lintBlankImports | train | func (f *file) lintBlankImports() {
// In package main and in tests, we don't complain about blank imports.
if f.pkg.main || f.isTest() {
return
}
// The first element of each contiguous group of blank imports should have
// an explanatory comment of some kind.
for i, imp := range f.f.Imports {
pos := f.fset... | go | {
"resource": ""
} |
q21702 | lintImports | train | func (f *file) lintImports() {
for i, is := range f.f.Imports {
_ = i
if is.Name != nil && is.Name.Name == "." && !f.isTest() {
f.errorf(is, 1, link(styleGuideBase+"#import-dot"), category("imports"), "should not use dot imports")
}
}
} | go | {
"resource": ""
} |
q21703 | lintExported | train | func (f *file) lintExported() {
if f.isTest() {
return
}
var lastGen *ast.GenDecl // last GenDecl entered.
// Set of GenDecls that have already had missing comments flagged.
genDeclMissingComments := make(map[*ast.GenDecl]bool)
f.walk(func(node ast.Node) bool {
switch v := node.(type) {
case *ast.GenDecl... | go | {
"resource": ""
} |
q21704 | lintTypeDoc | train | func (f *file) lintTypeDoc(t *ast.TypeSpec, doc *ast.CommentGroup) {
if !ast.IsExported(t.Name.Name) {
return
}
if doc == nil {
f.errorf(t, 1, link(docCommentsLink), category("comments"), "exported type %v should have comment or be unexported", t.Name)
return
}
s := doc.Text()
articles := [...]string{"A", ... | go | {
"resource": ""
} |
q21705 | lintVarDecls | train | func (f *file) lintVarDecls() {
var lastGen *ast.GenDecl // last GenDecl entered.
f.walk(func(node ast.Node) bool {
switch v := node.(type) {
case *ast.GenDecl:
if v.Tok != token.CONST && v.Tok != token.VAR {
return false
}
lastGen = v
return true
case *ast.ValueSpec:
if lastGen.Tok == token... | go | {
"resource": ""
} |
q21706 | lintElses | train | func (f *file) lintElses() {
// We don't want to flag if { } else if { } else { } constructions.
// They will appear as an IfStmt whose Else field is also an IfStmt.
// Record such a node so we ignore it when we visit it.
ignore := make(map[*ast.IfStmt]bool)
f.walk(func(node ast.Node) bool {
ifStmt, ok := node.... | go | {
"resource": ""
} |
q21707 | lintRanges | train | func (f *file) lintRanges() {
f.walk(func(node ast.Node) bool {
rs, ok := node.(*ast.RangeStmt)
if !ok {
return true
}
if isIdent(rs.Key, "_") && (rs.Value == nil || isIdent(rs.Value, "_")) {
p := f.errorf(rs.Key, 1, category("range-loop"), "should omit values from range; this loop is equivalent to `for... | go | {
"resource": ""
} |
q21708 | lintErrorf | train | func (f *file) lintErrorf() {
f.walk(func(node ast.Node) bool {
ce, ok := node.(*ast.CallExpr)
if !ok || len(ce.Args) != 1 {
return true
}
isErrorsNew := isPkgDot(ce.Fun, "errors", "New")
var isTestingError bool
se, ok := ce.Fun.(*ast.SelectorExpr)
if ok && se.Sel.Name == "Error" {
if typ := f.pkg.... | go | {
"resource": ""
} |
q21709 | lintErrors | train | func (f *file) lintErrors() {
for _, decl := range f.f.Decls {
gd, ok := decl.(*ast.GenDecl)
if !ok || gd.Tok != token.VAR {
continue
}
for _, spec := range gd.Specs {
spec := spec.(*ast.ValueSpec)
if len(spec.Names) != 1 || len(spec.Values) != 1 {
continue
}
ce, ok := spec.Values[0].(*ast.C... | go | {
"resource": ""
} |
q21710 | lintErrorStrings | train | func (f *file) lintErrorStrings() {
f.walk(func(node ast.Node) bool {
ce, ok := node.(*ast.CallExpr)
if !ok {
return true
}
if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") {
return true
}
if len(ce.Args) < 1 {
return true
}
str, ok := ce.Args[0].(*ast.BasicLit)
if... | go | {
"resource": ""
} |
q21711 | lintReceiverNames | train | func (f *file) lintReceiverNames() {
typeReceiver := map[string]string{}
f.walk(func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 {
return true
}
names := fn.Recv.List[0].Names
if len(names) < 1 {
return true
}
name := names[0].Name
const ref ... | go | {
"resource": ""
} |
q21712 | lintErrorReturn | train | func (f *file) lintErrorReturn() {
f.walk(func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok || fn.Type.Results == nil {
return true
}
ret := fn.Type.Results.List
if len(ret) <= 1 {
return true
}
if isIdent(ret[len(ret)-1].Type, "error") {
return true
}
// An error return parameter s... | go | {
"resource": ""
} |
q21713 | lintUnexportedReturn | train | func (f *file) lintUnexportedReturn() {
f.walk(func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok {
return true
}
if fn.Type.Results == nil {
return false
}
if !fn.Name.IsExported() {
return false
}
thing := "func"
if fn.Recv != nil && len(fn.Recv.List) > 0 {
thing = "method"
i... | go | {
"resource": ""
} |
q21714 | exportedType | train | func exportedType(typ types.Type) bool {
switch T := typ.(type) {
case *types.Named:
// Builtin types have no package.
return T.Obj().Pkg() == nil || T.Obj().Exported()
case *types.Map:
return exportedType(T.Key()) && exportedType(T.Elem())
case interface {
Elem() types.Type
}: // array, slice, pointer, ch... | go | {
"resource": ""
} |
q21715 | checkContextKeyType | train | func (f *file) checkContextKeyType(x *ast.CallExpr) {
sel, ok := x.Fun.(*ast.SelectorExpr)
if !ok {
return
}
pkg, ok := sel.X.(*ast.Ident)
if !ok || pkg.Name != "context" {
return
}
if sel.Sel.Name != "WithValue" {
return
}
// key is second argument to context.WithValue
if len(x.Args) != 3 {
return
... | go | {
"resource": ""
} |
q21716 | lintContextArgs | train | func (f *file) lintContextArgs() {
f.walk(func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok || len(fn.Type.Params.List) <= 1 {
return true
}
// A context.Context should be the first parameter of a function.
// Flag any that show up after the first.
for _, arg := range fn.Type.Params.List[1:] {
... | go | {
"resource": ""
} |
q21717 | isUntypedConst | train | func (f *file) isUntypedConst(expr ast.Expr) (defType string, ok bool) {
// Re-evaluate expr outside of its context to see if it's untyped.
// (An expr evaluated within, for example, an assignment context will get the type of the LHS.)
exprStr := f.render(expr)
tv, err := types.Eval(f.fset, f.pkg.typesPkg, expr.Pos... | go | {
"resource": ""
} |
q21718 | firstLineOf | train | func (f *file) firstLineOf(node, match ast.Node) string {
line := f.render(node)
if i := strings.Index(line, "\n"); i >= 0 {
line = line[:i]
}
return f.indentOf(match) + line
} | go | {
"resource": ""
} |
q21719 | imports | train | func (f *file) imports(importPath string) bool {
all := astutil.Imports(f.fset, f.f)
for _, p := range all {
for _, i := range p {
uq, err := strconv.Unquote(i.Path.Value)
if err == nil && importPath == uq {
return true
}
}
}
return false
} | go | {
"resource": ""
} |
q21720 | srcLine | train | func srcLine(src []byte, p token.Position) string {
// Run to end of line in both directions if not at line start/end.
lo, hi := p.Offset, p.Offset+1
for lo > 0 && src[lo-1] != '\n' {
lo--
}
for hi < len(src) && src[hi-1] != '\n' {
hi++
}
return string(src[lo:hi])
} | go | {
"resource": ""
} |
q21721 | importPaths | train | func importPaths(args []string) []string {
args = importPathsNoDotExpansion(args)
var out []string
for _, a := range args {
if strings.Contains(a, "...") {
if build.IsLocalImport(a) {
out = append(out, allPackagesInFS(a)...)
} else {
out = append(out, allPackages(a)...)
}
continue
}
out = a... | go | {
"resource": ""
} |
q21722 | hasPathPrefix | train | func hasPathPrefix(s, prefix string) bool {
switch {
default:
return false
case len(s) == len(prefix):
return s == prefix
case len(s) > len(prefix):
if prefix != "" && prefix[len(prefix)-1] == '/' {
return strings.HasPrefix(s, prefix)
}
return s[len(prefix)] == '/' && s[:len(prefix)] == prefix
}
} | go | {
"resource": ""
} |
q21723 | newGRPCClient | train | func newGRPCClient(doneCtx context.Context, c *Client) (*GRPCClient, error) {
conn, err := dialGRPCConn(c.config.TLSConfig, c.dialer)
if err != nil {
return nil, err
}
// Start the broker.
brokerGRPCClient := newGRPCBrokerClient(conn)
broker := newGRPCBroker(brokerGRPCClient, c.config.TLSConfig)
go broker.Run... | go | {
"resource": ""
} |
q21724 | ServeMux | train | func ServeMux(m ServeMuxMap) {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr,
"Invoked improperly. This is an internal command that shouldn't\n"+
"be manually invoked.\n")
os.Exit(1)
}
opts, ok := m[os.Args[1]]
if !ok {
fmt.Fprintf(os.Stderr, "Unknown plugin: %s\n", os.Args[1])
os.Exit(1)
}
Serve(... | go | {
"resource": ""
} |
q21725 | Recv | train | func (s *gRPCBrokerServer) Recv() (*plugin.ConnInfo, error) {
select {
case <-s.quit:
return nil, errors.New("broker closed")
case i := <-s.recv:
return i, nil
}
} | go | {
"resource": ""
} |
q21726 | Send | train | func (s *gRPCBrokerClientImpl) Send(i *plugin.ConnInfo) error {
ch := make(chan error)
defer close(ch)
select {
case <-s.quit:
return errors.New("broker closed")
case s.send <- &sendErr{
i: i,
ch: ch,
}:
}
return <-ch
} | go | {
"resource": ""
} |
q21727 | AcceptAndServe | train | func (b *GRPCBroker) AcceptAndServe(id uint32, s func([]grpc.ServerOption) *grpc.Server) {
listener, err := b.Accept(id)
if err != nil {
log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err)
return
}
defer listener.Close()
var opts []grpc.ServerOption
if b.tls != nil {
opts = []grpc.ServerOption... | go | {
"resource": ""
} |
q21728 | Close | train | func (b *GRPCBroker) Close() error {
b.streamer.Close()
b.o.Do(func() {
close(b.doneCh)
})
return nil
} | go | {
"resource": ""
} |
q21729 | parseJSON | train | func parseJSON(input []byte) (*logEntry, error) {
var raw map[string]interface{}
entry := &logEntry{}
err := json.Unmarshal(input, &raw)
if err != nil {
return nil, err
}
// Parse hclog-specific objects
if v, ok := raw["@message"]; ok {
entry.Message = v.(string)
delete(raw, "@message")
}
if v, ok := ... | go | {
"resource": ""
} |
q21730 | Check | train | func (s *SecureConfig) Check(filePath string) (bool, error) {
if len(s.Checksum) == 0 {
return false, ErrSecureConfigNoChecksum
}
if s.Hash == nil {
return false, ErrSecureConfigNoHash
}
file, err := os.Open(filePath)
if err != nil {
return false, err
}
defer file.Close()
_, err = io.Copy(s.Hash, file... | go | {
"resource": ""
} |
q21731 | Client | train | func (c *Client) Client() (ClientProtocol, error) {
_, err := c.Start()
if err != nil {
return nil, err
}
c.l.Lock()
defer c.l.Unlock()
if c.client != nil {
return c.client, nil
}
switch c.protocol {
case ProtocolNetRPC:
c.client, err = newRPCClient(c)
case ProtocolGRPC:
c.client, err = newGRPCCli... | go | {
"resource": ""
} |
q21732 | killed | train | func (c *Client) killed() bool {
c.l.Lock()
defer c.l.Unlock()
return c.processKilled
} | go | {
"resource": ""
} |
q21733 | loadServerCert | train | func (c *Client) loadServerCert(cert string) error {
certPool := x509.NewCertPool()
asn1, err := base64.RawStdEncoding.DecodeString(cert)
if err != nil {
return err
}
x509Cert, err := x509.ParseCertificate([]byte(asn1))
if err != nil {
return err
}
certPool.AddCert(x509Cert)
c.config.TLSConfig.RootCAs ... | go | {
"resource": ""
} |
q21734 | checkProtoVersion | train | func (c *Client) checkProtoVersion(protoVersion string) (int, PluginSet, error) {
serverVersion, err := strconv.Atoi(protoVersion)
if err != nil {
return 0, nil, fmt.Errorf("Error parsing protocol version %q: %s", protoVersion, err)
}
// record these for the error message
var clientVersions []int
// all versi... | go | {
"resource": ""
} |
q21735 | ReattachConfig | train | func (c *Client) ReattachConfig() *ReattachConfig {
c.l.Lock()
defer c.l.Unlock()
if c.address == nil {
return nil
}
if c.config.Cmd != nil && c.config.Cmd.Process == nil {
return nil
}
// If we connected via reattach, just return the information as-is
if c.config.Reattach != nil {
return c.config.Reat... | go | {
"resource": ""
} |
q21736 | Protocol | train | func (c *Client) Protocol() Protocol {
_, err := c.Start()
if err != nil {
return ProtocolInvalid
}
return c.protocol
} | go | {
"resource": ""
} |
q21737 | dialer | train | func (c *Client) dialer(_ string, timeout time.Duration) (net.Conn, error) {
conn, err := netAddrDialer(c.address)("", timeout)
if err != nil {
return nil, err
}
// If we have a TLS config we wrap our connection. We only do this
// for net/rpc since gRPC uses its own mechanism for TLS.
if c.protocol == Protoco... | go | {
"resource": ""
} |
q21738 | generateCert | train | func generateCert() (cert []byte, privateKey []byte, err error) {
key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
return nil, nil, err
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
sn, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, e... | go | {
"resource": ""
} |
q21739 | _pidAlive | train | func _pidAlive(pid int) bool {
h, err := syscall.OpenProcess(processDesiredAccess, false, uint32(pid))
if err != nil {
return false
}
var ec uint32
if e := syscall.GetExitCodeProcess(h, &ec); e != nil {
return false
}
return ec == exit_STILL_ACTIVE
} | go | {
"resource": ""
} |
q21740 | Config | train | func (s *GRPCServer) Config() string {
// Create a buffer that will contain our final contents
var buf bytes.Buffer
// Wrap the base64 encoding with JSON encoding.
if err := json.NewEncoder(&buf).Encode(s.config); err != nil {
// We panic since ths shouldn't happen under any scenario. We
// carefully control t... | go | {
"resource": ""
} |
q21741 | newRPCClient | train | func newRPCClient(c *Client) (*RPCClient, error) {
// Connect to the client
conn, err := net.Dial(c.address.Network(), c.address.String())
if err != nil {
return nil, err
}
if tcpConn, ok := conn.(*net.TCPConn); ok {
// Make sure to set keep alive so that the connection doesn't die
tcpConn.SetKeepAlive(true)... | go | {
"resource": ""
} |
q21742 | NewRPCClient | train | func NewRPCClient(conn io.ReadWriteCloser, plugins map[string]Plugin) (*RPCClient, error) {
// Create the yamux client so we can multiplex
mux, err := yamux.Client(conn, nil)
if err != nil {
conn.Close()
return nil, err
}
// Connect to the control stream.
control, err := mux.Open()
if err != nil {
mux.Clo... | go | {
"resource": ""
} |
q21743 | SyncStreams | train | func (c *RPCClient) SyncStreams(stdout io.Writer, stderr io.Writer) error {
go copyStream("stdout", stdout, c.stdout)
go copyStream("stderr", stderr, c.stderr)
return nil
} | go | {
"resource": ""
} |
q21744 | Close | train | func (c *RPCClient) Close() error {
// Call the control channel and ask it to gracefully exit. If this
// errors, then we save it so that we always return an error but we
// want to try to close the other channels anyways.
var empty struct{}
returnErr := c.control.Call("Control.Quit", true, &empty)
// Close the ... | go | {
"resource": ""
} |
q21745 | Ping | train | func (c *RPCClient) Ping() error {
var empty struct{}
return c.control.Call("Control.Ping", true, &empty)
} | go | {
"resource": ""
} |
q21746 | ServeConn | train | func (s *RPCServer) ServeConn(conn io.ReadWriteCloser) {
// First create the yamux server to wrap this connection
mux, err := yamux.Server(conn, nil)
if err != nil {
conn.Close()
log.Printf("[ERR] plugin: error creating yamux server: %s", err)
return
}
// Accept the control connection
control, err := mux.A... | go | {
"resource": ""
} |
q21747 | done | train | func (s *RPCServer) done() {
s.lock.Lock()
defer s.lock.Unlock()
if s.DoneCh != nil {
close(s.DoneCh)
s.DoneCh = nil
}
} | go | {
"resource": ""
} |
q21748 | protocolVersion | train | func protocolVersion(opts *ServeConfig) (int, Protocol, PluginSet) {
protoVersion := int(opts.ProtocolVersion)
pluginSet := opts.Plugins
protoType := ProtocolNetRPC
// Check if the client sent a list of acceptable versions
var clientVersions []int
if vs := os.Getenv("PLUGIN_PROTOCOL_VERSIONS"); vs != "" {
for _... | go | {
"resource": ""
} |
q21749 | _pidAlive | train | func _pidAlive(pid int) bool {
proc, err := os.FindProcess(pid)
if err == nil {
err = proc.Signal(syscall.Signal(0))
}
return err == nil
} | go | {
"resource": ""
} |
q21750 | AcceptAndServe | train | func (m *MuxBroker) AcceptAndServe(id uint32, v interface{}) {
conn, err := m.Accept(id)
if err != nil {
log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err)
return
}
serve(conn, "Plugin", v)
} | go | {
"resource": ""
} |
q21751 | pidWait | train | func pidWait(pid int) error {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for range ticker.C {
if !pidAlive(pid) {
break
}
}
return nil
} | go | {
"resource": ""
} |
q21752 | Shutdown | train | func (s *grpcControllerServer) Shutdown(ctx context.Context, _ *plugin.Empty) (*plugin.Empty, error) {
resp := &plugin.Empty{}
// TODO: figure out why GracefullStop doesn't work.
s.server.Stop()
return resp, nil
} | go | {
"resource": ""
} |
q21753 | IsPlanar | train | func (self SampleFormat) IsPlanar() bool {
switch self {
case S16P, S32P, FLTP, DBLP:
return true
default:
return false
}
} | go | {
"resource": ""
} |
q21754 | MakeAudioCodecType | train | func MakeAudioCodecType(base uint32) (c CodecType) {
c = CodecType(base)<<codecTypeOtherBits | CodecType(codecTypeAudioBit)
return
} | go | {
"resource": ""
} |
q21755 | HasSameFormat | train | func (self AudioFrame) HasSameFormat(other AudioFrame) bool {
if self.SampleRate != other.SampleRate {
return false
}
if self.ChannelLayout != other.ChannelLayout {
return false
}
if self.SampleFormat != other.SampleFormat {
return false
}
return true
} | go | {
"resource": ""
} |
q21756 | Slice | train | func (self AudioFrame) Slice(start int, end int) (out AudioFrame) {
if start > end {
panic(fmt.Sprintf("av: AudioFrame split failed start=%d end=%d invalid", start, end))
}
out = self
out.Data = append([][]byte(nil), out.Data...)
out.SampleCount = end - start
size := self.SampleFormat.BytesPerSample()
for i :=... | go | {
"resource": ""
} |
q21757 | Concat | train | func (self AudioFrame) Concat(in AudioFrame) (out AudioFrame) {
out = self
out.Data = append([][]byte(nil), out.Data...)
out.SampleCount += in.SampleCount
for i := range out.Data {
out.Data[i] = append(out.Data[i], in.Data[i]...)
}
return
} | go | {
"resource": ""
} |
q21758 | Do | train | func (self *Transcoder) Do(pkt av.Packet) (out []av.Packet, err error) {
stream := self.streams[pkt.Idx]
if stream.aenc != nil && stream.adec != nil {
if out, err = stream.audioDecodeAndEncode(pkt); err != nil {
return
}
} else {
out = append(out, pkt)
}
return
} | go | {
"resource": ""
} |
q21759 | Streams | train | func (self *Transcoder) Streams() (streams []av.CodecData, err error) {
for _, stream := range self.streams {
streams = append(streams, stream.codec)
}
return
} | go | {
"resource": ""
} |
q21760 | Close | train | func (self *Transcoder) Close() (err error) {
for _, stream := range self.streams {
if stream.aenc != nil {
stream.aenc.Close()
stream.aenc = nil
}
if stream.adec != nil {
stream.adec.Close()
stream.adec = nil
}
}
self.streams = nil
return
} | go | {
"resource": ""
} |
q21761 | WritePacket | train | func (self *Queue) WritePacket(pkt av.Packet) (err error) {
self.lock.Lock()
self.buf.Push(pkt)
if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame {
self.curgopcount++
}
for self.curgopcount >= self.maxgopcount && self.buf.Count > 1 {
pkt := self.buf.Pop()
if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFra... | go | {
"resource": ""
} |
q21762 | Oldest | train | func (self *Queue) Oldest() *QueueCursor {
cursor := self.newCursor()
cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos {
return buf.Head
}
return cursor
} | go | {
"resource": ""
} |
q21763 | DelayedTime | train | func (self *Queue) DelayedTime(dur time.Duration) *QueueCursor {
cursor := self.newCursor()
cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos {
i := buf.Tail - 1
if buf.IsValidPos(i) {
end := buf.Get(i)
for buf.IsValidPos(i) {
if end.Time-buf.Get(i).Time > dur {
break
}
i--
... | go | {
"resource": ""
} |
q21764 | DelayedGopCount | train | func (self *Queue) DelayedGopCount(n int) *QueueCursor {
cursor := self.newCursor()
cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos {
i := buf.Tail - 1
if videoidx != -1 {
for gop := 0; buf.IsValidPos(i) && gop < n; i-- {
pkt := buf.Get(i)
if pkt.Idx == int8(self.videoidx) && pkt.IsKeyF... | go | {
"resource": ""
} |
q21765 | ReadPacket | train | func (self *QueueCursor) ReadPacket() (pkt av.Packet, err error) {
self.que.cond.L.Lock()
buf := self.que.buf
if !self.gotpos {
self.pos = self.init(buf, self.que.videoidx)
self.gotpos = true
}
for {
if self.pos.LT(buf.Head) {
self.pos = buf.Head
} else if self.pos.GT(buf.Tail) {
self.pos = buf.Tail
... | go | {
"resource": ""
} |
q21766 | New | train | func New() *Martini {
m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(os.Stdout, "[martini] ", 0)}
m.Map(m.logger)
m.Map(defaultReturnHandler())
return m
} | go | {
"resource": ""
} |
q21767 | Logger | train | func (m *Martini) Logger(logger *log.Logger) {
m.logger = logger
m.Map(m.logger)
} | go | {
"resource": ""
} |
q21768 | Use | train | func (m *Martini) Use(handler Handler) {
validateHandler(handler)
m.handlers = append(m.handlers, handler)
} | go | {
"resource": ""
} |
q21769 | ServeHTTP | train | func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) {
m.createContext(res, req).run()
} | go | {
"resource": ""
} |
q21770 | RunOnAddr | train | func (m *Martini) RunOnAddr(addr string) {
// TODO: Should probably be implemented using a new instance of http.Server in place of
// calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use.
// This would also allow to improve testing when a custom host and port are pass... | go | {
"resource": ""
} |
q21771 | Classic | train | func Classic() *ClassicMartini {
r := NewRouter()
m := New()
m.Use(Logger())
m.Use(Recovery())
m.Use(Static("public"))
m.MapTo(r, (*Routes)(nil))
m.Action(r.Handle)
return &ClassicMartini{m, r}
} | go | {
"resource": ""
} |
q21772 | URLWith | train | func (r *route) URLWith(args []string) string {
if len(args) > 0 {
argCount := len(args)
i := 0
url := urlReg.ReplaceAllStringFunc(r.pattern, func(m string) string {
var val interface{}
if i < argCount {
val = args[i]
} else {
val = m
}
i += 1
return fmt.Sprintf(`%v`, val)
})
retur... | go | {
"resource": ""
} |
q21773 | URLFor | train | func (r *router) URLFor(name string, params ...interface{}) string {
route := r.findRoute(name)
if route == nil {
panic("route not found")
}
var args []string
for _, param := range params {
switch v := param.(type) {
case int:
args = append(args, strconv.FormatInt(int64(v), 10))
case string:
args =... | go | {
"resource": ""
} |
q21774 | MethodsFor | train | func (r *router) MethodsFor(path string) []string {
methods := []string{}
for _, route := range r.getRoutes() {
matches := route.regex.FindStringSubmatch(path)
if len(matches) > 0 && matches[0] == path && !hasMethod(methods, route.method) {
methods = append(methods, route.method)
}
}
return methods
} | go | {
"resource": ""
} |
q21775 | Logger | train | func Logger() Handler {
return func(res http.ResponseWriter, req *http.Request, c Context, log *log.Logger) {
start := time.Now()
addr := req.Header.Get("X-Real-IP")
if addr == "" {
addr = req.Header.Get("X-Forwarded-For")
if addr == "" {
addr = req.RemoteAddr
}
}
log.Printf("Started %s %s for... | go | {
"resource": ""
} |
q21776 | decodeSingleUnicodeEscape | train | func decodeSingleUnicodeEscape(in []byte) (rune, bool) {
// We need at least 6 characters total
if len(in) < 6 {
return utf8.RuneError, false
}
// Convert hex to decimal
h1, h2, h3, h4 := h2I(in[2]), h2I(in[3]), h2I(in[4]), h2I(in[5])
if h1 == badHex || h2 == badHex || h3 == badHex || h4 == badHex {
return u... | go | {
"resource": ""
} |
q21777 | parseInt | train | func parseInt(bytes []byte) (v int64, ok bool, overflow bool) {
if len(bytes) == 0 {
return 0, false, false
}
var neg bool = false
if bytes[0] == '-' {
neg = true
bytes = bytes[1:]
}
var b int64 = 0
for _, c := range bytes {
if c >= '0' && c <= '9' {
b = (10 * v) + int64(c-'0')
} else {
return ... | go | {
"resource": ""
} |
q21778 | lastToken | train | func lastToken(data []byte) int {
for i := len(data) - 1; i >= 0; i-- {
switch data[i] {
case ' ', '\n', '\r', '\t':
continue
default:
return i
}
}
return -1
} | go | {
"resource": ""
} |
q21779 | stringEnd | train | func stringEnd(data []byte) (int, bool) {
escaped := false
for i, c := range data {
if c == '"' {
if !escaped {
return i + 1, false
} else {
j := i - 1
for {
if j < 0 || data[j] != '\\' {
return i + 1, true // even number of backslashes
}
j--
if j < 0 || data[j] != '\\' {... | go | {
"resource": ""
} |
q21780 | ArrayEach | train | func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) (offset int, err error) {
if len(data) == 0 {
return -1, MalformedObjectError
}
offset = 1
if len(keys) > 0 {
if offset = searchKeys(data, keys...); offset == -1 {
return offset, KeyPathNotFoundErr... | go | {
"resource": ""
} |
q21781 | ObjectEach | train | func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error) {
var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings
offset := 0
// Descend to the desired key, if requested
if len(k... | go | {
"resource": ""
} |
q21782 | GetUnsafeString | train | func GetUnsafeString(data []byte, keys ...string) (val string, err error) {
v, _, _, e := Get(data, keys...)
if e != nil {
return "", e
}
return bytesToString(&v), nil
} | go | {
"resource": ""
} |
q21783 | GetString | train | func GetString(data []byte, keys ...string) (val string, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return "", e
}
if t != String {
return "", fmt.Errorf("Value is not a string: %s", string(v))
}
// If no escapes return raw conten
if bytes.IndexByte(v, '\\') == -1 {
return string(v), ni... | go | {
"resource": ""
} |
q21784 | GetFloat | train | func GetFloat(data []byte, keys ...string) (val float64, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return 0, e
}
if t != Number {
return 0, fmt.Errorf("Value is not a number: %s", string(v))
}
return ParseFloat(v)
} | go | {
"resource": ""
} |
q21785 | GetInt | train | func GetInt(data []byte, keys ...string) (val int64, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return 0, e
}
if t != Number {
return 0, fmt.Errorf("Value is not a number: %s", string(v))
}
return ParseInt(v)
} | go | {
"resource": ""
} |
q21786 | GetBoolean | train | func GetBoolean(data []byte, keys ...string) (val bool, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return false, e
}
if t != Boolean {
return false, fmt.Errorf("Value is not a boolean: %s", string(v))
}
return ParseBoolean(v)
} | go | {
"resource": ""
} |
q21787 | ParseFloat | train | func ParseFloat(b []byte) (float64, error) {
if v, err := parseFloat(&b); err != nil {
return 0, MalformedValueError
} else {
return v, nil
}
} | go | {
"resource": ""
} |
q21788 | ParseInt | train | func ParseInt(b []byte) (int64, error) {
if v, ok, overflow := parseInt(b); !ok {
if overflow {
return 0, OverflowIntegerError
}
return 0, MalformedValueError
} else {
return v, nil
}
} | go | {
"resource": ""
} |
q21789 | SetErrorf | train | func (f *Fpdf) SetErrorf(fmtStr string, args ...interface{}) {
if f.err == nil {
f.err = fmt.Errorf(fmtStr, args...)
}
} | go | {
"resource": ""
} |
q21790 | SetMargins | train | func (f *Fpdf) SetMargins(left, top, right float64) {
f.lMargin = left
f.tMargin = top
if right < 0 {
right = left
}
f.rMargin = right
} | go | {
"resource": ""
} |
q21791 | SetLeftMargin | train | func (f *Fpdf) SetLeftMargin(margin float64) {
f.lMargin = margin
if f.page > 0 && f.x < margin {
f.x = margin
}
} | go | {
"resource": ""
} |
q21792 | SetPageBox | train | func (f *Fpdf) SetPageBox(t string, x, y, wd, ht float64) {
f.SetPageBoxRec(t, PageBox{SizeType{Wd: wd, Ht: ht}, PointType{X: x, Y: y}})
} | go | {
"resource": ""
} |
q21793 | GetAutoPageBreak | train | func (f *Fpdf) GetAutoPageBreak() (auto bool, margin float64) {
auto = f.autoPageBreak
margin = f.bMargin
return
} | go | {
"resource": ""
} |
q21794 | SetAutoPageBreak | train | func (f *Fpdf) SetAutoPageBreak(auto bool, margin float64) {
f.autoPageBreak = auto
f.bMargin = margin
f.pageBreakTrigger = f.h - margin
} | go | {
"resource": ""
} |
q21795 | SetKeywords | train | func (f *Fpdf) SetKeywords(keywordsStr string, isUTF8 bool) {
if isUTF8 {
keywordsStr = utf8toutf16(keywordsStr)
}
f.keywords = keywordsStr
} | go | {
"resource": ""
} |
q21796 | GetStringWidth | train | func (f *Fpdf) GetStringWidth(s string) float64 {
if f.err != nil {
return 0
}
w := 0
for _, ch := range []byte(s) {
if ch == 0 {
break
}
w += f.currentFont.Cw[ch]
}
return float64(w) * f.fontSize / 1000
} | go | {
"resource": ""
} |
q21797 | SetLineCapStyle | train | func (f *Fpdf) SetLineCapStyle(styleStr string) {
var capStyle int
switch styleStr {
case "round":
capStyle = 1
case "square":
capStyle = 2
default:
capStyle = 0
}
f.capStyle = capStyle
if f.page > 0 {
f.outf("%d J", f.capStyle)
}
} | go | {
"resource": ""
} |
q21798 | SetLineJoinStyle | train | func (f *Fpdf) SetLineJoinStyle(styleStr string) {
var joinStyle int
switch styleStr {
case "round":
joinStyle = 1
case "bevel":
joinStyle = 2
default:
joinStyle = 0
}
f.joinStyle = joinStyle
if f.page > 0 {
f.outf("%d j", f.joinStyle)
}
} | go | {
"resource": ""
} |
q21799 | fillDrawOp | train | func fillDrawOp(styleStr string) (opStr string) {
switch strings.ToUpper(styleStr) {
case "", "D":
// Stroke the path.
opStr = "S"
case "F":
// fill the path, using the nonzero winding number rule
opStr = "f"
case "F*":
// fill the path, using the even-odd rule
opStr = "f*"
case "FD", "DF":
// fill a... | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.