_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L1063-L1093
|
func loadDoc(dst interface{}, src *pb.Document, exprs []*pb.Field) (err error) {
fields, err := protoToFields(src.Field)
if err != nil {
return err
}
facets, err := protoToFacets(src.Facet)
if err != nil {
return err
}
if len(exprs) > 0 {
exprFields, err := protoToFields(exprs)
if err != nil {
return err
}
// Mark each field as derived.
for i := range exprFields {
exprFields[i].Derived = true
}
fields = append(fields, exprFields...)
}
meta := &DocumentMetadata{
Rank: int(src.GetOrderId()),
Facets: facets,
}
switch x := dst.(type) {
case FieldLoadSaver:
return x.Load(fields, meta)
default:
return loadStructWithMeta(dst, fields, meta)
}
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/vm.go#L39-L55
|
func (v *vm) execute(cmd []command) {
v.ip = 0 // reset instruction pointer
for n := 0; n < maxCommands; n++ {
ip := v.ip
if ip >= uint32(len(cmd)) {
return
}
ins := cmd[ip]
ins.f(v, ins.bm, ins.op) // run cpu instruction
if v.ipMod {
// command modified ip, don't increment
v.ipMod = false
} else {
v.ip++ // increment ip for next command
}
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L321-L347
|
func (n *NetworkTransport) getConn(target ServerAddress) (*netConn, error) {
// Check for a pooled conn
if conn := n.getPooledConn(target); conn != nil {
return conn, nil
}
// Dial a new connection
conn, err := n.stream.Dial(target, n.timeout)
if err != nil {
return nil, err
}
// Wrap the conn
netConn := &netConn{
target: target,
conn: conn,
r: bufio.NewReader(conn),
w: bufio.NewWriter(conn),
}
// Setup encoder/decoders
netConn.dec = codec.NewDecoder(netConn.r, &codec.MsgpackHandle{})
netConn.enc = codec.NewEncoder(netConn.w, &codec.MsgpackHandle{})
// Done
return netConn, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L345-L349
|
func (v *SetOuterHTMLParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom2(&r, v)
return r.Error()
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/bool.go#L94-L102
|
func (b Bool) MarshalJSON() ([]byte, error) {
if !b.Valid {
return []byte("null"), nil
}
if !b.Bool {
return []byte("false"), nil
}
return []byte("true"), nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L1024-L1026
|
func (c *restConfig) HasCA() bool {
return len(c.CAData) > 0 || len(c.CAFile) > 0
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/api_server.go#L2195-L2218
|
func (a *apiServer) canonicalizeSubjects(ctx context.Context, subjects []string) ([]string, error) {
if subjects == nil {
return []string{}, nil
}
eg := &errgroup.Group{}
canonicalizedSubjects := make([]string, len(subjects))
for i, subject := range subjects {
i, subject := i, subject
eg.Go(func() error {
subject, err := a.canonicalizeSubject(ctx, subject)
if err != nil {
return err
}
canonicalizedSubjects[i] = subject
return nil
})
}
if err := eg.Wait(); err != nil {
return nil, err
}
return canonicalizedSubjects, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gcsweb/cmd/gcsweb/gcsweb.go#L566-L569
|
func (pfx *Prefix) Render(out http.ResponseWriter, inPath string) {
url := gcsPath + inPath + pfx.Prefix
htmlGridItem(out, iconDir, url, pfx.Prefix, "-", "-")
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2156-L2159
|
func (e MemoType) String() string {
name, _ := memoTypeMap[int32(e)]
return name
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/easyjson.go#L474-L478
|
func (v EventBackgroundServiceEventReceived) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoBackgroundservice5(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L914-L919
|
func WithValidatorTimeout(timeout time.Duration) ValidatorOpt {
return func(addVal *addValReq) error {
addVal.timeout = timeout
return nil
}
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/service.go#L300-L306
|
func Proxy(service *Service, path string, evt *event.Event, requestID string, w http.ResponseWriter, r *http.Request) error {
endpoint, err := service.getClient("production")
if err != nil {
return err
}
return endpoint.Proxy(path, evt, requestID, w, r)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/networks.go#L456-L488
|
func (c *Cluster) NetworkCreate(name, description string, config map[string]string) (int64, error) {
var id int64
err := c.Transaction(func(tx *ClusterTx) error {
result, err := tx.tx.Exec("INSERT INTO networks (name, description, state) VALUES (?, ?, ?)", name, description, networkCreated)
if err != nil {
return err
}
id, err := result.LastInsertId()
if err != nil {
return err
}
// Insert a node-specific entry pointing to ourselves.
columns := []string{"network_id", "node_id"}
values := []interface{}{id, c.nodeID}
_, err = query.UpsertObject(tx.tx, "networks_nodes", columns, values)
if err != nil {
return err
}
err = networkConfigAdd(tx.tx, id, c.nodeID, config)
if err != nil {
return err
}
return nil
})
if err != nil {
id = -1
}
return id, err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/api/response.go#L45-L53
|
func (r *Response) MetadataAsMap() (map[string]interface{}, error) {
ret := map[string]interface{}{}
err := r.MetadataAsStruct(&ret)
if err != nil {
return nil, err
}
return ret, nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_src.go#L393-L474
|
func deleteImage(ctx context.Context, sys *types.SystemContext, ref dockerReference) error {
// docker/distribution does not document what action should be used for deleting images.
//
// Current docker/distribution requires "pull" for reading the manifest and "delete" for deleting it.
// quay.io requires "push" (an explicit "pull" is unnecessary), does not grant any token (fails parsing the request) if "delete" is included.
// OpenShift ignores the action string (both the password and the token is an OpenShift API token identifying a user).
//
// We have to hard-code a single string, luckily both docker/distribution and quay.io support "*" to mean "everything".
c, err := newDockerClientFromRef(sys, ref, true, "*")
if err != nil {
return err
}
// When retrieving the digest from a registry >= 2.3 use the following header:
// "Accept": "application/vnd.docker.distribution.manifest.v2+json"
headers := make(map[string][]string)
headers["Accept"] = []string{manifest.DockerV2Schema2MediaType}
refTail, err := ref.tagOrDigest()
if err != nil {
return err
}
getPath := fmt.Sprintf(manifestPath, reference.Path(ref.ref), refTail)
get, err := c.makeRequest(ctx, "GET", getPath, headers, nil, v2Auth, nil)
if err != nil {
return err
}
defer get.Body.Close()
manifestBody, err := ioutil.ReadAll(get.Body)
if err != nil {
return err
}
switch get.StatusCode {
case http.StatusOK:
case http.StatusNotFound:
return errors.Errorf("Unable to delete %v. Image may not exist or is not stored with a v2 Schema in a v2 registry", ref.ref)
default:
return errors.Errorf("Failed to delete %v: %s (%v)", ref.ref, manifestBody, get.Status)
}
digest := get.Header.Get("Docker-Content-Digest")
deletePath := fmt.Sprintf(manifestPath, reference.Path(ref.ref), digest)
// When retrieving the digest from a registry >= 2.3 use the following header:
// "Accept": "application/vnd.docker.distribution.manifest.v2+json"
delete, err := c.makeRequest(ctx, "DELETE", deletePath, headers, nil, v2Auth, nil)
if err != nil {
return err
}
defer delete.Body.Close()
body, err := ioutil.ReadAll(delete.Body)
if err != nil {
return err
}
if delete.StatusCode != http.StatusAccepted {
return errors.Errorf("Failed to delete %v: %s (%v)", deletePath, string(body), delete.Status)
}
if c.signatureBase != nil {
manifestDigest, err := manifest.Digest(manifestBody)
if err != nil {
return err
}
for i := 0; ; i++ {
url := signatureStorageURL(c.signatureBase, manifestDigest, i)
if url == nil {
return errors.Errorf("Internal error: signatureStorageURL with non-nil base returned nil")
}
missing, err := c.deleteOneSignature(url)
if err != nil {
return err
}
if missing {
break
}
}
}
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_transport.go#L77-L83
|
func NewReference(path string) (types.ImageReference, error) {
resolved, err := explicitfilepath.ResolvePathToFullyExplicit(path)
if err != nil {
return nil, err
}
return dirReference{path: path, resolvedPath: resolved}, nil
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L107-L110
|
func (p MailBuilder) ReplyTo(name, addr string) MailBuilder {
p.replyTo = mail.Address{Name: name, Address: addr}
return p
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gcsweb/cmd/gcsweb/gcsweb.go#L262-L272
|
func splitBucketObject(path string) (string, string) {
path = strings.Trim(path, "/")
parts := strings.SplitN(path, "/", 2)
if len(parts) == 0 {
return "", ""
}
if len(parts) == 1 {
return parts[0], ""
}
return parts[0], parts[1]
}
|
https://github.com/antlinker/go-dirtyfilter/blob/533f538ffaa112776b1258c3db63e6f55648e18b/store/memory.go#L17-L45
|
func NewMemoryStore(config MemoryConfig) (*MemoryStore, error) {
memStore := &MemoryStore{
dataStore: cmap.NewConcurrencyMap(),
}
if config.Delim == 0 {
config.Delim = DefaultDelim
}
if dataLen := len(config.DataSource); dataLen > 0 {
for i := 0; i < dataLen; i++ {
memStore.dataStore.Set(config.DataSource[i], 1)
}
} else if config.Reader != nil {
buf := new(bytes.Buffer)
io.Copy(buf, config.Reader)
buf.WriteByte(config.Delim)
for {
line, err := buf.ReadString(config.Delim)
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
memStore.dataStore.Set(line, 1)
}
buf.Reset()
}
return memStore, nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4052-L4060
|
func (u OperationResultTr) MustManageOfferResult() ManageOfferResult {
val, ok := u.GetManageOfferResult()
if !ok {
panic("arm ManageOfferResult is not set")
}
return val
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/context.go#L45-L47
|
func WithHeaders(ctx context.Context, headers map[string]string) Context {
return tchannel.WrapWithHeaders(ctx, headers)
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L455-L459
|
func (mat *MatND) Clone() *MatND {
mat_c := (*C.CvMatND)(mat)
mat_ret := C.cvCloneMatND(mat_c)
return (*MatND)(mat_ret)
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L71-L73
|
func (api *API) DebugCookbookPathLocator(href string) *DebugCookbookPathLocator {
return &DebugCookbookPathLocator{Href(href), api}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/manifest.go#L115-L121
|
func isMultiImage(ctx context.Context, img types.UnparsedImage) (bool, error) {
_, mt, err := img.Manifest(ctx)
if err != nil {
return false, err
}
return manifest.MIMETypeIsMultiImage(mt), nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L810-L814
|
func (v *DeleteEntryParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCachestorage7(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L1385-L1389
|
func (v *ForciblyPurgeJavaScriptMemoryParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoMemory16(&r, v)
return r.Error()
}
|
https://github.com/heketi/tests/blob/f3775cbcefd6822086c729e3ce4b70ca85a5bd21/patch.go#L25-L39
|
func Patch(dest, value interface{}) Restorer {
destv := reflect.ValueOf(dest).Elem()
oldv := reflect.New(destv.Type()).Elem()
oldv.Set(destv)
valuev := reflect.ValueOf(value)
if !valuev.IsValid() {
// This isn't quite right when the destination type is not
// nilable, but it's better than the complex alternative.
valuev = reflect.Zero(destv.Type())
}
destv.Set(valuev)
return func() {
destv.Set(oldv)
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L753-L775
|
func (c *Cluster) StoragePoolVolumesGetType(project string, volumeType int, poolID, nodeID int64) ([]string, error) {
var poolName string
query := `
SELECT storage_volumes.name
FROM storage_volumes
JOIN projects ON projects.id=storage_volumes.project_id
WHERE (projects.name=? OR storage_volumes.type=?) AND storage_pool_id=? AND node_id=? AND type=?
`
inargs := []interface{}{project, StoragePoolVolumeTypeCustom, poolID, nodeID, volumeType}
outargs := []interface{}{poolName}
result, err := queryScan(c.db, query, inargs, outargs)
if err != nil {
return []string{}, err
}
response := []string{}
for _, r := range result {
response = append(response, r[0].(string))
}
return response, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L57-L61
|
func (v StopSamplingParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoMemory(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/y.go#L191-L195
|
func NewCloser(initial int) *Closer {
ret := &Closer{closed: make(chan struct{})}
ret.waiting.Add(initial)
return ret
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gbytes/buffer.go#L172-L217
|
func (b *Buffer) Detect(desired string, args ...interface{}) chan bool {
formattedRegexp := desired
if len(args) > 0 {
formattedRegexp = fmt.Sprintf(desired, args...)
}
re := regexp.MustCompile(formattedRegexp)
b.lock.Lock()
defer b.lock.Unlock()
if b.detectCloser == nil {
b.detectCloser = make(chan interface{})
}
closer := b.detectCloser
response := make(chan bool)
go func() {
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
defer close(response)
for {
select {
case <-ticker.C:
b.lock.Lock()
data, cursor := b.contents[b.readCursor:], b.readCursor
loc := re.FindIndex(data)
b.lock.Unlock()
if loc != nil {
response <- true
b.lock.Lock()
newCursorPosition := cursor + uint64(loc[1])
if newCursorPosition >= b.readCursor {
b.readCursor = newCursorPosition
}
b.lock.Unlock()
return
}
case <-closer:
return
}
}
}()
return response
}
|
https://github.com/nicholasjackson/bench/blob/2df9635f0ad020b2e82616b0fd87130aaa1ee12e/output/plot.go#L14-L117
|
func PlotData(interval time.Duration, r results.ResultSet, w io.Writer) {
set := r.Reduce(interval)
t := results.TabularResults{}
rows := t.Tabulate(set)
seriesY := createYSeries(rows)
seriesX := createXSeries(rows)
ticks := createXTicks(rows)
graph := chart.Chart{
Background: chart.Style{
Padding: chart.Box{
Top: 50,
Left: 25,
Right: 25,
Bottom: 25,
},
FillColor: drawing.ColorFromHex("efefef"),
},
XAxis: chart.XAxis{
Name: "Elapsed Time (s)",
NameStyle: chart.StyleShow(),
Style: chart.StyleShow(),
ValueFormatter: func(v interface{}) string {
return fmt.Sprintf("%.0f", v)
},
Ticks: ticks,
},
YAxis: chart.YAxis{
Name: "Count",
NameStyle: chart.StyleShow(),
Style: chart.StyleShow(),
ValueFormatter: func(v interface{}) string {
return fmt.Sprintf("%.0f", v)
},
},
YAxisSecondary: chart.YAxis{
Name: "Time (ms)",
NameStyle: chart.StyleShow(),
Style: chart.StyleShow(),
ValueFormatter: func(v interface{}) string {
return fmt.Sprintf("%.2f", v)
},
},
Series: []chart.Series{
chart.ContinuousSeries{
Name: "Success",
XValues: seriesX["x"],
YValues: seriesY["y.success"],
Style: chart.Style{
Show: true, //note; if we set ANY other properties, we must set this to true.
StrokeColor: drawing.ColorGreen, // will supercede defaults
FillColor: drawing.ColorGreen.WithAlpha(64), // will supercede defaults
},
},
chart.ContinuousSeries{
Name: "Failure",
XValues: seriesX["x"],
YValues: seriesY["y.failure"],
Style: chart.Style{
Show: true, //note; if we set ANY other properties, we must set this to true.
StrokeColor: drawing.ColorRed, // will supercede defaults
FillColor: drawing.ColorRed.WithAlpha(64), // will supercede defaults
},
},
chart.ContinuousSeries{
Name: "Timeout",
XValues: seriesX["x"],
YValues: seriesY["y.timeout"],
Style: chart.Style{
Show: true, //note; if we set ANY other properties, we must set this to true.
StrokeColor: drawing.ColorFromHex("FFD133"), // will supercede defaults
FillColor: drawing.ColorFromHex("FFD133").WithAlpha(64), // will supercede defaults
},
},
chart.ContinuousSeries{
Name: "Threads",
XValues: seriesX["x"],
YValues: seriesY["y.threads"],
Style: chart.Style{
Show: true, //note; if we set ANY other properties, we must set this to true.
StrokeColor: drawing.ColorFromHex("FF338D"), // will supercede defaults
},
},
chart.ContinuousSeries{
YAxis: chart.YAxisSecondary,
Name: "Request time (ms)",
XValues: seriesX["x"],
YValues: seriesY["y.request"],
Style: chart.Style{
Show: true, //note; if we set ANY other properties, we must set this to true.
StrokeColor: drawing.ColorBlue, // will supercede defaults
},
},
},
}
//note we have to do this as a separate step because we need a reference to graph
graph.Elements = []chart.Renderable{
chart.Legend(&graph),
}
graph.Render(chart.PNG, w)
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/util.go#L69-L93
|
func alignTypesForArithmetic(left, right interface{}) (reflect.Value, reflect.Value) {
// These avoid crashes for accessing nil interfaces
if left == nil {
left = 0
}
if right == nil {
right = 0
}
leftV := interfaceToNumeric(left)
rightV := interfaceToNumeric(right)
if leftV.Kind() == rightV.Kind() {
return leftV, rightV
}
var alignTo reflect.Type
if leftV.Kind() > rightV.Kind() {
alignTo = leftV.Type()
} else {
alignTo = rightV.Type()
}
return leftV.Convert(alignTo), rightV.Convert(alignTo)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/fake_open_wrapper.go#L35-L37
|
func (t *EventTimeHeap) Push(x interface{}) {
*t = append(*t, x.(sql.IssueEvent))
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/storage/chunk/storage.go#L46-L50
|
func (s *Storage) DeleteAll(ctx context.Context) error {
return s.objC.Walk(ctx, s.prefix, func(hash string) error {
return s.objC.Delete(ctx, hash)
})
}
|
https://github.com/tylerb/gls/blob/e606233f194d6c314156dc6a35f21a42a470c6f6/gls.go#L50-L60
|
func Get(key string) interface{} {
gid := curGoroutineID()
dataLock.RLock()
if data[gid] == nil {
dataLock.RUnlock()
return nil
}
value := data[gid][key]
dataLock.RUnlock()
return value
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2517-L2520
|
func (e CreateAccountResultCode) String() string {
name, _ := createAccountResultCodeMap[int32(e)]
return name
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L4124-L4128
|
func (v GetDocumentParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom47(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L959-L964
|
func PrintFunc(f func() string) error {
if isModeEnable(PRINT) {
return glg.out(PRINT, "%s", f())
}
return nil
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/stringutil/unicode.go#L47-L53
|
func ToASCII(s string) string {
// unicode.Mn: nonspacing marks
tr := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), runes.Map(mapLatinSpecial),
norm.NFC)
r, _, _ := transform.String(tr, s)
return r
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/stmt.go#L44-L75
|
func (s *Stmt) Generate(buf *file.Buffer) error {
if strings.HasPrefix(s.kind, "objects") {
return s.objects(buf)
}
if strings.HasPrefix(s.kind, "create") && strings.HasSuffix(s.kind, "-ref") {
return s.createRef(buf)
}
if strings.HasSuffix(s.kind, "-ref") || strings.Contains(s.kind, "-ref-by-") {
return s.ref(buf)
}
if strings.HasPrefix(s.kind, "names") {
return s.names(buf)
}
switch s.kind {
case "create":
return s.create(buf)
case "id":
return s.id(buf)
case "rename":
return s.rename(buf)
case "update":
return s.update(buf)
case "delete":
return s.delete(buf)
default:
return fmt.Errorf("Unknown statement '%s'", s.kind)
}
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/matchers.go#L415-L417
|
func Not(matcher types.GomegaMatcher) types.GomegaMatcher {
return &matchers.NotMatcher{Matcher: matcher}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/handlers.go#L94-L100
|
func (hmap *handlerMap) find(method []byte) Handler {
hmap.RLock()
handler := hmap.handlers[string(method)]
hmap.RUnlock()
return handler
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/read_only.go#L113-L118
|
func (ro *readOnly) lastPendingRequestCtx() string {
if len(ro.readIndexQueue) == 0 {
return ""
}
return ro.readIndexQueue[len(ro.readIndexQueue)-1]
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L130-L134
|
func ChompRightF(suffix string) func(string) string {
return func(s string) string {
return ChompRight(s, suffix)
}
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/binary-decode.go#L424-L544
|
func (cdc *Codec) decodeReflectBinaryArray(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions, bare bool) (n int, err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if printLog {
fmt.Println("(d) decodeReflectBinaryArray")
defer func() {
fmt.Printf("(d) -> err: %v\n", err)
}()
}
ert := info.Type.Elem()
if ert.Kind() == reflect.Uint8 {
panic("should not happen")
}
length := info.Type.Len()
einfo, err := cdc.getTypeInfo_wlock(ert)
if err != nil {
return
}
if !bare {
// Read byte-length prefixed byteslice.
var buf, _n = []byte(nil), int(0)
buf, _n, err = DecodeByteSlice(bz)
if slide(&bz, nil, _n) && err != nil {
return
}
// This is a trick for debuggability -- we slide on &n more later.
n += UvarintSize(uint64(len(buf)))
bz = buf
}
// If elem is not already a ByteLength type, read in packed form.
// This is a Proto wart due to Proto backwards compatibility issues.
// Amino2 will probably migrate to use the List typ3.
typ3 := typeToTyp3(einfo.Type, fopts)
if typ3 != Typ3_ByteLength {
// Read elements in packed form.
for i := 0; i < length; i++ {
var erv, _n = rv.Index(i), int(0)
_n, err = cdc.decodeReflectBinary(bz, einfo, erv, fopts, false)
if slide(&bz, &n, _n) && err != nil {
err = fmt.Errorf("error reading array contents: %v", err)
return
}
// Special case when reading default value, prefer nil.
if erv.Kind() == reflect.Ptr {
_, isDefault := isDefaultValue(erv)
if isDefault {
erv.Set(reflect.Zero(erv.Type()))
continue
}
}
}
// Ensure that we read the whole buffer.
if len(bz) > 0 {
err = errors.New("bytes left over after reading array contents")
return
}
} else {
// NOTE: ert is for the element value, while einfo.Type is dereferenced.
isErtStructPointer := ert.Kind() == reflect.Ptr && einfo.Type.Kind() == reflect.Struct
// Read elements in unpacked form.
for i := 0; i < length; i++ {
// Read field key (number and type).
var fnum, typ, _n = uint32(0), Typ3(0x00), int(0)
fnum, typ, _n, err = decodeFieldNumberAndTyp3(bz)
// Validate field number and typ3.
if fnum != fopts.BinFieldNum {
err = errors.New(fmt.Sprintf("expected repeated field number %v, got %v", fopts.BinFieldNum, fnum))
return
}
if typ != Typ3_ByteLength {
err = errors.New(fmt.Sprintf("expected repeated field type %v, got %v", Typ3_ByteLength, typ))
return
}
if slide(&bz, &n, _n) && err != nil {
return
}
// Decode the next ByteLength bytes into erv.
var erv = rv.Index(i)
// Special case if:
// * next ByteLength bytes are 0x00, and
// * - erv is not a struct pointer, or
// - field option doesn't have EmptyElements set
// (the condition below uses demorgan's law)
if (len(bz) > 0 && bz[0] == 0x00) &&
!(isErtStructPointer && fopts.EmptyElements) {
slide(&bz, &n, 1)
erv.Set(defaultValue(erv.Type()))
continue
}
// Normal case, read next non-nil element from bz.
// In case of any inner lists in unpacked form.
efopts := fopts
efopts.BinFieldNum = 1
_n, err = cdc.decodeReflectBinary(bz, einfo, erv, efopts, false)
if slide(&bz, &n, _n) && err != nil {
err = fmt.Errorf("error reading array contents: %v", err)
return
}
}
// Ensure that there are no more elements left,
// and no field number regression either.
// This is to provide better error messages.
if len(bz) > 0 {
var fnum = uint32(0)
fnum, _, _, err = decodeFieldNumberAndTyp3(bz)
if err != nil {
return
}
if fnum <= fopts.BinFieldNum {
err = fmt.Errorf("unexpected field number %v after repeated field number %v", fnum, fopts.BinFieldNum)
return
}
}
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/easyjson.go#L1492-L1496
|
func (v DispatchKeyEventParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoInput9(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/olorin/nagiosplugin/blob/893f9702af4ea1e2dc4cd6528cbdcdb3dc7ca064/check.go#L57-L63
|
func NewCheckWithOptions(options CheckOptions) *Check {
c := NewCheck()
if options.StatusPolicy != nil {
c.statusPolicy = options.StatusPolicy
}
return c
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1702-L1722
|
func prepareReviewersBody(logins []string, org string) (map[string][]string, error) {
body := map[string][]string{}
var errors []error
for _, login := range logins {
mat := teamRe.FindStringSubmatch(login)
if mat == nil {
if _, exists := body["reviewers"]; !exists {
body["reviewers"] = []string{}
}
body["reviewers"] = append(body["reviewers"], login)
} else if mat[1] == org {
if _, exists := body["team_reviewers"]; !exists {
body["team_reviewers"] = []string{}
}
body["team_reviewers"] = append(body["team_reviewers"], mat[2])
} else {
errors = append(errors, fmt.Errorf("team %s is not part of %s org", login, org))
}
}
return body, errorutil.NewAggregate(errors...)
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/cloudconfig_manifest_primatives.go#L61-L70
|
func (s *CloudConfigManifest) ContainsDiskType(diskTypeName string) (result bool) {
result = false
for _, diskType := range s.DiskTypes {
if diskType.Name == diskTypeName {
result = true
return
}
}
return
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L195-L212
|
func (c APIClient) StartCommitParent(repoName string, branch string, parentCommit string) (*pfs.Commit, error) {
commit, err := c.PfsAPIClient.StartCommit(
c.Ctx(),
&pfs.StartCommitRequest{
Parent: &pfs.Commit{
Repo: &pfs.Repo{
Name: repoName,
},
ID: parentCommit,
},
Branch: branch,
},
)
if err != nil {
return nil, grpcutil.ScrubGRPC(err)
}
return commit, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/router/router.go#L63-L65
|
func (r *DelayedRouter) AddAll(version, path string, h http.Handler) *mux.Route {
return r.addRoute(version, path, h, "GET", "POST", "PUT", "DELETE")
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L5586-L5590
|
func (v ForcePseudoStateParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss49(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dgl/gc.go#L203-L205
|
func (gc *GraphicContext) FillString(text string) (width float64) {
return gc.FillStringAt(text, 0, 0)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/compare.go#L123-L131
|
func mustInt64(val interface{}) int64 {
if v, ok := val.(int64); ok {
return v
}
if v, ok := val.(int); ok {
return int64(v)
}
panic("bad value")
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/resources.go#L27-L98
|
func api10ResourcesGet(d *Daemon, r *http.Request) Response {
// If a target was specified, forward the request to the relevant node.
response := ForwardedResponseIfTargetIsRemote(d, r)
if response != nil {
return response
}
// Get the local resource usage
res := api.Resources{}
cpu, err := util.CPUResource()
if err != nil {
return SmartError(err)
}
cards, _, err := deviceLoadGpu(false)
if err != nil {
return SmartError(err)
}
gpus := api.ResourcesGPU{}
gpus.Cards = []api.ResourcesGPUCard{}
processedCards := map[uint64]bool{}
for _, card := range cards {
id, err := strconv.ParseUint(card.id, 10, 64)
if err != nil {
continue
}
if processedCards[id] {
continue
}
gpu := api.ResourcesGPUCard{}
gpu.ID = id
gpu.Driver = card.driver
gpu.DriverVersion = card.driverVersion
gpu.PCIAddress = card.pci
gpu.Vendor = card.vendorName
gpu.VendorID = card.vendorID
gpu.Product = card.productName
gpu.ProductID = card.productID
gpu.NUMANode = card.numaNode
if card.isNvidia {
gpu.Nvidia = &api.ResourcesGPUCardNvidia{
CUDAVersion: card.nvidia.cudaVersion,
NVRMVersion: card.nvidia.nvrmVersion,
Brand: card.nvidia.brand,
Model: card.nvidia.model,
UUID: card.nvidia.uuid,
Architecture: card.nvidia.architecture,
}
}
gpus.Cards = append(gpus.Cards, gpu)
gpus.Total += 1
processedCards[id] = true
}
mem, err := util.MemoryResource()
if err != nil {
return SmartError(err)
}
res.CPU = *cpu
res.GPU = gpus
res.Memory = *mem
return SyncResponse(true, res)
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/build/_fixtures/coke/actions/app.go#L72-L78
|
func translations() buffalo.MiddlewareFunc {
var err error
if T, err = i18n.New(packr.New("../locales", "../locales"), "en-US"); err != nil {
app.Stop(err)
}
return T.Middleware()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/tools/etcd-dump-logs/main.go#L156-L158
|
func passConfChange(entry raftpb.Entry) (bool, string) {
return entry.Type == raftpb.EntryConfChange, "ConfigChange"
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/api_server.go#L2219-L2245
|
func (a *APIServer) mergeChunk(logger *taggedLogger, high int64, result *processResult) (retErr error) {
logger.Logf("starting to merge chunk")
defer func(start time.Time) {
if retErr != nil {
logger.Logf("errored merging chunk after %v: %v", time.Since(start), retErr)
} else {
logger.Logf("finished merging chunk after %v", time.Since(start))
}
}(time.Now())
buf := &bytes.Buffer{}
if result.datumsFailed <= 0 {
if err := a.datumCache.Merge(hashtree.NewWriter(buf), nil, nil); err != nil {
return err
}
}
if err := a.chunkCache.Put(high, buf); err != nil {
return err
}
if a.pipelineInfo.EnableStats {
buf.Reset()
if err := a.datumStatsCache.Merge(hashtree.NewWriter(buf), nil, nil); err != nil {
return err
}
return a.chunkStatsCache.Put(high, buf)
}
return nil
}
|
https://github.com/cloudfoundry-incubator/cf-test-helpers/blob/83791edc4b0a2d48b602088c30332063b8f02f32/helpers/app_commands.go#L19-L22
|
func CurlAppWithTimeout(cfg helpersinternal.CurlConfig, appName, path string, timeout time.Duration, args ...string) string {
appCurler := helpersinternal.NewAppCurler(Curl, cfg)
return appCurler.CurlAndWait(cfg, appName, path, timeout, args...)
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/codec.go#L717-L735
|
func isExported(field reflect.StructField) bool {
// Test 1:
if field.PkgPath != "" {
return false
}
// Test 2:
var first rune
for _, c := range field.Name {
first = c
break
}
// TODO: JAE: I'm not sure that the unicode spec
// is the correct spec to use, so this might be wrong.
if !unicode.IsUpper(first) {
return false
}
// Ok, it's exported.
return true
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_cluster.go#L101-L159
|
func clusterGetMemberConfig(cluster *db.Cluster) ([]api.ClusterMemberConfigKey, error) {
var pools map[string]map[string]string
var networks map[string]map[string]string
keys := []api.ClusterMemberConfigKey{}
err := cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
pools, err = tx.StoragePoolsNodeConfig()
if err != nil {
return errors.Wrapf(err, "Failed to fetch storage pools configuration")
}
networks, err = tx.NetworksNodeConfig()
if err != nil {
return errors.Wrapf(err, "Failed to fetch networks configuration")
}
return nil
})
if err != nil {
return nil, err
}
for pool, config := range pools {
for key := range config {
if strings.HasPrefix(key, "volatile.") {
continue
}
key := api.ClusterMemberConfigKey{
Entity: "storage-pool",
Name: pool,
Key: key,
Description: fmt.Sprintf("\"%s\" property for storage pool \"%s\"", key, pool),
}
keys = append(keys, key)
}
}
for network, config := range networks {
for key := range config {
if strings.HasPrefix(key, "volatile.") {
continue
}
key := api.ClusterMemberConfigKey{
Entity: "network",
Name: network,
Key: key,
Description: fmt.Sprintf("\"%s\" property for network \"%s\"", key, network),
}
keys = append(keys, key)
}
}
return keys, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L403-L406
|
func (p GetContentQuadsParams) WithObjectID(objectID runtime.RemoteObjectID) *GetContentQuadsParams {
p.ObjectID = objectID
return &p
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L535-L623
|
func (n *NetworkTransport) handleCommand(r *bufio.Reader, dec *codec.Decoder, enc *codec.Encoder) error {
// Get the rpc type
rpcType, err := r.ReadByte()
if err != nil {
return err
}
// Create the RPC object
respCh := make(chan RPCResponse, 1)
rpc := RPC{
RespChan: respCh,
}
// Decode the command
isHeartbeat := false
switch rpcType {
case rpcAppendEntries:
var req AppendEntriesRequest
if err := dec.Decode(&req); err != nil {
return err
}
rpc.Command = &req
// Check if this is a heartbeat
if req.Term != 0 && req.Leader != nil &&
req.PrevLogEntry == 0 && req.PrevLogTerm == 0 &&
len(req.Entries) == 0 && req.LeaderCommitIndex == 0 {
isHeartbeat = true
}
case rpcRequestVote:
var req RequestVoteRequest
if err := dec.Decode(&req); err != nil {
return err
}
rpc.Command = &req
case rpcInstallSnapshot:
var req InstallSnapshotRequest
if err := dec.Decode(&req); err != nil {
return err
}
rpc.Command = &req
rpc.Reader = io.LimitReader(r, req.Size)
default:
return fmt.Errorf("unknown rpc type %d", rpcType)
}
// Check for heartbeat fast-path
if isHeartbeat {
n.heartbeatFnLock.Lock()
fn := n.heartbeatFn
n.heartbeatFnLock.Unlock()
if fn != nil {
fn(rpc)
goto RESP
}
}
// Dispatch the RPC
select {
case n.consumeCh <- rpc:
case <-n.shutdownCh:
return ErrTransportShutdown
}
// Wait for response
RESP:
select {
case resp := <-respCh:
// Send the error first
respErr := ""
if resp.Error != nil {
respErr = resp.Error.Error()
}
if err := enc.Encode(respErr); err != nil {
return err
}
// Send the response
if err := enc.Encode(resp.Response); err != nil {
return err
}
case <-n.shutdownCh:
return ErrTransportShutdown
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L6631-L6635
|
func (v *CollectClassNamesParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss62(&r, v)
return r.Error()
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L252-L256
|
func (eC2Manager *EC2Manager) GetHealth() (*HealthOfTheEC2Account, error) {
cd := tcclient.Client(*eC2Manager)
responseObject, _, err := (&cd).APICall(nil, "GET", "/health", new(HealthOfTheEC2Account), nil)
return responseObject.(*HealthOfTheEC2Account), err
}
|
https://github.com/lucas-clemente/go-http-logger/blob/0ba07d157a1e5a262f5e7f5ee7bf37719fa8b5d9/logger.go#L40-L71
|
func Logger(next http.Handler) http.HandlerFunc {
stdlogger := log.New(os.Stdout, "", 0)
//errlogger := log.New(os.Stderr, "", 0)
return func(w http.ResponseWriter, r *http.Request) {
// Start timer
start := time.Now()
// Process request
writer := statusWriter{w, 0}
next.ServeHTTP(&writer, r)
// Stop timer
end := time.Now()
latency := end.Sub(start)
clientIP := r.RemoteAddr
method := r.Method
statusCode := writer.status
statusColor := colorForStatus(statusCode)
methodColor := colorForMethod(method)
stdlogger.Printf("[HTTP] %v |%s %3d %s| %12v | %s |%s %s %-7s %s\n",
end.Format("2006/01/02 - 15:04:05"),
statusColor, statusCode, reset,
latency,
clientIP,
methodColor, reset, method,
r.URL.Path,
)
}
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/ctors.go#L267-L272
|
func (api *TelegramBotAPI) NewOutgoingUserProfilePhotosRequest(userID int) *OutgoingUserProfilePhotosRequest {
return &OutgoingUserProfilePhotosRequest{
api: api,
UserID: userID,
}
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L767-L772
|
func InfoFunc(f func() string) error {
if isModeEnable(INFO) {
return glg.out(INFO, "%s", f())
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/pipeline/controller.go#L349-L442
|
func reconcile(c reconciler, key string) error {
logrus.Debugf("reconcile: %s\n", key)
ctx, namespace, name, err := fromKey(key)
if err != nil {
runtime.HandleError(err)
return nil
}
var wantPipelineRun bool
pj, err := c.getProwJob(name)
switch {
case apierrors.IsNotFound(err):
// Do not want pipeline
case err != nil:
return fmt.Errorf("get prowjob: %v", err)
case pj.Spec.Agent != prowjobv1.TektonAgent:
// Do not want a pipeline for this job
case pjutil.ClusterToCtx(pj.Spec.Cluster) != ctx:
// Build is in wrong cluster, we do not want this build
logrus.Warnf("%s found in context %s not %s", key, ctx, pjutil.ClusterToCtx(pj.Spec.Cluster))
case pj.DeletionTimestamp == nil:
wantPipelineRun = true
}
var havePipelineRun bool
p, err := c.getPipelineRun(ctx, namespace, name)
switch {
case apierrors.IsNotFound(err):
// Do not have a pipeline
case err != nil:
return fmt.Errorf("get pipelinerun %s: %v", key, err)
case p.DeletionTimestamp == nil:
havePipelineRun = true
}
var newPipelineRun bool
switch {
case !wantPipelineRun:
if !havePipelineRun {
if pj != nil && pj.Spec.Agent == prowjobv1.TektonAgent {
logrus.Infof("Observed deleted: %s", key)
}
return nil
}
// Skip deleting if the pipeline run is not created by prow
switch v, ok := p.Labels[kube.CreatedByProw]; {
case !ok, v != "true":
return nil
}
logrus.Infof("Delete PipelineRun/%s", key)
if err = c.deletePipelineRun(ctx, namespace, name); err != nil {
return fmt.Errorf("delete pipelinerun: %v", err)
}
return nil
case finalState(pj.Status.State):
logrus.Infof("Observed finished: %s", key)
return nil
case wantPipelineRun && pj.Spec.PipelineRunSpec == nil:
return fmt.Errorf("nil PipelineRunSpec in ProwJob/%s", key)
case wantPipelineRun && !havePipelineRun:
id, url, err := c.pipelineID(*pj)
if err != nil {
return fmt.Errorf("failed to get pipeline id: %v", err)
}
pj.Status.BuildID = id
pj.Status.URL = url
newPipelineRun = true
pr := makePipelineGitResource(*pj)
logrus.Infof("Create PipelineResource/%s", key)
if pr, err = c.createPipelineResource(ctx, namespace, pr); err != nil {
return fmt.Errorf("create PipelineResource/%s: %v", key, err)
}
newp, err := makePipelineRun(*pj, pr)
if err != nil {
return fmt.Errorf("make PipelineRun/%s: %v", key, err)
}
logrus.Infof("Create PipelineRun/%s", key)
p, err = c.createPipelineRun(ctx, namespace, newp)
if err != nil {
jerr := fmt.Errorf("start pipeline: %v", err)
// Set the prow job in error state to avoid an endless loop when
// the pipeline cannot be executed (e.g. referenced pipeline does not exist)
return updateProwJobState(c, key, newPipelineRun, pj, prowjobv1.ErrorState, jerr.Error())
}
}
if p == nil {
return fmt.Errorf("no pipelinerun found or created for %q, wantPipelineRun was %v", key, wantPipelineRun)
}
wantState, wantMsg := prowJobStatus(p.Status)
return updateProwJobState(c, key, newPipelineRun, pj, wantState, wantMsg)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L953-L955
|
func (p *SetVariableValueParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetVariableValue, p, nil)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3012-L3021
|
func (u ManageOfferSuccessResultOffer) ArmForSwitch(sw int32) (string, bool) {
switch ManageOfferEffect(sw) {
case ManageOfferEffectManageOfferCreated:
return "Offer", true
case ManageOfferEffectManageOfferUpdated:
return "Offer", true
default:
return "", true
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gopherage/pkg/cov/junit/calculation/calculation.go#L25-L31
|
func ProduceCovList(profiles []*cover.Profile) *CoverageList {
covList := newCoverageList("summary")
for _, prof := range profiles {
covList.Group = append(covList.Group, summarizeBlocks(prof))
}
return covList
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3978-L3982
|
func (v GetAppManifestParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage43(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L746-L749
|
func (p SetBreakpointOnFunctionCallParams) WithCondition(condition string) *SetBreakpointOnFunctionCallParams {
p.Condition = condition
return &p
}
|
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L63-L72
|
func (pool *Pool) subworker(job *Job) {
defer func() {
if err := recover(); err != nil {
log.Println("panic while running job:", err)
job.Result = nil
job.Err = fmt.Errorf(err.(string))
}
}()
job.Result = job.F(job.Args...)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4488-L4497
|
func (u TransactionResultResult) GetResults() (result []OperationResult, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Code))
if armName == "Results" {
result = *u.Results
ok = true
}
return
}
|
https://github.com/fujiwara/fluent-agent-hydra/blob/f5c1c02a0b892cf5c08918ec2ff7bbca71cc7e4f/fluent/fluent.go#L66-L86
|
func New(config Config) (f *Fluent, err error) {
if config.Server == "" {
config.Server = defaultServer
}
if config.Timeout == 0 {
config.Timeout = defaultTimeout
}
if config.RetryWait == 0 {
config.RetryWait = defaultRetryWait
}
if config.MaxRetry == 0 {
config.MaxRetry = defaultMaxRetry
}
f = &Fluent{
Config: config,
reconnecting: false,
cancelReconnect: make(chan bool),
}
err = f.connect()
return
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L32-L40
|
func (e *Envelope) GetHeaderKeys() (headers []string) {
if e.header == nil {
return
}
for key := range *e.header {
headers = append(headers, key)
}
return headers
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L1408-L1429
|
func (v *VM) Suspend() error {
var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE
var err C.VixError = C.VIX_OK
jobHandle = C.VixVM_Suspend(v.handle,
0, // powerOptions,
nil, // callbackProc,
nil) // clientData
defer C.Vix_ReleaseHandle(jobHandle)
err = C.vix_job_wait(jobHandle)
if C.VIX_OK != err {
return &Error{
Operation: "vm.Suspend",
Code: int(err & 0xFFFF),
Text: C.GoString(C.Vix_GetErrorText(err, nil)),
}
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/membership/cluster.go#L155-L164
|
func (c *RaftCluster) PeerURLs() []string {
c.Lock()
defer c.Unlock()
urls := make([]string, 0)
for _, p := range c.members {
urls = append(urls, p.PeerURLs...)
}
sort.Strings(urls)
return urls
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/types.go#L118-L120
|
func (t *OrientationType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L5098-L5102
|
func (v EventSetChildNodes) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom57(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L123-L127
|
func (v RequestEntriesReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCachestorage(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/float_array.go#L10-L87
|
func (b *TupleBuilder) PutFloat32Array(field string, value []float32) (wrote int, err error) {
// field type should be
if err = b.typeCheck(field, Float32ArrayField); err != nil {
return 0, err
}
size := len(value)
if size < math.MaxUint8 {
if b.available() < size*4+2 {
return 0, xbinary.ErrOutOfRange
}
// write length
xbinary.LittleEndian.PutFloat32Array(b.buffer, b.pos+2, value)
// write type code
b.buffer[b.pos] = byte(FloatArray8Code.OpCode)
// write length
b.buffer[b.pos+1] = byte(size)
wrote += size + 2
} else if size < math.MaxUint16 {
if b.available() < size*4+3 {
return 0, xbinary.ErrOutOfRange
}
// write length
xbinary.LittleEndian.PutUint16(b.buffer, b.pos+1, uint16(size))
// write value
xbinary.LittleEndian.PutFloat32Array(b.buffer, b.pos+3, value)
// write type code
b.buffer[b.pos] = byte(FloatArray16Code.OpCode)
wrote += 3 + size
} else if size < math.MaxUint32 {
if b.available() < size*4+5 {
return 0, xbinary.ErrOutOfRange
}
// write length
xbinary.LittleEndian.PutUint32(b.buffer, b.pos+1, uint32(size))
// write value
xbinary.LittleEndian.PutFloat32Array(b.buffer, b.pos+5, value)
// write type code
b.buffer[b.pos] = byte(FloatArray32Code.OpCode)
wrote += 5 + size
} else {
if b.available() < size*4+9 {
return 0, xbinary.ErrOutOfRange
}
// write length
xbinary.LittleEndian.PutUint64(b.buffer, b.pos+1, uint64(size))
// write value
xbinary.LittleEndian.PutFloat32Array(b.buffer, b.pos+9, value)
// write type code
b.buffer[b.pos] = byte(FloatArray64Code.OpCode)
wrote += 9 + size
}
b.offsets[field] = b.pos
b.pos += wrote
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L1803-L1807
|
func (v *LayoutTreeNode) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomsnapshot7(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L269-L271
|
func (t *ConnectionType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/client.go#L315-L335
|
func (c *Client) Delete(ctx context.Context, endpoint string) (*Response, error) {
// If the sanitizer is enabled, make sure the requested path is safe.
if c.sanitizerEnabled {
err := isPathSafe(endpoint)
if err != nil {
return nil, err
}
}
tracer := c.newTracer()
return tracer.Done(c.RoundTrip(func() (*http.Response, error) {
req, err := http.NewRequest(http.MethodDelete, endpoint, nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
c.addAuth(req)
tracer.Start(req)
return c.client.Do(req)
}))
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L111-L140
|
func (r *InclusiveRange) End() int {
if r.isEndCached {
return r.cachedEnd
}
r.isEndCached = true
// If we aren't stepping, or we don't have
// a full range, then just use the end value
if r.step == 1 || r.step == -1 || r.start == r.end {
r.cachedEnd = r.end
return r.cachedEnd
}
// If the step is in the wrong direction,
// compared to the range direction, then
// just use the start as the end.
if (r.end < r.start) && r.step < (r.end-r.start) {
r.cachedEnd = r.start
return r.cachedEnd
} else if (r.end > r.start) && r.step > (r.end-r.start) {
r.cachedEnd = r.start
return r.cachedEnd
}
// Calculate the end, taking into account the stepping
r.cachedEnd = r.closestInRange(r.end, r.start, r.end, r.step)
return r.cachedEnd
}
|
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L410-L415
|
func (l *slog) Warnf(format string, args ...interface{}) {
lvl := l.Level()
if lvl <= LevelWarn {
l.b.printf("WRN", l.tag, format, args...)
}
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/task.go#L62-L77
|
func (m *Task) Validate(formats strfmt.Registry) error {
var res []error
if err := m.NewTask.Validate(formats); err != nil {
res = append(res, err)
}
if err := m.TaskAllOf1.Validate(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
|
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L451-L468
|
func (c *Consumer) cmLoop(stopped <-chan none) {
ticker := time.NewTicker(c.client.config.Consumer.Offsets.CommitInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := c.commitOffsetsWithRetry(c.client.config.Group.Offsets.Retry.Max); err != nil {
c.handleError(&Error{Ctx: "commit", error: err})
return
}
case <-stopped:
return
case <-c.dying:
return
}
}
}
|
https://github.com/qor/roles/blob/d6375609fe3e5da46ad3a574fae244fb633e79c1/global.go#L14-L16
|
func Allow(mode PermissionMode, roles ...string) *Permission {
return Global.Allow(mode, roles...)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/transform.go#L66-L95
|
func Dispatch(plugin plugins.Plugin, DB *InfluxDB, issues chan sql.Issue, eventsCommentsChannel chan interface{}) {
for {
var points []plugins.Point
select {
case issue, ok := <-issues:
if !ok {
return
}
points = plugin.ReceiveIssue(issue)
case event, ok := <-eventsCommentsChannel:
if !ok {
return
}
switch event := event.(type) {
case sql.IssueEvent:
points = plugin.ReceiveIssueEvent(event)
case sql.Comment:
points = plugin.ReceiveComment(event)
default:
glog.Fatal("Received invalid object: ", event)
}
}
for _, point := range points {
if err := DB.Push(point.Tags, point.Values, point.Date); err != nil {
glog.Fatal("Failed to push point: ", err)
}
}
}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/platform_strings.go#L139-L192
|
func (ps *PlatformStrings) MapSlice(f func([]string) ([]string, error)) (PlatformStrings, []error) {
var errors []error
mapSlice := func(ss []string) []string {
rs, err := f(ss)
if err != nil {
errors = append(errors, err)
return nil
}
return rs
}
mapStringMap := func(m map[string][]string) map[string][]string {
if m == nil {
return nil
}
rm := make(map[string][]string)
for k, ss := range m {
ss = mapSlice(ss)
if len(ss) > 0 {
rm[k] = ss
}
}
if len(rm) == 0 {
return nil
}
return rm
}
mapPlatformMap := func(m map[Platform][]string) map[Platform][]string {
if m == nil {
return nil
}
rm := make(map[Platform][]string)
for k, ss := range m {
ss = mapSlice(ss)
if len(ss) > 0 {
rm[k] = ss
}
}
if len(rm) == 0 {
return nil
}
return rm
}
result := PlatformStrings{
Generic: mapSlice(ps.Generic),
OS: mapStringMap(ps.OS),
Arch: mapStringMap(ps.Arch),
Platform: mapPlatformMap(ps.Platform),
}
return result, errors
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L111-L120
|
func Get(c context.Context, key string) (*Item, error) {
m, err := GetMulti(c, []string{key})
if err != nil {
return nil, err
}
if _, ok := m[key]; !ok {
return nil, ErrCacheMiss
}
return m[key], nil
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/path.go#L110-L147
|
func (pa Path) GoString() string {
var ssPre, ssPost []string
var numIndirect int
for i, s := range pa {
var nextStep PathStep
if i+1 < len(pa) {
nextStep = pa[i+1]
}
switch s := s.(type) {
case Indirect:
numIndirect++
pPre, pPost := "(", ")"
switch nextStep.(type) {
case Indirect:
continue // Next step is indirection, so let them batch up
case StructField:
numIndirect-- // Automatic indirection on struct fields
case nil:
pPre, pPost = "", "" // Last step; no need for parenthesis
}
if numIndirect > 0 {
ssPre = append(ssPre, pPre+strings.Repeat("*", numIndirect))
ssPost = append(ssPost, pPost)
}
numIndirect = 0
continue
case Transform:
ssPre = append(ssPre, s.trans.name+"(")
ssPost = append(ssPost, ")")
continue
}
ssPost = append(ssPost, s.String())
}
for i, j := 0, len(ssPre)-1; i < j; i, j = i+1, j-1 {
ssPre[i], ssPre[j] = ssPre[j], ssPre[i]
}
return strings.Join(ssPre, "") + strings.Join(ssPost, "")
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/httputil/response.go#L40-L50
|
func httpResponseStruct(v reflect.Value) reflect.Value {
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Type().String() == "http.response" {
return v
}
return httpResponseStruct(v.FieldByName("ResponseWriter").Elem())
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L7518-L7522
|
func (v AddScriptToEvaluateOnNewDocumentReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage83(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L443-L447
|
func (cdc *Codec) MustUnmarshalJSON(bz []byte, ptr interface{}) {
if err := cdc.UnmarshalJSON(bz, ptr); err != nil {
panic(err)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.