_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L556-L575
|
func findOwnersForFile(log *logrus.Entry, path string, ownerMap map[string]map[*regexp.Regexp]sets.String) string {
d := path
for ; d != baseDirConvention; d = canonicalize(filepath.Dir(d)) {
relative, err := filepath.Rel(d, path)
if err != nil {
log.WithError(err).WithField("path", path).Errorf("Unable to find relative path between %q and path.", d)
return ""
}
for re, n := range ownerMap[d] {
if re != nil && !re.MatchString(relative) {
continue
}
if len(n) != 0 {
return d
}
}
}
return ""
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/adt/interval_tree.go#L178-L218
|
func (ivt *IntervalTree) Delete(ivl Interval) bool {
z := ivt.find(ivl)
if z == nil {
return false
}
y := z
if z.left != nil && z.right != nil {
y = z.successor()
}
x := y.left
if x == nil {
x = y.right
}
if x != nil {
x.parent = y.parent
}
if y.parent == nil {
ivt.root = x
} else {
if y == y.parent.left {
y.parent.left = x
} else {
y.parent.right = x
}
y.parent.updateMax()
}
if y != z {
z.iv = y.iv
z.updateMax()
}
if y.color() == black && x != nil {
ivt.deleteFixup(x)
}
ivt.count--
return true
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/nodecontainer.go#L160-L203
|
func nodeContainerUpdate(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
var config nodecontainer.NodeContainerConfig
err = ParseInput(r, &config)
if err != nil {
return err
}
poolName := InputValue(r, "pool")
var ctxs []permTypes.PermissionContext
if poolName != "" {
ctxs = append(ctxs, permission.Context(permTypes.CtxPool, poolName))
}
if !permission.Check(t, permission.PermNodecontainerUpdate, ctxs...) {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypeNodeContainer, Value: config.Name},
Kind: permission.PermNodecontainerUpdate,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermPoolReadEvents, ctxs...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
config.Name = r.URL.Query().Get(":name")
err = nodecontainer.UpdateContainer(poolName, &config)
if err != nil {
if err == nodecontainer.ErrNodeContainerNotFound {
return &tsuruErrors.HTTP{
Code: http.StatusNotFound,
Message: err.Error(),
}
}
if _, ok := err.(nodecontainer.ValidationErr); ok {
return &tsuruErrors.HTTP{
Code: http.StatusBadRequest,
Message: err.Error(),
}
}
return err
}
return nil
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L657-L664
|
func AddWithMask(src1, src2, dst, mask *IplImage) {
C.cvAdd(
unsafe.Pointer(src1),
unsafe.Pointer(src2),
unsafe.Pointer(dst),
unsafe.Pointer(mask),
)
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L142-L148
|
func LoadWorkspaceData(path, pkg string, data []byte) (*File, error) {
ast, err := bzl.ParseWorkspace(path, data)
if err != nil {
return nil, err
}
return ScanAST(pkg, ast), nil
}
|
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/collection.go#L88-L90
|
func (c *Collection) Collection() *mgo.Collection {
return c.Connection.Session.DB(c.Database).C(c.Name)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L289-L303
|
func (pr *prReject) UnmarshalJSON(data []byte) error {
*pr = prReject{}
var tmp prReject
if err := paranoidUnmarshalJSONObjectExactFields(data, map[string]interface{}{
"type": &tmp.Type,
}); err != nil {
return err
}
if tmp.Type != prTypeReject {
return InvalidPolicyFormatError(fmt.Sprintf("Unexpected policy requirement type \"%s\"", tmp.Type))
}
*pr = *newPRReject()
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_src.go#L66-L93
|
func (s *ociImageSource) GetManifest(ctx context.Context, instanceDigest *digest.Digest) ([]byte, string, error) {
var dig digest.Digest
var mimeType string
if instanceDigest == nil {
dig = digest.Digest(s.descriptor.Digest)
mimeType = s.descriptor.MediaType
} else {
dig = *instanceDigest
// XXX: instanceDigest means that we don't immediately have the context of what
// mediaType the manifest has. In OCI this means that we don't know
// what reference it came from, so we just *assume* that its
// MediaTypeImageManifest.
// FIXME: We should actually be able to look up the manifest in the index,
// and see the MIME type there.
mimeType = imgspecv1.MediaTypeImageManifest
}
manifestPath, err := s.ref.blobPath(dig, s.sharedBlobDir)
if err != nil {
return nil, "", err
}
m, err := ioutil.ReadFile(manifestPath)
if err != nil {
return nil, "", err
}
return m, mimeType, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L7839-L7843
|
func (v CookieParam) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork61(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/powered_by.go#L14-L29
|
func (mw *PoweredByMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
poweredBy := xPoweredByDefault
if mw.XPoweredBy != "" {
poweredBy = mw.XPoweredBy
}
return func(w ResponseWriter, r *Request) {
w.Header().Add("X-Powered-By", poweredBy)
// call the handler
h(w, r)
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/crc16/main.go#L95-L108
|
func Checksum(data []byte) []byte {
var crc uint16
var out bytes.Buffer
for _, b := range data {
crc = ((crc << 8) & 0xffff) ^ crc16tab[((crc>>8)^uint16(b))&0x00FF]
}
err := binary.Write(&out, binary.LittleEndian, crc)
if err != nil {
panic(err)
}
return out.Bytes()
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L376-L378
|
func (m *Mat) Set3D(x, y, z int, value Scalar) {
C.cvSet3D(unsafe.Pointer(m), C.int(x), C.int(y), C.int(z), (C.CvScalar)(value))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L919-L922
|
func (p SearchInResourceParams) WithCaseSensitive(caseSensitive bool) *SearchInResourceParams {
p.CaseSensitive = caseSensitive
return &p
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_dest.go#L389-L417
|
func isManifestInvalidError(err error) bool {
errors, ok := err.(errcode.Errors)
if !ok || len(errors) == 0 {
return false
}
err = errors[0]
ec, ok := err.(errcode.ErrorCoder)
if !ok {
return false
}
switch ec.ErrorCode() {
// ErrorCodeManifestInvalid is returned by OpenShift with acceptschema2=false.
case v2.ErrorCodeManifestInvalid:
return true
// ErrorCodeTagInvalid is returned by docker/distribution (at least as of commit ec87e9b6971d831f0eff752ddb54fb64693e51cd)
// when uploading to a tag (because it can’t find a matching tag inside the manifest)
case v2.ErrorCodeTagInvalid:
return true
// ErrorCodeUnsupported with 'Invalid JSON syntax' is returned by AWS ECR when
// uploading an OCI manifest that is (correctly, according to the spec) missing
// a top-level media type. See libpod issue #1719
// FIXME: remove this case when ECR behavior is fixed
case errcode.ErrorCodeUnsupported:
return strings.Contains(err.Error(), "Invalid JSON syntax")
default:
return false
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2discovery/discovery.go#L63-L69
|
func JoinCluster(lg *zap.Logger, durl, dproxyurl string, id types.ID, config string) (string, error) {
d, err := newDiscovery(lg, durl, dproxyurl, id)
if err != nil {
return "", err
}
return d.joinCluster(config)
}
|
https://github.com/sayanarijit/gopassgen/blob/cf555de90ad6031f567a55be7d7c90f2fbe8389a/gopassgen.go#L97-L143
|
func Generate(p Policy) (string, error) {
// Character length based policies should not be negative
if p.MinLength < 0 || p.MaxLength < 0 || p.MinUppers < 0 ||
p.MinLowers < 0 || p.MinDigits < 0 || p.MinSpclChars < 0 {
return "", ErrNegativeLengthNotAllowed
}
collectiveMinLength := p.MinUppers + p.MinLowers + p.MinDigits + p.MinSpclChars
// Min length is the collective min length
if collectiveMinLength > p.MinLength {
p.MinLength = collectiveMinLength
}
// Max length should be greater than collective minimun length
if p.MinLength > p.MaxLength {
return "", ErrMaxLengthExceeded
}
if p.MaxLength == 0 {
return "", nil
}
capsAlpha := []byte(p.UpperPool)
smallAlpha := []byte(p.LowerPool)
digits := []byte(p.DigitPool)
spclChars := []byte(p.SpclCharPool)
allChars := []byte(p.UpperPool + p.LowerPool + p.DigitPool + p.SpclCharPool)
passwd := CreateRandom(capsAlpha, p.MinUppers)
passwd = append(passwd, CreateRandom(smallAlpha, p.MinLowers)...)
passwd = append(passwd, CreateRandom(digits, p.MinDigits)...)
passwd = append(passwd, CreateRandom(spclChars, p.MinSpclChars)...)
passLen := len(passwd)
if passLen < p.MaxLength {
randLength := random(p.MinLength, p.MaxLength)
passwd = append(passwd, CreateRandom(allChars, randLength-passLen)...)
}
Shuffle(passwd)
return string(passwd), nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/transports/transports.go#L70-L72
|
func ImageName(ref types.ImageReference) string {
return ref.Transport().Name() + ":" + ref.StringWithinTransport()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L897-L922
|
func EtcdNodePortService(local bool, opts *AssetOpts) *v1.Service {
var clientNodePort int32
if local {
clientNodePort = 32379
}
return &v1.Service{
TypeMeta: metav1.TypeMeta{
Kind: "Service",
APIVersion: "v1",
},
ObjectMeta: objectMeta(etcdName, labels(etcdName), nil, opts.Namespace),
Spec: v1.ServiceSpec{
Type: v1.ServiceTypeNodePort,
Selector: map[string]string{
"app": etcdName,
},
Ports: []v1.ServicePort{
{
Port: 2379,
Name: "client-port",
NodePort: clientNodePort,
},
},
},
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L817-L852
|
func (r *Raft) appendConfigurationEntry(future *configurationChangeFuture) {
configuration, err := nextConfiguration(r.configurations.latest, r.configurations.latestIndex, future.req)
if err != nil {
future.respond(err)
return
}
r.logger.Info(fmt.Sprintf("Updating configuration with %s (%v, %v) to %+v",
future.req.command, future.req.serverID, future.req.serverAddress, configuration.Servers))
// In pre-ID compatibility mode we translate all configuration changes
// in to an old remove peer message, which can handle all supported
// cases for peer changes in the pre-ID world (adding and removing
// voters). Both add peer and remove peer log entries are handled
// similarly on old Raft servers, but remove peer does extra checks to
// see if a leader needs to step down. Since they both assert the full
// configuration, then we can safely call remove peer for everything.
if r.protocolVersion < 2 {
future.log = Log{
Type: LogRemovePeerDeprecated,
Data: encodePeers(configuration, r.trans),
}
} else {
future.log = Log{
Type: LogConfiguration,
Data: encodeConfiguration(configuration),
}
}
r.dispatchLogs([]*logFuture{&future.logFuture})
index := future.Index()
r.configurations.latest = configuration
r.configurations.latestIndex = index
r.leaderState.commitment.setConfiguration(configuration)
r.startStopReplication()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L176-L179
|
func (p DeleteCookiesParams) WithPath(path string) *DeleteCookiesParams {
p.Path = path
return &p
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/blockers/blockers.go#L73-L85
|
func FindAll(ghc githubClient, log *logrus.Entry, label, orgRepoTokens string) (Blockers, error) {
issues, err := search(
context.Background(),
ghc,
log,
blockerQuery(label, orgRepoTokens),
)
if err != nil {
return Blockers{}, fmt.Errorf("error searching for blocker issues: %v", err)
}
return fromIssues(issues), nil
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/lan.go#L76-L81
|
func (c *Client) GetLan(dcid, lanid string) (*Lan, error) {
url := lanPath(dcid, lanid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Lan{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/http.go#L249-L265
|
func IdentifyParams(a *metadata.Action, params APIParams) (payloadParams APIParams, queryParams APIParams) {
payloadParamNames := a.PayloadParamNames()
payloadParams = make(APIParams)
for _, n := range payloadParamNames {
if p, ok := params[n]; ok {
payloadParams[n] = p
}
}
queryParamNames := a.QueryParamNames()
queryParams = make(APIParams)
for _, n := range queryParamNames {
if p, ok := params[n]; ok {
queryParams[n] = p
}
}
return payloadParams, queryParams
}
|
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/usage.go#L110-L118
|
func Usage(prefix string, spec interface{}) error {
// The default is to output the usage information as a table
// Create tabwriter instance to support table output
tabs := tabwriter.NewWriter(os.Stdout, 1, 0, 4, ' ', 0)
err := Usagef(prefix, spec, tabs, DefaultTableFormat)
tabs.Flush()
return err
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/russian/step2.go#L9-L15
|
func step2(word *snowballword.SnowballWord) bool {
suffix, _ := word.RemoveFirstSuffixIn(word.RVstart, "и")
if suffix != "" {
return true
}
return false
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L53-L57
|
func JoinPage(url string, options ...Option) *Page {
pageOptions := config{}.Merge(options)
session := api.NewWithClient(url, pageOptions.HTTPClient)
return newPage(session)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/progress.go#L166-L177
|
func (pr *Progress) IsPaused() bool {
switch pr.State {
case ProgressStateProbe:
return pr.Paused
case ProgressStateReplicate:
return pr.ins.full()
case ProgressStateSnapshot:
return true
default:
panic("unexpected state")
}
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L204-L216
|
func (w *Writer) Put2(bs []byte) (n *skiplist.Node) {
var success bool
x := w.newItem(bs, w.useMemoryMgmt)
x.bornSn = w.getCurrSn()
n, success = w.store.Insert2(unsafe.Pointer(x), w.insCmp, w.existCmp, w.buf,
w.rand.Float32, &w.slSts1)
if success {
w.count++
} else {
w.freeItem(x)
}
return
}
|
https://github.com/apparentlymart/go-rundeck-api/blob/2c962acae81080a937c350a5bea054c239f27a81/rundeck/project.go#L66-L68
|
func (c *Client) DeleteProject(name string) error {
return c.delete([]string{"project", name})
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/user_command.go#L174-L199
|
func userGetCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 1 {
ExitWithError(ExitBadArgs, fmt.Errorf("user get command requires user name as its argument"))
}
name := args[0]
client := mustClientFromCmd(cmd)
resp, err := client.Auth.UserGet(context.TODO(), name)
if err != nil {
ExitWithError(ExitError, err)
}
if userShowDetail {
fmt.Printf("User: %s\n", name)
for _, role := range resp.Roles {
fmt.Printf("\n")
roleResp, err := client.Auth.RoleGet(context.TODO(), role)
if err != nil {
ExitWithError(ExitError, err)
}
display.RoleGet(role, *roleResp)
}
} else {
display.UserGet(name, *resp)
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/boltdb/boltdb.go#L255-L275
|
func (bdc *cache) appendReplacementCandidates(candidates []prioritize.CandidateWithTime, scopeBucket *bolt.Bucket, digest digest.Digest) []prioritize.CandidateWithTime {
b := scopeBucket.Bucket([]byte(digest.String()))
if b == nil {
return candidates
}
_ = b.ForEach(func(k, v []byte) error {
t := time.Time{}
if err := t.UnmarshalBinary(v); err != nil {
return err
}
candidates = append(candidates, prioritize.CandidateWithTime{
Candidate: types.BICReplacementCandidate{
Digest: digest,
Location: types.BICLocationReference{Opaque: string(k)},
},
LastSeen: t,
})
return nil
}) // FIXME? Log error (but throttle the log volume on repeated accesses)?
return candidates
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L714-L718
|
func (v SetProduceCompilationCacheParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage7(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/cookies.go#L63-L73
|
func (c *Cookies) Delete(name string) {
ck := http.Cookie{
Name: name,
Value: "v",
// Setting a time in the distant past, like the unix epoch, removes the cookie,
// since it has long expired.
Expires: time.Unix(0, 0),
}
http.SetCookie(c.res, &ck)
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/handler.go#L46-L71
|
func (hs *HandlersStack) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Get a context for the request from ctxPool.
c := getContext(w, r)
// Set some "good practice" default headers.
c.ResponseWriter.Header().Set("Cache-Control", "no-cache")
c.ResponseWriter.Header().Set("Content-Type", "application/json")
c.ResponseWriter.Header().Set("Connection", "keep-alive")
c.ResponseWriter.Header().Set("Vary", "Accept-Encoding")
//c.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
c.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "X-Requested-With")
c.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
// Always recover form panics.
defer c.Recover()
// Enter the handlers stack.
c.Next()
// Respnose data
// if c.written == false {
// c.Fail(errors.New("not written"))
// }
// Put the context to ctxPool
putContext(c)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L141-L161
|
func cephRBDVolumeMap(clusterName string, poolName string, volumeName string,
volumeType string, userName string) (string, error) {
devPath, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"--pool", poolName,
"map",
fmt.Sprintf("%s_%s", volumeType, volumeName))
if err != nil {
return "", err
}
idx := strings.Index(devPath, "/dev/rbd")
if idx < 0 {
return "", fmt.Errorf("Failed to detect mapped device path")
}
devPath = devPath[idx:]
return strings.TrimSpace(devPath), nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5905-L5913
|
func (u TransactionMeta) MustOperations() []OperationMeta {
val, ok := u.GetOperations()
if !ok {
panic("arm Operations is not set")
}
return val
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/spyglass.go#L317-L359
|
func (sg *Spyglass) ExtraLinks(src string) ([]ExtraLink, error) {
artifacts, err := sg.FetchArtifacts(src, "", 1000000, []string{"started.json"})
// Failing to find started.json is okay, just return nothing quietly.
if err != nil || len(artifacts) == 0 {
logrus.WithError(err).Debugf("Failed to find started.json while looking for extra links.")
return nil, nil
}
// Failing to read an artifact we already know to exist shouldn't happen, so that's an error.
content, err := artifacts[0].ReadAll()
if err != nil {
return nil, err
}
// Being unable to parse a successfully fetched started.json correctly is also an error.
started := metadata.Started{}
if err := json.Unmarshal(content, &started); err != nil {
return nil, err
}
// Not having any links is fine.
links, ok := started.Metadata.Meta("links")
if !ok {
return nil, nil
}
extraLinks := make([]ExtraLink, 0, len(*links))
for _, name := range links.Keys() {
m, ok := links.Meta(name)
if !ok {
// This should never happen, because Keys() should only return valid Metas.
logrus.Debugf("Got bad link key %q from %s, but that should be impossible.", name, artifacts[0].CanonicalLink())
continue
}
s := m.Strings()
link := ExtraLink{
Name: name,
URL: s["url"],
Description: s["description"],
}
if link.URL == "" || link.Name == "" {
continue
}
extraLinks = append(extraLinks, link)
}
return extraLinks, nil
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/helpers.go#L112-L120
|
func Includes(all, subset []string) bool {
for _, item := range subset {
if !Contains(all, item) {
return false
}
}
return true
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1298-L1302
|
func (v RequestNodeParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom13(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/db.go#L288-L291
|
func (c *Cluster) SetDefaultTimeout(timeout time.Duration) {
driver := c.db.Driver().(*dqlite.Driver)
driver.SetContextTimeout(timeout)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L68-L102
|
func keyToProto(defaultAppID string, k *Key) *pb.Reference {
appID := k.appID
if appID == "" {
appID = defaultAppID
}
n := 0
for i := k; i != nil; i = i.parent {
n++
}
e := make([]*pb.Path_Element, n)
for i := k; i != nil; i = i.parent {
n--
e[n] = &pb.Path_Element{
Type: &i.kind,
}
// At most one of {Name,Id} should be set.
// Neither will be set for incomplete keys.
if i.stringID != "" {
e[n].Name = &i.stringID
} else if i.intID != 0 {
e[n].Id = &i.intID
}
}
var namespace *string
if k.namespace != "" {
namespace = proto.String(k.namespace)
}
return &pb.Reference{
App: proto.String(appID),
NameSpace: namespace,
Path: &pb.Path{
Element: e,
},
}
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L744-L750
|
func AbsDiffScalar(src *IplImage, value Scalar, dst *IplImage) {
C.cvAbsDiffS(
unsafe.Pointer(src),
unsafe.Pointer(dst),
(C.CvScalar)(value),
)
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/route_info.go#L49-L70
|
func (ri *RouteInfo) Name(name string) *RouteInfo {
routeIndex := -1
for index, route := range ri.App.Routes() {
if route.Path == ri.Path && route.Method == ri.Method {
routeIndex = index
break
}
}
name = flect.Camelize(name)
if !strings.HasSuffix(name, "Path") {
name = name + "Path"
}
ri.PathName = name
if routeIndex != -1 {
ri.App.Routes()[routeIndex] = reflect.ValueOf(ri).Interface().(*RouteInfo)
}
return ri
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L4029-L4033
|
func (v *Initiator) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork27(&r, v)
return r.Error()
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/snapshot.go#L75-L80
|
func (c *Client) UpdateSnapshot(snapshotID string, request SnapshotProperties) (*Snapshot, error) {
url := snapshotColPath() + slash(snapshotID)
ret := &Snapshot{}
err := c.client.Patch(url, request, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cast/easyjson.go#L385-L389
|
func (v EventIssueUpdated) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCast4(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service_instance.go#L205-L276
|
func removeServiceInstance(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
unbindAll := r.URL.Query().Get("unbindall")
serviceName := r.URL.Query().Get(":service")
instanceName := r.URL.Query().Get(":instance")
serviceInstance, err := getServiceInstanceOrError(serviceName, instanceName)
if err != nil {
return err
}
keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "")
defer keepAliveWriter.Stop()
writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
w.Header().Set("Content-Type", "application/x-json-stream")
allowed := permission.Check(t, permission.PermServiceInstanceDelete,
contextsForServiceInstance(serviceInstance, serviceName)...,
)
if !allowed {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: serviceInstanceTarget(serviceName, instanceName),
Kind: permission.PermServiceInstanceDelete,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermServiceInstanceReadEvents,
contextsForServiceInstance(serviceInstance, serviceName)...),
})
if err != nil {
return err
}
evt.SetLogWriter(writer)
defer func() { evt.Done(err) }()
requestID := requestIDHeader(r)
unbindAllBool, _ := strconv.ParseBool(unbindAll)
if unbindAllBool {
if len(serviceInstance.Apps) > 0 {
for _, appName := range serviceInstance.Apps {
_, app, instErr := getServiceInstance(serviceInstance.ServiceName, serviceInstance.Name, appName)
if instErr != nil {
return instErr
}
fmt.Fprintf(evt, "Unbind app %q ...\n", app.GetName())
instErr = serviceInstance.UnbindApp(service.UnbindAppArgs{
App: app,
Restart: true,
ForceRemove: false,
Event: evt,
RequestID: requestID,
})
if instErr != nil {
return instErr
}
fmt.Fprintf(evt, "\nInstance %q is not bound to the app %q anymore.\n", serviceInstance.Name, app.GetName())
}
serviceInstance, err = getServiceInstanceOrError(serviceName, instanceName)
if err != nil {
return err
}
}
}
err = service.DeleteInstance(serviceInstance, evt, requestID)
if err != nil {
if err == service.ErrServiceInstanceBound {
return &tsuruErrors.HTTP{
Message: errors.Wrapf(err, `Applications bound to the service "%s": "%s"`+"\n", instanceName, strings.Join(serviceInstance.Apps, ",")).Error(),
Code: http.StatusBadRequest,
}
}
return err
}
evt.Write([]byte("service instance successfully removed\n"))
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/types.go#L40-L50
|
func (t *PressureLevel) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch PressureLevel(in.String()) {
case PressureLevelModerate:
*t = PressureLevelModerate
case PressureLevelCritical:
*t = PressureLevelCritical
default:
in.AddError(errors.New("unknown PressureLevel value"))
}
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/json-decode.go#L17-L148
|
func (cdc *Codec) decodeReflectJSON(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if info.Type.Kind() == reflect.Interface && rv.Kind() == reflect.Ptr {
panic("should not happen")
}
if printLog {
spew.Printf("(D) decodeReflectJSON(bz: %s, info: %v, rv: %#v (%v), fopts: %v)\n",
bz, info, rv.Interface(), rv.Type(), fopts)
defer func() {
fmt.Printf("(D) -> err: %v\n", err)
}()
}
// Special case for null for either interface, pointer, slice
// NOTE: This doesn't match the binary implementation completely.
if nullBytes(bz) {
rv.Set(reflect.Zero(rv.Type()))
return
}
// Dereference-and-construct pointers all the way.
// This works for pointer-pointers.
for rv.Kind() == reflect.Ptr {
if rv.IsNil() {
newPtr := reflect.New(rv.Type().Elem())
rv.Set(newPtr)
}
rv = rv.Elem()
}
// Special case:
if rv.Type() == timeType {
// Amino time strips the timezone, so must end with Z.
if len(bz) >= 2 && bz[0] == '"' && bz[len(bz)-1] == '"' {
if bz[len(bz)-2] != 'Z' {
err = fmt.Errorf("Amino:JSON time must be UTC and end with 'Z' but got %s.", bz)
return
}
} else {
err = fmt.Errorf("Amino:JSON time must be an RFC3339Nano string, but got %s.", bz)
return
}
}
// Handle override if a pointer to rv implements json.Unmarshaler.
if rv.Addr().Type().Implements(jsonUnmarshalerType) {
err = rv.Addr().Interface().(json.Unmarshaler).UnmarshalJSON(bz)
return
}
// Handle override if a pointer to rv implements UnmarshalAmino.
if info.IsAminoUnmarshaler {
// First, decode repr instance from bytes.
rrv, rinfo := reflect.New(info.AminoUnmarshalReprType).Elem(), (*TypeInfo)(nil)
rinfo, err = cdc.getTypeInfo_wlock(info.AminoUnmarshalReprType)
if err != nil {
return
}
err = cdc.decodeReflectJSON(bz, rinfo, rrv, fopts)
if err != nil {
return
}
// Then, decode from repr instance.
uwrm := rv.Addr().MethodByName("UnmarshalAmino")
uwouts := uwrm.Call([]reflect.Value{rrv})
erri := uwouts[0].Interface()
if erri != nil {
err = erri.(error)
}
return
}
switch ikind := info.Type.Kind(); ikind {
//----------------------------------------
// Complex
case reflect.Interface:
err = cdc.decodeReflectJSONInterface(bz, info, rv, fopts)
case reflect.Array:
err = cdc.decodeReflectJSONArray(bz, info, rv, fopts)
case reflect.Slice:
err = cdc.decodeReflectJSONSlice(bz, info, rv, fopts)
case reflect.Struct:
err = cdc.decodeReflectJSONStruct(bz, info, rv, fopts)
case reflect.Map:
err = cdc.decodeReflectJSONMap(bz, info, rv, fopts)
//----------------------------------------
// Signed, Unsigned
case reflect.Int64, reflect.Int:
fallthrough
case reflect.Uint64, reflect.Uint:
if bz[0] != '"' || bz[len(bz)-1] != '"' {
err = fmt.Errorf("invalid character -- Amino:JSON int/int64/uint/uint64 expects quoted values for javascript numeric support, got: %v.", string(bz))
if err != nil {
return
}
}
bz = bz[1 : len(bz)-1]
fallthrough
case reflect.Int32, reflect.Int16, reflect.Int8,
reflect.Uint32, reflect.Uint16, reflect.Uint8:
err = invokeStdlibJSONUnmarshal(bz, rv, fopts)
//----------------------------------------
// Misc
case reflect.Float32, reflect.Float64:
if !fopts.Unsafe {
return errors.New("Amino:JSON float* support requires `amino:\"unsafe\"`.")
}
fallthrough
case reflect.Bool, reflect.String:
err = invokeStdlibJSONUnmarshal(bz, rv, fopts)
//----------------------------------------
// Default
default:
panic(fmt.Sprintf("unsupported type %v", info.Type.Kind()))
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L215-L224
|
func (p *CreateBrowserContextParams) Do(ctx context.Context) (browserContextID BrowserContextID, err error) {
// execute
var res CreateBrowserContextReturns
err = cdp.Execute(ctx, CommandCreateBrowserContext, nil, &res)
if err != nil {
return "", err
}
return res.BrowserContextID, nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L242-L254
|
func (q *Query) Offset(offset int) *Query {
q = q.clone()
if offset < 0 {
q.err = errors.New("datastore: negative query offset")
return q
}
if offset > math.MaxInt32 {
q.err = errors.New("datastore: query offset overflow")
return q
}
q.offset = int32(offset)
return q
}
|
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/sentinel.go#L178-L202
|
func (s *Sentinel) HTTP(listener net.Listener, handler http.Handler, opts ...ServerOption) error {
s.Lock()
defer s.Unlock()
if s.started {
return ErrAlreadyStarted
}
var err error
// create server and apply options
server := &http.Server{
Handler: handler,
}
for _, o := range opts {
if err = o(server); err != nil {
return err
}
}
// register server
return s.Register(func() error {
return server.Serve(listener)
}, server.Shutdown, IgnoreServerClosed, IgnoreNetOpError)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/profiler.go#L66-L75
|
func (p *GetBestEffortCoverageParams) Do(ctx context.Context) (result []*ScriptCoverage, err error) {
// execute
var res GetBestEffortCoverageReturns
err = cdp.Execute(ctx, CommandGetBestEffortCoverage, nil, &res)
if err != nil {
return nil, err
}
return res.Result, nil
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/http.go#L15-L31
|
func NewHTTPTemplateFetcher(urls []string) (*HTTPTemplateFetcher, error) {
f := &HTTPTemplateFetcher{
URLs: make([]string, len(urls)),
}
for k, v := range urls {
u, err := url.Parse(v)
if err != nil {
return nil, err
}
if !u.IsAbs() {
return nil, fmt.Errorf("url %s is not an absolute url", v)
}
f.URLs[k] = u.String()
}
return f, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/config.go#L161-L175
|
func (c *ServerConfig) VerifyBootstrap() error {
if err := c.hasLocalMember(); err != nil {
return err
}
if err := c.advertiseMatchesCluster(); err != nil {
return err
}
if checkDuplicateURL(c.InitialPeerURLsMap) {
return fmt.Errorf("initial cluster %s has duplicate url", c.InitialPeerURLsMap)
}
if c.InitialPeerURLsMap.String() == "" && c.DiscoveryURL == "" {
return fmt.Errorf("initial cluster unset and no discovery URL found")
}
return nil
}
|
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/opts.go#L103-L110
|
func Resource(typ ResType, labels map[string]string) Option {
return func(sh *StackdriverHook) error {
return MonitoredResource(&logging.MonitoredResource{
Type: string(typ),
Labels: labels,
})(sh)
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/filter.go#L53-L62
|
func AggregateFilter(filters []Filter) Filter {
return func(presubmit config.Presubmit) (bool, bool, bool) {
for _, filter := range filters {
if shouldRun, forced, defaults := filter(presubmit); shouldRun {
return shouldRun, forced, defaults
}
}
return false, false, false
}
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L532-L534
|
func (p *Page) SetScriptTimeout(timeout int) error {
return p.session.SetScriptTimeout(timeout)
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L152-L154
|
func (db *DB) Offset(offset int) *Condition {
return newCondition(db).Offset(offset)
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/sendable.go#L157-L166
|
func (cbr *OutgoingCallbackQueryResponse) Send() error {
resp := &baseResponse{}
_, err := cbr.api.c.postJSON(answerCallbackQuery, resp, cbr)
if err != nil {
return err
}
return check(resp)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/boltdb/boltdb.go#L128-L142
|
func (bdc *cache) update(fn func(tx *bolt.Tx) error) (retErr error) {
lockPath(bdc.path)
defer unlockPath(bdc.path)
db, err := bolt.Open(bdc.path, 0600, nil)
if err != nil {
return err
}
defer func() {
if err := db.Close(); retErr == nil && err != nil {
retErr = err
}
}()
return db.Update(fn)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/resolver/endpoint/endpoint.go#L172-L178
|
func epsToAddrs(eps ...string) (addrs []resolver.Address) {
addrs = make([]resolver.Address, 0, len(eps))
for _, ep := range eps {
addrs = append(addrs, resolver.Address{Addr: ep})
}
return addrs
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L113-L117
|
func (v SetRemoteLocationsParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/context_header.go#L110-L116
|
func WrapWithHeaders(ctx context.Context, headers map[string]string) ContextWithHeaders {
h := &headersContainer{
reqHeaders: headers,
}
newCtx := context.WithValue(ctx, contextKeyHeaders, h)
return headerCtx{Context: newCtx}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/tide.go#L222-L242
|
func (tq TideQuery) ForRepo(org, repo string) bool {
fullName := fmt.Sprintf("%s/%s", org, repo)
for _, queryOrg := range tq.Orgs {
if queryOrg != org {
continue
}
// Check for repos excluded from the org.
for _, excludedRepo := range tq.ExcludedRepos {
if excludedRepo == fullName {
return false
}
}
return true
}
for _, queryRepo := range tq.Repos {
if queryRepo == fullName {
return true
}
}
return false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L6099-L6103
|
func (v EventAttributeModified) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom68(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/xslate.go#L299-L309
|
func (tx Xslate) Render(name string, vars Vars) (string, error) {
buf := rbpool.Get()
defer rbpool.Release(buf)
err := tx.RenderInto(buf, name, vars)
if err != nil {
return "", errors.Wrap(err, "failed to render template")
}
return buf.String(), nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L256-L273
|
func (c *ClusterTx) NodePending(id int64, pending bool) error {
value := 0
if pending {
value = 1
}
result, err := c.tx.Exec("UPDATE nodes SET pending=? WHERE id=?", value, id)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("query updated %d rows instead of 1", n)
}
return nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/cmd/client.go#L133-L150
|
func StreamJSONResponse(w io.Writer, response *http.Response) error {
if response == nil {
return errors.New("response cannot be nil")
}
defer response.Body.Close()
var err error
output := tsuruio.NewStreamWriter(w, nil)
for n := int64(1); n > 0 && err == nil; n, err = io.Copy(output, response.Body) {
}
if err != nil {
return err
}
unparsed := output.Remaining()
if len(unparsed) > 0 {
return errors.Errorf("unparsed message error: %s", string(unparsed))
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L71-L75
|
func (v SetVirtualTimePolicyReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoEmulation(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L181-L190
|
func FrameSet_FrameRange(id FrameSetId) (ret *C.char) {
fs, ok := sFrameSets.Get(id)
if !ok {
ret = C.CString("")
} else {
ret = C.CString(fs.FrameRange())
}
// caller must free the string
return ret
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/util.go#L76-L99
|
func DescribeMessage(m pb.Message, f EntryFormatter) string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "%x->%x %v Term:%d Log:%d/%d", m.From, m.To, m.Type, m.Term, m.LogTerm, m.Index)
if m.Reject {
fmt.Fprintf(&buf, " Rejected (Hint: %d)", m.RejectHint)
}
if m.Commit != 0 {
fmt.Fprintf(&buf, " Commit:%d", m.Commit)
}
if len(m.Entries) > 0 {
fmt.Fprintf(&buf, " Entries:[")
for i, e := range m.Entries {
if i != 0 {
buf.WriteString(", ")
}
buf.WriteString(DescribeEntry(e, f))
}
fmt.Fprintf(&buf, "]")
}
if !IsEmptySnap(m.Snapshot) {
fmt.Fprintf(&buf, " Snapshot:%v", m.Snapshot)
}
return buf.String()
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/y.go#L128-L134
|
func CompareKeys(key1, key2 []byte) int {
AssertTrue(len(key1) > 8 && len(key2) > 8)
if cmp := bytes.Compare(key1[:len(key1)-8], key2[:len(key2)-8]); cmp != 0 {
return cmp
}
return bytes.Compare(key1[len(key1)-8:], key2[len(key2)-8:])
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/embed/config_logging.go#L36-L41
|
func (cfg Config) GetLogger() *zap.Logger {
cfg.loggerMu.RLock()
l := cfg.logger
cfg.loggerMu.RUnlock()
return l
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L1256-L1265
|
func AmazonVaultSecret(region, bucket, vaultAddress, vaultRole, vaultToken, distribution string) map[string][]byte {
return map[string][]byte{
"amazon-region": []byte(region),
"amazon-bucket": []byte(bucket),
"amazon-vault-addr": []byte(vaultAddress),
"amazon-vault-role": []byte(vaultRole),
"amazon-vault-token": []byte(vaultToken),
"amazon-distribution": []byte(distribution),
}
}
|
https://github.com/go-audio/transforms/blob/51830ccc35a5ce4be9d09b1d1f3f82dad376c240/transforms.go#L11-L20
|
func FullWaveRectifier(buf *audio.FloatBuffer) error {
if buf == nil {
return audio.ErrInvalidBuffer
}
for i := 0; i < len(buf.Data); i++ {
buf.Data[i] = math.Abs(buf.Data[i])
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/gw/rpc.pb.gw.go#L1461-L1667
|
func RegisterMaintenanceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client etcdserverpb.MaintenanceClient) error {
mux.Handle("POST", pattern_Maintenance_Alarm_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Maintenance_Alarm_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Maintenance_Alarm_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Maintenance_Status_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Maintenance_Status_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Maintenance_Status_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Maintenance_Defragment_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Maintenance_Defragment_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Maintenance_Defragment_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Maintenance_Hash_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Maintenance_Hash_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Maintenance_Hash_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Maintenance_HashKV_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Maintenance_HashKV_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Maintenance_HashKV_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Maintenance_Snapshot_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Maintenance_Snapshot_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Maintenance_Snapshot_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Maintenance_MoveLeader_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Maintenance_MoveLeader_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Maintenance_MoveLeader_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1315-L1317
|
func (p *SetFileInputFilesParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetFileInputFiles, p, nil)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/certificates.go#L55-L83
|
func (c *Cluster) CertificateGet(fingerprint string) (cert *CertInfo, err error) {
cert = new(CertInfo)
inargs := []interface{}{fingerprint + "%"}
outfmt := []interface{}{
&cert.ID,
&cert.Fingerprint,
&cert.Type,
&cert.Name,
&cert.Certificate,
}
query := `
SELECT
id, fingerprint, type, name, certificate
FROM
certificates
WHERE fingerprint LIKE ?`
if err = dbQueryRowScan(c.db, query, inargs, outfmt); err != nil {
if err == sql.ErrNoRows {
return nil, ErrNoSuchObject
}
return nil, err
}
return cert, err
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/enamlbosh/api.go#L144-L163
|
func (s *Client) PushCloudConfig(manifest []byte) error {
ccm := enaml.NewCloudConfigManifest(manifest)
req, err := s.newCloudConfigRequest(*ccm)
if err != nil {
return err
}
res, err := s.http.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode >= 400 {
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
return fmt.Errorf("%s error pushing cloud config to BOSH: %s", res.Status, string(body))
}
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/archive/oci_dest.go#L104-L106
|
func (d *ociArchiveImageDestination) TryReusingBlob(ctx context.Context, info types.BlobInfo, cache types.BlobInfoCache, canSubstitute bool) (bool, types.BlobInfo, error) {
return d.unpackedDest.TryReusingBlob(ctx, info, cache, canSubstitute)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/migration.go#L105-L241
|
func (c *Cluster) ImportPreClusteringData(dump *Dump) error {
tx, err := c.db.Begin()
if err != nil {
return errors.Wrap(err, "failed to start cluster database transaction")
}
// Delete the default profile in the cluster database, which always
// gets created no matter what.
_, err = tx.Exec("DELETE FROM profiles WHERE id=1")
if err != nil {
tx.Rollback()
return errors.Wrap(err, "failed to delete default profile")
}
for _, table := range preClusteringTables {
logger.Debugf("Migrating data for table %s", table)
for i, row := range dump.Data[table] {
for i, element := range row {
// Convert []byte columns to string. This is safe to do since
// the pre-clustering schema only had TEXT fields and no BLOB.
bytes, ok := element.([]byte)
if ok {
row[i] = string(bytes)
}
}
columns := dump.Schema[table]
nullNodeID := false // Whether node-related rows should have a NULL node ID
appendNodeID := func() {
columns = append(columns, "node_id")
if nullNodeID {
row = append(row, nil)
} else {
row = append(row, int64(1))
}
}
switch table {
case "config":
// Don't migrate the core.https_address and maas.machine config keys,
// which is node-specific and must remain in the node
// database.
keys := []string{"core.https_address", "maas.machine"}
skip := false
for i, column := range columns {
value, ok := row[i].(string)
if !ok {
continue
}
if column == "key" && shared.StringInSlice(value, keys) {
skip = true
}
}
if skip {
continue
}
case "containers":
appendNodeID()
case "networks_config":
// The keys listed in NetworkNodeConfigKeys
// are the only ones which are not global to the
// cluster, so all other keys will have a NULL
// node_id.
index := 0
for i, column := range columns {
if column == "key" {
index = i
break
}
}
key := row[index].(string)
if !shared.StringInSlice(key, NetworkNodeConfigKeys) {
nullNodeID = true
break
}
appendNodeID()
case "storage_pools_config":
// The keys listed in StoragePoolNodeConfigKeys
// are the only ones which are not global to the
// cluster, so all other keys will have a NULL
// node_id.
index := 0
for i, column := range columns {
if column == "key" {
index = i
break
}
}
key := row[index].(string)
if !shared.StringInSlice(key, StoragePoolNodeConfigKeys) {
nullNodeID = true
break
}
appendNodeID()
case "networks":
fallthrough
case "storage_pools":
columns = append(columns, "state")
row = append(row, storagePoolCreated)
case "storage_volumes":
appendNodeID()
}
if shared.StringInSlice(table, preClusteringTablesRequiringProjectID) {
// These tables have a project_id reference in the new schema.
columns = append(columns, "project_id")
row = append(row, 1) // Reference the default project.
}
stmt := fmt.Sprintf("INSERT INTO %s(%s)", table, strings.Join(columns, ", "))
stmt += fmt.Sprintf(" VALUES %s", query.Params(len(columns)))
result, err := tx.Exec(stmt, row...)
if err != nil {
tx.Rollback()
return errors.Wrapf(err, "failed to insert row %d into %s", i, table)
}
n, err := result.RowsAffected()
if err != nil {
tx.Rollback()
return errors.Wrapf(err, "no result count for row %d of %s", i, table)
}
if n != 1 {
tx.Rollback()
return fmt.Errorf("could not insert %d int %s", i, table)
}
// Also insert the image ID to node ID association.
if shared.StringInSlice(table, []string{"images", "networks", "storage_pools"}) {
entity := table[:len(table)-1]
importNodeAssociation(entity, columns, row, tx)
}
}
}
return tx.Commit()
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/typestate.go#L97-L100
|
func (s *State) isResultPointer(thriftType *parser.Type) bool {
_, basicGoType := thriftToGo[s.rootType(thriftType).Name]
return !basicGoType
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L559-L562
|
func (p SynthesizeTapGestureParams) WithDuration(duration int64) *SynthesizeTapGestureParams {
p.Duration = duration
return &p
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/agouti.go#L51-L62
|
func EdgeDriver(options ...Option) *WebDriver {
var binaryName string
if runtime.GOOS == "windows" {
binaryName = "MicrosoftWebDriver.exe"
} else {
return nil
}
command := []string{binaryName, "--port={{.Port}}"}
// Using {{.Address}} means using 127.0.0.1
// But MicrosoftWebDriver only supports localhost, not 127.0.0.1
return NewWebDriver("http://localhost:{{.Port}}", command, options...)
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/int.go#L34-L40
|
func IntFromPtr(i *int64) Int {
if i == nil {
return NewInt(0, false)
}
n := NewInt(*i, true)
return n
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gexec/session.go#L283-L289
|
func Signal(signal os.Signal) {
trackedSessionsMutex.Lock()
defer trackedSessionsMutex.Unlock()
for _, session := range trackedSessions {
session.Signal(signal)
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/manifest.go#L160-L167
|
func MatchesDigest(manifest []byte, expectedDigest digest.Digest) (bool, error) {
// This should eventually support various digest types.
actualDigest, err := Digest(manifest)
if err != nil {
return false, err
}
return expectedDigest == actualDigest, nil
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L379-L393
|
func (g *Glg) SetLevelWriter(level LEVEL, writer io.Writer) *Glg {
if writer == nil {
return g
}
lev, ok := g.logger.Load(level)
if ok {
l := lev.(*logger)
l.writer = writer
l.updateMode()
g.logger.Store(level, l)
}
return g
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/api.go#L842-L885
|
func (r *Raft) Restore(meta *SnapshotMeta, reader io.Reader, timeout time.Duration) error {
metrics.IncrCounter([]string{"raft", "restore"}, 1)
var timer <-chan time.Time
if timeout > 0 {
timer = time.After(timeout)
}
// Perform the restore.
restore := &userRestoreFuture{
meta: meta,
reader: reader,
}
restore.init()
select {
case <-timer:
return ErrEnqueueTimeout
case <-r.shutdownCh:
return ErrRaftShutdown
case r.userRestoreCh <- restore:
// If the restore is ingested then wait for it to complete.
if err := restore.Error(); err != nil {
return err
}
}
// Apply a no-op log entry. Waiting for this allows us to wait until the
// followers have gotten the restore and replicated at least this new
// entry, which shows that we've also faulted and installed the
// snapshot with the contents of the restore.
noop := &logFuture{
log: Log{
Type: LogNoop,
},
}
noop.init()
select {
case <-timer:
return ErrEnqueueTimeout
case <-r.shutdownCh:
return ErrRaftShutdown
case r.applyCh <- noop:
return noop.Error()
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/devices.go#L177-L203
|
func findNvidiaMinor(pci string) (string, error) {
nvidiaPath := fmt.Sprintf("/proc/driver/nvidia/gpus/%s/information", pci)
buf, err := ioutil.ReadFile(nvidiaPath)
if err != nil {
return "", err
}
strBuf := strings.TrimSpace(string(buf))
idx := strings.Index(strBuf, "Device Minor:")
if idx != -1 {
idx += len("Device Minor:")
strBuf = strBuf[idx:]
strBuf = strings.TrimSpace(strBuf)
parts := strings.SplitN(strBuf, "\n", 2)
_, err = strconv.Atoi(parts[0])
if err == nil {
return parts[0], nil
}
}
minor, err := findNvidiaMinorOld()
if err == nil {
return minor, nil
}
return "", err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/operations.go#L72-L83
|
func (op *operation) RemoveHandler(target *EventTarget) error {
// Make sure we're not racing with ourselves
op.handlerLock.Lock()
defer op.handlerLock.Unlock()
// If the listener is gone, just return
if op.listener == nil {
return nil
}
return op.listener.RemoveHandler(target)
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/diff/result.go#L34-L36
|
func (dj *DeltaJob) RemovedProperty(name string, p *enaml.JobManifestProperty) {
dj.RemovedProperties[name] = *p
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/int.go#L46-L73
|
func (i *Int) UnmarshalJSON(data []byte) error {
var err error
var v interface{}
if err = json.Unmarshal(data, &v); err != nil {
return err
}
switch x := v.(type) {
case float64:
// Unmarshal again, directly to int64, to avoid intermediate float64
err = json.Unmarshal(data, &i.Int64)
case string:
str := string(x)
if len(str) == 0 {
i.Valid = false
return nil
}
i.Int64, err = strconv.ParseInt(str, 10, 64)
case map[string]interface{}:
err = json.Unmarshal(data, &i.NullInt64)
case nil:
i.Valid = false
return nil
default:
err = fmt.Errorf("json: cannot unmarshal %v into Go value of type zero.Int", reflect.TypeOf(v).Name())
}
i.Valid = (err == nil) && (i.Int64 != 0)
return err
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L86-L92
|
func (r *MapErrorRegistry) MustAddMessageError(code int, message string) *Error {
err, e := r.AddMessageError(code, message)
if e != nil {
panic(e)
}
return err
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/usermanagment.go#L230-L235
|
func (c *Client) UpdateShare(groupid string, resourceid string, obj Share) (*Share, error) {
url := umGroupSharePath(groupid, resourceid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Share{}
err := c.client.Put(url, obj, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/easyjson.go#L188-L192
|
func (v SetDOMStorageItemParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomstorage1(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/storage.go#L164-L168
|
func (ms *MemoryStorage) Snapshot() (pb.Snapshot, error) {
ms.Lock()
defer ms.Unlock()
return ms.snapshot, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L140-L144
|
func (v StartSamplingParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoMemory1(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/platform.go#L84-L90
|
func (s *platformService) FindByName(name string) (*appTypes.Platform, error) {
p, err := s.storage.FindByName(name)
if err != nil {
return nil, appTypes.ErrInvalidPlatform
}
return p, nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.