_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/fetcher/fetcher_github.go#L46-L64
|
func (h *Github) Init() error {
//apply defaults
if h.User == "" {
return fmt.Errorf("User required")
}
if h.Repo == "" {
return fmt.Errorf("Repo required")
}
if h.Asset == nil {
h.Asset = h.defaultAsset
}
h.releaseURL = "https://api.github.com/repos/" + h.User + "/" + h.Repo + "/releases/latest"
if h.Interval == 0 {
h.Interval = 5 * time.Minute
} else if h.Interval < 1*time.Minute {
log.Printf("[overseer.github] warning: intervals less than 1 minute will surpass the public rate limit")
}
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/archive/oci_dest.go#L20-L35
|
func newImageDestination(ctx context.Context, sys *types.SystemContext, ref ociArchiveReference) (types.ImageDestination, error) {
tempDirRef, err := createOCIRef(ref.image)
if err != nil {
return nil, errors.Wrapf(err, "error creating oci reference")
}
unpackedDest, err := tempDirRef.ociRefExtracted.NewImageDestination(ctx, sys)
if err != nil {
if err := tempDirRef.deleteTempDir(); err != nil {
return nil, errors.Wrapf(err, "error deleting temp directory %q", tempDirRef.tempDirectory)
}
return nil, err
}
return &ociArchiveImageDestination{ref: ref,
unpackedDest: unpackedDest,
tempDirRef: tempDirRef}, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2646-L2650
|
func (v *MoveToReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom29(&r, v)
return r.Error()
}
|
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/opts.go#L45-L50
|
func EntriesService(service *logging.EntriesService) Option {
return func(sh *StackdriverHook) error {
sh.service = service
return nil
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/simplestreams_images.go#L231-L238
|
func (r *ProtocolSimpleStreams) GetImageAlias(name string) (*api.ImageAliasesEntry, string, error) {
alias, err := r.ssClient.GetAlias(name)
if err != nil {
return nil, "", err
}
return alias, "", err
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/grpc.go#L124-L131
|
func ToGRPC(in error) error {
if err, ok := in.(Error); ok {
attrs, _ := json.Marshal(err.Attributes())
return grpc.Errorf(err.Type().GRPCCode(), format, err.Error(), err.Code(), attrs)
}
return grpc.Errorf(codes.Unknown, in.Error())
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/dry_run_client.go#L50-L52
|
func (c *dryRunProwJobClient) Create(*prowapi.ProwJob) (*prowapi.ProwJob, error) {
return nil, nil
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcauth/tcauth.go#L627-L631
|
func (auth *Auth) AzureContainerSAS(account, container, level string) (*AzureBlobSharedAccessSignature, error) {
cd := tcclient.Client(*auth)
responseObject, _, err := (&cd).APICall(nil, "GET", "/azure/"+url.QueryEscape(account)+"/containers/"+url.QueryEscape(container)+"/"+url.QueryEscape(level), new(AzureBlobSharedAccessSignature), nil)
return responseObject.(*AzureBlobSharedAccessSignature), err
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1725-L1746
|
func (o *Ordered) Serialize(_w io.Writer) error {
w := NewWriter(_w)
// Unwind directory stack
for len(o.dirStack) > 1 {
child := o.dirStack[len(o.dirStack)-1]
child.nodeProto.Hash = child.hash.Sum(nil)
o.dirStack = o.dirStack[:len(o.dirStack)-1]
parent := o.dirStack[len(o.dirStack)-1]
parent.hash.Write([]byte(fmt.Sprintf("%s:%s:", child.nodeProto.Name, child.nodeProto.Hash)))
parent.nodeProto.SubtreeSize += child.nodeProto.SubtreeSize
}
o.fs[0].nodeProto.Hash = o.fs[0].hash.Sum(nil)
for _, n := range o.fs {
if err := w.Write(&MergeNode{
k: b(n.path),
nodeProto: n.nodeProto,
}); err != nil {
return err
}
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_server.go#L43-L51
|
func (r *ProtocolLXD) UpdateServer(server api.ServerPut, ETag string) error {
// Send the request
_, _, err := r.query("PUT", "", server, ETag)
if err != nil {
return err
}
return nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/typed/tsuru/v1/app.go#L112-L120
|
func (c *apps) Delete(name string, options *meta_v1.DeleteOptions) error {
return c.client.Delete().
Namespace(c.ns).
Resource("apps").
Name(name).
Body(options).
Do().
Error()
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/socket/socket_classic.go#L107-L117
|
func LookupIP(ctx context.Context, host string) (addrs []net.IP, err error) {
packedAddrs, _, err := resolve(ctx, ipFamilies, host)
if err != nil {
return nil, fmt.Errorf("socket: failed resolving %q: %v", host, err)
}
addrs = make([]net.IP, len(packedAddrs))
for i, pa := range packedAddrs {
addrs[i] = net.IP(pa)
}
return addrs, nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/oci.go#L14-L22
|
func BlobInfoFromOCI1Descriptor(desc imgspecv1.Descriptor) types.BlobInfo {
return types.BlobInfo{
Digest: desc.Digest,
Size: desc.Size,
URLs: desc.URLs,
Annotations: desc.Annotations,
MediaType: desc.MediaType,
}
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxtype.go#L844-L856
|
func (box *Box2D) Points() []Point2D32f {
var pts [4]C.CvPoint2D32f
C.cvBoxPoints(
box.CVBox(),
(*C.CvPoint2D32f)(unsafe.Pointer(&pts[0])),
)
outPts := make([]Point2D32f, 4)
for i, p := range pts {
outPts[i].X = float32(p.x)
outPts[i].Y = float32(p.y)
}
return outPts
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L589-L591
|
func HTTPLogger(name string, handler http.Handler) http.Handler {
return glg.HTTPLogger(name, handler)
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/snowballword/snowballword.go#L247-L264
|
func (w *SnowballWord) FirstSuffixIfIn(startPos, endPos int, suffixes ...string) (suffix string, suffixRunes []rune) {
for _, suffix := range suffixes {
suffixRunes := []rune(suffix)
if w.HasSuffixRunesIn(0, endPos, suffixRunes) {
if endPos-len(suffixRunes) >= startPos {
return suffix, suffixRunes
} else {
// Empty out suffixRunes
suffixRunes = suffixRunes[:0]
return "", suffixRunes
}
}
}
// Empty out suffixRunes
suffixRunes = suffixRunes[:0]
return "", suffixRunes
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/wood/protector.go#L30-L42
|
func NewProtector(maxBody string, corsOptions cors.Options) func(http.Handler) http.Handler {
c := cors.New(corsOptions)
return func(next http.Handler) http.Handler {
return c.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// limit request body size
fire.LimitBody(w, r, int64(fire.DataSize(maxBody)))
// call next handler
next.ServeHTTP(w, r)
}))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/easyjson.go#L514-L518
|
func (v *GetUsageAndQuotaReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoStorage5(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1671-L1675
|
func (v EventAddHeapSnapshotChunk) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeapprofiler19(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L226-L230
|
func (pa *ConfigAgent) Config() *Configuration {
pa.mut.Lock()
defer pa.mut.Unlock()
return pa.configuration
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/tterse/tterse.go#L64-L68
|
func (p *TTerse) ParseString(name, template string) (*parser.AST, error) {
b := parser.NewBuilder()
lex := NewStringLexer(template)
return b.Parse(name, lex)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/types/set.go#L111-L123
|
func (us *unsafeSet) Sub(other Set) Set {
oValues := other.Values()
result := us.Copy().(*unsafeSet)
for _, val := range oValues {
if _, ok := result.d[val]; !ok {
continue
}
delete(result.d, val)
}
return result
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L453-L462
|
func FileSequence_Frame_Fill(id FileSeqId, fill *C.char) *C.char {
fs, ok := sFileSeqs.Get(id)
// caller must free string
if !ok {
return C.CString("")
}
gofill := C.GoString(fill)
frameStr, _ := fs.Frame(gofill)
return C.CString(frameStr)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/easyjson.go#L644-L648
|
func (v EventIndexedDBListUpdated) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoStorage7(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/idmap/idmapset_linux.go#L687-L736
|
func getFromProc(fname string) ([][]int64, error) {
entries := [][]int64{}
f, err := os.Open(fname)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
// Skip comments
s := strings.Split(scanner.Text(), "#")
if len(s[0]) == 0 {
continue
}
// Validate format
s = strings.Fields(s[0])
if len(s) < 3 {
return nil, fmt.Errorf("Unexpected values in %q: %q", fname, s)
}
// Get range start
entryStart, err := strconv.ParseUint(s[0], 10, 32)
if err != nil {
continue
}
// Get range size
entryHost, err := strconv.ParseUint(s[1], 10, 32)
if err != nil {
continue
}
// Get range size
entrySize, err := strconv.ParseUint(s[2], 10, 32)
if err != nil {
continue
}
entries = append(entries, []int64{int64(entryStart), int64(entryHost), int64(entrySize)})
}
if len(entries) == 0 {
return nil, fmt.Errorf("Namespace doesn't have any map set")
}
return entries, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/wal/wal.go#L297-L299
|
func OpenForRead(lg *zap.Logger, dirpath string, snap walpb.Snapshot) (*WAL, error) {
return openAtIndex(lg, dirpath, snap, false)
}
|
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/partitions.go#L161-L169
|
func (c *partitionConsumer) MarkOffset(offset int64, metadata string) {
c.mu.Lock()
if next := offset + 1; next > c.state.Info.Offset {
c.state.Info.Offset = next
c.state.Info.Metadata = metadata
c.state.Dirty = true
}
c.mu.Unlock()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/session.go#L115-L121
|
func WithTTL(ttl int) SessionOption {
return func(so *sessionOptions) {
if ttl > 0 {
so.ttl = ttl
}
}
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/release/boshrelease.go#L26-L39
|
func LoadBoshRelease(releaseRepo pull.Release, path string) (release *BoshRelease, err error) {
var rr io.ReadCloser
rr, err = releaseRepo.Read(path)
if err != nil {
return
}
defer func() {
if cerr := rr.Close(); cerr != nil {
err = cerr
}
}()
release, err = readBoshRelease(rr)
return
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/value.go#L120-L144
|
func (lf *logFile) read(p valuePointer, s *y.Slice) (buf []byte, err error) {
var nbr int64
offset := p.Offset
if lf.loadingMode == options.FileIO {
buf = s.Resize(int(p.Len))
var n int
n, err = lf.fd.ReadAt(buf, int64(offset))
nbr = int64(n)
} else {
// Do not convert size to uint32, because the lf.fmap can be of size
// 4GB, which overflows the uint32 during conversion to make the size 0,
// causing the read to fail with ErrEOF. See issue #585.
size := int64(len(lf.fmap))
valsz := p.Len
if int64(offset) >= size || int64(offset+valsz) > size {
err = y.ErrEOF
} else {
buf = lf.fmap[offset : offset+valsz]
nbr = int64(valsz)
}
}
y.NumReads.Add(1)
y.NumBytesRead.Add(nbr)
return buf, err
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/docker/config/config.go#L57-L86
|
func GetAuthentication(sys *types.SystemContext, registry string) (string, string, error) {
if sys != nil && sys.DockerAuthConfig != nil {
return sys.DockerAuthConfig.Username, sys.DockerAuthConfig.Password, nil
}
dockerLegacyPath := filepath.Join(homedir.Get(), dockerLegacyHomePath)
var paths []string
pathToAuth, err := getPathToAuth(sys)
if err == nil {
paths = append(paths, pathToAuth)
} else {
// Error means that the path set for XDG_RUNTIME_DIR does not exist
// but we don't want to completely fail in the case that the user is pulling a public image
// Logging the error as a warning instead and moving on to pulling the image
logrus.Warnf("%v: Trying to pull image in the event that it is a public image.", err)
}
paths = append(paths, filepath.Join(homedir.Get(), dockerHomePath), dockerLegacyPath)
for _, path := range paths {
legacyFormat := path == dockerLegacyPath
username, password, err := findAuthentication(registry, path, legacyFormat)
if err != nil {
return "", "", err
}
if username != "" && password != "" {
return username, password, nil
}
}
return "", "", nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L37-L63
|
func NewGateway(db *db.Node, cert *shared.CertInfo, options ...Option) (*Gateway, error) {
ctx, cancel := context.WithCancel(context.Background())
o := newOptions()
for _, option := range options {
option(o)
}
gateway := &Gateway{
db: db,
cert: cert,
options: o,
ctx: ctx,
cancel: cancel,
upgradeCh: make(chan struct{}, 16),
acceptCh: make(chan net.Conn),
store: &dqliteServerStore{},
}
err := gateway.init()
if err != nil {
return nil, err
}
return gateway, nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/examples/keyvalue/server/server.go#L107-L119
|
func (h *kvHandler) Set(ctx thrift.Context, key, value string) error {
if err := isValidKey(key); err != nil {
return err
}
h.Lock()
defer h.Unlock()
h.vals[key] = value
// Example of how to use response headers. Normally, these values should be passed via result structs.
ctx.SetResponseHeaders(map[string]string{"count": fmt.Sprint(len(h.vals))})
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L651-L660
|
func (p *SearchInResponseBodyParams) Do(ctx context.Context) (result []*debugger.SearchMatch, err error) {
// execute
var res SearchInResponseBodyReturns
err = cdp.Execute(ctx, CommandSearchInResponseBody, p, &res)
if err != nil {
return nil, err
}
return res.Result, nil
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/options.go#L260-L278
|
func Transformer(name string, f interface{}) Option {
v := reflect.ValueOf(f)
if !function.IsType(v.Type(), function.Transformer) || v.IsNil() {
panic(fmt.Sprintf("invalid transformer function: %T", f))
}
if name == "" {
name = function.NameOf(v)
if !identsRx.MatchString(name) {
name = "λ" // Lambda-symbol as placeholder name
}
} else if !identsRx.MatchString(name) {
panic(fmt.Sprintf("invalid name: %q", name))
}
tr := &transformer{name: name, fnc: reflect.ValueOf(f)}
if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
tr.typ = ti
}
return tr
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcsecrets/tcsecrets.go#L114-L118
|
func (secrets *Secrets) Set(name string, payload *Secret) error {
cd := tcclient.Client(*secrets)
_, _, err := (&cd).APICall(payload, "PUT", "/secret/"+url.QueryEscape(name), nil, nil)
return err
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/file.go#L78-L84
|
func (s *FileSource) Reader() (io.Reader, error) {
fh, err := os.Open(s.Path)
if err != nil {
return nil, err
}
return fh, nil
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/profitbricks.go#L15-L23
|
func NewClient(username, password string) *Client {
c := newPBRestClient(username, password, "", "", true)
return &Client{
userName: c.username,
password: c.password,
client: c,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L767-L771
|
func (v GetWindowBoundsReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser7(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/default_context.go#L189-L221
|
func (d *DefaultContext) Redirect(status int, url string, args ...interface{}) error {
d.Flash().persist(d.Session())
if strings.HasSuffix(url, "Path()") {
if len(args) > 1 {
return fmt.Errorf("you must pass only a map[string]interface{} to a route path: %T", args)
}
var m map[string]interface{}
if len(args) == 1 {
rv := reflect.Indirect(reflect.ValueOf(args[0]))
if !rv.Type().ConvertibleTo(mapType) {
return fmt.Errorf("you must pass only a map[string]interface{} to a route path: %T", args)
}
m = rv.Convert(mapType).Interface().(map[string]interface{})
}
h, ok := d.Value(strings.TrimSuffix(url, "()")).(RouteHelperFunc)
if !ok {
return fmt.Errorf("could not find a route helper named %s", url)
}
url, err := h(m)
if err != nil {
return err
}
http.Redirect(d.Response(), d.Request(), string(url), status)
return nil
}
if len(args) > 0 {
url = fmt.Sprintf(url, args...)
}
http.Redirect(d.Response(), d.Request(), url, status)
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_internal.go#L241-L304
|
func internalSQLPost(d *Daemon, r *http.Request) Response {
req := &internalSQLQuery{}
// Parse the request.
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return BadRequest(err)
}
if !shared.StringInSlice(req.Database, []string{"local", "global"}) {
return BadRequest(fmt.Errorf("Invalid database"))
}
if req.Query == "" {
return BadRequest(fmt.Errorf("No query provided"))
}
var db *sql.DB
if req.Database == "global" {
db = d.cluster.DB()
} else {
db = d.db.DB()
}
batch := internalSQLBatch{}
if req.Query == ".sync" {
d.gateway.Sync()
return SyncResponse(true, batch)
}
for _, query := range strings.Split(req.Query, ";") {
query = strings.TrimLeft(query, " ")
if query == "" {
continue
}
result := internalSQLResult{}
tx, err := db.Begin()
if err != nil {
return SmartError(err)
}
if strings.HasPrefix(strings.ToUpper(query), "SELECT") {
err = internalSQLSelect(tx, query, &result)
tx.Rollback()
} else {
err = internalSQLExec(tx, query, &result)
if err != nil {
tx.Rollback()
} else {
err = tx.Commit()
}
}
if err != nil {
return SmartError(err)
}
batch.Results = append(batch.Results, result)
}
return SyncResponse(true, batch)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2041-L2050
|
func (u OperationBody) GetDestination() (result AccountId, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "Destination" {
result = *u.Destination
ok = true
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/easyjson.go#L152-L156
|
func (v UntrackIndexedDBForOriginParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoStorage1(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L1868-L1872
|
func (v *EventLayerPainted) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoLayertree16(&r, v)
return r.Error()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/internal/oci_util.go#L71-L83
|
func ValidateOCIPath(path string) error {
if runtime.GOOS == "windows" {
// On Windows we must allow for a ':' as part of the path
if strings.Count(path, ":") > 1 {
return errors.Errorf("Invalid OCI reference: path %s contains more than one colon", path)
}
} else {
if strings.Contains(path, ":") {
return errors.Errorf("Invalid OCI reference: path %s contains a colon", path)
}
}
return nil
}
|
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/EvaluableExpression_sql.go#L21-L42
|
func (this EvaluableExpression) ToSQLQuery() (string, error) {
var stream *tokenStream
var transactions *expressionOutputStream
var transaction string
var err error
stream = newTokenStream(this.tokens)
transactions = new(expressionOutputStream)
for stream.hasNext() {
transaction, err = this.findNextSQLString(stream, transactions)
if err != nil {
return "", err
}
transactions.add(transaction)
}
return transactions.createString(" "), nil
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/handlers/elasticsearch/elasticsearch.go#L30-L38
|
func (c *Config) defaults() {
if c.BufferSize == 0 {
c.BufferSize = 100
}
if c.Prefix == "" {
c.Prefix = "logs"
}
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/event.go#L183-L210
|
func eventBlockAdd(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
if !permission.Check(t, permission.PermEventBlockAdd) {
return permission.ErrUnauthorized
}
var block event.Block
err = ParseInput(r, &block)
if err != nil {
return err
}
if block.Reason == "" {
return &errors.HTTP{Code: http.StatusBadRequest, Message: "reason is required"}
}
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypeEventBlock},
Kind: permission.PermEventBlockAdd,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermEventBlockReadEvents),
})
if err != nil {
return err
}
defer func() {
evt.Target.Value = block.ID.Hex()
evt.Done(err)
}()
return event.AddBlock(&block)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L512-L518
|
func containerLXCUnload(c *containerLXC) {
runtime.SetFinalizer(c, nil)
if c.c != nil {
c.c.Release()
c.c = nil
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1848-L1852
|
func (v CollectGarbageParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeapprofiler22(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L1728-L1735
|
func (r *Cloud) Locator(api *API) *CloudLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.CloudLocator(l["href"])
}
}
return nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/message.go#L74-L83
|
func (m *Message) AddAttachment(name, contentType string, r io.Reader) error {
m.Attachments = append(m.Attachments, Attachment{
Name: name,
ContentType: contentType,
Reader: r,
Embedded: false,
})
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L894-L896
|
func (c *Cluster) ImagesGetOnCurrentNode() (map[string][]string, error) {
return c.ImagesGetByNodeID(c.nodeID)
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocktracer.go#L80-L90
|
func (t *MockTracer) Inject(sm opentracing.SpanContext, format interface{}, carrier interface{}) error {
spanContext, ok := sm.(MockSpanContext)
if !ok {
return opentracing.ErrInvalidCarrier
}
injector, ok := t.injectors[format]
if !ok {
return opentracing.ErrUnsupportedFormat
}
return injector.Inject(spanContext, carrier)
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L272-L276
|
func (l *Logger) Panicf(format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
l.Output(2, LevelError, msg)
panic(msg)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/db.go#L300-L304
|
func (c *Cluster) Transaction(f func(*ClusterTx) error) error {
c.mu.RLock()
defer c.mu.RUnlock()
return c.transaction(f)
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/policy/codegen_client.go#L94-L96
|
func (api *API) AppliedPolicyLocator(href string) *AppliedPolicyLocator {
return &AppliedPolicyLocator{Href(href), api}
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/harness/api_checkers.go#L93-L97
|
func CheckInject(val bool) APICheckOption {
return func(s *APICheckSuite) {
s.opts.CheckInject = val
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L152-L156
|
func (v *StartSamplingParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoMemory1(&r, v)
return r.Error()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L1117-L1126
|
func (c APIClient) ListFile(repoName string, commitID string, path string) ([]*pfs.FileInfo, error) {
var result []*pfs.FileInfo
if err := c.ListFileF(repoName, commitID, path, 0, func(fi *pfs.FileInfo) error {
result = append(result, fi)
return nil
}); err != nil {
return nil, err
}
return result, nil
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/linecapjoin/linecapjoin.go#L32-L52
|
func Draw(gc draw2d.GraphicContext, cap draw2d.LineCap, join draw2d.LineJoin,
x0, y0, x1, y1, offset float64) {
gc.SetLineCap(cap)
gc.SetLineJoin(join)
// Draw thick line
gc.SetStrokeColor(color.NRGBA{0x33, 0x33, 0x33, 0xFF})
gc.SetLineWidth(30.0)
gc.MoveTo(x0, y0)
gc.LineTo((x0+x1)/2+offset, (y0+y1)/2)
gc.LineTo(x1, y1)
gc.Stroke()
// Draw thin helping line
gc.SetStrokeColor(color.NRGBA{0xFF, 0x33, 0x33, 0xFF})
gc.SetLineWidth(2.56)
gc.MoveTo(x0, y0)
gc.LineTo((x0+x1)/2+offset, (y0+y1)/2)
gc.LineTo(x1, y1)
gc.Stroke()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cron/cron.go#L120-L126
|
func (c *Cron) HasJob(name string) bool {
c.lock.Lock()
defer c.lock.Unlock()
_, ok := c.jobs[name]
return ok
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/axe/pool.go#L44-L54
|
func (p *Pool) Run() {
// start all queues
for queue := range p.queues {
queue.start(p)
}
// start all tasks
for _, task := range p.tasks {
task.start(p)
}
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L272-L293
|
func (ctx *Context) Recover() {
if err := recover(); err != nil {
if e, ok := err.(*ValidationError); ok == true {
ctx.Fail(e)
return
}
stack := make([]byte, 64<<10)
n := runtime.Stack(stack[:], false)
log.WithFields(log.Fields{"path": ctx.Request.URL.Path}).Errorln(string(stack[:n]))
if !ctx.Written() {
ctx.ResponseWriter.Header().Del("Content-Type")
if ctx.handlersStack.PanicHandler != nil {
ctx.Data["panic"] = err
ctx.handlersStack.PanicHandler(ctx)
} else {
ctx.Fail((&ServerError{}).New(http.StatusText(http.StatusInternalServerError)))
}
}
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L35-L61
|
func (r *Raft) checkRPCHeader(rpc RPC) error {
// Get the header off the RPC message.
wh, ok := rpc.Command.(WithRPCHeader)
if !ok {
return fmt.Errorf("RPC does not have a header")
}
header := wh.GetRPCHeader()
// First check is to just make sure the code can understand the
// protocol at all.
if header.ProtocolVersion < ProtocolVersionMin ||
header.ProtocolVersion > ProtocolVersionMax {
return ErrUnsupportedProtocol
}
// Second check is whether we should support this message, given the
// current protocol we are configured to run. This will drop support
// for protocol version 0 starting at protocol version 2, which is
// currently what we want, and in general support one version back. We
// may need to revisit this policy depending on how future protocol
// changes evolve.
if header.ProtocolVersion < r.conf.ProtocolVersion-1 {
return ErrUnsupportedProtocol
}
return nil
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive50.go#L139-L177
|
func calcKeys50(pass, salt []byte, kdfCount int) [][]byte {
if len(salt) > maxPbkdf2Salt {
salt = salt[:maxPbkdf2Salt]
}
keys := make([][]byte, 3)
if len(keys) == 0 {
return keys
}
prf := hmac.New(sha256.New, pass)
prf.Write(salt)
prf.Write([]byte{0, 0, 0, 1})
t := prf.Sum(nil)
u := append([]byte(nil), t...)
kdfCount--
for i, iter := range []int{kdfCount, 16, 16} {
for iter > 0 {
prf.Reset()
prf.Write(u)
u = prf.Sum(u[:0])
for j := range u {
t[j] ^= u[j]
}
iter--
}
keys[i] = append([]byte(nil), t...)
}
pwcheck := keys[2]
for i, v := range pwcheck[pwCheckSize:] {
pwcheck[i&(pwCheckSize-1)] ^= v
}
keys[2] = pwcheck[:pwCheckSize]
return keys
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1755-L1760
|
func NewUnordered(root string) *Unordered {
return &Unordered{
fs: make(map[string]*NodeProto),
root: clean(root),
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L6894-L6898
|
func (v CloseParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage75(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L68-L72
|
func AllowLargeResults(shouldAllow bool, tempTableName string, flattenResults bool) func(*Client) error {
return func(c *Client) error {
return c.setAllowLargeResults(shouldAllow, tempTableName, flattenResults)
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/http.go#L492-L555
|
func checkClusterCompatibilityFromHeader(lg *zap.Logger, localID types.ID, header http.Header, cid types.ID) error {
remoteName := header.Get("X-Server-From")
remoteServer := serverVersion(header)
remoteVs := ""
if remoteServer != nil {
remoteVs = remoteServer.String()
}
remoteMinClusterVer := minClusterVersion(header)
remoteMinClusterVs := ""
if remoteMinClusterVer != nil {
remoteMinClusterVs = remoteMinClusterVer.String()
}
localServer, localMinCluster, err := checkVersionCompatibility(remoteName, remoteServer, remoteMinClusterVer)
localVs := ""
if localServer != nil {
localVs = localServer.String()
}
localMinClusterVs := ""
if localMinCluster != nil {
localMinClusterVs = localMinCluster.String()
}
if err != nil {
if lg != nil {
lg.Warn(
"failed to check version compatibility",
zap.String("local-member-id", localID.String()),
zap.String("local-member-cluster-id", cid.String()),
zap.String("local-member-server-version", localVs),
zap.String("local-member-server-minimum-cluster-version", localMinClusterVs),
zap.String("remote-peer-server-name", remoteName),
zap.String("remote-peer-server-version", remoteVs),
zap.String("remote-peer-server-minimum-cluster-version", remoteMinClusterVs),
zap.Error(err),
)
} else {
plog.Errorf("request version incompatibility (%v)", err)
}
return errIncompatibleVersion
}
if gcid := header.Get("X-Etcd-Cluster-ID"); gcid != cid.String() {
if lg != nil {
lg.Warn(
"request cluster ID mismatch",
zap.String("local-member-id", localID.String()),
zap.String("local-member-cluster-id", cid.String()),
zap.String("local-member-server-version", localVs),
zap.String("local-member-server-minimum-cluster-version", localMinClusterVs),
zap.String("remote-peer-server-name", remoteName),
zap.String("remote-peer-server-version", remoteVs),
zap.String("remote-peer-server-minimum-cluster-version", remoteMinClusterVs),
zap.String("remote-peer-cluster-id", gcid),
)
} else {
plog.Errorf("request cluster ID mismatch (got %s want %s)", gcid, cid)
}
return errClusterIDMismatch
}
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/daemon/daemon_transport.go#L180-L190
|
func (ref daemonReference) PolicyConfigurationNamespaces() []string {
// See the explanation in daemonReference.PolicyConfigurationIdentity.
switch {
case ref.id != "":
return []string{}
case ref.ref != nil:
return policyconfiguration.DockerReferenceNamespaces(ref.ref)
default: // Coverage: Should never happen, NewReference above should refuse such values.
panic("Internal inconsistency: daemonReference has empty id and nil ref")
}
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L942-L961
|
func (v *VM) TotalSharedFolders() (int, error) {
var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE
var err C.VixError = C.VIX_OK
var numSharedFolders C.int
jobHandle = C.VixVM_GetNumSharedFolders(v.handle, nil, nil)
defer C.Vix_ReleaseHandle(jobHandle)
err = C.get_num_shared_folders(jobHandle, &numSharedFolders)
if C.VIX_OK != err {
return 0, &Error{
Operation: "vm.TotalSharedFolders",
Code: int(err & 0xFFFF),
Text: C.GoString(C.Vix_GetErrorText(err, nil)),
}
}
return int(numSharedFolders), nil
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/meta.go#L354-L359
|
func (m *Meta) MakeSlice() interface{} {
slice := reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(m.model)), 0, 0)
pointer := reflect.New(slice.Type())
pointer.Elem().Set(slice)
return pointer.Interface()
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/attrs.go#L98-L108
|
func (a *Attrs) Attrs() map[string]interface{} {
a.attrsLock.RLock()
defer a.attrsLock.RUnlock()
attrs := make(map[string]interface{})
for hash, val := range a.attrs {
key, _ := getHashAttr(hash)
attrs[key] = val
}
return attrs
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/command_line.go#L175-L199
|
func RegisterClientCommands(app *kingpin.Application) {
cm15Cmd := app.Command(Cm15Command, cm15.APIName)
registrar := rsapi.Registrar{APICmd: cm15Cmd}
cm15.RegisterCommands(®istrar)
cm16Cmd := app.Command(Cm16Command, cm16.APIName)
registrar = rsapi.Registrar{APICmd: cm16Cmd}
cm16.RegisterCommands(®istrar)
ssCmd := app.Command(SsCommand, ss.APIName)
registrar = rsapi.Registrar{APICmd: ssCmd}
ss.RegisterCommands(®istrar)
rl10Cmd := app.Command(Rl10Command, rl10.APIName)
registrar = rsapi.Registrar{APICmd: rl10Cmd}
rl10.RegisterCommands(®istrar)
caCmd := app.Command(CaCommand, ca.APIName)
registrar = rsapi.Registrar{APICmd: caCmd}
ca.RegisterCommands(®istrar)
policyCmd := app.Command(PolicyCommand, policy.APIName)
registrar = rsapi.Registrar{APICmd: policyCmd}
policy.RegisterCommands(®istrar)
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/smtp/util.go#L26-L70
|
func SendMailSSL(addr string, a smtp.Auth, from string, to []string, msg []byte) error {
conn, err := tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true}) //TODO: Not secure
if err != nil {
log.Println("Error Dialing", err)
return err
}
h, _, _ := net.SplitHostPort(addr)
c, err := smtp.NewClient(conn, h)
if err != nil {
log.Println("Error SMTP connection", err)
return err
}
defer c.Close()
if a != nil {
if ok, _ := c.Extension("AUTH"); ok {
if err = c.Auth(a); err != nil {
log.Printf("Authentication error: %v", err)
return err
}
}
}
if err = c.Mail(from); err != nil {
log.Printf("From error: %v", err)
return err
}
for _, addr := range to {
if err = c.Rcpt(addr); err != nil {
log.Printf("Recipient error: %v", err)
return err
}
}
w, err := c.Data()
if err != nil {
return err
}
w.Write(msg)
w.Close()
return c.Quit()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/ranch/ranch.go#L87-L99
|
func NewRanch(config string, s *Storage) (*Ranch, error) {
newRanch := &Ranch{
Storage: s,
UpdateTime: updateTime,
}
if config != "" {
if err := newRanch.SyncConfig(config); err != nil {
return nil, err
}
}
newRanch.LogStatus()
return newRanch, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/dco/dco.go#L296-L300
|
func shouldPrune(log *logrus.Entry) func(github.IssueComment) bool {
return func(comment github.IssueComment) bool {
return strings.Contains(comment.Body, dcoMsgPruneMatch)
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/fetcher/client.go#L230-L269
|
func (client *Client) FetchIssueComments(issueID int, latest time.Time, c chan *github.IssueComment) {
opt := &github.IssueListCommentsOptions{Since: latest, Sort: "updated", Direction: "asc"}
githubClient, err := client.getGitHubClient()
if err != nil {
close(c)
glog.Error(err)
return
}
count := 0
for {
client.limitsCheckAndWait()
comments, resp, err := githubClient.Issues.ListComments(
context.Background(),
client.Org,
client.Project,
issueID,
opt,
)
if err != nil {
close(c)
glog.Error(err)
return
}
for _, comment := range comments {
c <- comment
count++
}
if resp.NextPage == 0 {
break
}
opt.ListOptions.Page = resp.NextPage
}
glog.Infof("Fetched %d issue comments updated since %v for issue #%d.", count, latest, issueID)
close(c)
}
|
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L99-L117
|
func New(workers int) (pool *Pool) {
pool = new(Pool)
pool.num_workers = workers
pool.job_wanted_pipe = make(chan chan *Job)
pool.done_pipe = make(chan *Job)
pool.add_pipe = make(chan *Job)
pool.result_wanted_pipe = make(chan chan *Job)
pool.jobs_ready_to_run = list.New()
pool.jobs_completed = list.New()
pool.working_wanted_pipe = make(chan chan bool)
pool.stats_wanted_pipe = make(chan chan stats)
pool.worker_kill_pipe = make(chan bool)
pool.supervisor_kill_pipe = make(chan bool)
pool.interval = 1
pool.next_job_id = 0
// start the supervisor here so we can accept jobs before a Run call
pool.startSupervisor()
return
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2stats/leader.go#L124-L128
|
func (fs *FollowerStats) Fail() {
fs.Lock()
defer fs.Unlock()
fs.Counts.Fail++
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/crossdock/client/client.go#L43-L51
|
func (c *Client) Start() error {
if err := c.listen(); err != nil {
return err
}
go func() {
http.Serve(c.listener, c.mux)
}()
return nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/typecheck.go#L229-L587
|
func typecheck1(cfg *TypeConfig, f interface{}, typeof map[interface{}]string, assign map[string][]interface{}) {
// set sets the type of n to typ.
// If isDecl is true, n is being declared.
set := func(n ast.Expr, typ string, isDecl bool) {
if typeof[n] != "" || typ == "" {
if typeof[n] != typ {
assign[typ] = append(assign[typ], n)
}
return
}
typeof[n] = typ
// If we obtained typ from the declaration of x
// propagate the type to all the uses.
// The !isDecl case is a cheat here, but it makes
// up in some cases for not paying attention to
// struct fields. The real type checker will be
// more accurate so we won't need the cheat.
if id, ok := n.(*ast.Ident); ok && id.Obj != nil && (isDecl || typeof[id.Obj] == "") {
typeof[id.Obj] = typ
}
}
// Type-check an assignment lhs = rhs.
// If isDecl is true, this is := so we can update
// the types of the objects that lhs refers to.
typecheckAssign := func(lhs, rhs []ast.Expr, isDecl bool) {
if len(lhs) > 1 && len(rhs) == 1 {
if _, ok := rhs[0].(*ast.CallExpr); ok {
t := split(typeof[rhs[0]])
// Lists should have same length but may not; pair what can be paired.
for i := 0; i < len(lhs) && i < len(t); i++ {
set(lhs[i], t[i], isDecl)
}
return
}
}
if len(lhs) == 1 && len(rhs) == 2 {
// x = y, ok
rhs = rhs[:1]
} else if len(lhs) == 2 && len(rhs) == 1 {
// x, ok = y
lhs = lhs[:1]
}
// Match as much as we can.
for i := 0; i < len(lhs) && i < len(rhs); i++ {
x, y := lhs[i], rhs[i]
if typeof[y] != "" {
set(x, typeof[y], isDecl)
} else {
set(y, typeof[x], false)
}
}
}
expand := func(s string) string {
typ := cfg.Type[s]
if typ != nil && typ.Def != "" {
return typ.Def
}
return s
}
// The main type check is a recursive algorithm implemented
// by walkBeforeAfter(n, before, after).
// Most of it is bottom-up, but in a few places we need
// to know the type of the function we are checking.
// The before function records that information on
// the curfn stack.
var curfn []*ast.FuncType
before := func(n interface{}) {
// push function type on stack
switch n := n.(type) {
case *ast.FuncDecl:
curfn = append(curfn, n.Type)
case *ast.FuncLit:
curfn = append(curfn, n.Type)
}
}
// After is the real type checker.
after := func(n interface{}) {
if n == nil {
return
}
if false && reflect.TypeOf(n).Kind() == reflect.Ptr { // debugging trace
defer func() {
if t := typeof[n]; t != "" {
pos := fset.Position(n.(ast.Node).Pos())
fmt.Fprintf(os.Stderr, "%s: typeof[%s] = %s\n", pos, gofmt(n), t)
}
}()
}
switch n := n.(type) {
case *ast.FuncDecl, *ast.FuncLit:
// pop function type off stack
curfn = curfn[:len(curfn)-1]
case *ast.FuncType:
typeof[n] = mkType(joinFunc(split(typeof[n.Params]), split(typeof[n.Results])))
case *ast.FieldList:
// Field list is concatenation of sub-lists.
t := ""
for _, field := range n.List {
if t != "" {
t += ", "
}
t += typeof[field]
}
typeof[n] = t
case *ast.Field:
// Field is one instance of the type per name.
all := ""
t := typeof[n.Type]
if !isType(t) {
// Create a type, because it is typically *T or *p.T
// and we might care about that type.
t = mkType(gofmt(n.Type))
typeof[n.Type] = t
}
t = getType(t)
if len(n.Names) == 0 {
all = t
} else {
for _, id := range n.Names {
if all != "" {
all += ", "
}
all += t
typeof[id.Obj] = t
typeof[id] = t
}
}
typeof[n] = all
case *ast.ValueSpec:
// var declaration. Use type if present.
if n.Type != nil {
t := typeof[n.Type]
if !isType(t) {
t = mkType(gofmt(n.Type))
typeof[n.Type] = t
}
t = getType(t)
for _, id := range n.Names {
set(id, t, true)
}
}
// Now treat same as assignment.
typecheckAssign(makeExprList(n.Names), n.Values, true)
case *ast.AssignStmt:
typecheckAssign(n.Lhs, n.Rhs, n.Tok == token.DEFINE)
case *ast.Ident:
// Identifier can take its type from underlying object.
if t := typeof[n.Obj]; t != "" {
typeof[n] = t
}
case *ast.SelectorExpr:
// Field or method.
name := n.Sel.Name
if t := typeof[n.X]; t != "" {
if strings.HasPrefix(t, "*") {
t = t[1:] // implicit *
}
if typ := cfg.Type[t]; typ != nil {
if t := typ.dot(cfg, name); t != "" {
typeof[n] = t
return
}
}
tt := typeof[t+"."+name]
if isType(tt) {
typeof[n] = getType(tt)
return
}
}
// Package selector.
if x, ok := n.X.(*ast.Ident); ok && x.Obj == nil {
str := x.Name + "." + name
if cfg.Type[str] != nil {
typeof[n] = mkType(str)
return
}
if t := cfg.typeof(x.Name + "." + name); t != "" {
typeof[n] = t
return
}
}
case *ast.CallExpr:
// make(T) has type T.
if isTopName(n.Fun, "make") && len(n.Args) >= 1 {
typeof[n] = gofmt(n.Args[0])
return
}
// new(T) has type *T
if isTopName(n.Fun, "new") && len(n.Args) == 1 {
typeof[n] = "*" + gofmt(n.Args[0])
return
}
// Otherwise, use type of function to determine arguments.
t := typeof[n.Fun]
in, out := splitFunc(t)
if in == nil && out == nil {
return
}
typeof[n] = join(out)
for i, arg := range n.Args {
if i >= len(in) {
break
}
if typeof[arg] == "" {
typeof[arg] = in[i]
}
}
case *ast.TypeAssertExpr:
// x.(type) has type of x.
if n.Type == nil {
typeof[n] = typeof[n.X]
return
}
// x.(T) has type T.
if t := typeof[n.Type]; isType(t) {
typeof[n] = getType(t)
} else {
typeof[n] = gofmt(n.Type)
}
case *ast.SliceExpr:
// x[i:j] has type of x.
typeof[n] = typeof[n.X]
case *ast.IndexExpr:
// x[i] has key type of x's type.
t := expand(typeof[n.X])
if strings.HasPrefix(t, "[") || strings.HasPrefix(t, "map[") {
// Lazy: assume there are no nested [] in the array
// length or map key type.
if i := strings.Index(t, "]"); i >= 0 {
typeof[n] = t[i+1:]
}
}
case *ast.StarExpr:
// *x for x of type *T has type T when x is an expr.
// We don't use the result when *x is a type, but
// compute it anyway.
t := expand(typeof[n.X])
if isType(t) {
typeof[n] = "type *" + getType(t)
} else if strings.HasPrefix(t, "*") {
typeof[n] = t[len("*"):]
}
case *ast.UnaryExpr:
// &x for x of type T has type *T.
t := typeof[n.X]
if t != "" && n.Op == token.AND {
typeof[n] = "*" + t
}
case *ast.CompositeLit:
// T{...} has type T.
typeof[n] = gofmt(n.Type)
case *ast.ParenExpr:
// (x) has type of x.
typeof[n] = typeof[n.X]
case *ast.RangeStmt:
t := expand(typeof[n.X])
if t == "" {
return
}
var key, value string
if t == "string" {
key, value = "int", "rune"
} else if strings.HasPrefix(t, "[") {
key = "int"
if i := strings.Index(t, "]"); i >= 0 {
value = t[i+1:]
}
} else if strings.HasPrefix(t, "map[") {
if i := strings.Index(t, "]"); i >= 0 {
key, value = t[4:i], t[i+1:]
}
}
changed := false
if n.Key != nil && key != "" {
changed = true
set(n.Key, key, n.Tok == token.DEFINE)
}
if n.Value != nil && value != "" {
changed = true
set(n.Value, value, n.Tok == token.DEFINE)
}
// Ugly failure of vision: already type-checked body.
// Do it again now that we have that type info.
if changed {
typecheck1(cfg, n.Body, typeof, assign)
}
case *ast.TypeSwitchStmt:
// Type of variable changes for each case in type switch,
// but go/parser generates just one variable.
// Repeat type check for each case with more precise
// type information.
as, ok := n.Assign.(*ast.AssignStmt)
if !ok {
return
}
varx, ok := as.Lhs[0].(*ast.Ident)
if !ok {
return
}
t := typeof[varx]
for _, cas := range n.Body.List {
cas := cas.(*ast.CaseClause)
if len(cas.List) == 1 {
// Variable has specific type only when there is
// exactly one type in the case list.
if tt := typeof[cas.List[0]]; isType(tt) {
tt = getType(tt)
typeof[varx] = tt
typeof[varx.Obj] = tt
typecheck1(cfg, cas.Body, typeof, assign)
}
}
}
// Restore t.
typeof[varx] = t
typeof[varx.Obj] = t
case *ast.ReturnStmt:
if len(curfn) == 0 {
// Probably can't happen.
return
}
f := curfn[len(curfn)-1]
res := n.Results
if f.Results != nil {
t := split(typeof[f.Results])
for i := 0; i < len(res) && i < len(t); i++ {
set(res[i], t[i], false)
}
}
}
}
walkBeforeAfter(f, before, after)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L5702-L5706
|
func (v *EventInterstitialHidden) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage59(&r, v)
return r.Error()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/src.go#L349-L386
|
func (s *Source) GetManifest(ctx context.Context, instanceDigest *digest.Digest) ([]byte, string, error) {
if instanceDigest != nil {
// How did we even get here? GetManifest(ctx, nil) has returned a manifest.DockerV2Schema2MediaType.
return nil, "", errors.Errorf(`Manifest lists are not supported by "docker-daemon:"`)
}
if s.generatedManifest == nil {
if err := s.ensureCachedDataIsPresent(); err != nil {
return nil, "", err
}
m := manifest.Schema2{
SchemaVersion: 2,
MediaType: manifest.DockerV2Schema2MediaType,
ConfigDescriptor: manifest.Schema2Descriptor{
MediaType: manifest.DockerV2Schema2ConfigMediaType,
Size: int64(len(s.configBytes)),
Digest: s.configDigest,
},
LayersDescriptors: []manifest.Schema2Descriptor{},
}
for _, diffID := range s.orderedDiffIDList {
li, ok := s.knownLayers[diffID]
if !ok {
return nil, "", errors.Errorf("Internal inconsistency: Information about layer %s missing", diffID)
}
m.LayersDescriptors = append(m.LayersDescriptors, manifest.Schema2Descriptor{
Digest: diffID, // diffID is a digest of the uncompressed tarball
MediaType: manifest.DockerV2Schema2LayerMediaType,
Size: li.size,
})
}
manifestBytes, err := json.Marshal(&m)
if err != nil {
return nil, "", err
}
s.generatedManifest = manifestBytes
}
return s.generatedManifest, manifest.DockerV2Schema2MediaType, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/types.go#L231-L233
|
func (t PausedReason) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L490-L494
|
func (mat *SparseMat) InitSparseMatIterator(iter *SparseMatIterator) *SparseNode {
mat_c := (*C.CvSparseMat)(mat)
node := C.cvInitSparseMatIterator(mat_c, (*C.CvSparseMatIterator)(iter))
return (*SparseNode)(node)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/expect/expect.go#L97-L115
|
func (ep *ExpectProcess) ExpectFunc(f func(string) bool) (string, error) {
ep.mu.Lock()
for {
for len(ep.lines) == 0 && ep.err == nil {
ep.cond.Wait()
}
if len(ep.lines) == 0 {
break
}
l := ep.lines[0]
ep.lines = ep.lines[1:]
if f(l) {
ep.mu.Unlock()
return l, nil
}
}
ep.mu.Unlock()
return "", ep.err
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3061-L3070
|
func (u ManageOfferSuccessResultOffer) GetOffer() (result OfferEntry, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Effect))
if armName == "Offer" {
result = *u.Offer
ok = true
}
return
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer_heap.go#L76-L78
|
func (ph *peerHeap) updatePeer(peerScore *peerScore) {
heap.Fix(ph, peerScore.index)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/io/easyjson.go#L153-L157
|
func (v *ResolveBlobParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoIo1(&r, v)
return r.Error()
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcgceprovider/tcgceprovider.go#L103-L107
|
func (gceProvider *GceProvider) GetCredentials() error {
cd := tcclient.Client(*gceProvider)
_, _, err := (&cd).APICall(nil, "POST", "/credentials", nil, nil)
return err
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/watch/watch.go#L51-L57
|
func (e *Event) UnmarshalPrev(key *string, val proto.Message) error {
if err := CheckType(e.Template, val); err != nil {
return err
}
*key = string(e.PrevKey)
return proto.Unmarshal(e.PrevValue, val)
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L534-L547
|
func FileSequence_SetFrameSet(id FileSeqId, fsetId FrameSetId) bool {
fs, ok := sFileSeqs.Get(id)
if !ok {
return false
}
fset, ok := sFrameSets.Get(fsetId)
if !ok {
return false
}
fs.SetFrameSet(&fset.FrameSet)
return true
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/http/http_client.go#L184-L199
|
func (o *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {
v := &optionsJSON{}
if err := unmarshal(v); err != nil {
return err
}
*o = Options{
Timeout: v.Timeout.Duration(),
KeepAlive: v.KeepAlive.Duration(),
TLSHandshakeTimeout: v.TLSHandshakeTimeout.Duration(),
TLSSkipVerify: v.TLSSkipVerify,
RetryTimeMax: v.RetryTimeMax.Duration(),
RetrySleepMax: v.RetrySleepMax.Duration(),
RetrySleepBase: v.RetrySleepBase.Duration(),
}
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/ppsutil/util.go#L304-L313
|
func (r *PipelineManifestReader) NextCreatePipelineRequest() (*ppsclient.CreatePipelineRequest, error) {
var result ppsclient.CreatePipelineRequest
if err := jsonpb.UnmarshalNext(r.decoder, &result); err != nil {
if err == io.EOF {
return nil, err
}
return nil, fmt.Errorf("malformed pipeline spec: %s", err)
}
return &result, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/codegen_client.go#L1118-L1120
|
func (r *MultiCloudImage) Locator(api *API) *MultiCloudImageLocator {
return api.MultiCloudImageLocator(r.Href)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/config.go#L662-L690
|
func (c *ConfigUpdater) SetDefaults() {
if len(c.Maps) == 0 {
cf := c.ConfigFile
if cf == "" {
cf = "prow/config.yaml"
} else {
logrus.Warnf(`config_file is deprecated, please switch to "maps": {"%s": "config"} before July 2018`, cf)
}
pf := c.PluginFile
if pf == "" {
pf = "prow/plugins.yaml"
} else {
logrus.Warnf(`plugin_file is deprecated, please switch to "maps": {"%s": "plugins"} before July 2018`, pf)
}
c.Maps = map[string]ConfigMapSpec{
cf: {
Name: "config",
},
pf: {
Name: "plugins",
},
}
}
for name, spec := range c.Maps {
spec.Namespaces = append([]string{spec.Namespace}, spec.AdditionalNamespaces...)
c.Maps[name] = spec
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd.go#L85-L92
|
func (r *ProtocolLXD) do(req *http.Request) (*http.Response, error) {
if r.bakeryClient != nil {
r.addMacaroonHeaders(req)
return r.bakeryClient.Do(req)
}
return r.http.Do(req)
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L456-L490
|
func stateHandlerMiddleware(stateHandlers types.StateHandlers) proxy.Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/__setup" {
var s *types.ProviderState
decoder := json.NewDecoder(r.Body)
decoder.Decode(&s)
// Setup any provider state
for _, state := range s.States {
sf, stateFound := stateHandlers[state]
if !stateFound {
log.Printf("[WARN] state handler not found for state: %v", state)
} else {
// Execute state handler
if err := sf(); err != nil {
log.Printf("[ERROR] state handler for '%v' errored: %v", state, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
}
w.WriteHeader(http.StatusOK)
return
}
log.Println("[DEBUG] skipping state handler for request", r.RequestURI)
// Pass through to application
next.ServeHTTP(w, r)
})
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.