_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/filter.go#L36-L40
|
func CommandFilter(body string) Filter {
return func(p config.Presubmit) (bool, bool, bool) {
return p.TriggerMatches(body), p.TriggerMatches(body), true
}
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L251-L272
|
func TemplateWithDelimiters(s string, values map[string]interface{}, opening, closing string) string {
escapeDelimiter := func(delim string) string {
result := templateRe.ReplaceAllString(delim, "\\$1")
return templateRe2.ReplaceAllString(result, "\\$")
}
openingDelim := escapeDelimiter(opening)
closingDelim := escapeDelimiter(closing)
r := regexp.MustCompile(openingDelim + `(.+?)` + closingDelim)
matches := r.FindAllStringSubmatch(s, -1)
for _, submatches := range matches {
match := submatches[0]
key := submatches[1]
//log.Printf("match %s key %s\n", match, key)
if values[key] != nil {
v := fmt.Sprintf("%v", values[key])
s = strings.Replace(s, match, v, -1)
}
}
return s
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L87-L90
|
func (e CryptoKeyType) ValidEnum(v int32) bool {
_, ok := cryptoKeyTypeMap[v]
return ok
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/errors.go#L102-L126
|
func (c SystemErrCode) MetricsKey() string {
switch c {
case ErrCodeInvalid:
// Shouldn't ever need this.
return "invalid"
case ErrCodeTimeout:
return "timeout"
case ErrCodeCancelled:
return "cancelled"
case ErrCodeBusy:
return "busy"
case ErrCodeDeclined:
return "declined"
case ErrCodeUnexpected:
return "unexpected-error"
case ErrCodeBadRequest:
return "bad-request"
case ErrCodeNetwork:
return "network-error"
case ErrCodeProtocol:
return "protocol-error"
default:
return c.String()
}
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L205-L218
|
func (p *Pact) setupLogging() {
if p.logFilter == nil {
if p.LogLevel == "" {
p.LogLevel = "INFO"
}
p.logFilter = &logutils.LevelFilter{
Levels: []logutils.LogLevel{"DEBUG", "INFO", "WARN", "ERROR"},
MinLevel: logutils.LogLevel(p.LogLevel),
Writer: os.Stderr,
}
log.SetOutput(p.logFilter)
}
log.Println("[DEBUG] pact setup logging")
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/version/api_server.go#L45-L47
|
func String(v *pb.Version) string {
return fmt.Sprintf("%d.%d.%d%s", v.Major, v.Minor, v.Micro, v.Additional)
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/config.go#L111-L116
|
func (gc *goConfig) preprocessTags() {
if gc.genericTags == nil {
gc.genericTags = make(map[string]bool)
}
gc.genericTags["gc"] = true
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L1534-L1548
|
func (r *raft) increaseUncommittedSize(ents []pb.Entry) bool {
var s uint64
for _, e := range ents {
s += uint64(PayloadSize(e))
}
if r.uncommittedSize > 0 && r.uncommittedSize+s > r.maxUncommittedSize {
// If the uncommitted tail of the Raft log is empty, allow any size
// proposal. Otherwise, limit the size of the uncommitted tail of the
// log and drop any proposal that would push the size over the limit.
return false
}
r.uncommittedSize += s
return true
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/node.go#L87-L91
|
func (n *node) IsHidden() bool {
_, name := path.Split(n.Path)
return name[0] == '_'
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/update.go#L18-L53
|
func DotGo(updates map[int]Update, name string) error {
// Apply all the updates that we have on a pristine database and dump
// the resulting schema.
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
return fmt.Errorf("failed to open schema.go for writing: %v", err)
}
schema := NewFromMap(updates)
_, err = schema.Ensure(db)
if err != nil {
return err
}
dump, err := schema.Dump(db)
if err != nil {
return err
}
// Passing 1 to runtime.Caller identifies our caller.
_, filename, _, _ := runtime.Caller(1)
file, err := os.Create(path.Join(path.Dir(filename), name+".go"))
if err != nil {
return fmt.Errorf("failed to open Go file for writing: %v", err)
}
pkg := path.Base(path.Dir(filename))
_, err = file.Write([]byte(fmt.Sprintf(dotGoTemplate, pkg, dump)))
if err != nil {
return fmt.Errorf("failed to write to Go file: %v", err)
}
return nil
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/boundary.go#L86-L124
|
func (b *boundaryReader) Next() (bool, error) {
if b.finished {
return false, nil
}
if b.partsRead > 0 {
// Exhaust the current part to prevent errors when moving to the next part
_, _ = io.Copy(ioutil.Discard, b)
}
for {
line, err := b.r.ReadSlice('\n')
if err != nil && err != io.EOF {
return false, errors.WithStack(err)
}
if len(line) > 0 && (line[0] == '\r' || line[0] == '\n') {
// Blank line
continue
}
if b.isTerminator(line) {
b.finished = true
return false, nil
}
if err != io.EOF && b.isDelimiter(line) {
// Start of a new part
b.partsRead++
return true, nil
}
if err == io.EOF {
// Intentionally not wrapping with stack
return false, io.EOF
}
if b.partsRead == 0 {
// The first part didn't find the starting delimiter, burn off any preamble in front of
// the boundary
continue
}
b.finished = true
return false, errors.Errorf("expecting boundary %q, got %q", string(b.prefix), string(line))
}
}
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/inspect.go#L27-L52
|
func (s *Seekret) Inspect(Nworkers int) {
jobs := make(chan workerJob)
results := make(chan workerResult)
for w := 1; w <= Nworkers; w++ {
go inspect_worker(w, jobs, results)
}
objectGroupMap := s.GroupObjectsByPrimaryKeyHash()
go func() {
for _, objectGroup := range objectGroupMap {
jobs <- workerJob{
objectGroup: objectGroup,
ruleList: s.ruleList,
exceptionList: s.exceptionList,
}
}
close(jobs)
}()
for i := 0; i < len(objectGroupMap); i++ {
result := <-results
s.secretList = append(s.secretList, result.secretList...)
}
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L57-L59
|
func (s *Stack) Extend(extendBy int) {
s.Resize(s.Size() + extendBy)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/client/client.go#L302-L304
|
func (c *Client) Reset(rtype, state string, expire time.Duration, dest string) (map[string]string, error) {
return c.reset(rtype, state, expire, dest)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/tide.go#L259-L265
|
func newExpectedContext(c string) Context {
return Context{
Context: githubql.String(c),
State: githubql.StatusStateExpected,
Description: githubql.String(""),
}
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/middleware.go#L53-L72
|
func adapterFunc(handler HandlerFunc) http.HandlerFunc {
return func(origWriter http.ResponseWriter, origRequest *http.Request) {
// instantiate the rest objects
request := &Request{
origRequest,
nil,
map[string]interface{}{},
}
writer := &responseWriter{
origWriter,
false,
}
// call the wrapped handler
handler(writer, request)
}
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L95-L328
|
func (a *APIAnalyzer) AnalyzeResource(name string, resource interface{}, descriptor *gen.APIDescriptor) {
var res = resource.(map[string]interface{})
// Compute description
var description string
if d, ok := res["description"].(string); ok {
description = d
}
// Compute attributes, mediatype identifier, and links
var attributes []*gen.Attribute
var identifier string
var atts map[string]interface{}
var links map[string]string
if m, ok := res["media_type"].(map[string]interface{}); ok {
// Compute attributes
atts = m["attributes"].(map[string]interface{})
attributes = make([]*gen.Attribute, len(atts))
for idx, n := range sortedKeys(atts) {
at, ok := a.attributeTypes[n+"#"+name]
if !ok {
at = a.attributeTypes[n]
}
attributes[idx] = &gen.Attribute{n, inflect.Camelize(n), at}
}
// Compute mediatype identifier
contentTypes := m["content_types"].([]interface{})
if len(contentTypes) > 0 {
identifier = contentTypes[0].(string)
}
// Compute links
if l, ok := m["links"].(map[string]interface{}); ok {
links = make(map[string]string, len(l))
for n, d := range l {
links[n] = d.(string)
}
}
} else {
attributes = []*gen.Attribute{}
}
// Compute actions
var methods = res["methods"].(map[string]interface{})
var actionNames = sortedKeys(methods)
var actions = []*gen.Action{}
for _, actionName := range actionNames {
var m = methods[actionName]
var meth = m.(map[string]interface{})
var params map[string]interface{}
if p, ok := meth["parameters"]; ok {
params = p.(map[string]interface{})
}
var description = "No description provided for " + actionName + "."
if d, _ := meth["description"]; d != nil {
description = d.(string)
}
var routes = meth["routes"].([]interface{})
var strRoutes = make([]string, len(routes))
for i, r := range routes {
strRoutes[i] = r.(string)
}
var pathPatterns = ParseRoute(fmt.Sprintf("%s#%s", name, actionName), strRoutes)
if len(pathPatterns) == 0 {
// Custom action
continue
}
// HACK: /api/right_scripts/:id/update_source is a unique snowflake. It has no
// params, it accepts the script body as a text/plain type type!. We inject a
// fake param here that acts as a multipart file upload does.
if name == "RightScripts" && actionName == "update_source" {
params["filename"] = map[string]interface{}{
"class": "SourceUpload",
"mandatory": true,
"non_blank": true,
"description": "The file name to update the RightScript source with.",
}
}
var allParamNames = make([]string, len(params))
var i = 0
for n := range params {
allParamNames[i] = n
i++
}
sort.Strings(allParamNames)
var contentType string
if c, ok := meth["content_type"].(string); ok {
contentType = c
}
var paramAnalyzer = NewAnalyzer(params)
paramAnalyzer.Analyze()
// Record new parameter types
var paramTypeNames = make([]string, len(paramAnalyzer.ParamTypes))
var idx = 0
for n := range paramAnalyzer.ParamTypes {
paramTypeNames[idx] = n
idx++
}
sort.Strings(paramTypeNames)
for _, name := range paramTypeNames {
var pType = paramAnalyzer.ParamTypes[name]
if _, ok := a.rawTypes[name]; ok {
a.rawTypes[name] = append(a.rawTypes[name], pType)
} else {
a.rawTypes[name] = []*gen.ObjectDataType{pType}
}
}
// Update description with parameter descriptions
var mandatory []string
var optional []string
for _, p := range paramAnalyzer.Params {
if p.Mandatory {
desc := p.Name
if p.Description != "" {
desc += ": " + strings.TrimSpace(p.Description)
}
mandatory = append(mandatory, desc)
} else {
desc := p.Name
if p.Description != "" {
desc += ": " + strings.TrimSpace(p.Description)
}
optional = append(optional, desc)
}
}
if len(mandatory) > 0 {
sort.Strings(mandatory)
if !strings.HasSuffix(description, "\n") {
description += "\n"
}
description += "Required parameters:\n\t" + strings.Join(mandatory, "\n\t")
}
if len(optional) > 0 {
sort.Strings(optional)
if !strings.HasSuffix(description, "\n") {
description += "\n"
}
description += "Optional parameters:\n\t" + strings.Join(optional, "\n\t")
}
// Sort parameters by location
actionParams := paramAnalyzer.Params
leafParams := paramAnalyzer.LeafParams
var pathParamNames []string
var queryParamNames []string
var payloadParamNames []string
for _, p := range leafParams {
n := p.Name
if isQueryParam(actionName, n) {
queryParamNames = append(queryParamNames, n)
p.Location = gen.QueryParam
} else if isPathParam(n, pathPatterns) {
pathParamNames = append(pathParamNames, n)
p.Location = gen.PathParam
} else {
payloadParamNames = append(payloadParamNames, n)
p.Location = gen.PayloadParam
}
}
for _, p := range actionParams {
done := false
for _, ap := range leafParams {
if ap == p {
done = true
break
}
}
if done {
continue
}
n := p.Name
if isQueryParam(actionName, n) {
p.Location = gen.QueryParam
} else if isPathParam(n, pathPatterns) {
p.Location = gen.PathParam
} else {
p.Location = gen.PayloadParam
}
}
// Mix in filters information
if filters, ok := meth["filters"]; ok {
var filterParam *gen.ActionParam
for _, p := range actionParams {
if p.Name == "filter" {
filterParam = p
break
}
}
if filterParam != nil {
values := sortedKeys(filters.(map[string]interface{}))
ivalues := make([]interface{}, len(values))
for i, v := range values {
ivalues[i] = v
}
filterParam.ValidValues = ivalues
}
}
// Record action
action := gen.Action{
Name: actionName,
MethodName: inflect.Camelize(actionName),
Description: removeBlankLines(description),
ResourceName: inflect.Singularize(name),
PathPatterns: pathPatterns,
Params: actionParams,
LeafParams: paramAnalyzer.LeafParams,
Return: parseReturn(actionName, name, contentType),
ReturnLocation: actionName == "create" && name != "Oauth2",
PathParamNames: pathParamNames,
QueryParamNames: queryParamNames,
PayloadParamNames: payloadParamNames,
}
actions = append(actions, &action)
}
// We're done!
name = inflect.Singularize(name)
descriptor.Resources[name] = &gen.Resource{
Name: name,
ClientName: "API",
Description: removeBlankLines(description),
Actions: actions,
Attributes: attributes,
LocatorFunc: LocatorFunc(attributes, name),
Identifier: identifier,
Links: links,
}
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/iterator.go#L59-L61
|
func (item *Item) String() string {
return fmt.Sprintf("key=%q, version=%d, meta=%x", item.Key(), item.Version(), item.meta)
}
|
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/options/dag.go#L47-L52
|
func (dagOpts) InputEnc(enc string) DagPutOption {
return func(opts *DagPutSettings) error {
opts.InputEnc = enc
return nil
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L796-L814
|
func (t *SignedExchangeErrorField) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch SignedExchangeErrorField(in.String()) {
case SignedExchangeErrorFieldSignatureSig:
*t = SignedExchangeErrorFieldSignatureSig
case SignedExchangeErrorFieldSignatureIntegrity:
*t = SignedExchangeErrorFieldSignatureIntegrity
case SignedExchangeErrorFieldSignatureCertURL:
*t = SignedExchangeErrorFieldSignatureCertURL
case SignedExchangeErrorFieldSignatureCertSha256:
*t = SignedExchangeErrorFieldSignatureCertSha256
case SignedExchangeErrorFieldSignatureValidityURL:
*t = SignedExchangeErrorFieldSignatureValidityURL
case SignedExchangeErrorFieldSignatureTimestamps:
*t = SignedExchangeErrorFieldSignatureTimestamps
default:
in.AddError(errors.New("unknown SignedExchangeErrorField value"))
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L24-L39
|
func (m *Mapping) NaturalKey() []*Field {
key := []*Field{}
for _, field := range m.Fields {
if field.Config.Get("primary") != "" {
key = append(key, field)
}
}
if len(key) == 0 {
// Default primary key.
key = append(key, m.FieldByName("Name"))
}
return key
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1097-L1100
|
func (app *App) GetTeams() []authTypes.Team {
t, _ := servicemanager.Team.FindByNames(app.Teams)
return t
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_text.go#L348-L378
|
func (s diffStats) String() string {
var ss []string
var sum int
labels := [...]string{"ignored", "identical", "removed", "inserted", "modified"}
counts := [...]int{s.NumIgnored, s.NumIdentical, s.NumRemoved, s.NumInserted, s.NumModified}
for i, n := range counts {
if n > 0 {
ss = append(ss, fmt.Sprintf("%d %v", n, labels[i]))
}
sum += n
}
// Pluralize the name (adjusting for some obscure English grammar rules).
name := s.Name
if sum > 1 {
name = name + "s"
if strings.HasSuffix(name, "ys") {
name = name[:len(name)-2] + "ies" // e.g., "entrys" => "entries"
}
}
// Format the list according to English grammar (with Oxford comma).
switch n := len(ss); n {
case 0:
return ""
case 1, 2:
return strings.Join(ss, " and ") + " " + name
default:
return strings.Join(ss[:n-1], ", ") + ", and " + ss[n-1] + " " + name
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/op.go#L293-L295
|
func OpTxn(cmps []Cmp, thenOps []Op, elseOps []Op) Op {
return Op{t: tTxn, cmps: cmps, thenOps: thenOps, elseOps: elseOps}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/pkg/io/opener.go#L77-L81
|
func LogClose(c io.Closer) {
if err := c.Close(); err != nil {
logrus.WithError(err).Error("Failed to close")
}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/label/label.go#L177-L186
|
func (l Label) Contains(other Label) bool {
if l.Relative {
log.Panicf("l must not be relative: %s", l)
}
if other.Relative {
log.Panicf("other must not be relative: %s", other)
}
result := l.Repo == other.Repo && pathtools.HasPrefix(other.Pkg, l.Pkg)
return result
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/generators/record.go#L23-L37
|
func (v *Record) TypeName(i int, properties []string) (typename string) {
if i+1 < v.Length {
currentNode := v.Slice[i]
typename = "*" + FormatName(currentNode)
if i >= 1 {
parentNames := v.FindAllParentsOfSameNamedElement(currentNode, properties)
if len(parentNames) > 1 {
typename = "*" + FormatName(v.Slice[i-1]+"_"+currentNode)
}
}
} else {
typename = "interface{}"
}
return
}
|
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L68-L70
|
func (now *Now) EndOfHour() time.Time {
return now.BeginningOfHour().Add(time.Hour - time.Nanosecond)
}
|
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L530-L541
|
func (p *PubSub) notifySubs(msg *pb.Message) {
for _, topic := range msg.GetTopicIDs() {
subs := p.myTopics[topic]
for f := range subs {
select {
case f.ch <- &Message{msg}:
default:
log.Infof("Can't deliver message to subscription for topic %s; subscriber too slow", topic)
}
}
}
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/dominator.go#L121-L176
|
func (d *ltDom) initialize() {
type workItem struct {
name vName
parentName vName
}
// Initialize objs for mapping from object index back to Object.
i := 0
d.p.ForEachObject(func(x Object) bool {
d.objs[i] = x
i++
return true
})
// Add roots to the work stack, essentially pretending to visit
// the pseudo-root, numbering it 0.
d.semis[pseudoRoot] = 0
d.parents[pseudoRoot] = -1
d.vertices[0] = pseudoRoot
var work []workItem
for i := 1; i < 1+d.nRoots; i++ {
work = append(work, workItem{name: vName(i), parentName: 0})
}
n := vNumber(1) // 0 was the pseudo-root.
// Build the spanning tree, assigning vertex numbers to each object
// and initializing semi and parent.
for len(work) != 0 {
item := work[len(work)-1]
work = work[:len(work)-1]
if d.semis[item.name] != -1 {
continue
}
d.semis[item.name] = n
d.parents[item.name] = item.parentName
d.vertices[n] = item.name
n++
visitChild := func(_ int64, child Object, _ int64) bool {
childIdx, _ := d.p.findObjectIndex(d.p.Addr(child))
work = append(work, workItem{name: vName(childIdx + d.nRoots + 1), parentName: item.name})
return true
}
root, object := d.findVertexByName(item.name)
if root != nil {
d.p.ForEachRootPtr(root, visitChild)
} else {
d.p.ForEachPtr(object, visitChild)
}
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L227-L231
|
func (w *WriteBuffer) WriteUint32(n uint32) {
if b := w.reserve(4); b != nil {
binary.BigEndian.PutUint32(b, n)
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L59-L62
|
func (p AttachToTargetParams) WithFlatten(flatten bool) *AttachToTargetParams {
p.Flatten = flatten
return &p
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/leasing/txn.go#L93-L105
|
func (txn *txnLeasing) fallback(ops []v3.Op) (fbOps []v3.Op) {
for _, op := range ops {
if op.IsGet() {
continue
}
lkey, lend := txn.lkv.pfx+string(op.KeyBytes()), ""
if len(op.RangeBytes()) > 0 {
lend = txn.lkv.pfx + string(op.RangeBytes())
}
fbOps = append(fbOps, v3.OpGet(lkey, v3.WithRange(lend)))
}
return fbOps
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/peer.go#L30-L41
|
func newPeer(self mesh.PeerName, logger *log.Logger) *peer {
actions := make(chan func())
p := &peer{
st: newState(self),
send: nil, // must .register() later
actions: actions,
quit: make(chan struct{}),
logger: logger,
}
go p.loop(actions)
return p
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L440-L442
|
func (f *FakeClient) GetRepoProjects(owner, repo string) ([]github.Project, error) {
return f.RepoProjects[fmt.Sprintf("%s/%s", owner, repo)], nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L336-L353
|
func (o *ObjectDataType) IsEquivalent(other DataType) bool {
a, ok := other.(*ObjectDataType)
if !ok {
return false
}
if o.TypeName != a.TypeName {
return false
}
if len(o.Fields) != len(a.Fields) {
return false
}
for i, f := range o.Fields {
if !f.IsEquivalent(a.Fields[i]) {
return false
}
}
return true
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/database/easyjson.go#L428-L432
|
func (v *ExecuteSQLParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDatabase3(&r, v)
return r.Error()
}
|
https://github.com/tehnerd/gnl2go/blob/101b5c6e2d44eb00fbfe85917ffc0bf95249977b/gnl2go.go#L585-L593
|
func CreateMsgType(alist []AttrListTuple, familyId uint16) MessageType {
if v, exists := Family2MT[familyId]; exists {
return *v
}
var mt MessageType
mt.InitMessageType(alist, familyId)
Family2MT[familyId] = &mt
return mt
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L316-L319
|
func isMain(f *ast.FuncDecl) bool {
ft := f.Type
return f.Name.Name == "main" && f.Recv == nil && ft.Params.NumFields() == 0 && ft.Results.NumFields() == 0
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/get_apps_app_routes_route_responses.go#L25-L52
|
func (o *GetAppsAppRoutesRouteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewGetAppsAppRoutesRouteOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 404:
result := NewGetAppsAppRoutesRouteNotFound()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
result := NewGetAppsAppRoutesRouteDefault(response.Code())
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
if response.Code()/100 == 2 {
return result, nil
}
return nil, result
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L99-L108
|
func (p *EnableParams) Do(ctx context.Context) (debuggerID runtime.UniqueDebuggerID, err error) {
// execute
var res EnableReturns
err = cdp.Execute(ctx, CommandEnable, p, &res)
if err != nil {
return "", err
}
return res.DebuggerID, nil
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L197-L208
|
func New(options ...Option) (s *Service) {
s = &Service{
logger: stdLogger{},
}
for _, option := range options {
option(s)
}
if s.store == nil {
s.store = NewMemoryStore()
}
return
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/watch.go#L382-L415
|
func (w *watcher) RequestProgress(ctx context.Context) (err error) {
ctxKey := streamKeyFromCtx(ctx)
w.mu.Lock()
if w.streams == nil {
return fmt.Errorf("no stream found for context")
}
wgs := w.streams[ctxKey]
if wgs == nil {
wgs = w.newWatcherGrpcStream(ctx)
w.streams[ctxKey] = wgs
}
donec := wgs.donec
reqc := wgs.reqc
w.mu.Unlock()
pr := &progressRequest{}
select {
case reqc <- pr:
return nil
case <-ctx.Done():
if err == nil {
return ctx.Err()
}
return err
case <-donec:
if wgs.closeErr != nil {
return wgs.closeErr
}
// retry; may have dropped stream from no ctxs
return w.RequestProgress(ctx)
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_transport.go#L149-L151
|
func (ref dirReference) NewImageSource(ctx context.Context, sys *types.SystemContext) (types.ImageSource, error) {
return newImageSource(ref), nil
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L213-L224
|
func Humanize(s string) string {
if s == "" {
return s
}
s = Underscore(s)
var humanizeRe = regexp.MustCompile(`_id$`)
s = humanizeRe.ReplaceAllString(s, "")
s = strings.Replace(s, "_", " ", -1)
s = strings.TrimSpace(s)
s = Capitalize(s)
return s
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/ash/enforcer.go#L52-L59
|
func AddFilter(filter bson.M) *Enforcer {
return E("ash/AddFilter", fire.Except(fire.Create, fire.CollectionAction), func(ctx *fire.Context) error {
// assign specified filter
ctx.Filters = append(ctx.Filters, filter)
return nil
})
}
|
https://github.com/go-audio/transforms/blob/51830ccc35a5ce4be9d09b1d1f3f82dad376c240/mono.go#L7-L30
|
func MonoDownmix(buf *audio.FloatBuffer) error {
if buf == nil || buf.Format == nil {
return audio.ErrInvalidBuffer
}
nChans := buf.Format.NumChannels
if nChans < 2 {
return nil
}
nChansF := float64(nChans)
frameCount := buf.NumFrames()
newData := make([]float64, frameCount)
for i := 0; i < frameCount; i++ {
newData[i] = 0
for j := 0; j < nChans; j++ {
newData[i] += buf.Data[i*nChans+j]
}
newData[i] /= nChansF
}
buf.Data = newData
buf.Format.NumChannels = 1
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L358-L367
|
func (p *GetWindowForTargetParams) Do(ctx context.Context) (windowID WindowID, bounds *Bounds, err error) {
// execute
var res GetWindowForTargetReturns
err = cdp.Execute(ctx, CommandGetWindowForTarget, p, &res)
if err != nil {
return 0, nil, err
}
return res.WindowID, res.Bounds, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L1041-L1076
|
func setCName(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
cNameMsg := "You must provide the cname."
cnames, _ := InputValues(r, "cname")
if len(cnames) == 0 {
return &errors.HTTP{Code: http.StatusBadRequest, Message: cNameMsg}
}
appName := r.URL.Query().Get(":app")
a, err := getAppFromContext(appName, r)
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermAppUpdateCnameAdd,
contextsForApp(&a)...,
)
if !allowed {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: appTarget(appName),
Kind: permission.PermAppUpdateCnameAdd,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(&a)...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
if err = a.AddCName(cnames...); err == nil {
return nil
}
if err.Error() == "Invalid cname" {
return &errors.HTTP{Code: http.StatusBadRequest, Message: err.Error()}
}
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L175-L180
|
func (in *ProwJobList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/cache.go#L51-L53
|
func (c *MergeCache) Put(id int64, tree io.Reader) (retErr error) {
return c.Cache.Put(fmt.Sprint(id), tree)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L397-L400
|
func (p GetContentQuadsParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *GetContentQuadsParams {
p.BackendNodeID = backendNodeID
return &p
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L83-L86
|
func RegisterPullRequestHandler(name string, fn PullRequestHandler, help HelpProvider) {
pluginHelp[name] = help
pullRequestHandlers[name] = fn
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L1625-L1629
|
func (v *SetStyleSheetTextParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss14(&r, v)
return r.Error()
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/plan.go#L102-L127
|
func removePlan(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
allowed := permission.Check(t, permission.PermPlanDelete)
if !allowed {
return permission.ErrUnauthorized
}
planName := r.URL.Query().Get(":planname")
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypePlan, Value: planName},
Kind: permission.PermPlanDelete,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermPlanReadEvents),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
err = servicemanager.Plan.Remove(planName)
if err == appTypes.ErrPlanNotFound {
return &errors.HTTP{
Code: http.StatusNotFound,
Message: err.Error(),
}
}
return err
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/api_server.go#L138-L140
|
func (a *apiServer) LogReq(request interface{}) {
a.pachLogger.Log(request, nil, nil, 0)
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L249-L251
|
func (router *Router) Gossip() GossipData {
return &topologyGossipData{peers: router.Peers, update: router.Peers.names()}
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L453-L464
|
func (g *Glg) EnableColor() *Glg {
g.logger.Range(func(key, val interface{}) bool {
l := val.(*logger)
l.isColor = true
l.updateMode()
g.logger.Store(key.(LEVEL), l)
return true
})
return g
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/api.go#L666-L676
|
func (r *Raft) VerifyLeader() Future {
metrics.IncrCounter([]string{"raft", "verify_leader"}, 1)
verifyFuture := &verifyFuture{}
verifyFuture.init()
select {
case <-r.shutdownCh:
return errorFuture{ErrRaftShutdown}
case r.verifyCh <- verifyFuture:
return verifyFuture
}
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L221-L223
|
func (api *API) AnalysisSnapshotLocator(href string) *AnalysisSnapshotLocator {
return &AnalysisSnapshotLocator{Href(href), api}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/config.go#L12-L14
|
func (n *NodeTx) UpdateConfig(values map[string]string) error {
return query.UpdateConfig(n.tx, "config", values)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/pretty/pretty.go#L97-L110
|
func PrintWorkerStatus(w io.Writer, workerStatus *ppsclient.WorkerStatus, fullTimestamps bool) {
fmt.Fprintf(w, "%s\t", workerStatus.WorkerID)
fmt.Fprintf(w, "%s\t", workerStatus.JobID)
for _, datum := range workerStatus.Data {
fmt.Fprintf(w, datum.Path)
}
fmt.Fprintf(w, "\t")
if fullTimestamps {
fmt.Fprintf(w, "%s\t", workerStatus.Started.String())
} else {
fmt.Fprintf(w, "%s\t", pretty.Ago(workerStatus.Started))
}
fmt.Fprintf(w, "%d\t\n", workerStatus.QueueSize)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L140-L143
|
func (p CallFunctionOnParams) WithUserGesture(userGesture bool) *CallFunctionOnParams {
p.UserGesture = userGesture
return &p
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/dco/dco.go#L273-L293
|
func MarkdownSHAList(org, repo string, list []github.GitCommit) string {
lines := make([]string, len(list))
lineFmt := "- [%s](https://github.com/%s/%s/commits/%s) %s"
for i, commit := range list {
if commit.SHA == "" {
continue
}
// if we somehow encounter a SHA that's less than 7 characters, we will
// just use it as is.
shortSHA := commit.SHA
if len(shortSHA) > 7 {
shortSHA = shortSHA[:7]
}
// get the first line of the commit
message := strings.Split(commit.Message, "\n")[0]
lines[i] = fmt.Sprintf(lineFmt, shortSHA, org, repo, commit.SHA, message)
}
return strings.Join(lines, "\n")
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L922-L1058
|
func cephContainerDelete(clusterName string, poolName string, volumeName string,
volumeType string, userName string) int {
logEntry := fmt.Sprintf("%s/%s_%s", poolName, volumeType, volumeName)
snaps, err := cephRBDVolumeListSnapshots(clusterName, poolName,
volumeName, volumeType, userName)
if err == nil {
var zombies int
for _, snap := range snaps {
logEntry := fmt.Sprintf("%s/%s_%s@%s", poolName,
volumeType, volumeName, snap)
ret := cephContainerSnapshotDelete(clusterName,
poolName, volumeName, volumeType, snap, userName)
if ret < 0 {
logger.Errorf(`Failed to delete RBD storage volume "%s"`, logEntry)
return -1
} else if ret == 1 {
logger.Debugf(`Marked RBD storage volume "%s" as zombie`, logEntry)
zombies++
} else {
logger.Debugf(`Deleted RBD storage volume "%s"`, logEntry)
}
}
if zombies > 0 {
// unmap
err = cephRBDVolumeUnmap(clusterName, poolName,
volumeName, volumeType, userName, true)
if err != nil {
logger.Errorf(`Failed to unmap RBD storage volume "%s": %s`, logEntry, err)
return -1
}
logger.Debugf(`Unmapped RBD storage volume "%s"`, logEntry)
if strings.HasPrefix(volumeType, "zombie_") {
logger.Debugf(`RBD storage volume "%s" already marked as zombie`, logEntry)
return 1
}
newVolumeName := fmt.Sprintf("%s_%s", volumeName,
uuid.NewRandom().String())
err := cephRBDVolumeMarkDeleted(clusterName, poolName,
volumeType, volumeName, newVolumeName, userName,
"")
if err != nil {
logger.Errorf(`Failed to mark RBD storage volume "%s" as zombie: %s`, logEntry, err)
return -1
}
logger.Debugf(`Marked RBD storage volume "%s" as zombie`, logEntry)
return 1
}
} else {
if err != db.ErrNoSuchObject {
logger.Errorf(`Failed to retrieve snapshots of RBD storage volume: %s`, err)
return -1
}
parent, err := cephRBDVolumeGetParent(clusterName, poolName,
volumeName, volumeType, userName)
if err == nil {
logger.Debugf(`Detected "%s" as parent of RBD storage volume "%s"`, parent, logEntry)
_, parentVolumeType, parentVolumeName,
parentSnapshotName, err := parseParent(parent)
if err != nil {
logger.Errorf(`Failed to parse parent "%s" of RBD storage volume "%s"`, parent, logEntry)
return -1
}
logger.Debugf(`Split parent "%s" of RBD storage volume "%s" into volume type "%s", volume name "%s", and snapshot name "%s"`, parent, logEntry, parentVolumeType,
parentVolumeName, parentSnapshotName)
// unmap
err = cephRBDVolumeUnmap(clusterName, poolName,
volumeName, volumeType, userName, true)
if err != nil {
logger.Errorf(`Failed to unmap RBD storage volume "%s": %s`, logEntry, err)
return -1
}
logger.Debugf(`Unmapped RBD storage volume "%s"`, logEntry)
// delete
err = cephRBDVolumeDelete(clusterName, poolName,
volumeName, volumeType, userName)
if err != nil {
logger.Errorf(`Failed to delete RBD storage volume "%s": %s`, logEntry, err)
return -1
}
logger.Debugf(`Deleted RBD storage volume "%s"`, logEntry)
// Only delete the parent snapshot of the container if
// it is a zombie. If it is not we know that LXD is
// still using it.
if strings.HasPrefix(parentVolumeType, "zombie_") ||
strings.HasPrefix(parentSnapshotName, "zombie_") {
ret := cephContainerSnapshotDelete(clusterName,
poolName, parentVolumeName,
parentVolumeType, parentSnapshotName,
userName)
if ret < 0 {
logger.Errorf(`Failed to delete snapshot "%s" of RBD storage volume "%s"`, parentSnapshotName, logEntry)
return -1
}
logger.Debugf(`Deleteed snapshot "%s" of RBD storage volume "%s"`, parentSnapshotName, logEntry)
}
return 0
} else {
if err != db.ErrNoSuchObject {
logger.Errorf(`Failed to retrieve parent of RBD storage volume "%s"`, logEntry)
return -1
}
logger.Debugf(`RBD storage volume "%s" does not have parent`, logEntry)
// unmap
err = cephRBDVolumeUnmap(clusterName, poolName,
volumeName, volumeType, userName, true)
if err != nil {
logger.Errorf(`Failed to unmap RBD storage volume "%s": %s`, logEntry, err)
return -1
}
logger.Debugf(`Unmapped RBD storage volume "%s"`, logEntry)
// delete
err = cephRBDVolumeDelete(clusterName, poolName,
volumeName, volumeType, userName)
if err != nil {
logger.Errorf(`Failed to delete RBD storage volume "%s": %s`, logEntry, err)
return -1
}
logger.Debugf(`Deleted RBD storage volume "%s"`, logEntry)
}
}
return 0
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/count.go#L44-L60
|
func CountAll(tx *sql.Tx) (map[string]int, error) {
tables, err := SelectStrings(tx, "SELECT name FROM sqlite_master WHERE type = 'table'")
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch table names")
}
counts := map[string]int{}
for _, table := range tables {
count, err := Count(tx, table, "")
if err != nil {
return nil, errors.Wrapf(err, "Failed to count rows of %s", table)
}
counts[table] = count
}
return counts, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/pfs.go#L148-L153
|
func IsBranchNotFoundErr(err error) bool {
if err == nil {
return false
}
return branchNotFoundRe.MatchString(err.Error())
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L6447-L6451
|
func (v ComputedProperty) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss60(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/portforwarder.go#L161-L166
|
func (f *PortForwarder) RunForSAMLACS(localPort uint16) error {
if localPort == 0 {
localPort = samlAcsLocalPort
}
return f.Run("pachd", localPort, 654)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L4853-L4857
|
func (v GetCertificateParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork37(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3311-L3314
|
func (e ChangeTrustResultCode) String() string {
name, _ := changeTrustResultCodeMap[int32(e)]
return name
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/reader.go#L53-L66
|
func (r *Reader) ReadUint16() uint16 {
if r.err != nil {
return 0
}
buf := r.buf[:2]
var readN int
readN, r.err = io.ReadFull(r.reader, buf)
if readN < 2 {
return 0
}
return binary.BigEndian.Uint16(buf)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L208-L211
|
func (p DispatchMouseEventParams) WithButton(button ButtonType) *DispatchMouseEventParams {
p.Button = button
return &p
}
|
https://github.com/mailgun/iptools/blob/ba8d5743f6788db9906c07c292a033f194849563/ip.go#L58-L74
|
func GetPrivateHostIPs() ([]net.IP, error) {
ips, err := GetHostIPs()
if err != nil {
return nil, err
}
var privateIPs []net.IP
for _, ip := range ips {
// skip loopback, non-IPv4 and non-private addresses
if ip.IsLoopback() || ip.To4() == nil || !IsPrivate(ip) {
continue
}
privateIPs = append(privateIPs, ip)
}
return privateIPs, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/influx.go#L101-L112
|
func mergeTags(defaultTags, extraTags map[string]string) map[string]string {
newTags := map[string]string{}
for k, v := range defaultTags {
newTags[k] = v
}
for k, v := range extraTags {
newTags[k] = v
}
return newTags
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/deploymentmanifest.go#L179-L184
|
func (s *DeploymentManifest) Tag(key string) string {
if s.Tags == nil {
return ""
}
return s.Tags[key]
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L1372-L1376
|
func (v SearchInResourceReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage15(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4114-L4123
|
func (u OperationResultTr) GetSetOptionsResult() (result SetOptionsResult, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "SetOptionsResult" {
result = *u.SetOptionsResult
ok = true
}
return
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/default_context.go#L224-L232
|
func (d *DefaultContext) Data() map[string]interface{} {
d.moot.Lock()
m := map[string]interface{}{}
for k, v := range d.data {
m[k] = v
}
d.moot.Unlock()
return m
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcqueue/tcqueue.go#L609-L613
|
func (queue *Queue) CompleteArtifact(taskId, runId, name string, payload *CompleteArtifactRequest) error {
cd := tcclient.Client(*queue)
_, _, err := (&cd).APICall(payload, "PUT", "/task/"+url.QueryEscape(taskId)+"/runs/"+url.QueryEscape(runId)+"/artifacts/"+url.QueryEscape(name), nil, nil)
return err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_operations.go#L55-L65
|
func (r *ProtocolLXD) GetOperation(uuid string) (*api.Operation, string, error) {
op := api.Operation{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/operations/%s", url.QueryEscape(uuid)), nil, "", &op)
if err != nil {
return nil, "", err
}
return &op, etag, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L1739-L1743
|
func (v CanEmulateReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoEmulation20(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/types.go#L461-L463
|
func (t *SetDownloadBehaviorBehavior) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/log.go#L38-L47
|
func (l *templateLogger) SetFormat(format string) error {
l.m.Lock()
defer l.m.Unlock()
t, err := template.New("genmai").Parse(format)
if err != nil {
return err
}
l.t = t
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/migrate_container.go#L123-L177
|
func (s *migrationSourceWs) checkForPreDumpSupport() (bool, int) {
// Ask CRIU if this architecture/kernel/criu combination
// supports pre-copy (dirty memory tracking)
criuMigrationArgs := CriuMigrationArgs{
cmd: lxc.MIGRATE_FEATURE_CHECK,
stateDir: "",
function: "feature-check",
stop: false,
actionScript: false,
dumpDir: "",
preDumpDir: "",
features: lxc.FEATURE_MEM_TRACK,
}
err := s.container.Migrate(&criuMigrationArgs)
if err != nil {
// CRIU says it does not know about dirty memory tracking.
// This means the rest of this function is irrelevant.
return false, 0
}
// CRIU says it can actually do pre-dump. Let's set it to true
// unless the user wants something else.
use_pre_dumps := true
// What does the configuration say about pre-copy
tmp := s.container.ExpandedConfig()["migration.incremental.memory"]
if tmp != "" {
use_pre_dumps = shared.IsTrue(tmp)
}
var max_iterations int
// migration.incremental.memory.iterations is the value after which the
// container will be definitely migrated, even if the remaining number
// of memory pages is below the defined threshold.
tmp = s.container.ExpandedConfig()["migration.incremental.memory.iterations"]
if tmp != "" {
max_iterations, _ = strconv.Atoi(tmp)
} else {
// default to 10
max_iterations = 10
}
if max_iterations > 999 {
// the pre-dump directory is hardcoded to a string
// with maximal 3 digits. 999 pre-dumps makes no
// sense at all, but let's make sure the number
// is not higher than this.
max_iterations = 999
}
logger.Debugf("Using maximal %d iterations for pre-dumping", max_iterations)
return use_pre_dumps, max_iterations
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/ranch/storage.go#L42-L71
|
func NewStorage(r storage.PersistenceLayer, storage string) (*Storage, error) {
s := &Storage{
resources: r,
}
if storage != "" {
var data struct {
Resources []common.Resource
}
buf, err := ioutil.ReadFile(storage)
if err == nil {
logrus.Infof("Current state: %s.", string(buf))
err = json.Unmarshal(buf, &data)
if err != nil {
return nil, err
}
} else if !os.IsNotExist(err) {
return nil, err
}
logrus.Info("Before adding resource loop")
for _, res := range data.Resources {
if err := s.AddResource(res); err != nil {
logrus.WithError(err).Errorf("Failed Adding Resources: %s - %s.", res.Name, res.State)
}
logrus.Infof("Successfully Added Resources: %s - %s.", res.Name, res.State)
}
}
return s, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/gw/rpc.pb.gw.go#L1275-L1277
|
func RegisterClusterHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterClusterHandlerClient(ctx, mux, etcdserverpb.NewClusterClient(conn))
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/identity.go#L117-L126
|
func ServiceAccount(c context.Context) (string, error) {
req := &pb.GetServiceAccountNameRequest{}
res := &pb.GetServiceAccountNameResponse{}
err := internal.Call(c, "app_identity_service", "GetServiceAccountName", req, res)
if err != nil {
return "", err
}
return res.GetServiceAccountName(), err
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocktracer.go#L43-L49
|
func (t *MockTracer) FinishedSpans() []*MockSpan {
t.RLock()
defer t.RUnlock()
spans := make([]*MockSpan, len(t.finishedSpans))
copy(spans, t.finishedSpans)
return spans
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L2903-L2910
|
func (r *Datacenter) Locator(api *API) *DatacenterLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.DatacenterLocator(l["href"])
}
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/resources.go#L266-L307
|
func CPUResource() (*api.ResourcesCPU, error) {
c := api.ResourcesCPU{}
threads, err := getThreads()
if err != nil {
return nil, err
}
var cur *api.ResourcesCPUSocket
c.Total = uint64(len(threads))
for _, v := range threads {
if uint64(len(c.Sockets)) <= v.socketID {
c.Sockets = append(c.Sockets, api.ResourcesCPUSocket{})
cur = &c.Sockets[v.socketID]
// Count the number of cores on the socket
// Note that we can't assume sequential core IDs
socketCores := map[uint64]bool{}
for _, thread := range threads {
if thread.socketID != v.socketID {
continue
}
socketCores[thread.coreID] = true
}
cur.Cores = uint64(len(socketCores))
} else {
cur = &c.Sockets[v.socketID]
}
cur.Socket = v.socketID
cur.NUMANode = v.numaNode
cur.Threads++
cur.Name = v.name
cur.Vendor = v.vendor
cur.Frequency = v.frequency
cur.FrequencyTurbo = v.frequencyTurbo
}
return &c, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/query.go#L50-L59
|
func selectTablesSQL(tx *sql.Tx) ([]string, error) {
statement := `
SELECT sql FROM sqlite_master WHERE
type IN ('table', 'index', 'view') AND
name != 'schema' AND
name NOT LIKE 'sqlite_%'
ORDER BY name
`
return query.SelectStrings(tx, statement)
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L211-L308
|
func (p MailBuilder) Build() (*Part, error) {
if p.err != nil {
return nil, p.err
}
// Validations
if p.from.Address == "" {
return nil, errors.New("from not set")
}
if p.subject == "" {
return nil, errors.New("subject not set")
}
if len(p.to)+len(p.cc)+len(p.bcc) == 0 {
return nil, errors.New("no recipients (to, cc, bcc) set")
}
// Fully loaded structure; the presence of text, html, inlines, and attachments will determine
// how much is necessary:
//
// multipart/mixed
// |- multipart/related
// | |- multipart/alternative
// | | |- text/plain
// | | `- text/html
// | `- inlines..
// `- attachments..
//
// We build this tree starting at the leaves, re-rooting as needed.
var root, part *Part
if p.text != nil || p.html == nil {
root = NewPart(ctTextPlain)
root.Content = p.text
root.Charset = utf8
}
if p.html != nil {
part = NewPart(ctTextHTML)
part.Content = p.html
part.Charset = utf8
if root == nil {
root = part
} else {
root.NextSibling = part
}
}
if p.text != nil && p.html != nil {
// Wrap Text & HTML bodies
part = root
root = NewPart(ctMultipartAltern)
root.AddChild(part)
}
if len(p.inlines) > 0 {
part = root
root = NewPart(ctMultipartRelated)
root.AddChild(part)
for _, ip := range p.inlines {
// Copy inline Part to isolate mutations
part = &Part{}
*part = *ip
part.Header = make(textproto.MIMEHeader)
root.AddChild(part)
}
}
if len(p.attachments) > 0 {
part = root
root = NewPart(ctMultipartMixed)
root.AddChild(part)
for _, ap := range p.attachments {
// Copy attachment Part to isolate mutations
part = &Part{}
*part = *ap
part.Header = make(textproto.MIMEHeader)
root.AddChild(part)
}
}
// Headers
h := root.Header
h.Set(hnMIMEVersion, "1.0")
h.Set("From", p.from.String())
h.Set("Subject", p.subject)
if len(p.to) > 0 {
h.Set("To", stringutil.JoinAddress(p.to))
}
if len(p.cc) > 0 {
h.Set("Cc", stringutil.JoinAddress(p.cc))
}
if p.replyTo.Address != "" {
h.Set("Reply-To", p.replyTo.String())
}
date := p.date
if date.IsZero() {
date = time.Now()
}
h.Set("Date", date.Format(time.RFC1123Z))
for k, v := range p.header {
for _, s := range v {
h.Add(k, s)
}
}
return root, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L1084-L1164
|
func (d *Daemon) setupExternalAuthentication(authEndpoint string, authPubkey string, expiry int64, domains string) error {
// Parse the list of domains
authDomains := []string{}
for _, domain := range strings.Split(domains, ",") {
if domain == "" {
continue
}
authDomains = append(authDomains, strings.TrimSpace(domain))
}
// Allow disable external authentication
if authEndpoint == "" {
d.externalAuth = nil
return nil
}
// Setup the candid client
idmClient, err := candidclient.New(candidclient.NewParams{
BaseURL: authEndpoint,
})
if err != nil {
return err
}
idmClientWrapper := &IdentityClientWrapper{
client: idmClient,
ValidDomains: authDomains,
}
// Generate an internal private key
key, err := bakery.GenerateKey()
if err != nil {
return err
}
pkCache := bakery.NewThirdPartyStore()
pkLocator := httpbakery.NewThirdPartyLocator(nil, pkCache)
if authPubkey != "" {
// Parse the public key
pkKey := bakery.Key{}
err := pkKey.UnmarshalText([]byte(authPubkey))
if err != nil {
return err
}
// Add the key information
pkCache.AddInfo(authEndpoint, bakery.ThirdPartyInfo{
PublicKey: bakery.PublicKey{Key: pkKey},
Version: 3,
})
// Allow http URLs if we have a public key set
if strings.HasPrefix(authEndpoint, "http://") {
pkLocator.AllowInsecure()
}
}
// Setup the bakery
bakery := identchecker.NewBakery(identchecker.BakeryParams{
Key: key,
Location: authEndpoint,
Locator: pkLocator,
Checker: httpbakery.NewChecker(),
IdentityClient: idmClientWrapper,
Authorizer: identchecker.ACLAuthorizer{
GetACL: func(ctx context.Context, op bakery.Op) ([]string, bool, error) {
return []string{identchecker.Everyone}, false, nil
},
},
})
// Store our settings
d.externalAuth = &externalAuth{
endpoint: authEndpoint,
expiry: expiry,
bakery: bakery,
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L2229-L2233
|
func (v SetBypassServiceWorkerParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork17(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/ctors.go#L133-L145
|
func (api *TelegramBotAPI) NewOutgoingStickerResend(recipient Recipient, fileID string) *OutgoingSticker {
return &OutgoingSticker{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileID: fileID,
},
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/apparmor.go#L663-L707
|
func AALoadProfile(c container) error {
state := c.DaemonState()
if !state.OS.AppArmorAdmin {
return nil
}
if err := mkApparmorNamespace(c, AANamespace(c)); err != nil {
return err
}
/* In order to avoid forcing a profile parse (potentially slow) on
* every container start, let's use apparmor's binary policy cache,
* which checks mtime of the files to figure out if the policy needs to
* be regenerated.
*
* Since it uses mtimes, we shouldn't just always write out our local
* apparmor template; instead we should check to see whether the
* template is the same as ours. If it isn't we should write our
* version out so that the new changes are reflected and we definitely
* force a recompile.
*/
profile := path.Join(aaPath, "profiles", AAProfileShort(c))
content, err := ioutil.ReadFile(profile)
if err != nil && !os.IsNotExist(err) {
return err
}
updated := getAAProfileContent(c)
if string(content) != string(updated) {
if err := os.MkdirAll(path.Join(aaPath, "cache"), 0700); err != nil {
return err
}
if err := os.MkdirAll(path.Join(aaPath, "profiles"), 0700); err != nil {
return err
}
if err := ioutil.WriteFile(profile, []byte(updated), 0600); err != nil {
return err
}
}
return runApparmor(APPARMOR_CMD_LOAD, c)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/types.go#L177-L179
|
func (t BreakLocationType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L11111-L11113
|
func (api *API) ServerLocator(href string) *ServerLocator {
return &ServerLocator{Href(href), api}
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpclog/grpc.go#L39-L53
|
func UnaryServerInterceptor(log ttnlog.Interface) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
log := getLog(log).WithField("method", info.FullMethod)
log = log.WithFields(FieldsFromIncomingContext(ctx))
start := time.Now()
resp, err = handler(ctx, req)
log = log.WithField("duration", time.Since(start))
if err != nil {
log.WithError(err).Debug("rpc-server: call failed")
return
}
log.Debug("rpc-server: call done")
return
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.