_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/sessionauth/login.go#L92-L97
|
func LoginRequired(r render.Render, user User, req *http.Request) {
if user.IsAuthenticated() == false {
path := fmt.Sprintf("%s?%s=%s", RedirectUrl, RedirectParam, req.URL.Path)
r.Redirect(path, 302)
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L5103-L5107
|
func (v *GetInlineStylesForNodeParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss44(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/images.go#L999-L1122
|
func autoUpdateImage(d *Daemon, op *operation, id int, info *api.Image, project string) error {
fingerprint := info.Fingerprint
_, source, err := d.cluster.ImageSourceGet(id)
if err != nil {
logger.Error("Error getting source image", log.Ctx{"err": err, "fp": fingerprint})
return err
}
// Get the IDs of all storage pools on which a storage volume
// for the requested image currently exists.
poolIDs, err := d.cluster.ImageGetPools(fingerprint)
if err != nil {
logger.Error("Error getting image pools", log.Ctx{"err": err, "fp": fingerprint})
return err
}
// Translate the IDs to poolNames.
poolNames, err := d.cluster.ImageGetPoolNamesFromIDs(poolIDs)
if err != nil {
logger.Error("Error getting image pools", log.Ctx{"err": err, "fp": fingerprint})
return err
}
// If no optimized pools at least update the base store
if len(poolNames) == 0 {
poolNames = append(poolNames, "")
}
logger.Debug("Processing image", log.Ctx{"fp": fingerprint, "server": source.Server, "protocol": source.Protocol, "alias": source.Alias})
// Set operation metadata to indicate whether a refresh happened
setRefreshResult := func(result bool) {
if op == nil {
return
}
metadata := map[string]interface{}{"refreshed": result}
op.UpdateMetadata(metadata)
}
// Update the image on each pool where it currently exists.
hash := fingerprint
for _, poolName := range poolNames {
newInfo, err := d.ImageDownload(op, source.Server, source.Protocol, source.Certificate, "", source.Alias, false, true, poolName, false, project)
if err != nil {
logger.Error("Failed to update the image", log.Ctx{"err": err, "fp": fingerprint})
continue
}
hash = newInfo.Fingerprint
if hash == fingerprint {
logger.Debug("Already up to date", log.Ctx{"fp": fingerprint})
continue
}
newId, _, err := d.cluster.ImageGet("default", hash, false, true)
if err != nil {
logger.Error("Error loading image", log.Ctx{"err": err, "fp": hash})
continue
}
if info.Cached {
err = d.cluster.ImageLastAccessInit(hash)
if err != nil {
logger.Error("Error setting cached flag", log.Ctx{"err": err, "fp": hash})
continue
}
}
err = d.cluster.ImageLastAccessUpdate(hash, info.LastUsedAt)
if err != nil {
logger.Error("Error setting last use date", log.Ctx{"err": err, "fp": hash})
continue
}
err = d.cluster.ImageAliasesMove(id, newId)
if err != nil {
logger.Error("Error moving aliases", log.Ctx{"err": err, "fp": hash})
continue
}
// If we do have optimized pools, make sure we remove
// the volumes associated with the image.
if poolName != "" {
err = doDeleteImageFromPool(d.State(), fingerprint, poolName)
if err != nil {
logger.Error("Error deleting image from pool", log.Ctx{"err": err, "fp": fingerprint})
}
}
}
// Image didn't change, nothing to do.
if hash == fingerprint {
setRefreshResult(false)
return nil
}
// Remove main image file.
fname := filepath.Join(d.os.VarDir, "images", fingerprint)
if shared.PathExists(fname) {
err = os.Remove(fname)
if err != nil {
logger.Debugf("Error deleting image file %s: %s", fname, err)
}
}
// Remove the rootfs file for the image.
fname = filepath.Join(d.os.VarDir, "images", fingerprint) + ".rootfs"
if shared.PathExists(fname) {
err = os.Remove(fname)
if err != nil {
logger.Debugf("Error deleting image file %s: %s", fname, err)
}
}
// Remove the database entry for the image.
if err = d.cluster.ImageDelete(id); err != nil {
logger.Debugf("Error deleting image from database %s: %s", fname, err)
}
setRefreshResult(true)
return nil
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L132-L138
|
func LoadData(path, pkg string, data []byte) (*File, error) {
ast, err := bzl.ParseBuild(path, data)
if err != nil {
return nil, err
}
return ScanAST(pkg, ast), nil
}
|
https://github.com/coreos/go-semver/blob/e214231b295a8ea9479f11b70b35d5acf3556d9b/semver/semver.go#L165-L167
|
func (v Version) Slice() []int64 {
return []int64{v.Major, v.Minor, v.Patch}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/types.go#L457-L460
|
func (j *ProwJob) SetComplete() {
j.Status.CompletionTime = new(metav1.Time)
*j.Status.CompletionTime = metav1.Now()
}
|
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/parsed_query.go#L48-L70
|
func (pq *ParsedQuery) GenerateQuery(bindVariables map[string]*querypb.BindVariable, extras map[string]Encodable) ([]byte, error) {
if len(pq.bindLocations) == 0 {
return []byte(pq.Query), nil
}
buf := bytes.NewBuffer(make([]byte, 0, len(pq.Query)))
current := 0
for _, loc := range pq.bindLocations {
buf.WriteString(pq.Query[current:loc.offset])
name := pq.Query[loc.offset : loc.offset+loc.length]
if encodable, ok := extras[name[1:]]; ok {
encodable.EncodeSQL(buf)
} else {
supplied, _, err := FetchBindVar(name, bindVariables)
if err != nil {
return nil, err
}
EncodeValue(buf, supplied)
}
current = loc.offset + loc.length
}
buf.WriteString(pq.Query[current:])
return buf.Bytes(), nil
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/util.go#L13-L19
|
func ToInterfaceSlice(slice []string) []interface{} {
result := make([]interface{}, len(slice))
for i, v := range slice {
result[i] = v
}
return result
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/options.go#L456-L481
|
func Reporter(r interface {
// PushStep is called when a tree-traversal operation is performed.
// The PathStep itself is only valid until the step is popped.
// The PathStep.Values are valid for the duration of the entire traversal
// and must not be mutated.
//
// Equal always calls PushStep at the start to provide an operation-less
// PathStep used to report the root values.
//
// Within a slice, the exact set of inserted, removed, or modified elements
// is unspecified and may change in future implementations.
// The entries of a map are iterated through in an unspecified order.
PushStep(PathStep)
// Report is called exactly once on leaf nodes to report whether the
// comparison identified the node as equal, unequal, or ignored.
// A leaf node is one that is immediately preceded by and followed by
// a pair of PushStep and PopStep calls.
Report(Result)
// PopStep ascends back up the value tree.
// There is always a matching pop call for every push call.
PopStep()
}) Option {
return reporter{r}
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive.go#L95-L134
|
func findSig(br *bufio.Reader) (int, error) {
for n := 0; n <= maxSfxSize; {
b, err := br.ReadSlice(sigPrefix[0])
n += len(b)
if err == bufio.ErrBufferFull {
continue
} else if err != nil {
if err == io.EOF {
err = errNoSig
}
return 0, err
}
b, err = br.Peek(len(sigPrefix[1:]) + 2)
if err != nil {
if err == io.EOF {
err = errNoSig
}
return 0, err
}
if !bytes.HasPrefix(b, []byte(sigPrefix[1:])) {
continue
}
b = b[len(sigPrefix)-1:]
var ver int
switch {
case b[0] == 0:
ver = fileFmt15
case b[0] == 1 && b[1] == 0:
ver = fileFmt50
default:
continue
}
_, _ = br.ReadSlice('\x00')
return ver, nil
}
return 0, errNoSig
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/region.go#L128-L133
|
func (r region) SlicePtr() region {
if r.typ.Kind != KindSlice {
panic("can't Ptr a non-slice")
}
return region{p: r.p, a: r.a, typ: &Type{Name: "*" + r.typ.Name[2:], Size: r.p.proc.PtrSize(), Kind: KindPtr, Elem: r.typ.Elem}}
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/mapping.go#L69-L74
|
func (m *Mapping) OrigSource() (string, int64) {
if m.origF == nil {
return "", 0
}
return m.origF.Name(), m.origOff
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L561-L565
|
func (v RequestCacheNamesReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCachestorage4(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L367-L376
|
func OpenReader(name, password string) (*ReadCloser, error) {
v, err := openVolume(name, password)
if err != nil {
return nil, err
}
rc := new(ReadCloser)
rc.v = v
rc.Reader.init(v)
return rc, nil
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L39-L48
|
func (img *IplImage) InitHeader(w, h, depth, channels, origin, align int) {
C.cvInitImageHeader(
(*C.IplImage)(img),
C.cvSize(C.int(w), C.int(h)),
C.int(depth),
C.int(channels),
C.int(origin),
C.int(align),
)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/connect.go#L21-L34
|
func Connect(address string, cert *shared.CertInfo, notify bool) (lxd.ContainerServer, error) {
args := &lxd.ConnectionArgs{
TLSServerCert: string(cert.PublicKey()),
TLSClientCert: string(cert.PublicKey()),
TLSClientKey: string(cert.PrivateKey()),
SkipGetServer: true,
}
if notify {
args.UserAgent = "lxd-cluster-notifier"
}
url := fmt.Sprintf("https://%s", address)
return lxd.ConnectLXD(url, args)
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/internal/diff/diff.go#L35-L52
|
func (es EditScript) String() string {
b := make([]byte, len(es))
for i, e := range es {
switch e {
case Identity:
b[i] = '.'
case UniqueX:
b[i] = 'X'
case UniqueY:
b[i] = 'Y'
case Modified:
b[i] = 'M'
default:
panic("invalid edit-type")
}
}
return string(b)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L3930-L3934
|
func (v *EventScriptFailedToParse) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger38(&r, v)
return r.Error()
}
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/parse.go#L105-L115
|
func walkFields(v reflect.Value, visit func(field reflect.StructField, val reflect.Value, owner reflect.Type) bool) {
t := v.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
val := v.Field(i)
expand := visit(field, val, t)
if expand && field.Type.Kind() == reflect.Struct {
walkFields(val, visit)
}
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L433-L442
|
func (p *GetTargetsParams) Do(ctx context.Context) (targetInfos []*Info, err error) {
// execute
var res GetTargetsReturns
err = cdp.Execute(ctx, CommandGetTargets, nil, &res)
if err != nil {
return nil, err
}
return res.TargetInfos, nil
}
|
https://github.com/wawandco/fako/blob/c36a0bc97398c9100daa83ebef1c4e7af32c7654/fakers.go#L138-L159
|
func fuzzValueFor(kind reflect.Kind) reflect.Value {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
switch kind {
case reflect.String:
return reflect.ValueOf(randomString(25))
case reflect.Int:
return reflect.ValueOf(r.Int())
case reflect.Int32:
return reflect.ValueOf(r.Int31())
case reflect.Int64:
return reflect.ValueOf(r.Int63())
case reflect.Float32:
return reflect.ValueOf(r.Float32())
case reflect.Float64:
return reflect.ValueOf(r.Float64())
case reflect.Bool:
val := r.Intn(2) > 0
return reflect.ValueOf(val)
}
return reflect.ValueOf("")
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/status.go#L62-L90
|
func makePeerStatusSlice(peers *Peers) []PeerStatus {
var slice []PeerStatus
peers.forEach(func(peer *Peer) {
var connections []connectionStatus
if peer == peers.ourself.Peer {
for conn := range peers.ourself.getConnections() {
connections = append(connections, makeConnectionStatus(conn))
}
} else {
// Modifying peer.connections requires a write lock on
// Peers, and since we are holding a read lock (due to the
// ForEach), access without locking the peer is safe.
for _, conn := range peer.connections {
connections = append(connections, makeConnectionStatus(conn))
}
}
slice = append(slice, PeerStatus{
peer.Name.String(),
peer.NickName,
peer.UID,
peer.ShortID,
peer.Version,
connections,
})
})
return slice
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L476-L479
|
func (p SynthesizeScrollGestureParams) WithXOverscroll(xOverscroll float64) *SynthesizeScrollGestureParams {
p.XOverscroll = xOverscroll
return &p
}
|
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/options/dag.go#L56-L61
|
func (dagOpts) Kind(kind string) DagPutOption {
return func(opts *DagPutSettings) error {
opts.Kind = kind
return nil
}
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nodetable/table.go#L162-L209
|
func (nt *NodeTable) Remove(key []byte) (success bool, nptr unsafe.Pointer) {
res := nt.find(key)
if res.status&ntFoundMask == ntFoundMask {
success = true
if res.status == ntFoundInFast {
nptr = decodePointer(res.fastHTValue)
// Key needs to be removed from fastHT. For that we need to move
// an item present in slowHT and overwrite fastHT entry.
if res.hasConflict {
slowHTValues := nt.slowHT[res.hash]
v := slowHTValues[0] // New fastHT candidate
slowHTValues = append([]uint64(nil), slowHTValues[1:]...)
nt.slowHTCount--
var conflict bool
if len(slowHTValues) == 0 {
delete(nt.slowHT, res.hash)
nt.conflicts--
} else {
conflict = true
nt.slowHT[res.hash] = slowHTValues
}
nt.fastHT[res.hash] = encodePointer(decodePointer(v), conflict)
} else {
delete(nt.fastHT, res.hash)
nt.fastHTCount--
}
} else {
nptr = decodePointer(res.slowHTValues[res.slowHTPos])
// Remove key from slowHT
newSlowValue := append([]uint64(nil), res.slowHTValues[:res.slowHTPos]...)
if res.slowHTPos+1 != len(res.slowHTValues) {
newSlowValue = append(newSlowValue, res.slowHTValues[res.slowHTPos+1:]...)
}
nt.slowHTCount--
if len(newSlowValue) == 0 {
delete(nt.slowHT, res.hash)
nt.fastHT[res.hash] = encodePointer(decodePointer(nt.fastHT[res.hash]), false)
nt.conflicts--
} else {
nt.slowHT[res.hash] = newSlowValue
}
}
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L271-L273
|
func (p *DiscardConsoleEntriesParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandDiscardConsoleEntries, nil, nil)
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/export_unsafe.go#L21-L23
|
func retrieveUnexportedField(v reflect.Value, f reflect.StructField) reflect.Value {
return reflect.NewAt(f.Type, unsafe.Pointer(v.UnsafeAddr()+f.Offset)).Elem()
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/module.go#L98-L100
|
func (t *funcTab) add(min, max core.Address, f *Func) {
t.entries = append(t.entries, funcTabEntry{min: min, max: max, f: f})
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/access_barrier.go#L77-L82
|
func CompareBS(this, that unsafe.Pointer) int {
thisItm := (*BarrierSession)(this)
thatItm := (*BarrierSession)(that)
return int(thisItm.seqno) - int(thatItm.seqno)
}
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/http_client.go#L31-L49
|
func ClientWithTimeout(timeout time.Duration) *http.Client {
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: func(netw, addr string) (net.Conn, error) {
c, err := net.DialTimeout(netw, addr, timeout)
if err != nil {
return nil, err
}
if tc, ok := c.(*net.TCPConn); ok {
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(timeout)
}
return &deadlineConn{timeout, c}, nil
},
ResponseHeaderTimeout: timeout,
MaxIdleConnsPerHost: 10,
}
return &http.Client{Transport: transport}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L4547-L4551
|
func (v *GetMediaQueriesParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss40(&r, v)
return r.Error()
}
|
https://github.com/google/subcommands/blob/d47216cd17848d55a33e6f651cbe408243ed55b8/subcommands.go#L113-L115
|
func (cdr *Commander) ImportantFlag(name string) {
cdr.important = append(cdr.important, name)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/ioutil/pagewriter.go#L43-L51
|
func NewPageWriter(w io.Writer, pageBytes, pageOffset int) *PageWriter {
return &PageWriter{
w: w,
pageOffset: pageOffset,
pageBytes: pageBytes,
buf: make([]byte, defaultBufferBytes+pageBytes),
bufWatermarkBytes: defaultBufferBytes,
}
}
|
https://github.com/apparentlymart/go-rundeck-api/blob/2c962acae81080a937c350a5bea054c239f27a81/rundeck/job.go#L317-L324
|
func (c *Client) GetJobsForProject(projectName string) ([]JobDetail, error) {
jobList := &jobDetailList{}
err := c.get([]string{"jobs", "export"}, map[string]string{"project": projectName}, jobList)
if err != nil {
return nil, err
}
return jobList.Jobs, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/easyjson.go#L808-L812
|
func (v *EventDomStorageItemRemoved) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomstorage7(&r, v)
return r.Error()
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/bytecode.go#L32-L34
|
func (b *ByteCode) Append(op Op) {
b.OpList = append(b.OpList, op)
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/io/flushing_writer.go#L60-L65
|
func (w *FlushingWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hijacker, ok := w.ResponseWriter.(http.Hijacker); ok {
return hijacker.Hijack()
}
return nil, nil, errors.New("cannot hijack connection")
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/helpers.go#L191-L197
|
func toStringArray(a []interface{}) []string {
res := make([]string, len(a))
for i, v := range a {
res[i] = fmt.Sprintf("%v", v)
}
return res
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/router/router.go#L75-L89
|
func Get(name string) (Router, error) {
routerType, prefix, err := Type(name)
if err != nil {
return nil, &ErrRouterNotFound{Name: name}
}
factory, ok := routers[routerType]
if !ok {
return nil, errors.Errorf("unknown router: %q.", routerType)
}
r, err := factory(name, prefix)
if err != nil {
return nil, err
}
return r, nil
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L125-L128
|
func (p MailBuilder) Text(body []byte) MailBuilder {
p.text = body
return p
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/replication.go#L434-L453
|
func (r *Raft) pipelineSend(s *followerReplication, p AppendPipeline, nextIdx *uint64, lastIndex uint64) (shouldStop bool) {
// Create a new append request
req := new(AppendEntriesRequest)
if err := r.setupAppendEntries(s, req, *nextIdx, lastIndex); err != nil {
return true
}
// Pipeline the append entries
if _, err := p.AppendEntries(req, new(AppendEntriesResponse)); err != nil {
r.logger.Error(fmt.Sprintf("Failed to pipeline AppendEntries to %v: %v", s.peer, err))
return true
}
// Increase the next send log to avoid re-sending old logs
if n := len(req.Entries); n > 0 {
last := req.Entries[n-1]
*nextIdx = last.Index + 1
}
return false
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2657-L2666
|
func NewPaymentResult(code PaymentResultCode, value interface{}) (result PaymentResult, err error) {
result.Code = code
switch PaymentResultCode(code) {
case PaymentResultCodePaymentSuccess:
// void
default:
// void
}
return
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/label_sync/main.go#L224-L247
|
func (c Configuration) Labels() []Label {
var labelarrays [][]Label
labelarrays = append(labelarrays, c.Default.Labels)
for _, repo := range c.Repos {
labelarrays = append(labelarrays, repo.Labels)
}
labelmap := make(map[string]Label)
for _, labels := range labelarrays {
for _, l := range labels {
name := strings.ToLower(l.Name)
if _, ok := labelmap[name]; !ok {
labelmap[name] = l
}
}
}
var labels []Label
for _, label := range labelmap {
labels = append(labels, label)
}
sort.Slice(labels, func(i, j int) bool { return labels[i].Name < labels[j].Name })
return labels
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/outgoing.go#L194-L210
|
func (oa *OutgoingAudio) querystring() querystring {
toReturn := map[string]string(oa.getBaseQueryString())
if oa.Duration != 0 {
toReturn["duration"] = fmt.Sprint(oa.Duration)
}
if oa.Performer != "" {
toReturn["performer"] = oa.Performer
}
if oa.Title != "" {
toReturn["title"] = oa.Title
}
return querystring(toReturn)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L710-L713
|
func (p PrintToPDFParams) WithPaperWidth(paperWidth float64) *PrintToPDFParams {
p.PaperWidth = paperWidth
return &p
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/js.go#L23-L33
|
func (e *Engine) JavaScript(names ...string) Renderer {
if e.JavaScriptLayout != "" && len(names) == 1 {
names = append(names, e.JavaScriptLayout)
}
hr := &templateRenderer{
Engine: e,
contentType: "application/javascript",
names: names,
}
return hr
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L2350-L2363
|
func isBtrfsSubVolume(subvolPath string) bool {
fs := syscall.Stat_t{}
err := syscall.Lstat(subvolPath, &fs)
if err != nil {
return false
}
// Check if BTRFS_FIRST_FREE_OBJECTID
if fs.Ino != 256 {
return false
}
return true
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/mex.go#L116-L144
|
func (mex *messageExchange) forwardPeerFrame(frame *Frame) error {
// We want a very specific priority here:
// 1. Timeouts/cancellation (mex.ctx errors)
// 2. Whether recvCh has buffer space (non-blocking select over mex.recvCh)
// 3. Other mex errors (mex.errCh)
// Which is why we check the context error only (instead of mex.checkError).
// In the mex.errCh case, we do a non-blocking write to recvCh to prioritize it.
if err := mex.ctx.Err(); err != nil {
return GetContextError(err)
}
select {
case mex.recvCh <- frame:
return nil
case <-mex.ctx.Done():
// Note: One slow reader processing a large request could stall the connection.
// If we see this, we need to increase the recvCh buffer size.
return GetContextError(mex.ctx.Err())
case <-mex.errCh.c:
// Select will randomly choose a case, but we want to prioritize
// sending a frame over the errCh. Try a non-blocking write.
select {
case mex.recvCh <- frame:
return nil
default:
}
return mex.errCh.err
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L1259-L1263
|
func (v *Page) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHar6(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/types.go#L53-L65
|
func (t *VirtualTimePolicy) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch VirtualTimePolicy(in.String()) {
case VirtualTimePolicyAdvance:
*t = VirtualTimePolicyAdvance
case VirtualTimePolicyPause:
*t = VirtualTimePolicyPause
case VirtualTimePolicyPauseIfNetworkFetchesPending:
*t = VirtualTimePolicyPauseIfNetworkFetchesPending
default:
in.AddError(errors.New("unknown VirtualTimePolicy value"))
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/client.go#L76-L91
|
func Conns(ctx context.Context, pipelineRcName string, etcdClient *etcd.Client, etcdPrefix string, workerGrpcPort uint16) ([]*grpc.ClientConn, error) {
resp, err := etcdClient.Get(ctx, path.Join(etcdPrefix, WorkerEtcdPrefix, pipelineRcName), etcd.WithPrefix())
if err != nil {
return nil, err
}
var result []*grpc.ClientConn
for _, kv := range resp.Kvs {
conn, err := grpc.Dial(fmt.Sprintf("%s:%d", path.Base(string(kv.Key)), workerGrpcPort),
append(client.DefaultDialOptions(), grpc.WithInsecure())...)
if err != nil {
return nil, err
}
result = append(result, conn)
}
return result, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1480-L1487
|
func GlobLiteralPrefix(pattern string) string {
pattern = clean(pattern)
idx := globRegex.FindStringIndex(pattern)
if idx == nil {
return pattern
}
return pattern[:idx[0]]
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L158-L269
|
func (c *ClusterTx) ProfileList(filter ProfileFilter) ([]Profile, error) {
// Result slice.
objects := make([]Profile, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Project != "" {
criteria["Project"] = filter.Project
}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Project"] != nil && criteria["Name"] != nil {
stmt = c.stmt(profileObjectsByProjectAndName)
args = []interface{}{
filter.Project,
filter.Name,
}
} else if criteria["Project"] != nil {
stmt = c.stmt(profileObjectsByProject)
args = []interface{}{
filter.Project,
}
} else {
stmt = c.stmt(profileObjects)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, Profile{})
return []interface{}{
&objects[i].ID,
&objects[i].Project,
&objects[i].Name,
&objects[i].Description,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch profiles")
}
// Fill field Config.
configObjects, err := c.ProfileConfigRef(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch field Config")
}
for i := range objects {
_, ok := configObjects[objects[i].Project]
if !ok {
subIndex := map[string]map[string]string{}
configObjects[objects[i].Project] = subIndex
}
value := configObjects[objects[i].Project][objects[i].Name]
if value == nil {
value = map[string]string{}
}
objects[i].Config = value
}
// Fill field Devices.
devicesObjects, err := c.ProfileDevicesRef(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch field Devices")
}
for i := range objects {
_, ok := devicesObjects[objects[i].Project]
if !ok {
subIndex := map[string]map[string]map[string]string{}
devicesObjects[objects[i].Project] = subIndex
}
value := devicesObjects[objects[i].Project][objects[i].Name]
if value == nil {
value = map[string]map[string]string{}
}
objects[i].Devices = value
}
// Fill field UsedBy.
usedByObjects, err := c.ProfileUsedByRef(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch field UsedBy")
}
for i := range objects {
_, ok := usedByObjects[objects[i].Project]
if !ok {
subIndex := map[string][]string{}
usedByObjects[objects[i].Project] = subIndex
}
value := usedByObjects[objects[i].Project][objects[i].Name]
if value == nil {
value = []string{}
}
objects[i].UsedBy = value
}
return objects, nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L70-L80
|
func Stat(c context.Context, blobKey appengine.BlobKey) (*BlobInfo, error) {
c, _ = appengine.Namespace(c, "") // Blobstore is always in the empty string namespace
dskey := datastore.NewKey(c, blobInfoKind, string(blobKey), 0, nil)
bi := &BlobInfo{
BlobKey: blobKey,
}
if err := datastore.Get(c, dskey, bi); err != nil && !isErrFieldMismatch(err) {
return nil, err
}
return bi, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/clonerefs/run.go#L119-L161
|
func addSSHKeys(paths []string) ([]string, error) {
vars, err := exec.Command("ssh-agent").CombinedOutput()
if err != nil {
return []string{}, fmt.Errorf("failed to start ssh-agent: %v", err)
}
logrus.Info("Started SSH agent")
// ssh-agent will output three lines of text, in the form:
// SSH_AUTH_SOCK=xxx; export SSH_AUTH_SOCK;
// SSH_AGENT_PID=xxx; export SSH_AGENT_PID;
// echo Agent pid xxx;
// We need to parse out the environment variables from that.
parts := strings.Split(string(vars), ";")
env := []string{strings.TrimSpace(parts[0]), strings.TrimSpace(parts[2])}
for _, keyPath := range paths {
// we can be given literal paths to keys or paths to dirs
// that are mounted from a secret, so we need to check which
// we have
if err := filepath.Walk(keyPath, func(path string, info os.FileInfo, err error) error {
if strings.HasPrefix(info.Name(), "..") {
// kubernetes volumes also include files we
// should not look be looking into for keys
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
if info.IsDir() {
return nil
}
cmd := exec.Command("ssh-add", path)
cmd.Env = append(cmd.Env, env...)
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to add ssh key at %s: %v: %s", path, err, output)
}
logrus.Infof("Added SSH key at %s", path)
return nil
}); err != nil {
return env, fmt.Errorf("error walking path %q: %v", keyPath, err)
}
}
return env, nil
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer_name_mac.go#L48-L78
|
func PeerNameFromString(nameStr string) (PeerName, error) {
var a, b, c, d, e, f uint64
match := func(format string, args ...interface{}) bool {
a, b, c, d, e, f = 0, 0, 0, 0, 0, 0
n, err := fmt.Sscanf(nameStr+"\000", format+"\000", args...)
return err == nil && n == len(args)
}
switch {
case match("%2x:%2x:%2x:%2x:%2x:%2x", &a, &b, &c, &d, &e, &f):
case match("::%2x:%2x:%2x:%2x", &c, &d, &e, &f):
case match("%2x::%2x:%2x:%2x", &a, &d, &e, &f):
case match("%2x:%2x::%2x:%2x", &a, &b, &e, &f):
case match("%2x:%2x:%2x::%2x", &a, &b, &c, &f):
case match("%2x:%2x:%2x:%2x::", &a, &b, &c, &d):
case match("::%2x:%2x:%2x", &d, &e, &f):
case match("%2x::%2x:%2x", &a, &e, &f):
case match("%2x:%2x::%2x", &a, &b, &f):
case match("%2x:%2x:%2x::", &a, &b, &c):
case match("::%2x:%2x", &e, &f):
case match("%2x::%2x", &a, &f):
case match("%2x:%2x::", &a, &b):
case match("::%2x", &f):
case match("%2x::", &a):
default:
return UnknownPeerName, fmt.Errorf("invalid peer name format: %q", nameStr)
}
return PeerName(a<<40 | b<<32 | c<<24 | d<<16 | e<<8 | f), nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/cluster.go#L57-L71
|
func GetKubernetesClient(masterURL, kubeConfig string) (kubernetes.Interface, error) {
config, err := loadClusterConfig(masterURL, kubeConfig)
if err != nil {
return nil, err
}
// generate the client based off of the config
client, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
logrus.Info("Successfully constructed k8s client")
return client, nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L373-L391
|
func (d *Destination) sendFile(path string, expectedSize int64, stream io.Reader) error {
hdr, err := tar.FileInfoHeader(&tarFI{path: path, size: expectedSize}, "")
if err != nil {
return nil
}
logrus.Debugf("Sending as tar file %s", path)
if err := d.tar.WriteHeader(hdr); err != nil {
return err
}
// TODO: This can take quite some time, and should ideally be cancellable using a context.Context.
size, err := io.Copy(d.tar, stream)
if err != nil {
return err
}
if size != expectedSize {
return errors.Errorf("Size mismatch when copying %s, expected %d, got %d", path, expectedSize, size)
}
return nil
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/format/format.go#L160-L164
|
func Object(object interface{}, indentation uint) string {
indent := strings.Repeat(Indent, int(indentation))
value := reflect.ValueOf(object)
return fmt.Sprintf("%s<%s>: %s", indent, formatType(object), formatValue(value, indentation))
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/obj.go#L494-L519
|
func NewClientFromEnv(storageRoot string) (c Client, err error) {
storageBackend, ok := os.LookupEnv(StorageBackendEnvVar)
if !ok {
return nil, fmt.Errorf("storage backend environment variable not found")
}
switch storageBackend {
case Amazon:
c, err = NewAmazonClientFromEnv()
case Google:
c, err = NewGoogleClientFromEnv()
case Microsoft:
c, err = NewMicrosoftClientFromEnv()
case Minio:
c, err = NewMinioClientFromEnv()
case Local:
c, err = NewLocalClient(storageRoot)
}
switch {
case err != nil:
return nil, err
case c != nil:
return TracingObjClient(storageBackend, c), nil
default:
return nil, fmt.Errorf("unrecognized storage backend: %s", storageBackend)
}
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gexec/build.go#L36-L38
|
func BuildWithEnvironment(packagePath string, env []string, args ...string) (compiledPath string, err error) {
return doBuild(build.Default.GOPATH, packagePath, env, args...)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/bridge.go#L203-L228
|
func (b *bridge) ioCopy(dst io.Writer, src io.Reader) (err error) {
buf := make([]byte, 32*1024)
for {
select {
case <-b.blackholec:
io.Copy(ioutil.Discard, src)
return nil
default:
}
nr, er := src.Read(buf)
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
if ew != nil {
return ew
}
if nr != nw {
return io.ErrShortWrite
}
}
if er != nil {
err = er
break
}
}
return err
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/prompt.go#L38-L63
|
func PromptCmd() *cobra.Command {
var promptCmd = &cobra.Command{
Use: "prompt",
Short: "Open a prompt with auto-completion (non-Windows)",
Long: `Use this command to use the Kubicron API via a shell prompt.
This command will open a prompt using go-prompt (with auto-completion) to
allow you to run commands interactively from the shell.
Currently this doesn't work on Windows systems`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) > 0 {
logger.Critical("Too many arguments.")
os.Exit(1)
}
if err := runPrompt(); err != nil {
logger.Critical(err.Error())
os.Exit(1)
}
},
}
initializePrompt()
return promptCmd
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4039-L4048
|
func (u OperationResultTr) GetPathPaymentResult() (result PathPaymentResult, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "PathPaymentResult" {
result = *u.PathPaymentResult
ok = true
}
return
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L11093-L11100
|
func (r *Server) Locator(api *API) *ServerLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.ServerLocator(l["href"])
}
}
return nil
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/ash/enforcer.go#L27-L31
|
func GrantAccess() *Enforcer {
return E("ash/GrantAccess", fire.All(), func(_ *fire.Context) error {
return nil
})
}
|
https://github.com/gokyle/fswatch/blob/1dbdf8320a690537582afe0f45c947f501adeaad/watcher.go#L114-L134
|
func (w *Watcher) watch(sndch chan<- *Notification) {
defer func() {
recover()
}()
for {
<-time.After(WatchDelay)
for _, wi := range w.paths {
if wi.Update() && w.shouldNotify(wi) {
sndch <- wi.Notification()
}
if wi.LastEvent == NOEXIST && w.auto_watch {
delete(w.paths, wi.Path)
}
if len(w.paths) == 0 {
w.Stop()
}
}
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/raft.go#L104-L119
|
func (n *NodeTx) RaftNodesReplace(nodes []RaftNode) error {
_, err := n.tx.Exec("DELETE FROM raft_nodes")
if err != nil {
return err
}
columns := []string{"id", "address"}
for _, node := range nodes {
values := []interface{}{node.ID, node.Address}
_, err := query.UpsertObject(n.tx, "raft_nodes", columns, values)
if err != nil {
return err
}
}
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L125-L214
|
func Image(ctx context.Context, policyContext *signature.PolicyContext, destRef, srcRef types.ImageReference, options *Options) (manifest []byte, retErr error) {
// NOTE this function uses an output parameter for the error return value.
// Setting this and returning is the ideal way to return an error.
//
// the defers in this routine will wrap the error return with its own errors
// which can be valuable context in the middle of a multi-streamed copy.
if options == nil {
options = &Options{}
}
reportWriter := ioutil.Discard
if options.ReportWriter != nil {
reportWriter = options.ReportWriter
}
dest, err := destRef.NewImageDestination(ctx, options.DestinationCtx)
if err != nil {
return nil, errors.Wrapf(err, "Error initializing destination %s", transports.ImageName(destRef))
}
defer func() {
if err := dest.Close(); err != nil {
retErr = errors.Wrapf(retErr, " (dest: %v)", err)
}
}()
rawSource, err := srcRef.NewImageSource(ctx, options.SourceCtx)
if err != nil {
return nil, errors.Wrapf(err, "Error initializing source %s", transports.ImageName(srcRef))
}
defer func() {
if err := rawSource.Close(); err != nil {
retErr = errors.Wrapf(retErr, " (src: %v)", err)
}
}()
// If reportWriter is not a TTY (e.g., when piping to a file), do not
// print the progress bars to avoid long and hard to parse output.
// createProgressBar() will print a single line instead.
progressOutput := reportWriter
if !isTTY(reportWriter) {
progressOutput = ioutil.Discard
}
copyInParallel := dest.HasThreadSafePutBlob() && rawSource.HasThreadSafeGetBlob()
c := &copier{
dest: dest,
rawSource: rawSource,
reportWriter: reportWriter,
progressOutput: progressOutput,
progressInterval: options.ProgressInterval,
progress: options.Progress,
copyInParallel: copyInParallel,
// FIXME? The cache is used for sources and destinations equally, but we only have a SourceCtx and DestinationCtx.
// For now, use DestinationCtx (because blob reuse changes the behavior of the destination side more); eventually
// we might want to add a separate CommonCtx — or would that be too confusing?
blobInfoCache: blobinfocache.DefaultCache(options.DestinationCtx),
}
unparsedToplevel := image.UnparsedInstance(rawSource, nil)
multiImage, err := isMultiImage(ctx, unparsedToplevel)
if err != nil {
return nil, errors.Wrapf(err, "Error determining manifest MIME type for %s", transports.ImageName(srcRef))
}
if !multiImage {
// The simple case: Just copy a single image.
if manifest, err = c.copyOneImage(ctx, policyContext, options, unparsedToplevel); err != nil {
return nil, err
}
} else {
// This is a manifest list. Choose a single image and copy it.
// FIXME: Copy to destinations which support manifest lists, one image at a time.
instanceDigest, err := image.ChooseManifestInstanceFromManifestList(ctx, options.SourceCtx, unparsedToplevel)
if err != nil {
return nil, errors.Wrapf(err, "Error choosing an image from manifest list %s", transports.ImageName(srcRef))
}
logrus.Debugf("Source is a manifest list; copying (only) instance %s", instanceDigest)
unparsedInstance := image.UnparsedInstance(rawSource, &instanceDigest)
if manifest, err = c.copyOneImage(ctx, policyContext, options, unparsedInstance); err != nil {
return nil, err
}
}
if err := c.dest.Commit(ctx); err != nil {
return nil, errors.Wrap(err, "Error committing the finished image")
}
return manifest, nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/table.go#L120-L189
|
func OpenTable(fd *os.File, mode options.FileLoadingMode, cksum []byte) (*Table, error) {
fileInfo, err := fd.Stat()
if err != nil {
// It's OK to ignore fd.Close() errs in this function because we have only read
// from the file.
_ = fd.Close()
return nil, y.Wrap(err)
}
filename := fileInfo.Name()
id, ok := ParseFileID(filename)
if !ok {
_ = fd.Close()
return nil, errors.Errorf("Invalid filename: %s", filename)
}
t := &Table{
fd: fd,
ref: 1, // Caller is given one reference.
id: id,
loadingMode: mode,
}
t.tableSize = int(fileInfo.Size())
// We first load to RAM, so we can read the index and do checksum.
if err := t.loadToRAM(); err != nil {
return nil, err
}
// Enforce checksum before we read index. Otherwise, if the file was
// truncated, we'd end up with panics in readIndex.
if len(cksum) > 0 && !bytes.Equal(t.Checksum, cksum) {
return nil, fmt.Errorf(
"CHECKSUM_MISMATCH: Table checksum does not match checksum in MANIFEST."+
" NOT including table %s. This would lead to missing data."+
"\n sha256 %x Expected\n sha256 %x Found\n", filename, cksum, t.Checksum)
}
if err := t.readIndex(); err != nil {
return nil, y.Wrap(err)
}
it := t.NewIterator(false)
defer it.Close()
it.Rewind()
if it.Valid() {
t.smallest = it.Key()
}
it2 := t.NewIterator(true)
defer it2.Close()
it2.Rewind()
if it2.Valid() {
t.biggest = it2.Key()
}
switch mode {
case options.LoadToRAM:
// No need to do anything. t.mmap is already filled.
case options.MemoryMap:
t.mmap, err = y.Mmap(fd, false, fileInfo.Size())
if err != nil {
_ = fd.Close()
return nil, y.Wrapf(err, "Unable to map file")
}
case options.FileIO:
t.mmap = nil
default:
panic(fmt.Sprintf("Invalid loading mode: %v", mode))
}
return t, nil
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L346-L348
|
func (l *Logger) Warn(args ...interface{}) {
l.Output(2, LevelWarn, fmt.Sprint(args...))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2806-L2810
|
func (v *GetHeapUsageReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime25(&r, v)
return r.Error()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/version/api_server.go#L32-L34
|
func NewAPIServer(version *pb.Version, options APIServerOptions) pb.APIServer {
return newAPIServer(version, options)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/none/none.go#L47-L49
|
func (noCache) CandidateLocations(transport types.ImageTransport, scope types.BICTransportScope, digest digest.Digest, canSubstitute bool) []types.BICReplacementCandidate {
return nil
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L55-L62
|
func newTCPCryptoState(sessionKey *[32]byte, outbound bool) *tcpCryptoState {
s := &tcpCryptoState{sessionKey: sessionKey}
if outbound {
s.nonce[0] |= (1 << 7)
}
s.nonce[0] |= (1 << 6)
return s
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/fileseq.go#L219-L236
|
func toRange(start, end, step int) []int {
nums := []int{}
if step < 1 {
step = 1
}
if start <= end {
for i := start; i <= end; {
nums = append(nums, i)
i += step
}
} else {
for i := start; i >= end; {
nums = append(nums, i)
i -= step
}
}
return nums
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/nic.go#L86-L91
|
func (c *Client) DeleteNic(dcid, srvid, nicid string) (*http.Header, error) {
url := nicPath(dcid, srvid, nicid)
ret := &http.Header{}
err := c.client.Delete(url, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L573-L577
|
func (v *RequestCacheNamesReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCachestorage4(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L711-L720
|
func (p *SetBreakpointByURLParams) Do(ctx context.Context) (breakpointID BreakpointID, locations []*Location, err error) {
// execute
var res SetBreakpointByURLReturns
err = cdp.Execute(ctx, CommandSetBreakpointByURL, p, &res)
if err != nil {
return "", nil, err
}
return res.BreakpointID, res.Locations, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/platform.go#L32-L84
|
func platformAdd(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
name := InputValue(r, "name")
file, _, err := r.FormFile("dockerfile_content")
if err != nil {
return &tErrors.HTTP{Code: http.StatusBadRequest, Message: err.Error()}
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
return err
}
if len(data) == 0 {
return &tErrors.HTTP{Code: http.StatusBadRequest, Message: appTypes.ErrMissingFileContent.Error()}
}
args := make(map[string]string)
for key, values := range r.Form {
args[key] = values[0]
}
canCreatePlatform := permission.Check(t, permission.PermPlatformCreate)
if !canCreatePlatform {
return permission.ErrUnauthorized
}
w.Header().Set("Content-Type", "application/x-json-stream")
keepAliveWriter := io.NewKeepAliveWriter(w, 30*time.Second, "")
defer keepAliveWriter.Stop()
writer := &io.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypePlatform, Value: name},
Kind: permission.PermPlatformCreate,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermPlatformReadEvents),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
evt.SetLogWriter(writer)
ctx, cancel := evt.CancelableContext(context.Background())
err = servicemanager.Platform.Create(appTypes.PlatformOptions{
Name: name,
Args: args,
Data: data,
Output: evt,
Ctx: ctx,
})
cancel()
if err != nil {
return err
}
writer.Write([]byte("Platform successfully added!\n"))
return nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/action/action.go#L98-L114
|
func NewPipeline(actions ...*Action) *Pipeline {
// Actions are usually global functions, copying them
// guarantees each copy has an isolated Result.
newActions := make([]*Action, len(actions))
for i, action := range actions {
newAction := &Action{
Name: action.Name,
Forward: action.Forward,
Backward: action.Backward,
MinParams: action.MinParams,
OnError: action.OnError,
}
newActions[i] = newAction
}
return &Pipeline{actions: newActions}
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/docker/scheduler.go#L183-L200
|
func (s *segregatedScheduler) aggregateContainersBy(matcher bson.M) (map[string]int, error) {
coll := s.provisioner.Collection()
defer coll.Close()
pipe := coll.Pipe([]bson.M{
matcher,
{"$group": bson.M{"_id": "$hostaddr", "count": bson.M{"$sum": 1}}},
})
var results []nodeAggregate
err := pipe.All(&results)
if err != nil {
return nil, err
}
countMap := make(map[string]int)
for _, result := range results {
countMap[result.HostAddr] = result.Count
}
return countMap, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/domstorage.go#L159-L161
|
func (p *SetDOMStorageItemParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetDOMStorageItem, p, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L870-L874
|
func (v *KeyframeStyle) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoAnimation8(&r, v)
return r.Error()
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/autoscale.go#L106-L132
|
func autoScaleDeleteRule(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
allowedDeleteRule := permission.Check(t, permission.PermNodeAutoscale)
if !allowedDeleteRule {
return permission.ErrUnauthorized
}
rulePool := r.URL.Query().Get(":id")
var ctxs []permTypes.PermissionContext
if rulePool != "" {
ctxs = append(ctxs, permission.Context(permTypes.CtxPool, rulePool))
}
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypePool, Value: rulePool},
Kind: permission.PermNodeAutoscaleDelete,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermPoolReadEvents, ctxs...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
err = autoscale.DeleteRule(rulePool)
if err == mgo.ErrNotFound {
return &tsuruErrors.HTTP{Code: http.StatusNotFound, Message: "rule not found"}
}
return nil
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/deep_copy.go#L18-L26
|
func DeepCopy(o interface{}) (r interface{}) {
if o == nil {
return nil
}
src := reflect.ValueOf(o)
dst := reflect.New(src.Type()).Elem()
deepCopy(src, dst)
return dst.Interface()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/watchable_store.go#L409-L433
|
func kvsToEvents(lg *zap.Logger, wg *watcherGroup, revs, vals [][]byte) (evs []mvccpb.Event) {
for i, v := range vals {
var kv mvccpb.KeyValue
if err := kv.Unmarshal(v); err != nil {
if lg != nil {
lg.Panic("failed to unmarshal mvccpb.KeyValue", zap.Error(err))
} else {
plog.Panicf("cannot unmarshal event: %v", err)
}
}
if !wg.contains(string(kv.Key)) {
continue
}
ty := mvccpb.PUT
if isTombstone(revs[i]) {
ty = mvccpb.DELETE
// patch in mod revision so watchers won't skip
kv.ModRevision = bytesToRev(revs[i]).main
}
evs = append(evs, mvccpb.Event{Kv: &kv, Type: ty})
}
return evs
}
|
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/memory.go#L146-L154
|
func NewChannelMemoryBackend(size int) *ChannelMemoryBackend {
backend := &ChannelMemoryBackend{
maxSize: size,
incoming: make(chan *Record, 1024),
events: make(chan event),
}
backend.Start()
return backend
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/logger.go#L58-L63
|
func (opt *Options) Debugf(format string, v ...interface{}) {
if opt.Logger == nil {
return
}
opt.Logger.Debugf(format, v...)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L618-L626
|
func (r *ProtocolLXD) UpdateImage(fingerprint string, image api.ImagePut, ETag string) error {
// Send the request
_, _, err := r.query("PUT", fmt.Sprintf("/images/%s", url.QueryEscape(fingerprint)), image, ETag)
if err != nil {
return err
}
return nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/auth.go#L642-L656
|
func listKeys(w http.ResponseWriter, r *http.Request, t auth.Token) error {
u, err := auth.ConvertNewUser(t.User())
if err != nil {
return err
}
keys, err := u.ListKeys()
if err == authTypes.ErrKeyDisabled {
return &errors.HTTP{Code: http.StatusBadRequest, Message: err.Error()}
}
if err != nil {
return err
}
w.Header().Add("Content-Type", "application/json")
return json.NewEncoder(w).Encode(keys)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L70-L74
|
func (v *StepOverParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger(&r, v)
return r.Error()
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/patch_apps_app_parameters.go#L117-L120
|
func (o *PatchAppsAppParams) WithApp(app string) *PatchAppsAppParams {
o.SetApp(app)
return o
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/watcher_hub.go#L180-L186
|
func (wh *watcherHub) clone() *watcherHub {
clonedHistory := wh.EventHistory.clone()
return &watcherHub{
EventHistory: clonedHistory,
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/watcher_hub.go#L123-L139
|
func (wh *watcherHub) notify(e *Event) {
e = wh.EventHistory.addEvent(e) // add event into the eventHistory
segments := strings.Split(e.Node.Key, "/")
currPath := "/"
// walk through all the segments of the path and notify the watchers
// if the path is "/foo/bar", it will notify watchers with path "/",
// "/foo" and "/foo/bar"
for _, segment := range segments {
currPath = path.Join(currPath, segment)
// notify the watchers who interests in the changes of current path
wh.notifyWatchers(e, currPath, false)
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/connection.go#L751-L809
|
func (c *Connection) checkExchanges() {
c.callOnExchangeChange()
moveState := func(fromState, toState connectionState) bool {
err := c.withStateLock(func() error {
if c.state != fromState {
return errors.New("")
}
c.state = toState
return nil
})
return err == nil
}
curState := c.readState()
origState := curState
if curState != connectionClosed && c.stoppedExchanges.Load() {
if moveState(curState, connectionClosed) {
curState = connectionClosed
}
}
if curState == connectionStartClose {
if !c.relay.canClose() {
return
}
if c.inbound.count() == 0 && moveState(connectionStartClose, connectionInboundClosed) {
curState = connectionInboundClosed
}
}
if curState == connectionInboundClosed {
// Safety check -- this should never happen since we already did the check
// when transitioning to connectionInboundClosed.
if !c.relay.canClose() {
c.relay.logger.Error("Relay can't close even though state is InboundClosed.")
return
}
if c.outbound.count() == 0 && moveState(connectionInboundClosed, connectionClosed) {
curState = connectionClosed
}
}
if curState != origState {
// If the connection is closed, we can notify writeFrames to stop which
// closes the underlying network connection. We never close sendCh to avoid
// races causing panics, see 93ef5c112c8b321367ae52d2bd79396e2e874f31
if curState == connectionClosed {
close(c.stopCh)
}
c.log.WithFields(
LogField{"newState", curState},
).Debug("Connection state updated during shutdown.")
c.callOnCloseStateChange()
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L241-L248
|
func (w *WriteBuffer) WriteUvarint(n uint64) {
// A uvarint could be up to 10 bytes long.
buf := make([]byte, 10)
varBytes := binary.PutUvarint(buf, n)
if b := w.reserve(varBytes); b != nil {
copy(b, buf[0:varBytes])
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L298-L302
|
func (v *SetShowHitTestBordersParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoOverlay3(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L307-L314
|
func (in *UtilityImages) DeepCopy() *UtilityImages {
if in == nil {
return nil
}
out := new(UtilityImages)
in.DeepCopyInto(out)
return out
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/deviceorientation/easyjson.go#L93-L97
|
func (v SetDeviceOrientationOverrideParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDeviceorientation(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.