_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/http.go#L135-L149
func CheckTrustState(cert x509.Certificate, trustedCerts map[string]x509.Certificate) (bool, string) { // Extra validity check (should have been caught by TLS stack) if time.Now().Before(cert.NotBefore) || time.Now().After(cert.NotAfter) { return false, "" } for k, v := range trustedCerts { if bytes.Compare(cert.Raw, v.Raw) == 0 { logger.Debug("Found cert", log.Ctx{"name": k}) return true, k } } return false, "" }
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/web/server.go#L153-L155
func (mux *LoggingServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { mux.serveMux.ServeHTTP(w, r) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1794-L1813
func (u *Unordered) Ordered() *Ordered { paths := make([]string, len(u.fs)) i := 0 for path := range u.fs { paths[i] = path i++ } sort.Strings(paths) o := NewOrdered("") for i := 1; i < len(paths); i++ { path := paths[i] n := u.fs[path] if n.DirNode != nil { o.putDir(path, n) } else { o.putFile(path, n) } } return o }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/golint/golint.go#L144-L197
func problemsInFiles(r *git.Repo, files map[string]string) (map[string]map[int]lint.Problem, []github.DraftReviewComment) { problems := make(map[string]map[int]lint.Problem) var lintErrorComments []github.DraftReviewComment l := new(lint.Linter) for f, patch := range files { problems[f] = make(map[int]lint.Problem) src, err := ioutil.ReadFile(filepath.Join(r.Dir, f)) if err != nil { lintErrorComments = append(lintErrorComments, github.DraftReviewComment{ Path: f, Body: fmt.Sprintf("%v", err), }) } ps, err := l.Lint(f, src) if err != nil { // Get error line by parsing the error message errLineIndexStart := strings.LastIndex(err.Error(), f) + len(f) reNumber := regexp.MustCompile(`:([0-9]+):`) matches := reNumber.FindStringSubmatch(err.Error()[errLineIndexStart:]) newComment := github.DraftReviewComment{ Path: f, Body: err.Error(), } if len(matches) > 1 { errLineString := matches[1] errLine, errAtoi := strconv.Atoi(errLineString) if errAtoi == nil { newComment.Position = errLine } // Trim error message to after the line and column numbers reTrimError := regexp.MustCompile(`(:[0-9]+:[0-9]+: )`) matches = reTrimError.FindStringSubmatch(err.Error()) if len(matches) > 0 { newComment.Body = err.Error()[len(matches[0])+errLineIndexStart:] } } lintErrorComments = append(lintErrorComments, newComment) } al, err := AddedLines(patch) if err != nil { lintErrorComments = append(lintErrorComments, github.DraftReviewComment{ Path: f, Body: fmt.Sprintf("computing added lines in %s: %v", f, err), }) } for _, p := range ps { if pl, ok := al[p.Position.Line]; ok { problems[f][pl] = p } } } return problems, lintErrorComments }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/create_account.go#L59-L62
func (m NativeAmount) MutateCreateAccount(o *xdr.CreateAccountOp) (err error) { o.StartingBalance, err = amount.Parse(m.Amount) return }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/reflect.go#L131-L167
func defaultValue(rt reflect.Type) (rv reflect.Value) { switch rt.Kind() { case reflect.Ptr: // Dereference all the way and see if it's a time type. rt_:= rt.Elem() for rt_.Kind() == reflect.Ptr { rt_ = rt_.Elem() } switch rt_ { case timeType: // Start from the top and construct pointers as needed. rv = reflect.New(rt).Elem() rt_, rv_ := rt, rv for rt_.Kind() == reflect.Ptr { newPtr := reflect.New(rt_.Elem()) rv_.Set(newPtr) rt_ = rt_.Elem() rv_ = rv_.Elem() } // Set to 1970, the whole point of this function. rv_.Set(reflect.ValueOf(zeroTime)) return rv } case reflect.Struct: switch rt { case timeType: // Set to 1970, the whole point of this function. rv = reflect.New(rt).Elem() rv.Set(reflect.ValueOf(zeroTime)) return rv } } // Just return the default Go zero object. // Return an empty struct. return reflect.Zero(rt) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L1069-L1073
func (v SetBreakpointParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger11(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/resolver/endpoint/endpoint.go#L195-L215
func ParseEndpoint(endpoint string) (proto string, host string, scheme string) { proto = "tcp" host = endpoint url, uerr := url.Parse(endpoint) if uerr != nil || !strings.Contains(endpoint, "://") { return proto, host, scheme } scheme = url.Scheme // strip scheme:// prefix since grpc dials by host host = url.Host switch url.Scheme { case "http", "https": case "unix", "unixs": proto = "unix" host = url.Host + url.Path default: proto, host = "", "" } return proto, host, scheme }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/file.go#L54-L75
func (s *FileSource) LastModified() (time.Time, error) { // Calling os.Stat() for *every* Render of the same source is a waste // Only call os.Stat() if we haven't done so in the last 1 second if time.Since(s.LastStat) < time.Second { // A-ha! it's not that long ago we calculated this value, just return // the same thing as our last call return s.LastStatResult.ModTime(), nil } // If we got here, our previous check was too old or this is the first // time we're checking for os.Stat() fi, err := os.Stat(s.Path) if err != nil { return time.Time{}, err } // Save these for later... s.LastStat = time.Now() s.LastStatResult = fi return s.LastStatResult.ModTime(), nil }
https://github.com/sourcegraph/go-vcsurl/blob/2305ecca26ab74e3f819cb3875cd631f467e0c2b/vcsurl.go#L42-L49
func (r *RepoInfo) Link() string { switch r.RepoHost { case GoogleCode: return fmt.Sprintf("https://code.google.com/p/%s", r.FullName) default: return (&url.URL{Scheme: "https", Host: string(r.RepoHost), Path: "/" + r.FullName}).String() } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L53-L56
func (p DispatchKeyEventParams) WithTimestamp(timestamp *TimeSinceEpoch) *DispatchKeyEventParams { p.Timestamp = timestamp return &p }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcauth/types.go#L912-L915
func (this *HawkSignatureAuthenticationResponse) MarshalJSON() ([]byte, error) { x := json.RawMessage(*this) return (&x).MarshalJSON() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/common/common.go#L235-L239
func (ud *UserData) FromMap(m UserDataMap) { for key, value := range m { ud.Store(key, value) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/easyjson.go#L223-L227
func (v UntrackCacheStorageForOriginParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoStorage2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/cluster.go#L37-L91
func createCluster(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { allowed := permission.Check(t, permission.PermClusterCreate) if !allowed { return permission.ErrUnauthorized } var provCluster provTypes.Cluster err = ParseInput(r, &provCluster) if err != nil { return err } evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypeCluster, Value: provCluster.Name}, Kind: permission.PermClusterCreate, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermClusterReadEvents), }) if err != nil { return err } defer func() { evt.Done(err) }() _, err = servicemanager.Cluster.FindByName(provCluster.Name) if err == nil { return &tsuruErrors.HTTP{ Code: http.StatusConflict, Message: "cluster already exists", } } for _, poolName := range provCluster.Pools { _, err = pool.GetPoolByName(poolName) if err != nil { if err == pool.ErrPoolNotFound { return &tsuruErrors.HTTP{ Code: http.StatusNotFound, Message: err.Error(), } } return err } } streamResponse := strings.HasPrefix(r.Header.Get("Accept"), "application/x-json-stream") if streamResponse { 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) } provCluster.Writer = evt err = servicemanager.Cluster.Create(provCluster) if err != nil { return errors.WithStack(err) } return nil }
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/OperatorSymbol.go#L227-L236
func (this OperatorSymbol) IsModifierType(candidate []OperatorSymbol) bool { for _, symbolType := range candidate { if this == symbolType { return true } } return false }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L302-L311
func (p *GetAppManifestParams) Do(ctx context.Context) (url string, errors []*AppManifestError, data string, err error) { // execute var res GetAppManifestReturns err = cdp.Execute(ctx, CommandGetAppManifest, nil, &res) if err != nil { return "", nil, "", err } return res.URL, res.Errors, res.Data, nil }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/json/encode.go#L12-L14
func NewEncoder(w io.Writer) *objconv.Encoder { return objconv.NewEncoder(NewEmitter(w)) }
https://github.com/olorin/nagiosplugin/blob/893f9702af4ea1e2dc4cd6528cbdcdb3dc7ca064/result.go#L50-L66
func NewStatusPolicy(statuses []Status) (*statusPolicy, error) { newPol := make(statusPolicy) for i, status := range statuses { newPol[status] = statusSeverity(i) } // Ensure all statuses are covered by the new policy. defaultPol := NewDefaultStatusPolicy() for status := range *defaultPol { _, ok := newPol[status] if !ok { return nil, fmt.Errorf("missing status: %v", status) } } return &newPol, nil }
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L388-L393
func (l *slog) Infof(format string, args ...interface{}) { lvl := l.Level() if lvl <= LevelInfo { l.b.printf("INF", l.tag, format, args...) } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L619-L630
func (c *Cluster) ContainerConfigGet(id int, key string) (string, error) { q := "SELECT value FROM containers_config WHERE container_id=? AND key=?" value := "" arg1 := []interface{}{id, key} arg2 := []interface{}{&value} err := dbQueryRowScan(c.db, q, arg1, arg2) if err == sql.ErrNoRows { return "", ErrNoSuchObject } return value, err }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L121-L155
func (c *ClusterTx) ProfileURIs(filter ProfileFilter) ([]string, error) { // 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(profileNamesByProjectAndName) args = []interface{}{ filter.Project, filter.Name, } } else if criteria["Project"] != nil { stmt = c.stmt(profileNamesByProject) args = []interface{}{ filter.Project, } } else { stmt = c.stmt(profileNames) args = []interface{}{} } code := cluster.EntityTypes["profile"] formatter := cluster.EntityFormatURIs[code] return query.SelectURIs(stmt, formatter, args...) }
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/example/main.go#L19-L28
func prog(state overseer.State) { fmt.Printf("app#%s (%s) listening...\n", BuildID, state.ID) http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { d, _ := time.ParseDuration(r.URL.Query().Get("d")) time.Sleep(d) fmt.Fprintf(w, "app#%s (%s) says hello\n", BuildID, state.ID) })) http.Serve(state.Listener, nil) fmt.Printf("app#%s (%s) exiting...\n", BuildID, state.ID) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L4921-L4925
func (v GetMatchedStylesForNodeParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss42(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kokardy/listing/blob/795534c33c5ab6be8b85a15951664ab11fb70ea7/comb.go#L52-L69
func repeated_combinations(list []int, select_num, buf int) (c chan []int) { c = make(chan []int, buf) go func() { defer close(c) if select_num == 1 { for v := range list { c <- []int{v} } return } for i := 0; i < len(list); i++ { for sub_comb := range repeated_combinations(list[i:], select_num-1, buf) { c <- append([]int{list[i]}, sub_comb...) } } }() return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L309-L313
func (v RequestCachedResponseReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCachestorage2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L674-L683
func (p *SetStyleSheetTextParams) Do(ctx context.Context) (sourceMapURL string, err error) { // execute var res SetStyleSheetTextReturns err = cdp.Execute(ctx, CommandSetStyleSheetText, p, &res) if err != nil { return "", err } return res.SourceMapURL, nil }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/routes.go#L229-L232
func (r *routes) calculateUnicast(establishedAndSymmetric bool) unicastRoutes { _, unicast := r.ourself.routes(nil, establishedAndSymmetric) return unicast }
https://github.com/kokardy/listing/blob/795534c33c5ab6be8b85a15951664ab11fb70ea7/comb.go#L29-L49
func combinations(list []int, select_num, buf int) (c chan []int) { c = make(chan []int, buf) go func() { defer close(c) switch { case select_num == 0: c <- []int{} case select_num == len(list): c <- list case len(list) < select_num: return default: for i := 0; i < len(list); i++ { for sub_comb := range combinations(list[i+1:], select_num-1, buf) { c <- append([]int{list[i]}, sub_comb...) } } } }() return }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L883-L885
func (g *Glg) CustomLog(level string, val ...interface{}) error { return g.out(g.TagStringToLevel(level), blankFormat(len(val)), val...) }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/model.go#L31-L45
func InitSlice(ptr interface{}) []Model { // get slice slice := reflect.ValueOf(ptr).Elem() // make model slice models := make([]Model, slice.Len()) // iterate over entries for i := 0; i < slice.Len(); i++ { m := Init(slice.Index(i).Interface().(Model)) models[i] = m } return models }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/skl/arena.go#L43-L51
func newArena(n int64) *Arena { // Don't store data at position 0 in order to reserve offset=0 as a kind // of nil pointer. out := &Arena{ n: 1, buf: make([]byte, n), } return out }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L294-L303
func ClusterRole(opts *AssetOpts) *rbacv1.ClusterRole { return &rbacv1.ClusterRole{ TypeMeta: metav1.TypeMeta{ Kind: "ClusterRole", APIVersion: "rbac.authorization.k8s.io/v1", }, ObjectMeta: objectMeta(roleName, labels(""), nil, opts.Namespace), Rules: rolePolicyRules, } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/operations.go#L493-L536
func operationGet(d *Daemon, r *http.Request) Response { id := mux.Vars(r)["id"] var body *api.Operation // First check if the query is for a local operation from this node op, err := operationGetInternal(id) if err == nil { _, body, err = op.Render() if err != nil { return SmartError(err) } return SyncResponse(true, body) } // Then check if the query is from an operation on another node, and, if so, forward it var address string err = d.cluster.Transaction(func(tx *db.ClusterTx) error { operation, err := tx.OperationByUUID(id) if err != nil { return err } address = operation.NodeAddress return nil }) if err != nil { return SmartError(err) } cert := d.endpoints.NetworkCert() client, err := cluster.Connect(address, cert, false) if err != nil { return SmartError(err) } body, _, err = client.GetOperation(id) if err != nil { return SmartError(err) } return SyncResponse(true, body) }
https://github.com/pandemicsyn/oort/blob/fca1d3baddc1d944387cc8bbe8b21f911ec9091b/oort/cmdctrl.go#L158-L162
func (o *Server) SoftwareVersion() string { o.cmdCtrlLock.RLock() defer o.cmdCtrlLock.RUnlock() return o.binaryUpgrade.GetCurrentVersion() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util.go#L111-L153
func HostPath(path string) string { // Ignore empty paths if len(path) == 0 { return path } // Don't prefix stdin/stdout if path == "-" { return path } // Check if we're running in a snap package snap := os.Getenv("SNAP") snapName := os.Getenv("SNAP_NAME") if snap == "" || snapName != "lxd" { return path } // Handle relative paths if path[0] != os.PathSeparator { // Use the cwd of the parent as snap-confine alters our own cwd on launch ppid := os.Getppid() if ppid < 1 { return path } pwd, err := os.Readlink(fmt.Sprintf("/proc/%d/cwd", ppid)) if err != nil { return path } path = filepath.Clean(strings.Join([]string{pwd, path}, string(os.PathSeparator))) } // Check if the path is already snap-aware for _, prefix := range []string{"/dev", "/snap", "/var/snap", "/var/lib/snapd"} { if path == prefix || strings.HasPrefix(path, fmt.Sprintf("%s/", prefix)) { return path } } return fmt.Sprintf("/var/lib/snapd/hostfs%s", path) }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dimg/fileutil.go#L33-L46
func LoadFromPngFile(filePath string) (image.Image, error) { // Open file f, err := os.OpenFile(filePath, 0, 0) if err != nil { return nil, err } defer f.Close() b := bufio.NewReader(f) img, err := png.Decode(b) if err != nil { return nil, err } return img, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L920-L931
func (c *Client) CreateCommentReaction(org, repo string, id int, reaction string) error { c.log("CreateCommentReaction", org, repo, id, reaction) r := Reaction{Content: reaction} _, err := c.request(&request{ method: http.MethodPost, path: fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", org, repo, id), accept: "application/vnd.github.squirrel-girl-preview", exitCodes: []int{201}, requestBody: &r, }, nil) return err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L368-L397
func (c *Client) request(method, path string, params url.Values, measure bool) (*http.Response, error) { var resp *http.Response var err error backoff := retryDelay urlPath := fmt.Sprintf("%s%s", c.baseURL, path) if params != nil { urlPath = fmt.Sprintf("%s?%s", urlPath, params.Encode()) } start := time.Now() for retries := 0; retries < maxRetries; retries++ { resp, err = c.doRequest(method, urlPath) if err == nil && resp.StatusCode < 500 { break } else if err == nil && retries+1 < maxRetries { resp.Body.Close() } // Capture the retry in a metric. if measure && c.metrics != nil { c.metrics.RequestRetries.Inc() } time.Sleep(backoff) backoff *= 2 } if measure && resp != nil { c.measure(method, path, resp.StatusCode, start) } return resp, err }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L192-L198
func (p *Page) URL() (string, error) { url, err := p.session.GetURL() if err != nil { return "", fmt.Errorf("failed to retrieve URL: %s", err) } return url, nil }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/string.go#L43-L51
func (e *Engine) String(s string, args ...interface{}) Renderer { if len(args) > 0 { s = fmt.Sprintf(s, args...) } return stringRenderer{ Engine: e, body: s, } }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_reference.go#L139-L153
func (s storageReference) StringWithinTransport() string { optionsList := "" options := s.transport.store.GraphOptions() if len(options) > 0 { optionsList = ":" + strings.Join(options, ",") } res := "[" + s.transport.store.GraphDriverName() + "@" + s.transport.store.GraphRoot() + "+" + s.transport.store.RunRoot() + optionsList + "]" if s.named != nil { res = res + s.named.String() } if s.id != "" { res = res + "@" + s.id } return res }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/walk/walk.go#L293-L332
func (r *symlinkResolver) follow(c *config.Config, dir, rel, base string) bool { if dir == c.RepoRoot && strings.HasPrefix(base, "bazel-") { // Links such as bazel-<workspace>, bazel-out, bazel-genfiles are created by // Bazel to point to internal build directories. return false } // See if the user has explicitly directed us to follow the link. wc := getWalkConfig(c) linkRel := path.Join(rel, base) for _, follow := range wc.follow { if linkRel == follow { return true } } // See if the symlink points to a tree that has been already visited. fullpath := filepath.Join(dir, base) dest, err := filepath.EvalSymlinks(fullpath) if err != nil { return false } if !filepath.IsAbs(dest) { dest, err = filepath.Abs(filepath.Join(dir, dest)) if err != nil { return false } } for _, p := range r.visited { if pathtools.HasPrefix(dest, p) || pathtools.HasPrefix(p, dest) { return false } } r.visited = append(r.visited, dest) stat, err := os.Stat(fullpath) if err != nil { return false } return stat.IsDir() }
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/logger.go#L186-L189
func (l *Logger) Panic(args ...interface{}) { l.log(CRITICAL, nil, args...) panic(fmt.Sprint(args...)) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L30-L144
func Bootstrap(state *state.State, gateway *Gateway, name string) error { // Check parameters if name == "" { return fmt.Errorf("node name must not be empty") } err := membershipCheckNoLeftoverClusterCert(state.OS.VarDir) if err != nil { return err } var address string err = state.Node.Transaction(func(tx *db.NodeTx) error { // Fetch current network address and raft nodes config, err := node.ConfigLoad(tx) if err != nil { return errors.Wrap(err, "failed to fetch node configuration") } address = config.ClusterAddress() // Make sure node-local database state is in order. err = membershipCheckNodeStateForBootstrapOrJoin(tx, address) if err != nil { return err } // Add ourselves as first raft node err = tx.RaftNodeFirst(address) if err != nil { return errors.Wrap(err, "failed to insert first raft node") } return nil }) if err != nil { return err } // Update our own entry in the nodes table. err = state.Cluster.Transaction(func(tx *db.ClusterTx) error { // Make sure cluster database state is in order. err := membershipCheckClusterStateForBootstrapOrJoin(tx) if err != nil { return err } // Add ourselves to the nodes table. err = tx.NodeUpdate(1, name, address) if err != nil { return errors.Wrap(err, "failed to update cluster node") } return nil }) if err != nil { return err } // Shutdown the gateway. This will trash any dqlite connection against // our in-memory dqlite driver and shutdown the associated raft // instance. We also lock regular access to the cluster database since // we don't want any other database code to run while we're // reconfiguring raft. err = state.Cluster.EnterExclusive() if err != nil { return errors.Wrap(err, "failed to acquire cluster database lock") } err = gateway.Shutdown() if err != nil { return errors.Wrap(err, "failed to shutdown gRPC SQL gateway") } // Re-initialize the gateway. This will create a new raft factory an // dqlite driver instance, which will be exposed over gRPC by the // gateway handlers. err = gateway.init() if err != nil { return errors.Wrap(err, "failed to re-initialize gRPC SQL gateway") } err = gateway.waitLeadership() if err != nil { return err } // The cluster certificates are symlinks against the regular node // certificate. for _, ext := range []string{".crt", ".key", ".ca"} { if ext == ".ca" && !shared.PathExists(filepath.Join(state.OS.VarDir, "server.ca")) { continue } err := os.Symlink("server"+ext, filepath.Join(state.OS.VarDir, "cluster"+ext)) if err != nil { return errors.Wrap(err, "failed to create cluster cert symlink") } } // Make sure we can actually connect to the cluster database through // the network endpoint. This also releases the previously acquired // lock and makes the Go SQL pooling system invalidate the old // connection, so new queries will be executed over the new gRPC // network connection. err = state.Cluster.ExitExclusive(func(tx *db.ClusterTx) error { _, err := tx.Nodes() return err }) if err != nil { return errors.Wrap(err, "cluster database initialization failed") } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L6569-L6573
func (v *CopyToReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom74(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/etcdhttp/base.go#L141-L203
func WriteError(lg *zap.Logger, w http.ResponseWriter, r *http.Request, err error) { if err == nil { return } switch e := err.(type) { case *v2error.Error: e.WriteTo(w) case *httptypes.HTTPError: if et := e.WriteTo(w); et != nil { if lg != nil { lg.Debug( "failed to write v2 HTTP error", zap.String("remote-addr", r.RemoteAddr), zap.String("internal-server-error", e.Error()), zap.Error(et), ) } else { plog.Debugf("error writing HTTPError (%v) to %s", et, r.RemoteAddr) } } default: switch err { case etcdserver.ErrTimeoutDueToLeaderFail, etcdserver.ErrTimeoutDueToConnectionLost, etcdserver.ErrNotEnoughStartedMembers, etcdserver.ErrUnhealthy: if lg != nil { lg.Warn( "v2 response error", zap.String("remote-addr", r.RemoteAddr), zap.String("internal-server-error", err.Error()), ) } else { mlog.MergeError(err) } default: if lg != nil { lg.Warn( "unexpected v2 response error", zap.String("remote-addr", r.RemoteAddr), zap.String("internal-server-error", err.Error()), ) } else { mlog.MergeErrorf("got unexpected response error (%v)", err) } } herr := httptypes.NewHTTPError(http.StatusInternalServerError, "Internal Server Error") if et := herr.WriteTo(w); et != nil { if lg != nil { lg.Debug( "failed to write v2 HTTP error", zap.String("remote-addr", r.RemoteAddr), zap.String("internal-server-error", err.Error()), zap.Error(et), ) } else { plog.Debugf("error writing HTTPError (%v) to %s", et, r.RemoteAddr) } } } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-p2c/transfer.go#L21-L49
func rsyncSend(conn *websocket.Conn, path string, rsyncArgs string) error { cmd, dataSocket, stderr, err := rsyncSendSetup(path, rsyncArgs) if err != nil { return err } if dataSocket != nil { defer dataSocket.Close() } readDone, writeDone := shared.WebsocketMirror(conn, dataSocket, io.ReadCloser(dataSocket), nil, nil) output, err := ioutil.ReadAll(stderr) if err != nil { cmd.Process.Kill() cmd.Wait() return fmt.Errorf("Failed to rsync: %v\n%s", err, output) } err = cmd.Wait() <-readDone <-writeDone if err != nil { return fmt.Errorf("Failed to rsync: %v\n%s", err, output) } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L845-L849
func (v *RemoveBindingParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime8(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdmain/gateway.go#L53-L61
func newGatewayCommand() *cobra.Command { lpc := &cobra.Command{ Use: "gateway <subcommand>", Short: "gateway related command", } lpc.AddCommand(newGatewayStartCommand()) return lpc }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2245-L2249
func (v *GlobalLexicalScopeNamesParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime20(&r, v) return r.Error() }
https://github.com/ctripcorp/ghost/blob/9dce30d85194129b9c0ba6702c612f3b5c41d02f/pool/blockingPool.go#L36-L52
func NewBlockingPool(initCap, maxCap int, livetime time.Duration, factory Factory) (Pool, error) { if initCap < 0 || maxCap < 1 || initCap > maxCap { return nil, errors.New("invalid capacity settings") } newPool := &blockingPool{ timeout: 3, conns: make(chan *WrappedConn, maxCap), factory: factory, livetime: livetime, } for i := 0; i < initCap; i++ { newPool.conns <- newPool.wrap(nil) } return newPool, nil }
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L833-L850
func (p *PubSub) Publish(topic string, data []byte) error { seqno := p.nextSeqno() m := &pb.Message{ Data: data, TopicIDs: []string{topic}, From: []byte(p.host.ID()), Seqno: seqno, } if p.signKey != nil { m.From = []byte(p.signID) err := signMessage(p.signID, p.signKey, m) if err != nil { return err } } p.publish <- &Message{m} return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/mkbuild-cluster/main.go#L107-L110
func useContext(o options, ctx string) error { _, cmd := command("kubectl", "config", "use-context", ctx) return cmd.Run() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L514-L533
func (p *GetResponseBodyForInterceptionParams) Do(ctx context.Context) (body []byte, err error) { // execute var res GetResponseBodyForInterceptionReturns err = cdp.Execute(ctx, CommandGetResponseBodyForInterception, p, &res) if err != nil { return nil, err } // decode var dec []byte if res.Base64encoded { dec, err = base64.StdEncoding.DecodeString(res.Body) if err != nil { return nil, err } } else { dec = []byte(res.Body) } return dec, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L291-L295
func (v *SetAutoAttachParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget2(&r, v) return r.Error() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3891-L3973
func NewOperationResultTr(aType OperationType, value interface{}) (result OperationResultTr, err error) { result.Type = aType switch OperationType(aType) { case OperationTypeCreateAccount: tv, ok := value.(CreateAccountResult) if !ok { err = fmt.Errorf("invalid value, must be CreateAccountResult") return } result.CreateAccountResult = &tv case OperationTypePayment: tv, ok := value.(PaymentResult) if !ok { err = fmt.Errorf("invalid value, must be PaymentResult") return } result.PaymentResult = &tv case OperationTypePathPayment: tv, ok := value.(PathPaymentResult) if !ok { err = fmt.Errorf("invalid value, must be PathPaymentResult") return } result.PathPaymentResult = &tv case OperationTypeManageOffer: tv, ok := value.(ManageOfferResult) if !ok { err = fmt.Errorf("invalid value, must be ManageOfferResult") return } result.ManageOfferResult = &tv case OperationTypeCreatePassiveOffer: tv, ok := value.(ManageOfferResult) if !ok { err = fmt.Errorf("invalid value, must be ManageOfferResult") return } result.CreatePassiveOfferResult = &tv case OperationTypeSetOptions: tv, ok := value.(SetOptionsResult) if !ok { err = fmt.Errorf("invalid value, must be SetOptionsResult") return } result.SetOptionsResult = &tv case OperationTypeChangeTrust: tv, ok := value.(ChangeTrustResult) if !ok { err = fmt.Errorf("invalid value, must be ChangeTrustResult") return } result.ChangeTrustResult = &tv case OperationTypeAllowTrust: tv, ok := value.(AllowTrustResult) if !ok { err = fmt.Errorf("invalid value, must be AllowTrustResult") return } result.AllowTrustResult = &tv case OperationTypeAccountMerge: tv, ok := value.(AccountMergeResult) if !ok { err = fmt.Errorf("invalid value, must be AccountMergeResult") return } result.AccountMergeResult = &tv case OperationTypeInflation: tv, ok := value.(InflationResult) if !ok { err = fmt.Errorf("invalid value, must be InflationResult") return } result.InflationResult = &tv case OperationTypeManageData: tv, ok := value.(ManageDataResult) if !ok { err = fmt.Errorf("invalid value, must be ManageDataResult") return } result.ManageDataResult = &tv } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/io/io.go#L62-L65
func (p ReadParams) WithOffset(offset int64) *ReadParams { p.Offset = offset return &p }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/query.go#L41-L46
func selectSchemaVersions(tx *sql.Tx) ([]int, error) { statement := ` SELECT version FROM schema ORDER BY version ` return query.SelectIntegers(tx, statement) }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/taskmanager/task.go#L18-L23
func (s *Task) SetPublicMeta(name string, value interface{}) { if s.MetaData == nil { s.MetaData = make(map[string]interface{}) } s.MetaData[name] = value }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/label_sync/main.go#L148-L183
func writeTemplate(templatePath string, outputPath string, data interface{}) error { // set up template funcMap := template.FuncMap{ "anchor": func(input string) string { return strings.Replace(input, ":", " ", -1) }, } t, err := template.New(filepath.Base(templatePath)).Funcs(funcMap).ParseFiles(templatePath) if err != nil { return err } // ensure output path exists if !pathExists(outputPath) { _, err = os.Create(outputPath) if err != nil { return err } } // open file at output path and truncate f, err := os.OpenFile(outputPath, os.O_RDWR, 0644) if err != nil { return err } defer f.Close() f.Truncate(0) // render template to output path err = t.Execute(f, data) if err != nil { return err } return nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/policy/codegen_client.go#L1129-L1131
func (api *API) PublishedTemplateLocator(href string) *PublishedTemplateLocator { return &PublishedTemplateLocator{Href(href), api} }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/cmd/viewcore/html.go#L393-L404
func objField(c *gocore.Process, x gocore.Object, off int64) string { t, r := c.Type(x) if t == nil { return fmt.Sprintf("f%d", off) } s := "" if r > 1 { s = fmt.Sprintf("[%d]", off/t.Size) off %= t.Size } return s + typeFieldName(t, off) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L2370-L2377
func (r *CookbookAttachment) Locator(api *API) *CookbookAttachmentLocator { for _, l := range r.Links { if l["rel"] == "self" { return api.CookbookAttachmentLocator(l["href"]) } } return nil }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/log_adapter.go#L108-L110
func (la *LogAdapter) Dbgf(msg string, a ...interface{}) error { return la.Debugf(msg, a...) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/errutil/http.go#L25-L30
func (h *HTTPError) Code() int { if h == nil { return http.StatusOK } return h.code }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L4391-L4395
func (v FrameResourceTree) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage46(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/adt/interval_tree.go#L433-L439
func (ivt *IntervalTree) Find(ivl Interval) (ret *IntervalValue) { n := ivt.find(ivl) if n == nil { return nil } return &n.iv }
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/key.go#L185-L270
func KeyStretcher(cipherType string, hashType string, secret []byte) (StretchedKeys, StretchedKeys) { var cipherKeySize int var ivSize int switch cipherType { case "AES-128": ivSize = 16 cipherKeySize = 16 case "AES-256": ivSize = 16 cipherKeySize = 32 case "Blowfish": ivSize = 8 // Note: 24 arbitrarily selected, needs more thought cipherKeySize = 32 } hmacKeySize := 20 seed := []byte("key expansion") result := make([]byte, 2*(ivSize+cipherKeySize+hmacKeySize)) var h func() hash.Hash switch hashType { case "SHA1": h = sha1.New case "SHA256": h = sha256.New case "SHA512": h = sha512.New default: panic("Unrecognized hash function, programmer error?") } m := hmac.New(h, secret) // note: guaranteed to never return an error m.Write(seed) a := m.Sum(nil) j := 0 for j < len(result) { m.Reset() // note: guaranteed to never return an error. m.Write(a) m.Write(seed) b := m.Sum(nil) todo := len(b) if j+todo > len(result) { todo = len(result) - j } copy(result[j:j+todo], b) j += todo m.Reset() // note: guaranteed to never return an error. m.Write(a) a = m.Sum(nil) } half := len(result) / 2 r1 := result[:half] r2 := result[half:] var k1 StretchedKeys var k2 StretchedKeys k1.IV = r1[0:ivSize] k1.CipherKey = r1[ivSize : ivSize+cipherKeySize] k1.MacKey = r1[ivSize+cipherKeySize:] k2.IV = r2[0:ivSize] k2.CipherKey = r2[ivSize : ivSize+cipherKeySize] k2.MacKey = r2[ivSize+cipherKeySize:] return k1, k2 }
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/s3gof3r.go#L260-L265
func init() { logger = internalLogger{ log.New(ioutil.Discard, "", log.LstdFlags), false, } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/portforwarder.go#L202-L205
func (f *PortForwarder) Lock() error { pidfile.SetPidfilePath(path.Join(os.Getenv("HOME"), ".pachyderm/port-forward.pid")) return pidfile.Write() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L1623-L1627
func (v *DeliverPushMessageParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoServiceworker17(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/easyjson.go#L594-L598
func (v *EventDomStorageItemsCleared) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomstorage5(&r, v) return r.Error() }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/clitable/table.go#L190-L196
func (t *Table) getHead() string { s := "|" for _, name := range t.Fields { s += t.fieldString(name, strings.Title(name)) + "|" } return s }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L1643-L1647
func (v SetExtraHTTPHeadersParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork11(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L471-L484
func (ap Approvers) GetCCs() []string { randomizedApprovers := ap.owners.GetShuffledApprovers() currentApprovers := ap.GetCurrentApproversSet() approversAndAssignees := currentApprovers.Union(ap.assignees) leafReverseMap := ap.owners.GetReverseMap(ap.owners.GetLeafApprovers()) suggested := ap.owners.KeepCoveringApprovers(leafReverseMap, approversAndAssignees, randomizedApprovers) approversAndSuggested := currentApprovers.Union(suggested) everyone := approversAndSuggested.Union(ap.assignees) fullReverseMap := ap.owners.GetReverseMap(ap.owners.GetApprovers()) keepAssignees := ap.owners.KeepCoveringApprovers(fullReverseMap, approversAndSuggested, everyone.List()) return suggested.Union(keepAssignees).List() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/networks.go#L93-L98
func (c *ClusterTx) NetworkNodeJoin(networkID, nodeID int64) error { columns := []string{"network_id", "node_id"} values := []interface{}{networkID, nodeID} _, err := query.UpsertObject(c.tx, "networks_nodes", columns, values) return err }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L105-L107
func (s *selectable) FindByID(id string) *Selection { return newSelection(s.session, s.selectors.Append(target.ID, id).Single()) }
https://github.com/marcuswestin/go-errs/blob/b09b17aacd5a8213690bc30f9ccfe7400be7b380/errs.go#L104-L106
func UserError(info Info, publicMsg ...interface{}) Err { return newErr(debug.Stack(), nil, true, info, publicMsg) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/client.go#L110-L120
func Clients(ctx context.Context, pipelineRcName string, etcdClient *etcd.Client, etcdPrefix string, workerGrpcPort uint16) ([]Client, error) { conns, err := Conns(ctx, pipelineRcName, etcdClient, etcdPrefix, workerGrpcPort) if err != nil { return nil, err } var result []Client for _, conn := range conns { result = append(result, newClient(conn)) } return result, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/easyjson.go#L252-L256
func (v TraceConfig) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTracing(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L6753-L6757
func (v CollectClassNamesFromSubtreeReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom76(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gcsweb/cmd/gcsweb/gcsweb.go#L577-L580
func (tl txnLogger) Printf(fmt string, args ...interface{}) { args = append([]interface{}{tl.nonce}, args...) log.Printf("[txn-%s] "+fmt, args...) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/types.go#L361-L363
func (t *ExceptionsState) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/put_apps_app_routes_route_parameters.go#L87-L90
func (o *PutAppsAppRoutesRouteParams) WithContext(ctx context.Context) *PutAppsAppRoutesRouteParams { o.SetContext(ctx) return o }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/storage.go#L95-L97
func (ms *MemoryStorage) InitialState() (pb.HardState, pb.ConfState, error) { return ms.hardState, ms.snapshot.Metadata.ConfState, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/fake_comment_wrapper.go#L50-L63
func (o *FakeCommentPluginWrapper) ReceiveComment(comment sql.Comment) []Point { // Create a fake "commented" event for every comment we receive. fakeEvent := sql.IssueEvent{ IssueID: comment.IssueID, Event: "commented", EventCreatedAt: comment.CommentCreatedAt, Actor: &comment.User, } return append( o.plugin.ReceiveComment(comment), o.plugin.ReceiveIssueEvent(fakeEvent)..., ) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/tlsclientconfig/tlsclientconfig.go#L20-L82
func SetupCertificates(dir string, tlsc *tls.Config) error { logrus.Debugf("Looking for TLS certificates and private keys in %s", dir) fs, err := ioutil.ReadDir(dir) if err != nil { if os.IsNotExist(err) { return nil } if os.IsPermission(err) { logrus.Debugf("Skipping scan of %s due to permission error: %v", dir, err) return nil } return err } for _, f := range fs { fullPath := filepath.Join(dir, f.Name()) if strings.HasSuffix(f.Name(), ".crt") { logrus.Debugf(" crt: %s", fullPath) data, err := ioutil.ReadFile(fullPath) if err != nil { if os.IsNotExist(err) { // Dangling symbolic link? // Race with someone who deleted the // file after we read the directory's // list of contents? logrus.Warnf("error reading certificate %q: %v", fullPath, err) continue } return err } if tlsc.RootCAs == nil { systemPool, err := tlsconfig.SystemCertPool() if err != nil { return errors.Wrap(err, "unable to get system cert pool") } tlsc.RootCAs = systemPool } tlsc.RootCAs.AppendCertsFromPEM(data) } if strings.HasSuffix(f.Name(), ".cert") { certName := f.Name() keyName := certName[:len(certName)-5] + ".key" logrus.Debugf(" cert: %s", fullPath) if !hasFile(fs, keyName) { return errors.Errorf("missing key %s for client certificate %s. Note that CA certificates should use the extension .crt", keyName, certName) } cert, err := tls.LoadX509KeyPair(filepath.Join(dir, certName), filepath.Join(dir, keyName)) if err != nil { return err } tlsc.Certificates = append(tlsc.Certificates, cert) } if strings.HasSuffix(f.Name(), ".key") { keyName := f.Name() certName := keyName[:len(keyName)-4] + ".cert" logrus.Debugf(" key: %s", fullPath) if !hasFile(fs, certName) { return errors.Errorf("missing client certificate %s for key %s", certName, keyName) } } } return nil }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/object.go#L370-L382
func (p *Process) findHeapInfo(a core.Address) *heapInfo { k := a / heapInfoSize / pageTableSize i := a / heapInfoSize % pageTableSize t := p.pageTable[k] if t == nil { return nil } h := &t[i] if h.base == 0 { return nil } return h }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L1296-L1300
func (v *EventAnimationCreated) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoAnimation14(&r, v) return r.Error() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/coverage/diff/view.go#L36-L41
func deltaDisplayed(change *coverageChange) string { if change.baseRatio < 0 { return "" } return fmt.Sprintf("%.1f", (change.newRatio-change.baseRatio)*100) }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L214-L220
func (router *Router) sendPendingGossip() bool { sentSomething := false for conn := range router.Ourself.getConnections() { sentSomething = conn.(gossipConnection).gossipSenders().Flush() || sentSomething } return sentSomething }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/listener.go#L360-L408
func (info TLSInfo) ClientConfig() (*tls.Config, error) { var cfg *tls.Config var err error if !info.Empty() { cfg, err = info.baseConfig() if err != nil { return nil, err } } else { cfg = &tls.Config{ServerName: info.ServerName} } cfg.InsecureSkipVerify = info.InsecureSkipVerify cs := info.cafiles() if len(cs) > 0 { cfg.RootCAs, err = tlsutil.NewCertPool(cs) if err != nil { return nil, err } } if info.selfCert { cfg.InsecureSkipVerify = true } if info.EmptyCN { hasNonEmptyCN := false cn := "" tlsutil.NewCert(info.CertFile, info.KeyFile, func(certPEMBlock []byte, keyPEMBlock []byte) (tls.Certificate, error) { var block *pem.Block block, _ = pem.Decode(certPEMBlock) cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return tls.Certificate{}, err } if len(cert.Subject.CommonName) != 0 { hasNonEmptyCN = true cn = cert.Subject.CommonName } return tls.X509KeyPair(certPEMBlock, keyPEMBlock) }) if hasNonEmptyCN { return nil, fmt.Errorf("cert has non empty Common Name (%s)", cn) } } return cfg, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/client/client.go#L286-L298
func (c *Client) UpdateOne(name, state string, userData *common.UserData) error { c.lock.Lock() defer c.lock.Unlock() r, err := c.storage.Get(name) if err != nil { return fmt.Errorf("no resource name %v", name) } if err := c.update(r.GetName(), state, userData); err != nil { return err } return c.updateLocalResource(r, state, userData) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/branch_protection.go#L167-L175
func (bp BranchProtection) GetOrg(name string) *Org { o, ok := bp.Orgs[name] if ok { o.Policy = bp.Apply(o.Policy) } else { o.Policy = bp.Policy } return &o }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L190-L202
func (m *Member) Rev(ctx context.Context) (int64, error) { cli, err := m.CreateEtcdClient() if err != nil { return 0, fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() resp, err := cli.Status(ctx, m.EtcdClientEndpoint) if err != nil { return 0, err } return resp.Header.Revision, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L1863-L1867
func (v SearchMatch) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger19(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/ikawaha/kagome.ipadic/blob/fe03f87a0c7c32945d956fcfc934c3e11d5eb182/internal/dic/index.go#L105-L118
func (idx IndexTable) WriteTo(w io.Writer) (n int64, err error) { n, err = idx.Da.WriteTo(w) var b bytes.Buffer enc := gob.NewEncoder(&b) if err = enc.Encode(idx.Dup); err != nil { return } x, err := b.WriteTo(w) if err != nil { return } n += x return }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/servers.go#L55-L64
func New(opts ...Option) (s *Servers) { s = &Servers{ logger: stdLogger{}, recover: func() {}, } for _, opt := range opts { opt(s) } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L428-L430
func (p *SetPageScaleFactorParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetPageScaleFactor, p, nil) }