_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L297-L303
|
func (b *BasicDataType) IsEquivalent(other DataType) bool {
t, ok := other.(*BasicDataType)
if !ok {
return false
}
return *t == *b
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L496-L565
|
func (c *Client) EnsureBuildableJob(spec *prowapi.ProwJobSpec) error {
var jobInfo *JobInfo
// wait at most 20 seconds for the job to appear
getJobInfoBackoff := wait.Backoff{
Duration: time.Duration(10) * time.Second,
Factor: 1,
Jitter: 0,
Steps: 2,
}
getJobErr := wait.ExponentialBackoff(getJobInfoBackoff, func() (bool, error) {
var jobErr error
jobInfo, jobErr = c.GetJobInfo(spec)
if jobErr != nil && !strings.Contains(strings.ToLower(jobErr.Error()), "404 not found") {
return false, jobErr
}
return jobInfo != nil, nil
})
if getJobErr != nil {
return fmt.Errorf("Job %v does not exist", spec.Job)
}
isParameterized := c.JobParameterized(jobInfo)
c.logger.Tracef("JobHasParameters: %v", isParameterized)
if isParameterized || len(jobInfo.Builds) > 0 {
return nil
}
buildErr := c.LaunchBuild(spec, nil)
if buildErr != nil {
return buildErr
}
backoff := wait.Backoff{
Duration: time.Duration(5) * time.Second,
Factor: 1,
Jitter: 1,
Steps: 10,
}
return wait.ExponentialBackoff(backoff, func() (bool, error) {
c.logger.Debugf("Waiting for job %v to become parameterized", spec.Job)
jobInfo, _ := c.GetJobInfo(spec)
isParameterized := false
if jobInfo != nil {
isParameterized = c.JobParameterized(jobInfo)
if isParameterized && jobInfo.LastBuild != nil {
c.logger.Debugf("Job %v is now parameterized, aborting the build", spec.Job)
err := c.Abort(getJobName(spec), jobInfo.LastBuild)
if err != nil {
c.logger.Infof("Couldn't abort build #%v for job %v: %v", jobInfo.LastBuild.Number, spec.Job, err)
}
}
}
// don't stop on (possibly) intermittent errors
return isParameterized, nil
})
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/publish.go#L30-L45
|
func (p *Publisher) Publish(request types.PublishRequest) error {
log.Println("[DEBUG] pact publisher: publish pact")
if p.pactClient == nil {
c := NewClient()
p.pactClient = c
}
err := request.Validate()
if err != nil {
return err
}
return p.pactClient.PublishPacts(request)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2704-L2730
|
func (c *Client) GetColumnProjectCard(columnID int, cardNumber int) (*ProjectCard, error) {
c.log("GetColumnProjectCard", columnID, cardNumber)
if c.fake {
return nil, nil
}
path := fmt.Sprintf("/projects/columns/%d/cards", columnID)
var cards []ProjectCard
err := c.readPaginatedResults(
path,
acceptNone,
func() interface{} {
return &[]ProjectCard{}
},
func(obj interface{}) {
cards = append(cards, *(obj.(*[]ProjectCard))...)
},
)
if err != nil {
return nil, err
}
for _, card := range cards {
if card.ContentID == cardNumber {
return &card, nil
}
}
return nil, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/stringutil/rand.go#L37-L43
|
func RandomStrings(slen uint, n int) (ss []string) {
ss = make([]string, 0, n)
for i := 0; i < n; i++ {
ss = append(ss, randString(slen))
}
return ss
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/ppsutil/util.go#L237-L260
|
func PipelineReqFromInfo(pipelineInfo *ppsclient.PipelineInfo) *ppsclient.CreatePipelineRequest {
return &ppsclient.CreatePipelineRequest{
Pipeline: pipelineInfo.Pipeline,
Transform: pipelineInfo.Transform,
ParallelismSpec: pipelineInfo.ParallelismSpec,
HashtreeSpec: pipelineInfo.HashtreeSpec,
Egress: pipelineInfo.Egress,
OutputBranch: pipelineInfo.OutputBranch,
ScaleDownThreshold: pipelineInfo.ScaleDownThreshold,
ResourceRequests: pipelineInfo.ResourceRequests,
ResourceLimits: pipelineInfo.ResourceLimits,
Input: pipelineInfo.Input,
Description: pipelineInfo.Description,
CacheSize: pipelineInfo.CacheSize,
EnableStats: pipelineInfo.EnableStats,
Batch: pipelineInfo.Batch,
MaxQueueSize: pipelineInfo.MaxQueueSize,
Service: pipelineInfo.Service,
ChunkSpec: pipelineInfo.ChunkSpec,
DatumTimeout: pipelineInfo.DatumTimeout,
JobTimeout: pipelineInfo.JobTimeout,
Salt: pipelineInfo.Salt,
}
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/english/step3.go#L10-L56
|
func step3(w *snowballword.SnowballWord) bool {
suffix, suffixRunes := w.FirstSuffix(
"ational", "tional", "alize", "icate", "ative",
"iciti", "ical", "ful", "ness",
)
// If it is not in R1, do nothing
if suffix == "" || len(suffixRunes) > len(w.RS)-w.R1start {
return false
}
// Handle special cases where we're not just going to
// replace the suffix with another suffix: there are
// other things we need to do.
//
if suffix == "ative" {
// If in R2, delete.
//
if len(w.RS)-w.R2start >= 5 {
w.RemoveLastNRunes(len(suffixRunes))
return true
}
return false
}
// Handle a suffix that was found, which is going
// to be replaced with a different suffix.
//
var repl string
switch suffix {
case "ational":
repl = "ate"
case "tional":
repl = "tion"
case "alize":
repl = "al"
case "icate", "iciti", "ical":
repl = "ic"
case "ful", "ness":
repl = ""
}
w.ReplaceSuffixRunes(suffixRunes, []rune(repl), true)
return true
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L120-L122
|
func (s *FakeVCDClient) DeployVApp(templateName, templateHref, vcdHref string) (vapp *vcloudclient.VApp, err error) {
return s.FakeVApp, s.ErrUnDeployFake
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L1815-L1819
|
func (v EventNodeHighlightRequested) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoOverlay18(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/go-audio/transforms/blob/51830ccc35a5ce4be9d09b1d1f3f82dad376c240/stereo_pan.go#L14-L36
|
func StereoPan(buf *audio.FloatBuffer, pan float64) error {
if buf == nil || buf.Format == nil || buf.Format.NumChannels != 2 {
return audio.ErrInvalidBuffer
}
if pan < 0 || pan > 1 {
return errors.New("invalid pan value, should be betwen 0 and 1")
}
if pan == 0.5 {
return nil
}
if pan < 0.5 {
for i := 0; i+2 <= len(buf.Data); i += 2 {
buf.Data[i+1] *= (pan * 2)
}
} else {
for i := 0; i+2 <= len(buf.Data); i += 2 {
buf.Data[i] *= ((1 - pan) * 2)
}
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/commentpruner/commentpruner.go#L67-L104
|
func (c *EventClient) PruneComments(shouldPrune func(github.IssueComment) bool) {
c.once.Do(func() {
botName, err := c.ghc.BotName()
if err != nil {
c.log.WithError(err).Error("failed to get the bot's name. Pruning will consider all comments.")
}
comments, err := c.ghc.ListIssueComments(c.org, c.repo, c.number)
if err != nil {
c.log.WithError(err).Errorf("failed to list comments for %s/%s#%d", c.org, c.repo, c.number)
}
if botName != "" {
for _, comment := range comments {
if comment.User.Login == botName {
c.comments = append(c.comments, comment)
}
}
}
})
c.lock.Lock()
defer c.lock.Unlock()
var remaining []github.IssueComment
for _, comment := range c.comments {
removed := false
if shouldPrune(comment) {
if err := c.ghc.DeleteComment(c.org, c.repo, comment.ID); err != nil {
c.log.WithError(err).Errorf("failed to delete stale comment with ID '%d'", comment.ID)
} else {
removed = true
}
}
if !removed {
remaining = append(remaining, comment)
}
}
c.comments = remaining
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/docker/container/container.go#L358-L411
|
func (c *Container) Commit(client provision.BuilderDockerClient, limiter provision.ActionLimiter, writer io.Writer, isDeploy bool) (string, error) {
log.Debugf("committing container %s", c.ID)
repository, tag := image.SplitImageName(c.BuildingImage)
opts := docker.CommitContainerOptions{Container: c.ID, Repository: repository, Tag: tag}
done := limiter.Start(c.HostAddr)
image, err := client.CommitContainer(opts)
done()
if err != nil {
return "", log.WrapError(errors.Wrapf(err, "error in commit container %s", c.ID))
}
tags := []string{tag}
if isDeploy && tag != "latest" {
tags = append(tags, "latest")
err = client.TagImage(fmt.Sprintf("%s:%s", repository, tag), docker.TagImageOptions{
Repo: repository,
Tag: "latest",
Force: true,
})
if err != nil {
return "", log.WrapError(errors.Wrapf(err, "error in tag container %s", c.ID))
}
}
imgHistory, err := client.ImageHistory(c.BuildingImage)
imgSize := ""
if err == nil && len(imgHistory) > 0 {
fullSize := imgHistory[0].Size
if len(imgHistory) > 1 && strings.Contains(imgHistory[1].CreatedBy, "tail -f /dev/null") {
fullSize += imgHistory[1].Size
}
imgSize = fmt.Sprintf("(%.02fMB)", float64(fullSize)/1024/1024)
}
fmt.Fprintf(writer, " ---> Sending image to repository %s\n", imgSize)
log.Debugf("image %s generated from container %s", image.ID, c.ID)
for _, tag := range tags {
maxTry, _ := config.GetInt("docker:registry-max-try")
if maxTry <= 0 {
maxTry = 3
}
for i := 0; i < maxTry; i++ {
err = dockercommon.PushImage(client, repository, tag, dockercommon.RegistryAuthConfig(repository))
if err != nil {
fmt.Fprintf(writer, "Could not send image, trying again. Original error: %s\n", err.Error())
log.Errorf("error in push image %s: %s", c.BuildingImage, err)
time.Sleep(time.Second)
continue
}
break
}
if err != nil {
return "", log.WrapError(errors.Wrapf(err, "error in push image %s", c.BuildingImage))
}
}
return c.BuildingImage, nil
}
|
https://github.com/mastahyeti/fakeca/blob/c1d84b1b473e99212130da7b311dd0605de5ed0a/configuration.go#L200-L204
|
func NotBefore(value time.Time) Option {
return func(c *configuration) {
c.notBefore = &value
}
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/network.go#L415-L464
|
func (v *VM) NetworkAdapters() ([]*NetworkAdapter, error) {
vmxPath, err := v.VmxPath()
if err != nil {
return nil, err
}
vmx, err := readVmx(vmxPath)
if err != nil {
return nil, err
}
var adapters []*NetworkAdapter
// VMX ethernet adapters seem to not be zero based
for i := 1; i <= v.totalNetworkAdapters(vmx); i++ {
id := strconv.Itoa(i)
prefix := "ethernet" + id
if vmx[prefix+".present"] == "FALSE" {
continue
}
wakeOnPckRcv, _ := strconv.ParseBool(vmx[prefix+".wakeOnPcktRcv"])
lnkStateProp, _ := strconv.ParseBool(vmx[prefix+".linkStatePropagation.enable"])
present, _ := strconv.ParseBool(vmx[prefix+".present"])
startConnected, _ := strconv.ParseBool(vmx[prefix+".startConnected"])
address, _ := net.ParseMAC(vmx[prefix+".address"])
genAddress, _ := net.ParseMAC(vmx[prefix+".generatedAddress"])
vswitch, _ := GetVSwitch(vmx[prefix+".vnet"])
adapter := &NetworkAdapter{
ID: id,
present: present,
ConnType: NetworkType(vmx[prefix+".connectionType"]),
Vdevice: VNetDevice(vmx[prefix+".virtualDev"]),
WakeOnPcktRcv: wakeOnPckRcv,
LinkStatePropagation: lnkStateProp,
MacAddrType: MacAddressType(vmx[prefix+".addressType"]),
MacAddress: address,
VSwitch: vswitch,
StartConnected: startConnected,
GeneratedMacAddress: genAddress,
GeneratedMacAddressOffset: vmx[prefix+".generatedAddressOffset"],
PciSlotNumber: vmx[prefix+".pciSlotNumber"],
}
adapters = append(adapters, adapter)
}
return adapters, nil
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/storage/postgres/storage.go#L361-L381
|
func (s *Storage) Delete(ctx context.Context, subjectID, accessToken, refreshToken string, expiredAtFrom, expiredAtTo *time.Time) (int64, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "postgres.storage.delete")
defer span.Finish()
where, args := s.where(subjectID, accessToken, refreshToken, expiredAtFrom, expiredAtTo)
if where.Len() == 0 {
return 0, fmt.Errorf("session cannot be deleted, no where parameter provided: %s", where.String())
}
query := "DELETE FROM " + s.schema + "." + s.table + " WHERE " + where.String()
labels := prometheus.Labels{"query": "delete"}
start := time.Now()
result, err := s.db.Exec(query, args...)
s.incQueries(labels, start)
if err != nil {
s.incError(labels)
return 0, err
}
return result.RowsAffected()
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L700-L712
|
func (r *Rule) SetAttr(key string, value interface{}) {
rhs := ExprFromValue(value)
if attr, ok := r.attrs[key]; ok {
attr.RHS = rhs
} else {
r.attrs[key] = &bzl.AssignExpr{
LHS: &bzl.Ident{Name: key},
RHS: rhs,
Op: "=",
}
}
r.updated = true
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2325-L2329
|
func (v *Scope) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger23(&r, v)
return r.Error()
}
|
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/ecdsa.go#L163-L171
|
func (ePub *ECDSAPublicKey) Equals(o Key) bool {
oPub, ok := o.(*ECDSAPublicKey)
if !ok {
return false
}
return ePub.pub.X != nil && ePub.pub.Y != nil && oPub.pub.X != nil && oPub.pub.Y != nil &&
0 == ePub.pub.X.Cmp(oPub.pub.X) && 0 == ePub.pub.Y.Cmp(oPub.pub.Y)
}
|
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L272-L311
|
func (c *Consumer) Close() (err error) {
c.closeOnce.Do(func() {
close(c.dying)
<-c.dead
if e := c.release(); e != nil {
err = e
}
if e := c.consumer.Close(); e != nil {
err = e
}
close(c.messages)
close(c.errors)
if e := c.leaveGroup(); e != nil {
err = e
}
close(c.partitions)
close(c.notifications)
// drain
for range c.messages {
}
for range c.errors {
}
for p := range c.partitions {
_ = p.Close()
}
for range c.notifications {
}
c.client.release()
if c.ownClient {
if e := c.client.Close(); e != nil {
err = e
}
}
})
return
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L226-L232
|
func (w *Writer) Delete2(bs []byte) (n *skiplist.Node, success bool) {
if n := w.GetNode(bs); n != nil {
return n, w.DeleteNode(n)
}
return nil, false
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L766-L783
|
func (c APIClient) ListTag(f func(*pfs.ListTagsResponse) error) error {
listTagClient, err := c.ObjectAPIClient.ListTags(c.Ctx(), &pfs.ListTagsRequest{IncludeObject: true})
if err != nil {
return grpcutil.ScrubGRPC(err)
}
for {
listTagResponse, err := listTagClient.Recv()
if err != nil {
if err == io.EOF {
return nil
}
return grpcutil.ScrubGRPC(err)
}
if err := f(listTagResponse); err != nil {
return err
}
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6660-L6669
|
func (u StellarMessage) GetTransaction() (result TransactionEnvelope, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "Transaction" {
result = *u.Transaction
ok = true
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/layertree.go#L208-L217
|
func (p *ProfileSnapshotParams) Do(ctx context.Context) (timings []PaintProfile, err error) {
// execute
var res ProfileSnapshotReturns
err = cdp.Execute(ctx, CommandProfileSnapshot, p, &res)
if err != nil {
return nil, err
}
return res.Timings, nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/connection.go#L871-L873
|
func (c *Connection) getLastActivityTime() time.Time {
return time.Unix(0, c.lastActivity.Load())
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L369-L377
|
func getAddress(rawURL string) string {
parsedURL, err := url.Parse(rawURL)
if err != nil {
return ""
}
splitHost := strings.Split(parsedURL.Host, ":")
return splitHost[0]
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/recipes/key.go#L154-L163
|
func newUniqueEphemeralKV(s *concurrency.Session, prefix, val string) (ek *EphemeralKV, err error) {
for {
newKey := fmt.Sprintf("%s/%v", prefix, time.Now().UnixNano())
ek, err = newEphemeralKV(s, newKey, val)
if err == nil || err != ErrKeyExists {
break
}
}
return ek, err
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/parser/github.go#L35-L41
|
func getGitHubUrl(bootstrapScript string) string {
//```https://raw.githubusercontent.com/kubicorn/kubicorn/master/bootstrap/amazon_k8s_ubuntu_16.04_node.sh```
//should be
//```https://raw.githubusercontent.com/kubicorn/bootstrap/master/amazon_k8s_ubuntu_16.04_node.sh"```
return fmt.Sprintf("%s%s/%s/%s", githubProtocol, githubRepo, githubBranch, bootstrapScript[10:])
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L215-L219
|
func (v SetShowPaintRectsParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoOverlay2(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/obj.go#L205-L216
|
func NewGoogleClientFromEnv() (Client, error) {
bucket, ok := os.LookupEnv(GoogleBucketEnvVar)
if !ok {
return nil, fmt.Errorf("%s not found", GoogleBucketEnvVar)
}
creds, ok := os.LookupEnv(GoogleCredEnvVar)
if !ok {
return nil, fmt.Errorf("%s not found", GoogleCredEnvVar)
}
opts := []option.ClientOption{option.WithCredentialsJSON([]byte(creds))}
return NewGoogleClient(bucket, opts)
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L366-L368
|
func (m *Mat) Set1D(x int, value Scalar) {
C.cvSet1D(unsafe.Pointer(m), C.int(x), (C.CvScalar)(value))
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1916-L1925
|
func (u OperationBody) GetManageOfferOp() (result ManageOfferOp, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "ManageOfferOp" {
result = *u.ManageOfferOp
ok = true
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L1490-L1494
|
func (v *GetMetadataParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb12(&r, v)
return r.Error()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/ostree/ostree_transport.go#L41-L61
|
func (t ostreeTransport) ValidatePolicyConfigurationScope(scope string) error {
sep := strings.Index(scope, ":")
if sep < 0 {
return errors.Errorf("Invalid ostree: scope %s: Must include a repo", scope)
}
repo := scope[:sep]
if !strings.HasPrefix(repo, "/") {
return errors.Errorf("Invalid ostree: scope %s: repository must be an absolute path", scope)
}
cleaned := filepath.Clean(repo)
if cleaned != repo {
return errors.Errorf(`Invalid ostree: scope %s: Uses non-canonical path format, perhaps try with path %s`, scope, cleaned)
}
// FIXME? In the namespaces within a repo,
// we could be verifying the various character set and length restrictions
// from docker/distribution/reference.regexp.go, but other than that there
// are few semantically invalid strings.
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/easyjson.go#L154-L158
|
func (v *StartObservingParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoBackgroundservice1(&r, v)
return r.Error()
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/auth.go#L379-L410
|
func removeTeam(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
name := r.URL.Query().Get(":name")
allowed := permission.Check(t, permission.PermTeamDelete,
permission.Context(permTypes.CtxTeam, name),
)
if !allowed {
return &errors.HTTP{Code: http.StatusNotFound, Message: fmt.Sprintf(`Team "%s" not found.`, name)}
}
evt, err := event.New(&event.Opts{
Target: teamTarget(name),
Kind: permission.PermTeamDelete,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermTeamReadEvents, permission.Context(permTypes.CtxTeam, name)),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
err = servicemanager.Team.Remove(name)
if err != nil {
if _, ok := err.(*authTypes.ErrTeamStillUsed); ok {
msg := fmt.Sprintf("This team cannot be removed because there are still references to it:\n%s", err)
return &errors.HTTP{Code: http.StatusForbidden, Message: msg}
}
if err == authTypes.ErrTeamNotFound {
return &errors.HTTP{Code: http.StatusNotFound, Message: fmt.Sprintf(`Team "%s" not found.`, name)}
}
return err
}
return nil
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/deep_copy.go#L152-L178
|
func callDeepCopy(src, dst reflect.Value) bool {
dc := src.MethodByName("DeepCopy")
if !dc.IsValid() {
return false
}
if dc.Type().NumIn() != 0 {
return false
}
if dc.Type().NumOut() != 1 {
return false
}
otype := dc.Type().Out(0)
if dst.Kind() == reflect.Ptr &&
dst.Type().Elem() == otype {
cpy := reflect.New(dst.Type().Elem())
out := dc.Call(nil)[0]
cpy.Elem().Set(out)
dst.Set(cpy)
return true
}
if dst.Type() == otype {
out := dc.Call(nil)[0]
dst.Set(out)
return true
}
return false
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/s3/error.go#L66-L68
|
func invalidFilePathError(w http.ResponseWriter, r *http.Request) {
writeError(w, r, http.StatusBadRequest, "InvalidFilePath", "Invalid file path")
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L578-L582
|
func (v TakeResponseBodyForInterceptionAsStreamParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork4(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/util.go#L134-L141
|
func serverVersion(h http.Header) *semver.Version {
verStr := h.Get("X-Server-Version")
// backward compatibility with etcd 2.0
if verStr == "" {
verStr = "2.0.0"
}
return semver.Must(semver.NewVersion(verStr))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cast/cast.go#L131-L133
|
func (p *StopCastingParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandStopCasting, p, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L129-L132
|
func (p DispatchKeyEventParams) WithLocation(location int64) *DispatchKeyEventParams {
p.Location = location
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L381-L383
|
func (p *SetShowDebugBordersParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetShowDebugBorders, p, nil)
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/loader.go#L13-L19
|
func (f *Flags) DumpAST(b bool) {
if b {
f.flags |= MaskDumpAST
} else {
f.flags &= ^MaskDumpAST
}
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L104-L113
|
func VerifyBody(expectedBody []byte) http.HandlerFunc {
return CombineHandlers(
func(w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
req.Body.Close()
Expect(err).ShouldNot(HaveOccurred())
Expect(body).Should(Equal(expectedBody), "Body Mismatch")
},
)
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/codegenerator/model/model.go#L200-L266
|
func (apiDefs APIDefinitions) GenerateCode(goOutputDir, modelData string, downloaded time.Time) {
downloadedTime = downloaded
for i := range apiDefs {
apiDefs[i].PackageName = "tc" + strings.ToLower(apiDefs[i].Data.Name())
// Used throughout docs, and also methods that use the class, we need a
// variable name to be used when referencing the go type. It should not
// clash with either the package name or the go type of the principle
// member of the package (e.g. awsprovisioner.AwsProvisioner). We'll
// lowercase the name (e.g. awsProvisioner) and if that clashes with
// either package or principle member, we'll just use my<Name>. This
// results in e.g. `var myQueue queue.Queue`, but `var awsProvisioner
// awsprovisioner.AwsProvisioner`.
apiDefs[i].ExampleVarName = strings.ToLower(string(apiDefs[i].Data.Name()[0])) + apiDefs[i].Data.Name()[1:]
if apiDefs[i].ExampleVarName == apiDefs[i].Data.Name() || apiDefs[i].ExampleVarName == apiDefs[i].PackageName {
apiDefs[i].ExampleVarName = "my" + apiDefs[i].Data.Name()
}
apiDefs[i].PackagePath = filepath.Join(goOutputDir, apiDefs[i].PackageName)
err = os.MkdirAll(apiDefs[i].PackagePath, 0755)
exitOnFail(err)
fmt.Printf("Generating go types for %s\n", apiDefs[i].PackageName)
job := &jsonschema2go.Job{
Package: apiDefs[i].PackageName,
URLs: apiDefs[i].schemaURLs,
ExportTypes: true,
TypeNameBlacklist: apiDefs[i].members,
DisableNestedStructs: true,
}
result, err := job.Execute()
exitOnFail(err)
apiDefs[i].schemas = result.SchemaSet
typesSourceFile := filepath.Join(apiDefs[i].PackagePath, "types.go")
FormatSourceAndSave(typesSourceFile, result.SourceCode)
fmt.Printf("Generating functions and methods for %s\n", job.Package)
content := `
// The following code is AUTO-GENERATED. Please DO NOT edit.
// To update this generated code, run the following command:
// in the /codegenerator/model subdirectory of this project,
// making sure that ` + "`${GOPATH}/bin` is in your `PATH`" + `:
//
// go install && go generate
//
// This package was generated from the schema defined at
// ` + apiDefs[i].URL + `
`
content += apiDefs[i].generateAPICode()
sourceFile := filepath.Join(apiDefs[i].PackagePath, apiDefs[i].PackageName+".go")
FormatSourceAndSave(sourceFile, []byte(content))
}
content := "Generated: " + strconv.FormatInt(downloadedTime.Unix(), 10) + "\n"
content += "The following file is an auto-generated static dump of the API models at time of code generation.\n"
content += "It is provided here for reference purposes, but is not used by any code.\n"
content += "\n"
for i := range apiDefs {
content += text.Underline(apiDefs[i].URL)
content += apiDefs[i].Data.String() + "\n\n"
for _, url := range apiDefs[i].schemas.SortedSanitizedURLs() {
content += text.Underline(url)
content += apiDefs[i].schemas.SubSchema(url).String() + "\n\n"
}
}
exitOnFail(ioutil.WriteFile(modelData, []byte(content), 0644))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L348-L352
|
func (v GetFramesWithManifestsReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoApplicationcache3(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L1540-L1559
|
func (s *storageCeph) cephRBDVolumeDumpToFile(sourceVolumeName string, file string) error {
logger.Debugf(`Dumping RBD storage volume "%s" to "%s"`, sourceVolumeName, file)
args := []string{
"export",
"--id", s.UserName,
"--cluster", s.ClusterName,
sourceVolumeName,
file,
}
rbdSendCmd := exec.Command("rbd", args...)
err := rbdSendCmd.Run()
if err != nil {
return err
}
logger.Debugf(`Dumped RBD storage volume "%s" to "%s"`, sourceVolumeName, file)
return nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2832-L2840
|
func (u PathPaymentResult) MustSuccess() PathPaymentResultSuccess {
val, ok := u.GetSuccess()
if !ok {
panic("arm Success is not set")
}
return val
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L177-L179
|
func (s *selectable) AllByClass(text string) *MultiSelection {
return newMultiSelection(s.session, s.selectors.Append(target.Class, text))
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/dump.go#L81-L130
|
func dumpTable(tx *sql.Tx, table, schema string) (string, error) {
statements := []string{schema}
// Query all rows.
rows, err := tx.Query(fmt.Sprintf("SELECT * FROM %s ORDER BY rowid", table))
if err != nil {
return "", errors.Wrap(err, "failed to fetch rows")
}
defer rows.Close()
// Figure column names
columns, err := rows.Columns()
if err != nil {
return "", errors.Wrap(err, "failed to get columns")
}
// Generate an INSERT statement for each row.
for i := 0; rows.Next(); i++ {
raw := make([]interface{}, len(columns)) // Raw column values
row := make([]interface{}, len(columns))
for i := range raw {
row[i] = &raw[i]
}
err := rows.Scan(row...)
if err != nil {
return "", errors.Wrapf(err, "failed to scan row %d", i)
}
values := make([]string, len(columns))
for j, v := range raw {
switch v := v.(type) {
case int64:
values[j] = strconv.FormatInt(v, 10)
case string:
values[j] = fmt.Sprintf("'%s'", v)
case []byte:
values[j] = fmt.Sprintf("'%s'", string(v))
case time.Time:
values[j] = strconv.FormatInt(v.Unix(), 10)
default:
if v != nil {
return "", fmt.Errorf("bad type in column %s of row %d", columns[j], i)
}
values[j] = "NULL"
}
}
statement := fmt.Sprintf("INSERT INTO %s VALUES(%s);", table, strings.Join(values, ","))
statements = append(statements, statement)
}
return strings.Join(statements, "\n") + "\n", nil
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/merger/merger.go#L167-L180
|
func substituteRule(r *rule.Rule, substitutions map[string]string, info rule.KindInfo) {
for attr := range info.SubstituteAttrs {
if expr := r.Attr(attr); expr != nil {
expr = rule.MapExprStrings(expr, func(s string) string {
if rename, ok := substitutions[strings.TrimPrefix(s, ":")]; ok {
return ":" + rename
} else {
return s
}
})
r.SetAttr(attr, expr)
}
}
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/spanish/step3.go#L9-L33
|
func step3(word *snowballword.SnowballWord) bool {
suffix, suffixRunes := word.FirstSuffixIfIn(word.RVstart, len(word.RS),
"os", "a", "o", "á", "í", "ó", "e", "é",
)
// No suffix found, nothing to do.
//
if suffix == "" {
return false
}
// Remove all these suffixes
word.RemoveLastNRunes(len(suffixRunes))
if suffix == "e" || suffix == "é" {
// If preceded by gu with the u in RV delete the u
//
guSuffix, _ := word.FirstSuffix("gu")
if guSuffix != "" {
word.RemoveLastNRunes(1)
}
}
return true
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L865-L867
|
func (p *RemoveScriptToEvaluateOnNewDocumentParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandRemoveScriptToEvaluateOnNewDocument, p, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L469-L478
|
func (p *GetDocumentParams) Do(ctx context.Context) (root *cdp.Node, err error) {
// execute
var res GetDocumentReturns
err = cdp.Execute(ctx, CommandGetDocument, p, &res)
if err != nil {
return nil, err
}
return res.Root, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L2430-L2434
|
func (v *EventConsoleProfileFinished) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler23(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L4794-L4798
|
func (v *CompileScriptParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime45(&r, v)
return r.Error()
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/routes.go#L252-L263
|
func (r *routes) calculateBroadcast(name PeerName, establishedAndSymmetric bool) []PeerName {
hops := []PeerName{}
peer, found := r.peers.byName[name]
if !found {
return hops
}
if found, reached := peer.routes(r.ourself.Peer, establishedAndSymmetric); found {
r.ourself.forEachConnectedPeer(establishedAndSymmetric, reached,
func(remotePeer *Peer) { hops = append(hops, remotePeer.Name) })
}
return hops
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L5694-L5701
|
func (r *MultiCloudImageMatcher) Locator(api *API) *MultiCloudImageMatcherLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.MultiCloudImageMatcherLocator(l["href"])
}
}
return nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L86-L94
|
func (b *TransactionBuilder) Sign(signers ...string) (result TransactionEnvelopeBuilder) {
result.Mutate(b)
for _, s := range signers {
result.Mutate(Sign{s})
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/memory.go#L38-L47
|
func (p *GetDOMCountersParams) Do(ctx context.Context) (documents int64, nodes int64, jsEventListeners int64, err error) {
// execute
var res GetDOMCountersReturns
err = cdp.Execute(ctx, CommandGetDOMCounters, nil, &res)
if err != nil {
return 0, 0, 0, err
}
return res.Documents, res.Nodes, res.JsEventListeners, nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/daemon/daemon_dest.go#L127-L144
|
func (d *daemonImageDestination) Commit(ctx context.Context) error {
logrus.Debugf("docker-daemon: Closing tar stream")
if err := d.Destination.Commit(ctx); err != nil {
return err
}
if err := d.writer.Close(); err != nil {
return err
}
d.committed = true // We may still fail, but we are done sending to imageLoadGoroutine.
logrus.Debugf("docker-daemon: Waiting for status")
select {
case <-ctx.Done():
return ctx.Err()
case err := <-d.statusChannel:
return err
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/prstatus/prstatus.go#L173-L288
|
func (da *DashboardAgent) HandlePrStatus(queryHandler PullRequestQueryHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
serverError := func(action string, err error) {
da.log.WithError(err).Errorf("Error %s.", action)
msg := fmt.Sprintf("500 Internal server error %s: %v", action, err)
http.Error(w, msg, http.StatusInternalServerError)
}
data := UserData{
Login: false,
}
// Get existing session. Invalidate everything if we fail and continue as
// if not logged in.
session, err := da.goac.CookieStore.Get(r, tokenSession)
if err != nil {
da.log.WithError(err).Info("Failed to get existing session, invalidating GitHub login session")
if err := invalidateGitHubSession(w, r, session); err != nil {
serverError("Failed to invalidate GitHub session", err)
return
}
}
// If access token exists, get user login using the access token. This is a
// chance to validate whether the access token is consumable or not. If
// not, we invalidate the sessions and continue as if not logged in.
token, ok := session.Values[tokenKey].(*oauth2.Token)
var user *github.User
var botName string
if ok && token.Valid() {
githubClient := github.NewClient(func() []byte { return []byte(token.AccessToken) }, github.DefaultGraphQLEndpoint, github.DefaultAPIEndpoint)
var err error
botName, err = githubClient.BotName()
user = &github.User{Login: botName}
if err != nil {
if strings.Contains(err.Error(), "401") {
da.log.Info("Failed to access GitHub with existing access token, invalidating GitHub login session")
if err := invalidateGitHubSession(w, r, session); err != nil {
serverError("Failed to invalidate GitHub session", err)
return
}
} else {
serverError("Error with getting user login", err)
return
}
}
}
if user != nil {
login := user.Login
data.Login = true
// Saves login. We save the login under 2 cookies. One for the use of client to render the
// data and one encoded for server to verify the identity of the authenticated user.
http.SetCookie(w, &http.Cookie{
Name: loginSession,
Value: login,
Path: "/",
Expires: time.Now().Add(time.Hour * 24 * 30),
Secure: true,
})
session.Values[loginKey] = login
if err := session.Save(r, w); err != nil {
serverError("Save oauth session", err)
return
}
// Construct query
ghc := github.NewClient(func() []byte { return []byte(token.AccessToken) }, github.DefaultGraphQLEndpoint, github.DefaultAPIEndpoint)
query := da.ConstructSearchQuery(login)
if err := r.ParseForm(); err == nil {
if q := r.Form.Get("query"); q != "" {
query = q
}
}
// If neither repo nor org is specified in the search query. We limit the search to repos that
// are configured with either Prow or Tide.
if !queryConstrainsRepos(query) {
for _, v := range da.repos {
query += fmt.Sprintf(" repo:\"%s\"", v)
}
}
pullRequests, err := queryHandler.QueryPullRequests(context.Background(), ghc, query)
if err != nil {
serverError("Error with querying user data.", err)
return
}
var pullRequestWithContexts []PullRequestWithContexts
for _, pr := range pullRequests {
prcontexts, err := queryHandler.GetHeadContexts(ghc, pr)
if err != nil {
serverError("Error with getting head context of pr", err)
continue
}
pullRequestWithContexts = append(pullRequestWithContexts, PullRequestWithContexts{
Contexts: prcontexts,
PullRequest: pr,
})
}
data.PullRequestsWithContexts = pullRequestWithContexts
}
marshaledData, err := json.Marshal(data)
if err != nil {
da.log.WithError(err).Error("Error with marshalling user data.")
}
if v := r.URL.Query().Get("var"); v != "" {
fmt.Fprintf(w, "var %s = ", v)
w.Write(marshaledData)
io.WriteString(w, ";")
} else {
w.Write(marshaledData)
}
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2830-L2834
|
func (v *HandleJavaScriptDialogParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage29(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L445-L449
|
func (v RemoteLocation) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget4(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/ast.go#L12-L19
|
func (ast *AST) Visit() <-chan node.Node {
c := make(chan node.Node)
go func() {
defer close(c)
ast.Root.Visit(c)
}()
return c
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gexec/session.go#L269-L275
|
func Terminate() {
trackedSessionsMutex.Lock()
defer trackedSessionsMutex.Unlock()
for _, session := range trackedSessions {
session.Terminate()
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/systeminfo/systeminfo.go#L43-L52
|
func (p *GetInfoParams) Do(ctx context.Context) (gpu *GPUInfo, modelName string, modelVersion string, commandLine string, err error) {
// execute
var res GetInfoReturns
err = cdp.Execute(ctx, CommandGetInfo, nil, &res)
if err != nil {
return nil, "", "", "", err
}
return res.Gpu, res.ModelName, res.ModelVersion, res.CommandLine, nil
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/gzip.go#L51-L63
|
func (w *gzipResponseWriter) WriteHeader(code int) {
// Always set the Vary header, even if this particular request
// is not gzipped.
w.Header().Add("Vary", "Accept-Encoding")
if w.canGzip {
w.Header().Set("Content-Encoding", "gzip")
}
w.ResponseWriter.WriteHeader(code)
w.wroteHeader = true
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L842-L844
|
func (p *SetCookiesParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetCookies, p, nil)
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L76-L80
|
func QuoteItems(arr []string) []string {
return Map(arr, func(s string) string {
return strconv.Quote(s)
})
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cv.go#L241-L250
|
func MorphologyEx(src, dst, temp *IplImage, element *IplConvKernel, operation int, iterations int) {
C.cvMorphologyEx(
unsafe.Pointer(src),
unsafe.Pointer(dst),
unsafe.Pointer(temp),
(*C.IplConvKernel)(unsafe.Pointer(element)),
C.int(operation),
C.int(iterations),
)
}
|
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/shell.go#L175-L179
|
func (s *Shell) Pin(path string) error {
return s.Request("pin/add", path).
Option("recursive", true).
Exec(context.Background(), nil)
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/namespaced/namespaces.go#L49-L53
|
func (n *ns) Set(namespaces []string) {
n.Lock()
defer n.Unlock()
n.namespaces = namespaces
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L552-L607
|
func (s *storageBtrfs) StoragePoolVolumeCreate() error {
logger.Infof("Creating BTRFS storage volume \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
_, err := s.StoragePoolMount()
if err != nil {
return err
}
isSnapshot := shared.IsSnapshot(s.volume.Name)
// Create subvolume path on the storage pool.
var customSubvolumePath string
if isSnapshot {
customSubvolumePath = s.getCustomSnapshotSubvolumePath(s.pool.Name)
} else {
customSubvolumePath = s.getCustomSubvolumePath(s.pool.Name)
}
if !shared.PathExists(customSubvolumePath) {
err := os.MkdirAll(customSubvolumePath, 0700)
if err != nil {
return err
}
}
// Create subvolume.
var customSubvolumeName string
if isSnapshot {
customSubvolumeName = getStoragePoolVolumeSnapshotMountPoint(s.pool.Name, s.volume.Name)
} else {
customSubvolumeName = getStoragePoolVolumeMountPoint(s.pool.Name, s.volume.Name)
}
err = btrfsSubVolumeCreate(customSubvolumeName)
if err != nil {
return err
}
// apply quota
if s.volume.Config["size"] != "" {
size, err := shared.ParseByteSizeString(s.volume.Config["size"])
if err != nil {
return err
}
err = s.StorageEntitySetQuota(storagePoolVolumeTypeCustom, size, nil)
if err != nil {
return err
}
}
logger.Infof("Created BTRFS storage volume \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
return nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/permission.go#L83-L111
|
func removeRole(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
if !permission.Check(t, permission.PermRoleDelete) {
return permission.ErrUnauthorized
}
roleName := r.URL.Query().Get(":name")
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypeRole, Value: roleName},
Kind: permission.PermRoleDelete,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermRoleReadEvents),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
usersWithRole, err := auth.ListUsersWithRole(roleName)
if err != nil {
return err
}
if len(usersWithRole) != 0 {
return &errors.HTTP{Code: http.StatusPreconditionFailed, Message: permTypes.ErrRemoveRoleWithUsers.Error()}
}
err = permission.DestroyRole(roleName)
if err == permTypes.ErrRoleNotFound {
return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
return err
}
|
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L263-L268
|
func WithStrictSignatureVerification(required bool) Option {
return func(p *PubSub) error {
p.signStrict = required
return nil
}
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/route.go#L160-L165
|
func (m *Route) validateTypeEnum(path, location string, value interface{}) error {
if err := validate.Enum(path, location, value, routeTypeTypePropEnum); err != nil {
return err
}
return nil
}
|
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L318-L320
|
func (b *Backend) Logger(subsystemTag string) Logger {
return &slog{LevelInfo, subsystemTag, b}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/peribolos/main.go#L719-L744
|
func configureOrgMeta(client orgMetadataClient, orgName string, want org.Metadata) error {
cur, err := client.GetOrg(orgName)
if err != nil {
return fmt.Errorf("failed to get %s metadata: %v", orgName, err)
}
change := false
change = updateString(&cur.BillingEmail, want.BillingEmail) || change
change = updateString(&cur.Company, want.Company) || change
change = updateString(&cur.Email, want.Email) || change
change = updateString(&cur.Name, want.Name) || change
change = updateString(&cur.Description, want.Description) || change
change = updateString(&cur.Location, want.Location) || change
if want.DefaultRepositoryPermission != nil {
w := string(*want.DefaultRepositoryPermission)
change = updateString(&cur.DefaultRepositoryPermission, &w)
}
change = updateBool(&cur.HasOrganizationProjects, want.HasOrganizationProjects) || change
change = updateBool(&cur.HasRepositoryProjects, want.HasRepositoryProjects) || change
change = updateBool(&cur.MembersCanCreateRepositories, want.MembersCanCreateRepositories) || change
if change {
if _, err := client.EditOrg(orgName, *cur); err != nil {
return fmt.Errorf("failed to edit %s metadata: %v", orgName, err)
}
}
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/http.go#L14-L36
|
func (a *API) BuildRequest(resource, action, href string, params rsapi.APIParams) (*http.Request, error) {
// First lookup metadata
res, ok := GenMetadata[resource]
if !ok {
return nil, fmt.Errorf("No resource with name '%s'", resource)
}
act := res.GetAction(action)
if act == nil {
return nil, fmt.Errorf("No action with name '%s' on %s", action, resource)
}
// Now lookup action request HTTP method, url, params and payload.
vars, err := res.ExtractVariables(href)
if err != nil {
return nil, err
}
actionURL, err := act.URL(vars)
if err != nil {
return nil, err
}
_, queryParams := rsapi.IdentifyParams(act, params)
return a.BuildHTTPRequest("GET", actionURL.Path, "1.6", queryParams, nil)
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/float.go#L99-L110
|
func (f Float) MarshalJSON() ([]byte, error) {
if !f.Valid {
return []byte("null"), nil
}
if math.IsInf(f.Float64, 0) || math.IsNaN(f.Float64) {
return nil, &json.UnsupportedValueError{
Value: reflect.ValueOf(f.Float64),
Str: strconv.FormatFloat(f.Float64, 'g', -1, 64),
}
}
return []byte(strconv.FormatFloat(f.Float64, 'f', -1, 64)), nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/election.go#L44-L46
|
func NewElection(s *Session, pfx string) *Election {
return &Election{session: s, keyPrefix: pfx + "/"}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L552-L563
|
func (g *Gateway) cachedRaftNodes() ([]string, error) {
var addresses []string
err := g.db.Transaction(func(tx *db.NodeTx) error {
var err error
addresses, err = tx.RaftNodeAddresses()
return err
})
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch raft nodes")
}
return addresses, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/networks.go#L567-L579
|
func (c *Cluster) NetworkDelete(name string) error {
id, _, err := c.NetworkGet(name)
if err != nil {
return err
}
err = exec(c.db, "DELETE FROM networks WHERE id=?", id)
if err != nil {
return err
}
return nil
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/geometry/geometry.go#L42-L88
|
func CurveRectangle(gc draw2d.GraphicContext, x0, y0,
rectWidth, rectHeight float64, stroke, fill color.Color) {
radius := (rectWidth + rectHeight) / 4
x1 := x0 + rectWidth
y1 := y0 + rectHeight
if rectWidth/2 < radius {
if rectHeight/2 < radius {
gc.MoveTo(x0, (y0+y1)/2)
gc.CubicCurveTo(x0, y0, x0, y0, (x0+x1)/2, y0)
gc.CubicCurveTo(x1, y0, x1, y0, x1, (y0+y1)/2)
gc.CubicCurveTo(x1, y1, x1, y1, (x1+x0)/2, y1)
gc.CubicCurveTo(x0, y1, x0, y1, x0, (y0+y1)/2)
} else {
gc.MoveTo(x0, y0+radius)
gc.CubicCurveTo(x0, y0, x0, y0, (x0+x1)/2, y0)
gc.CubicCurveTo(x1, y0, x1, y0, x1, y0+radius)
gc.LineTo(x1, y1-radius)
gc.CubicCurveTo(x1, y1, x1, y1, (x1+x0)/2, y1)
gc.CubicCurveTo(x0, y1, x0, y1, x0, y1-radius)
}
} else {
if rectHeight/2 < radius {
gc.MoveTo(x0, (y0+y1)/2)
gc.CubicCurveTo(x0, y0, x0, y0, x0+radius, y0)
gc.LineTo(x1-radius, y0)
gc.CubicCurveTo(x1, y0, x1, y0, x1, (y0+y1)/2)
gc.CubicCurveTo(x1, y1, x1, y1, x1-radius, y1)
gc.LineTo(x0+radius, y1)
gc.CubicCurveTo(x0, y1, x0, y1, x0, (y0+y1)/2)
} else {
gc.MoveTo(x0, y0+radius)
gc.CubicCurveTo(x0, y0, x0, y0, x0+radius, y0)
gc.LineTo(x1-radius, y0)
gc.CubicCurveTo(x1, y0, x1, y0, x1, y0+radius)
gc.LineTo(x1, y1-radius)
gc.CubicCurveTo(x1, y1, x1, y1, x1-radius, y1)
gc.LineTo(x0+radius, y1)
gc.CubicCurveTo(x0, y1, x0, y1, x0, y1-radius)
}
}
gc.Close()
gc.SetStrokeColor(stroke)
gc.SetFillColor(fill)
gc.SetLineWidth(10.0)
gc.FillStroke()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L300-L305
|
func (h *dbHashTree) Glob(pattern string, f func(string, *NodeProto) error) error {
pattern = clean(pattern)
return h.View(func(tx *bolt.Tx) error {
return glob(tx, pattern, f)
})
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/put_command.go#L67-L77
|
func putCommandFunc(cmd *cobra.Command, args []string) {
key, value, opts := getPutOp(args)
ctx, cancel := commandCtx(cmd)
resp, err := mustClientFromCmd(cmd).Put(ctx, key, value, opts...)
cancel()
if err != nil {
ExitWithError(ExitError, err)
}
display.Put(*resp)
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L351-L353
|
func (l *Logger) Warnf(format string, args ...interface{}) {
l.Output(2, LevelWarn, fmt.Sprintf(format, args...))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L1046-L1050
|
func (v *SetDownloadBehaviorParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage11(&r, v)
return r.Error()
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/rl10.go#L16-L18
|
func New(host string, auth rsapi.Authenticator) *API {
return fromAPI(rsapi.New(host, auth))
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/api_server.go#L148-L156
|
func (a *apiServer) LogResp(request interface{}, response interface{}, err error, duration time.Duration) {
if err == nil {
a.pachLogger.LogAtLevelFromDepth(request, response, err, duration, logrus.InfoLevel, 4)
} else if authclient.IsErrNotActivated(err) {
a.pachLogger.LogAtLevelFromDepth(request, response, err, duration, logrus.DebugLevel, 4)
} else {
a.pachLogger.LogAtLevelFromDepth(request, response, err, duration, logrus.ErrorLevel, 4)
}
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/commands.go#L242-L328
|
func (a *API) ShowActions(cmd, hrefPrefix string, values ActionCommands) error {
res, _, err := a.parseResource(cmd, hrefPrefix, values)
resource := ""
if err == nil {
resource = res.Name
}
if _, ok := a.Metadata[hrefPrefix]; ok {
resource = hrefPrefix
}
resNames := make([]string, len(a.Metadata))
actionsByRes := make(map[string][][]string)
idx := 0
for n := range a.Metadata {
resNames[idx] = n
idx++
}
sort.Strings(resNames)
for _, resName := range resNames {
actionsByRes[resName] = make([][]string, 0)
res := a.Metadata[resName]
if resource != "" && resName != resource {
continue
}
for _, action := range res.Actions {
for _, pattern := range action.PathPatterns {
vars := pattern.Variables
ivars := make([]interface{}, len(vars))
for i, v := range vars {
ivars[i] = interface{}(":" + v)
}
subPattern := pattern.Pattern
pat := fmt.Sprintf(subPattern, ivars...)
var ok bool
pat, ok = shortenPattern(res, pat, "/actions/"+action.Name)
if !ok {
pat, _ = shortenPattern(res, pat, "/"+action.Name)
}
actionsByRes[resName] = append(actionsByRes[resName], []string{action.Name, pat})
}
}
}
var lines []string
actionTitle := "Action"
hrefTitle := "Href"
resourceTitle := "Resource"
maxActionLen := len(actionTitle)
maxHrefLen := len(hrefTitle)
maxResourceLen := len(resourceTitle)
for res, actions := range actionsByRes {
if len(res) > maxResourceLen {
maxResourceLen = len(res)
}
for _, action := range actions {
if len(action[0]) > maxActionLen {
maxActionLen = len(action[0])
}
if len(action[1]) > maxHrefLen {
maxHrefLen = len(action[1])
}
}
}
for idx, resName := range resNames {
as := actionsByRes[resName]
for i, action := range as {
title := ""
if i == 0 {
title = resName
if idx > 0 {
lines = append(lines, fmt.Sprintf("%s\t%s\t%s",
strings.Repeat("-", maxResourceLen),
strings.Repeat("-", maxActionLen),
strings.Repeat("-", maxHrefLen)))
}
}
lines = append(lines, fmt.Sprintf("%s\t%s\t%s", title, action[0], action[1]))
}
}
w := tabwriter.NewWriter(os.Stdout, 0, 4, 1, ' ', 0)
w.Write([]byte(fmt.Sprintf("%s\t%s\t%s\n", resourceTitle, actionTitle, hrefTitle)))
w.Write([]byte(fmt.Sprintf("%s\t%s\t%s\n", strings.Repeat("=", maxResourceLen),
strings.Repeat("=", maxActionLen),
strings.Repeat("=", maxHrefLen))))
w.Write([]byte(strings.Join(lines, "\n")))
w.Write([]byte("\n"))
return w.Flush()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/easyjson.go#L905-L909
|
func (v *EventCacheStorageContentUpdated) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoStorage10(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/version/version.go#L18-L48
|
func NewDottedVersion(versionString string) (*DottedVersion, error) {
formatError := fmt.Errorf("Invalid version format: %s", versionString)
split := strings.Split(versionString, ".")
if len(split) < 2 {
return nil, formatError
}
maj, err := strconv.Atoi(split[0])
if err != nil {
return nil, formatError
}
min, err := strconv.Atoi(split[1])
if err != nil {
return nil, formatError
}
patch := -1
if len(split) == 3 {
patch, err = strconv.Atoi(split[2])
if err != nil {
return nil, formatError
}
}
return &DottedVersion{
Major: maj,
Minor: min,
Patch: patch,
}, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/initupload/run.go#L105-L148
|
func processCloneLog(logfile string, uploadTargets map[string]gcs.UploadFunc) (bool, string, error) {
var cloneRecords []clone.Record
data, err := ioutil.ReadFile(logfile)
if err != nil {
return true, "", fmt.Errorf("could not read clone log: %v", err)
}
if err = json.Unmarshal(data, &cloneRecords); err != nil {
return true, "", fmt.Errorf("could not unmarshal clone records: %v", err)
}
// Do not read from cloneLog directly. Instead create multiple readers from cloneLog so it can
// be uploaded to both clone-log.txt and build-log.txt on failure.
cloneLog := bytes.Buffer{}
var failed bool
var mainRefSHA string
for idx, record := range cloneRecords {
cloneLog.WriteString(clone.FormatRecord(record))
failed = failed || record.Failed
// fill in mainRefSHA with FinalSHA from the first record
if idx == 0 {
mainRefSHA = record.FinalSHA
}
}
uploadTargets["clone-log.txt"] = gcs.DataUpload(bytes.NewReader(cloneLog.Bytes()))
uploadTargets["clone-records.json"] = gcs.FileUpload(logfile)
if failed {
uploadTargets["build-log.txt"] = gcs.DataUpload(bytes.NewReader(cloneLog.Bytes()))
passed := !failed
now := time.Now().Unix()
finished := gcs.Finished{
Timestamp: &now,
Passed: &passed,
Result: "FAILURE",
}
finishedData, err := json.Marshal(&finished)
if err != nil {
return true, mainRefSHA, fmt.Errorf("could not marshal finishing data: %v", err)
}
uploadTargets["finished.json"] = gcs.DataUpload(bytes.NewReader(finishedData))
}
return failed, mainRefSHA, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L530-L552
|
func (t *BlockedReason) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch BlockedReason(in.String()) {
case BlockedReasonOther:
*t = BlockedReasonOther
case BlockedReasonCsp:
*t = BlockedReasonCsp
case BlockedReasonMixedContent:
*t = BlockedReasonMixedContent
case BlockedReasonOrigin:
*t = BlockedReasonOrigin
case BlockedReasonInspector:
*t = BlockedReasonInspector
case BlockedReasonSubresourceFilter:
*t = BlockedReasonSubresourceFilter
case BlockedReasonContentType:
*t = BlockedReasonContentType
case BlockedReasonCollapsedByClient:
*t = BlockedReasonCollapsedByClient
default:
in.AddError(errors.New("unknown BlockedReason value"))
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/oci.go#L35-L41
|
func manifestOCI1FromComponents(config imgspecv1.Descriptor, src types.ImageSource, configBlob []byte, layers []imgspecv1.Descriptor) genericManifest {
return &manifestOCI1{
src: src,
configBlob: configBlob,
m: manifest.OCI1FromComponents(config, layers),
}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/package.go#L127-L143
|
func (pkg *goPackage) firstGoFile() string {
goSrcs := []platformStringsBuilder{
pkg.library.sources,
pkg.binary.sources,
pkg.test.sources,
}
for _, sb := range goSrcs {
if sb.strs != nil {
for s := range sb.strs {
if strings.HasSuffix(s, ".go") {
return s
}
}
}
}
return ""
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/harness/api_checkers.go#L63-L73
|
func RunAPIChecks(
t *testing.T,
newTracer func() (tracer opentracing.Tracer, closer func()),
opts ...APICheckOption,
) {
s := &APICheckSuite{newTracer: newTracer}
for _, opt := range opts {
opt(s)
}
suite.Run(t, s)
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L309-L311
|
func (m *Message) EmbedReader(name string, r io.Reader, settings ...FileSetting) {
m.embedded = m.appendFile(m.embedded, fileFromReader(name, r), settings)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.