_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/db.go#L33-L41
func (t *Int64) Scan(src interface{}) error { val, ok := src.(int64) if !ok { return errors.New("Invalid value for xdr.Int64") } *t = Int64(val) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L93-L97
func (v Resource) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoApplicationcache(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/innkeeperclient/ik_client.go#L55-L61
func (s *IkClient) GetStatus(requestID string) (resp *GetStatusResponse, err error) { resp = new(GetStatusResponse) qp := url.Values{} qp.Add(requestIDGetParam, requestID) err = s.Call(RouteGetStatus, qp, resp) return }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/structs.go#L71-L77
func (h *header) Decode(buf []byte) { h.klen = binary.BigEndian.Uint32(buf[0:4]) h.vlen = binary.BigEndian.Uint32(buf[4:8]) h.expiresAt = binary.BigEndian.Uint64(buf[8:16]) h.meta = buf[16] h.userMeta = buf[17] }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/resolver/endpoint/endpoint.go#L112-L127
func (b *builder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { if len(target.Authority) < 1 { return nil, fmt.Errorf("'etcd' target scheme requires non-empty authority identifying etcd cluster being routed to") } id := target.Authority es, err := b.getResolverGroup(id) if err != nil { return nil, fmt.Errorf("failed to build resolver: %v", err) } r := &Resolver{ endpointID: id, cc: cc, } es.addResolver(r) return r, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5223-L5231
func (u BucketEntry) ArmForSwitch(sw int32) (string, bool) { switch BucketEntryType(sw) { case BucketEntryTypeLiveentry: return "LiveEntry", true case BucketEntryTypeDeadentry: return "DeadEntry", true } return "-", false }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/fake_open_wrapper.go#L60-L65
func NewFakeOpenPluginWrapper(plugin Plugin) *FakeOpenPluginWrapper { return &FakeOpenPluginWrapper{ plugin: plugin, alreadyOpen: map[string]bool{}, } }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/release/boshrelease.go#L71-L79
func (r *BoshRelease) readBoshJob(jr io.Reader) (enaml.JobManifest, error) { var job enaml.JobManifest jw := pkg.NewTgzWalker(jr) jw.OnMatch("job.MF", func(file pkg.FileEntry) error { return decodeYaml(file.Reader, &job) }) err := jw.Walk() return job, err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2169-L2196
func (c *Client) ListTeamMembers(id int, role string) ([]TeamMember, error) { c.log("ListTeamMembers", id, role) if c.fake { return nil, nil } path := fmt.Sprintf("/teams/%d/members", id) var teamMembers []TeamMember err := c.readPaginatedResultsWithValues( path, url.Values{ "per_page": []string{"100"}, "role": []string{role}, }, // This accept header enables the nested teams preview. // https://developer.github.com/changes/2017-08-30-preview-nested-teams/ "application/vnd.github.hellcat-preview+json", func() interface{} { return &[]TeamMember{} }, func(obj interface{}) { teamMembers = append(teamMembers, *(obj.(*[]TeamMember))...) }, ) if err != nil { return nil, err } return teamMembers, nil }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_actions.go#L29-L36
func (s *Selection) Click() error { return s.forEachElement(func(selectedElement element.Element) error { if err := selectedElement.Click(); err != nil { return fmt.Errorf("failed to click on %s: %s", s, err) } return nil }) }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/compare.go#L552-L581
func (rc *recChecker) Check(p Path) { const minLen = 1 << 16 if rc.next == 0 { rc.next = minLen } if len(p) < rc.next { return } rc.next <<= 1 // Check whether the same transformer has appeared at least twice. var ss []string m := map[Option]int{} for _, ps := range p { if t, ok := ps.(Transform); ok { t := t.Option() if m[t] == 1 { // Transformer was used exactly once before tf := t.(*transformer).fnc.Type() ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0))) } m[t]++ } } if len(ss) > 0 { const warning = "recursive set of Transformers detected" const help = "consider using cmpopts.AcyclicTransformer" set := strings.Join(ss, "\n\t") panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help)) } }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L410-L413
func (m *Nitro) MemoryInUse() int64 { storeStats := m.aggrStoreStats() return storeStats.Memory + m.snapshots.MemoryInUse() + m.gcsnapshots.MemoryInUse() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1359-L1368
func (c *Client) GetSingleCommit(org, repo, SHA string) (SingleCommit, error) { c.log("GetSingleCommit", org, repo, SHA) var commit SingleCommit _, err := c.request(&request{ method: http.MethodGet, path: fmt.Sprintf("/repos/%s/%s/commits/%s", org, repo, SHA), exitCodes: []int{200}, }, &commit) return commit, err }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L105-L134
func (e *Envelope) AddressList(key string) ([]*mail.Address, error) { if e.header == nil { return nil, fmt.Errorf("No headers available") } if !AddressHeaders[strings.ToLower(key)] { return nil, fmt.Errorf("%s is not an address header", key) } str := decodeToUTF8Base64Header(e.header.Get(key)) if str == "" { return nil, mail.ErrHeaderNotPresent } // These statements are handy for debugging ParseAddressList errors // fmt.Println("in: ", m.header.Get(key)) // fmt.Println("out: ", str) ret, err := mail.ParseAddressList(str) switch { case err == nil: // carry on case err.Error() == "mail: expected comma": ret, err = mail.ParseAddressList(ensureCommaDelimitedAddresses(str)) if err != nil { return nil, err } default: return nil, err } return ret, nil }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L417-L432
func (g *Glg) AddStdLevel(tag string, mode MODE, isColor bool) *Glg { atomic.AddUint32(g.levelCounter, 1) lev := LEVEL(atomic.LoadUint32(g.levelCounter)) g.levelMap.Store(tag, lev) l := &logger{ writer: nil, std: os.Stdout, color: Colorless, isColor: isColor, mode: mode, tag: tag, } l.updateMode() g.logger.Store(lev, l) return g }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/volume.go#L258-L312
func volumeBind(w http.ResponseWriter, r *http.Request, t auth.Token) error { var bindInfo struct { App string MountPoint string ReadOnly bool NoRestart bool } err := ParseInput(r, &bindInfo) if err != nil { return err } dbVolume, err := volume.Load(r.URL.Query().Get(":name")) if err != nil { if err == volume.ErrVolumeNotFound { return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()} } return err } canBindVolume := permission.Check(t, permission.PermVolumeUpdateBind, contextsForVolume(dbVolume)...) if !canBindVolume { return permission.ErrUnauthorized } a, err := getAppFromContext(bindInfo.App, r) if err != nil { return err } canBindApp := permission.Check(t, permission.PermAppUpdateBindVolume, contextsForApp(&a)...) if !canBindApp { return permission.ErrUnauthorized } evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypeVolume, Value: dbVolume.Name}, Kind: permission.PermVolumeUpdateBind, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermVolumeReadEvents, contextsForVolume(dbVolume)...), }) if err != nil { return err } defer func() { evt.Done(err) }() err = dbVolume.BindApp(bindInfo.App, bindInfo.MountPoint, bindInfo.ReadOnly) if err != nil || bindInfo.NoRestart { if err == volume.ErrVolumeAlreadyBound { return &errors.HTTP{Code: http.StatusConflict, Message: err.Error()} } return err } w.Header().Set("Content-Type", "application/x-json-stream") keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "") defer keepAliveWriter.Stop() writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} evt.SetLogWriter(writer) return a.Restart("", evt) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/action_analysis.go#L244-L272
func (a *APIAnalyzer) ParseUrls(urls interface{}) ([]*gen.PathPattern, error) { var patterns []*gen.PathPattern if urlElems, ok := urls.([]interface{}); ok { patterns = make([]*gen.PathPattern, len(urlElems)) for i, elem := range urlElems { if pair, ok := elem.([]interface{}); ok { if len(pair) != 2 { return nil, fmt.Errorf("Invalid URL pair %v, must be [verb, path]", pair) } patterns[i] = toPattern(pair[0].(string), pair[1].(string)) } else if url, ok := elem.(map[string]interface{}); ok { verb, ok := url["verb"].(string) if !ok { return nil, fmt.Errorf("Missing verb in url %v", url) } path, ok := url["path"].(string) if !ok { return nil, fmt.Errorf("Missing path in url %v", url) } patterns[i] = toPattern(verb, path) } else { return nil, fmt.Errorf("Invalid url format %#v", elem) } } } else { return nil, fmt.Errorf("Invalid \"urls\" format %v", prettify(urls)) } return patterns, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/pfsdb/pfsdb.go#L52-L61
func Commits(etcdClient *etcd.Client, etcdPrefix string, repo string) col.Collection { return col.NewCollection( etcdClient, path.Join(etcdPrefix, commitsPrefix, repo), []*col.Index{ProvenanceIndex}, &pfs.CommitInfo{}, nil, nil, ) }
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/group.go#L18-L20
func (dom *Domain) Group(name string, members []*Account) *Group { return &Group{Domain: dom, Name: name, Members: members} }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2151-L2162
func (c *Client) RemoveTeamMembership(id int, user string) error { c.log("RemoveTeamMembership", id, user) if c.fake { return nil } _, err := c.request(&request{ method: http.MethodDelete, path: fmt.Sprintf("/teams/%d/memberships/%s", id, user), exitCodes: []int{204}, }, nil) return err }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/lookaside.go#L146-L176
func (config *registryConfiguration) signatureTopLevel(ref dockerReference, write bool) string { if config.Docker != nil { // Look for a full match. identity := ref.PolicyConfigurationIdentity() if ns, ok := config.Docker[identity]; ok { logrus.Debugf(` Using "docker" namespace %s`, identity) if url := ns.signatureTopLevel(write); url != "" { return url } } // Look for a match of the possible parent namespaces. for _, name := range ref.PolicyConfigurationNamespaces() { if ns, ok := config.Docker[name]; ok { logrus.Debugf(` Using "docker" namespace %s`, name) if url := ns.signatureTopLevel(write); url != "" { return url } } } } // Look for a default location if config.DefaultDocker != nil { logrus.Debugf(` Using "default-docker" configuration`) if url := config.DefaultDocker.signatureTopLevel(write); url != "" { return url } } logrus.Debugf(" No signature storage configuration found for %s", ref.PolicyConfigurationIdentity()) return "" }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/adapter.go#L45-L50
func AdapterOf(typ reflect.Type) (a Adapter, ok bool) { adapterMutex.RLock() a, ok = adapterStore[typ] adapterMutex.RUnlock() return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L701-L705
func (v GetTargetsReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget6(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/skus/m1small/types.go#L12-L23
func IsEnabled() bool { if appEnv, err := cfenv.Current(); err == nil { if taskService, err := appEnv.Services.WithName("innkeeper-service"); err == nil { if taskService.Credentials["enable"].(string) == "1" { return true } } } lo.G.Error("m1small not enabled") return false }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L82-L86
func (v *TakeHeapSnapshotParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeapprofiler(&r, v) return r.Error() }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/permission.go#L698-L726
func assignRoleToToken(w http.ResponseWriter, r *http.Request, t auth.Token) error { if !permission.Check(t, permission.PermRoleUpdateAssign) { return permission.ErrUnauthorized } tokenID := InputValue(r, "token_id") contextValue := InputValue(r, "context") roleName := r.URL.Query().Get(":name") evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypeRole, Value: roleName}, Kind: permission.PermRoleUpdateAssign, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermRoleReadEvents), }) if err != nil { return err } defer func() { evt.Done(err) }() err = canUseRole(t, roleName, contextValue) if err != nil { return err } err = servicemanager.TeamToken.AddRole(tokenID, roleName, contextValue) if err == authTypes.ErrTeamTokenNotFound { w.WriteHeader(http.StatusNotFound) return nil } return err }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/get_apps_app_routes_parameters.go#L77-L80
func (o *GetAppsAppRoutesParams) WithTimeout(timeout time.Duration) *GetAppsAppRoutesParams { o.SetTimeout(timeout) return o }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4214-L4223
func (u OperationResultTr) GetInflationResult() (result InflationResult, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "InflationResult" { result = *u.InflationResult ok = true } return }
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/french/step5.go#L9-L16
func step5(word *snowballword.SnowballWord) bool { suffix, _ := word.FirstSuffix("enn", "onn", "ett", "ell", "eill") if suffix != "" { word.RemoveLastNRunes(1) } return false }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/levels.go#L376-L378
func (l *levelHandler) isCompactable(delSize int64) bool { return l.getTotalSize()-delSize >= l.maxTotalSize }
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/garbler.go#L55-L78
func (g Garbler) password(req PasswordStrengthRequirements) (string, error) { //Step 1: Figure out settings letters := 0 mustGarble := 0 switch { case req.MaximumTotalLength > 0 && req.MaximumTotalLength > 6: letters = req.MaximumTotalLength - req.Digits - req.Punctuation case req.MaximumTotalLength > 0 && req.MaximumTotalLength <= 6: letters = req.MaximumTotalLength - req.Punctuation mustGarble = req.Digits case req.MinimumTotalLength > req.Digits+req.Punctuation+6: letters = req.MinimumTotalLength - req.Digits - req.Punctuation default: letters = req.MinimumTotalLength } if req.Uppercase > letters { letters = req.Uppercase } password := g.garbledSequence(letters, mustGarble) password = g.uppercase(password, req.Uppercase) password = g.addNums(password, req.Digits-mustGarble) password = g.punctuate(password, req.Punctuation) return password, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service.go#L266-L302
func grantServiceAccess(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { serviceName := r.URL.Query().Get(":service") s, err := getService(serviceName) if err != nil { return err } allowed := permission.Check(t, permission.PermServiceUpdateGrantAccess, contextsForServiceProvision(&s)..., ) if !allowed { return permission.ErrUnauthorized } teamName := r.URL.Query().Get(":team") team, err := servicemanager.Team.FindByName(teamName) if err != nil { if err == authTypes.ErrTeamNotFound { return &errors.HTTP{Code: http.StatusBadRequest, Message: "Team not found"} } return err } evt, err := event.New(&event.Opts{ Target: serviceTarget(s.Name), Kind: permission.PermServiceUpdateGrantAccess, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermServiceReadEvents, contextsForServiceProvision(&s)...), }) if err != nil { return err } defer func() { evt.Done(err) }() err = s.GrantAccess(team) if err != nil { return &errors.HTTP{Code: http.StatusConflict, Message: err.Error()} } return service.Update(s) }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L812-L820
func ShouldKeep(e bzl.Expr) bool { for _, c := range append(e.Comment().Before, e.Comment().Suffix...) { text := strings.TrimSpace(strings.TrimPrefix(c.Token, "#")) if text == "keep" { return true } } return false }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L739-L760
func (c *Client) ListOrgInvitations(org string) ([]OrgInvitation, error) { c.log("ListOrgInvitations", org) if c.fake { return nil, nil } path := fmt.Sprintf("/orgs/%s/invitations", org) var ret []OrgInvitation err := c.readPaginatedResults( path, acceptNone, func() interface{} { return &[]OrgInvitation{} }, func(obj interface{}) { ret = append(ret, *(obj.(*[]OrgInvitation))...) }, ) if err != nil { return nil, err } return ret, nil }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L58-L117
func (l *CachedByteCodeLoader) Load(key string) (bc *vm.ByteCode, err error) { defer func() { if bc != nil && err == nil && l.ShouldDumpByteCode() { fmt.Fprintf(os.Stderr, "%s\n", bc.String()) } }() var source TemplateSource if l.CacheLevel > CacheNone { var entity *CacheEntity for _, cache := range l.Caches { entity, err = cache.Get(key) if err == nil { break } } if err == nil { if l.CacheLevel == CacheNoVerify { return entity.ByteCode, nil } t, err := entity.Source.LastModified() if err != nil { return nil, errors.Wrap(err, "failed to get last-modified from source") } if t.Before(entity.ByteCode.GeneratedOn) { return entity.ByteCode, nil } // ByteCode validation failed, but we can still re-use source source = entity.Source } } if source == nil { source, err = l.Fetcher.FetchTemplate(key) if err != nil { return nil, errors.Wrap(err, "failed to fetch template") } } rdr, err := source.Reader() if err != nil { return nil, errors.Wrap(err, "failed to get the reader") } bc, err = l.LoadReader(key, rdr) if err != nil { return nil, errors.Wrap(err, "failed to read byte code") } entity := &CacheEntity{bc, source} for _, cache := range l.Caches { cache.Set(key, entity) } return bc, nil }
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L826-L830
func (p *PubSub) GetTopics() []string { out := make(chan []string, 1) p.getTopics <- &topicReq{resp: out} return <-out }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/skl/skl.go#L126-L135
func NewSkiplist(arenaSize int64) *Skiplist { arena := newArena(arenaSize) head := newNode(arena, nil, y.ValueStruct{}, maxHeight) return &Skiplist{ height: 1, head: head, arena: arena, ref: 1, } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/artifact-uploader/main.go#L91-L95
func (o *Options) AddFlags(flags *flag.FlagSet) { flags.IntVar(&o.NumWorkers, "num-workers", 25, "Number of threads to use for processing updates.") flags.StringVar(&o.ProwJobNamespace, "prow-job-ns", "", "Namespace containing ProwJobs.") o.Options.AddFlags(flags) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L378-L382
func (v SetSkipAllPausesParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger4(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/session.go#L18-L20
func (s *Session) Save() error { return s.Session.Save(s.req, s.res) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_pools.go#L270-L310
func storagePoolGet(d *Daemon, r *http.Request) Response { // If a target was specified, forward the request to the relevant node. response := ForwardedResponseIfTargetIsRemote(d, r) if response != nil { return response } poolName := mux.Vars(r)["name"] // Get the existing storage pool. poolID, pool, err := d.cluster.StoragePoolGet(poolName) if err != nil { return SmartError(err) } // Get all users of the storage pool. poolUsedBy, err := storagePoolUsedByGet(d.State(), poolID, poolName) if err != nil && err != db.ErrNoSuchObject { return SmartError(err) } pool.UsedBy = poolUsedBy targetNode := queryParam(r, "target") clustered, err := cluster.Enabled(d.db) if err != nil { return SmartError(err) } // If no target node is specified and the daemon is clustered, we omit // the node-specific fields. if targetNode == "" && clustered { for _, key := range db.StoragePoolNodeConfigKeys { delete(pool.Config, key) } } etag := []interface{}{pool.Name, pool.Driver, pool.Config} return SyncResponseETag(true, &pool, etag) }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/encoder.go#L82-L87
func EncodeUvarint(w io.Writer, u uint64) (err error) { var buf [10]byte n := binary.PutUvarint(buf[:], u) _, err = w.Write(buf[0:n]) return }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L383-L385
func (n *NetworkTransport) RequestVote(id ServerID, target ServerAddress, args *RequestVoteRequest, resp *RequestVoteResponse) error { return n.genericRPC(id, target, rpcRequestVote, args, resp) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L813-L828
func (c *Client) GetUserPermission(org, repo, user string) (string, error) { c.log("GetUserPermission", org, repo, user) var perm struct { Perm string `json:"permission"` } _, err := c.request(&request{ method: http.MethodGet, path: fmt.Sprintf("/repos/%s/%s/collaborators/%s/permission", org, repo, user), exitCodes: []int{200}, }, &perm) if err != nil { return "", err } return perm.Perm, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/manage_data.go#L38-L53
func (b *ManageDataBuilder) Mutate(muts ...interface{}) { for _, m := range muts { var err error switch mut := m.(type) { case OperationMutator: err = mut.MutateOperation(&b.O) default: err = errors.New("Mutator type not allowed") } if err != nil { b.Err = err return } } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/parse.go#L110-L128
func Parse(pkg *ast.Package, name string) (*Mapping, error) { str := findStruct(pkg.Scope, name) if str == nil { return nil, fmt.Errorf("No declaration found for %q", name) } fields, err := parseStruct(str) if err != nil { return nil, errors.Wrapf(err, "Failed to parse %q", name) } m := &Mapping{ Package: pkg.Name, Name: name, Fields: fields, } return m, nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/manifest.go#L85-L136
func GuessMIMEType(manifest []byte) string { // A subset of manifest fields; the rest is silently ignored by json.Unmarshal. // Also docker/distribution/manifest.Versioned. meta := struct { MediaType string `json:"mediaType"` SchemaVersion int `json:"schemaVersion"` Signatures interface{} `json:"signatures"` }{} if err := json.Unmarshal(manifest, &meta); err != nil { return "" } switch meta.MediaType { case DockerV2Schema2MediaType, DockerV2ListMediaType: // A recognized type. return meta.MediaType } // this is the only way the function can return DockerV2Schema1MediaType, and recognizing that is essential for stripping the JWS signatures = computing the correct manifest digest. switch meta.SchemaVersion { case 1: if meta.Signatures != nil { return DockerV2Schema1SignedMediaType } return DockerV2Schema1MediaType case 2: // best effort to understand if this is an OCI image since mediaType // isn't in the manifest for OCI anymore // for docker v2s2 meta.MediaType should have been set. But given the data, this is our best guess. ociMan := struct { Config struct { MediaType string `json:"mediaType"` } `json:"config"` Layers []imgspecv1.Descriptor `json:"layers"` }{} if err := json.Unmarshal(manifest, &ociMan); err != nil { return "" } if ociMan.Config.MediaType == imgspecv1.MediaTypeImageConfig && len(ociMan.Layers) != 0 { return imgspecv1.MediaTypeImageManifest } ociIndex := struct { Manifests []imgspecv1.Descriptor `json:"manifests"` }{} if err := json.Unmarshal(manifest, &ociIndex); err != nil { return "" } if len(ociIndex.Manifests) != 0 && ociIndex.Manifests[0].MediaType == imgspecv1.MediaTypeImageManifest { return imgspecv1.MediaTypeImageIndex } return DockerV2Schema2MediaType } return "" }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/pipeline/controller.go#L561-L587
func makePipelineGitResource(pj prowjobv1.ProwJob) *pipelinev1alpha1.PipelineResource { var revision string if pj.Spec.Refs != nil { if len(pj.Spec.Refs.Pulls) > 0 { revision = pj.Spec.Refs.Pulls[0].SHA } else { revision = pj.Spec.Refs.BaseSHA } } pr := pipelinev1alpha1.PipelineResource{ ObjectMeta: pipelineMeta(pj), Spec: pipelinev1alpha1.PipelineResourceSpec{ Type: pipelinev1alpha1.PipelineResourceTypeGit, Params: []pipelinev1alpha1.Param{ { Name: "url", Value: sourceURL(pj), }, { Name: "revision", Value: revision, }, }, }, } return &pr }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2664-L2668
func (v *GetIsolateIDReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime23(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/auth/auth.go#L185-L191
func IsErrInvalidPrincipal(err error) bool { if err == nil { return false } return strings.Contains(err.Error(), "invalid principal \"") && strings.Contains(err.Error(), "\"; must start with one of \"pipeline:\", \"github:\", or \"robot:\", or have no \":\"") }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/docker_schema1.go#L27-L33
func manifestSchema1FromComponents(ref reference.Named, fsLayers []manifest.Schema1FSLayers, history []manifest.Schema1History, architecture string) (genericManifest, error) { m, err := manifest.Schema1FromComponents(ref, fsLayers, history, architecture) if err != nil { return nil, err } return &manifestSchema1{m: m}, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L548-L553
func GetNodeForLocation(x int64, y int64) *GetNodeForLocationParams { return &GetNodeForLocationParams{ X: x, Y: y, } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/introspection.go#L413-L433
func (mexset *messageExchangeSet) IntrospectState(opts *IntrospectionOptions) ExchangeSetRuntimeState { mexset.RLock() setState := ExchangeSetRuntimeState{ Name: mexset.name, Count: len(mexset.exchanges), } if opts.IncludeExchanges { setState.Exchanges = make(map[string]ExchangeRuntimeState, len(mexset.exchanges)) for k, v := range mexset.exchanges { state := ExchangeRuntimeState{ ID: k, MessageType: v.msgType, } setState.Exchanges[strconv.Itoa(int(k))] = state } } mexset.RUnlock() return setState }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L708-L715
func SubScalarWithMask(src *IplImage, value Scalar, dst, mask *IplImage) { C.cvSubS( unsafe.Pointer(src), (C.CvScalar)(value), unsafe.Pointer(dst), unsafe.Pointer(mask), ) }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/object.go#L138-L159
func (p *Process) IsPtr(a core.Address) bool { h := p.findHeapInfo(a) if h != nil { return h.IsPtr(a, p.proc.PtrSize()) } for _, m := range p.modules { for _, s := range [2]string{"data", "bss"} { min := core.Address(m.r.Field(s).Uintptr()) max := core.Address(m.r.Field("e" + s).Uintptr()) if a < min || a >= max { continue } gc := m.r.Field("gc" + s + "mask").Field("bytedata").Address() i := a.Sub(min) return p.proc.ReadUint8(gc.Add(i/8))>>uint(i%8) != 0 } } // Everywhere else can't be a pointer. At least, not a pointer into the Go heap. // TODO: stacks? // TODO: finalizers? return false }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/load.go#L285-L296
func initField(val reflect.Value, index []int) reflect.Value { for _, i := range index[:len(index)-1] { val = val.Field(i) if val.Kind() == reflect.Ptr { if val.IsNil() { val.Set(reflect.New(val.Type().Elem())) } val = val.Elem() } } return val.Field(index[len(index)-1]) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L68-L78
func NewPolicyFromFile(fileName string) (*Policy, error) { contents, err := ioutil.ReadFile(fileName) if err != nil { return nil, err } policy, err := NewPolicyFromBytes(contents) if err != nil { return nil, errors.Wrapf(err, "invalid policy in %q", fileName) } return policy, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L279-L283
func (v *UpdateRegistrationParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoServiceworker1(&r, v) return r.Error() }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpclog/grpc.go#L95-L118
func StreamClientInterceptor(log ttnlog.Interface) grpc.StreamClientInterceptor { return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (stream grpc.ClientStream, err error) { log := getLog(log).WithField("method", method) log = log.WithFields(FieldsFromOutgoingContext(ctx)) log.Debug("rpc-client: stream starting") stream, err = streamer(ctx, desc, cc, method, opts...) if err != nil { if err == context.Canceled || grpc.Code(err) == codes.Canceled { log.Debug("rpc-client: stream canceled") return } log.WithError(err).Debug("rpc-client: stream failed") return } go func() { <-stream.Context().Done() if err := stream.Context().Err(); err != nil { log = log.WithError(err) } log.Debug("rpc-client: stream done") }() return } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2809-L2813
func (v PauseOnAsyncCallParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger29(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp_information_query.go#L20-L24
func (c *Client) RawInformationQuery(from, to, id, iqType, requestNamespace, body string) (string, error) { const xmlIQ = "<iq from='%s' to='%s' id='%s' type='%s'><query xmlns='%s'>%s</query></iq>" _, err := fmt.Fprintf(c.conn, xmlIQ, xmlEscape(from), xmlEscape(to), id, iqType, requestNamespace, body) return id, err }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L7177-L7186
func (u ScpStatementPledges) GetNominate() (result ScpNomination, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "Nominate" { result = *u.Nominate ok = true } return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/issue-creator/sources/triage-filer.go#L325-L333
func topClusters(clusters []*Cluster, count int) []*Cluster { less := func(i, j int) bool { return clusters[i].totalBuilds > clusters[j].totalBuilds } sort.SliceStable(clusters, less) if len(clusters) < count { count = len(clusters) } return clusters[0:count] }
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/float_array.go#L90-L167
func (b *TupleBuilder) PutFloat64Array(field string, value []float64) (wrote int, err error) { // field type should be if err = b.typeCheck(field, Float64ArrayField); err != nil { return 0, err } size := len(value) if size < math.MaxUint8 { if b.available() < size*8+2 { return 0, xbinary.ErrOutOfRange } // write length xbinary.LittleEndian.PutFloat64Array(b.buffer, b.pos+2, value) // write type code b.buffer[b.pos] = byte(DoubleArray8Code.OpCode) // write length b.buffer[b.pos+1] = byte(size) wrote += size + 2 } else if size < math.MaxUint16 { if b.available() < size*8+3 { return 0, xbinary.ErrOutOfRange } // write length xbinary.LittleEndian.PutUint16(b.buffer, b.pos+1, uint16(size)) // write value xbinary.LittleEndian.PutFloat64Array(b.buffer, b.pos+3, value) // write type code b.buffer[b.pos] = byte(DoubleArray16Code.OpCode) wrote += 3 + size } else if size < math.MaxUint32 { if b.available() < size*8+5 { return 0, xbinary.ErrOutOfRange } // write length xbinary.LittleEndian.PutUint32(b.buffer, b.pos+1, uint32(size)) // write value xbinary.LittleEndian.PutFloat64Array(b.buffer, b.pos+5, value) // write type code b.buffer[b.pos] = byte(DoubleArray32Code.OpCode) wrote += 5 + size } else { if b.available() < size*8+9 { return 0, xbinary.ErrOutOfRange } // write length xbinary.LittleEndian.PutUint64(b.buffer, b.pos+1, uint64(size)) // write value xbinary.LittleEndian.PutFloat64Array(b.buffer, b.pos+9, value) // write type code b.buffer[b.pos] = byte(DoubleArray64Code.OpCode) wrote += 9 + size } b.offsets[field] = b.pos b.pos += wrote return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L611-L616
func (t MonotonicTime) MarshalEasyJSON(out *jwriter.Writer) { v := float64(time.Time(t).Sub(*MonotonicTimeEpoch)) / float64(time.Second) out.Buffer.EnsureSpace(20) out.Buffer.Buf = strconv.AppendFloat(out.Buffer.Buf, v, 'f', -1, 64) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/file_snapshot.go#L296-L346
func (f *FileSnapshotStore) Open(id string) (*SnapshotMeta, io.ReadCloser, error) { // Get the metadata meta, err := f.readMeta(id) if err != nil { f.logger.Printf("[ERR] snapshot: Failed to get meta data to open snapshot: %v", err) return nil, nil, err } // Open the state file statePath := filepath.Join(f.path, id, stateFilePath) fh, err := os.Open(statePath) if err != nil { f.logger.Printf("[ERR] snapshot: Failed to open state file: %v", err) return nil, nil, err } // Create a CRC64 hash stateHash := crc64.New(crc64.MakeTable(crc64.ECMA)) // Compute the hash _, err = io.Copy(stateHash, fh) if err != nil { f.logger.Printf("[ERR] snapshot: Failed to read state file: %v", err) fh.Close() return nil, nil, err } // Verify the hash computed := stateHash.Sum(nil) if bytes.Compare(meta.CRC, computed) != 0 { f.logger.Printf("[ERR] snapshot: CRC checksum failed (stored: %v computed: %v)", meta.CRC, computed) fh.Close() return nil, nil, fmt.Errorf("CRC mismatch") } // Seek to the start if _, err := fh.Seek(0, 0); err != nil { f.logger.Printf("[ERR] snapshot: State file seek failed: %v", err) fh.Close() return nil, nil, err } // Return a buffered file buffered := &bufferedFile{ bh: bufio.NewReader(fh), fh: fh, } return &meta.SnapshotMeta, buffered, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L975-L980
func (c *Client) readPaginatedResults(path, accept string, newObj func() interface{}, accumulate func(interface{})) error { values := url.Values{ "per_page": []string{"100"}, } return c.readPaginatedResultsWithValues(path, values, accept, newObj, accumulate) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/memory.go#L145-L148
func (p StartSamplingParams) WithSamplingInterval(samplingInterval int64) *StartSamplingParams { p.SamplingInterval = samplingInterval return &p }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_client.go#L405-L412
func (c *dockerClient) makeRequest(ctx context.Context, method, path string, headers map[string][]string, stream io.Reader, auth sendAuth, extraScope *authScope) (*http.Response, error) { if err := c.detectProperties(ctx); err != nil { return nil, err } url := fmt.Sprintf("%s://%s%s", c.scheme, c.registry, path) return c.makeRequestToResolvedURL(ctx, method, url, headers, stream, -1, auth, extraScope) }
https://github.com/willf/pad/blob/eccfe5d84172e4f9dfd83fac9ed3a5f0eafbc2b4/utf8/pad.go#L19-L21
func Left(str string, len int, pad string) string { return times(pad, len-utf8.RuneCountInString(str)) + str }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L429-L501
func Rebalance(state *state.State, gateway *Gateway) (string, []db.RaftNode, error) { // First get the current raft members, since this method should be // called after a node has left. currentRaftNodes, err := gateway.currentRaftNodes() if err != nil { return "", nil, errors.Wrap(err, "failed to get current raft nodes") } if len(currentRaftNodes) >= membershipMaxRaftNodes { // We're already at full capacity. return "", nil, nil } currentRaftAddresses := make([]string, len(currentRaftNodes)) for i, node := range currentRaftNodes { currentRaftAddresses[i] = node.Address } // Check if we have a spare node that we can turn into a database one. address := "" err = state.Cluster.Transaction(func(tx *db.ClusterTx) error { config, err := ConfigLoad(tx) if err != nil { return errors.Wrap(err, "failed load cluster configuration") } nodes, err := tx.Nodes() if err != nil { return errors.Wrap(err, "failed to get cluster nodes") } // Find a node that is not part of the raft cluster yet. for _, node := range nodes { if shared.StringInSlice(node.Address, currentRaftAddresses) { continue // This is already a database node } if node.IsOffline(config.OfflineThreshold()) { continue // This node is offline } logger.Debugf( "Found spare node %s (%s) to be promoted as database node", node.Name, node.Address) address = node.Address break } return nil }) if err != nil { return "", nil, err } if address == "" { // No node to promote return "", nil, nil } // Update the local raft_table adding the new member and building a new // list. updatedRaftNodes := currentRaftNodes err = gateway.db.Transaction(func(tx *db.NodeTx) error { id, err := tx.RaftNodeAdd(address) if err != nil { return errors.Wrap(err, "failed to add new raft node") } updatedRaftNodes = append(updatedRaftNodes, db.RaftNode{ID: id, Address: address}) err = tx.RaftNodesReplace(updatedRaftNodes) if err != nil { return errors.Wrap(err, "failed to update raft nodes") } return nil }) if err != nil { return "", nil, err } return address, updatedRaftNodes, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1567-L1596
func (app *App) SetEnvs(setEnvs bind.SetEnvArgs) error { if len(setEnvs.Envs) == 0 { return nil } for _, env := range setEnvs.Envs { err := validateEnv(env.Name) if err != nil { return err } } if setEnvs.Writer != nil { fmt.Fprintf(setEnvs.Writer, "---- Setting %d new environment variables ----\n", len(setEnvs.Envs)) } for _, env := range setEnvs.Envs { app.setEnv(env) } conn, err := db.Conn() if err != nil { return err } defer conn.Close() err = conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$set": bson.M{"env": app.Env}}) if err != nil { return err } if setEnvs.ShouldRestart { return app.restartIfUnits(setEnvs.Writer) } return nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1497-L1501
func GetHashTreeTag(pachClient *client.APIClient, storageRoot string, treeRef *pfs.Tag) (HashTree, error) { return getHashTree(storageRoot, func(w io.Writer) error { return pachClient.GetTag(treeRef.Name, w) }) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/obj.go#L466-L491
func ParseURL(urlStr string) (*ObjectStoreURL, error) { url, err := url.Parse(urlStr) if err != nil { return nil, fmt.Errorf("error parsing url %v: %v", urlStr, err) } switch url.Scheme { case "s3", "gcs", "gs", "local": return &ObjectStoreURL{ Store: url.Scheme, Bucket: url.Host, Object: strings.Trim(url.Path, "/"), }, nil case "as", "wasb": // In Azure, the first part of the path is the container name. parts := strings.Split(strings.Trim(url.Path, "/"), "/") if len(parts) < 1 { return nil, fmt.Errorf("malformed Azure URI: %v", urlStr) } return &ObjectStoreURL{ Store: url.Scheme, Bucket: parts[0], Object: strings.Trim(path.Join(parts[1:]...), "/"), }, nil } return nil, fmt.Errorf("unrecognized object store: %s", url.Scheme) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/easyjson.go#L1269-L1273
func (v *DispatchMouseEventParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoInput8(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/fuse/file.go#L164-L170
func (c *counter) wait(n int64) { c.mu.Lock() defer c.mu.Unlock() for c.n < n { c.cond.Wait() } }
https://github.com/omniscale/go-mapnik/blob/710dfcc5e486e5760d0a5c46be909d91968e1ffb/mapnik.go#L140-L143
func (m *Map) Free() { C.mapnik_map_free(m.m) m.m = nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_pools.go#L72-L88
func (r *ProtocolLXD) CreateStoragePool(pool api.StoragePoolsPost) error { if !r.HasExtension("storage") { return fmt.Errorf("The server is missing the required \"storage\" API extension") } if pool.Driver == "ceph" && !r.HasExtension("storage_driver_ceph") { return fmt.Errorf("The server is missing the required \"storage_driver_ceph\" API extension") } // Send the request _, _, err := r.query("POST", "/storage-pools", pool, "") if err != nil { return err } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L186-L201
func (f *Field) ZeroValue() string { if f.Type.Code != TypeColumn { panic("attempt to get zero value of non-column field") } switch f.Type.Name { case "string": return `""` case "int": // FIXME: we use -1 since at the moment integer criteria are // required to be positive. return "-1" default: panic("unsupported zero value") } }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L814-L821
func (db *DB) isAutoIncrementable(field *reflect.StructField) bool { switch field.Type.Kind() { case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: return true } return false }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/tide.go#L296-L301
func (tqs TideQueries) QueryMap() *QueryMap { return &QueryMap{ queries: tqs, cache: make(map[string]TideQueries), } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/domdebugger.go#L191-L196
func SetDOMBreakpoint(nodeID cdp.NodeID, typeVal DOMBreakpointType) *SetDOMBreakpointParams { return &SetDOMBreakpointParams{ NodeID: nodeID, Type: typeVal, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/easyjson.go#L1018-L1022
func (v EventListener) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomdebugger10(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L6560-L6564
func (v *CollectClassNamesReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss61(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/srv/srv.go#L133-L142
func GetSRVService(service, serviceName string, scheme string) (SRVService string) { if scheme == "https" { service = fmt.Sprintf("%s-ssl", service) } if serviceName != "" { return fmt.Sprintf("%s-%s", service, serviceName) } return service }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L591-L641
func (p *Pact) VerifyMessageProviderRaw(request VerifyMessageRequest) (types.ProviderVerifierResponse, error) { p.Setup(false) response := types.ProviderVerifierResponse{} // Starts the message wrapper API with hooks back to the message handlers // This maps the 'description' field of a message pact, to a function handler // that will implement the message producer. This function must return an object and optionally // and error. The object will be marshalled to JSON for comparison. mux := http.NewServeMux() port, err := utils.GetFreePort() if err != nil { return response, fmt.Errorf("unable to allocate a port for verification: %v", err) } // Construct verifier request verificationRequest := types.VerifyRequest{ ProviderBaseURL: fmt.Sprintf("http://localhost:%d", port), PactURLs: request.PactURLs, BrokerURL: request.BrokerURL, Tags: request.Tags, BrokerUsername: request.BrokerUsername, BrokerPassword: request.BrokerPassword, BrokerToken: request.BrokerToken, PublishVerificationResults: request.PublishVerificationResults, ProviderVersion: request.ProviderVersion, Provider: p.Provider, } mux.HandleFunc("/", messageVerificationHandler(request.MessageHandlers, request.StateHandlers)) ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { log.Fatal(err) } defer ln.Close() log.Printf("[DEBUG] API handler starting: port %d (%s)", port, ln.Addr()) go http.Serve(ln, mux) portErr := waitForPort(port, "tcp", "localhost", p.ClientTimeout, fmt.Sprintf(`Timed out waiting for pact proxy on port %d - check for errors`, port)) if portErr != nil { log.Fatal("Error:", err) return response, portErr } log.Println("[DEBUG] pact provider verification") return p.pactClient.VerifyProvider(verificationRequest) }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/region.go#L62-L67
func (r region) Uint64() uint64 { if r.typ.Kind != KindUint || r.typ.Size != 8 { panic("bad uint64 type " + r.typ.Name) } return r.p.proc.ReadUint64(r.a) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction_envelope.go#L38-L48
func (b *TransactionEnvelopeBuilder) Mutate(muts ...TransactionEnvelopeMutator) { b.Init() for _, m := range muts { err := m.MutateTransactionEnvelope(b) if err != nil { b.Err = err return } } }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/channel/channel.go#L51-L58
func Send(c context.Context, clientID, message string) error { req := &pb.SendMessageRequest{ ApplicationKey: &clientID, Message: &message, } resp := &basepb.VoidProto{} return remapError(internal.Call(c, service, "SendChannelMessage", req, resp)) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L362-L365
func (e AssetType) ValidEnum(v int32) bool { _, ok := assetTypeMap[v] return ok }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistries/system_registries.go#L72-L78
func GetRegistries(sys *types.SystemContext) ([]string, error) { config, err := loadRegistryConf(sys) if err != nil { return nil, err } return config.Registries.Search.Registries, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps.go#L157-L162
func NewPipelineInput(repoName string, glob string) *pps.PipelineInput { return &pps.PipelineInput{ Repo: NewRepo(repoName), Glob: glob, } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L7232-L7234
func (api *API) PermissionLocator(href string) *PermissionLocator { return &PermissionLocator{Href(href), api} }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1054-L1078
func (c *Client) GetPullRequests(org, repo string) ([]PullRequest, error) { c.log("GetPullRequests", org, repo) var prs []PullRequest if c.fake { return prs, nil } path := fmt.Sprintf("/repos/%s/%s/pulls", org, repo) err := c.readPaginatedResults( path, // allow the description and draft fields // https://developer.github.com/changes/2018-02-22-label-description-search-preview/ // https://developer.github.com/changes/2019-02-14-draft-pull-requests/ "application/vnd.github.symmetra-preview+json, application/vnd.github.shadow-cat-preview", func() interface{} { return &[]PullRequest{} }, func(obj interface{}) { prs = append(prs, *(obj.(*[]PullRequest))...) }, ) if err != nil { return nil, err } return prs, err }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L500-L508
func (u Asset) MustAlphaNum12() AssetAlphaNum12 { val, ok := u.GetAlphaNum12() if !ok { panic("arm AlphaNum12 is not set") } return val }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/inbound.go#L367-L372
func (response *InboundCallResponse) Arg2Writer() (ArgWriter, error) { if err := NewArgWriter(response.arg1Writer()).Write(nil); err != nil { return nil, err } return response.arg2Writer() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/build/main.go#L109-L129
func newBuildConfig(cfg rest.Config, stop chan struct{}) (*buildConfig, error) { bc, err := buildset.NewForConfig(&cfg) if err != nil { return nil, err } // Ensure the knative-build CRD is deployed // TODO(fejta): probably a better way to do this _, err = bc.BuildV1alpha1().Builds("").List(metav1.ListOptions{Limit: 1}) if err != nil { return nil, err } // Assume watches receive updates, but resync every 30m in case something wonky happens bif := buildinfo.NewSharedInformerFactory(bc, 30*time.Minute) bif.Build().V1alpha1().Builds().Lister() go bif.Start(stop) return &buildConfig{ client: bc, informer: bif.Build().V1alpha1().Builds(), }, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L1354-L1358
func (v *NameValuePair) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoHar7(&r, v) return r.Error() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L251-L253
func NewClient(getToken func() []byte, graphqlEndpoint string, bases ...string) *Client { return NewClientWithFields(logrus.Fields{}, getToken, graphqlEndpoint, bases...) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L5328-L5332
func (v *CallArgument) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime49(&r, v) return r.Error() }