_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rsync.go#L21-L64
func rsyncLocalCopy(source string, dest string, bwlimit string) (string, error) { err := os.MkdirAll(dest, 0755) if err != nil { return "", err } rsyncVerbosity := "-q" if debug { rsyncVerbosity = "-vi" } if bwlimit == "" { bwlimit = "0" } msg, err := shared.RunCommand("rsync", "-a", "-HAX", "--sparse", "--devices", "--delete", "--checksum", "--numeric-ids", "--xattrs", "--bwlimit", bwlimit, rsyncVerbosity, shared.AddSlash(source), dest) if err != nil { runError, ok := err.(shared.RunError) if ok { exitError, ok := runError.Err.(*exec.ExitError) if ok { waitStatus := exitError.Sys().(syscall.WaitStatus) if waitStatus.ExitStatus() == 24 { return msg, nil } } } return msg, err } return msg, nil }
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/collection.go#L286-L291
func (c *Collection) Delete(query bson.M) (*mgo.ChangeInfo, error) { sess := c.Connection.Session.Clone() defer sess.Close() col := c.collectionOnSession(sess) return col.RemoveAll(query) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/pipeline/controller.go#L549-L558
func sourceURL(pj prowjobv1.ProwJob) string { if pj.Spec.Refs == nil { return "" } sourceURL := pj.Spec.Refs.CloneURI if sourceURL == "" { sourceURL = fmt.Sprintf("%s.git", pj.Spec.Refs.RepoLink) } return sourceURL }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L760-L770
func (r *Rule) IsEmpty(info KindInfo) bool { if info.NonEmptyAttrs == nil { return false } for k := range info.NonEmptyAttrs { if _, ok := r.attrs[k]; ok { return false } } return true }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L3685-L3690
func (o *ListUint16Option) Set(value string) error { val := Uint16Option{} val.Set(value) *o = append(*o, val) return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L276-L288
func ensureSchemaTableExists(tx *sql.Tx) error { exists, err := DoesSchemaTableExist(tx) if err != nil { return fmt.Errorf("failed to check if schema table is there: %v", err) } if !exists { err := createSchemaTable(tx) if err != nil { return fmt.Errorf("failed to create schema table: %v", err) } } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/main.go#L555-L569
func handleBadge(ja *jobs.JobAgent) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { setHeadersNoCaching(w) wantJobs := r.URL.Query().Get("jobs") if wantJobs == "" { http.Error(w, "missing jobs query parameter", http.StatusBadRequest) return } w.Header().Set("Content-Type", "image/svg+xml") allJobs := ja.ProwJobs() _, _, svg := renderBadge(pickLatestJobs(allJobs, wantJobs)) w.Write(svg) } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/require/require.go#L316-L332
func NoErrorWithinT(tb testing.TB, t time.Duration, f func() error, msgAndArgs ...interface{}) { tb.Helper() errCh := make(chan error) go func() { // This goro will leak if the timeout is exceeded, but it's okay because the // test is failing anyway errCh <- f() }() select { case err := <-errCh: if err != nil { fatal(tb, msgAndArgs, "No error is expected but got %s", err.Error()) } case <-time.After(t): fatal(tb, msgAndArgs, "operation did not finish within %s", t.String()) } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L671-L678
func (r *raft) tickElection() { r.electionElapsed++ if r.promotable() && r.pastElectionTimeout() { r.electionElapsed = 0 r.Step(pb.Message{From: r.id, Type: pb.MsgHup}) } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/watch.go#L129-L131
func (wr *WatchResponse) IsProgressNotify() bool { return len(wr.Events) == 0 && !wr.Canceled && !wr.Created && wr.CompactRevision == 0 && wr.Header.Revision != 0 }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L5644-L5648
func (v *EventWebSocketFrameError) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork44(&r, v) return r.Error() }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L142-L146
func ClassifyF(s string) func(string) string { return func(s string) string { return Classify(s) } }
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive50.go#L225-L251
func (a *archive50) parseFileEncryptionRecord(b readBuf, f *fileBlockHeader) error { if ver := b.uvarint(); ver != 0 { return errUnknownEncMethod } flags := b.uvarint() keys, err := a.getKeys(&b) if err != nil { return err } f.key = keys[0] if len(b) < 16 { return errCorruptEncrypt } f.iv = b.bytes(16) if flags&file5EncCheckPresent > 0 { if err := checkPassword(&b, keys); err != nil { return err } } if flags&file5EncUseMac > 0 { a.checksum.key = keys[1] } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/compact_op.go#L37-L41
func OpCompact(rev int64, opts ...CompactOption) CompactOp { ret := CompactOp{revision: rev} ret.applyCompactOpts(opts) return ret }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/tracing.go#L283-L288
func TracerFromRegistrar(registrar Registrar) opentracing.Tracer { if tracerProvider, ok := registrar.(tracerProvider); ok { return tracerProvider.Tracer() } return opentracing.GlobalTracer() }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/expr.go#L307-L354
func makePlatformStringsExpr(ps platformStringsExprs) bzl.Expr { makeSelect := func(dict *bzl.DictExpr) bzl.Expr { return &bzl.CallExpr{ X: &bzl.Ident{Name: "select"}, List: []bzl.Expr{dict}, } } forceMultiline := func(e bzl.Expr) { switch e := e.(type) { case *bzl.ListExpr: e.ForceMultiLine = true case *bzl.CallExpr: e.List[0].(*bzl.DictExpr).ForceMultiLine = true } } var parts []bzl.Expr if ps.generic != nil { parts = append(parts, ps.generic) } if ps.os != nil { parts = append(parts, makeSelect(ps.os)) } if ps.arch != nil { parts = append(parts, makeSelect(ps.arch)) } if ps.platform != nil { parts = append(parts, makeSelect(ps.platform)) } if len(parts) == 0 { return nil } if len(parts) == 1 { return parts[0] } expr := parts[0] forceMultiline(expr) for _, part := range parts[1:] { forceMultiline(part) expr = &bzl.BinaryExpr{ Op: "+", X: expr, Y: part, } } return expr }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L193-L201
func NewNetworkTransportWithLogger( stream StreamLayer, maxPool int, timeout time.Duration, logger *log.Logger, ) *NetworkTransport { config := &NetworkTransportConfig{Stream: stream, MaxPool: maxPool, Timeout: timeout, Logger: logger} return NewNetworkTransportWithConfig(config) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/easyjson.go#L1070-L1074
func (v *DispatchTouchEventParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoInput7(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L205-L213
func FieldColumns(fields []*Field) string { columns := make([]string, len(fields)) for i, field := range fields { columns[i] = field.Column() } return strings.Join(columns, ", ") }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/easyjson.go#L594-L598
func (v *SynthesizePinchGestureParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoInput3(&r, v) return r.Error() }
https://github.com/geoffgarside/ber/blob/27a1aff36ce64dbe5d93c08cc5f161983134ddc5/ber.go#L476-L478
func invalidLength(offset, length, sliceLength int) bool { return offset+length < offset || offset+length > sliceLength }
https://github.com/mipearson/rfw/blob/6f0a6f3266ba1058df9ef0c94cda1cecd2e62852/rfw.go#L41-L52
func (l *Writer) Write(p []byte) (int, error) { l.mutex.Lock() defer l.mutex.Unlock() inode, err := l.checkInode() if os.IsNotExist(err) || inode != l.inode { err = l.reopen() if err != nil { return 0, err } } return l.file.Write(p) }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/matchers.go#L401-L403
func Or(ms ...types.GomegaMatcher) types.GomegaMatcher { return &matchers.OrMatcher{Matchers: ms} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L2196-L2200
func (v DocumentSnapshot) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomsnapshot10(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/opts.go#L116-L125
func LogName(name string) Option { return func(sh *StackdriverHook) error { if sh.projectID == "" { sh.logName = name } else { sh.logName = fmt.Sprintf("projects/%s/logs/%s", sh.projectID, name) } return nil } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2auth/auth.go#L468-L517
func (ou User) merge(lg *zap.Logger, nu User, s PasswordStore) (User, error) { var out User if ou.User != nu.User { return out, authErr(http.StatusConflict, "Merging user data with conflicting usernames: %s %s", ou.User, nu.User) } out.User = ou.User if nu.Password != "" { hash, err := s.HashPassword(nu.Password) if err != nil { return ou, err } out.Password = hash } else { out.Password = ou.Password } currentRoles := types.NewUnsafeSet(ou.Roles...) for _, g := range nu.Grant { if currentRoles.Contains(g) { if lg != nil { lg.Warn( "attempted to grant a duplicate role for a user", zap.String("user-name", nu.User), zap.String("role-name", g), ) } else { plog.Noticef("granting duplicate role %s for user %s", g, nu.User) } return User{}, authErr(http.StatusConflict, fmt.Sprintf("Granting duplicate role %s for user %s", g, nu.User)) } currentRoles.Add(g) } for _, r := range nu.Revoke { if !currentRoles.Contains(r) { if lg != nil { lg.Warn( "attempted to revoke a ungranted role for a user", zap.String("user-name", nu.User), zap.String("role-name", r), ) } else { plog.Noticef("revoking ungranted role %s for user %s", r, nu.User) } return User{}, authErr(http.StatusConflict, fmt.Sprintf("Revoking ungranted role %s for user %s", r, nu.User)) } currentRoles.Remove(r) } out.Roles = currentRoles.Values() sort.Strings(out.Roles) return out, nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/codegen_client.go#L1437-L1439
func (api *API) NetworkInterfaceAttachmentLocator(href string) *NetworkInterfaceAttachmentLocator { return &NetworkInterfaceAttachmentLocator{Href(href), api} }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/branch_protection.go#L201-L212
func (r Repo) GetBranch(name string) (*Branch, error) { b, ok := r.Branches[name] if ok { b.Policy = r.Apply(b.Policy) if b.Protect == nil { return nil, errors.New("defined branch policies must set protect") } } else { b.Policy = r.Policy } return &b, nil }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L278-L303
func (gc *GraphicContext) newGroup(drawType drawType) *Group { group := Group{} // set attrs to group if drawType&stroked == stroked { group.Stroke = toSvgRGBA(gc.Current.StrokeColor) group.StrokeWidth = toSvgLength(gc.Current.LineWidth) group.StrokeLinecap = gc.Current.Cap.String() group.StrokeLinejoin = gc.Current.Join.String() if len(gc.Current.Dash) > 0 { group.StrokeDasharray = toSvgArray(gc.Current.Dash) group.StrokeDashoffset = toSvgLength(gc.Current.DashOffset) } } if drawType&filled == filled { group.Fill = toSvgRGBA(gc.Current.FillColor) group.FillRule = toSvgFillRule(gc.Current.FillRule) } group.Transform = toSvgTransform(gc.Current.Tr) // attach gc.svg.Groups = append(gc.svg.Groups, &group) return &group }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/external-plugins/needs-rebase/plugin/plugin.go#L60-L66
func HelpProvider(enabledRepos []string) (*pluginhelp.PluginHelp, error) { return &pluginhelp.PluginHelp{ Description: `The needs-rebase plugin manages the '` + labels.NeedsRebase + `' label by removing it from Pull Requests that are mergeable and adding it to those which are not. The plugin reacts to commit changes on PRs in addition to periodically scanning all open PRs for any changes to mergeability that could have resulted from changes in other PRs.`, }, nil }
https://github.com/ianschenck/envflag/blob/9111d830d133f952887a936367fb0211c3134f0d/envflag.go#L95-L97
func UintVar(p *uint, name string, value uint, usage string) { EnvironmentFlags.UintVar(p, name, value, usage) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L1320-L1324
func (v QueryObjectsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime13(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/process.go#L70-L72
func (p *Process) Readable(a Address) bool { return p.findMapping(a) != nil }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/bytecode.go#L45-L58
func (b *ByteCode) String() string { buf := rbpool.Get() defer rbpool.Release(buf) fmt.Fprintf(buf, "// Bytecode for '%s'\n// Generated On: %s\n", b.Name, b.GeneratedOn, ) for k, v := range b.OpList { fmt.Fprintf(buf, "%03d. %s\n", k+1, v) } return buf.String() }
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/sign.go#L45-L60
func (b *Bucket) Sign(req *http.Request) { if req.Header == nil { req.Header = http.Header{} } if b.S3.Keys.SecurityToken != "" { req.Header.Set("X-Amz-Security-Token", b.S3.Keys.SecurityToken) } req.Header.Set("User-Agent", "S3Gof3r") s := &signer{ Time: time.Now(), Request: req, Region: b.S3.Region(), Keys: b.S3.Keys, } s.sign() }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L374-L377
func (w *WriteBuffer) Wrap(b []byte) { w.buffer = b w.remaining = b }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/diff/boshreleasediffer.go#L52-L68
func (d boshReleaseDiffer) allJobNames() []string { jobNamesMap := make(map[string]string) var addJobNames = func(br *release.BoshRelease) { if br != nil { for jbname := range br.JobManifests { jobNamesMap[jbname] = jbname } } } addJobNames(d.release1) addJobNames(d.release2) var jobNames []string for jname := range jobNamesMap { jobNames = append(jobNames, jname) } return jobNames }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/cluster_util.go#L181-L223
func decideClusterVersion(lg *zap.Logger, vers map[string]*version.Versions) *semver.Version { var cv *semver.Version lv := semver.Must(semver.NewVersion(version.Version)) for mid, ver := range vers { if ver == nil { return nil } v, err := semver.NewVersion(ver.Server) if err != nil { if lg != nil { lg.Warn( "failed to parse server version of remote member", zap.String("remote-member-id", mid), zap.String("remote-member-version", ver.Server), zap.Error(err), ) } else { plog.Errorf("cannot understand the version of member %s (%v)", mid, err) } return nil } if lv.LessThan(*v) { if lg != nil { lg.Warn( "leader found higher-versioned member", zap.String("local-member-version", lv.String()), zap.String("remote-member-id", mid), zap.String("remote-member-version", ver.Server), ) } else { plog.Warningf("the local etcd version %s is not up-to-date", lv.String()) plog.Warningf("member %s has a higher version %s", mid, ver.Server) } } if cv == nil { cv = v } else if v.LessThan(*cv) { cv = v } } return cv }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L7851-L7855
func (v *CookieParam) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork61(&r, v) return r.Error() }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/profiles/openstack/ecs/ubuntu_16_04.go#L25-L126
func NewUbuntuCluster(name string) *cluster.Cluster { var ( masterName = fmt.Sprintf("%s-master", name) nodeName = fmt.Sprintf("%s-node", name) ) controlPlaneProviderConfig := &cluster.ControlPlaneProviderConfig{ Cloud: cluster.CloudECS, Location: "nl-ams1", SSH: &cluster.SSH{ PublicKeyPath: "~/.ssh/id_rsa.pub", User: "ubuntu", }, Values: &cluster.Values{ ItemMap: map[string]string{ "INJECTEDTOKEN": kubeadm.GetRandomToken(), }, }, KubernetesAPI: &cluster.KubernetesAPI{ Port: "443", }, Network: &cluster.Network{ Type: cluster.NetworkTypePublic, InternetGW: &cluster.InternetGW{ Name: "default", }, }, } machineSetsProviderConfigs := []*cluster.MachineProviderConfig{ { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeMaster, Name: masterName, MaxCount: 1, Image: "GNU/Linux Ubuntu Server 16.04 Xenial Xerus x64", Size: "e3standard.x3", BootstrapScripts: []string{ "bootstrap/ecs_k8s_ubuntu_16.04_master.sh", }, Subnets: []*cluster.Subnet{ { Name: "internal", CIDR: "192.168.200.0/24", }, }, Firewalls: []*cluster.Firewall{ { Name: masterName, IngressRules: []*cluster.IngressRule{ { IngressFromPort: "22", IngressToPort: "22", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressFromPort: "443", IngressToPort: "443", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressSource: "192.168.200.0/24", }, }, }, }, }, }, { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeNode, Name: nodeName, MaxCount: 2, Image: "GNU/Linux Ubuntu Server 16.04 Xenial Xerus x64", Size: "e3standard.x3", BootstrapScripts: []string{ "bootstrap/ecs_k8s_ubuntu_16.04_node.sh", }, Firewalls: []*cluster.Firewall{ { Name: nodeName, IngressRules: []*cluster.IngressRule{ { IngressFromPort: "22", IngressToPort: "22", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressSource: "192.168.200.0/24", }, }, }, }, }, }, } c := cluster.NewCluster(name) c.SetProviderConfig(controlPlaneProviderConfig) c.NewMachineSetsFromProviderConfigs(machineSetsProviderConfigs) return c }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L263-L266
func (p SetDeviceMetricsOverrideParams) WithViewport(viewport *page.Viewport) *SetDeviceMetricsOverrideParams { p.Viewport = viewport return &p }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L329-L343
func (g *Glg) SetWriter(writer io.Writer) *Glg { if writer == nil { return g } g.logger.Range(func(key, val interface{}) bool { l := val.(*logger) l.writer = writer l.updateMode() g.logger.Store(key.(LEVEL), l) return true }) return g }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/easyjson.go#L893-L897
func (v EventCacheStorageContentUpdated) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoStorage10(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L160-L214
func NewPubSub(ctx context.Context, h host.Host, rt PubSubRouter, opts ...Option) (*PubSub, error) { ps := &PubSub{ host: h, ctx: ctx, rt: rt, signID: h.ID(), signKey: h.Peerstore().PrivKey(h.ID()), signStrict: true, incoming: make(chan *RPC, 32), publish: make(chan *Message), newPeers: make(chan peer.ID), newPeerStream: make(chan inet.Stream), newPeerError: make(chan peer.ID), peerDead: make(chan peer.ID), cancelCh: make(chan *Subscription), getPeers: make(chan *listPeerReq), addSub: make(chan *addSubReq), getTopics: make(chan *topicReq), sendMsg: make(chan *sendReq, 32), addVal: make(chan *addValReq), rmVal: make(chan *rmValReq), validateThrottle: make(chan struct{}, defaultValidateThrottle), eval: make(chan func()), myTopics: make(map[string]map[*Subscription]struct{}), topics: make(map[string]map[peer.ID]struct{}), peers: make(map[peer.ID]chan *RPC), topicVals: make(map[string]*topicVal), blacklist: NewMapBlacklist(), blacklistPeer: make(chan peer.ID), seenMessages: timecache.NewTimeCache(TimeCacheDuration), counter: uint64(time.Now().UnixNano()), } for _, opt := range opts { err := opt(ps) if err != nil { return nil, err } } if ps.signStrict && ps.signKey == nil { return nil, fmt.Errorf("strict signature verification enabled but message signing is disabled") } rt.Attach(ps) for _, id := range rt.Protocols() { h.SetStreamHandler(id, ps.handleNewStream) } h.Network().Notify((*PubSubNotif)(ps)) go ps.processLoop(ctx) return ps, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/boskos.go#L88-L98
func NewBoskosHandler(r *ranch.Ranch) *http.ServeMux { mux := http.NewServeMux() mux.Handle("/", handleDefault(r)) mux.Handle("/acquire", handleAcquire(r)) mux.Handle("/acquirebystate", handleAcquireByState(r)) mux.Handle("/release", handleRelease(r)) mux.Handle("/reset", handleReset(r)) mux.Handle("/update", handleUpdate(r)) mux.Handle("/metric", handleMetric(r)) return mux }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/pjutil.go#L142-L147
func PeriodicSpec(p config.Periodic) prowapi.ProwJobSpec { pjs := specFromJobBase(p.JobBase) pjs.Type = prowapi.PeriodicJob return pjs }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_actions.go#L225-L235
func (s *Selection) FlickFinger(xOffset, yOffset int, speed uint) error { selectedElement, err := s.elements.GetExactlyOne() if err != nil { return fmt.Errorf("failed to select element from %s: %s", s, err) } if err := s.session.TouchFlick(selectedElement.(*api.Element), api.XYOffset{X: xOffset, Y: yOffset}, api.ScalarSpeed(speed)); err != nil { return fmt.Errorf("failed to flick finger on %s: %s", s, err) } return nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/iaas/machine.go#L124-L142
func FindMachineByIdOrAddress(id string, address string) (Machine, error) { coll, err := collection() if err != nil { return Machine{}, err } defer coll.Close() var result Machine query := bson.M{} if id != "" { query["_id"] = id } else { query["address"] = address } err = coll.Find(query).One(&result) if err == mgo.ErrNotFound { err = ErrMachineNotFound } return result, err }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/timeout.go#L10-L20
func IsTimeoutError(err error) bool { if err == context.DeadlineExceeded { return true } if t, ok := err.(interface { IsTimeout() bool }); ok { return t.IsTimeout() } return false }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L5986-L5990
func (v EventFrameRequestedNavigation) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage63(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/authenticator.go#L133-L271
func (a *Authenticator) Authorizer(scope string, force, loadClient, loadResourceOwner bool) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // create tracer tracer := fire.NewTracerFromRequest(r, "flame/Authenticator.Authorizer") tracer.Tag("scope", scope) tracer.Tag("force", force) tracer.Tag("loadClient", loadClient) tracer.Tag("loadResourceOwner", loadResourceOwner) defer tracer.Finish(true) // add span to context r = r.WithContext(tracer.Context(r.Context())) // immediately pass on request if force is not set and there is // no authentication information provided if !force && r.Header.Get("Authorization") == "" { // call next handler next.ServeHTTP(w, r) return } // continue any previous aborts defer stack.Resume(func(err error) { // directly write bearer errors if bearerError, ok := err.(*bearer.Error); ok { _ = bearer.WriteError(w, bearerError) return } // set critical error on last span tracer.Tag("error", true) tracer.Log("error", err.Error()) tracer.Log("stack", stack.Trace()) // otherwise report critical errors if a.Reporter != nil { a.Reporter(err) } // ignore errors caused by writing critical errors _ = bearer.WriteError(w, bearer.ServerError()) }) // parse scope s := oauth2.ParseScope(scope) // parse bearer token tk, err := bearer.ParseToken(r) stack.AbortIf(err) // parse token claims, expired, err := a.policy.ParseToken(tk) if expired { stack.Abort(bearer.InvalidToken("expired token")) } else if err != nil { stack.Abort(bearer.InvalidToken("malformed token")) } // copy store store := a.store.Copy() defer store.Close() // create state state := &state{ request: r, writer: w, store: store, tracer: tracer, } // get token accessToken := a.getToken(state, a.policy.Token, bson.ObjectIdHex(claims.Id)) if accessToken == nil { stack.Abort(bearer.InvalidToken("unknown token")) } // get additional data typ, scope, expiresAt, clientID, resourceOwnerID := accessToken.GetTokenData() // validate token type if typ != AccessToken { stack.Abort(bearer.InvalidToken("invalid type")) } // validate expiration if expiresAt.Before(time.Now()) { stack.Abort(bearer.InvalidToken("expired token")) } // validate scope if !oauth2.Scope(scope).Includes(s) { stack.Abort(bearer.InsufficientScope(s.String())) } // create new context with access token ctx := context.WithValue(r.Context(), AccessTokenContextKey, accessToken) // call next handler if client should not be loaded if !loadClient { // call next handler next.ServeHTTP(w, r.WithContext(ctx)) return } // get client client := a.getFirstClient(state, clientID) if client == nil { stack.Abort(errors.New("missing client")) } // create new context with client ctx = context.WithValue(ctx, ClientContextKey, client) // call next handler if resource owner does not exist or should not // be loaded if resourceOwnerID == nil || !loadResourceOwner { // call next handler next.ServeHTTP(w, r.WithContext(ctx)) return } // get resource owner resourceOwner := a.getFirstResourceOwner(state, client, *resourceOwnerID) if resourceOwner == nil { stack.Abort(errors.New("missing resource owner")) } // create new context with resource owner ctx = context.WithValue(ctx, ResourceOwnerContextKey, resourceOwner) // call next handler next.ServeHTTP(w, r.WithContext(ctx)) }) } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/tide.go#L1136-L1141
func (c *changedFilesAgent) prune() { c.Lock() defer c.Unlock() c.changeCache = c.nextChangeCache c.nextChangeCache = make(map[changeCacheKey][]string) }
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/cascade.go#L65-L92
func CascadeSave(collection *Collection, doc Document) error { // Find out which properties to cascade if conv, ok := doc.(CascadingDocument); ok { toCascade := conv.GetCascade(collection) for _, conf := range toCascade { if len(conf.ReferenceQuery) == 0 { conf.ReferenceQuery = []*ReferenceField{&ReferenceField{"_id", doc.GetId()}} } _, err := cascadeSaveWithConfig(conf, doc) if err != nil { return err } if conf.Nest { results := conf.Collection.Find(conf.Query) for results.Next(conf.Instance) { err = CascadeSave(conf.Collection, conf.Instance) if err != nil { return err } } } } } return nil }
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/lang/i18n.go#L28-L32
func Languages(tags []xlang.Tag) Option { return Option{func(o *options) { o.languages = tags }} }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/status.go#L30-L49
func NewStatus(router *Router) *Status { return &Status{ Protocol: Protocol, ProtocolMinVersion: int(router.ProtocolMinVersion), ProtocolMaxVersion: ProtocolMaxVersion, Encryption: router.usingPassword(), PeerDiscovery: router.PeerDiscovery, Name: router.Ourself.Name.String(), NickName: router.Ourself.NickName, Port: router.Port, Peers: makePeerStatusSlice(router.Peers), UnicastRoutes: makeUnicastRouteStatusSlice(router.Routes), BroadcastRoutes: makeBroadcastRouteStatusSlice(router.Routes), Connections: makeLocalConnectionStatusSlice(router.ConnectionMaker), TerminationCount: router.ConnectionMaker.terminationCount, Targets: router.ConnectionMaker.Targets(false), OverlayDiagnostics: router.Overlay.Diagnostics(), TrustedSubnets: makeTrustedSubnetsSlice(router.TrustedSubnets), } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L391-L394
func (p GetContentQuadsParams) WithNodeID(nodeID cdp.NodeID) *GetContentQuadsParams { p.NodeID = nodeID return &p }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_cluster.go#L82-L94
func (r *ProtocolLXD) GetClusterMembers() ([]api.ClusterMember, error) { if !r.HasExtension("clustering") { return nil, fmt.Errorf("The server is missing the required \"clustering\" API extension") } members := []api.ClusterMember{} _, err := r.queryStruct("GET", "/cluster/members?recursion=1", nil, "", &members) if err != nil { return nil, err } return members, nil }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/delete_apps_app_routes_route_parameters.go#L126-L129
func (o *DeleteAppsAppRoutesRouteParams) WithRoute(route string) *DeleteAppsAppRoutesRouteParams { o.SetRoute(route) return o }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/tide.go#L483-L517
func filterPR(ghc githubClient, sp *subpool, pr *PullRequest) bool { log := sp.log.WithFields(pr.logFields()) // Skip PRs that are known to be unmergeable. if pr.Mergeable == githubql.MergeableStateConflicting { log.Debug("filtering out PR as it is unmergeable") return true } // Filter out PRs with unsuccessful contexts unless the only unsuccessful // contexts are pending required prowjobs. contexts, err := headContexts(log, ghc, pr) if err != nil { log.WithError(err).Error("Getting head contexts.") return true } presubmitsHaveContext := func(context string) bool { for _, job := range sp.presubmits[int(pr.Number)] { if job.Context == context { return true } } return false } for _, ctx := range unsuccessfulContexts(contexts, sp.cc, log) { if ctx.State != githubql.StatusStatePending { log.WithField("context", ctx.Context).Debug("filtering out PR as unsuccessful context is not pending") return true } if !presubmitsHaveContext(string(ctx.Context)) { log.WithField("context", ctx.Context).Debug("filtering out PR as unsuccessful context is not Prow-controlled") return true } } return false }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/param_analyzer.go#L295-L298
func (p *ParamAnalyzer) parseParam(path string, param map[string]interface{}, child *gen.ActionParam) *gen.ActionParam { dType := p.parseDataType(path, child) return p.newParam(path, param, dType) }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/middleware.go#L90-L101
func (ms *MiddlewareStack) Replace(mw1 MiddlewareFunc, mw2 MiddlewareFunc) { m1k := funcKey(mw1) stack := []MiddlewareFunc{} for _, mw := range ms.stack { if funcKey(mw) == m1k { stack = append(stack, mw2) } else { stack = append(stack, mw) } } ms.stack = stack }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/matchers.go#L386-L388
func And(ms ...types.GomegaMatcher) types.GomegaMatcher { return &matchers.AndMatcher{Matchers: ms} }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2123-L2146
func (c *Client) UpdateTeamMembership(id int, user string, maintainer bool) (*TeamMembership, error) { c.log("UpdateTeamMembership", id, user, maintainer) if c.fake { return nil, nil } tm := TeamMembership{} if maintainer { tm.Role = RoleMaintainer } else { tm.Role = RoleMember } if c.dry { return &tm, nil } _, err := c.request(&request{ method: http.MethodPut, path: fmt.Sprintf("/teams/%d/memberships/%s", id, user), requestBody: &tm, exitCodes: []int{200}, }, &tm) return &tm, err }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/dwarf.go#L18-L201
func (p *Process) readDWARFTypes() { d, _ := p.proc.DWARF() // Make one of our own Types for each dwarf type. r := d.Reader() var types []*Type for e, err := r.Next(); e != nil && err == nil; e, err = r.Next() { if isNonGoCU(e) { r.SkipChildren() continue } switch e.Tag { case dwarf.TagArrayType, dwarf.TagPointerType, dwarf.TagStructType, dwarf.TagBaseType, dwarf.TagSubroutineType, dwarf.TagTypedef: dt, err := d.Type(e.Offset) if err != nil { continue } t := &Type{Name: gocoreName(dt), Size: dwarfSize(dt, p.proc.PtrSize())} p.dwarfMap[dt] = t types = append(types, t) } } p.runtimeNameMap = map[string][]*Type{} // Fill in fields of types. Postponed until now so we're sure // we have all the Types allocated and available. for dt, t := range p.dwarfMap { switch x := dt.(type) { case *dwarf.ArrayType: t.Kind = KindArray t.Elem = p.dwarfMap[x.Type] t.Count = x.Count case *dwarf.PtrType: t.Kind = KindPtr // unsafe.Pointer has a void base type. if _, ok := x.Type.(*dwarf.VoidType); !ok { t.Elem = p.dwarfMap[x.Type] } case *dwarf.StructType: t.Kind = KindStruct for _, f := range x.Field { fType := p.dwarfMap[f.Type] // Work around issue 21094. There's no guarantee that the // pointer type is in the DWARF, so just invent a Type. if strings.HasPrefix(t.Name, "sudog<") && f.Name == "elem" && strings.Count(t.Name, "*")+1 != strings.Count(gocoreName(f.Type), "*") { ptrName := "*" + gocoreName(f.Type) fType = &Type{Name: ptrName, Kind: KindPtr, Size: p.proc.PtrSize(), Elem: fType} p.runtimeNameMap[ptrName] = []*Type{fType} } t.Fields = append(t.Fields, Field{Name: f.Name, Type: fType, Off: f.ByteOffset}) } case *dwarf.BoolType: t.Kind = KindBool case *dwarf.IntType: t.Kind = KindInt case *dwarf.UintType: t.Kind = KindUint case *dwarf.FloatType: t.Kind = KindFloat case *dwarf.ComplexType: t.Kind = KindComplex case *dwarf.FuncType: t.Kind = KindFunc case *dwarf.TypedefType: // handle these types in the loop below default: panic(fmt.Sprintf("unknown type %s %T", dt, dt)) } } // Detect strings & slices for _, t := range types { if t.Kind != KindStruct { continue } if t.Name == "string" { // TODO: also "struct runtime.stringStructDWARF" ? t.Kind = KindString t.Elem = t.Fields[0].Type.Elem // TODO: check that it is always uint8. t.Fields = nil } if len(t.Name) >= 9 && t.Name[:9] == "struct []" || len(t.Name) >= 2 && t.Name[:2] == "[]" { t.Kind = KindSlice t.Elem = t.Fields[0].Type.Elem t.Fields = nil } } // Copy info from base types into typedefs. for dt, t := range p.dwarfMap { tt, ok := dt.(*dwarf.TypedefType) if !ok { continue } base := tt.Type // Walk typedef chain until we reach a non-typedef type. for { if x, ok := base.(*dwarf.TypedefType); ok { base = x.Type continue } break } bt := p.dwarfMap[base] // Copy type info from base. Everything except the name. name := t.Name *t = *bt t.Name = name // Detect some special types. If the base is some particular type, // then the alias gets marked as special. // We have aliases like: // interface {} -> struct runtime.eface // error -> struct runtime.iface // Note: the base itself does not get marked as special. // (Unlike strings and slices, where they do.) if bt.Name == "runtime.eface" { t.Kind = KindEface t.Fields = nil } if bt.Name == "runtime.iface" { t.Kind = KindIface t.Fields = nil } } // Make a runtime name -> Type map for existing DWARF types. for dt, t := range p.dwarfMap { name := runtimeName(dt) p.runtimeNameMap[name] = append(p.runtimeNameMap[name], t) } // Construct the runtime.specialfinalizer type. It won't be found // in DWARF before 1.10 because it does not appear in the type of any variable. // type specialfinalizer struct { // special special // fn *funcval // nret uintptr // fint *_type // ot *ptrtype // } if p.runtimeNameMap["runtime.specialfinalizer"] == nil { special := p.findType("runtime.special") p.runtimeNameMap["runtime.specialfinalizer"] = []*Type{ &Type{ Name: "runtime.specialfinalizer", Size: special.Size + 4*p.proc.PtrSize(), Kind: KindStruct, Fields: []Field{ Field{ Name: "special", Off: 0, Type: special, }, Field{ Name: "fn", Off: special.Size, Type: p.findType("*runtime.funcval"), }, Field{ Name: "nret", Off: special.Size + p.proc.PtrSize(), Type: p.findType("uintptr"), }, Field{ Name: "fint", Off: special.Size + 2*p.proc.PtrSize(), Type: p.findType("*runtime._type"), }, Field{ Name: "fn", Off: special.Size + 3*p.proc.PtrSize(), Type: p.findType("*runtime.ptrtype"), }, }, }, } } }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L173-L183
func newImageSource(sys *types.SystemContext, ref openshiftReference) (types.ImageSource, error) { client, err := newOpenshiftClient(ref) if err != nil { return nil, err } return &openshiftImageSource{ client: client, sys: sys, }, nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/docker_schema2.go#L159-L165
func Schema2FromManifest(manifest []byte) (*Schema2, error) { s2 := Schema2{} if err := json.Unmarshal(manifest, &s2); err != nil { return nil, err } return &s2, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3rpc/key.go#L181-L260
func checkIntervals(reqs []*pb.RequestOp) (map[string]struct{}, adt.IntervalTree, error) { var dels adt.IntervalTree // collect deletes from this level; build first to check lower level overlapped puts for _, req := range reqs { tv, ok := req.Request.(*pb.RequestOp_RequestDeleteRange) if !ok { continue } dreq := tv.RequestDeleteRange if dreq == nil { continue } var iv adt.Interval if len(dreq.RangeEnd) != 0 { iv = adt.NewStringAffineInterval(string(dreq.Key), string(dreq.RangeEnd)) } else { iv = adt.NewStringAffinePoint(string(dreq.Key)) } dels.Insert(iv, struct{}{}) } // collect children puts/deletes puts := make(map[string]struct{}) for _, req := range reqs { tv, ok := req.Request.(*pb.RequestOp_RequestTxn) if !ok { continue } putsThen, delsThen, err := checkIntervals(tv.RequestTxn.Success) if err != nil { return nil, dels, err } putsElse, delsElse, err := checkIntervals(tv.RequestTxn.Failure) if err != nil { return nil, dels, err } for k := range putsThen { if _, ok := puts[k]; ok { return nil, dels, rpctypes.ErrGRPCDuplicateKey } if dels.Intersects(adt.NewStringAffinePoint(k)) { return nil, dels, rpctypes.ErrGRPCDuplicateKey } puts[k] = struct{}{} } for k := range putsElse { if _, ok := puts[k]; ok { // if key is from putsThen, overlap is OK since // either then/else are mutually exclusive if _, isSafe := putsThen[k]; !isSafe { return nil, dels, rpctypes.ErrGRPCDuplicateKey } } if dels.Intersects(adt.NewStringAffinePoint(k)) { return nil, dels, rpctypes.ErrGRPCDuplicateKey } puts[k] = struct{}{} } dels.Union(delsThen, adt.NewStringAffineInterval("\x00", "")) dels.Union(delsElse, adt.NewStringAffineInterval("\x00", "")) } // collect and check this level's puts for _, req := range reqs { tv, ok := req.Request.(*pb.RequestOp_RequestPut) if !ok || tv.RequestPut == nil { continue } k := string(tv.RequestPut.Key) if _, ok := puts[k]; ok { return nil, dels, rpctypes.ErrGRPCDuplicateKey } if dels.Intersects(adt.NewStringAffinePoint(k)) { return nil, dels, rpctypes.ErrGRPCDuplicateKey } puts[k] = struct{}{} } return puts, dels, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L71-L77
func validateRepoName(name string) error { match, _ := regexp.MatchString("^[a-zA-Z0-9_-]+$", name) if !match { return fmt.Errorf("repo name (%v) invalid: only alphanumeric characters, underscores, and dashes are allowed", name) } return nil }
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/forwarder.go#L16-L18
func (f Forwarder) Email() string { return fmt.Sprintf("%s@%s", f.Name, f.Domain.Name) }
https://github.com/giantswarm/certctl/blob/2a6615f61499cd09a8d5ced9a5fade322d2de254/service/pki/service.go#L17-L31
func DefaultServiceConfig() ServiceConfig { newClientConfig := vaultclient.DefaultConfig() newClientConfig.Address = "http://127.0.0.1:8200" newVaultClient, err := vaultclient.NewClient(newClientConfig) if err != nil { panic(err) } newConfig := ServiceConfig{ // Dependencies. VaultClient: newVaultClient, } return newConfig }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqls/manager.go#L242-L287
func (w *workManager) loadRecursive(paths []string) { walkFn := func(path string, info os.FileInfo, err error) error { if err != nil { return nil } var isDir bool if info.IsDir() { isDir = true } else if info, err = os.Stat(path); err == nil && info.IsDir() { isDir = true } if isDir { if !Options.AllFiles { // Skip tranversing into hidden dirs if len(info.Name()) > 1 && strings.HasPrefix(info.Name(), ".") { return walk.SkipDir } } // Add the path to the input channel for sequence scanning w.inDirs <- path } return nil } dirs, seqs := preparePaths(paths) for _, s := range seqs { w.inSeqs <- s } for _, r := range dirs { r := r if err := walk.Walk(r, walkFn); err != nil { if err != walk.SkipDir { fmt.Fprintf(errOut, "%s %q: %s\n", ErrorPath, r, err) } } } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3735-L3739
func (v *GetFrameTreeReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage40(&r, v) return r.Error() }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/api_analyzer.go#L91-L93
func (reg *TypeRegistry) GetNamedType(name string) *gen.ObjectDataType { return reg.NamedTypes[toGoTypeName(name)] }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/request.go#L34-L44
func GetRequestEndpoint(r *http.Request) string { proto := r.Header.Get("X-Forwarded-Proto") if proto == "" { if r.TLS == nil { proto = "http" } else { proto = "https" } } return proto + "://" + r.Host }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L3632-L3636
func (v Media) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss31(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/relay.go#L223-L237
func (r *Relayer) Relay(f *Frame) error { if f.messageType() != messageTypeCallReq { err := r.handleNonCallReq(f) if err == errUnknownID { // This ID may be owned by an outgoing call, so check the outbound // message exchange, and if it succeeds, then the frame has been // handled successfully. if err := r.conn.outbound.forwardPeerFrame(f); err == nil { return nil } } return err } return r.handleCallReq(newLazyCallReq(f)) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/boskos.go#L246-L275
func handleRelease(r *ranch.Ranch) http.HandlerFunc { return func(res http.ResponseWriter, req *http.Request) { logrus.WithField("handler", "handleDone").Infof("From %v", req.RemoteAddr) if req.Method != http.MethodPost { msg := fmt.Sprintf("Method %v, /release only accepts POST.", req.Method) logrus.Warning(msg) http.Error(res, msg, http.StatusMethodNotAllowed) return } name := req.URL.Query().Get("name") dest := req.URL.Query().Get("dest") owner := req.URL.Query().Get("owner") if name == "" || dest == "" || owner == "" { msg := fmt.Sprintf("Name: %v, dest: %v, owner: %v, all of them must be set in the request.", name, dest, owner) logrus.Warning(msg) http.Error(res, msg, http.StatusBadRequest) return } if err := r.Release(name, dest, owner); err != nil { logrus.WithError(err).Errorf("Done failed: %v - %v (from %v)", name, dest, owner) http.Error(res, err.Error(), ErrorToStatus(err)) return } logrus.Infof("Done with resource %v, set to state %v", name, dest) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L3250-L3254
func (v *EventInspectRequested) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime29(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/member_command.go#L84-L96
func NewMemberListCommand() *cobra.Command { cc := &cobra.Command{ Use: "list", Short: "Lists all members in the cluster", Long: `When --write-out is set to simple, this command prints out comma-separated member lists for each endpoint. The items in the lists are ID, Status, Name, Peer Addrs, Client Addrs. `, Run: memberListCommandFunc, } return cc }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L598-L601
func (p NavigateParams) WithTransitionType(transitionType TransitionType) *NavigateParams { p.TransitionType = transitionType return &p }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/strkey/main.go#L102-L108
func MustEncode(version VersionByte, src []byte) string { e, err := Encode(version, src) if err != nil { panic(err) } return e }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/skus/m1small/m1small.go#L18-L23
func (s *SkuM1Small) PollForTasks() { if task, err := s.TaskManager.FindAndStallTaskForCaller(SkuName); err == nil { fmt.Println(task) } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1070-L1074
func (v GetBrowserContextsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget11(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/felixge/httpsnoop/blob/eadd4fad6aac69ae62379194fe0219f3dbc80fd3/capture_metrics.go#L28-L32
func CaptureMetrics(hnd http.Handler, w http.ResponseWriter, r *http.Request) Metrics { return CaptureMetricsFn(w, func(ww http.ResponseWriter) { hnd.ServeHTTP(ww, r) }) }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L913-L953
func saveDoc(src interface{}) (*pb.Document, error) { var err error var fields []Field var meta *DocumentMetadata switch x := src.(type) { case FieldLoadSaver: fields, meta, err = x.Save() default: fields, meta, err = saveStructWithMeta(src) } if err != nil { return nil, err } fieldsProto, err := fieldsToProto(fields) if err != nil { return nil, err } d := &pb.Document{ Field: fieldsProto, OrderId: proto.Int32(int32(time.Since(orderIDEpoch).Seconds())), OrderIdSource: pb.Document_DEFAULTED.Enum(), } if meta != nil { if meta.Rank != 0 { if !validDocRank(meta.Rank) { return nil, fmt.Errorf("search: invalid rank %d, must be [0, 2^31)", meta.Rank) } *d.OrderId = int32(meta.Rank) d.OrderIdSource = pb.Document_SUPPLIED.Enum() } if len(meta.Facets) > 0 { facets, err := facetsToProto(meta.Facets) if err != nil { return nil, err } d.Facet = facets } } return d, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L43-L46
func (p GrantPermissionsParams) WithBrowserContextID(browserContextID target.BrowserContextID) *GrantPermissionsParams { p.BrowserContextID = browserContextID return &p }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistriesv2/system_registries_v2.go#L335-L348
func FindUnqualifiedSearchRegistries(ctx *types.SystemContext) ([]Registry, error) { registries, err := GetRegistries(ctx) if err != nil { return nil, err } unqualified := []Registry{} for _, reg := range registries { if reg.Search { unqualified = append(unqualified, reg) } } return unqualified, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/states.go#L55-L62
func (a *ActiveState) ReceiveEvent(eventName, label string, t time.Time) (State, bool) { if a.exit.Match(eventName, label) { return &InactiveState{ entry: a.exit.Opposite(), }, true } return a, false }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1153-L1157
func (v ExposeDevToolsProtocolParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget12(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/EvaluableExpression.go#L44-L48
func NewEvaluableExpression(expression string) (*EvaluableExpression, error) { functions := make(map[string]ExpressionFunction) return NewEvaluableExpressionWithFunctions(expression, functions) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2603-L2607
func (s *reloadingTokenSource) Token() (*oauth2.Token, error) { return &oauth2.Token{ AccessToken: string(s.getToken()), }, nil }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/message.go#L98-L100
func (m *Message) SetHeader(field, value string) { m.Headers[field] = value }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nodetable/table.go#L96-L102
func (nt *NodeTable) Stats() string { return fmt.Sprintf("\nFastHTCount = %d\n"+ "SlowHTCount = %d\n"+ "Conflicts = %d\n"+ "MemoryInUse = %d\n", nt.fastHTCount, nt.slowHTCount, nt.conflicts, nt.MemoryInUse()) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L1332-L1336
func (v *QueryObjectsParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime13(&r, v) return r.Error() }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/types/publish_request.go#L44-L90
func (p *PublishRequest) Validate() error { p.Args = []string{} if len(p.PactURLs) != 0 { p.Args = append(p.Args, p.PactURLs...) } else { return fmt.Errorf("'PactURLs' is mandatory") } if p.BrokerUsername != "" { p.Args = append(p.Args, "--broker-username", p.BrokerUsername) } if p.BrokerPassword != "" { p.Args = append(p.Args, "--broker-password", p.BrokerPassword) } if p.PactBroker != "" && ((p.BrokerUsername == "" && p.BrokerPassword != "") || (p.BrokerUsername != "" && p.BrokerPassword == "")) { return errors.New("both 'BrokerUsername' and 'BrokerPassword' must be supplied if one given") } if p.PactBroker == "" { return fmt.Errorf("'PactBroker' is mandatory") } p.Args = append(p.Args, "--broker-base-url", p.PactBroker) if p.BrokerToken != "" { p.Args = append(p.Args, "--broker-token", p.BrokerToken) } if p.ConsumerVersion == "" { return fmt.Errorf("'ConsumerVersion' is mandatory") } p.Args = append(p.Args, "--consumer-app-version", p.ConsumerVersion) if len(p.Tags) > 0 { for _, t := range p.Tags { p.Args = append(p.Args, "--tag", t) } } if p.Verbose { p.Args = append(p.Args, "--verbose") } return nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L293-L295
func (u AccountId) GetEd25519() (result Uint256, ok bool) { return PublicKey(u).GetEd25519() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_cluster.go#L1111-L1136
func internalClusterPostPromote(d *Daemon, r *http.Request) Response { req := internalClusterPostPromoteRequest{} // Parse the request err := json.NewDecoder(r.Body).Decode(&req) if err != nil { return BadRequest(err) } // Sanity checks if len(req.RaftNodes) == 0 { return BadRequest(fmt.Errorf("No raft nodes provided")) } nodes := make([]db.RaftNode, len(req.RaftNodes)) for i, node := range req.RaftNodes { nodes[i].ID = node.ID nodes[i].Address = node.Address } err = cluster.Promote(d.State(), d.gateway, nodes) if err != nil { return SmartError(err) } return SyncResponse(true, nil) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L802-L810
func Count(state *state.State) (int, error) { var count int err := state.Cluster.Transaction(func(tx *db.ClusterTx) error { var err error count, err = tx.NodesCount() return err }) return count, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L1594-L1598
func (v LayoutTreeSnapshot) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomsnapshot6(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/scorredoira/email/blob/c1787f8317a847a7adc13673be80723268e6e639/email.go#L225-L227
func Send(addr string, auth smtp.Auth, m *Message) error { return smtp.SendMail(addr, auth, m.From.Address, m.Tolist(), m.Bytes()) }