_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/render.go#L17-L52
func New(opts Options) *Engine { if opts.Helpers == nil { opts.Helpers = map[string]interface{}{} } if opts.TemplateEngines == nil { opts.TemplateEngines = map[string]TemplateEngine{} } if _, ok := opts.TemplateEngines["html"]; !ok { opts.TemplateEngines["html"] = plush.BuffaloRenderer } if _, ok := opts.TemplateEngines["text"]; !ok { opts.TemplateEngines["text"] = plush.BuffaloRenderer } if _, ok := opts.TemplateEngines["txt"]; !ok { opts.TemplateEngines["txt"] = plush.BuffaloRenderer } if _, ok := opts.TemplateEngines["js"]; !ok { opts.TemplateEngines["js"] = plush.BuffaloRenderer } if _, ok := opts.TemplateEngines["md"]; !ok { opts.TemplateEngines["md"] = MDTemplateEngine } if _, ok := opts.TemplateEngines["tmpl"]; !ok { opts.TemplateEngines["tmpl"] = GoTemplateEngine } if opts.DefaultContentType == "" { opts.DefaultContentType = "text/html; charset=utf-8" } e := &Engine{ Options: opts, } return e }
https://github.com/codemodus/kace/blob/e3ecf78ee2a5e58652cb2be34d3159ad9c89acf8/kace.go#L110-L112
func (k *Kace) Kebab(s string) string { return delimitedCase(s, kebabDelim, false) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L183-L192
func (p *GetBrowserCommandLineParams) Do(ctx context.Context) (arguments []string, err error) { // execute var res GetBrowserCommandLineReturns err = cdp.Execute(ctx, CommandGetBrowserCommandLine, nil, &res) if err != nil { return nil, err } return res.Arguments, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L135-L137
func (p *DispatchKeyEventParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandDispatchKeyEvent, p, nil) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/cluster_util.go#L63-L131
func getClusterFromRemotePeers(lg *zap.Logger, urls []string, timeout time.Duration, logerr bool, rt http.RoundTripper) (*membership.RaftCluster, error) { cc := &http.Client{ Transport: rt, Timeout: timeout, } for _, u := range urls { addr := u + "/members" resp, err := cc.Get(addr) if err != nil { if logerr { if lg != nil { lg.Warn("failed to get cluster response", zap.String("address", addr), zap.Error(err)) } else { plog.Warningf("could not get cluster response from %s: %v", u, err) } } continue } b, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { if logerr { if lg != nil { lg.Warn("failed to read body of cluster response", zap.String("address", addr), zap.Error(err)) } else { plog.Warningf("could not read the body of cluster response: %v", err) } } continue } var membs []*membership.Member if err = json.Unmarshal(b, &membs); err != nil { if logerr { if lg != nil { lg.Warn("failed to unmarshal cluster response", zap.String("address", addr), zap.Error(err)) } else { plog.Warningf("could not unmarshal cluster response: %v", err) } } continue } id, err := types.IDFromString(resp.Header.Get("X-Etcd-Cluster-ID")) if err != nil { if logerr { if lg != nil { lg.Warn( "failed to parse cluster ID", zap.String("address", addr), zap.String("header", resp.Header.Get("X-Etcd-Cluster-ID")), zap.Error(err), ) } else { plog.Warningf("could not parse the cluster ID from cluster res: %v", err) } } continue } // check the length of membership members // if the membership members are present then prepare and return raft cluster // if membership members are not present then the raft cluster formed will be // an invalid empty cluster hence return failed to get raft cluster member(s) from the given urls error if len(membs) > 0 { return membership.NewClusterFromMembers(lg, "", id, membs), nil } return nil, fmt.Errorf("failed to get raft cluster member(s) from the given URLs") } return nil, fmt.Errorf("could not retrieve cluster information from the given URLs") }
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/ed25519.go#L117-L125
func UnmarshalEd25519PublicKey(data []byte) (PubKey, error) { if len(data) != 32 { return nil, errors.New("expect ed25519 public key data size to be 32") } return &Ed25519PublicKey{ k: ed25519.PublicKey(data), }, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1919-L1923
func (v AddInspectedHeapObjectParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeapprofiler23(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/retry.go#L159-L165
func (rs *RequestState) HasRetries(err error) bool { if rs == nil { return false } rOpts := rs.retryOpts return rs.Attempt < rOpts.MaxAttempts && rOpts.RetryOn.CanRetry(err) }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L587-L600
func NewVideoWriter(filename string, fourcc int, fps float32, frame_width, frame_height, is_color int) *VideoWriter { size := C.cvSize(C.int(frame_width), C.int(frame_height)) filename_c := C.CString(filename) defer C.free(unsafe.Pointer(filename_c)) rv := C.cvCreateVideoWriter(filename_c, C.int(fourcc), C.double(fps), size, C.int(is_color), ) return (*VideoWriter)(rv) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L407-L411
func (v *SeekAnimationsParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoAnimation3(&r, v) return r.Error() }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L2978-L2980
func (api *API) ScenarioLocator(href string) *ScenarioLocator { return &ScenarioLocator{Href(href), api} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L1267-L1271
func (v *GetAllTimeSamplingProfileReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoMemory14(&r, v) return r.Error() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pubsub/subscriber/server.go#L199-L242
func (s *PullServer) Run(ctx context.Context) error { configEvent := make(chan config.Delta, 2) s.Subscriber.ConfigAgent.Subscribe(configEvent) var err error defer func() { if err != nil { logrus.WithError(ctx.Err()).Error("Pull server shutting down") } logrus.Warn("Pull server shutting down") }() currentConfig := s.Subscriber.ConfigAgent.Config().PubSubSubscriptions errGroup, derivedCtx, err := s.handlePulls(ctx, currentConfig) if err != nil { return err } for { select { // Parent context. Shutdown case <-ctx.Done(): return ctx.Err() // Current thread context, it may be failing already case <-derivedCtx.Done(): err = errGroup.Wait() return err // Checking for update config case event := <-configEvent: newConfig := event.After.PubSubSubscriptions logrus.Info("Received new config") if !reflect.DeepEqual(currentConfig, newConfig) { logrus.Warn("New config found, reloading pull Server") // Making sure the current thread finishes before starting a new one. errGroup.Wait() // Starting a new thread with new config errGroup, derivedCtx, err = s.handlePulls(ctx, newConfig) if err != nil { return err } currentConfig = newConfig } } } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L314-L358
func (a *ssAuthenticator) Sign(r *http.Request) error { if time.Now().After(a.refreshAt) { u := buildURL(a.host, "api/catalog/new_session") u += "?account_id=" + strconv.Itoa(a.accountID) authReq, err := http.NewRequest("GET", u, nil) if err != nil { return err } if err := a.auther.Sign(authReq); err != nil { return err } // A bit tricky: if the auther is the cookie signer it could have updated the // host after being redirected. if ca, ok := a.auther.(*cookieSigner); ok { a.SetHost(ca.host) authReq.Host = a.host authReq.URL.Host = a.host } authReq.Header.Set("Content-Type", "application/json") resp, err := a.client.DoHidden(authReq) if err != nil { return fmt.Errorf("Authentication failed: %s", err) } if resp.StatusCode != 303 { body, err := ioutil.ReadAll(resp.Body) var msg string if err != nil { msg = " - <failed to read body>" } if len(body) > 0 { msg = " - " + string(body) } return fmt.Errorf("Authentication failed: %s%s", resp.Status, msg) } a.refreshAt = time.Now().Add(2 * time.Hour) } a.auther.Sign(r) r.Header.Set("X-Api-Version", "1.0") r.Host = a.host r.URL.Host = a.host return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L4693-L4697
func (v *GetCookiesParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork35(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L230-L248
func (r *ProtocolLXD) MigrateStoragePoolVolume(pool string, volume api.StorageVolumePost) (Operation, error) { if !r.HasExtension("storage_api_remote_volume_handling") { return nil, fmt.Errorf("The server is missing the required \"storage_api_remote_volume_handling\" API extension") } // Sanity check if !volume.Migration { return nil, fmt.Errorf("Can't ask for a rename through MigrateStoragePoolVolume") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/custom/%s", url.QueryEscape(pool), volume.Name) op, _, err := r.queryOperation("POST", path, volume, "") if err != nil { return nil, err } return op, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/config.go#L552-L569
func warnDeprecated(last *time.Time, freq time.Duration, msg string) { // have we warned within the last freq? warnLock.RLock() fresh := time.Now().Sub(*last) <= freq warnLock.RUnlock() if fresh { // we've warned recently return } // Warning is stale, will we win the race to warn? warnLock.Lock() defer warnLock.Unlock() now := time.Now() // Recalculate now, we might wait awhile for the lock if now.Sub(*last) <= freq { // Nope, we lost return } *last = now logrus.Warn(msg) }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/util.go#L22-L30
func ColumnName(d Dialect, tname, cname string) string { if cname != "*" { cname = d.Quote(cname) } if tname == "" { return cname } return fmt.Sprintf("%s.%s", d.Quote(tname), cname) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/abort.go#L54-L102
func TerminateOlderPresubmitJobs(pjc prowClient, log *logrus.Entry, pjs []prowapi.ProwJob, cleanup ProwJobResourcesCleanup) error { dupes := map[jobIndentifier]int{} for i, pj := range pjs { if pj.Complete() || pj.Spec.Type != prowapi.PresubmitJob { continue } ji := jobIndentifier{ job: pj.Spec.Job, organization: pj.Spec.Refs.Org, repository: pj.Spec.Refs.Repo, pullRequest: pj.Spec.Refs.Pulls[0].Number, } prev, ok := dupes[ji] if !ok { dupes[ji] = i continue } cancelIndex := i if (&pjs[prev].Status.StartTime).Before(&pj.Status.StartTime) { cancelIndex = prev dupes[ji] = i } toCancel := pjs[cancelIndex] // TODO cancel the prow job before cleaning up its resources and make this system // independent. // See this discussion for more details: https://github.com/kubernetes/test-infra/pull/11451#discussion_r263523932 if err := cleanup(toCancel); err != nil { log.WithError(err).WithFields(ProwJobFields(&toCancel)).Warn("Cannot clean up job resources") } toCancel.SetComplete() prevState := toCancel.Status.State toCancel.Status.State = prowapi.AbortedState log.WithFields(ProwJobFields(&toCancel)). WithField("from", prevState). WithField("to", toCancel.Status.State).Info("Transitioning states") npj, err := pjc.ReplaceProwJob(toCancel.ObjectMeta.Name, toCancel) if err != nil { return err } pjs[cancelIndex] = npj } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L330-L333
func (p EvaluateParams) WithIncludeCommandLineAPI(includeCommandLineAPI bool) *EvaluateParams { p.IncludeCommandLineAPI = includeCommandLineAPI return &p }
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/log.go#L115-L117
func Errorf(format string, args ...interface{}) { logger.Output(2, LevelError, fmt.Sprintf(format, args...)) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/genfiles/genfiles.go#L71-L104
func NewGroup(gc ghFileClient, owner, repo, sha string) (*Group, error) { g := &Group{ Paths: make(map[string]bool), FileNames: make(map[string]bool), PathPrefixes: make(map[string]bool), FilePrefixes: make(map[string]bool), } bs, err := gc.GetFile(owner, repo, genConfigFile, sha) if err != nil { switch err.(type) { case *github.FileNotFound: return g, nil default: return nil, fmt.Errorf("could not get .generated_files: %v", err) } } repoFiles, err := g.load(bytes.NewBuffer(bs)) if err != nil { return nil, err } for _, f := range repoFiles { bs, err = gc.GetFile(owner, repo, f, sha) if err != nil { return nil, err } if err = g.loadPaths(bytes.NewBuffer(bs)); err != nil { return nil, err } } return g, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/selective_string.go#L108-L114
func NewSelectiveStringsValue(valids ...string) *SelectiveStringsValue { vm := make(map[string]struct{}) for _, v := range valids { vm[v] = struct{}{} } return &SelectiveStringsValue{valids: vm, vs: []string{}} }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L228-L235
func FieldParams(fields []*Field) string { args := make([]string, len(fields)) for i, field := range fields { args[i] = lex.Minuscule(field.Name) } return strings.Join(args, ", ") }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L557-L560
func (p GetNodeForLocationParams) WithIncludeUserAgentShadowDOM(includeUserAgentShadowDOM bool) *GetNodeForLocationParams { p.IncludeUserAgentShadowDOM = includeUserAgentShadowDOM return &p }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/docker_schema1.go#L138-L151
func (m *Schema1) UpdateLayerInfos(layerInfos []types.BlobInfo) error { // Our LayerInfos includes empty layers (where m.ExtractedV1Compatibility[].ThrowAway), so expect them to be included here as well. if len(m.FSLayers) != len(layerInfos) { return errors.Errorf("Error preparing updated manifest: layer count changed from %d to %d", len(m.FSLayers), len(layerInfos)) } m.FSLayers = make([]Schema1FSLayers, len(layerInfos)) for i, info := range layerInfos { // (docker push) sets up m.ExtractedV1Compatibility[].{Id,Parent} based on values of info.Digest, // but (docker pull) ignores them in favor of computing DiffIDs from uncompressed data, except verifying the child->parent links and uniqueness. // So, we don't bother recomputing the IDs in m.History.V1Compatibility. m.FSLayers[(len(layerInfos)-1)-i].BlobSum = info.Digest } return nil }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/type.go#L45-L47
func (rat Rat) Value() (driver.Value, error) { return rat.FloatString(decimalScale), nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L312-L323
func declImports(gen *ast.GenDecl, path string) bool { if gen.Tok != token.IMPORT { return false } for _, spec := range gen.Specs { impspec := spec.(*ast.ImportSpec) if importPath(impspec) == path { return true } } return false }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2313-L2317
func (v Scope) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger23(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L14303-L14305
func (api *API) VolumeLocator(href string) *VolumeLocator { return &VolumeLocator{Href(href), api} }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/ignore.go#L25-L28
func IgnoreFields(typ interface{}, names ...string) cmp.Option { sf := newStructFilter(typ, names...) return cmp.FilterPath(sf.filter, cmp.Ignore()) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L1985-L1989
func (v SetMediaTextParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss18(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/txn_command.go#L34-L42
func NewTxnCommand() *cobra.Command { cmd := &cobra.Command{ Use: "txn [options]", Short: "Txn processes all the requests in one transaction", Run: txnCommandFunc, } cmd.Flags().BoolVarP(&txnInteractive, "interactive", "i", false, "Input transaction in interactive mode") return cmd }
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/tls.go#L37-L40
func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error { server := &Server{Addr: addr, Handler: handler} return server.ListenAndServeTLS(certFile, keyFile) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L449-L453
func (v SetCustomObjectFormatterEnabledParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime4(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/walk/walk.go#L216-L218
func shouldUpdate(rel string, mode Mode, updateParent bool, updateRels map[string]bool) bool { return mode == VisitAllUpdateSubdirsMode && updateParent || updateRels[rel] }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L352-L355
func (p SetPausedInDebuggerMessageParams) WithMessage(message string) *SetPausedInDebuggerMessageParams { p.Message = message return &p }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L514-L522
func (ap Approvers) ListApprovals() []Approval { approvals := []Approval{} for _, approver := range ap.GetCurrentApproversSet().List() { approvals = append(approvals, ap.approvers[approver]) } return approvals }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2438-L2442
func (v *NavigateToHistoryEntryParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage25(&r, v) return r.Error() }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/binding/binding.go#L78-L91
func Exec(req *http.Request, value interface{}) error { if ba, ok := value.(Bindable); ok { return ba.Bind(req) } ct := httpx.ContentType(req) if ct == "" { return errors.New("blank content type") } if b, ok := binders[ct]; ok { return b(req, value) } return fmt.Errorf("could not find a binder for %s", ct) }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L466-L473
func (l *InclusiveRanges) Contains(value int) bool { for _, b := range l.blocks { if b.Contains(value) { return true } } return false }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/watcher_hub.go#L59-L116
func (wh *watcherHub) watch(key string, recursive, stream bool, index, storeIndex uint64) (Watcher, *v2error.Error) { reportWatchRequest() event, err := wh.EventHistory.scan(key, recursive, index) if err != nil { err.Index = storeIndex return nil, err } w := &watcher{ eventChan: make(chan *Event, 100), // use a buffered channel recursive: recursive, stream: stream, sinceIndex: index, startIndex: storeIndex, hub: wh, } wh.mutex.Lock() defer wh.mutex.Unlock() // If the event exists in the known history, append the EtcdIndex and return immediately if event != nil { ne := event.Clone() ne.EtcdIndex = storeIndex w.eventChan <- ne return w, nil } l, ok := wh.watchers[key] var elem *list.Element if ok { // add the new watcher to the back of the list elem = l.PushBack(w) } else { // create a new list and add the new watcher l = list.New() elem = l.PushBack(w) wh.watchers[key] = l } w.remove = func() { if w.removed { // avoid removing it twice return } w.removed = true l.Remove(elem) atomic.AddInt64(&wh.count, -1) reportWatcherRemoved() if l.Len() == 0 { delete(wh.watchers, key) } } atomic.AddInt64(&wh.count, 1) reportWatcherAdded() return w, nil }
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/page.go#L136-L171
func (f Font) Encoder() TextEncoding { enc := f.V.Key("Encoding") switch enc.Kind() { case Name: switch enc.Name() { case "WinAnsiEncoding": return &byteEncoder{&winAnsiEncoding} case "MacRomanEncoding": return &byteEncoder{&macRomanEncoding} case "Identity-H": // TODO: Should be big-endian UCS-2 decoder return &nopEncoder{} default: println("unknown encoding", enc.Name()) return &nopEncoder{} } case Dict: return &dictEncoder{enc.Key("Differences")} case Null: // ok, try ToUnicode default: println("unexpected encoding", enc.String()) return &nopEncoder{} } toUnicode := f.V.Key("ToUnicode") if toUnicode.Kind() == Dict { m := readCmap(toUnicode) if m == nil { return &nopEncoder{} } return m } return &byteEncoder{&pdfDocEncoding} }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L312-L421
func createApp(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { var ia inputApp err = ParseInput(r, &ia) if err != nil { return err } a := app.App{ TeamOwner: ia.TeamOwner, Platform: ia.Platform, Plan: appTypes.Plan{Name: ia.Plan}, Name: ia.Name, Description: ia.Description, Pool: ia.Pool, RouterOpts: ia.RouterOpts, Router: ia.Router, Tags: ia.Tags, Quota: quota.UnlimitedQuota, } tags, _ := InputValues(r, "tag") a.Tags = append(a.Tags, tags...) // for compatibility if a.TeamOwner == "" { a.TeamOwner, err = autoTeamOwner(t, permission.PermAppCreate) if err != nil { return err } } canCreate := permission.Check(t, permission.PermAppCreate, permission.Context(permTypes.CtxTeam, a.TeamOwner), ) if !canCreate { return permission.ErrUnauthorized } u, err := auth.ConvertNewUser(t.User()) if err != nil { return err } if a.Platform != "" { repo, _ := image.SplitImageName(a.Platform) platform, errPlat := servicemanager.Platform.FindByName(repo) if errPlat != nil { return errPlat } if platform.Disabled { canUsePlat := permission.Check(t, permission.PermPlatformUpdate) || permission.Check(t, permission.PermPlatformCreate) if !canUsePlat { return &errors.HTTP{Code: http.StatusBadRequest, Message: appTypes.ErrInvalidPlatform.Error()} } } } evt, err := event.New(&event.Opts{ Target: appTarget(a.Name), Kind: permission.PermAppCreate, 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 = app.CreateApp(&a, u) if err != nil { log.Errorf("Got error while creating app: %s", err) if _, ok := err.(appTypes.NoTeamsError); ok { return &errors.HTTP{ Code: http.StatusBadRequest, Message: "In order to create an app, you should be member of at least one team", } } if e, ok := err.(*appTypes.AppCreationError); ok { if e.Err == app.ErrAppAlreadyExists { return &errors.HTTP{Code: http.StatusConflict, Message: e.Error()} } if _, ok := e.Err.(*quota.QuotaExceededError); ok { return &errors.HTTP{ Code: http.StatusForbidden, Message: "Quota exceeded", } } } if err == appTypes.ErrInvalidPlatform { return &errors.HTTP{Code: http.StatusBadRequest, Message: err.Error()} } return err } repo, err := repository.Manager().GetRepository(a.Name) if err != nil { return err } msg := map[string]interface{}{ "status": "success", "repository_url": repo.ReadWriteURL, } addrs, err := a.GetAddresses() if err != nil { return err } if len(addrs) > 0 { msg["ip"] = addrs[0] } jsonMsg, err := json.Marshal(msg) if err != nil { return err } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) w.Write(jsonMsg) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L982-L986
func (v *SetAttributeValueParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom9(&r, v) return r.Error() }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/log_adapter.go#L182-L184
func (la *LogAdapter) Warning(msg string) error { return la.Log(LevelWarning, nil, msg) }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/delay/delay.go#L120-L152
func fileKey(file string) (string, error) { if !internal.IsSecondGen() || internal.MainPath == "" { return file, nil } // If the caller is in the same Dir as mainPath, then strip everything but the file name. if filepath.Dir(file) == internal.MainPath { return filepath.Base(file), nil } // If the path contains "_gopath/src/", which is what the builder uses for // apps which don't use go modules, strip everything up to and including src. // Or, if the path starts with /tmp/staging, then we're importing a package // from the app's module (and we must be using go modules), and we have a // path like /tmp/staging1234/srv/... so strip everything up to and // including the first /srv/. // And be sure to look at the GOPATH, for local development. s := string(filepath.Separator) for _, s := range []string{filepath.Join("_gopath", "src") + s, s + "srv" + s, filepath.Join(build.Default.GOPATH, "src") + s} { if idx := strings.Index(file, s); idx > 0 { return file[idx+len(s):], nil } } // Finally, if that all fails then we must be using go modules, and the file is a module, // so the path looks like /go/pkg/mod/github.com/foo/bar@v0.0.0-20181026220418-f595d03440dc/baz.go // So... remove everything up to and including mod, plus the @.... version string. m := "/mod/" if idx := strings.Index(file, m); idx > 0 { file = file[idx+len(m):] } else { return file, fmt.Errorf("fileKey: unknown file path format for %q", file) } return modVersionPat.ReplaceAllString(file, ""), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L1142-L1146
func (v *GetCurrentTimeParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoAnimation12(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L2064-L2068
func (v SetKeyframeKeyReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss19(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/omniscale/go-mapnik/blob/710dfcc5e486e5760d0a5c46be909d91968e1ffb/mapnik.go#L354-L372
func (m *Map) RenderToFile(opts RenderOpts, path string) error { scaleFactor := opts.ScaleFactor if scaleFactor == 0.0 { scaleFactor = 1.0 } cs := C.CString(path) defer C.free(unsafe.Pointer(cs)) var format *C.char if opts.Format != "" { format = C.CString(opts.Format) } else { format = C.CString("png256") } defer C.free(unsafe.Pointer(format)) if C.mapnik_map_render_to_file(m.m, cs, C.double(opts.Scale), C.double(scaleFactor), format) != 0 { return m.lastError() } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1049-L1053
func (v ResolveNodeReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom10(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/label_sync/main.go#L553-L633
func (ru RepoUpdates) DoUpdates(org string, gc client) error { var numUpdates int for _, updates := range ru { numUpdates += len(updates) } updateChan := make(chan repoUpdate, numUpdates) for repo, updates := range ru { logrus.WithField("org", org).WithField("repo", repo).Infof("Applying %d changes", len(updates)) for _, item := range updates { updateChan <- repoUpdate{repo: repo, update: item} } } close(updateChan) wg := sync.WaitGroup{} wg.Add(maxConcurrentWorkers) errChan := make(chan error, numUpdates) for i := 0; i < maxConcurrentWorkers; i++ { go func(updates <-chan repoUpdate) { defer wg.Done() for item := range updates { repo := item.repo update := item.update logrus.WithField("org", org).WithField("repo", repo).WithField("why", update.Why).Debug("running update") switch update.Why { case "missing": err := gc.AddRepoLabel(org, repo, update.Wanted.Name, update.Wanted.Description, update.Wanted.Color) if err != nil { errChan <- err } case "change", "rename": err := gc.UpdateRepoLabel(org, repo, update.Current.Name, update.Wanted.Name, update.Wanted.Description, update.Wanted.Color) if err != nil { errChan <- err } case "dead": err := gc.DeleteRepoLabel(org, repo, update.Current.Name) if err != nil { errChan <- err } case "migrate": issues, err := gc.FindIssues(fmt.Sprintf("is:open repo:%s/%s label:\"%s\" -label:\"%s\"", org, repo, update.Current.Name, update.Wanted.Name), "", false) if err != nil { errChan <- err } if len(issues) == 0 { if err = gc.DeleteRepoLabel(org, repo, update.Current.Name); err != nil { errChan <- err } } for _, i := range issues { if err = gc.AddLabel(org, repo, i.Number, update.Wanted.Name); err != nil { errChan <- err continue } if err = gc.RemoveLabel(org, repo, i.Number, update.Current.Name); err != nil { errChan <- err } } default: errChan <- errors.New("unknown label operation: " + update.Why) } } }(updateChan) } wg.Wait() close(errChan) var overallErr error if len(errChan) > 0 { var updateErrs []error for updateErr := range errChan { updateErrs = append(updateErrs, updateErr) } overallErr = fmt.Errorf("failed to list labels: %v", updateErrs) } return overallErr }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/kubernetes_cluster_clients.go#L133-L143
func (o *ExperimentalKubernetesOptions) ProwJobClient(namespace string, dryRun bool) (prowJobClient prowv1.ProwJobInterface, err error) { if err := o.resolve(dryRun); err != nil { return nil, err } if o.dryRun { return kube.NewDryRunProwJobClient(o.DeckURI), nil } return o.prowJobClientset.ProwV1().ProwJobs(namespace), nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/admission/admission.go#L97-L118
func writeResponse(ar admissionapi.AdmissionRequest, w io.Writer, decide decider) error { response, err := decide(ar) if err != nil { logrus.WithError(err).Error("failed decision") response = &admissionapi.AdmissionResponse{ Result: &meta.Status{ Message: err.Error(), }, } } var result admissionapi.AdmissionReview result.Response = response result.Response.UID = ar.UID out, err := json.Marshal(result) if err != nil { return fmt.Errorf("encode response: %v", err) } if _, err := w.Write(out); err != nil { return fmt.Errorf("write response: %v", err) } return nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/pool/pool.go#L102-L140
func (p *Pool) Do(ctx context.Context, f func(cc *grpc.ClientConn) error) error { var conn *connCount if err := func() error { p.connsLock.Lock() defer p.connsLock.Unlock() for { for addr, mapConn := range p.conns { if mapConn.cc == nil { cc, err := grpc.DialContext(ctx, addr, p.opts...) if err != nil { return fmt.Errorf("failed to connect to %s: %+v", addr, err) } mapConn.cc = cc conn = mapConn // We break because this conn has a count of 0 which we know // we're not beating break } else { mapConnCount := atomic.LoadInt64(&mapConn.count) if mapConnCount < p.queueSize && (conn == nil || mapConnCount < atomic.LoadInt64(&conn.count)) { conn = mapConn } } } if conn == nil { p.connsCond.Wait() } else { atomic.AddInt64(&conn.count, 1) break } } return nil }(); err != nil { return err } defer p.connsCond.Broadcast() defer atomic.AddInt64(&conn.count, -1) return f(conn.cc) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/cachestorage.go#L168-L171
func (p RequestEntriesParams) WithPathFilter(pathFilter string) *RequestEntriesParams { p.PathFilter = pathFilter return &p }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/validate.go#L30-L37
func Validate(svc *parser.Service) error { for _, m := range svc.Methods { if err := validateMethod(svc, m); err != nil { return err } } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2480-L2484
func (v PerformSearchReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom27(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L300-L305
func (p *Page) ConfirmPopup() error { if err := p.session.AcceptAlert(); err != nil { return fmt.Errorf("failed to confirm popup: %s", err) } return nil }
https://github.com/Unknwon/goconfig/blob/3dba17dd7b9ec8509b3621a73a30a4b333eb28da/read.go#L271-L277
func (c *ConfigFile) AppendFiles(files ...string) error { if len(c.fileNames) == 1 && c.fileNames[0] == "" { return fmt.Errorf("Cannot append file data to in-memory data") } c.fileNames = append(c.fileNames, files...) return c.Reload() }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/state/git/impl.go#L122-L150
func (git *JSONGitStore) Commit(c *cluster.Cluster) error { if c == nil { return fmt.Errorf("Nil cluster spec") } bytes, err := json.Marshal(c) if err != nil { return err } //writes latest changes to git repo. git.Write(state.ClusterJSONFile, bytes) //commits the changes r, err := g.NewFilesystemRepository(state.ClusterJSONFile) if err != nil { return err } // Add a new remote, with the default fetch refspec _, err = r.CreateRemote(&config.RemoteConfig{ Name: git.ClusterName, URL: git.options.CommitConfig.Remote, }) _, err = r.Commits() if err != nil { return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L4554-L4558
func (v *FrameResource) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage47(&r, v) return r.Error() }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/auth/auth.go#L47-L64
func (c *TokenCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { md := ttnctx.MetadataFromOutgoingContext(ctx) token, _ := ttnctx.TokenFromMetadata(md) if token != "" { return map[string]string{tokenKey: token}, nil } if c.tokenFunc != nil { var k string if v, ok := md[c.tokenFuncKey]; ok && len(v) > 0 { k = v[0] } return map[string]string{tokenKey: c.tokenFunc(k)}, nil } if c.token != "" { return map[string]string{tokenKey: c.token}, nil } return map[string]string{tokenKey: ""}, nil }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L73-L75
func (gc *GraphicContext) FillString(text string) (cursor float64) { return gc.FillStringAt(text, 0, 0) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_transport.go#L70-L73
func ParseReference(reference string) (types.ImageReference, error) { dir, image := internal.SplitPathAndImage(reference) return NewReference(dir, image) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/etcd_config.go#L67-L107
func (e *Etcd) Flags() (fs []string) { tp := reflect.TypeOf(*e) vo := reflect.ValueOf(*e) for _, name := range etcdFields { field, ok := tp.FieldByName(name) if !ok { panic(fmt.Errorf("field %q not found", name)) } fv := reflect.Indirect(vo).FieldByName(name) var sv string switch fv.Type().Kind() { case reflect.String: sv = fv.String() case reflect.Slice: n := fv.Len() sl := make([]string, n) for i := 0; i < n; i++ { sl[i] = fv.Index(i).String() } sv = strings.Join(sl, ",") case reflect.Int64: sv = fmt.Sprintf("%d", fv.Int()) case reflect.Bool: sv = fmt.Sprintf("%v", fv.Bool()) default: panic(fmt.Errorf("field %q (%v) cannot be parsed", name, fv.Type().Kind())) } fname := field.Tag.Get("yaml") // TODO: remove this if fname == "initial-corrupt-check" { fname = "experimental-" + fname } if sv != "" { fs = append(fs, fmt.Sprintf("--%s=%s", fname, sv)) } } return fs }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L644-L648
func (v *RequestCacheNamesParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCachestorage5(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L498-L502
func (v *GetApplicationCacheForFrameReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoApplicationcache5(&r, v) return r.Error() }
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/cors/cors.go#L140-L163
func Allow(opts *Options) http.HandlerFunc { return func(res http.ResponseWriter, req *http.Request) { var ( origin = req.Header.Get(headerOrigin) requestedMethod = req.Header.Get(headerRequestMethod) requestedHeaders = req.Header.Get(headerRequestHeaders) // additional headers to be added // to the response. headers map[string]string ) if req.Method == "OPTIONS" && (requestedMethod != "" || requestedHeaders != "") { // TODO: if preflight, respond with exact headers if allowed headers = opts.PreflightHeader(origin, requestedMethod, requestedHeaders) } else { headers = opts.Header(origin) } for key, value := range headers { res.Header().Set(key, value) } } }
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/cubehash.go#L337-L359
func cubehash256(data []byte) []byte { c := NewCubeHash() buf := make([]byte, 32) buf[0] = 0x80 c.inputBlock(data) c.sixteenRounds() c.inputBlock(buf) c.sixteenRounds() c.xv ^= 1 for j := 0; j < 10; j++ { c.sixteenRounds() } out := make([]byte, 32) binary.LittleEndian.PutUint32(out[0:], c.x0) binary.LittleEndian.PutUint32(out[4:], c.x1) binary.LittleEndian.PutUint32(out[8:], c.x2) binary.LittleEndian.PutUint32(out[12:], c.x3) binary.LittleEndian.PutUint32(out[16:], c.x4) binary.LittleEndian.PutUint32(out[20:], c.x5) binary.LittleEndian.PutUint32(out[24:], c.x6) binary.LittleEndian.PutUint32(out[28:], c.x7) return out }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L6824-L6828
func (v CollectClassNamesFromSubtreeParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom77(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/route_wrapper.go#L39-L56
func (m *RouteWrapper) Validate(formats strfmt.Registry) error { var res []error if err := m.validateError(formats); err != nil { // prop res = append(res, err) } if err := m.validateRoute(formats); err != nil { // prop res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L2158-L2162
func (v SetCacheDisabledParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork16(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L550-L554
func (b *Base) Diem(exitCode int, m *Attrs, msg string, a ...interface{}) { b.Log(LevelFatal, m, msg, a...) b.ShutdownLoggers() curExiter.Exit(exitCode) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2960-L2964
func (v ExecutionContextDescription) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime27(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/asset.go#L148-L154
func (a Asset) MustExtract(typ interface{}, code interface{}, issuer interface{}) { err := a.Extract(typ, code, issuer) if err != nil { panic(err) } }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/post_apps_app_routes_responses.go#L25-L59
func (o *PostAppsAppRoutesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewPostAppsAppRoutesOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 400: result := NewPostAppsAppRoutesBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 409: result := NewPostAppsAppRoutesConflict() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: result := NewPostAppsAppRoutesDefault(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/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L6025-L6029
func (v EventMediaQueryResultChanged) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss54(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service_broker.go#L24-L39
func serviceBrokerList(w http.ResponseWriter, r *http.Request, t auth.Token) error { if !permission.Check(t, permission.PermServiceBrokerRead) { return permission.ErrUnauthorized } brokers, err := servicemanager.ServiceBroker.List() if err != nil { return err } if len(brokers) == 0 { w.WriteHeader(http.StatusNoContent) return nil } return json.NewEncoder(w).Encode(map[string]interface{}{ "brokers": brokers, }) }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L239-L247
func (ctx *Context) DeleteSession() error { sid := ctx.Data["Sid"].(string) ctx.Data["session"] = nil provider.Destroy(sid) cookie := httpCookie cookie.MaxAge = -1 http.SetCookie(ctx.ResponseWriter, &cookie) return nil }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/coding/idheader.go#L10-L21
func FromIDHeader(v string) string { if v == "" { return v } v = strings.TrimLeft(v, "<") v = strings.TrimRight(v, ">") r, err := url.QueryUnescape(v) if err != nil { return v } return r }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/index.go#L20-L36
func index(w http.ResponseWriter, r *http.Request) error { host, _ := config.GetString("host") userCreate, _ := config.GetBool("auth:user-registration") scheme, _ := config.GetString("auth:scheme") repoManager, _ := config.GetString("repo-manager") data := map[string]interface{}{ "tsuruTarget": host, "userCreate": userCreate, "nativeLogin": scheme == "" || scheme == "native", "keysEnabled": repoManager == "" || repoManager == "gandalf", } template, err := getTemplate() if err != nil { return err } return template.Execute(w, data) }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/snapshot.go#L59-L64
func (c *Client) GetSnapshot(snapshotID string) (*Snapshot, error) { url := snapshotColPath() + slash(snapshotID) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &Snapshot{} err := c.client.Get(url, ret, http.StatusOK) return ret, err }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L258-L265
func (s *FileSequence) PaddingStyle() PadStyle { for style, mapper := range padders { if mapper == s.padMapper { return style } } return PadStyleDefault }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/sync/sync.go#L357-L395
func Push(client *pachclient.APIClient, root string, commit *pfs.Commit, overwrite bool) error { var g errgroup.Group if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { g.Go(func() (retErr error) { if path == root || info.IsDir() { return nil } f, err := os.Open(path) if err != nil { return err } defer func() { if err := f.Close(); err != nil && retErr == nil { retErr = err } }() relPath, err := filepath.Rel(root, path) if err != nil { return err } if overwrite { if err := client.DeleteFile(commit.Repo.Name, commit.ID, relPath); err != nil { return err } } _, err = client.PutFile(commit.Repo.Name, commit.ID, relPath, f) return err }) return nil }); err != nil { return err } return g.Wait() }
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/notifiee.go#L52-L56
func (nb *NotifyBundle) OpenedStream(n Network, s Stream) { if nb.OpenedStreamF != nil { nb.OpenedStreamF(n, s) } }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/quic/quic.go#L67-L69
func (s *Server) Shutdown(_ context.Context) (err error) { return s.Server.Close() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2735-L2739
func (v LayoutViewport) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage28(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L540-L561
func (p *Peer) BeginCall(ctx context.Context, serviceName, methodName string, callOptions *CallOptions) (*OutboundCall, error) { if callOptions == nil { callOptions = defaultCallOptions } callOptions.RequestState.AddSelectedPeer(p.HostPort()) if err := validateCall(ctx, serviceName, methodName, callOptions); err != nil { return nil, err } conn, err := p.GetConnection(ctx) if err != nil { return nil, err } call, err := conn.beginCall(ctx, serviceName, methodName, callOptions) if err != nil { return nil, err } return call, err }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/ppsutil/util.go#L192-L205
func FailPipeline(ctx context.Context, etcdClient *etcd.Client, pipelinesCollection col.Collection, pipelineName string, reason string) error { _, err := col.NewSTM(ctx, etcdClient, func(stm col.STM) error { pipelines := pipelinesCollection.ReadWrite(stm) pipelinePtr := new(pps.EtcdPipelineInfo) if err := pipelines.Get(pipelineName, pipelinePtr); err != nil { return err } pipelinePtr.State = pps.PipelineState_PIPELINE_FAILURE pipelinePtr.Reason = reason pipelines.Put(pipelineName, pipelinePtr) return nil }) return err }
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/outgoing.go#L710-L722
func NewInlineQueryResultVideo(id, videoURL, thumbURL, title, text string, mimeType MIMEType) *InlineQueryResultVideo { return &InlineQueryResultVideo{ InlineQueryResultBase: InlineQueryResultBase{ Type: PhotoResult, ID: id, }, VideoURL: videoURL, MIMEType: mimeType, ThumbURL: thumbURL, Title: title, Text: text, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L613-L616
func (p GetOuterHTMLParams) WithObjectID(objectID runtime.RemoteObjectID) *GetOuterHTMLParams { p.ObjectID = objectID return &p }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/logexporter/cmd/main.go#L119-L131
func createFullSystemdLogfile(outputDir string) error { cmd := exec.Command("journalctl", "--output=short-precise", "-D", *journalPath) // Run the command and record the output to a file. output, err := cmd.Output() if err != nil { return fmt.Errorf("Journalctl command failed: %v", err) } logfile := filepath.Join(outputDir, "systemd.log") if err := ioutil.WriteFile(logfile, output, 0444); err != nil { return fmt.Errorf("Writing full journalctl logs to file failed: %v", err) } return nil }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/detect.go#L9-L19
func detectMultipartMessage(root *Part) bool { // Parse top-level multipart ctype := root.Header.Get(hnContentType) mediatype, _, _, err := parseMediaType(ctype) if err != nil { return false } // According to rfc2046#section-5.1.7 all other multipart should // be treated as multipart/mixed return strings.HasPrefix(mediatype, ctMultipartPrefix) }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L57-L87
func (p *Part) AddChild(child *Part) { if p == child { // Prevent paradox. return } if p != nil { if p.FirstChild == nil { // Make it the first child. p.FirstChild = child } else { // Append to sibling chain. current := p.FirstChild for current.NextSibling != nil { current = current.NextSibling } if current == child { // Prevent infinite loop. return } current.NextSibling = child } } // Update all new first-level children Parent pointers. for c := child; c != nil; c = c.NextSibling { if c == c.NextSibling { // Prevent infinite loop. return } c.Parent = p } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssm/codegen_client.go#L829-L831
func (r *Notification) Locator(api *API) *NotificationLocator { return api.NotificationLocator(r.Href) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/phaino/local.go#L120-L159
func findRepo(wd, path string) (string, error) { opwd, err := realPath(wd) if err != nil { return "", fmt.Errorf("wd not found: %v", err) } if strings.HasPrefix(path, "github.com/kubernetes/") { path = strings.Replace(path, "github.com/kubernetes/", "k8s.io/", 1) } var old string pwd := opwd for old != pwd { old = pwd if strings.HasSuffix(pwd, "/"+path) { return pwd, nil } pwd = filepath.Dir(pwd) } pwd = opwd for old != pwd { old = pwd check := filepath.Join(pwd, path) if info, err := os.Stat(check); err == nil && info.IsDir() { return check, nil } pwd = filepath.Dir(pwd) } base := filepath.Base(path) pwd = opwd for old != pwd { old = pwd check := filepath.Join(pwd, base) if info, err := os.Stat(check); err == nil && info.IsDir() { return check, nil } pwd = filepath.Dir(pwd) } return "", errors.New("cannot find repo") }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L252-L259
func HighlightRect(x int64, y int64, width int64, height int64) *HighlightRectParams { return &HighlightRectParams{ X: x, Y: y, Width: width, Height: height, } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/connection.go#L471-L514
func (c *Connection) SendSystemError(id uint32, span Span, err error) error { frame := c.opts.FramePool.Get() if err := frame.write(&errorMessage{ id: id, errCode: GetSystemErrorCode(err), tracing: span, message: GetSystemErrorMessage(err), }); err != nil { // This shouldn't happen - it means writing the errorMessage is broken. c.log.WithFields( LogField{"remotePeer", c.remotePeerInfo}, LogField{"id", id}, ErrField(err), ).Warn("Couldn't create outbound frame.") return fmt.Errorf("failed to create outbound error frame: %v", err) } // When sending errors, we hold the state rlock to ensure that sendCh is not closed // as we are sending the frame. return c.withStateRLock(func() error { // Errors cannot be sent if the connection has been closed. if c.state == connectionClosed { c.log.WithFields( LogField{"remotePeer", c.remotePeerInfo}, LogField{"id", id}, ).Info("Could not send error frame on closed connection.") return fmt.Errorf("failed to send error frame, connection state %v", c.state) } select { case c.sendCh <- frame: // Good to go return nil default: // If the send buffer is full, log and return an error. } c.log.WithFields( LogField{"remotePeer", c.remotePeerInfo}, LogField{"id", id}, ErrField(err), ).Warn("Couldn't send outbound frame.") return fmt.Errorf("failed to send error frame, buffer full") }) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L581-L584
func (p SetUserAgentOverrideParams) WithAcceptLanguage(acceptLanguage string) *SetUserAgentOverrideParams { p.AcceptLanguage = acceptLanguage return &p }