_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L2054-L2059
|
func (o *ListInt16Option) Set(value string) error {
val := Int16Option{}
val.Set(value)
*o = append(*o, val)
return nil
}
|
https://github.com/skyrings/skyring-common/blob/d1c0bb1cbd5ed8438be1385c85c4f494608cde1e/provisioner/provision_provider.go#L43-L50
|
func RegisterProvider(name string, factory ProvidersFactory) {
providersMutex.Lock()
defer providersMutex.Unlock()
if _, found := providers[name]; found {
logger.Get().Critical("Auth provider %s was registered twice", name)
}
providers[name] = factory
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/client/client.go#L169-L190
|
func (c *Client) AcquireByStateWait(ctx context.Context, state, dest string, names []string) ([]common.Resource, error) {
if ctx == nil {
return nil, ErrContextRequired
}
// Try to acquire the resource(s) until available or the context is
// cancelled or its deadline exceeded.
for {
r, err := c.AcquireByState(state, dest, names)
if err != nil {
if err == ErrAlreadyInUse || err == ErrNotFound {
select {
case <-ctx.Done():
return nil, err
case <-time.After(3 * time.Second):
continue
}
}
return nil, err
}
return r, nil
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/client/client.go#L128-L149
|
func (c *Client) AcquireWait(ctx context.Context, rtype, state, dest string) (*common.Resource, error) {
if ctx == nil {
return nil, ErrContextRequired
}
// Try to acquire the resource until available or the context is
// cancelled or its deadline exceeded.
for {
r, err := c.Acquire(rtype, state, dest)
if err != nil {
if err == ErrAlreadyInUse || err == ErrNotFound {
select {
case <-ctx.Done():
return nil, err
case <-time.After(3 * time.Second):
continue
}
}
return nil, err
}
return r, nil
}
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L486-L511
|
func (v *VM) Screenshot() ([]byte, error) {
var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE
var err C.VixError = C.VIX_OK
var byteCount C.int
var screenBits C.char
jobHandle = C.VixVM_CaptureScreenImage(v.handle,
C.VIX_CAPTURESCREENFORMAT_PNG,
C.VIX_INVALID_HANDLE,
nil,
nil)
defer C.Vix_ReleaseHandle(jobHandle)
err = C.get_screenshot_bytes(jobHandle, &byteCount, &screenBits)
defer C.Vix_FreeBuffer(unsafe.Pointer(&screenBits))
if C.VIX_OK != err {
return nil, &Error{
Operation: "vm.Screenshot",
Code: int(err & 0xFFFF),
Text: C.GoString(C.Vix_GetErrorText(err, nil)),
}
}
return C.GoBytes(unsafe.Pointer(&screenBits), byteCount), nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L189-L201
|
func newVariableDumpClient(c *http.Client) HTTPClient {
dc := &dumpClient{Client: c}
dc.isInsecure = func() bool {
return Insecure
}
dc.dumpFormat = func() Format {
return DumpFormat
}
dc.hiddenHeaders = func() map[string]bool {
return HiddenHeaders
}
return dc
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L1070-L1074
|
func (v SetSamplingIntervalParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoProfiler13(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/entrypoint/run.go#L76-L89
|
func (o Options) Run() int {
code, err := o.ExecuteProcess()
if err != nil {
logrus.WithError(err).Error("Error executing test process")
}
if err := o.mark(code); err != nil {
logrus.WithError(err).Error("Error writing exit code to marker file")
return InternalErrorCode // we need to mark the real error code to safely return AlwaysZero
}
if o.AlwaysZero {
return 0
}
return code
}
|
https://github.com/r3labs/sse/blob/2f90368216802092e9ed520c43e974e11d50438d/server.go#L43-L51
|
func (s *Server) Close() {
s.mu.Lock()
defer s.mu.Unlock()
for id := range s.Streams {
s.Streams[id].quit <- true
delete(s.Streams, id)
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/peer.go#L323-L329
|
func (p *peer) Resume() {
p.mu.Lock()
defer p.mu.Unlock()
p.paused = false
p.msgAppReader.resume()
p.msgAppV2Reader.resume()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1319-L1323
|
func (v *EventTargetDestroyed) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget14(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L2041-L2045
|
func (v GetBestEffortCoverageParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoProfiler20(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L560-L564
|
func (v *RunScriptReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime5(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.go#L55-L64
|
func (c *ClusterTx) ProjectNames() ([]string, error) {
stmt := "SELECT name FROM projects"
names, err := query.SelectStrings(c.tx, stmt)
if err != nil {
return nil, errors.Wrap(err, "Fetch project names")
}
return names, nil
}
|
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/utils/utils.go#L58-L64
|
func Getopt(name, dfault string) string {
value := os.Getenv(name)
if value == "" {
value = dfault
}
return value
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/dry_run_client.go#L70-L72
|
func (c *dryRunProwJobClient) DeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) error {
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L234-L236
|
func (c APIClient) BlockCommit(repoName string, commitID string) (*pfs.CommitInfo, error) {
return c.inspectCommit(repoName, commitID, pfs.CommitState_FINISHED)
}
|
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L27-L41
|
func (now *Now) BeginningOfWeek() time.Time {
t := now.BeginningOfDay()
weekday := int(t.Weekday())
if WeekStartDay != time.Sunday {
weekStartDayInt := int(WeekStartDay)
if weekday < weekStartDayInt {
weekday = weekday + 7 - weekStartDayInt
} else {
weekday = weekday - weekStartDayInt
}
}
return t.AddDate(0, 0, -weekday)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/peribolos/main.go#L564-L683
|
func configureTeams(client teamClient, orgName string, orgConfig org.Config, maxDelta float64, ignoreSecretTeams bool) (map[string]github.Team, error) {
if err := validateTeamNames(orgConfig); err != nil {
return nil, err
}
// What teams exist?
ids := map[int]github.Team{}
ints := sets.Int{}
teamList, err := client.ListTeams(orgName)
if err != nil {
return nil, fmt.Errorf("failed to list teams: %v", err)
}
logrus.Debugf("Found %d teams", len(teamList))
for _, t := range teamList {
if ignoreSecretTeams && org.Privacy(t.Privacy) == org.Secret {
continue
}
ids[t.ID] = t
ints.Insert(t.ID)
}
if ignoreSecretTeams {
logrus.Debugf("Found %d non-secret teams", len(teamList))
}
// What is the lowest ID for each team?
older := map[string][]github.Team{}
names := map[string]github.Team{}
for _, t := range ids {
logger := logrus.WithFields(logrus.Fields{"id": t.ID, "name": t.Name})
n := t.Name
switch val, ok := names[n]; {
case !ok: // first occurrence of the name
logger.Debug("First occurrence of this team name.")
names[n] = t
case ok && t.ID < val.ID: // t has the lower ID, replace and send current to older set
logger.Debugf("Replacing previous recorded team (%d) with this one due to smaller ID.", val.ID)
names[n] = t
older[n] = append(older[n], val)
default: // t does not have smallest id, add it to older set
logger.Debugf("Adding team to older set as a smaller ID is already recoded for it.", val.ID)
older[n] = append(older[n], val)
}
}
// What team are we using for each configured name, and which names are missing?
matches := map[string]github.Team{}
missing := map[string]org.Team{}
used := sets.Int{}
var match func(teams map[string]org.Team)
match = func(teams map[string]org.Team) {
for name, orgTeam := range teams {
logger := logrus.WithField("name", name)
match(orgTeam.Children)
t := findTeam(names, name, orgTeam.Previously...)
if t == nil {
missing[name] = orgTeam
logger.Debug("Could not find team in GitHub for this configuration.")
continue
}
matches[name] = *t // t.Name != name if we matched on orgTeam.Previously
logger.WithField("id", t.ID).Debug("Found a team in GitHub for this configuration.")
used.Insert(t.ID)
}
}
match(orgConfig.Teams)
// First compute teams we will delete, ensure we are not deleting too many
unused := ints.Difference(used)
if delta := float64(len(unused)) / float64(len(ints)); delta > maxDelta {
return nil, fmt.Errorf("cannot delete %d teams or %.3f of %s teams (exceeds limit of %.3f)", len(unused), delta, orgName, maxDelta)
}
// Create any missing team names
var failures []string
for name, orgTeam := range missing {
t := &github.Team{Name: name}
if orgTeam.Description != nil {
t.Description = *orgTeam.Description
}
if orgTeam.Privacy != nil {
t.Privacy = string(*orgTeam.Privacy)
}
t, err := client.CreateTeam(orgName, *t)
if err != nil {
logrus.WithError(err).Warnf("Failed to create %s in %s", name, orgName)
failures = append(failures, name)
continue
}
matches[name] = *t
// t.ID may include an ID already present in ints if other actors are deleting teams.
used.Insert(t.ID)
}
if n := len(failures); n > 0 {
return nil, fmt.Errorf("failed to create %d teams: %s", n, strings.Join(failures, ", "))
}
// Remove any IDs returned by CreateTeam() that are in the unused set.
if reused := unused.Intersection(used); len(reused) > 0 {
// Logically possible for:
// * another actor to delete team N after the ListTeams() call
// * github to reuse team N after someone deleted it
// Therefore used may now include IDs in unused, handle this situation.
logrus.Warnf("Will not delete %d team IDs reused by github: %v", len(reused), reused.List())
unused = unused.Difference(reused)
}
// Delete undeclared teams.
for id := range unused {
if err := client.DeleteTeam(id); err != nil {
str := fmt.Sprintf("%d(%s)", id, ids[id].Name)
logrus.WithError(err).Warnf("Failed to delete team %s from %s", str, orgName)
failures = append(failures, str)
}
}
if n := len(failures); n > 0 {
return nil, fmt.Errorf("failed to delete %d teams: %s", n, strings.Join(failures, ", "))
}
// Return matches
return matches, nil
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L230-L234
|
func (eC2Manager *EC2Manager) GetPrices() (*ListOfPrices, error) {
cd := tcclient.Client(*eC2Manager)
responseObject, _, err := (&cd).APICall(nil, "GET", "/prices", new(ListOfPrices), nil)
return responseObject.(*ListOfPrices), err
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/cmd/tsurud/checker.go#L125-L147
|
func checkRouter() error {
defaultRouter, _ := config.GetString("docker:router")
if defaultRouter == "" {
return errors.Errorf(`You must configure a default router in "docker:router".`)
}
isHipacheOld := false
if defaultRouter == "hipache" {
hipacheOld, _ := config.Get("hipache")
isHipacheOld = hipacheOld != nil
}
routerConf, _ := config.Get("routers:" + defaultRouter)
if isHipacheOld {
return config.NewWarning(`Setting "hipache:*" config entries is deprecated. You should configure your router with "routers:*". See http://docs.tsuru.io/en/latest/reference/config.html#routers for more details.`)
}
if routerConf == nil {
return errors.Errorf(`You must configure your default router %q in "routers:%s".`, defaultRouter, defaultRouter)
}
routerType, _ := config.Get("routers:" + defaultRouter + ":type")
if routerType == nil {
return errors.Errorf(`You must configure your default router type in "routers:%s:type".`, defaultRouter)
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L321-L325
|
func (v *RequestCachedResponseReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCachestorage2(&r, v)
return r.Error()
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L19-L36
|
func NewFrameSet(frange string) (*FrameSet, error) {
// Process the frame range and get a slice of match slices
matches, err := frameRangeMatches(frange)
if err != nil {
return nil, err
}
frameSet := &FrameSet{frange, &ranges.InclusiveRanges{}}
// Process each slice match and add it to the frame set
for _, match := range matches {
if err = frameSet.handleMatch(match); err != nil {
return nil, err
}
}
return frameSet, nil
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/tracer.go#L294-L299
|
func (t Tag) Apply(o *StartSpanOptions) {
if o.Tags == nil {
o.Tags = make(map[string]interface{})
}
o.Tags[t.Key] = t.Value
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L364-L367
|
func (e *EnumerableDataType) IsEquivalent(other DataType) bool {
_, ok := other.(*EnumerableDataType)
return ok
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/httputil/response.go#L20-L25
|
func (w responseWriterBinder) Write(p []byte) (int, error) {
for _, f := range w.before {
f(p)
}
return w.Writer.Write(p)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/tide.go#L520-L528
|
func poolPRMap(subpoolMap map[string]*subpool) map[string]PullRequest {
prs := make(map[string]PullRequest)
for _, sp := range subpoolMap {
for _, pr := range sp.prs {
prs[prKey(&pr)] = pr
}
}
return prs
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L1030-L1032
|
func (c *restConfig) HasCertAuth() bool {
return len(c.CertData) != 0 || len(c.CertFile) != 0
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/domain_redirect.go#L17-L76
|
func DomainRedirectHandler(h http.Handler, domain, httpsPort string) http.Handler {
if domain == "" && httpsPort == "" {
return h
}
scheme := "http"
port := ""
if httpsPort != "" {
if _, err := strconv.Atoi(httpsPort); err == nil {
scheme = "https"
port = httpsPort
}
if _, p, err := net.SplitHostPort(httpsPort); err == nil {
scheme = "https"
port = p
}
}
if port == "443" {
port = ""
}
var altDomain string
if strings.HasPrefix("www.", domain) {
altDomain = strings.TrimPrefix(domain, "www.")
} else {
altDomain = "www." + domain
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
d, p, err := net.SplitHostPort(r.Host)
if err != nil {
d = r.Host
}
rs := r.URL.Scheme
if fs := r.Header.Get("X-Forwarded-Proto"); fs != "" {
rs = strings.ToLower(fs)
}
s := scheme
if rs == "https" {
s = "https"
}
if d == domain && rs == s {
h.ServeHTTP(w, r)
return
}
switch {
case s == "http" && p == "80":
p = ""
case s == "https" && p == "443":
p = ""
case port != "":
p = ":" + port
case p != "":
p = ":" + p
}
if d == altDomain {
http.Redirect(w, r, strings.Join([]string{s, "://", domain, p, r.RequestURI}, ""), http.StatusMovedPermanently)
return
}
http.Redirect(w, r, strings.Join([]string{s, "://", domain, p, r.RequestURI}, ""), http.StatusFound)
})
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/recovery/recovery.go#L55-L57
|
func WithLogFunc(logf func(format string, a ...interface{})) Option {
return func(o *Handler) { o.logf = logf }
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L9724-L9731
|
func (r *Route) Locator(api *API) *RouteLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.RouteLocator(l["href"])
}
}
return nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1227-L1234
|
func NewLedgerEntryExt(v int32, value interface{}) (result LedgerEntryExt, err error) {
result.V = v
switch int32(v) {
case 0:
// void
}
return
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/displayer.go#L93-L99
|
func (d *Displayer) ApplyHeaderExtract(header string) error {
d.RawOutput = d.response.Header.Get(header)
if d.RawOutput == "" {
return fmt.Errorf("Response does not contain the '%s' header", header)
}
return nil
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/outgoing.go#L188-L191
|
func (oa *OutgoingAudio) SetTitle(to string) *OutgoingAudio {
oa.Title = to
return oa
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/manifest.go#L67-L73
|
func manifestLayerInfosToBlobInfos(layers []manifest.LayerInfo) []types.BlobInfo {
blobs := make([]types.BlobInfo, len(layers))
for i, layer := range layers {
blobs[i] = layer.BlobInfo
}
return blobs
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3138-L3142
|
func (v *GetRelayoutBoundaryParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom35(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L431-L440
|
func (p *GetIsolateIDParams) Do(ctx context.Context) (id string, err error) {
// execute
var res GetIsolateIDReturns
err = cdp.Execute(ctx, CommandGetIsolateID, nil, &res)
if err != nil {
return "", err
}
return res.ID, nil
}
|
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/garbler.go#L129-L142
|
func (g Garbler) punctuate(p string, numPunc int) string {
if numPunc <= 0 {
return p
}
ret := p
for i := 0; i < numPunc; i++ {
if i%2 == 0 {
ret += string(Punctuation[randInt(len(Punctuation))])
} else {
ret = string(Punctuation[randInt(len(Punctuation))]) + ret
}
}
return ret
}
|
https://github.com/codemodus/kace/blob/e3ecf78ee2a5e58652cb2be34d3159ad9c89acf8/kace.go#L105-L107
|
func (k *Kace) SnakeUpper(s string) string {
return delimitedCase(s, snakeDelim, true)
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcgithub/tcgithub.go#L166-L170
|
func (github *Github) Repository(owner, repo string) (*RepositoryResponse, error) {
cd := tcclient.Client(*github)
responseObject, _, err := (&cd).APICall(nil, "GET", "/repository/"+url.QueryEscape(owner)+"/"+url.QueryEscape(repo), new(RepositoryResponse), nil)
return responseObject.(*RepositoryResponse), err
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcawsprovisioner/tcawsprovisioner.go#L269-L273
|
func (awsProvisioner *AwsProvisioner) CreateSecret(token string, payload *SecretRequest) error {
cd := tcclient.Client(*awsProvisioner)
_, _, err := (&cd).APICall(payload, "PUT", "/secret/"+url.QueryEscape(token), nil, nil)
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L299-L304
|
func (a RepoAliases) ExpandAlias(alias string) sets.String {
if a == nil {
return nil
}
return a[github.NormLogin(alias)]
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1147-L1154
|
func NewFilter(numTrees int64, tree int64) Filter {
return func(k []byte) bool {
if pathToTree(k, numTrees) == uint64(tree) {
return true
}
return false
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/key_index.go#L256-L269
|
func (ki *keyIndex) keep(atRev int64, available map[revision]struct{}) {
if ki.isEmpty() {
return
}
genIdx, revIndex := ki.doCompact(atRev, available)
g := &ki.generations[genIdx]
if !g.isEmpty() {
// remove any tombstone
if revIndex == len(g.revs)-1 && genIdx != len(ki.generations)-1 {
delete(available, g.revs[revIndex])
}
}
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L240-L242
|
func (s *MockHeritageClient) CreateAuthRequest(verb, requestURL, path string, args interface{}) (*http.Request, error) {
return &http.Request{}, nil
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/cmd/viewcore/main.go#L180-L194
|
func useLine(c *cobra.Command) string {
var useline string
if c.HasParent() {
useline = commandPath(c.Parent()) + " " + c.Use
} else {
useline = c.Use
}
if c.DisableFlagsInUseLine {
return useline
}
if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {
useline += " [flags]"
}
return useline
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L237-L239
|
func (p *EmulateNetworkConditionsParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandEmulateNetworkConditions, p, nil)
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer_name_hash.go#L47-L53
|
func (name PeerName) bytes() []byte {
res, err := hex.DecodeString(string(name))
if err != nil {
panic("unable to decode name to bytes: " + name)
}
return res
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L882-L885
|
func (p AddBindingParams) WithExecutionContextID(executionContextID ExecutionContextID) *AddBindingParams {
p.ExecutionContextID = executionContextID
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L139-L142
|
func (p EvaluateOnCallFrameParams) WithObjectGroup(objectGroup string) *EvaluateOnCallFrameParams {
p.ObjectGroup = objectGroup
return &p
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcsecrets/tcsecrets.go#L101-L105
|
func (secrets *Secrets) Ping() error {
cd := tcclient.Client(*secrets)
_, _, err := (&cd).APICall(nil, "GET", "/ping", nil, nil)
return err
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/log_unstable.go#L35-L40
|
func (u *unstable) maybeFirstIndex() (uint64, bool) {
if u.snapshot != nil {
return u.snapshot.Metadata.Index + 1, true
}
return 0, false
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L323-L325
|
func SetMulti(c context.Context, item []*Item) error {
return set(c, item, nil, pb.MemcacheSetRequest_SET)
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/web/server.go#L173-L175
|
func (mux *LoggingServeMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
mux.serveMux.Handle(pattern, http.HandlerFunc(handler))
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L69-L79
|
func VerifyBasicAuth(username string, password string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
auth := req.Header.Get("Authorization")
Expect(auth).ShouldNot(Equal(""), "Authorization header must be specified")
decoded, err := base64.StdEncoding.DecodeString(auth[6:])
Expect(err).ShouldNot(HaveOccurred())
Expect(string(decoded)).Should(Equal(fmt.Sprintf("%s:%s", username, password)), "Authorization mismatch")
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_transport.go#L174-L177
|
func (ref dirReference) layerPath(digest digest.Digest) string {
// FIXME: Should we keep the digest identification?
return filepath.Join(ref.path, digest.Hex())
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/relay.go#L511-L540
|
func (r *Relayer) failRelayItem(items *relayItems, id uint32, failure string) {
item, ok := items.Get(id)
if !ok {
items.logger.WithFields(LogField{"id", id}).Warn("Attempted to fail non-existent relay item.")
return
}
// The call could time-out right as we entomb it, which would cause spurious
// error logs, so ensure we can stop the timeout.
if !item.timeout.Stop() {
return
}
// Entomb it so that we don't get unknown exchange errors on further frames
// for this call.
item, ok = items.Entomb(id, _relayTombTTL)
if !ok {
return
}
if item.call != nil {
// If the client is too slow, then there's no point sending an error frame.
if failure != _relayErrorSourceConnSlow {
r.conn.SendSystemError(id, item.span, errFrameNotSent)
}
item.call.Failed(failure)
item.call.End()
}
r.decrementPending()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/dry_run_client.go#L55-L57
|
func (c *dryRunProwJobClient) Update(*prowapi.ProwJob) (*prowapi.ProwJob, error) {
return nil, nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/unparsed.go#L44-L67
|
func (i *UnparsedImage) Manifest(ctx context.Context) ([]byte, string, error) {
if i.cachedManifest == nil {
m, mt, err := i.src.GetManifest(ctx, i.instanceDigest)
if err != nil {
return nil, "", err
}
// ImageSource.GetManifest does not do digest verification, but we do;
// this immediately protects also any user of types.Image.
if digest, haveDigest := i.expectedManifestDigest(); haveDigest {
matches, err := manifest.MatchesDigest(m, digest)
if err != nil {
return nil, "", errors.Wrap(err, "Error computing manifest digest")
}
if !matches {
return nil, "", errors.Errorf("Manifest does not match provided manifest digest %s", digest)
}
}
i.cachedManifest = m
i.cachedManifestMIMEType = mt
}
return i.cachedManifest, i.cachedManifestMIMEType, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/trigger/trigger.go#L250-L262
|
func skipRequested(c Client, pr *github.PullRequest, skippedJobs []config.Presubmit) error {
var errors []error
for _, job := range skippedJobs {
if job.SkipReport {
continue
}
c.Logger.Infof("Skipping %s build.", job.Name)
if err := c.GitHubClient.CreateStatus(pr.Base.Repo.Owner.Login, pr.Base.Repo.Name, pr.Head.SHA, skippedStatusFor(job.Context)); err != nil {
errors = append(errors, err)
}
}
return errorutil.NewAggregate(errors...)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L335-L415
|
func (c *ClusterTx) ProfileConfigRef(filter ProfileFilter) (map[string]map[string]map[string]string, error) {
// Result slice.
objects := make([]struct {
Project string
Name string
Key string
Value string
}, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Project != "" {
criteria["Project"] = filter.Project
}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Project"] != nil && criteria["Name"] != nil {
stmt = c.stmt(profileConfigRefByProjectAndName)
args = []interface{}{
filter.Project,
filter.Name,
}
} else if criteria["Project"] != nil {
stmt = c.stmt(profileConfigRefByProject)
args = []interface{}{
filter.Project,
}
} else {
stmt = c.stmt(profileConfigRef)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, struct {
Project string
Name string
Key string
Value string
}{})
return []interface{}{
&objects[i].Project,
&objects[i].Name,
&objects[i].Key,
&objects[i].Value,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch ref for profiles")
}
// Build index by primary name.
index := map[string]map[string]map[string]string{}
for _, object := range objects {
_, ok := index[object.Project]
if !ok {
subIndex := map[string]map[string]string{}
index[object.Project] = subIndex
}
item, ok := index[object.Project][object.Name]
if !ok {
item = map[string]string{}
}
index[object.Project][object.Name] = item
item[object.Key] = object.Value
}
return index, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/types.go#L30-L32
|
func (t PressureLevel) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/quota/quota.go#L62-L77
|
func (s *QuotaService) Set(appName string, inUse int) error {
q, err := s.Storage.Get(appName)
if err != nil {
return err
}
if inUse < 0 {
return quota.ErrLessThanZero
}
if !q.IsUnlimited() && inUse > q.Limit {
return "a.QuotaExceededError{
Requested: uint(inUse),
Available: uint(q.Limit),
}
}
return s.Storage.Set(appName, inUse)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L147-L150
|
func (p CallFunctionOnParams) WithAwaitPromise(awaitPromise bool) *CallFunctionOnParams {
p.AwaitPromise = awaitPromise
return &p
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L105-L143
|
func (r *ProtocolLXD) GetPrivateImageFile(fingerprint string, secret string, req ImageFileRequest) (*ImageFileResponse, error) {
// Sanity checks
if req.MetaFile == nil && req.RootfsFile == nil {
return nil, fmt.Errorf("No file requested")
}
uri := fmt.Sprintf("/1.0/images/%s/export", url.QueryEscape(fingerprint))
var err error
uri, err = r.setQueryAttributes(uri)
if err != nil {
return nil, err
}
// Attempt to download from host
if secret == "" && shared.PathExists("/dev/lxd/sock") && os.Geteuid() == 0 {
unixURI := fmt.Sprintf("http://unix.socket%s", uri)
// Setup the HTTP client
devlxdHTTP, err := unixHTTPClient(nil, "/dev/lxd/sock")
if err == nil {
resp, err := lxdDownloadImage(fingerprint, unixURI, r.httpUserAgent, devlxdHTTP, req)
if err == nil {
return resp, nil
}
}
}
// Build the URL
uri = fmt.Sprintf("%s%s", r.httpHost, uri)
if secret != "" {
uri, err = setQueryParam(uri, "secret", secret)
if err != nil {
return nil, err
}
}
return lxdDownloadImage(fingerprint, uri, r.httpUserAgent, r.http, req)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L174-L177
|
func (p ContinueRequestParams) WithMethod(method string) *ContinueRequestParams {
p.Method = method
return &p
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/wip/wip-label.go#L115-L130
|
func handle(gc githubClient, le *logrus.Entry, e *event) error {
needsLabel := e.draft || titleRegex.MatchString(e.title)
if needsLabel && !e.hasLabel {
if err := gc.AddLabel(e.org, e.repo, e.number, labels.WorkInProgress); err != nil {
le.Warnf("error while adding Label %q: %v", labels.WorkInProgress, err)
return err
}
} else if !needsLabel && e.hasLabel {
if err := gc.RemoveLabel(e.org, e.repo, e.number, labels.WorkInProgress); err != nil {
le.Warnf("error while removing Label %q: %v", labels.WorkInProgress, err)
return err
}
}
return nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/channel.go#L635-L652
|
func (ch *Channel) addConnection(c *Connection, direction connectionDirection) bool {
ch.mutable.Lock()
defer ch.mutable.Unlock()
if c.readState() != connectionActive {
return false
}
switch state := ch.mutable.state; state {
case ChannelClient, ChannelListening:
break
default:
return false
}
ch.mutable.conns[c.connID] = c
return true
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L135-L137
|
func (f *FakeClient) ListIssueEvents(owner, repo string, number int) ([]github.ListedIssueEvent, error) {
return append([]github.ListedIssueEvent{}, f.IssueEvents[number]...), nil
}
|
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/assetfs/filesystem.go#L65-L74
|
func (fs *AssetFileSystem) Glob(pattern string) (matches []string, err error) {
for _, pth := range fs.paths {
if results, err := filepath.Glob(filepath.Join(pth, pattern)); err == nil {
for _, result := range results {
matches = append(matches, strings.TrimPrefix(result, pth))
}
}
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3304-L3308
|
func (v *GetOuterHTMLParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom37(&r, v)
return r.Error()
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L796-L801
|
func (db *DB) hasSkipTag(field *reflect.StructField) bool {
if field.Tag.Get(dbTag) == skipTag {
return true
}
return false
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L775-L777
|
func (g *Glg) Success(val ...interface{}) error {
return g.out(OK, blankFormat(len(val)), val...)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L836-L839
|
func (p ReloadParams) WithScriptToEvaluateOnLoad(scriptToEvaluateOnLoad string) *ReloadParams {
p.ScriptToEvaluateOnLoad = scriptToEvaluateOnLoad
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L401-L410
|
func (p *EvaluateParams) Do(ctx context.Context) (result *RemoteObject, exceptionDetails *ExceptionDetails, err error) {
// execute
var res EvaluateReturns
err = cdp.Execute(ctx, CommandEvaluate, p, &res)
if err != nil {
return nil, nil, err
}
return res.Result, res.ExceptionDetails, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L11610-L11617
|
func (r *ServerArray) Locator(api *API) *ServerArrayLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.ServerArrayLocator(l["href"])
}
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3782-L3786
|
func (v GetFrameTreeParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage41(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/auth.go#L470-L534
|
func teamInfo(w http.ResponseWriter, r *http.Request, t auth.Token) error {
teamName := r.URL.Query().Get(":name")
team, err := servicemanager.Team.FindByName(teamName)
if err != nil {
return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
canRead := permission.Check(t, permission.PermTeamRead)
if !canRead {
return permission.ErrUnauthorized
}
apps, err := app.List(&app.Filter{
Extra: map[string][]string{"teams": {team.Name}},
TeamOwner: team.Name})
if err != nil {
return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
pools, err := pool.ListPoolsForTeam(team.Name)
if err != nil {
return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
users, err := auth.ListUsers()
if err != nil {
return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
cachedRoles := make(map[string]permission.Role)
includedUsers := make([]*apiUser, 0)
for _, user := range users {
for _, roleInstance := range user.Roles {
role, ok := cachedRoles[roleInstance.Name]
if !ok {
roleFound, err := permission.FindRole(roleInstance.Name)
if err != nil {
return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
cachedRoles[roleInstance.Name] = roleFound
role = cachedRoles[roleInstance.Name]
}
if role.ContextType == permTypes.CtxGlobal || (role.ContextType == permTypes.CtxTeam && roleInstance.ContextValue == team.Name) {
canInclude := permission.Check(t, permission.PermTeam)
if canInclude {
roleMap := make(map[string]*permission.Role)
perms, err := t.Permissions()
if err != nil {
return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
userData, err := createAPIUser(perms, &user, roleMap, canInclude)
if err != nil {
return &errors.HTTP{Code: http.StatusInternalServerError, Message: err.Error()}
}
includedUsers = append(includedUsers, userData)
break
}
}
}
}
result := map[string]interface{}{
"name": team.Name,
"tags": team.Tags,
"users": includedUsers,
"pools": pools,
"apps": apps,
}
w.Header().Set("Content-Type", "application/json")
return json.NewEncoder(w).Encode(result)
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/location.go#L55-L60
|
func (c *Client) GetLocation(locid string) (*Location, error) {
url := locationPath(locid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Location{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L74-L153
|
func NewFileSequencePad(sequence string, style PadStyle) (*FileSequence, error) {
var dir, basename, pad, ext string
var frameSet *FrameSet
var err error
// Determine which style of padding to use
padder, ok := padders[style]
if !ok {
padder = defaultPadding
}
parts := splitPattern.FindStringSubmatch(sequence)
if len(parts) == 0 {
// If no match at this point, we are dealing with a possible
// path that contains no range. Maybe a single frame or no frame.
for _, pad := range defaultPadding.AllChars() {
if strings.Contains(sequence, pad) {
return nil, fmt.Errorf("Failed to parse sequence: %s", sequence)
}
}
// We assume the sequence is just a single file path, containing
// no frame patterns
dir, basename = filepath.Split(sequence)
idx := strings.LastIndex(basename, ".")
if idx > -1 {
basename, ext = basename[:idx], basename[idx:]
}
if dir == "" && basename == "" && ext != "" {
// Just assume all we have is a file extension
} else {
// Try to see if we can at least find a specific frame
// number, a la .<frame>.ext
parts = singleFrame.FindStringSubmatch(sequence)
if len(parts) > 0 {
frameStr := parts[2]
frameSet, err = NewFrameSet(frameStr)
if err != nil {
frameSet = nil
} else {
// Reparse the dir/basename to not include the trailing frame
dir, basename = filepath.Split(parts[1])
// Calculate the padding chars
pad = padder.PaddingChars(len(strings.TrimSpace(frameStr)))
}
ext = parts[3]
}
}
} else {
// We are dealing with a pattern containing a frame range
frameSet, err = NewFrameSet(parts[2])
if err != nil {
frameSet = nil
}
dir, basename = filepath.Split(parts[1])
pad = parts[3]
ext = parts[4]
}
seq := &FileSequence{
basename: basename,
dir: dir,
ext: ext,
padChar: pad,
zfill: 0, // Fill will be calculated after SetPadding()
frameSet: frameSet,
padMapper: padder,
}
seq.SetPadding(pad)
return seq, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L942-L983
|
func UpdateNodeStatus(nodeData provision.NodeStatusData) ([]UpdateUnitsResult, error) {
node, findNodeErr := findNodeForNodeData(nodeData)
var nodeAddresses []string
if findNodeErr == nil {
nodeAddresses = []string{node.Address()}
} else {
nodeAddresses = nodeData.Addrs
}
if healer.HealerInstance != nil {
err := healer.HealerInstance.UpdateNodeData(nodeAddresses, nodeData.Checks)
if err != nil {
log.Errorf("[update node status] unable to set node status in healer: %s", err)
}
}
if findNodeErr == provision.ErrNodeNotFound {
counterNodesNotFound.Inc()
log.Errorf("[update node status] node not found with nodedata: %#v", nodeData)
result := make([]UpdateUnitsResult, len(nodeData.Units))
for i, unitData := range nodeData.Units {
result[i] = UpdateUnitsResult{ID: unitData.ID, Found: false}
}
return result, nil
}
if findNodeErr != nil {
return nil, findNodeErr
}
unitProv, ok := node.Provisioner().(provision.UnitStatusProvisioner)
if !ok {
return []UpdateUnitsResult{}, nil
}
result := make([]UpdateUnitsResult, len(nodeData.Units))
for i, unitData := range nodeData.Units {
unit := provision.Unit{ID: unitData.ID, Name: unitData.Name}
err := unitProv.SetUnitStatus(unit, unitData.Status)
_, isNotFound := err.(*provision.UnitNotFoundError)
if err != nil && !isNotFound {
return nil, err
}
result[i] = UpdateUnitsResult{ID: unitData.ID, Found: !isNotFound}
}
return result, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L106-L116
|
func (c APIClient) ListRepo() ([]*pfs.RepoInfo, error) {
request := &pfs.ListRepoRequest{}
repoInfos, err := c.PfsAPIClient.ListRepo(
c.Ctx(),
request,
)
if err != nil {
return nil, grpcutil.ScrubGRPC(err)
}
return repoInfos.RepoInfo, nil
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L297-L305
|
func (g *Glg) SetPrefix(pref string) *Glg {
v, ok := g.logger.Load(PRINT)
if ok {
value := v.(*logger)
value.tag = pref
g.logger.Store(PRINT, value)
}
return g
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/state/state.go#L23-L31
|
func NewState(node *db.Node, cluster *db.Cluster, maas *maas.Controller, os *sys.OS, endpoints *endpoints.Endpoints) *State {
return &State{
Node: node,
Cluster: cluster,
MAAS: maas,
OS: os,
Endpoints: endpoints,
}
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L79-L81
|
func (s *selectable) FindByLink(text string) *Selection {
return newSelection(s.session, s.selectors.Append(target.Link, text).Single())
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/membership/cluster.go#L117-L134
|
func (c *RaftCluster) MemberByName(name string) *Member {
c.Lock()
defer c.Unlock()
var memb *Member
for _, m := range c.members {
if m.Name == name {
if memb != nil {
if c.lg != nil {
c.lg.Panic("two member with same name found", zap.String("name", name))
} else {
plog.Panicf("two members with the given name %q exist", name)
}
}
memb = m
}
}
return memb.Clone()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/oci.go#L40-L48
|
func OCI1FromComponents(config imgspecv1.Descriptor, layers []imgspecv1.Descriptor) *OCI1 {
return &OCI1{
imgspecv1.Manifest{
Versioned: specs.Versioned{SchemaVersion: 2},
Config: config,
Layers: layers,
},
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/api.go#L712-L722
|
func (r *Raft) RemovePeer(peer ServerAddress) Future {
if r.protocolVersion > 2 {
return errorFuture{ErrUnsupportedProtocol}
}
return r.requestConfigChange(configurationChangeRequest{
command: RemoveServer,
serverID: ServerID(peer),
prevIndex: 0,
}, 0)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L715-L798
|
func List(state *state.State) ([]api.ClusterMember, error) {
addresses := []string{} // Addresses of database nodes
err := state.Node.Transaction(func(tx *db.NodeTx) error {
nodes, err := tx.RaftNodes()
if err != nil {
return errors.Wrap(err, "failed to fetch current raft nodes")
}
for _, node := range nodes {
addresses = append(addresses, node.Address)
}
return nil
})
if err != nil {
return nil, err
}
var nodes []db.NodeInfo
var offlineThreshold time.Duration
err = state.Cluster.Transaction(func(tx *db.ClusterTx) error {
nodes, err = tx.Nodes()
if err != nil {
return err
}
offlineThreshold, err = tx.NodeOfflineThreshold()
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
result := make([]api.ClusterMember, len(nodes))
now := time.Now()
version := nodes[0].Version()
for i, node := range nodes {
result[i].ServerName = node.Name
result[i].URL = fmt.Sprintf("https://%s", node.Address)
result[i].Database = shared.StringInSlice(node.Address, addresses)
if node.IsOffline(offlineThreshold) {
result[i].Status = "Offline"
result[i].Message = fmt.Sprintf(
"no heartbeat since %s", now.Sub(node.Heartbeat))
} else {
result[i].Status = "Online"
result[i].Message = "fully operational"
}
n, err := util.CompareVersions(version, node.Version())
if err != nil {
result[i].Status = "Broken"
result[i].Message = "inconsistent version"
continue
}
if n == 1 {
// This node's version is lower, which means the
// version that the previous node in the loop has been
// upgraded.
version = node.Version()
}
}
// Update the state of online nodes that have been upgraded and whose
// schema is more recent than the rest of the nodes.
for i, node := range nodes {
if result[i].Status != "Online" {
continue
}
n, err := util.CompareVersions(version, node.Version())
if err != nil {
continue
}
if n == 2 {
result[i].Status = "Blocked"
result[i].Message = "waiting for other nodes to be upgraded"
}
}
return result, nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4894-L4902
|
func (u LedgerUpgrade) MustNewMaxTxSetSize() Uint32 {
val, ok := u.GetNewMaxTxSetSize()
if !ok {
panic("arm NewMaxTxSetSize is not set")
}
return val
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/client.go#L280-L287
|
func (c *Client) Dial(ep string) (*grpc.ClientConn, error) {
creds := c.directDialCreds(ep)
// Use the grpc passthrough resolver to directly dial a single endpoint.
// This resolver passes through the 'unix' and 'unixs' endpoints schemes used
// by etcd without modification, allowing us to directly dial endpoints and
// using the same dial functions that we use for load balancer dialing.
return c.dial(fmt.Sprintf("passthrough:///%s", ep), creds)
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L39-L127
|
func (s *FrameSet) handleMatch(match []string) error {
switch len(match) {
// Single frame match
case 1:
f, err := parseInt(match[0])
if err != nil {
return err
}
s.rangePtr.AppendUnique(f, f, 1)
// Simple frame range
case 2:
start, err := parseInt(match[0])
if err != nil {
return err
}
end, err := parseInt(match[1])
if err != nil {
return err
}
// Handle descending frame ranges, like 10-1
var inc int
if start > end {
inc = -1
} else {
inc = 1
}
s.rangePtr.AppendUnique(start, end, inc)
// Complex frame range
case 4:
var (
err error
mod string
start, end, chunk int
)
chunk, err = parseInt(match[3])
if err != nil {
return err
}
if chunk == 0 {
return fmt.Errorf("Failed to parse part of range %v. "+
"Encountered invalid 0 value", match[3])
}
if start, err = parseInt(match[0]); err != nil {
return err
}
if end, err = parseInt(match[1]); err != nil {
return err
}
if mod = match[2]; !isModifier(mod) {
return fmt.Errorf("%q is not one of the valid modifier 'xy:'", mod)
}
switch mod {
case `x`:
s.rangePtr.AppendUnique(start, end, chunk)
case `y`:
// TODO: Add proper support for adding inverse of range.
// This approach will add excessive amounts of singe
// range elements. They could be compressed into chunks
skip := start
aRange := ranges.NewInclusiveRange(start, end, 1)
var val int
for it := aRange.IterValues(); !it.IsDone(); {
val = it.Next()
if val == skip {
skip += chunk
continue
}
s.rangePtr.AppendUnique(val, val, 1)
}
case `:`:
for ; chunk > 0; chunk-- {
s.rangePtr.AppendUnique(start, end, chunk)
}
}
default:
return fmt.Errorf("Unexpected match []string size: %v", match)
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/peribolos/main.go#L904-L951
|
func configureTeamRepos(client teamRepoClient, githubTeams map[string]github.Team, name, orgName string, team org.Team) error {
gt, ok := githubTeams[name]
if !ok { // configureTeams is buggy if this is the case
return fmt.Errorf("%s not found in id list", name)
}
want := team.Repos
have := map[string]github.RepoPermissionLevel{}
repos, err := client.ListTeamRepos(gt.ID)
if err != nil {
return fmt.Errorf("failed to list team %d(%s) repos: %v", gt.ID, name, err)
}
for _, repo := range repos {
have[repo.Name] = github.LevelFromPermissions(repo.Permissions)
}
actions := map[string]github.RepoPermissionLevel{}
for wantRepo, wantPermission := range want {
if havePermission, haveRepo := have[wantRepo]; haveRepo && havePermission == wantPermission {
// nothing to do
continue
}
// create or update this permission
actions[wantRepo] = wantPermission
}
for haveRepo := range have {
if _, wantRepo := want[haveRepo]; !wantRepo {
// should remove these permissions
actions[haveRepo] = github.None
}
}
var updateErrors []error
for repo, permission := range actions {
var err error
if permission == github.None {
err = client.RemoveTeamRepo(gt.ID, orgName, repo)
} else {
err = client.UpdateTeamRepo(gt.ID, orgName, repo, permission)
}
if err != nil {
updateErrors = append(updateErrors, fmt.Errorf("failed to update team %d(%s) permissions on repo %s to %s: %v", gt.ID, name, repo, permission, err))
}
}
return errorutil.NewAggregate(updateErrors...)
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/errors.go#L77-L83
|
func (e *DBError) New(dbName string, message string) *DBError {
e.HTTPCode = http.StatusInternalServerError
e.Errno = 0
e.Message = message
e.DBName = dbName
return e
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L475-L492
|
func (c *cluster) waitNoLeader(membs []*member) {
noLeader := false
for !noLeader {
noLeader = true
for _, m := range membs {
select {
case <-m.s.StopNotify():
continue
default:
}
if m.s.Lead() != 0 {
noLeader = false
time.Sleep(10 * tickDuration)
break
}
}
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_snapshot.go#L35-L63
|
func (m *InmemSnapshotStore) Create(version SnapshotVersion, index, term uint64,
configuration Configuration, configurationIndex uint64, trans Transport) (SnapshotSink, error) {
// We only support version 1 snapshots at this time.
if version != 1 {
return nil, fmt.Errorf("unsupported snapshot version %d", version)
}
name := snapshotName(term, index)
m.Lock()
defer m.Unlock()
sink := &InmemSnapshotSink{
meta: SnapshotMeta{
Version: version,
ID: name,
Index: index,
Term: term,
Peers: encodePeers(configuration, trans),
Configuration: configuration,
ConfigurationIndex: configurationIndex,
},
contents: &bytes.Buffer{},
}
m.hasSnapshot = true
m.latest = sink
return sink, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L542-L558
|
func (r *raft) sendHeartbeat(to uint64, ctx []byte) {
// Attach the commit as min(to.matched, r.committed).
// When the leader sends out heartbeat message,
// the receiver(follower) might not be matched with the leader
// or it might not have all the committed entries.
// The leader MUST NOT forward the follower's commit to
// an unmatched index.
commit := min(r.getProgress(to).Match, r.raftLog.committed)
m := pb.Message{
To: to,
Type: pb.MsgHeartbeat,
Commit: commit,
Context: ctx,
}
r.send(m)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L1530-L1534
|
func (v SetStyleSheetTextReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss13(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/relay.go#L439-L473
|
func (r *Relayer) handleNonCallReq(f *Frame) error {
frameType := frameTypeFor(f)
finished := finishesCall(f)
// If we read a request frame, we need to use the outbound map to decide
// the destination. Otherwise, we use the inbound map.
items := r.outbound
if frameType == responseFrame {
items = r.inbound
}
item, ok := items.Get(f.Header.ID)
if !ok {
return errUnknownID
}
if item.tomb {
// Call timed out, ignore this frame. (We've already handled stats.)
// TODO: metrics for late-arriving frames.
return nil
}
originalID := f.Header.ID
f.Header.ID = item.remapID
sent, failure := item.destination.Receive(f, frameType)
if !sent {
r.failRelayItem(items, originalID, failure)
return nil
}
if finished {
r.finishRelayItem(items, originalID)
}
return nil
}
|
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/rbuf.go#L447-L465
|
func (b *FixedSizeRingBuf) LegalPos() (a0, aLast, b0, bLast int) {
a0 = -1
aLast = -1
b0 = -1
bLast = -1
if b.Readable == 0 {
return
}
a0 = b.Beg
last := b.Beg + b.Readable - 1
if last < b.N {
aLast = last
return
}
aLast = b.N - 1
b0 = 0
bLast = last % b.N
return
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.