_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/key.go#L113-L115
|
func GenerateKeyPair(typ, bits int) (PrivKey, PubKey, error) {
return GenerateKeyPairWithReader(typ, bits, rand.Reader)
}
|
https://github.com/auth0/go-jwt-middleware/blob/5493cabe49f7bfa6e2ec444a09d334d90cd4e2bd/jwtmiddleware.go#L140-L144
|
func FromParameter(param string) TokenExtractor {
return func(r *http.Request) (string, error) {
return r.URL.Query().Get(param), nil
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L409-L413
|
func (v StopWorkerParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoServiceworker3(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L90-L93
|
func (p DispatchKeyEventParams) WithKey(key string) *DispatchKeyEventParams {
p.Key = key
return &p
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/default.go#L226-L228
|
func Diem(exitCode int, m *Attrs, msg string, a ...interface{}) {
curDefault.Diem(exitCode, m, msg, a...)
}
|
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/opts.go#L91-L96
|
func MonitoredResource(resource *logging.MonitoredResource) Option {
return func(sh *StackdriverHook) error {
sh.resource = resource
return nil
}
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/y.go#L285-L295
|
func (t *Throttle) Finish() error {
t.wg.Wait()
close(t.ch)
close(t.errCh)
for err := range t.errCh {
if err != nil {
return err
}
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_internal.go#L205-L238
|
func internalSQLGet(d *Daemon, r *http.Request) Response {
database := r.FormValue("database")
if !shared.StringInSlice(database, []string{"local", "global"}) {
return BadRequest(fmt.Errorf("Invalid database"))
}
schemaFormValue := r.FormValue("schema")
schemaOnly, err := strconv.Atoi(schemaFormValue)
if err != nil {
schemaOnly = 0
}
var schema string
var db *sql.DB
if database == "global" {
db = d.cluster.DB()
schema = cluster.FreshSchema()
} else {
db = d.db.DB()
schema = node.FreshSchema()
}
tx, err := db.Begin()
if err != nil {
return SmartError(errors.Wrap(err, "failed to start transaction"))
}
defer tx.Rollback()
dump, err := query.Dump(tx, schema, schemaOnly == 1)
if err != nil {
return SmartError(errors.Wrapf(err, "failed dump database %s", database))
}
return SyncResponse(true, internalSQLDump{Text: dump})
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L188-L219
|
func (cdc *Codec) MarshalBinaryBare(o interface{}) ([]byte, error) {
// Dereference value if pointer.
var rv, _, isNilPtr = derefPointers(reflect.ValueOf(o))
if isNilPtr {
// NOTE: You can still do so by calling
// `.MarshalBinaryLengthPrefixed(struct{ *SomeType })` or so on.
panic("MarshalBinaryBare cannot marshal a nil pointer directly. Try wrapping in a struct?")
}
// Encode Amino:binary bytes.
var bz []byte
buf := new(bytes.Buffer)
rt := rv.Type()
info, err := cdc.getTypeInfo_wlock(rt)
if err != nil {
return nil, err
}
err = cdc.encodeReflectBinary(buf, info, rv, FieldOptions{BinFieldNum: 1}, true)
if err != nil {
return nil, err
}
bz = buf.Bytes()
// If registered concrete, prepend prefix bytes.
if info.Registered {
pb := info.Prefix.Bytes()
bz = append(pb, bz...)
}
return bz, nil
}
|
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/atomic_rbuf.go#L246-L248
|
func (b *AtomicFixedSizeRingBuf) ReadWithoutAdvance(p []byte) (n int, err error) {
return b.ReadAndMaybeAdvance(p, false)
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gstruct/errors/nested_types.go#L58-L72
|
func (err AggregateError) Error() string {
if len(err) == 0 {
// This should never happen, really.
return ""
}
if len(err) == 1 {
return err[0].Error()
}
result := fmt.Sprintf("[%s", err[0].Error())
for i := 1; i < len(err); i++ {
result += fmt.Sprintf(", %s", err[i].Error())
}
result += "]"
return result
}
|
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/pprof.go#L18-L30
|
func (mux *ServerMux) InitPProf(prefix string) {
if prefix == "" {
prefix = "/debug/pprof"
}
mux.HandleFunc(router.Wildcard(fmt.Sprintf("%s/*", prefix)),
WrapHTTPHandlerFunc(pprofIndex(prefix)), nil)
mux.HandleFunc(router.Simple(fmt.Sprintf("%s/cmdline", prefix)),
WrapHTTPHandlerFunc(http.HandlerFunc(pprof.Cmdline)), nil)
mux.HandleFunc(router.Simple(fmt.Sprintf("%s/profile", prefix)),
WrapHTTPHandlerFunc(http.HandlerFunc(pprof.Profile)), nil)
mux.HandleFunc(router.Simple(fmt.Sprintf("%s/symbol", prefix)),
WrapHTTPHandlerFunc(http.HandlerFunc(pprof.Symbol)), nil)
}
|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L4617-L4622
|
func (o *ListUintptrOption) Set(value string) error {
val := UintptrOption{}
val.Set(value)
*o = append(*o, val)
return nil
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/mock_service.go#L78-L82
|
func (m *MockService) AddInteraction(interaction *Interaction) error {
log.Println("[DEBUG] mock service add interaction")
url := fmt.Sprintf("%s/interactions", m.BaseURL)
return m.call("POST", url, interaction)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/sync/sync.go#L319-L354
|
func (p *Puller) CleanUp() (int64, error) {
var result error
select {
case result = <-p.errCh:
default:
}
// Open all the pipes to unblock the goros
var pipes []io.Closer
func() {
p.Lock()
defer p.Unlock()
p.cleaned = true
for path := range p.pipes {
f, err := os.OpenFile(path, syscall.O_NONBLOCK+os.O_RDONLY, os.ModeNamedPipe)
if err != nil && result == nil {
result = err
}
pipes = append(pipes, f)
}
p.pipes = make(map[string]bool)
}()
// Wait for all goros to exit
p.wg.Wait()
// Close the pipes
for _, pipe := range pipes {
if err := pipe.Close(); err != nil && result == nil {
result = err
}
}
size := p.size
p.size = 0
return size, result
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/model.go#L62-L72
|
func (b *Base) MustGet(name string) interface{} {
// find field
field := b.meta.Fields[name]
if field == nil {
panic(fmt.Sprintf(`coal: field "%s" not found on "%s"`, name, b.meta.Name))
}
// read value from model struct
structField := reflect.ValueOf(b.model).Elem().Field(field.index)
return structField.Interface()
}
|
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/ecdsa.go#L129-L140
|
func (ePriv *ECDSAPrivateKey) Sign(data []byte) ([]byte, error) {
hash := sha256.Sum256(data)
r, s, err := ecdsa.Sign(rand.Reader, ePriv.priv, hash[:])
if err != nil {
return nil, err
}
return asn1.Marshal(ECDSASig{
R: r,
S: s,
})
}
|
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/table.go#L6-L36
|
func (c *Client) InsertNewTable(projectID, datasetID, tableName string, fields map[string]string) error {
// If the table already exists, an error will be raised here.
service, err := c.connect()
if err != nil {
return err
}
// build the table schema
schema := &bigquery.TableSchema{}
for k, v := range fields {
schema.Fields = append(schema.Fields, &bigquery.TableFieldSchema{Name: k, Type: v})
}
// build the table to insert
table := &bigquery.Table{}
table.Schema = schema
tr := &bigquery.TableReference{}
tr.DatasetId = datasetID
tr.ProjectId = projectID
tr.TableId = tableName
table.TableReference = tr
_, err = service.Tables.Insert(projectID, datasetID, table).Do()
if err != nil {
return err
}
return nil
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/policy.go#L124-L146
|
func (p *Policy) GenerateToken(id bson.ObjectId, issuedAt, expiresAt time.Time, client Client, resourceOwner ResourceOwner, token GenericToken) (string, error) {
// prepare claims
claims := &TokenClaims{}
claims.Id = id.Hex()
claims.IssuedAt = issuedAt.Unix()
claims.ExpiresAt = expiresAt.Unix()
// set user data
if p.TokenData != nil {
claims.Data = p.TokenData(client, resourceOwner, token)
}
// create token
tkn := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// sign token
str, err := tkn.SignedString(p.Secret)
if err != nil {
return "", nil
}
return str, nil
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/indexer.go#L72-L87
|
func (i *Indexer) Ensure(store *Store) error {
// copy store
s := store.Copy()
defer s.Close()
// go through all raw indexes
for _, i := range i.indexes {
// ensure single index
err := s.DB().C(i.coll).EnsureIndex(i.index)
if err != nil {
return err
}
}
return nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1010-L1040
|
func (app *App) Grant(team *authTypes.Team) error {
if _, found := app.findTeam(team); found {
return ErrAlreadyHaveAccess
}
app.Teams = append(app.Teams, team.Name)
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
err = conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$addToSet": bson.M{"teams": team.Name}})
if err != nil {
return err
}
users, err := auth.ListUsersWithPermissions(permission.Permission{
Scheme: permission.PermAppDeploy,
Context: permission.Context(permTypes.CtxTeam, team.Name),
})
if err != nil {
conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$pull": bson.M{"teams": team.Name}})
return err
}
for _, user := range users {
err = repository.Manager().GrantAccess(app.Name, user.Email)
if err != nil {
conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$pull": bson.M{"teams": team.Name}})
return err
}
}
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L14529-L14536
|
func (r *VolumeAttachment) Locator(api *API) *VolumeAttachmentLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.VolumeAttachmentLocator(l["href"])
}
}
return nil
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/smtp/server.go#L51-L54
|
func (s *SMTP) SendMail(from string, to []string, msg []byte) (err error) {
err = s.send(s.addr, s.auth, from, to, msg)
return
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/tracing_keys.go#L84-L95
|
func (c tracingHeadersCarrier) ForeachKey(handler func(key, val string) error) error {
for k, v := range c {
if !strings.HasPrefix(k, tracingKeyPrefix) {
continue
}
noPrefixKey := tracingKeyDecoding.mapAndCache(k)
if err := handler(noPrefixKey, v); err != nil {
return err
}
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L680-L682
|
func (p *SetBlockedURLSParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetBlockedURLS, p, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L858-L863
|
func SetScriptSource(scriptID runtime.ScriptID, scriptSource string) *SetScriptSourceParams {
return &SetScriptSourceParams{
ScriptID: scriptID,
ScriptSource: scriptSource,
}
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/get_apps_app_routes_route_parameters.go#L82-L85
|
func (o *GetAppsAppRoutesRouteParams) WithTimeout(timeout time.Duration) *GetAppsAppRoutesRouteParams {
o.SetTimeout(timeout)
return o
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L202-L205
|
func (p DispatchMouseEventParams) WithTimestamp(timestamp *TimeSinceEpoch) *DispatchMouseEventParams {
p.Timestamp = timestamp
return &p
}
|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L3397-L3406
|
func (o *MapUintOption) Set(value string) error {
parts := stringMapRegex.Split(value, 2)
if len(parts) != 2 {
return fmt.Errorf("expected KEY=VALUE got '%s'", value)
}
val := UintOption{}
val.Set(parts[1])
(*o)[parts[0]] = val
return nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1162-L1171
|
func (u LedgerEntryData) GetOffer() (result OfferEntry, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "Offer" {
result = *u.Offer
ok = true
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1968-L1972
|
func (v QuerySelectorAllReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom21(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/jstemmer/go-junit-report/blob/af01ea7f8024089b458d804d5cdf190f962a9a0c/formatter/formatter.go#L63-L149
|
func JUnitReportXML(report *parser.Report, noXMLHeader bool, goVersion string, w io.Writer) error {
suites := JUnitTestSuites{}
// convert Report to JUnit test suites
for _, pkg := range report.Packages {
pkg.Benchmarks = mergeBenchmarks(pkg.Benchmarks)
ts := JUnitTestSuite{
Tests: len(pkg.Tests) + len(pkg.Benchmarks),
Failures: 0,
Time: formatTime(pkg.Duration),
Name: pkg.Name,
Properties: []JUnitProperty{},
TestCases: []JUnitTestCase{},
}
classname := pkg.Name
if idx := strings.LastIndex(classname, "/"); idx > -1 && idx < len(pkg.Name) {
classname = pkg.Name[idx+1:]
}
// properties
if goVersion == "" {
// if goVersion was not specified as a flag, fall back to version reported by runtime
goVersion = runtime.Version()
}
ts.Properties = append(ts.Properties, JUnitProperty{"go.version", goVersion})
if pkg.CoveragePct != "" {
ts.Properties = append(ts.Properties, JUnitProperty{"coverage.statements.pct", pkg.CoveragePct})
}
// individual test cases
for _, test := range pkg.Tests {
testCase := JUnitTestCase{
Classname: classname,
Name: test.Name,
Time: formatTime(test.Duration),
Failure: nil,
}
if test.Result == parser.FAIL {
ts.Failures++
testCase.Failure = &JUnitFailure{
Message: "Failed",
Type: "",
Contents: strings.Join(test.Output, "\n"),
}
}
if test.Result == parser.SKIP {
testCase.SkipMessage = &JUnitSkipMessage{strings.Join(test.Output, "\n")}
}
ts.TestCases = append(ts.TestCases, testCase)
}
// individual benchmarks
for _, benchmark := range pkg.Benchmarks {
benchmarkCase := JUnitTestCase{
Classname: classname,
Name: benchmark.Name,
Time: formatBenchmarkTime(benchmark.Duration),
}
ts.TestCases = append(ts.TestCases, benchmarkCase)
}
suites.Suites = append(suites.Suites, ts)
}
// to xml
bytes, err := xml.MarshalIndent(suites, "", "\t")
if err != nil {
return err
}
writer := bufio.NewWriter(w)
if !noXMLHeader {
writer.WriteString(xml.Header)
}
writer.Write(bytes)
writer.WriteByte('\n')
writer.Flush()
return nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/set_options.go#L114-L120
|
func SetThresholds(low, medium, high uint32) Thresholds {
return Thresholds{
Low: &low,
Medium: &medium,
High: &high,
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/informers/externalversions/prowjobs/v1/prowjob.go#L57-L77
|
func NewFilteredProwJobInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.ProwV1().ProwJobs(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.ProwV1().ProwJobs(namespace).Watch(options)
},
},
&prowjobsv1.ProwJob{},
resyncPeriod,
indexers,
)
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/uuid/uuid.go#L25-L34
|
func TimeOrderedUUID() string {
unixTime := uint32(time.Now().UTC().Unix())
return fmt.Sprintf("%08x-%04x-%04x-%04x-%04x%08x",
unixTime,
rand.MustGenerateRandomBytes(2),
rand.MustGenerateRandomBytes(2),
rand.MustGenerateRandomBytes(2),
rand.MustGenerateRandomBytes(2),
rand.MustGenerateRandomBytes(4))
}
|
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L760-L773
|
func (p *PubSub) getValidators(msg *Message) []*topicVal {
var vals []*topicVal
for _, topic := range msg.GetTopicIDs() {
val, ok := p.topicVals[topic]
if !ok {
continue
}
vals = append(vals, val)
}
return vals
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L225-L285
|
func (r *ProtocolLXD) CreateContainerFromImage(source ImageServer, image api.Image, req api.ContainersPost) (RemoteOperation, error) {
// Set the minimal source fields
req.Source.Type = "image"
// Optimization for the local image case
if r == source {
// Always use fingerprints for local case
req.Source.Fingerprint = image.Fingerprint
req.Source.Alias = ""
op, err := r.CreateContainer(req)
if err != nil {
return nil, err
}
rop := remoteOperation{
targetOp: op,
chDone: make(chan bool),
}
// Forward targetOp to remote op
go func() {
rop.err = rop.targetOp.Wait()
close(rop.chDone)
}()
return &rop, nil
}
// Minimal source fields for remote image
req.Source.Mode = "pull"
// If we have an alias and the image is public, use that
if req.Source.Alias != "" && image.Public {
req.Source.Fingerprint = ""
} else {
req.Source.Fingerprint = image.Fingerprint
req.Source.Alias = ""
}
// Get source server connection information
info, err := source.GetConnectionInfo()
if err != nil {
return nil, err
}
req.Source.Protocol = info.Protocol
req.Source.Certificate = info.Certificate
// Generate secret token if needed
if !image.Public {
secret, err := source.GetImageSecret(image.Fingerprint)
if err != nil {
return nil, err
}
req.Source.Secret = secret
}
return r.tryCreateContainer(req, info.Addresses)
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/value.go#L253-L336
|
func (vlog *valueLog) iterate(lf *logFile, offset uint32, fn logEntry) (uint32, error) {
fi, err := lf.fd.Stat()
if err != nil {
return 0, err
}
if int64(offset) == fi.Size() {
// We're at the end of the file already. No need to do anything.
return offset, nil
}
if vlog.opt.ReadOnly {
// We're not at the end of the file. We'd need to replay the entries, or
// possibly truncate the file.
return 0, ErrReplayNeeded
}
// We're not at the end of the file. Let's Seek to the offset and start reading.
if _, err := lf.fd.Seek(int64(offset), io.SeekStart); err != nil {
return 0, errFile(err, lf.path, "Unable to seek")
}
reader := bufio.NewReader(lf.fd)
read := &safeRead{
k: make([]byte, 10),
v: make([]byte, 10),
recordOffset: offset,
}
var lastCommit uint64
var validEndOffset uint32
for {
e, err := read.Entry(reader)
if err == io.EOF {
break
} else if err == io.ErrUnexpectedEOF || err == errTruncate {
break
} else if err != nil {
return 0, err
} else if e == nil {
continue
}
var vp valuePointer
vp.Len = uint32(headerBufSize + len(e.Key) + len(e.Value) + crc32.Size)
read.recordOffset += vp.Len
vp.Offset = e.offset
vp.Fid = lf.fid
if e.meta&bitTxn > 0 {
txnTs := y.ParseTs(e.Key)
if lastCommit == 0 {
lastCommit = txnTs
}
if lastCommit != txnTs {
break
}
} else if e.meta&bitFinTxn > 0 {
txnTs, err := strconv.ParseUint(string(e.Value), 10, 64)
if err != nil || lastCommit != txnTs {
break
}
// Got the end of txn. Now we can store them.
lastCommit = 0
validEndOffset = read.recordOffset
} else {
if lastCommit != 0 {
// This is most likely an entry which was moved as part of GC.
// We shouldn't get this entry in the middle of a transaction.
break
}
validEndOffset = read.recordOffset
}
if err := fn(*e, vp); err != nil {
if err == errStop {
break
}
return 0, errFile(err, lf.path, "Iteration function")
}
}
return validEndOffset, nil
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decode_reader.go#L78-L81
|
func (w *window) writeByte(c byte) {
w.buf[w.w] = c
w.w = (w.w + 1) & w.mask
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/hyperbahn/gen-go/hyperbahn/hyperbahn.go#L51-L56
|
func (p *HyperbahnClient) Discover(query *DiscoveryQuery) (r *DiscoveryResult_, err error) {
if err = p.sendDiscover(query); err != nil {
return
}
return p.recvDiscover()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/mason/storage.go#L48-L50
|
func (s *Storage) DeleteConfig(name string) error {
return s.configs.Delete(name)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/cache.go#L56-L67
|
func (c *MergeCache) Get(id int64, w io.Writer, filter Filter) (retErr error) {
r, err := c.Cache.Get(fmt.Sprint(id))
if err != nil {
return err
}
defer func() {
if err := r.Close(); err != nil && retErr == nil {
retErr = err
}
}()
return NewWriter(w).Copy(NewReader(r, filter))
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L190-L193
|
func (eC2Manager *EC2Manager) EnsureKeyPair_SignedURL(name string, duration time.Duration) (*url.URL, error) {
cd := tcclient.Client(*eC2Manager)
return (&cd).SignedURL("/key-pairs/"+url.QueryEscape(name), nil, duration)
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/axe/queue.go#L62-L98
|
func (q *Queue) Callback(name string, delay time.Duration, matcher fire.Matcher, cb func(ctx *fire.Context) Model) *fire.Callback {
return fire.C("axe/Queue.Callback", matcher, func(ctx *fire.Context) error {
// set task tag
ctx.Tracer.Tag("task", name)
// get data
var data Model
if cb != nil {
data = cb(ctx)
}
// check if controller uses same store
if q.store == ctx.Controller.Store {
// enqueue job using context store
_, err := Enqueue(ctx.Store, name, data, delay)
if err != nil {
return err
}
} else {
// enqueue job using queue store
_, err := q.Enqueue(name, data, delay)
if err != nil {
return err
}
}
// respond with an empty object
if ctx.Operation.Action() {
err := ctx.Respond(fire.Map{})
if err != nil {
return err
}
}
return nil
})
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/dir_windows.go#L70-L100
|
func acquireDirectoryLock(dirPath string, pidFileName string, readOnly bool) (*directoryLockGuard, error) {
if readOnly {
return nil, ErrWindowsNotSupported
}
// Convert to absolute path so that Release still works even if we do an unbalanced
// chdir in the meantime.
absLockFilePath, err := filepath.Abs(filepath.Join(dirPath, pidFileName))
if err != nil {
return nil, errors.Wrap(err, "Cannot get absolute path for pid lock file")
}
// This call creates a file handler in memory that only one process can use at a time. When
// that process ends, the file is deleted by the system.
// FILE_ATTRIBUTE_TEMPORARY is used to tell Windows to try to create the handle in memory.
// FILE_FLAG_DELETE_ON_CLOSE is not specified in syscall_windows.go but tells Windows to delete
// the file when all processes holding the handler are closed.
// XXX: this works but it's a bit klunky. i'd prefer to use LockFileEx but it needs unsafe pkg.
h, err := syscall.CreateFile(
syscall.StringToUTF16Ptr(absLockFilePath), 0, 0, nil,
syscall.OPEN_ALWAYS,
uint32(FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE),
0)
if err != nil {
return nil, errors.Wrapf(err,
"Cannot create lock file %q. Another process is using this Badger database",
absLockFilePath)
}
return &directoryLockGuard{h: h, path: absLockFilePath}, nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/info/options.go#L17-L25
|
func (opts *Options) Validate() error {
if opts.App.IsZero() {
opts.App = meta.New(".")
}
if opts.Out.Writer == nil {
opts.Out = rx.NewWriter(os.Stdout)
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L189-L193
|
func (v *SetDockTileParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser1(&r, v)
return r.Error()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/ostree/ostree_transport.go#L201-L209
|
func (ref ostreeReference) NewImageSource(ctx context.Context, sys *types.SystemContext) (types.ImageSource, error) {
var tmpDir string
if sys == nil || sys.OSTreeTmpDirPath == "" {
tmpDir = os.TempDir()
} else {
tmpDir = sys.OSTreeTmpDirPath
}
return newImageSource(tmpDir, ref)
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L220-L224
|
func (w *WriteBuffer) WriteUint16(n uint16) {
if b := w.reserve(2); b != nil {
binary.BigEndian.PutUint16(b, n)
}
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L61-L64
|
func (gc *GraphicContext) Fill(paths ...*draw2d.Path) {
gc.drawPaths(filled, paths...)
gc.Current.Path.Clear()
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/mnemosyned/daemon.go#L83-L113
|
func NewDaemon(opts *DaemonOpts) (*Daemon, error) {
d := &Daemon{
done: make(chan struct{}),
opts: opts,
logger: opts.Logger,
serverOptions: opts.RPCOptions,
rpcListener: opts.RPCListener,
debugListener: opts.DebugListener,
}
if err := d.setPostgresConnectionParameters(); err != nil {
return nil, err
}
if d.opts.SessionTTL == 0 {
d.opts.SessionTTL = storage.DefaultTTL
}
if d.opts.SessionTTC == 0 {
d.opts.SessionTTC = storage.DefaultTTC
}
if d.opts.Storage == "" {
d.opts.Storage = storage.EnginePostgres
}
if d.opts.PostgresTable == "" {
d.opts.PostgresTable = "session"
}
if d.opts.PostgresSchema == "" {
d.opts.PostgresSchema = "mnemosyne"
}
return d, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L64-L72
|
func (o Owners) GetApprovers() map[string]sets.String {
ownersToApprovers := map[string]sets.String{}
for fn := range o.GetOwnersSet() {
ownersToApprovers[fn] = o.repo.Approvers(fn)
}
return ownersToApprovers
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L180-L183
|
func (p ContinueRequestParams) WithPostData(postData string) *ContinueRequestParams {
p.PostData = postData
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L6037-L6041
|
func (v *EventMediaQueryResultChanged) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss54(&r, v)
return r.Error()
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L629-L638
|
func (t *Iterator) Next(dst interface{}) (*Key, error) {
k, e, err := t.next()
if err != nil {
return nil, err
}
if dst != nil && !t.q.keysOnly {
err = loadEntity(dst, e)
}
return k, err
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L76-L82
|
func Camelize(s string) string {
return camelizeRe.ReplaceAllStringFunc(s, func(val string) string {
val = strings.ToUpper(val)
val = camelizeRe2.ReplaceAllString(val, "")
return val
})
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rbac/server.go#L211-L213
|
func (r *Server) RenameProject(id int64, name string) error {
return r.AddProject(id, name)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/boltdb/boltdb.go#L71-L84
|
func unlockPath(path string) {
pathLocksMutex.Lock()
defer pathLocksMutex.Unlock()
pl, ok := pathLocks[path]
if !ok {
// Should this return an error instead? BlobInfoCache ultimately ignores errors…
panic(fmt.Sprintf("Internal error: unlocking nonexistent lock for path %s", path))
}
pl.mutex.Unlock()
pl.refCount--
if pl.refCount == 0 {
delete(pathLocks, path)
}
}
|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L2753-L2758
|
func (o *ListInt8Option) Set(value string) error {
val := Int8Option{}
val.Set(value)
*o = append(*o, val)
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/raft.go#L92-L101
|
func (n *NodeTx) RaftNodeDelete(id int64) error {
deleted, err := query.DeleteObject(n.tx, "raft_nodes", id)
if err != nil {
return err
}
if !deleted {
return ErrNoSuchObject
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/tools/etcd-dump-logs/main.go#L145-L150
|
func excerpt(str string, pre, suf int) string {
if pre+suf > len(str) {
return fmt.Sprintf("%q", str)
}
return fmt.Sprintf("%q...%q", str[:pre], str[len(str)-suf:])
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/manage_offer.go#L103-L133
|
func (m Rate) MutateManageOffer(o interface{}) (err error) {
switch o := o.(type) {
default:
err = errors.New("Unexpected operation type")
case *xdr.ManageOfferOp:
o.Selling, err = m.Selling.ToXdrObject()
if err != nil {
return
}
o.Buying, err = m.Buying.ToXdrObject()
if err != nil {
return
}
o.Price, err = price.Parse(string(m.Price))
case *xdr.CreatePassiveOfferOp:
o.Selling, err = m.Selling.ToXdrObject()
if err != nil {
return
}
o.Buying, err = m.Buying.ToXdrObject()
if err != nil {
return
}
o.Price, err = price.Parse(string(m.Price))
}
return
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/sourced.go#L97-L99
|
func (i *sourcedImage) Manifest(ctx context.Context) ([]byte, string, error) {
return i.manifestBlob, i.manifestMIMEType, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/tracing/tracing.go#L167-L170
|
func StreamClientInterceptor() grpc.StreamClientInterceptor {
return otgrpc.OpenTracingStreamClientInterceptor(opentracing.GlobalTracer(),
otgrpc.IncludingSpans(addTraceIfTracingEnabled))
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L438-L451
|
func (config *directClientConfig) getCluster() clientcmdCluster {
clusterInfos := config.config.Clusters
clusterInfoName := config.getClusterName()
var mergedClusterInfo clientcmdCluster
mergo.Merge(&mergedClusterInfo, defaultCluster)
mergo.Merge(&mergedClusterInfo, envVarCluster)
if configClusterInfo, exists := clusterInfos[clusterInfoName]; exists {
mergo.Merge(&mergedClusterInfo, configClusterInfo)
}
// REMOVED: overrides support
return mergedClusterInfo
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L5097-L5101
|
func (v *EventScreencastFrame) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage52(&r, v)
return r.Error()
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L138-L159
|
func (v *VM) ReadOnly() (bool, error) {
var err C.VixError = C.VIX_OK
readonly := C.VIX_PROPERTY_NONE
err = C.get_property(v.handle,
C.VIX_PROPERTY_VM_READ_ONLY,
unsafe.Pointer(&readonly))
if C.VIX_OK != err {
return false, &Error{
Operation: "vm.ReadOnly",
Code: int(err & 0xFFFF),
Text: C.GoString(C.Vix_GetErrorText(err, nil)),
}
}
if readonly == 0 {
return false, nil
}
return true, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/db/storage/storage.go#L88-L90
|
func (s *Storage) DropDatabase(name string) error {
return s.session.DB(name).DropDatabase()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L4017-L4021
|
func (v Initiator) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork27(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L164-L168
|
func (v GetManifestForFrameReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoApplicationcache1(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/iterator.go#L206-L211
|
func (t *Table) NewIterator(reversed bool) *Iterator {
t.IncrRef() // Important.
ti := &Iterator{t: t, reversed: reversed}
ti.next()
return ti
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/ranch/storage.go#L89-L100
|
func (s *Storage) GetResource(name string) (common.Resource, error) {
i, err := s.resources.Get(name)
if err != nil {
return common.Resource{}, err
}
var res common.Resource
res, err = common.ItemToResource(i)
if err != nil {
return common.Resource{}, err
}
return res, nil
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/json-encode.go#L338-L405
|
func (cdc *Codec) encodeReflectJSONMap(w io.Writer, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) {
if printLog {
fmt.Println("(e) encodeReflectJSONMap")
defer func() {
fmt.Printf("(e) -> err: %v\n", err)
}()
}
// Part 1.
err = writeStr(w, `{`)
if err != nil {
return
}
// Part 2.
defer func() {
if err == nil {
err = writeStr(w, `}`)
}
}()
// Ensure that the map key type is a string.
if rv.Type().Key().Kind() != reflect.String {
err = errors.New("encodeReflectJSONMap: map key type must be a string")
return
}
var writeComma = false
for _, krv := range rv.MapKeys() {
// Get dereferenced object value and info.
var vrv, _, isNil = derefPointers(rv.MapIndex(krv))
// Add a comma if we need to.
if writeComma {
err = writeStr(w, `,`)
if err != nil {
return
}
writeComma = false
}
// Write field name.
err = invokeStdlibJSONMarshal(w, krv.Interface())
if err != nil {
return
}
// Write colon.
err = writeStr(w, `:`)
if err != nil {
return
}
// Write field value.
if isNil {
err = writeStr(w, `null`)
} else {
var vinfo *TypeInfo
vinfo, err = cdc.getTypeInfo_wlock(vrv.Type())
if err != nil {
return
}
err = cdc.encodeReflectJSON(w, vinfo, vrv, fopts) // pass through fopts
}
if err != nil {
return
}
writeComma = true
}
return
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/innkeeperclient/ik_client.go#L12-L18
|
func New(uri string, user string, password string) InnkeeperClient {
return &IkClient{
URI: uri,
User: user,
Password: password,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/storage.go#L149-L151
|
func (p *UntrackCacheStorageForOriginParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandUntrackCacheStorageForOrigin, p, nil)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/idmap/shift_linux.go#L186-L199
|
func SetCaps(path string, caps []byte, uid int64) error {
cpath := C.CString(path)
defer C.free(unsafe.Pointer(cpath))
ccaps := C.CString(string(caps))
defer C.free(unsafe.Pointer(ccaps))
r := C.set_vfs_ns_caps(cpath, ccaps, C.ssize_t(len(caps)), C.uint32_t(uid))
if r != 0 {
return fmt.Errorf("Failed to apply capabilities to: %s", path)
}
return nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/skl/skl.go#L424-L427
|
func (s *Iterator) Value() y.ValueStruct {
valOffset, valSize := s.n.getValueOffset()
return s.list.arena.getVal(valOffset, valSize)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5584-L5596
|
func NewScpHistoryEntry(v int32, value interface{}) (result ScpHistoryEntry, err error) {
result.V = v
switch int32(v) {
case 0:
tv, ok := value.(ScpHistoryEntryV0)
if !ok {
err = fmt.Errorf("invalid value, must be ScpHistoryEntryV0")
return
}
result.V0 = &tv
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L1709-L1713
|
func (v SetBlackboxPatternsParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger17(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5067-L5075
|
func (u LedgerKey) MustAccount() LedgerKeyAccount {
val, ok := u.GetAccount()
if !ok {
panic("arm Account is not set")
}
return val
}
|
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/atomic_rbuf.go#L451-L470
|
func (b *AtomicFixedSizeRingBuf) Adopt(me []byte) {
b.tex.Lock()
defer b.tex.Unlock()
n := len(me)
if n > b.N {
b.A[0] = me
b.A[1] = make([]byte, n, n)
b.N = n
b.Use = 0
b.Beg = 0
b.readable = n
} else {
// we already have a larger buffer, reuse it.
copy(b.A[0], me)
b.Use = 0
b.Beg = 0
b.readable = n
}
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/template_engine.go#L12-L31
|
func GoTemplateEngine(input string, data map[string]interface{}, helpers map[string]interface{}) (string, error) {
// since go templates don't have the concept of an optional map argument like Plush does
// add this "null" map so it can be used in templates like this:
// {{ partial "flash.html" .nilOpts }}
data["nilOpts"] = map[string]interface{}{}
t := template.New(input)
if helpers != nil {
t = t.Funcs(helpers)
}
t, err := t.Parse(input)
if err != nil {
return "", err
}
bb := &bytes.Buffer{}
err = t.Execute(bb, data)
return bb.String(), err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1361-L1374
|
func (r *ProtocolLXD) UpdateContainerSnapshot(containerName string, name string, container api.ContainerSnapshotPut, ETag string) (Operation, error) {
if !r.HasExtension("snapshot_expiry") {
return nil, fmt.Errorf("The server is missing the required \"snapshot_expiry\" API extension")
}
// Send the request
op, _, err := r.queryOperation("PUT", fmt.Sprintf("/containers/%s/snapshots/%s",
url.QueryEscape(containerName), url.QueryEscape(name)), container, ETag)
if err != nil {
return nil, err
}
return op, nil
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/file_snapshot.go#L208-L224
|
func (f *FileSnapshotStore) List() ([]*SnapshotMeta, error) {
// Get the eligible snapshots
snapshots, err := f.getSnapshots()
if err != nil {
f.logger.Printf("[ERR] snapshot: Failed to get snapshots: %v", err)
return nil, err
}
var snapMeta []*SnapshotMeta
for _, meta := range snapshots {
snapMeta = append(snapMeta, &meta.SnapshotMeta)
if len(snapMeta) == f.retain {
break
}
}
return snapMeta, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/client/client.go#L153-L164
|
func (c *Client) AcquireByState(state, dest string, names []string) ([]common.Resource, error) {
resources, err := c.acquireByState(state, dest, names)
if err != nil {
return nil, err
}
c.lock.Lock()
defer c.lock.Unlock()
for _, r := range resources {
c.storage.Add(r)
}
return resources, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L314-L318
|
func (v *SnapshotCommandLogParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoLayertree2(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/client/json.go#L62-L72
|
func caseSensitiveJsonIterator() jsoniter.API {
config := jsoniter.Config{
EscapeHTML: true,
SortMapKeys: true,
ValidateJsonRawMessage: true,
CaseSensitive: true,
}.Froze()
// Force jsoniter to decode number to interface{} via int64/float64, if possible.
config.RegisterExtension(&customNumberExtension{})
return config
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L429-L434
|
func (s *FileSequence) SetDirname(dir string) {
if !strings.HasSuffix(dir, string(filepath.Separator)) {
dir = dir + string(filepath.Separator)
}
s.dir = dir
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L259-L261
|
func (d *dumpClient) Do(req *http.Request) (*http.Response, error) {
return d.doImp(req, false, nil)
}
|
https://github.com/danott/envflag/blob/14c5f9aaa227ddb49f3206fe06432edfc27735a5/envflag.go#L59-L69
|
func Environ() []string {
s := make([]string, 0)
FlagSet.VisitAll(func(f *flag.Flag) {
if value, ok := getenv(f.Name); ok {
s = append(s, flagAsEnv(f.Name)+"="+value)
}
})
return s
}
|
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/binding/binding.go#L116-L132
|
func Json(jsonStruct interface{}, ifacePtr ...interface{}) martini.Handler {
return func(context martini.Context, req *http.Request) {
ensureNotPointer(jsonStruct)
jsonStruct := reflect.New(reflect.TypeOf(jsonStruct))
errors := newErrors()
if req.Body != nil {
defer req.Body.Close()
}
if err := json.NewDecoder(req.Body).Decode(jsonStruct.Interface()); err != nil {
errors.Overall[DeserializationError] = err.Error()
}
validateAndMap(jsonStruct, context, errors, ifacePtr...)
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/fuzzy/cluster.go#L144-L162
|
func (c *cluster) LeaderPlus(n int) []*raftNode {
r := make([]*raftNode, 0, n+1)
ldr := c.Leader(time.Second)
if ldr != nil {
r = append(r, ldr)
}
if len(r) >= n {
return r
}
for _, node := range c.nodes {
if !containsNode(r, node) {
r = append(r, node)
if len(r) >= n {
return r
}
}
}
return r
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L357-L365
|
func (ap Approvers) GetCurrentApproversSetCased() sets.String {
currentApprovers := sets.NewString()
for _, approval := range ap.approvers {
currentApprovers.Insert(approval.Login)
}
return currentApprovers
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3723-L3727
|
func (v GetFrameTreeReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage40(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/object.go#L78-L85
|
func (o *Object) GetMetadata(key string) (string, error) {
data, ok := o.Metadata[key]
if !ok {
return "", fmt.Errorf("%s unexistent key", key)
}
return data.value, nil
}
|
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/password_strength.go#L62-L78
|
func MakeRequirements(password string) PasswordStrengthRequirements {
pwd := []byte(password)
reqs := PasswordStrengthRequirements{}
reqs.MaximumTotalLength = len(password)
reqs.MinimumTotalLength = len(password)
for i := range pwd {
switch {
case unicode.IsDigit(rune(pwd[i])):
reqs.Digits++
case unicode.IsUpper(rune(pwd[i])):
reqs.Uppercase++
case unicode.IsPunct(rune(pwd[i])):
reqs.Punctuation++
}
}
return reqs
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L404-L406
|
func (cd Codec) Set(c context.Context, item *Item) error {
return singleError(cd.set(c, []*Item{item}, pb.MemcacheSetRequest_SET))
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L230-L239
|
func MatchBuildFileName(dir string, names []string, files []os.FileInfo) string {
for _, name := range names {
for _, fi := range files {
if fi.Name() == name && !fi.IsDir() {
return filepath.Join(dir, name)
}
}
}
return ""
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_image.go#L826-L842
|
func (s *storageImageDestination) PutManifest(ctx context.Context, manifestBlob []byte) error {
if s.imageRef.named != nil {
if digested, ok := s.imageRef.named.(reference.Digested); ok {
matches, err := manifest.MatchesDigest(manifestBlob, digested.Digest())
if err != nil {
return err
}
if !matches {
return fmt.Errorf("Manifest does not match expected digest %s", digested.Digest())
}
}
}
s.manifest = make([]byte, len(manifestBlob))
copy(s.manifest, manifestBlob)
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/txn_command.go#L45-L66
|
func txnCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 0 {
ExitWithError(ExitBadArgs, fmt.Errorf("txn command does not accept argument"))
}
reader := bufio.NewReader(os.Stdin)
txn := mustClientFromCmd(cmd).Txn(context.Background())
promptInteractive("compares:")
txn.If(readCompares(reader)...)
promptInteractive("success requests (get, put, del):")
txn.Then(readOps(reader)...)
promptInteractive("failure requests (get, put, del):")
txn.Else(readOps(reader)...)
resp, err := txn.Commit()
if err != nil {
ExitWithError(ExitError, err)
}
display.Txn(*resp)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.