_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/clonerefs/parse.go#L41-L91
|
func ParseRefs(value string) (*prowapi.Refs, error) {
gitRef := &prowapi.Refs{}
values := strings.SplitN(value, "=", 2)
if len(values) != 2 {
return gitRef, fmt.Errorf("refspec %s invalid: does not contain '='", value)
}
info := values[0]
allRefs := values[1]
infoValues := strings.SplitN(info, ",", 2)
if len(infoValues) != 2 {
return gitRef, fmt.Errorf("refspec %s invalid: does not contain 'org,repo' as prefix", value)
}
gitRef.Org = infoValues[0]
gitRef.Repo = infoValues[1]
refValues := strings.Split(allRefs, ",")
if len(refValues) == 1 && refValues[0] == "" {
return gitRef, fmt.Errorf("refspec %s invalid: does not contain any refs", value)
}
baseRefParts := strings.Split(refValues[0], ":")
if len(baseRefParts) != 1 && len(baseRefParts) != 2 {
return gitRef, fmt.Errorf("refspec %s invalid: malformed base ref", refValues[0])
}
gitRef.BaseRef = baseRefParts[0]
if len(baseRefParts) == 2 {
gitRef.BaseSHA = baseRefParts[1]
}
for _, refValue := range refValues[1:] {
refParts := strings.Split(refValue, ":")
if len(refParts) == 0 || len(refParts) > 3 {
return gitRef, fmt.Errorf("refspec %s invalid: malformed pull ref", refValue)
}
pullNumber, err := strconv.Atoi(refParts[0])
if err != nil {
return gitRef, fmt.Errorf("refspec %s invalid: pull request identifier not a number: %v", refValue, err)
}
pullRef := prowapi.Pull{
Number: pullNumber,
}
if len(refParts) > 1 {
pullRef.SHA = refParts[1]
}
if len(refParts) > 2 {
pullRef.Ref = refParts[2]
}
gitRef.Pulls = append(gitRef.Pulls, pullRef)
}
return gitRef, nil
}
|
https://github.com/ianschenck/envflag/blob/9111d830d133f952887a936367fb0211c3134f0d/envflag.go#L116-L118
|
func Uint64(name string, value uint64, usage string) *uint64 {
return EnvironmentFlags.Uint64(name, value, usage)
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/proto/generate.go#L98-L141
|
func buildPackages(pc *ProtoConfig, dir, rel string, protoFiles, genFiles []string) []*Package {
packageMap := make(map[string]*Package)
for _, name := range protoFiles {
info := protoFileInfo(dir, name)
key := info.PackageName
if pc.groupOption != "" {
for _, opt := range info.Options {
if opt.Key == pc.groupOption {
key = opt.Value
break
}
}
}
if packageMap[key] == nil {
packageMap[key] = newPackage(info.PackageName)
}
packageMap[key].addFile(info)
}
switch pc.Mode {
case DefaultMode:
pkg, err := selectPackage(dir, rel, packageMap)
if err != nil {
log.Print(err)
}
if pkg == nil {
return nil // empty rule created in generateEmpty
}
for _, name := range genFiles {
pkg.addGenFile(dir, name)
}
return []*Package{pkg}
case PackageMode:
pkgs := make([]*Package, 0, len(packageMap))
for _, pkg := range packageMap {
pkgs = append(pkgs, pkg)
}
return pkgs
default:
return nil
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/replication.go#L531-L544
|
func (r *Raft) setNewLogs(req *AppendEntriesRequest, nextIndex, lastIndex uint64) error {
// Append up to MaxAppendEntries or up to the lastIndex
req.Entries = make([]*Log, 0, r.conf.MaxAppendEntries)
maxIndex := min(nextIndex+uint64(r.conf.MaxAppendEntries)-1, lastIndex)
for i := nextIndex; i <= maxIndex; i++ {
oldLog := new(Log)
if err := r.logs.GetLog(i, oldLog); err != nil {
r.logger.Error(fmt.Sprintf("Failed to get log at index %d: %v", i, err))
return err
}
req.Entries = append(req.Entries, oldLog)
}
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/docker_schema1.go#L214-L231
|
func (m *Schema1) Inspect(_ func(types.BlobInfo) ([]byte, error)) (*types.ImageInspectInfo, error) {
s1 := &Schema2V1Image{}
if err := json.Unmarshal([]byte(m.History[0].V1Compatibility), s1); err != nil {
return nil, err
}
i := &types.ImageInspectInfo{
Tag: m.Tag,
Created: &s1.Created,
DockerVersion: s1.DockerVersion,
Architecture: s1.Architecture,
Os: s1.OS,
Layers: layerInfosToStrings(m.LayerInfos()),
}
if s1.Config != nil {
i.Labels = s1.Config.Labels
}
return i, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/config.go#L414-L435
|
func Load(prowConfig, jobConfig string) (c *Config, err error) {
// we never want config loading to take down the prow components
defer func() {
if r := recover(); r != nil {
c, err = nil, fmt.Errorf("panic loading config: %v", r)
}
}()
c, err = loadConfig(prowConfig, jobConfig)
if err != nil {
return nil, err
}
if err := c.finalizeJobConfig(); err != nil {
return nil, err
}
if err := c.validateComponentConfig(); err != nil {
return nil, err
}
if err := c.validateJobConfig(); err != nil {
return nil, err
}
return c, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L273-L286
|
func (f *FakeClient) GetIssueLabels(owner, repo string, number int) ([]github.Label, error) {
re := regexp.MustCompile(fmt.Sprintf(`^%s/%s#%d:(.*)$`, owner, repo, number))
la := []github.Label{}
allLabels := sets.NewString(f.IssueLabelsExisting...)
allLabels.Insert(f.IssueLabelsAdded...)
allLabels.Delete(f.IssueLabelsRemoved...)
for _, l := range allLabels.List() {
groups := re.FindStringSubmatch(l)
if groups != nil {
la = append(la, github.Label{Name: groups[1]})
}
}
return la, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L820-L859
|
func runCommand(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
msg := "You must provide the command to run"
command := InputValue(r, "command")
if len(command) < 1 {
return &errors.HTTP{Code: http.StatusBadRequest, Message: msg}
}
appName := r.URL.Query().Get(":app")
once := InputValue(r, "once")
isolated := InputValue(r, "isolated")
a, err := getAppFromContext(appName, r)
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermAppRun,
contextsForApp(&a)...,
)
if !allowed {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: appTarget(appName),
Kind: permission.PermAppRun,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(&a)...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
w.Header().Set("Content-Type", "application/x-json-stream")
keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "")
defer keepAliveWriter.Stop()
writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
evt.SetLogWriter(writer)
onceBool, _ := strconv.ParseBool(once)
isolatedBool, _ := strconv.ParseBool(isolated)
args := provision.RunArgs{Once: onceBool, Isolated: isolatedBool}
return a.Run(command, evt, args)
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/geometry/geometry.go#L20-L26
|
func Main(gc draw2d.GraphicContext, ext string) (string, error) {
// Draw the droid
Draw(gc, 297, 210)
// Return the output filename
return samples.Output("geometry", ext), nil
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/volume.go#L110-L117
|
func (c *Client) RestoreSnapshot(dcid string, volid string, snapshotID string) (*http.Header, error) {
path := volumePath(dcid, volid) + "/restore-snapshot"
data := url.Values{}
data.Set("snapshotId", snapshotID)
ret := &http.Header{}
err := c.client.Post(path, data, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2608-L2612
|
func (v *RestartFrameParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger26(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rbac/server.go#L190-L208
|
func (r *Server) DeleteProject(id int64) error {
// Update RBAC
err := r.postResources(nil, []string{strconv.FormatInt(id, 10)}, false)
if err != nil {
return err
}
// Update project map
r.resourcesLock.Lock()
for k, v := range r.resources {
if v == strconv.FormatInt(id, 10) {
delete(r.resources, k)
break
}
}
r.resourcesLock.Unlock()
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L483-L562
|
func (r *ProtocolLXD) tryCopyImage(req api.ImagesPost, urls []string) (RemoteOperation, error) {
if len(urls) == 0 {
return nil, fmt.Errorf("The source server isn't listening on the network")
}
rop := remoteOperation{
chDone: make(chan bool),
}
// For older servers, apply the aliases after copy
if !r.HasExtension("image_create_aliases") && req.Aliases != nil {
rop.chPost = make(chan bool)
go func() {
defer close(rop.chPost)
// Wait for the main operation to finish
<-rop.chDone
if rop.err != nil {
return
}
// Get the operation data
op, err := rop.GetTarget()
if err != nil {
return
}
// Extract the fingerprint
fingerprint := op.Metadata["fingerprint"].(string)
// Add the aliases
for _, entry := range req.Aliases {
alias := api.ImageAliasesPost{}
alias.Name = entry.Name
alias.Target = fingerprint
r.CreateImageAlias(alias)
}
}()
}
// Forward targetOp to remote op
go func() {
success := false
errors := map[string]error{}
for _, serverURL := range urls {
req.Source.Server = serverURL
op, err := r.CreateImage(req, nil)
if err != nil {
errors[serverURL] = err
continue
}
rop.targetOp = op
for _, handler := range rop.handlers {
rop.targetOp.AddHandler(handler)
}
err = rop.targetOp.Wait()
if err != nil {
errors[serverURL] = err
continue
}
success = true
break
}
if !success {
rop.err = remoteOperationError("Failed remote image download", errors)
}
close(rop.chDone)
}()
return &rop, nil
}
|
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/encodable.go#L38-L52
|
func (iv InsertValues) EncodeSQL(buf *bytes.Buffer) {
for i, rows := range iv {
if i != 0 {
buf.WriteString(", ")
}
buf.WriteByte('(')
for j, bv := range rows {
if j != 0 {
buf.WriteString(", ")
}
bv.EncodeSQL(buf)
}
buf.WriteByte(')')
}
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/sendable.go#L145-L154
|
func (ub *OutgoingUnbanChatMember) Send() error {
resp := &baseResponse{}
_, err := ub.api.c.postJSON(unbanChatMember, resp, ub)
if err != nil {
return err
}
return check(resp)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L260-L264
|
func (v *ResetPermissionsParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser2(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/net.go#L73-L84
|
func CanonicalNetworkAddress(address string) string {
_, _, err := net.SplitHostPort(address)
if err != nil {
ip := net.ParseIP(address)
if ip != nil && ip.To4() == nil {
address = fmt.Sprintf("[%s]:%s", address, shared.DefaultPort)
} else {
address = fmt.Sprintf("%s:%s", address, shared.DefaultPort)
}
}
return address
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L254-L261
|
func (in *ProwJobStatus) DeepCopy() *ProwJobStatus {
if in == nil {
return nil
}
out := new(ProwJobStatus)
in.DeepCopyInto(out)
return out
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/storage/storagemock/instrumented_storage.go#L137-L157
|
func (_m *InstrumentedStorage) SetValue(_a0 context.Context, _a1 string, _a2 string, _a3 string) (map[string]string, error) {
ret := _m.Called(_a0, _a1, _a2, _a3)
var r0 map[string]string
if rf, ok := ret.Get(0).(func(context.Context, string, string, string) map[string]string); ok {
r0 = rf(_a0, _a1, _a2, _a3)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(map[string]string)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(context.Context, string, string, string) error); ok {
r1 = rf(_a0, _a1, _a2, _a3)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/datasource/mongo/mongo.go#L34-L75
|
func NewMongo(filename string, environment string) (*Mongo, error) {
ctx := context.Background()
cnf, err := GetMongo(filename, environment)
if err != nil {
return nil, err
}
var uri string
if len(cnf.Username) > 0 && len(cnf.Password) > 0 {
uri = fmt.Sprintf(`mongodb://%s:%s@%s:%d/%s`,
cnf.Username,
cnf.Password,
cnf.Host,
cnf.Port,
cnf.Database,
)
} else {
uri = fmt.Sprintf(`mongodb://%s:%d/%s`,
cnf.Host,
cnf.Port,
cnf.Database,
)
}
client, err := mongo.NewClient(uri)
if err != nil {
log.Printf("L'URI du serveur MongoDB est incorrect: %s", uri)
return nil, err
}
err = client.Connect(ctx)
if err != nil {
log.Print("Impossible d'utiliser ce context")
return nil, err
}
db := client.Database(cnf.Database)
err = client.Ping(ctx, nil)
if err != nil {
log.Printf("Impossible de contacter %v sur le port %d", cnf.Host, cnf.Port)
return nil, err
}
return &Mongo{Client: client, Database: db, context: ctx}, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L130-L132
|
func (f *FakeClient) ListReviews(owner, repo string, number int) ([]github.Review, error) {
return append([]github.Review{}, f.Reviews[number]...), nil
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cv.go#L46-L51
|
func Smooth(src, dst *IplImage, smoothtype,
param1, param2 int, param3, param4 float64) {
C.cvSmooth(unsafe.Pointer(src), unsafe.Pointer(dst), C.int(smoothtype),
C.int(param1), C.int(param2), C.double(param3), C.double(param4),
)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L3558-L3562
|
func (v EventExceptionThrown) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime33(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/matcher.go#L100-L105
|
func EachLike(content interface{}, minRequired int) Matcher {
return eachLike{
Contents: content,
Min: minRequired,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/heapprofiler.go#L267-L276
|
func (p *StopSamplingParams) Do(ctx context.Context) (profile *SamplingHeapProfile, err error) {
// execute
var res StopSamplingReturns
err = cdp.Execute(ctx, CommandStopSampling, nil, &res)
if err != nil {
return nil, err
}
return res.Profile, nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_transport.go#L42-L44
|
func (t ociTransport) ParseReference(reference string) (types.ImageReference, error) {
return ParseReference(reference)
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L269-L281
|
func (w *Writer) GetNode(bs []byte) *skiplist.Node {
iter := w.store.NewIterator(w.iterCmp, w.buf)
defer iter.Close()
x := w.newItem(bs, false)
x.bornSn = w.getCurrSn()
if found := iter.SeekWithCmp(unsafe.Pointer(x), w.insCmp, w.existCmp); found {
return iter.GetNode()
}
return nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4077-L4085
|
func (u OperationResultTr) MustCreatePassiveOfferResult() ManageOfferResult {
val, ok := u.GetCreatePassiveOfferResult()
if !ok {
panic("arm CreatePassiveOfferResult is not set")
}
return val
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L749-L754
|
func (g *Glg) InfoFunc(f func() string) error {
if g.isModeEnable(INFO) {
return g.out(INFO, "%s", f())
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L2087-L2091
|
func (v SetCookieParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork15(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L260-L267
|
func (w *WriteBuffer) WriteLen8String(s string) {
if int(byte(len(s))) != len(s) {
w.setErr(errStringTooLong)
}
w.WriteSingleByte(byte(len(s)))
w.WriteString(s)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/sys.go#L18-L40
|
func GetArchitectures() ([]int, error) {
architectures := []int{}
architectureName, err := osarch.ArchitectureGetLocal()
if err != nil {
return nil, err
}
architecture, err := osarch.ArchitectureId(architectureName)
if err != nil {
return nil, err
}
architectures = append(architectures, architecture)
personalities, err := osarch.ArchitecturePersonalities(architecture)
if err != nil {
return nil, err
}
for _, personality := range personalities {
architectures = append(architectures, personality)
}
return architectures, nil
}
|
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/context.go#L32-L35
|
func (ctx *Context) Redirect(code int, url string) {
ctx.Response.Status = code
ctx.Response.Data = url
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L364-L369
|
func (p *Page) SwitchToWindow(name string) error {
if err := p.session.SetWindowByName(name); err != nil {
return fmt.Errorf("failed to switch to named window: %s", err)
}
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L978-L980
|
func (api *API) TSSControlLocator(href string) *TSSControlLocator {
return &TSSControlLocator{Href(href), api}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L483-L491
|
func (c *Client) JobParameterized(jobInfo *JobInfo) bool {
for _, prop := range jobInfo.Property {
if prop.ParameterDefinitions != nil && len(prop.ParameterDefinitions) > 0 {
return true
}
}
return false
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/plan.go#L70-L88
|
func (s *planService) ensureDefault() error {
plans, err := s.storage.FindAll()
if err != nil {
return err
}
if len(plans) > 0 {
return nil
}
configMemory, _ := config.GetInt("docker:memory")
configSwap, _ := config.GetInt("docker:swap")
dp := appTypes.Plan{
Name: "autogenerated",
Memory: int64(configMemory) * 1024 * 1024,
Swap: int64(configSwap-configMemory) * 1024 * 1024,
CpuShare: 100,
Default: true,
}
return s.storage.Insert(dp)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L78-L86
|
func (c APIClient) CreateRepo(repoName string) error {
_, err := c.PfsAPIClient.CreateRepo(
c.Ctx(),
&pfs.CreateRepoRequest{
Repo: NewRepo(repoName),
},
)
return grpcutil.ScrubGRPC(err)
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/replication.go#L113-L117
|
func (s *followerReplication) setLastContact() {
s.lastContactLock.Lock()
s.lastContact = time.Now()
s.lastContactLock.Unlock()
}
|
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/log/access.go#L29-L33
|
func Logger(l handler.Logger) Option {
return Option{func(o *options) {
o.logger = l
}}
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/address.go#L29-L34
|
func (a Address) Min(b Address) Address {
if a < b {
return a
}
return b
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1008-L1012
|
func NewWriter(w io.Writer) *Writer {
return &Writer{
pbw: pbutil.NewWriter(w),
}
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/delete_apps_app_routes_route_parameters.go#L93-L96
|
func (o *DeleteAppsAppRoutesRouteParams) WithContext(ctx context.Context) *DeleteAppsAppRoutesRouteParams {
o.SetContext(ctx)
return o
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps/util.go#L50-L62
|
func SortInput(input *Input) {
VisitInput(input, func(input *Input) {
SortInputs := func(inputs []*Input) {
sort.SliceStable(inputs, func(i, j int) bool { return InputName(inputs[i]) < InputName(inputs[j]) })
}
switch {
case input.Cross != nil:
SortInputs(input.Cross)
case input.Union != nil:
SortInputs(input.Union)
}
})
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/rpc.pb.go#L1544-L1550
|
func (*WatchRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _WatchRequest_OneofMarshaler, _WatchRequest_OneofUnmarshaler, _WatchRequest_OneofSizer, []interface{}{
(*WatchRequest_CreateRequest)(nil),
(*WatchRequest_CancelRequest)(nil),
(*WatchRequest_ProgressRequest)(nil),
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logging/log.go#L98-L105
|
func WaitRecord(ch chan *log.Record, timeout time.Duration) *log.Record {
select {
case record := <-ch:
return record
case <-time.After(timeout):
return nil
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3595-L3598
|
func (e InflationResultCode) String() string {
name, _ := inflationResultCodeMap[int32(e)]
return name
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/iterator.go#L395-L425
|
func (txn *Txn) NewIterator(opt IteratorOptions) *Iterator {
if txn.discarded {
panic("Transaction has already been discarded")
}
// Do not change the order of the next if. We must track the number of running iterators.
if atomic.AddInt32(&txn.numIterators, 1) > 1 && txn.update {
atomic.AddInt32(&txn.numIterators, -1)
panic("Only one iterator can be active at one time, for a RW txn.")
}
// TODO: If Prefix is set, only pick those memtables which have keys with
// the prefix.
tables, decr := txn.db.getMemTables()
defer decr()
txn.db.vlog.incrIteratorCount()
var iters []y.Iterator
if itr := txn.newPendingWritesIterator(opt.Reverse); itr != nil {
iters = append(iters, itr)
}
for i := 0; i < len(tables); i++ {
iters = append(iters, tables[i].NewUniIterator(opt.Reverse))
}
iters = txn.db.lc.appendIterators(iters, &opt) // This will increment references.
res := &Iterator{
txn: txn,
iitr: y.NewMergeIterator(iters, opt.Reverse),
opt: opt,
readTs: txn.readTs,
}
return res
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L132-L139
|
func (in *ProwJob) DeepCopy() *ProwJob {
if in == nil {
return nil
}
out := new(ProwJob)
in.DeepCopyInto(out)
return out
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/type.go#L115-L217
|
func (p *Process) runtimeType2Type(a core.Address) *Type {
if t := p.runtimeMap[a]; t != nil {
return t
}
// Read runtime._type.size
r := region{p: p, a: a, typ: p.findType("runtime._type")}
size := int64(r.Field("size").Uintptr())
// Find module this type is in.
var m *module
for _, x := range p.modules {
if x.types <= a && a < x.etypes {
m = x
break
}
}
// Read information out of the runtime._type.
var name string
if m != nil {
x := m.types.Add(int64(r.Field("str").Int32()))
n := uint16(p.proc.ReadUint8(x.Add(1)))<<8 + uint16(p.proc.ReadUint8(x.Add(2)))
b := make([]byte, n)
p.proc.ReadAt(b, x.Add(3))
name = string(b)
if r.Field("tflag").Uint8()&uint8(p.rtConstants["tflagExtraStar"]) != 0 {
name = name[1:]
}
} else {
// A reflect-generated type.
// TODO: The actual name is in the runtime.reflectOffs map.
// Too hard to look things up in maps here, just allocate a placeholder for now.
name = fmt.Sprintf("reflect.generatedType%x", a)
}
// Read ptr/nonptr bits
ptrSize := p.proc.PtrSize()
nptrs := int64(r.Field("ptrdata").Uintptr()) / ptrSize
var ptrs []int64
if r.Field("kind").Uint8()&uint8(p.rtConstants["kindGCProg"]) == 0 {
gcdata := r.Field("gcdata").Address()
for i := int64(0); i < nptrs; i++ {
if p.proc.ReadUint8(gcdata.Add(i/8))>>uint(i%8)&1 != 0 {
ptrs = append(ptrs, i*ptrSize)
}
}
} else {
// TODO: run GC program to get ptr indexes
}
// Find a Type that matches this type.
// (The matched type will be one constructed from DWARF info.)
// It must match name, size, and pointer bits.
var candidates []*Type
for _, t := range p.runtimeNameMap[name] {
if size == t.Size && equal(ptrs, t.ptrs()) {
candidates = append(candidates, t)
}
}
var t *Type
if len(candidates) > 0 {
// If a runtime type matches more than one DWARF type,
// pick one arbitrarily.
// This looks mostly harmless. DWARF has some redundant entries.
// For example, [32]uint8 appears twice.
// TODO: investigate the reason for this duplication.
t = candidates[0]
} else {
// There's no corresponding DWARF type. Make our own.
t = &Type{Name: name, Size: size, Kind: KindStruct}
n := t.Size / ptrSize
// Types to use for ptr/nonptr fields of runtime types which
// have no corresponding DWARF type.
ptr := p.findType("unsafe.Pointer")
nonptr := p.findType("uintptr")
if ptr == nil || nonptr == nil {
panic("ptr / nonptr standins missing")
}
for i := int64(0); i < n; i++ {
typ := nonptr
if len(ptrs) > 0 && ptrs[0] == i*ptrSize {
typ = ptr
ptrs = ptrs[1:]
}
t.Fields = append(t.Fields, Field{
Name: fmt.Sprintf("f%d", i),
Off: i * ptrSize,
Type: typ,
})
}
if t.Size%ptrSize != 0 {
// TODO: tail of <ptrSize data.
}
}
// Memoize.
p.runtimeMap[a] = t
return t
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/rmdir_command.go#L38-L54
|
func rmdirCommandFunc(c *cli.Context, ki client.KeysAPI) {
if len(c.Args()) == 0 {
handleError(c, ExitBadArgs, errors.New("key required"))
}
key := c.Args()[0]
ctx, cancel := contextWithTotalTimeout(c)
resp, err := ki.Delete(ctx, key, &client.DeleteOptions{Dir: true})
cancel()
if err != nil {
handleError(c, ExitServerError, err)
}
if !resp.Node.Dir || c.GlobalString("output") != "simple" {
printResponseKey(resp, c.GlobalString("output"))
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/dco/dco.go#L145-L161
|
func checkExistingLabels(gc gitHubClient, l *logrus.Entry, org, repo string, number int) (hasYesLabel, hasNoLabel bool, err error) {
labels, err := gc.GetIssueLabels(org, repo, number)
if err != nil {
return false, false, fmt.Errorf("error getting pull request labels: %v", err)
}
for _, l := range labels {
if l.Name == dcoYesLabel {
hasYesLabel = true
}
if l.Name == dcoNoLabel {
hasNoLabel = true
}
}
return hasYesLabel, hasNoLabel, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/ca.go#L22-L30
|
func FromCommandLine(cmdLine *cmd.CommandLine) (*API, error) {
api, err := rsapi.FromCommandLine(cmdLine)
if err != nil {
return nil, err
}
api.Host = apiHostFromLogin(cmdLine.Host)
api.Metadata = GenMetadata
return &API{api}, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gopherage/pkg/cov/diff.go#L27-L53
|
func DiffProfiles(before []*cover.Profile, after []*cover.Profile) ([]*cover.Profile, error) {
var diff []*cover.Profile
if len(before) != len(after) {
return nil, fmt.Errorf("before and after have different numbers of profiles (%d vs. %d)", len(before), len(after))
}
for i, beforeProfile := range before {
afterProfile := after[i]
if err := ensureProfilesMatch(beforeProfile, afterProfile); err != nil {
return nil, fmt.Errorf("error on profile #%d: %v", i, err)
}
diffProfile := cover.Profile{FileName: beforeProfile.FileName, Mode: beforeProfile.Mode}
for j, beforeBlock := range beforeProfile.Blocks {
afterBlock := afterProfile.Blocks[j]
diffBlock := cover.ProfileBlock{
StartLine: beforeBlock.StartLine,
StartCol: beforeBlock.StartCol,
EndLine: beforeBlock.EndLine,
EndCol: beforeBlock.EndCol,
NumStmt: beforeBlock.NumStmt,
Count: afterBlock.Count - beforeBlock.Count,
}
diffProfile.Blocks = append(diffProfile.Blocks, diffBlock)
}
diff = append(diff, &diffProfile)
}
return diff, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/security/easyjson.go#L215-L219
|
func (v *StateExplanation) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoSecurity(&r, v)
return r.Error()
}
|
https://github.com/codemodus/kace/blob/e3ecf78ee2a5e58652cb2be34d3159ad9c89acf8/ktrie/ktrie.go#L21-L38
|
func (n *KNode) Add(rs []rune) {
cur := n
for k, v := range rs {
link := cur.linkByVal(v)
if link == nil {
link = NewKNode(v)
cur.links = append(cur.links, link)
}
if k == len(rs)-1 {
link.end = true
}
cur = link
}
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/apis/cluster/cluster.go#L76-L85
|
func (c *Cluster) ProviderConfig() *ControlPlaneProviderConfig {
//providerConfig providerConfig
raw := c.ClusterAPI.Spec.ProviderConfig
providerConfig := &ControlPlaneProviderConfig{}
err := json.Unmarshal([]byte(raw), providerConfig)
if err != nil {
logger.Critical("Unable to unmarshal provider config: %v", err)
}
return providerConfig
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/objutil/int.go#L13-L69
|
func ParseInt(b []byte) (int64, error) {
var val int64
if len(b) == 0 {
return 0, errorInvalidUint64(b)
}
if b[0] == '-' {
const max = Int64Min
const lim = max / 10
if b = b[1:]; len(b) == 0 {
return 0, errorInvalidUint64(b)
}
for _, d := range b {
if !(d >= '0' && d <= '9') {
return 0, errorInvalidInt64(b)
}
if val < lim {
return 0, errorOverflowInt64(b)
}
val *= 10
x := int64(d - '0')
if val < (max + x) {
return 0, errorOverflowInt64(b)
}
val -= x
}
} else {
const max = Int64Max
const lim = max / 10
for _, d := range b {
if !(d >= '0' && d <= '9') {
return 0, errorInvalidInt64(b)
}
x := int64(d - '0')
if val > lim {
return 0, errorOverflowInt64(b)
}
if val *= 10; val > (max - x) {
return 0, errorOverflowInt64(b)
}
val += x
}
}
return val, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L520-L523
|
func (p SetVirtualTimePolicyParams) WithMaxVirtualTimeTaskStarvationCount(maxVirtualTimeTaskStarvationCount int64) *SetVirtualTimePolicyParams {
p.MaxVirtualTimeTaskStarvationCount = maxVirtualTimeTaskStarvationCount
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1900-L1904
|
func (v *DetachFromTargetParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget21(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L273-L277
|
func (v *TakeCoverageDeltaParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss2(&r, v)
return r.Error()
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L703-L705
|
func (g *Glg) Log(val ...interface{}) error {
return g.out(LOG, blankFormat(len(val)), val...)
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L142-L144
|
func (db *DB) OrderBy(table interface{}, column interface{}, order ...interface{}) *Condition {
return newCondition(db).OrderBy(table, column, order...)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L182-L184
|
func (p *DeleteCookiesParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandDeleteCookies, p, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L1538-L1542
|
func (v *SetRequestInterceptionParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork10(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L43-L46
|
func (p AwaitPromiseParams) WithReturnByValue(returnByValue bool) *AwaitPromiseParams {
p.ReturnByValue = returnByValue
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1867-L1871
|
func (v QuerySelectorParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom20(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/saml.go#L340-L377
|
func (a *apiServer) updateConfig(config *auth.AuthConfig) error {
if config == nil {
config = &auth.AuthConfig{}
}
newConfig, err := validateConfig(config, internal)
if err != nil {
return err
}
// It's possible that 'config' is non-nil, but empty (this is the case when
// users clear the config from the command line). Therefore, check
// newConfig.IDP.Name != "" instead of config != nil.
if newConfig.IDP.Name != "" {
a.configCache = newConfig
// construct SAML handler
a.samlSP = &saml.ServiceProvider{
Logger: logrus.New(),
IDPMetadata: a.configCache.IDP.Metadata,
AcsURL: *a.configCache.SAMLSvc.ACSURL,
MetadataURL: *a.configCache.SAMLSvc.MetadataURL,
// Not set:
// Key: Private key for Pachyderm ACS. Unclear if needed
// Certificate: Public key for Pachyderm ACS. Unclear if needed
// ForceAuthn: (whether users need to re-authenticate with the IdP, even
// if they already have a session--leaving this false)
// AuthnNameIDFormat: (format the ACS expects the AuthnName to be in)
// MetadataValidDuration: (how long the SP endpoints are valid? Returned
// by the Metadata service)
}
a.redirectAddress = a.configCache.SAMLSvc.DashURL // Set redirect address from config as well
} else {
a.configCache = nil
a.samlSP = nil
a.redirectAddress = nil
}
return nil
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/time.go#L64-L69
|
func (t Time) ValueOrZero() time.Time {
if !t.Valid {
return time.Time{}
}
return t.Time
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/detect.go#L45-L61
|
func detectTextHeader(header textproto.MIMEHeader, emptyContentTypeIsText bool) bool {
ctype := header.Get(hnContentType)
if ctype == "" && emptyContentTypeIsText {
return true
}
mediatype, _, _, err := parseMediaType(ctype)
if err != nil {
return false
}
switch mediatype {
case ctTextPlain, ctTextHTML:
return true
}
return false
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/chain.go#L12-L17
|
func ChainHandlers(handlers ...func(http.Handler) http.Handler) (h http.Handler) {
for i := len(handlers) - 1; i >= 0; i-- {
h = handlers[i](h)
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/domsnapshot.go#L84-L93
|
func (p *CaptureSnapshotParams) Do(ctx context.Context) (documents []*DocumentSnapshot, strings []string, err error) {
// execute
var res CaptureSnapshotReturns
err = cdp.Execute(ctx, CommandCaptureSnapshot, p, &res)
if err != nil {
return nil, nil, err
}
return res.Documents, res.Strings, nil
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/deploymentmanifest.go#L35-L39
|
func NewDeploymentManifest(b []byte) *DeploymentManifest {
dm := new(DeploymentManifest)
yaml.Unmarshal(b, dm)
return dm
}
|
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/log/access.go#L49-L81
|
func Access(h http.Handler, opts ...Option) http.Handler {
o := options{logger: handler.OutLogger(), dateFormat: AccessDateFormat}
o.apply(opts)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
wrapper := handler.NewResponseWrapper(w)
uri := r.URL.RequestURI()
remoteAddr := remoteAddr(r)
remoteUser := remoteUser(r)
method := r.Method
referer := r.Header.Get("Referer")
userAgent := r.Header.Get("User-Agent")
h.ServeHTTP(wrapper, r)
for k, v := range wrapper.Header() {
w.Header()[k] = v
}
w.WriteHeader(wrapper.Code)
w.Write(wrapper.Body.Bytes())
now := time.Now()
timestamp := now.Format(o.dateFormat)
code := wrapper.Code
length := wrapper.Body.Len()
o.logger.Print(fmt.Sprintf("%s - %s [%s - %s] \"%s %s\" %d %d \"%s\" %s",
remoteAddr, remoteUser, timestamp, now.Sub(start), method, uri, code, length, referer, userAgent))
})
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L374-L442
|
func (q *Query) Count(c context.Context) (int, error) {
// Check that the query is well-formed.
if q.err != nil {
return 0, q.err
}
// Run a copy of the query, with keysOnly true (if we're not a projection,
// since the two are incompatible), and an adjusted offset. We also set the
// limit to zero, as we don't want any actual entity data, just the number
// of skipped results.
newQ := q.clone()
newQ.keysOnly = len(newQ.projection) == 0
newQ.limit = 0
if q.limit < 0 {
// If the original query was unlimited, set the new query's offset to maximum.
newQ.offset = math.MaxInt32
} else {
newQ.offset = q.offset + q.limit
if newQ.offset < 0 {
// Do the best we can, in the presence of overflow.
newQ.offset = math.MaxInt32
}
}
req := &pb.Query{}
if err := newQ.toProto(req, internal.FullyQualifiedAppID(c)); err != nil {
return 0, err
}
res := &pb.QueryResult{}
if err := internal.Call(c, "datastore_v3", "RunQuery", req, res); err != nil {
return 0, err
}
// n is the count we will return. For example, suppose that our original
// query had an offset of 4 and a limit of 2008: the count will be 2008,
// provided that there are at least 2012 matching entities. However, the
// RPCs will only skip 1000 results at a time. The RPC sequence is:
// call RunQuery with (offset, limit) = (2012, 0) // 2012 == newQ.offset
// response has (skippedResults, moreResults) = (1000, true)
// n += 1000 // n == 1000
// call Next with (offset, limit) = (1012, 0) // 1012 == newQ.offset - n
// response has (skippedResults, moreResults) = (1000, true)
// n += 1000 // n == 2000
// call Next with (offset, limit) = (12, 0) // 12 == newQ.offset - n
// response has (skippedResults, moreResults) = (12, false)
// n += 12 // n == 2012
// // exit the loop
// n -= 4 // n == 2008
var n int32
for {
// The QueryResult should have no actual entity data, just skipped results.
if len(res.Result) != 0 {
return 0, errors.New("datastore: internal error: Count request returned too much data")
}
n += res.GetSkippedResults()
if !res.GetMoreResults() {
break
}
if err := callNext(c, res, newQ.offset-n, q.count); err != nil {
return 0, err
}
}
n -= q.offset
if n < 0 {
// If the offset was greater than the number of matching entities,
// return 0 instead of negative.
n = 0
}
return int(n), nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L1099-L1103
|
func (v *ReleaseObjectParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime10(&r, v)
return r.Error()
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L8773-L8775
|
func (api *API) RepositoryAssetLocator(href string) *RepositoryAssetLocator {
return &RepositoryAssetLocator{Href(href), api}
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/capability/capability.go#L31-L52
|
func Enabled(ctx context.Context, api, capability string) bool {
req := &pb.IsEnabledRequest{
Package: &api,
Capability: []string{capability},
}
res := &pb.IsEnabledResponse{}
if err := internal.Call(ctx, "capability_service", "IsEnabled", req, res); err != nil {
log.Warningf(ctx, "capability.Enabled: RPC failed: %v", err)
return false
}
switch *res.SummaryStatus {
case pb.IsEnabledResponse_ENABLED,
pb.IsEnabledResponse_SCHEDULED_FUTURE,
pb.IsEnabledResponse_SCHEDULED_NOW:
return true
case pb.IsEnabledResponse_UNKNOWN:
log.Errorf(ctx, "capability.Enabled: unknown API capability %s/%s", api, capability)
return false
default:
return false
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/util.go#L82-L103
|
func checkPostResponse(resp *http.Response, body []byte, req *http.Request, to types.ID) error {
switch resp.StatusCode {
case http.StatusPreconditionFailed:
switch strings.TrimSuffix(string(body), "\n") {
case errIncompatibleVersion.Error():
plog.Errorf("request sent was ignored by peer %s (server version incompatible)", to)
return errIncompatibleVersion
case errClusterIDMismatch.Error():
plog.Errorf("request sent was ignored (cluster ID mismatch: remote[%s]=%s, local=%s)",
to, resp.Header.Get("X-Etcd-Cluster-ID"), req.Header.Get("X-Etcd-Cluster-ID"))
return errClusterIDMismatch
default:
return fmt.Errorf("unhandled error %q when precondition failed", string(body))
}
case http.StatusForbidden:
return errMemberRemoved
case http.StatusNoContent:
return nil
default:
return fmt.Errorf("unexpected http status %s while posting to %q", http.StatusText(resp.StatusCode), req.URL.String())
}
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcauth/tcauth.go#L296-L300
|
func (auth *Auth) Role(roleId string) (*GetRoleResponse, error) {
cd := tcclient.Client(*auth)
responseObject, _, err := (&cd).APICall(nil, "GET", "/roles/"+url.QueryEscape(roleId), new(GetRoleResponse), nil)
return responseObject.(*GetRoleResponse), err
}
|
https://github.com/akutz/gotil/blob/6fa2e80bd3ac40f15788cfc3d12ebba49a0add92/gotil.go#L297-L307
|
func IsTCPPortAvailable(port int) bool {
if port < minTCPPort || port > maxTCPPort {
return false
}
conn, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
return false
}
conn.Close()
return true
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/crier/controller.go#L134-L139
|
func (c *Controller) runWorker() {
c.wg.Add(1)
for c.processNextItem() {
}
c.wg.Done()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/github.go#L40-L42
|
func (o *GitHubOptions) AddFlags(fs *flag.FlagSet) {
o.addFlags(true, fs)
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/module.go#L131-L164
|
func (t *pcTab) read(core *core.Process, data core.Address) {
var pcQuantum int64
switch core.Arch() {
case "386", "amd64", "amd64p32":
pcQuantum = 1
case "s390x":
pcQuantum = 2
case "arm", "arm64", "mips", "mipsle", "mips64", "mips64le", "ppc64", "ppc64le":
pcQuantum = 4
default:
panic("unknown architecture " + core.Arch())
}
val := int64(-1)
first := true
for {
// Advance value.
v, n := readVarint(core, data)
if v == 0 && !first {
return
}
data = data.Add(n)
if v&1 != 0 {
val += ^(v >> 1)
} else {
val += v >> 1
}
// Advance pc.
v, n = readVarint(core, data)
data = data.Add(n)
t.entries = append(t.entries, pcTabEntry{bytes: v * pcQuantum, val: val})
first = false
}
}
|
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/requestbuilder.go#L24-L27
|
func (r *RequestBuilder) Arguments(args ...string) *RequestBuilder {
r.args = append(r.args, args...)
return r
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/log/log.go#L311-L347
|
func (l *GRPCLogWriter) Write(p []byte) (int, error) {
parts := strings.SplitN(string(p), " ", 4)
entry := l.logger.WithField("source", l.source)
if len(parts) == 4 {
// parts[1] and parts[2] contain the date and time, but logrus already
// adds this under the `time` entry field, so it's not needed (though
// the time will presumably be marginally ahead of the original log
// message)
level := parts[0]
message := strings.TrimSpace(parts[3])
if level == "INFO:" {
entry.Info(message)
} else if level == "ERROR:" {
entry.Error(message)
} else if level == "WARNING:" {
entry.Warning(message)
} else if level == "FATAL:" {
// no need to call fatal ourselves because gRPC will exit the
// process
entry.Error(message)
} else {
entry.Error(message)
entry.Error("entry had unknown log level prefix: '%s'; this is a bug, please report it along with the previous log entry", level)
}
} else {
// can't format the message -- just display the contents
entry := l.logger.WithFields(logrus.Fields{
"source": l.source,
})
entry.Error(p)
entry.Error("entry had unexpected format; this is a bug, please report it along with the previous log entry")
}
return len(p), nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L829-L849
|
func transportNew(config *restConfig) (http.RoundTripper, error) {
// REMOVED: custom config.Transport support.
// Set transport level security
var (
rt http.RoundTripper
err error
)
rt, err = tlsCacheGet(config)
if err != nil {
return nil, err
}
// REMOVED: HTTPWrappersForConfig(config, rt) in favor of the caller setting HTTP headers itself based on restConfig. Only this inlined check remains.
if len(config.Username) != 0 && len(config.BearerToken) != 0 {
return nil, errors.Errorf("username/password or bearer token may be set, but not both")
}
return rt, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/lenses/metadata/lens.go#L77-L140
|
func (lens Lens) Body(artifacts []lenses.Artifact, resourceDir string, data string) string {
var buf bytes.Buffer
type MetadataViewData struct {
Status string
StartTime time.Time
FinishedTime time.Time
Elapsed time.Duration
Metadata map[string]string
}
metadataViewData := MetadataViewData{Status: "Pending"}
started := gcs.Started{}
finished := gcs.Finished{}
for _, a := range artifacts {
read, err := a.ReadAll()
if err != nil {
logrus.WithError(err).Error("Failed reading from artifact.")
}
if a.JobPath() == "started.json" {
if err = json.Unmarshal(read, &started); err != nil {
logrus.WithError(err).Error("Error unmarshaling started.json")
}
metadataViewData.StartTime = time.Unix(started.Timestamp, 0)
} else if a.JobPath() == "finished.json" {
if err = json.Unmarshal(read, &finished); err != nil {
logrus.WithError(err).Error("Error unmarshaling finished.json")
}
if finished.Timestamp != nil {
metadataViewData.FinishedTime = time.Unix(*finished.Timestamp, 0)
}
metadataViewData.Status = finished.Result
}
}
if !metadataViewData.StartTime.IsZero() {
if metadataViewData.FinishedTime.IsZero() {
metadataViewData.Elapsed = time.Now().Sub(metadataViewData.StartTime)
} else {
metadataViewData.Elapsed =
metadataViewData.FinishedTime.Sub(metadataViewData.StartTime)
}
metadataViewData.Elapsed = metadataViewData.Elapsed.Round(time.Second)
}
metadataViewData.Metadata = map[string]string{"node": started.Node}
metadatas := []metadata.Metadata{started.Metadata, finished.Metadata}
for _, m := range metadatas {
for k, v := range m {
if s, ok := v.(string); ok && v != "" {
metadataViewData.Metadata[k] = s
}
}
}
metadataTemplate, err := template.ParseFiles(filepath.Join(resourceDir, "template.html"))
if err != nil {
return fmt.Sprintf("Failed to load template: %v", err)
}
if err := metadataTemplate.ExecuteTemplate(&buf, "body", metadataViewData); err != nil {
logrus.WithError(err).Error("Error executing template.")
}
return buf.String()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/easyjson.go#L941-L945
|
func (v *EventRequestPaused) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoFetch8(&r, v)
return r.Error()
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/android/android.go#L27-L76
|
func Draw(gc draw2d.GraphicContext, x, y float64) {
// set the fill and stroke color of the droid
gc.SetFillColor(color.RGBA{0x44, 0xff, 0x44, 0xff})
gc.SetStrokeColor(color.RGBA{0x44, 0x44, 0x44, 0xff})
// set line properties
gc.SetLineCap(draw2d.RoundCap)
gc.SetLineWidth(5)
// head
gc.MoveTo(x+30, y+70)
gc.ArcTo(x+80, y+70, 50, 50, 180*(math.Pi/180), 180*(math.Pi/180))
gc.Close()
gc.FillStroke()
gc.MoveTo(x+60, y+25)
gc.LineTo(x+50, y+10)
gc.MoveTo(x+100, y+25)
gc.LineTo(x+110, y+10)
gc.Stroke()
// left eye
draw2dkit.Circle(gc, x+60, y+45, 5)
gc.FillStroke()
// right eye
draw2dkit.Circle(gc, x+100, y+45, 5)
gc.FillStroke()
// body
draw2dkit.RoundedRectangle(gc, x+30, y+75, x+30+100, y+75+90, 10, 10)
gc.FillStroke()
draw2dkit.Rectangle(gc, x+30, y+75, x+30+100, y+75+80)
gc.FillStroke()
// left arm
draw2dkit.RoundedRectangle(gc, x+5, y+80, x+5+20, y+80+70, 10, 10)
gc.FillStroke()
// right arm
draw2dkit.RoundedRectangle(gc, x+135, y+80, x+135+20, y+80+70, 10, 10)
gc.FillStroke()
// left leg
draw2dkit.RoundedRectangle(gc, x+50, y+150, x+50+20, y+150+50, 10, 10)
gc.FillStroke()
// right leg
draw2dkit.RoundedRectangle(gc, x+90, y+150, x+90+20, y+150+50, 10, 10)
gc.FillStroke()
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/wrap.go#L254-L256
|
func (a *Field) Declaration() string {
return fmt.Sprintf("%s %s", a.Name(), a.ArgType())
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L356-L359
|
func (w *WriteBuffer) Reset() {
w.remaining = w.buffer
w.err = nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L2627-L2631
|
func (v RuleMatch) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss24(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4439-L4448
|
func (u TransactionResultResult) ArmForSwitch(sw int32) (string, bool) {
switch TransactionResultCode(sw) {
case TransactionResultCodeTxSuccess:
return "Results", true
case TransactionResultCodeTxFailed:
return "Results", true
default:
return "", true
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/amount/main.go#L36-L53
|
func Parse(v string) (xdr.Int64, error) {
var f, o, r big.Rat
_, ok := f.SetString(v)
if !ok {
return xdr.Int64(0), fmt.Errorf("cannot parse amount: %s", v)
}
o.SetInt64(One)
r.Mul(&f, &o)
is := r.FloatString(0)
i, err := strconv.ParseInt(is, 10, 64)
if err != nil {
return xdr.Int64(0), err
}
return xdr.Int64(i), nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L262-L327
|
func (d *Destination) writeLegacyLayerMetadata(layerDescriptors []manifest.Schema2Descriptor) (layerPaths []string, lastLayerID string, err error) {
var chainID digest.Digest
lastLayerID = ""
for i, l := range layerDescriptors {
// This chainID value matches the computation in docker/docker/layer.CreateChainID …
if chainID == "" {
chainID = l.Digest
} else {
chainID = digest.Canonical.FromString(chainID.String() + " " + l.Digest.String())
}
// … but note that this image ID does not match docker/docker/image/v1.CreateID. At least recent
// versions allocate new IDs on load, as long as the IDs we use are unique / cannot loop.
//
// Overall, the goal of computing a digest dependent on the full history is to avoid reusing an image ID
// (and possibly creating a loop in the "parent" links) if a layer with the same DiffID appears two or more
// times in layersDescriptors. The ChainID values are sufficient for this, the v1.CreateID computation
// which also mixes in the full image configuration seems unnecessary, at least as long as we are storing
// only a single image per tarball, i.e. all DiffID prefixes are unique (can’t differ only with
// configuration).
layerID := chainID.Hex()
physicalLayerPath := l.Digest.Hex() + ".tar"
// The layer itself has been stored into physicalLayerPath in PutManifest.
// So, use that path for layerPaths used in the non-legacy manifest
layerPaths = append(layerPaths, physicalLayerPath)
// ... and create a symlink for the legacy format;
if err := d.sendSymlink(filepath.Join(layerID, legacyLayerFileName), filepath.Join("..", physicalLayerPath)); err != nil {
return nil, "", errors.Wrap(err, "Error creating layer symbolic link")
}
b := []byte("1.0")
if err := d.sendBytes(filepath.Join(layerID, legacyVersionFileName), b); err != nil {
return nil, "", errors.Wrap(err, "Error writing VERSION file")
}
// The legacy format requires a config file per layer
layerConfig := make(map[string]interface{})
layerConfig["id"] = layerID
// The root layer doesn't have any parent
if lastLayerID != "" {
layerConfig["parent"] = lastLayerID
}
// The root layer configuration file is generated by using subpart of the image configuration
if i == len(layerDescriptors)-1 {
var config map[string]*json.RawMessage
err := json.Unmarshal(d.config, &config)
if err != nil {
return nil, "", errors.Wrap(err, "Error unmarshaling config")
}
for _, attr := range [7]string{"architecture", "config", "container", "container_config", "created", "docker_version", "os"} {
layerConfig[attr] = config[attr]
}
}
b, err := json.Marshal(layerConfig)
if err != nil {
return nil, "", errors.Wrap(err, "Error marshaling layer config")
}
if err := d.sendBytes(filepath.Join(layerID, legacyConfigFileName), b); err != nil {
return nil, "", errors.Wrap(err, "Error writing config json file")
}
lastLayerID = layerID
}
return layerPaths, lastLayerID, nil
}
|
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nsqlookup/handler.go#L460-L566
|
func (h TCPHandler) ServeConn(ctx context.Context, conn net.Conn) {
const bufSize = 2048
var r = bufio.NewReaderSize(conn, bufSize)
var w = bufio.NewWriterSize(conn, bufSize)
if h.ReadTimeout == 0 {
h.ReadTimeout = DefaultReadTimeout
}
if h.WriteTimeout == 0 {
h.WriteTimeout = DefaultWriteTimeout
}
if h.EngineTimeout == 0 {
h.EngineTimeout = DefaultEngineTimeout
}
if ctx == nil {
ctx = context.Background()
}
host, port, _ := net.SplitHostPort(conn.LocalAddr().String())
if h.Info.TcpPort == 0 {
h.Info.TcpPort, _ = strconv.Atoi(port)
}
if len(h.Info.BroadcastAddress) == 0 {
h.Info.BroadcastAddress = host
}
if len(h.Info.Hostname) == 0 {
h.Info.Hostname, _ = os.Hostname()
}
if len(h.Info.Version) == 0 {
info, _ := h.Engine.LookupInfo(ctx)
h.Info.Version = info.Version
}
var node Node
var cmdChan = make(chan Command)
var resChan = make(chan Response)
var errChan = make(chan error, 2)
var doneChan = ctx.Done()
defer func() {
if node != nil {
err := node.Unregister(ctx)
log.Printf("UNREGISTER node = %s, err = %s", node, err)
}
}()
defer close(resChan)
go h.readLoop(ctx, conn, r, cmdChan, errChan)
go h.writeLoop(ctx, conn, w, resChan, errChan)
for {
var cmd Command
var res Response
var err error
select {
case <-doneChan:
return
case <-errChan:
return
case cmd = <-cmdChan:
}
switch c := cmd.(type) {
case Ping:
res, err = h.ping(ctx, node)
case Identify:
node, res, err = h.identify(ctx, node, c.Info, conn)
case Register:
res, err = h.register(ctx, node, c.Topic, c.Channel)
case Unregister:
node, res, err = h.unregister(ctx, node, c.Topic, c.Channel)
default:
res = makeErrInvalid("unknown command")
}
if err != nil {
switch e := err.(type) {
case Error:
res = e
default:
log.Print(err)
return
}
}
select {
case <-doneChan:
return
case <-errChan:
return
case resChan <- res:
}
}
}
|
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L571-L577
|
func (v Value) Int64() int64 {
x, ok := v.data.(int64)
if !ok {
return 0
}
return x
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L125-L146
|
func (p *Page) GetCookies() ([]*http.Cookie, error) {
apiCookies, err := p.session.GetCookies()
if err != nil {
return nil, fmt.Errorf("failed to get cookies: %s", err)
}
cookies := []*http.Cookie{}
for _, apiCookie := range apiCookies {
expSeconds := int64(apiCookie.Expiry)
expNano := int64(apiCookie.Expiry-float64(expSeconds)) * 1000000000
cookie := &http.Cookie{
Name: apiCookie.Name,
Value: apiCookie.Value,
Path: apiCookie.Path,
Domain: apiCookie.Domain,
Secure: apiCookie.Secure,
HttpOnly: apiCookie.HTTPOnly,
Expires: time.Unix(expSeconds, expNano),
}
cookies = append(cookies, cookie)
}
return cookies, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/helpers.go#L90-L106
|
func parameters(a *gen.Action) string {
var m = a.MandatoryParams()
var hasOptional = a.HasOptionalParams()
var countParams = len(m)
if hasOptional {
countParams++
}
var params = make([]string, countParams)
for i, param := range m {
params[i] = fmt.Sprintf("%s %s", fixReserved(param.VarName), param.Signature())
}
if hasOptional {
params[countParams-1] = "options rsapi.APIParams"
}
return strings.Join(params, ", ")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.