_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L379-L382
func (p EvaluateParams) WithThrowOnSideEffect(throwOnSideEffect bool) *EvaluateParams { p.ThrowOnSideEffect = throwOnSideEffect return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L933-L949
func (t *InitiatorType) UnmarshalEasyJSON(in *jlexer.Lexer) { switch InitiatorType(in.String()) { case InitiatorTypeParser: *t = InitiatorTypeParser case InitiatorTypeScript: *t = InitiatorTypeScript case InitiatorTypePreload: *t = InitiatorTypePreload case InitiatorTypeSignedExchange: *t = InitiatorTypeSignedExchange case InitiatorTypeOther: *t = InitiatorTypeOther default: in.AddError(errors.New("unknown InitiatorType value")) } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2857-L2865
func (u PathPaymentResult) MustNoIssuer() Asset { val, ok := u.GetNoIssuer() if !ok { panic("arm NoIssuer is not set") } return val }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/helpers.go#L147-L152
func Require(m Model, flags ...string) { // check all flags for _, f := range flags { L(m, f, true) } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L1500-L1574
func (loc *InstanceCombinationLocator) Update(options rsapi.APIParams) (*InstanceCombination, error) { var res *InstanceCombination var params rsapi.APIParams params = rsapi.APIParams{} var viewOpt = options["view"] if viewOpt != nil { params["view"] = viewOpt } var p rsapi.APIParams p = rsapi.APIParams{} var cloudNameOpt = options["cloud_name"] if cloudNameOpt != nil { p["cloud_name"] = cloudNameOpt } var cloudVendorNameOpt = options["cloud_vendor_name"] if cloudVendorNameOpt != nil { p["cloud_vendor_name"] = cloudVendorNameOpt } var datacenterNameOpt = options["datacenter_name"] if datacenterNameOpt != nil { p["datacenter_name"] = datacenterNameOpt } var instanceTypeNameOpt = options["instance_type_name"] if instanceTypeNameOpt != nil { p["instance_type_name"] = instanceTypeNameOpt } var monthlyUsageHoursOpt = options["monthly_usage_hours"] if monthlyUsageHoursOpt != nil { p["monthly_usage_hours"] = monthlyUsageHoursOpt } var monthlyUsageOptionOpt = options["monthly_usage_option"] if monthlyUsageOptionOpt != nil { p["monthly_usage_option"] = monthlyUsageOptionOpt } var patternsOpt = options["patterns"] if patternsOpt != nil { p["patterns"] = patternsOpt } var platformOpt = options["platform"] if platformOpt != nil { p["platform"] = platformOpt } var quantityOpt = options["quantity"] if quantityOpt != nil { p["quantity"] = quantityOpt } uri, err := loc.ActionPath("InstanceCombination", "update") if err != nil { return res, err } req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p) if err != nil { return res, err } resp, err := loc.api.PerformRequest(req) if err != nil { return res, err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { respBody, _ := ioutil.ReadAll(resp.Body) sr := string(respBody) if sr != "" { sr = ": " + sr } return res, fmt.Errorf("invalid response %s%s", resp.Status, sr) } defer resp.Body.Close() respBody, err := ioutil.ReadAll(resp.Body) if err != nil { return res, err } err = json.Unmarshal(respBody, &res) return res, err }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/grpcproxy/cache/store.go#L44-L51
func keyFunc(req *pb.RangeRequest) string { // TODO: use marshalTo to reduce allocation b, err := req.Marshal() if err != nil { panic(err) } return string(b) }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L350-L426
func (db *DB) Insert(obj interface{}) (affected int64, err error) { objs, rtype, tableName, err := db.tableObjs("Insert", obj) if err != nil { return -1, err } if len(objs) < 1 { return 0, nil } for _, obj := range objs { if hook, ok := obj.(BeforeInserter); ok { if err := hook.BeforeInsert(); err != nil { return -1, err } } } fieldIndexes := db.collectFieldIndexes(rtype, nil) cols := make([]string, len(fieldIndexes)) for i, index := range fieldIndexes { cols[i] = db.dialect.Quote(db.columnFromTag(rtype.FieldByIndex(index))) } var args []interface{} for _, obj := range objs { rv := reflect.Indirect(reflect.ValueOf(obj)) for _, index := range fieldIndexes { args = append(args, rv.FieldByIndex(index).Interface()) } } numHolders := 0 values := make([]string, len(objs)) holders := make([]string, len(cols)) for i := 0; i < len(values); i++ { for j := 0; j < len(holders); j++ { holders[j] = db.dialect.PlaceHolder(numHolders) numHolders++ } values[i] = fmt.Sprintf("(%s)", strings.Join(holders, ", ")) } query := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s", db.dialect.Quote(tableName), strings.Join(cols, ", "), strings.Join(values, ", "), ) stmt, err := db.prepare(query, args...) if err != nil { return -1, err } defer stmt.Close() result, err := stmt.Exec(args...) if err != nil { return -1, err } affected, _ = result.RowsAffected() if len(objs) == 1 { if pkIdx := db.findPKIndex(rtype, nil); len(pkIdx) > 0 { field := rtype.FieldByIndex(pkIdx) if db.isAutoIncrementable(&field) { id, err := db.LastInsertId() if err != nil { return affected, err } rv := reflect.Indirect(reflect.ValueOf(objs[0])).FieldByIndex(pkIdx) for rv.Kind() == reflect.Ptr { rv = rv.Elem() } rv.Set(reflect.ValueOf(id).Convert(rv.Type())) } } } for _, obj := range objs { if hook, ok := obj.(AfterInserter); ok { if err := hook.AfterInsert(); err != nil { return affected, err } } } return affected, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/domdebugger.go#L42-L45
func (p GetEventListenersParams) WithDepth(depth int64) *GetEventListenersParams { p.Depth = depth return &p }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L1382-L1453
func (loc *InstanceCombinationLocator) Create(cloudName string, cloudVendorName string, instanceTypeName string, monthlyUsageOption string, platform string, quantity int, options rsapi.APIParams) (*InstanceCombinationLocator, error) { var res *InstanceCombinationLocator if cloudName == "" { return res, fmt.Errorf("cloudName is required") } if cloudVendorName == "" { return res, fmt.Errorf("cloudVendorName is required") } if instanceTypeName == "" { return res, fmt.Errorf("instanceTypeName is required") } if monthlyUsageOption == "" { return res, fmt.Errorf("monthlyUsageOption is required") } if platform == "" { return res, fmt.Errorf("platform is required") } var params rsapi.APIParams params = rsapi.APIParams{} var viewOpt = options["view"] if viewOpt != nil { params["view"] = viewOpt } var p rsapi.APIParams p = rsapi.APIParams{ "cloud_name": cloudName, "cloud_vendor_name": cloudVendorName, "instance_type_name": instanceTypeName, "monthly_usage_option": monthlyUsageOption, "platform": platform, "quantity": quantity, } var datacenterNameOpt = options["datacenter_name"] if datacenterNameOpt != nil { p["datacenter_name"] = datacenterNameOpt } var monthlyUsageHoursOpt = options["monthly_usage_hours"] if monthlyUsageHoursOpt != nil { p["monthly_usage_hours"] = monthlyUsageHoursOpt } var patternsOpt = options["patterns"] if patternsOpt != nil { p["patterns"] = patternsOpt } uri, err := loc.ActionPath("InstanceCombination", "create") if err != nil { return res, err } req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p) if err != nil { return res, err } resp, err := loc.api.PerformRequest(req) if err != nil { return res, err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { respBody, _ := ioutil.ReadAll(resp.Body) sr := string(respBody) if sr != "" { sr = ": " + sr } return res, fmt.Errorf("invalid response %s%s", resp.Status, sr) } location := resp.Header.Get("Location") if len(location) == 0 { return res, fmt.Errorf("Missing location header in response") } else { return &InstanceCombinationLocator{Href(location), loc.api}, nil } }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/route_mappings.go#L145-L194
func (a *App) Resource(p string, r Resource) *App { g := a.Group(p) p = "/" rv := reflect.ValueOf(r) if rv.Kind() == reflect.Ptr { rv = rv.Elem() } rt := rv.Type() rname := fmt.Sprintf("%s.%s", rt.PkgPath(), rt.Name()) + ".%s" n := strings.TrimSuffix(rt.Name(), "Resource") paramName := name.New(n).ParamID().String() type paramKeyable interface { ParamKey() string } if pk, ok := r.(paramKeyable); ok { paramName = pk.ParamKey() } spath := path.Join(p, "{"+paramName+"}") setFuncKey(r.List, fmt.Sprintf(rname, "List")) g.GET(p, r.List) if n, ok := r.(newable); ok { setFuncKey(n.New, fmt.Sprintf(rname, "New")) g.GET(path.Join(p, "new"), n.New) } setFuncKey(r.Show, fmt.Sprintf(rname, "Show")) g.GET(path.Join(spath), r.Show) if n, ok := r.(editable); ok { setFuncKey(n.Edit, fmt.Sprintf(rname, "Edit")) g.GET(path.Join(spath, "edit"), n.Edit) } setFuncKey(r.Create, fmt.Sprintf(rname, "Create")) g.POST(p, r.Create) setFuncKey(r.Update, fmt.Sprintf(rname, "Update")) g.PUT(path.Join(spath), r.Update) setFuncKey(r.Destroy, fmt.Sprintf(rname, "Destroy")) g.DELETE(path.Join(spath), r.Destroy) g.Prefix = path.Join(g.Prefix, spath) return g }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/encoding/encode.go#L210-L287
func ToStringInterfaceMap(tagName string, input interface{}, properties ...string) (map[string]interface{}, error) { vmap := imap(make(map[string]interface{})) s := structs.New(input) s.TagName = tagName if len(properties) == 0 { properties = s.Names() } for _, field := range s.Fields() { if !field.IsExported() { continue } if !stringInSlice(field.Name(), properties) { continue } fieldName, opts := parseTag(field.Tag(tagName)) squash, omitempty, include := opts.Has("squash"), opts.Has("omitempty"), opts.Has("include") if !squash && (fieldName == "" || fieldName == "-") { continue } val := field.Value() if omitempty { if field.IsZero() { continue } if z, ok := val.(isZeroer); ok && z.IsZero() { continue } if z, ok := val.(isEmptier); ok && z.IsEmpty() { continue } } kind := field.Kind() if kind == reflect.Ptr { v := reflect.ValueOf(val) if v.IsNil() { if fieldName != "" && fieldName != "-" { vmap.Set(fieldName, nil) } continue } elem := v.Elem() kind = elem.Kind() val = elem.Interface() } if (squash || include) && kind == reflect.Struct { var newProperties []string for _, prop := range properties { if strings.HasPrefix(prop, field.Name()+".") { newProperties = append(newProperties, strings.TrimPrefix(prop, field.Name()+".")) } } m, err := ToStringInterfaceMap(tagName, val, newProperties...) if err != nil { return nil, err } var prefix string if !squash { prefix = fieldName + "." } for k, v := range m { vmap.Set(prefix+k, v) } continue } vmap.Set(fieldName, val) } return vmap, nil }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/tasks/get_tasks_responses.go#L25-L45
func (o *GetTasksReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewGetTasksOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil default: result := NewGetTasksDefault(response.Code()) if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } if response.Code()/100 == 2 { return result, nil } return nil, result } }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/json-decode.go#L289-L355
func (cdc *Codec) decodeReflectJSONSlice(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if !rv.CanAddr() { panic("rv not addressable") } if printLog { fmt.Println("(d) decodeReflectJSONSlice") defer func() { fmt.Printf("(d) -> err: %v\n", err) }() } var ert = info.Type.Elem() switch ert.Kind() { case reflect.Uint8: // Special case: byte slice err = json.Unmarshal(bz, rv.Addr().Interface()) if err != nil { return } if rv.Len() == 0 { // Special case when length is 0. // NOTE: We prefer nil slices. rv.Set(info.ZeroValue) } else { // NOTE: Already set via json.Unmarshal() above. } return default: // General case. var einfo *TypeInfo einfo, err = cdc.getTypeInfo_wlock(ert) if err != nil { return } // Read into rawSlice. var rawSlice []json.RawMessage if err = json.Unmarshal(bz, &rawSlice); err != nil { return } // Special case when length is 0. // NOTE: We prefer nil slices. var length = len(rawSlice) if length == 0 { rv.Set(info.ZeroValue) return } // Read into a new slice. var esrt = reflect.SliceOf(ert) // TODO could be optimized. var srv = reflect.MakeSlice(esrt, length, length) for i := 0; i < length; i++ { erv := srv.Index(i) ebz := rawSlice[i] err = cdc.decodeReflectJSON(ebz, einfo, erv, fopts) if err != nil { return } } // TODO do we need this extra step? rv.Set(srv) return } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L274-L281
func (r *Alert) Locator(api *API) *AlertLocator { for _, l := range r.Links { if l["rel"] == "self" { return api.AlertLocator(l["href"]) } } return nil }
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/tracer.go#L58-L60
func (NopTracer) Done(re *Response, err error) (*Response, error) { return re, err }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.go#L118-L127
func (c *ClusterTx) ProjectHasImages(name string) (bool, error) { project, err := c.ProjectGet(name) if err != nil { return false, errors.Wrap(err, "fetch project") } enabled := project.Config["features.images"] == "true" return enabled, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/errors.go#L29-L37
func (l ErrorList) Error() string { switch len(l) { case 0: return "no errors" case 1: return l[0].Error() } return fmt.Sprintf("%s (and %d more errors)", l[0], len(l)-1) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L7115-L7119
func (v *BoxModel) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom78(&r, v) return r.Error() }
https://github.com/Financial-Times/neo-model-utils-go/blob/aea1e95c83055aaed6761c5e546400dd383fb220/mapper/types.go#L51-L60
func MostSpecificType(types []string) (string, error) { if len(types) == 0 { return "", errors.New("no types supplied") } sorted, err := SortTypes(types) if err != nil { return "", err } return sorted[len(sorted)-1], nil }
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/add.go#L63-L65
func (s *Shell) AddNoPin(r io.Reader) (string, error) { return s.Add(r, Pin(false)) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6673-L6681
func (u StellarMessage) MustQSetHash() Uint256 { val, ok := u.GetQSetHash() if !ok { panic("arm QSetHash is not set") } return val }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L1314-L1318
func (v GetAllTimeSamplingProfileParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoMemory15(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L617-L631
func (c *Client) ReplaceConfigMap(name string, config ConfigMap) (ConfigMap, error) { c.log("ReplaceConfigMap", name) namespace := c.namespace if config.Namespace != "" { namespace = config.Namespace } var retConfigMap ConfigMap err := c.request(&request{ method: http.MethodPut, path: fmt.Sprintf("/api/v1/namespaces/%s/configmaps/%s", namespace, name), requestBody: &config, }, &retConfigMap) return retConfigMap, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L321-L330
func (p *TakeResponseBodyAsStreamParams) Do(ctx context.Context) (stream io.StreamHandle, err error) { // execute var res TakeResponseBodyAsStreamReturns err = cdp.Execute(ctx, CommandTakeResponseBodyAsStream, p, &res) if err != nil { return "", err } return res.Stream, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/coverage/downloader/downloader.go#L41-L65
func listGcsObjects(ctx context.Context, client *storage.Client, bucketName, prefix, delim string) ( []string, error) { var objects []string it := client.Bucket(bucketName).Objects(ctx, &storage.Query{ Prefix: prefix, Delimiter: delim, }) for { attrs, err := it.Next() if err == iterator.Done { break } if err != nil { return objects, fmt.Errorf("error iterating: %v", err) } if attrs.Prefix != "" { objects = append(objects, path.Base(attrs.Prefix)) } } logrus.Info("end of listGcsObjects(...)") return objects, nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/arguments.go#L86-L92
func (r ArgReadHelper) Read(bs *[]byte) error { return r.read(func() error { var err error *bs, err = ioutil.ReadAll(r.reader) return err }) }
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/alias.go#L20-L22
func (a Alias) Email() string { return fmt.Sprintf("%s@%s", a.Name, a.account.Domain.Name) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L61-L67
func (v *ValueStruct) Decode(b []byte) { v.Meta = b[0] v.UserMeta = b[1] var sz int v.ExpiresAt, sz = binary.Uvarint(b[2:]) v.Value = b[2+sz:] }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/form.go#L16-L18
func (f *FormErrors) AddError(e string) { f.Errors = append(f.Errors, e) }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L264-L266
func (s *MockSpan) LogEventWithPayload(event string, payload interface{}) { s.LogFields(log.String("event", event), log.Object("payload", payload)) }
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/assetfs/filesystem.go#L19-L34
func (fs *AssetFileSystem) RegisterPath(pth string) error { if _, err := os.Stat(pth); !os.IsNotExist(err) { var existing bool for _, p := range fs.paths { if p == pth { existing = true break } } if !existing { fs.paths = append(fs.paths, pth) } return nil } return errors.New("not found") }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L47-L49
func (t ResourceType) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/controller.go#L260-L307
func (c *Controller) terminateDupes(pjs []prowapi.ProwJob, jbs map[string]Build) error { // "job org/repo#number" -> newest job dupes := make(map[string]int) for i, pj := range pjs { if pj.Complete() || pj.Spec.Type != prowapi.PresubmitJob { continue } n := fmt.Sprintf("%s %s/%s#%d", pj.Spec.Job, pj.Spec.Refs.Org, pj.Spec.Refs.Repo, pj.Spec.Refs.Pulls[0].Number) prev, ok := dupes[n] if !ok { dupes[n] = i continue } cancelIndex := i if (&pjs[prev].Status.StartTime).Before(&pj.Status.StartTime) { cancelIndex = prev dupes[n] = i } toCancel := pjs[cancelIndex] // Allow aborting presubmit jobs for commits that have been superseded by // newer commits in GitHub pull requests. if c.config().AllowCancellations { build, buildExists := jbs[toCancel.ObjectMeta.Name] // Avoid cancelling enqueued builds. if buildExists && build.IsEnqueued() { continue } // Otherwise, abort it. if buildExists { if err := c.jc.Abort(getJobName(&toCancel.Spec), &build); err != nil { c.log.WithError(err).WithFields(pjutil.ProwJobFields(&toCancel)).Warn("Cannot cancel Jenkins build") } } } toCancel.SetComplete() prevState := toCancel.Status.State toCancel.Status.State = prowapi.AbortedState c.log.WithFields(pjutil.ProwJobFields(&toCancel)). WithField("from", prevState). WithField("to", toCancel.Status.State).Info("Transitioning states.") npj, err := c.prowJobClient.Update(&toCancel) if err != nil { return err } pjs[cancelIndex] = *npj } return nil }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L1013-L1018
func (g *Glg) FailFunc(f func() string) error { if g.isModeEnable(FAIL) { return g.out(FAIL, "%s", f()) } return nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_transport.go#L79-L94
func NewReference(dir, image string) (types.ImageReference, error) { resolved, err := explicitfilepath.ResolvePathToFullyExplicit(dir) if err != nil { return nil, err } if err := internal.ValidateOCIPath(dir); err != nil { return nil, err } if err = internal.ValidateImageName(image); err != nil { return nil, err } return ociReference{dir: dir, resolvedDir: resolved, image: image}, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/router.go#L204-L233
func removeAppRouter(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { appName := r.URL.Query().Get(":app") routerName := r.URL.Query().Get(":router") a, err := getAppFromContext(appName, r) if err != nil { return err } allowed := permission.Check(t, permission.PermAppUpdateRouterRemove, contextsForApp(&a)..., ) if !allowed { return permission.ErrUnauthorized } evt, err := event.New(&event.Opts{ Target: appTarget(appName), Kind: permission.PermAppUpdateRouterRemove, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(&a)...), }) if err != nil { return err } defer func() { evt.Done(err) }() err = a.RemoveRouter(routerName) if _, isNotFound := err.(*router.ErrRouterNotFound); isNotFound { return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()} } return err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/easyjson.go#L752-L756
func (v GetCategoriesReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTracing6(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/config.go#L96-L110
func deleteConfig(tx *sql.Tx, table string, keys []string) error { n := len(keys) if n == 0 { return nil // Nothing to delete. } query := fmt.Sprintf("DELETE FROM %s WHERE key IN %s", table, Params(n)) values := make([]interface{}, n) for i, key := range keys { values[i] = key } _, err := tx.Exec(query, values...) return err }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/embed/etcd.go#L95-L251
func StartEtcd(inCfg *Config) (e *Etcd, err error) { if err = inCfg.Validate(); err != nil { return nil, err } serving := false e = &Etcd{cfg: *inCfg, stopc: make(chan struct{})} cfg := &e.cfg defer func() { if e == nil || err == nil { return } if !serving { // errored before starting gRPC server for serveCtx.serversC for _, sctx := range e.sctxs { close(sctx.serversC) } } e.Close() e = nil }() if e.cfg.logger != nil { e.cfg.logger.Info( "configuring peer listeners", zap.Strings("listen-peer-urls", e.cfg.getLPURLs()), ) } if e.Peers, err = configurePeerListeners(cfg); err != nil { return e, err } if e.cfg.logger != nil { e.cfg.logger.Info( "configuring client listeners", zap.Strings("listen-client-urls", e.cfg.getLCURLs()), ) } if e.sctxs, err = configureClientListeners(cfg); err != nil { return e, err } for _, sctx := range e.sctxs { e.Clients = append(e.Clients, sctx.l) } var ( urlsmap types.URLsMap token string ) memberInitialized := true if !isMemberInitialized(cfg) { memberInitialized = false urlsmap, token, err = cfg.PeerURLsMapAndToken("etcd") if err != nil { return e, fmt.Errorf("error setting up initial cluster: %v", err) } } // AutoCompactionRetention defaults to "0" if not set. if len(cfg.AutoCompactionRetention) == 0 { cfg.AutoCompactionRetention = "0" } autoCompactionRetention, err := parseCompactionRetention(cfg.AutoCompactionMode, cfg.AutoCompactionRetention) if err != nil { return e, err } backendFreelistType := parseBackendFreelistType(cfg.ExperimentalBackendFreelistType) srvcfg := etcdserver.ServerConfig{ Name: cfg.Name, ClientURLs: cfg.ACUrls, PeerURLs: cfg.APUrls, DataDir: cfg.Dir, DedicatedWALDir: cfg.WalDir, SnapshotCount: cfg.SnapshotCount, SnapshotCatchUpEntries: cfg.SnapshotCatchUpEntries, MaxSnapFiles: cfg.MaxSnapFiles, MaxWALFiles: cfg.MaxWalFiles, InitialPeerURLsMap: urlsmap, InitialClusterToken: token, DiscoveryURL: cfg.Durl, DiscoveryProxy: cfg.Dproxy, NewCluster: cfg.IsNewCluster(), PeerTLSInfo: cfg.PeerTLSInfo, TickMs: cfg.TickMs, ElectionTicks: cfg.ElectionTicks(), InitialElectionTickAdvance: cfg.InitialElectionTickAdvance, AutoCompactionRetention: autoCompactionRetention, AutoCompactionMode: cfg.AutoCompactionMode, QuotaBackendBytes: cfg.QuotaBackendBytes, BackendBatchLimit: cfg.BackendBatchLimit, BackendFreelistType: backendFreelistType, BackendBatchInterval: cfg.BackendBatchInterval, MaxTxnOps: cfg.MaxTxnOps, MaxRequestBytes: cfg.MaxRequestBytes, StrictReconfigCheck: cfg.StrictReconfigCheck, ClientCertAuthEnabled: cfg.ClientTLSInfo.ClientCertAuth, AuthToken: cfg.AuthToken, BcryptCost: cfg.BcryptCost, CORS: cfg.CORS, HostWhitelist: cfg.HostWhitelist, InitialCorruptCheck: cfg.ExperimentalInitialCorruptCheck, CorruptCheckTime: cfg.ExperimentalCorruptCheckTime, PreVote: cfg.PreVote, Logger: cfg.logger, LoggerConfig: cfg.loggerConfig, LoggerCore: cfg.loggerCore, LoggerWriteSyncer: cfg.loggerWriteSyncer, Debug: cfg.Debug, ForceNewCluster: cfg.ForceNewCluster, EnableGRPCGateway: cfg.EnableGRPCGateway, } print(e.cfg.logger, *cfg, srvcfg, memberInitialized) if e.Server, err = etcdserver.NewServer(srvcfg); err != nil { return e, err } // buffer channel so goroutines on closed connections won't wait forever e.errc = make(chan error, len(e.Peers)+len(e.Clients)+2*len(e.sctxs)) // newly started member ("memberInitialized==false") // does not need corruption check if memberInitialized { if err = e.Server.CheckInitialHashKV(); err != nil { // set "EtcdServer" to nil, so that it does not block on "EtcdServer.Close()" // (nothing to close since rafthttp transports have not been started) e.Server = nil return e, err } } e.Server.Start() if err = e.servePeers(); err != nil { return e, err } if err = e.serveClients(); err != nil { return e, err } if err = e.serveMetrics(); err != nil { return e, err } if e.cfg.logger != nil { e.cfg.logger.Info( "now serving peer/client/metrics", zap.String("local-member-id", e.Server.ID().String()), zap.Strings("initial-advertise-peer-urls", e.cfg.getAPURLs()), zap.Strings("listen-peer-urls", e.cfg.getLPURLs()), zap.Strings("advertise-client-urls", e.cfg.getACURLs()), zap.Strings("listen-client-urls", e.cfg.getLCURLs()), zap.Strings("listen-metrics-urls", e.cfg.getMetricsURLs()), ) } serving = true return e, nil }
https://github.com/goware/urlx/blob/4fc201f7f862af2abfaca0c2904be15ea0037a34/urlx.go#L191-L197
func ResolveString(rawURL string) (*net.IPAddr, error) { u, err := Parse(rawURL) if err != nil { return nil, err } return Resolve(u) }
https://github.com/jstemmer/go-junit-report/blob/af01ea7f8024089b458d804d5cdf190f962a9a0c/parser/parser.go#L291-L303
func (r *Report) Failures() int { count := 0 for _, p := range r.Packages { for _, t := range p.Tests { if t.Result == FAIL { count++ } } } return count }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L93-L96
func (e CryptoKeyType) String() string { name, _ := cryptoKeyTypeMap[int32(e)] return name }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/client.go#L195-L200
func WithRootCAs(path string) Option { return func(settings *clientSettings) error { settings.caCerts = x509.NewCertPool() return addCertFromFile(settings.caCerts, path) } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/issue-creator/sources/triage-filer.go#L133-L201
func (f *TriageFiler) filterAndValidate(windowDays int) error { f.latestStart = int64(0) for _, start := range f.data.Builds.Cols.Started { if start > f.latestStart { f.latestStart = start } } cutoffTime := time.Unix(f.latestStart, 0).AddDate(0, 0, -windowDays).Unix() validClusts := []*Cluster{} for clustIndex, clust := range f.data.Clustered { if len(clust.Identifier) == 0 { return fmt.Errorf("the cluster at index %d in the triage JSON data does not specify an ID", clustIndex) } if clust.Tests == nil { return fmt.Errorf("cluster '%s' does not have a 'tests' key", clust.Identifier) } validTests := []*Test{} for _, test := range clust.Tests { if len(test.Name) == 0 { return fmt.Errorf("cluster '%s' contains a test without a name", clust.Identifier) } if test.Jobs == nil { return fmt.Errorf("cluster '%s' does not have a 'jobs' key", clust.Identifier) } validJobs := []*Job{} for _, job := range test.Jobs { if len(job.Name) == 0 { return fmt.Errorf("cluster '%s' contains a job without a name under test '%s'", clust.Identifier, test.Name) } // Filter out PR jobs if strings.HasPrefix(job.Name, "pr:") { continue } if len(job.Builds) == 0 { return fmt.Errorf("cluster '%s' contains job '%s' under test '%s' with no failing builds", clust.Identifier, job.Name, test.Name) } validBuilds := []int{} rowMap, ok := f.data.Builds.Jobs[job.Name] if !ok { return fmt.Errorf("triage json data does not contain buildnum to row index mapping for job '%s'", job.Name) } for _, buildnum := range job.Builds { row, err := rowMap.rowForBuild(buildnum) if err != nil { return err } if f.data.Builds.Cols.Started[row] > cutoffTime { validBuilds = append(validBuilds, buildnum) } } if len(validBuilds) > 0 { job.Builds = validBuilds validJobs = append(validJobs, job) } } if len(validJobs) > 0 { test.Jobs = validJobs validTests = append(validTests, test) } } if len(validTests) > 0 { clust.Tests = validTests validClusts = append(validClusts, clust) } } f.data.Clustered = validClusts return nil }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/types/pact_message_request.go#L27-L49
func (m *PactMessageRequest) Validate() error { m.Args = []string{} body, err := json.Marshal(m.Message) if err != nil { return err } m.Args = append(m.Args, []string{ "update", string(body), "--consumer", m.Consumer, "--provider", m.Provider, "--pact-dir", m.PactDir, "--pact-specification-version", "3", }...) return nil }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/atomic_rbuf.go#L285-L320
func (b *AtomicFixedSizeRingBuf) Write(p []byte) (n int, err error) { b.tex.Lock() defer b.tex.Unlock() for { if len(p) == 0 { // nothing (left) to copy in; notice we shorten our // local copy p (below) as we read from it. return } writeCapacity := b.N - b.readable if writeCapacity <= 0 { // we are all full up already. return n, io.ErrShortWrite } if len(p) > writeCapacity { err = io.ErrShortWrite // leave err set and // keep going, write what we can. } writeStart := (b.Beg + b.readable) % b.N upperLim := intMin2(writeStart+writeCapacity, b.N) k := copy(b.A[b.Use][writeStart:upperLim], p) n += k b.readable += k p = p[k:] // we can fill from b.A[b.Use][0:something] from // p's remainder, so loop } }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L875-L880
func WarnFunc(f func() string) error { if isModeEnable(WARN) { return glg.out(WARN, "%s", f()) } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L314-L321
func EmulateTouchFromMouseEvent(typeVal MouseType, x int64, y int64, button ButtonType) *EmulateTouchFromMouseEventParams { return &EmulateTouchFromMouseEventParams{ Type: typeVal, X: x, Y: y, Button: button, } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util.go#L551-L559
func StringMapHasStringKey(m map[string]string, keys ...string) bool { for _, k := range keys { if _, ok := m[k]; ok { return true } } return false }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/refresh/refresh.go#L11-L23
func New(opts *Options) (*genny.Generator, error) { g := genny.New() if err := opts.Validate(); err != nil { return g, err } g.Box(packr.New("buffalo:genny:refresh", "../refresh/templates")) ctx := plush.NewContext() ctx.Set("app", opts.App) g.Transformer(plushgen.Transformer(ctx)) g.Transformer(genny.Dot()) return g, nil }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/task.go#L43-L59
func (m Task) MarshalJSON() ([]byte, error) { var _parts [][]byte aO0, err := swag.WriteJSON(m.NewTask) if err != nil { return nil, err } _parts = append(_parts, aO0) aO1, err := swag.WriteJSON(m.TaskAllOf1) if err != nil { return nil, err } _parts = append(_parts, aO1) return swag.ConcatJSON(_parts...), nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/gw/rpc.pb.gw.go#L678-L680
func RegisterKVHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterKVHandlerClient(ctx, mux, etcdserverpb.NewKVClient(conn)) }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_apache.go#L183-L188
func (u *accessLogUtil) ApacheQueryString() string { if u.R.URL.RawQuery != "" { return "?" + u.R.URL.RawQuery } return "" }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L2405-L2429
func (d *driver) getTreeForFile(pachClient *client.APIClient, file *pfs.File) (hashtree.HashTree, error) { if file.Commit == nil { t, err := hashtree.NewDBHashTree(d.storageRoot) if err != nil { return nil, err } return t, nil } commitInfo, err := d.inspectCommit(pachClient, file.Commit, pfs.CommitState_STARTED) if err != nil { return nil, err } if commitInfo.Finished != nil { tree, err := d.getTreeForCommit(pachClient, file.Commit) if err != nil { return nil, err } return tree, nil } parentTree, err := d.getTreeForCommit(pachClient, commitInfo.ParentCommit) if err != nil { return nil, err } return d.getTreeForOpenCommit(pachClient, file, parentTree) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/level_handler.go#L288-L299
func (s *levelHandler) overlappingTables(_ levelHandlerRLocked, kr keyRange) (int, int) { if len(kr.left) == 0 || len(kr.right) == 0 { return 0, 0 } left := sort.Search(len(s.tables), func(i int) bool { return y.CompareKeys(kr.left, s.tables[i].Biggest()) <= 0 }) right := sort.Search(len(s.tables), func(i int) bool { return y.CompareKeys(kr.right, s.tables[i].Smallest()) < 0 }) return left, right }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L175-L186
func (f *FakeClient) DeleteComment(owner, repo string, ID int) error { f.IssueCommentsDeleted = append(f.IssueCommentsDeleted, fmt.Sprintf("%s/%s#%d", owner, repo, ID)) for num, ics := range f.IssueComments { for i, ic := range ics { if ic.ID == ID { f.IssueComments[num] = append(ics[:i], ics[i+1:]...) return nil } } } return fmt.Errorf("could not find issue comment %d", ID) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cast/easyjson.go#L314-L318
func (v EventSinksUpdated) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCast3(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/io/easyjson.go#L331-L335
func (v ReadParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoIo3(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/animation.go#L189-L194
func SeekAnimations(animations []string, currentTime float64) *SeekAnimationsParams { return &SeekAnimationsParams{ Animations: animations, CurrentTime: currentTime, } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/lease_command.go#L135-L142
func NewLeaseListCommand() *cobra.Command { lc := &cobra.Command{ Use: "list", Short: "List all active leases", Run: leaseListCommandFunc, } return lc }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/walk/walk.go#L221-L227
func shouldVisit(rel string, mode Mode, updateRels map[string]bool) bool { if mode != UpdateDirsMode { return true } _, ok := updateRels[rel] return ok }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/controller.go#L186-L205
func (c *Controller) StrLenIn(fieldName string, p interface{}, l ...int) string { if p == nil { p = "" } v, ok := p.(string) if ok == false { panic((&ValidationError{}).New(fieldName + "格式错误")) } length := utf8.RuneCountInString(v) b := false for i := 0; i < len(l); i++ { if l[i] == length { b = true } } if b == false { panic((&ValidationError{}).New(fieldName + "值的长度应该在" + strings.Replace(strings.Trim(fmt.Sprint(l), "[]"), " ", ",", -1) + "中")) } return v }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/snapshot/v3_snapshot.go#L412-L494
func (s *v3Manager) saveWALAndSnap() error { if err := fileutil.CreateDirAll(s.walDir); err != nil { return err } // add members again to persist them to the store we create. st := v2store.New(etcdserver.StoreClusterPrefix, etcdserver.StoreKeysPrefix) s.cl.SetStore(st) for _, m := range s.cl.Members() { s.cl.AddMember(m) } m := s.cl.MemberByName(s.name) md := &etcdserverpb.Metadata{NodeID: uint64(m.ID), ClusterID: uint64(s.cl.ID())} metadata, merr := md.Marshal() if merr != nil { return merr } w, walerr := wal.Create(s.lg, s.walDir, metadata) if walerr != nil { return walerr } defer w.Close() peers := make([]raft.Peer, len(s.cl.MemberIDs())) for i, id := range s.cl.MemberIDs() { ctx, err := json.Marshal((*s.cl).Member(id)) if err != nil { return err } peers[i] = raft.Peer{ID: uint64(id), Context: ctx} } ents := make([]raftpb.Entry, len(peers)) nodeIDs := make([]uint64, len(peers)) for i, p := range peers { nodeIDs[i] = p.ID cc := raftpb.ConfChange{ Type: raftpb.ConfChangeAddNode, NodeID: p.ID, Context: p.Context, } d, err := cc.Marshal() if err != nil { return err } ents[i] = raftpb.Entry{ Type: raftpb.EntryConfChange, Term: 1, Index: uint64(i + 1), Data: d, } } commit, term := uint64(len(ents)), uint64(1) if err := w.Save(raftpb.HardState{ Term: term, Vote: peers[0].ID, Commit: commit, }, ents); err != nil { return err } b, berr := st.Save() if berr != nil { return berr } raftSnap := raftpb.Snapshot{ Data: b, Metadata: raftpb.SnapshotMetadata{ Index: commit, Term: term, ConfState: raftpb.ConfState{ Nodes: nodeIDs, }, }, } sn := snap.New(s.lg, s.snapDir) if err := sn.SaveSnap(raftSnap); err != nil { return err } return w.SaveSnapshot(walpb.Snapshot{Index: commit, Term: term}) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_cluster.go#L112-L123
func (r *ProtocolLXD) RenameClusterMember(name string, member api.ClusterMemberPost) error { if !r.HasExtension("clustering") { return fmt.Errorf("The server is missing the required \"clustering\" API extension") } _, _, err := r.query("POST", fmt.Sprintf("/cluster/members/%s", name), member, "") if err != nil { return err } return nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistriesv2/system_registries_v2.go#L194-L249
func postProcessRegistries(regs []Registry) ([]Registry, error) { var registries []Registry regMap := make(map[string][]Registry) for _, reg := range regs { var err error // make sure Location and Prefix are valid reg.Location, err = parseLocation(reg.Location) if err != nil { return nil, err } if reg.Prefix == "" { reg.Prefix = reg.Location } else { reg.Prefix, err = parseLocation(reg.Prefix) if err != nil { return nil, err } } // make sure mirrors are valid for _, mir := range reg.Mirrors { mir.Location, err = parseLocation(mir.Location) if err != nil { return nil, err } } registries = append(registries, reg) regMap[reg.Location] = append(regMap[reg.Location], reg) } // Given a registry can be mentioned multiple times (e.g., to have // multiple prefixes backed by different mirrors), we need to make sure // there are no conflicts among them. // // Note: we need to iterate over the registries array to ensure a // deterministic behavior which is not guaranteed by maps. for _, reg := range registries { others, _ := regMap[reg.Location] for _, other := range others { if reg.Insecure != other.Insecure { msg := fmt.Sprintf("registry '%s' is defined multiple times with conflicting 'insecure' setting", reg.Location) return nil, &InvalidRegistries{s: msg} } if reg.Blocked != other.Blocked { msg := fmt.Sprintf("registry '%s' is defined multiple times with conflicting 'blocked' setting", reg.Location) return nil, &InvalidRegistries{s: msg} } } } return registries, nil }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/dominator.go#L298-L300
func (d *ltDom) link(v, w vName) { d.ancestor[w] = v }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1309-L1319
func (c *Client) GetRepo(owner, name string) (Repo, error) { c.log("GetRepo", owner, name) var repo Repo _, err := c.request(&request{ method: http.MethodGet, path: fmt.Sprintf("/repos/%s/%s", owner, name), exitCodes: []int{200}, }, &repo) return repo, err }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/serviceenv/service_env.go#L186-L194
func (env *ServiceEnv) GetKubeClient() *kube.Clientset { if err := env.kubeEg.Wait(); err != nil { panic(err) // If env can't connect, there's no sensible way to recover } if env.kubeClient == nil { panic("service env never connected to kubernetes") } return env.kubeClient }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/memory.go#L229-L238
func (p *GetBrowserSamplingProfileParams) Do(ctx context.Context) (profile *SamplingProfile, err error) { // execute var res GetBrowserSamplingProfileReturns err = cdp.Execute(ctx, CommandGetBrowserSamplingProfile, nil, &res) if err != nil { return nil, err } return res.Profile, nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/skl/arena.go#L123-L126
func (s *Arena) getVal(offset uint32, size uint16) (ret y.ValueStruct) { ret.Decode(s.buf[offset : offset+uint32(size)]) return }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/json-decode.go#L415-L466
func (cdc *Codec) decodeReflectJSONMap(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if !rv.CanAddr() { panic("rv not addressable") } if printLog { fmt.Println("(d) decodeReflectJSONMap") defer func() { fmt.Printf("(d) -> err: %v\n", err) }() } // Map all the fields(keys) to their blobs/bytes. // NOTE: In decodeReflectBinaryMap, we don't need to do this, // since fields are encoded in order. var rawMap = make(map[string]json.RawMessage) err = json.Unmarshal(bz, &rawMap) if err != nil { return } var krt = rv.Type().Key() if krt.Kind() != reflect.String { err = fmt.Errorf("decodeReflectJSONMap: key type must be string") // TODO also support []byte and maybe others return } var vinfo *TypeInfo vinfo, err = cdc.getTypeInfo_wlock(rv.Type().Elem()) if err != nil { return } var mrv = reflect.MakeMapWithSize(rv.Type(), len(rawMap)) for key, valueBytes := range rawMap { // Get map value rv. vrv := reflect.New(mrv.Type().Elem()).Elem() // Decode valueBytes into vrv. err = cdc.decodeReflectJSON(valueBytes, vinfo, vrv, fopts) if err != nil { return } // And set. krv := reflect.New(reflect.TypeOf("")).Elem() krv.SetString(key) mrv.SetMapIndex(krv, vrv) } rv.Set(mrv) return nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction_envelope.go#L92-L111
func (m Sign) MutateTransactionEnvelope(txe *TransactionEnvelopeBuilder) error { hash, err := txe.child.Hash() if err != nil { return err } kp, err := keypair.Parse(m.Seed) if err != nil { return err } sig, err := kp.SignDecorated(hash[:]) if err != nil { return err } txe.E.Signatures = append(txe.E.Signatures, sig) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L939-L948
func (p *SearchInResourceParams) Do(ctx context.Context) (result []*debugger.SearchMatch, err error) { // execute var res SearchInResourceReturns err = cdp.Execute(ctx, CommandSearchInResource, p, &res) if err != nil { return nil, err } return res.Result, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/parse.go#L40-L59
func Filters(pkg *ast.Package, entity string) [][]string { objects := pkg.Scope.Objects filters := [][]string{} prefix := fmt.Sprintf("%sObjectsBy", entity) for name := range objects { if !strings.HasPrefix(name, prefix) { continue } rest := name[len(prefix):] filters = append(filters, strings.Split(rest, "And")) } sort.SliceStable(filters, func(i, j int) bool { return len(filters[i]) > len(filters[j]) }) return filters }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage/quota/projectquota.go#L208-L219
func GetProject(path string) (uint32, error) { // Call ioctl through CGo cPath := C.CString(path) defer C.free(unsafe.Pointer(cPath)) id := C.quota_get_path(cPath) if id < 0 { return 0, fmt.Errorf("Failed to get project from '%s'", path) } return uint32(id), nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/minio_client.go#L19-L28
func newMinioClient(endpoint, bucket, id, secret string, secure bool) (*minioClient, error) { mclient, err := minio.New(endpoint, id, secret, secure) if err != nil { return nil, err } return &minioClient{ bucket: bucket, Client: mclient, }, nil }
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/lyra2.go#L454-L602
func lyra2(k []byte, pwd []byte, salt []byte, timeCost uint64, nRows int, nCols int) { //============================= Basic variables ============================// row := 2 //index of row to be processed prev := 1 //index of prev (last row ever computed/modified) var rowa uint64 //index of row* (a previous row, deterministically picked during Setup and randomly picked while Wandering) var tau uint64 //Time Loop iterator step := 1 //Visitation step (used during Setup and Wandering phases) var window uint64 = 2 //Visitation window (used to define which rows can be revisited during Setup) var gap uint64 = 1 //Modifier to the step, assuming the values 1 or -1 var i int //auxiliary iteration counter //==========================================================================/ //========== Initializing the Memory Matrix and pointers to it =============// //Tries to allocate enough space for the whole memory matrix rowLenInt64 := blockLenInt64 * nCols //rowLenBytes := rowLenInt64 * 8 i = nRows * rowLenInt64 wholeMatrix := make([]uint64, i) //Allocates pointers to each row of the matrix memMatrix := make([][]uint64, nRows) //Places the pointers in the correct positions ptrWord := 0 for i = 0; i < nRows; i++ { memMatrix[i] = wholeMatrix[ptrWord:] ptrWord += rowLenInt64 } //==========================================================================/ //============= Getting the password + salt + basil padded with 10*1 ===============// //OBS.:The memory matrix will temporarily hold the password: not for saving memory, //but this ensures that the password copied locally will be overwritten as soon as possible //First, we clean enough blocks for the password, salt, basil and padding nBlocksInput := ((len(salt) + len(pwd) + 6*8) / blockLenBlake2SafeBytes) + 1 ptrByte := 0 // (byte*) wholeMatrix; //Prepends the password for j := 0; j < len(pwd)/8; j++ { wholeMatrix[ptrByte+j] = binary.LittleEndian.Uint64(pwd[j*8:]) } ptrByte += len(pwd) / 8 //Concatenates the salt for j := 0; j < len(salt)/8; j++ { wholeMatrix[ptrByte+j] = binary.LittleEndian.Uint64(salt[j*8:]) } ptrByte += len(salt) / 8 //Concatenates the basil: every integer passed as parameter, in the order they are provided by the interface wholeMatrix[ptrByte] = uint64(len(k)) ptrByte++ wholeMatrix[ptrByte] = uint64(len(pwd)) ptrByte++ wholeMatrix[ptrByte] = uint64(len(salt)) ptrByte++ wholeMatrix[ptrByte] = timeCost ptrByte++ wholeMatrix[ptrByte] = uint64(nRows) ptrByte++ wholeMatrix[ptrByte] = uint64(nCols) ptrByte++ //Now comes the padding wholeMatrix[ptrByte] = 0x80 //first byte of padding: right after the password //resets the pointer to the start of the memory matrix ptrByte = (nBlocksInput*blockLenBlake2SafeBytes)/8 - 1 //sets the pointer to the correct position: end of incomplete block wholeMatrix[ptrByte] ^= 0x0100000000000000 //last byte of padding: at the end of the last incomplete block00 //==========================================================================/ //======================= Initializing the Sponge State ====================// //Sponge state: 16 uint64_t, BLOCK_LEN_INT64 words of them for the bitrate (b) and the remainder for the capacity (c) state := initState() //==========================================================================/ //================================ Setup Phase =============================// //Absorbing salt, password and basil: this is the only place in which the block length is hard-coded to 512 bits ptrWord = 0 for i = 0; i < nBlocksInput; i++ { absorbBlockBlake2Safe(state, wholeMatrix[ptrWord:]) //absorbs each block of pad(pwd || salt || basil) ptrWord += blockLenBlake2SafeInt64 //goes to next block of pad(pwd || salt || basil) } //Initializes M[0] and M[1] reducedSqueezeRow0(state, memMatrix[0], nCols) //The locally copied password is most likely overwritten here reducedDuplexRow1(state, memMatrix[0], memMatrix[1], nCols) for row < nRows { //M[row] = rand; //M[row*] = M[row*] XOR rotW(rand) reducedDuplexRowSetup(state, memMatrix[prev], memMatrix[rowa], memMatrix[row], nCols) //updates the value of row* (deterministically picked during Setup)) rowa = (rowa + uint64(step)) & (window - 1) //update prev: it now points to the last row ever computed prev = row //updates row: goes to the next row to be computed row++ //Checks if all rows in the window where visited. if rowa == 0 { step = int(window + gap) //changes the step: approximately doubles its value window *= 2 //doubles the size of the re-visitation window gap = -gap //inverts the modifier to the step } } //==========================================================================/ //============================ Wandering Phase =============================// row = 0 //Resets the visitation to the first row of the memory matrix for tau = 1; tau <= timeCost; tau++ { //Step is approximately half the number of all rows of the memory matrix for an odd tau; otherwise, it is -1 step = nRows/2 - 1 if tau%2 == 0 { step = -1 } for row0 := false; !row0; row0 = (row == 0) { //Selects a pseudorandom index row* //------------------------------------------------------------------------------------------ //rowa = ((unsigned int)state[0]) & (nRows-1); //(USE THIS IF nRows IS A POWER OF 2) rowa = state[0] % uint64(nRows) //(USE THIS FOR THE "GENERIC" CASE) //------------------------------------------------------------------------------------------ //Performs a reduced-round duplexing operation over M[row*] XOR M[prev], updating both M[row*] and M[row] reducedDuplexRow(state, memMatrix[prev], memMatrix[rowa], memMatrix[row], nCols) //update prev: it now points to the last row ever computed prev = row //updates row: goes to the next row to be computed //------------------------------------------------------------------------------------------ //row = (row + step) & (nRows-1); //(USE THIS IF nRows IS A POWER OF 2) row = (row + step) % nRows //(USE THIS FOR THE "GENERIC" CASE) //------------------------------------------------------------------------------------------ } } //==========================================================================/ //============================ Wrap-up Phase ===============================// //Absorbs the last block of the memory matrix absorbBlock(state, memMatrix[rowa]) //Squeezes the key squeeze(state, k) //==========================================================================/ }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L449-L452
func (s *FileSequence) SetPaddingStyle(style PadStyle) { s.padMapper = padders[style] s.SetPadding(s.padMapper.PaddingChars(s.ZFill())) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1200-L1209
func (p *ResolveNodeParams) Do(ctx context.Context) (object *runtime.RemoteObject, err error) { // execute var res ResolveNodeReturns err = cdp.Execute(ctx, CommandResolveNode, p, &res) if err != nil { return nil, err } return res.Object, nil }
https://github.com/insionng/martini/blob/2d0ba5dc75fe9549c10e2f71927803a11e5e4957/context.go#L75-L77
func (ctx *Cotex) WriteString(content string) { ctx.ResponseWriter.Write([]byte(content)) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L57-L61
func (v TerminateExecutionParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/lyra2re2.go#L38-L59
func Sum(data []byte) ([]byte, error) { blake := blake256.New() if _, err := blake.Write(data); err != nil { return nil, err } resultBlake := blake.Sum(nil) keccak := sha3.NewKeccak256() if _, err := keccak.Write(resultBlake); err != nil { return nil, err } resultkeccak := keccak.Sum(nil) resultcube := cubehash256(resultkeccak) lyra2result := make([]byte, 32) lyra2(lyra2result, resultcube, resultcube, 1, 4, 4) var skeinresult [32]byte skein.Sum256(&skeinresult, lyra2result, nil) resultcube2 := cubehash256(skeinresult[:]) resultbmw := bmw256(resultcube2) return resultbmw, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L622-L625
func (c *Client) ListRepoHooks(org, repo string) ([]Hook, error) { c.log("ListRepoHooks", org, repo) return c.listHooks(org, &repo) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/manifest.go#L285-L299
func (mf *manifestFile) rewrite() error { // In Windows the files should be closed before doing a Rename. if err := mf.fp.Close(); err != nil { return err } fp, netCreations, err := helpRewrite(mf.directory, &mf.manifest) if err != nil { return err } mf.fp = fp mf.manifest.Creations = netCreations mf.manifest.Deletions = 0 return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L524-L535
func (c *Cluster) ImageAssociateNode(project, fingerprint string) error { imageID, _, err := c.ImageGet(project, fingerprint, false, true) if err != nil { return err } err = c.Transaction(func(tx *ClusterTx) error { _, err := tx.tx.Exec("INSERT INTO images_nodes(image_id, node_id) VALUES(?, ?)", imageID, c.nodeID) return err }) return err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L228-L231
func (p DispatchMouseEventParams) WithDeltaX(deltaX float64) *DispatchMouseEventParams { p.DeltaX = deltaX return &p }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/provision.go#L637-L647
func Registry() ([]Provisioner, error) { registry := make([]Provisioner, 0, len(provisioners)) for _, pFunc := range provisioners { p, err := pFunc() if err != nil { return nil, err } registry = append(registry, p) } return registry, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/db/storage.go#L167-L171
func (s *LogStorage) CreateAppLogCollection(appName string) (*storage.Collection, error) { c := s.AppLogCollection(appName) err := c.Create(&logCappedInfo) return c, err }
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/conn.go#L35-L58
func DialTo(addr string) (*Conn, error) { const network = "tcp" if "" == addr { addr = "127.0.0.1:telnet" } conn, err := net.Dial(network, addr) if nil != err { return nil, err } dataReader := newDataReader(conn) dataWriter := newDataWriter(conn) clientConn := Conn{ conn:conn, dataReader:dataReader, dataWriter:dataWriter, } return &clientConn, nil }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L2698-L2707
func (o *MapInt8Option) Set(value string) error { parts := stringMapRegex.Split(value, 2) if len(parts) != 2 { return fmt.Errorf("expected KEY=VALUE got '%s'", value) } val := Int8Option{} val.Set(parts[1]) (*o)[parts[0]] = val return nil }
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L191-L244
func (l *Logger) OutputJson(callDepth int, level Level, body interface{}) { if l.level > level { return } buf := l.bufs.Get().([]byte) buf = buf[0:0] defer l.bufs.Put(buf) type JsonLog struct { Time string `json:"log_time"` Level string `json:"log_level"` File string `json:"log_file"` Line string `json:"log_line"` Body interface{} `json:"log_body"` } var jsonlog JsonLog if l.flag&Ltime > 0 { now := time.Now().Format(timeFormat) jsonlog.Time = now } if l.flag&Llevel > 0 { jsonlog.Level = level.String() } if l.flag&Lfile > 0 { _, file, line, ok := runtime.Caller(callDepth) if !ok { file = "???" line = 0 } else { for i := len(file) - 1; i > 0; i-- { if file[i] == '/' { file = file[i+1:] break } } } jsonlog.File = file jsonlog.Line = string(strconv.AppendInt(buf, int64(line), 10)) } jsonlog.Body = body msg, _ := json.Marshal(jsonlog) msg = append(msg, '\n') l.hLock.Lock() l.handler.Write(msg) l.hLock.Unlock() }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/deploymentmanifest.go#L197-L201
func (s *DeploymentManifest) RemoveTag(key string) { if s.Tags != nil { delete(s.Tags, key) } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/gopath.go#L31-L39
func ResolveWithGoPath(filename string) (string, error) { for _, file := range goPathCandidates(filename) { if _, err := os.Stat(file); !os.IsNotExist(err) { return file, nil } } return "", fmt.Errorf("file not found on GOPATH: %q", filename) }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/tracer.go#L260-L262
func (t StartTime) Apply(o *StartSpanOptions) { o.StartTime = time.Time(t) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L785-L789
func (v SetLifecycleEventsEnabledParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage8(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L1213-L1217
func (v EventAnimationStarted) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoAnimation13(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/main.go#L810-L883
func handleArtifactView(o options, sg *spyglass.Spyglass, cfg config.Getter) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { setHeadersNoCaching(w) pathSegments := strings.Split(r.URL.Path, "/") if len(pathSegments) != 2 { http.NotFound(w, r) return } lensName := pathSegments[0] resource := pathSegments[1] lens, err := lenses.GetLens(lensName) if err != nil { http.Error(w, fmt.Sprintf("No such template: %s (%v)", lensName, err), http.StatusNotFound) return } lensConfig := lens.Config() lensResourcesDir := lenses.ResourceDirForLens(o.spyglassFilesLocation, lensConfig.Name) reqString := r.URL.Query().Get("req") var request spyglass.LensRequest err = json.Unmarshal([]byte(reqString), &request) if err != nil { http.Error(w, fmt.Sprintf("Failed to parse request: %v", err), http.StatusBadRequest) return } artifacts, err := sg.FetchArtifacts(request.Source, "", cfg().Deck.Spyglass.SizeLimit, request.Artifacts) if err != nil { http.Error(w, fmt.Sprintf("Failed to retrieve expected artifacts: %v", err), http.StatusInternalServerError) return } switch resource { case "iframe": t, err := template.ParseFiles(path.Join(o.templateFilesLocation, "spyglass-lens.html")) if err != nil { http.Error(w, fmt.Sprintf("Failed to load template: %v", err), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; encoding=utf-8") t.Execute(w, struct { Title string BaseURL string Head template.HTML Body template.HTML }{ lensConfig.Title, "/spyglass/static/" + lensName + "/", template.HTML(lens.Header(artifacts, lensResourcesDir)), template.HTML(lens.Body(artifacts, lensResourcesDir, "")), }) case "rerender": data, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, fmt.Sprintf("Failed to read body: %v", err), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; encoding=utf-8") w.Write([]byte(lens.Body(artifacts, lensResourcesDir, string(data)))) case "callback": data, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, fmt.Sprintf("Failed to read body: %v", err), http.StatusInternalServerError) return } w.Write([]byte(lens.Callback(artifacts, lensResourcesDir, string(data)))) default: http.NotFound(w, r) } } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2409-L2413
func (v *PushNodeByPathToFrontendParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom26(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L557-L561
func (v *ResolveAnimationParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoAnimation5(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/log.go#L62-L66
func Crit(msg string, ctx ...interface{}) { if Log != nil { Log.Crit(msg, ctx...) } }