_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/xslate.go#L319-L331
|
func (tx *Xslate) RenderString(template string, vars Vars) (string, error) {
_, file, line, _ := runtime.Caller(1)
bc, err := tx.Loader.LoadString(fmt.Sprintf("%s:%d", file, line), template)
if err != nil {
return "", errors.Wrap(err, "failed to parse template string")
}
buf := rbpool.Get()
defer rbpool.Release(buf)
tx.VM.Run(bc, vm.Vars(vars), buf)
return buf.String(), nil
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/bit_reader.go#L106-L115
|
func (r *rarBitReader) readFull(p []byte) error {
for i := range p {
c, err := r.ReadByte()
if err != nil {
return err
}
p[i] = c
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/report.go#L74-L87
|
func (r *CSVReport) AddRecord(label string, elapsed time.Duration) error {
if len(r.records) == 0 {
r.addRecord(csvFields)
}
record := []string{
fmt.Sprintf("%d", time.Now().UnixNano()/int64(time.Millisecond)), // timestamp
fmt.Sprintf("%d", elapsed/time.Millisecond),
label,
"", // responseCode is not used
"true", // success"
}
return r.addRecord(record)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L654-L705
|
func (ic *imageCopier) copyLayer(ctx context.Context, srcInfo types.BlobInfo, pool *mpb.Progress) (types.BlobInfo, digest.Digest, error) {
cachedDiffID := ic.c.blobInfoCache.UncompressedDigest(srcInfo.Digest) // May be ""
diffIDIsNeeded := ic.diffIDsAreNeeded && cachedDiffID == ""
// If we already have the blob, and we don't need to compute the diffID, then we don't need to read it from the source.
if !diffIDIsNeeded {
reused, blobInfo, err := ic.c.dest.TryReusingBlob(ctx, srcInfo, ic.c.blobInfoCache, ic.canSubstituteBlobs)
if err != nil {
return types.BlobInfo{}, "", errors.Wrapf(err, "Error trying to reuse blob %s at destination", srcInfo.Digest)
}
if reused {
logrus.Debugf("Skipping blob %s (already present):", srcInfo.Digest)
bar := ic.c.createProgressBar(pool, srcInfo, "blob", "skipped: already exists")
bar.SetTotal(0, true)
return blobInfo, cachedDiffID, nil
}
}
// Fallback: copy the layer, computing the diffID if we need to do so
srcStream, srcBlobSize, err := ic.c.rawSource.GetBlob(ctx, srcInfo, ic.c.blobInfoCache)
if err != nil {
return types.BlobInfo{}, "", errors.Wrapf(err, "Error reading blob %s", srcInfo.Digest)
}
defer srcStream.Close()
bar := ic.c.createProgressBar(pool, srcInfo, "blob", "done")
blobInfo, diffIDChan, err := ic.copyLayerFromStream(ctx, srcStream, types.BlobInfo{Digest: srcInfo.Digest, Size: srcBlobSize}, diffIDIsNeeded, bar)
if err != nil {
return types.BlobInfo{}, "", err
}
diffID := cachedDiffID
if diffIDIsNeeded {
select {
case <-ctx.Done():
return types.BlobInfo{}, "", ctx.Err()
case diffIDResult := <-diffIDChan:
if diffIDResult.err != nil {
return types.BlobInfo{}, "", errors.Wrap(diffIDResult.err, "Error computing layer DiffID")
}
logrus.Debugf("Computed DiffID %s for layer %s", diffIDResult.digest, srcInfo.Digest)
// This is safe because we have just computed diffIDResult.Digest ourselves, and in the process
// we have read all of the input blob, so srcInfo.Digest must have been validated by digestingReader.
ic.c.blobInfoCache.RecordDigestUncompressedPair(srcInfo.Digest, diffIDResult.digest)
diffID = diffIDResult.digest
}
}
bar.SetTotal(srcInfo.Size, true)
return blobInfo, diffID, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_pools.go#L106-L118
|
func (r *ProtocolLXD) DeleteStoragePool(name string) error {
if !r.HasExtension("storage") {
return fmt.Errorf("The server is missing the required \"storage\" API extension")
}
// Send the request
_, _, err := r.query("DELETE", fmt.Sprintf("/storage-pools/%s", url.QueryEscape(name)), nil, "")
if err != nil {
return err
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/urlpick.go#L51-L57
|
func (p *urlPicker) unreachable(u url.URL) {
p.mu.Lock()
defer p.mu.Unlock()
if u == p.urls[p.picked] {
p.picked = (p.picked + 1) % len(p.urls)
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2338-L2342
|
func (v *PushNodeByPathToFrontendReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom25(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/connection.go#L173-L214
|
func httpsLXD(url string, args *ConnectionArgs) (ContainerServer, error) {
// Use empty args if not specified
if args == nil {
args = &ConnectionArgs{}
}
// Initialize the client struct
server := ProtocolLXD{
httpCertificate: args.TLSServerCert,
httpHost: url,
httpProtocol: "https",
httpUserAgent: args.UserAgent,
bakeryInteractor: args.AuthInteractor,
}
if args.AuthType == "candid" {
server.RequireAuthenticated(true)
}
// Setup the HTTP client
httpClient, err := tlsHTTPClient(args.HTTPClient, args.TLSClientCert, args.TLSClientKey, args.TLSCA, args.TLSServerCert, args.InsecureSkipVerify, args.Proxy)
if err != nil {
return nil, err
}
if args.CookieJar != nil {
httpClient.Jar = args.CookieJar
}
server.http = httpClient
if args.AuthType == "candid" {
server.setupBakeryClient()
}
// Test the connection and seed the server information
if !args.SkipGetServer {
_, _, err := server.GetServer()
if err != nil {
return nil, err
}
}
return &server, nil
}
|
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/ed25519.go#L102-L109
|
func (k *Ed25519PublicKey) Equals(o Key) bool {
edk, ok := o.(*Ed25519PublicKey)
if !ok {
return false
}
return bytes.Equal(k.k, edk.k)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2discovery/discovery.go#L95-L122
|
func newProxyFunc(lg *zap.Logger, proxy string) (func(*http.Request) (*url.URL, error), error) {
if proxy == "" {
return nil, nil
}
// Do a small amount of URL sanitization to help the user
// Derived from net/http.ProxyFromEnvironment
proxyURL, err := url.Parse(proxy)
if err != nil || !strings.HasPrefix(proxyURL.Scheme, "http") {
// proxy was bogus. Try prepending "http://" to it and
// see if that parses correctly. If not, we ignore the
// error and complain about the original one
var err2 error
proxyURL, err2 = url.Parse("http://" + proxy)
if err2 == nil {
err = nil
}
}
if err != nil {
return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err)
}
if lg != nil {
lg.Info("running proxy with discovery", zap.String("proxy-url", proxyURL.String()))
} else {
plog.Infof("using proxy %q", proxyURL.String())
}
return http.ProxyURL(proxyURL), nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L348-L359
|
func (c *Client) request(r *request, ret interface{}) (int, error) {
statusCode, b, err := c.requestRaw(r)
if err != nil {
return statusCode, err
}
if ret != nil {
if err := json.Unmarshal(b, ret); err != nil {
return statusCode, err
}
}
return statusCode, nil
}
|
https://github.com/r3labs/sse/blob/2f90368216802092e9ed520c43e974e11d50438d/client.go#L181-L188
|
func (c *Client) Unsubscribe(ch chan *Event) {
c.mu.Lock()
defer c.mu.Unlock()
if c.subscribed[ch] != nil {
c.subscribed[ch] <- true
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/docker_list.go#L38-L58
|
func chooseDigestFromManifestList(sys *types.SystemContext, blob []byte) (digest.Digest, error) {
wantedArch := runtime.GOARCH
if sys != nil && sys.ArchitectureChoice != "" {
wantedArch = sys.ArchitectureChoice
}
wantedOS := runtime.GOOS
if sys != nil && sys.OSChoice != "" {
wantedOS = sys.OSChoice
}
list := manifestList{}
if err := json.Unmarshal(blob, &list); err != nil {
return "", err
}
for _, d := range list.Manifests {
if d.Platform.Architecture == wantedArch && d.Platform.OS == wantedOS {
return d.Digest, nil
}
}
return "", fmt.Errorf("no image found in manifest list for architecture %s, OS %s", wantedArch, wantedOS)
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L191-L193
|
func (img *IplImage) Set3D(x, y, z int, value Scalar) {
C.cvSet3D(unsafe.Pointer(img), C.int(z), C.int(y), C.int(x), (C.CvScalar)(value))
}
|
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L28-L31
|
func Parse(xp string) (XPathExec, error) {
n, err := parser.Parse(xp)
return XPathExec{n: n}, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L6152-L6156
|
func (v *EventFrameDetached) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage65(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/kubernetes_cluster_clients.go#L159-L173
|
func (o *ExperimentalKubernetesOptions) BuildClusterClients(namespace string, dryRun bool) (buildClusterClients map[string]corev1.PodInterface, err error) {
if err := o.resolve(dryRun); err != nil {
return nil, err
}
if o.dryRun {
return nil, errors.New("no dry-run pod client is supported for build clusters in dry-run mode")
}
buildClients := map[string]corev1.PodInterface{}
for context, client := range o.kubernetesClientsByContext {
buildClients[context] = client.CoreV1().Pods(namespace)
}
return buildClients, nil
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/english/step1c.go#L9-L24
|
func step1c(w *snowballword.SnowballWord) bool {
rsLen := len(w.RS)
// Replace suffix y or Y by i if preceded by a non-vowel which is not
// the first letter of the word (so cry -> cri, by -> by, say -> say)
//
// Note: the unicode code points for
// y, Y, & i are 121, 89, & 105 respectively.
//
if len(w.RS) > 2 && (w.RS[rsLen-1] == 121 || w.RS[rsLen-1] == 89) && !isLowerVowel(w.RS[rsLen-2]) {
w.RS[rsLen-1] = 105
return true
}
return false
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L670-L691
|
func (c *Cluster) ImageAliasAdd(project, name string, imageID int, desc string) error {
err := c.Transaction(func(tx *ClusterTx) error {
enabled, err := tx.ProjectHasImages(project)
if err != nil {
return errors.Wrap(err, "Check if project has images")
}
if !enabled {
project = "default"
}
return nil
})
if err != nil {
return err
}
stmt := `
INSERT INTO images_aliases (name, image_id, description, project_id)
VALUES (?, ?, ?, (SELECT id FROM projects WHERE name = ?))
`
err = exec(c.db, stmt, name, imageID, desc, project)
return err
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/grpcproxy/watcher.go#L121-L129
|
func (w *watcher) post(wr *pb.WatchResponse) bool {
select {
case w.wps.watchCh <- wr:
case <-time.After(50 * time.Millisecond):
w.wps.cancel()
return false
}
return true
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/wrap.go#L227-L236
|
func (m *Method) WrapResult(respVar string) string {
if !m.HasReturn() {
panic("cannot wrap a return when there is no return mode")
}
if m.state.isResultPointer(m.ReturnType) {
return respVar
}
return "&" + respVar
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/server/server.go#L12-L61
|
func NewAPIServer(
env *serviceenv.ServiceEnv,
etcdPrefix string,
namespace string,
workerImage string,
workerSidecarImage string,
workerImagePullPolicy string,
storageRoot string,
storageBackend string,
storageHostPath string,
iamRole string,
imagePullSecret string,
noExposeDockerSocket bool,
reporter *metrics.Reporter,
workerUsesRoot bool,
workerGrpcPort uint16,
port uint16,
pprofPort uint16,
httpPort uint16,
peerPort uint16,
) (ppsclient.APIServer, error) {
apiServer := &apiServer{
Logger: log.NewLogger("pps.API"),
env: env,
etcdPrefix: etcdPrefix,
namespace: namespace,
workerImage: workerImage,
workerSidecarImage: workerSidecarImage,
workerImagePullPolicy: workerImagePullPolicy,
storageRoot: storageRoot,
storageBackend: storageBackend,
storageHostPath: storageHostPath,
iamRole: iamRole,
imagePullSecret: imagePullSecret,
noExposeDockerSocket: noExposeDockerSocket,
reporter: reporter,
workerUsesRoot: workerUsesRoot,
pipelines: ppsdb.Pipelines(env.GetEtcdClient(), etcdPrefix),
jobs: ppsdb.Jobs(env.GetEtcdClient(), etcdPrefix),
monitorCancels: make(map[string]func()),
workerGrpcPort: workerGrpcPort,
port: port,
pprofPort: pprofPort,
httpPort: httpPort,
peerPort: peerPort,
}
apiServer.validateKube()
go apiServer.master()
return apiServer, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L280-L314
|
func (c *ClusterTx) ContainerListExpanded() ([]Container, error) {
containers, err := c.ContainerList(ContainerFilter{})
if err != nil {
return nil, errors.Wrap(err, "Load containers")
}
profiles, err := c.ProfileList(ProfileFilter{})
if err != nil {
return nil, errors.Wrap(err, "Load profiles")
}
// Index of all profiles by project and name.
profilesByProjectAndName := map[string]map[string]Profile{}
for _, profile := range profiles {
profilesByName, ok := profilesByProjectAndName[profile.Project]
if !ok {
profilesByName = map[string]Profile{}
profilesByProjectAndName[profile.Project] = profilesByName
}
profilesByName[profile.Name] = profile
}
for i, container := range containers {
profiles := make([]api.Profile, len(container.Profiles))
for j, name := range container.Profiles {
profile := profilesByProjectAndName[container.Project][name]
profiles[j] = *ProfileToAPI(&profile)
}
containers[i].Config = ProfilesExpandConfig(container.Config, profiles)
containers[i].Devices = ProfilesExpandDevices(container.Devices, profiles)
}
return containers, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1471-L1485
|
func (r *ProtocolLXD) GetContainerMetadata(name string) (*api.ImageMetadata, string, error) {
if !r.HasExtension("container_edit_metadata") {
return nil, "", fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension")
}
metadata := api.ImageMetadata{}
url := fmt.Sprintf("/containers/%s/metadata", url.QueryEscape(name))
etag, err := r.queryStruct("GET", url, nil, "", &metadata)
if err != nil {
return nil, "", err
}
return &metadata, etag, err
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L427-L432
|
func isTTY(w io.Writer) bool {
if f, ok := w.(*os.File); ok {
return terminal.IsTerminal(int(f.Fd()))
}
return false
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5154-L5163
|
func (u LedgerKey) GetData() (result LedgerKeyData, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "Data" {
result = *u.Data
ok = true
}
return
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/api_server.go#L314-L433
|
func NewAPIServer(pachClient *client.APIClient, etcdClient *etcd.Client, etcdPrefix string, pipelineInfo *pps.PipelineInfo, workerName string, namespace string, hashtreeStorage string) (*APIServer, error) {
initPrometheus()
cfg, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
kubeClient, err := kube.NewForConfig(cfg)
if err != nil {
return nil, err
}
server := &APIServer{
pachClient: pachClient,
kubeClient: kubeClient,
etcdClient: etcdClient,
etcdPrefix: etcdPrefix,
pipelineInfo: pipelineInfo,
logMsgTemplate: pps.LogMessage{
PipelineName: pipelineInfo.Pipeline.Name,
WorkerID: os.Getenv(client.PPSPodNameEnv),
},
workerName: workerName,
namespace: namespace,
jobs: ppsdb.Jobs(etcdClient, etcdPrefix),
pipelines: ppsdb.Pipelines(etcdClient, etcdPrefix),
plans: col.NewCollection(etcdClient, path.Join(etcdPrefix, planPrefix), nil, &Plan{}, nil, nil),
shards: col.NewCollection(etcdClient, path.Join(etcdPrefix, shardPrefix, pipelineInfo.Pipeline.Name), nil, &ShardInfo{}, nil, nil),
hashtreeStorage: hashtreeStorage,
claimedShard: make(chan context.Context, 1),
shard: noShard,
clients: make(map[string]Client),
}
logger, err := server.getTaggedLogger(pachClient, "", nil, false)
if err != nil {
return nil, err
}
resp, err := pachClient.Enterprise.GetState(context.Background(), &enterprise.GetStateRequest{})
if err != nil {
logger.Logf("failed to get enterprise state with error: %v\n", err)
} else {
server.exportStats = resp.State == enterprise.State_ACTIVE
}
numWorkers, err := ppsutil.GetExpectedNumWorkers(kubeClient, pipelineInfo.ParallelismSpec)
if err != nil {
logger.Logf("error getting number of workers, default to 1 worker: %v", err)
numWorkers = 1
}
server.numWorkers = numWorkers
numShards, err := ppsutil.GetExpectedNumHashtrees(pipelineInfo.HashtreeSpec)
if err != nil {
logger.Logf("error getting number of shards, default to 1 shard: %v", err)
numShards = 1
}
server.numShards = numShards
root := filepath.Join(hashtreeStorage, uuid.NewWithoutDashes())
if err := os.MkdirAll(filepath.Join(root, "chunk", "stats"), 0777); err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Join(root, "datum", "stats"), 0777); err != nil {
return nil, err
}
server.chunkCache = hashtree.NewMergeCache(filepath.Join(root, "chunk"))
server.chunkStatsCache = hashtree.NewMergeCache(filepath.Join(root, "chunk", "stats"))
server.datumCache = hashtree.NewMergeCache(filepath.Join(root, "datum"))
server.datumStatsCache = hashtree.NewMergeCache(filepath.Join(root, "datum", "stats"))
var noDocker bool
if _, err := os.Stat("/var/run/docker.sock"); err != nil {
noDocker = true
}
if pipelineInfo.Transform.Image != "" && !noDocker {
docker, err := docker.NewClientFromEnv()
if err != nil {
return nil, err
}
image, err := docker.InspectImage(pipelineInfo.Transform.Image)
if err != nil {
return nil, fmt.Errorf("error inspecting image %s: %+v", pipelineInfo.Transform.Image, err)
}
if pipelineInfo.Transform.User == "" {
pipelineInfo.Transform.User = image.Config.User
}
if pipelineInfo.Transform.WorkingDir == "" {
pipelineInfo.Transform.WorkingDir = image.Config.WorkingDir
}
if server.pipelineInfo.Transform.Cmd == nil {
server.pipelineInfo.Transform.Cmd = image.Config.Entrypoint
}
}
if pipelineInfo.Transform.User != "" {
user, err := lookupDockerUser(pipelineInfo.Transform.User)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
// If `user` is `nil`, `uid` and `gid` will get set, and we won't
// customize the user that executes the worker process.
if user != nil { // user is nil when os.IsNotExist(err) is true in which case we use root
uid, err := strconv.ParseUint(user.Uid, 10, 32)
if err != nil {
return nil, err
}
uid32 := uint32(uid)
server.uid = &uid32
gid, err := strconv.ParseUint(user.Gid, 10, 32)
if err != nil {
return nil, err
}
gid32 := uint32(gid)
server.gid = &gid32
}
}
switch {
case pipelineInfo.Service != nil:
go server.master("service", server.serviceSpawner)
case pipelineInfo.Spout != nil:
go server.master("spout", server.spoutSpawner)
default:
go server.master("pipeline", server.jobSpawner)
}
go server.worker()
return server, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L293-L295
|
func (api *API) ApplicationLocator(href string) *ApplicationLocator {
return &ApplicationLocator{Href(href), api}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/schema.go#L17-L26
|
func (s Schema) Keys() []string {
keys := make([]string, len(s))
i := 0
for key := range s {
keys[i] = key
i++
}
sort.Strings(keys)
return keys
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L77-L102
|
func (r *ProtocolLXD) GetPrivateImage(fingerprint string, secret string) (*api.Image, string, error) {
image := api.Image{}
// Build the API path
path := fmt.Sprintf("/images/%s", url.QueryEscape(fingerprint))
var err error
path, err = r.setQueryAttributes(path)
if err != nil {
return nil, "", err
}
if secret != "" {
path, err = setQueryParam(path, "secret", secret)
if err != nil {
return nil, "", err
}
}
// Fetch the raw value
etag, err := r.queryStruct("GET", path, nil, "", &image)
if err != nil {
return nil, "", err
}
return &image, etag, nil
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/tasks/get_tasks_parameters.go#L70-L73
|
func (o *GetTasksParams) WithTimeout(timeout time.Duration) *GetTasksParams {
o.SetTimeout(timeout)
return o
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L12796-L12803
|
func (r *ServerTemplateMultiCloudImage) Locator(api *API) *ServerTemplateMultiCloudImageLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.ServerTemplateMultiCloudImageLocator(l["href"])
}
}
return nil
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/registry.go#L18-L32
|
func (r *registry) Register(err *ErrDescriptor) {
r.Lock()
defer r.Unlock()
if err.Code == NoCode {
panic(fmt.Errorf("No code defined in error descriptor (message: `%s`)", err.MessageFormat))
}
if r.byCode[err.Code] != nil {
panic(fmt.Errorf("errors: Duplicate error code %v registered", err.Code))
}
err.registered = true
r.byCode[err.Code] = err
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/skiplist.go#L324-L336
|
func (s *Skiplist) Delete(itm unsafe.Pointer, cmp CompareFn,
buf *ActionBuffer, sts *Stats) bool {
token := s.barrier.Acquire()
defer s.barrier.Release(token)
found := s.findPath(itm, cmp, buf, sts) != nil
if !found {
return false
}
delNode := buf.succs[0]
return s.deleteNode(delNode, cmp, buf, sts)
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/usermanagment.go#L182-L187
|
func (c *Client) CreateGroup(grp Group) (*Group, error) {
url := umGroups() + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Group{}
err := c.client.Post(url, grp, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L444-L446
|
func LeaseByTag(c context.Context, maxTasks int, queueName string, leaseTime int, tag string) ([]*Task, error) {
return lease(c, maxTasks, queueName, leaseTime, true, []byte(tag))
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/cmd/viewcore/html.go#L20-L216
|
func serveHTML(c *gocore.Process, port int, async bool) {
http.HandleFunc("/object", func(w http.ResponseWriter, r *http.Request) {
objs, ok := r.URL.Query()["o"]
if !ok || len(objs) != 1 {
fmt.Fprintf(w, "wrong or missing o= object specification")
return
}
obj, err := strconv.ParseInt(objs[0], 16, 64)
if err != nil {
fmt.Fprintf(w, "unparseable o= object specification: %s", err)
return
}
a := core.Address(obj)
x, _ := c.FindObject(a)
if x == 0 {
fmt.Fprintf(w, "can't find object at %x", a)
return
}
addr := c.Addr(x)
size := c.Size(x)
typ, repeat := c.Type(x)
tableStyle(w)
fmt.Fprintf(w, "<h1>object %x</h1>\n", a)
fmt.Fprintf(w, "<h3>%s</h3>\n", html.EscapeString(typeName(c, x)))
fmt.Fprintf(w, "<h3>%d bytes</h3>\n", size)
if typ != nil && repeat == 1 && typ.String() == "runtime.g" {
found := false
for _, g := range c.Goroutines() {
if g.Addr() == addr {
found = true
break
}
}
if found {
fmt.Fprintf(w, "<h3><a href=\"goroutine?g=%x\">goroutine stack</a></h3>\n", addr)
}
}
fmt.Fprintf(w, "<table>\n")
fmt.Fprintf(w, "<tr><th align=left>field</th><th align=left colspan=\"2\">type</th><th align=left>value</th></tr>\n")
var end int64
if typ != nil {
n := size / typ.Size
if n > 1 {
for i := int64(0); i < n; i++ {
htmlObject(w, c, fmt.Sprintf("[%d]", i), addr.Add(i*typ.Size), typ, nil)
}
} else {
htmlObject(w, c, "", addr, typ, nil)
}
end = n * typ.Size
}
for i := end; i < size; i += c.Process().PtrSize() {
fmt.Fprintf(w, "<tr><td>f%d</td><td colspan=\"2\">?</td>", i)
if c.IsPtr(addr.Add(i)) {
fmt.Fprintf(w, "<td>%s</td>", htmlPointer(c, c.Process().ReadPtr(addr.Add(i))))
} else {
fmt.Fprintf(w, "<td><pre>")
for j := int64(0); j < c.Process().PtrSize(); j++ {
fmt.Fprintf(w, "%02x ", c.Process().ReadUint8(addr.Add(i+j)))
}
fmt.Fprintf(w, "</pre></td><td><pre>")
for j := int64(0); j < c.Process().PtrSize(); j++ {
r := c.Process().ReadUint8(addr.Add(i + j))
if r >= 32 && r <= 126 {
fmt.Fprintf(w, "%s", html.EscapeString(string(rune(r))))
} else {
fmt.Fprintf(w, ".")
}
}
fmt.Fprintf(w, "</pre></td>")
}
fmt.Fprintf(w, "</tr>\n")
}
fmt.Fprintf(w, "</table>\n")
fmt.Fprintf(w, "<h3>references to this object</h3>\n")
nrev := 0
c.ForEachReversePtr(x, func(z gocore.Object, r *gocore.Root, i, j int64) bool {
if nrev == 10 {
fmt.Fprintf(w, "...additional references elided...<br/>\n")
return false
}
if r != nil {
fmt.Fprintf(w, "%s%s", r.Name, typeFieldName(r.Type, i))
} else {
t, r := c.Type(z)
if t == nil {
fmt.Fprintf(w, "%s", htmlPointer(c, c.Addr(z).Add(i)))
} else {
idx := ""
if r > 1 {
idx = fmt.Sprintf("[%d]", i/t.Size)
i %= t.Size
}
fmt.Fprintf(w, "%s%s%s", htmlPointer(c, c.Addr(z)), idx, typeFieldName(t, i))
}
}
fmt.Fprintf(w, " → %s<br/>\n", htmlPointer(c, a.Add(j)))
nrev++
return true
})
})
http.HandleFunc("/goroutines", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>goroutines</h1>\n")
tableStyle(w)
fmt.Fprintf(w, "<table>\n")
fmt.Fprintf(w, "<tr><th align=left>goroutine</th><th align=left>top of stack</th></tr>\n")
for _, g := range c.Goroutines() {
fmt.Fprintf(w, "<tr><td><a href=\"goroutine?g=%x\">%x</a></td><td>%s</td></tr>\n", g.Addr(), g.Addr(), g.Frames()[0].Func().Name())
}
fmt.Fprintf(w, "</table>\n")
// TODO: export goroutine state (runnable, running, syscall, ...) and print it here.
})
http.HandleFunc("/goroutine", func(w http.ResponseWriter, r *http.Request) {
gs, ok := r.URL.Query()["g"]
if !ok || len(gs) != 1 {
fmt.Fprintf(w, "wrong or missing g= goroutine specification")
return
}
addr, err := strconv.ParseInt(gs[0], 16, 64)
if err != nil {
fmt.Fprintf(w, "unparseable g= goroutine specification: %s\n", err)
return
}
a := core.Address(addr)
var g *gocore.Goroutine
for _, x := range c.Goroutines() {
if x.Addr() == a {
g = x
break
}
}
if g == nil {
fmt.Fprintf(w, "goroutine %x not found\n", a)
return
}
tableStyle(w)
fmt.Fprintf(w, "<h1>goroutine %x</h1>\n", g.Addr())
fmt.Fprintf(w, "<h3>%s</h3>\n", htmlPointer(c, g.Addr()))
fmt.Fprintf(w, "<h3>%d bytes of stack</h3>\n", g.Stack())
for _, f := range g.Frames() {
fmt.Fprintf(w, "<h3>%s+%d</h3>\n", f.Func().Name(), f.PC().Sub(f.Func().Entry()))
// TODO: convert fn+off to file+lineno.
fmt.Fprintf(w, "<table>\n")
fmt.Fprintf(w, "<tr><th align=left>field</th><th align=left colspan=\"2\">type</th><th align=left>value</th></tr>\n")
for _, r := range f.Roots() {
htmlObject(w, c, r.Name, r.Addr, r.Type, f.Live)
}
fmt.Fprintf(w, "</table>\n")
}
})
http.HandleFunc("/globals", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>globals</h1>\n")
tableStyle(w)
fmt.Fprintf(w, "<table>\n")
fmt.Fprintf(w, "<tr><th align=left>field</th><th align=left colspan=\"2\">type</th><th align=left>value</th></tr>\n")
for _, r := range c.Globals() {
htmlObject(w, c, r.Name, r.Addr, r.Type, nil)
}
fmt.Fprintf(w, "</table>\n")
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>core dump viewer</h1>\n")
fmt.Fprintf(w, "%s<br/>\n", c.Process().Arch())
fmt.Fprintf(w, "%s<br/>\n", c.BuildVersion())
fmt.Fprintf(w, "<a href=\"goroutines\">goroutines</a><br/>\n")
fmt.Fprintf(w, "<a href=\"globals\">globals</a><br/>\n")
tableStyle(w)
fmt.Fprintf(w, "<table>\n")
fmt.Fprintf(w, "<tr><th align=left>category</th><th align=left>bytes</th><th align=left>percent</th></tr>\n")
all := c.Stats().Size
var p func(*gocore.Stats, string)
p = func(s *gocore.Stats, prefix string) {
fmt.Fprintf(w, "<tr><td>%s%s</td><td align=right>%d</td><td align=right>%.2f</td></tr>\n", prefix, s.Name, s.Size, float64(s.Size)/float64(all)*100)
for _, c := range s.Children {
p(c, prefix+"..")
}
}
p(c.Stats(), "")
fmt.Fprintf(w, "</table>\n")
})
if port <= 0 {
port = 8080
}
fmt.Printf("start serving on http://localhost:%d\n", port)
httpAddr := fmt.Sprintf(":%d", port)
if async {
go http.ListenAndServe(httpAddr, nil)
return
}
http.ListenAndServe(httpAddr, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L1613-L1617
|
func (v *Effect) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoAnimation17(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gcsweb/cmd/gcsweb/gcsweb.go#L543-L558
|
func (rec *Record) Render(out http.ResponseWriter, inPath string) {
mtime := "<unknown>"
ts, err := time.Parse(time.RFC3339, rec.MTime)
if err == nil {
mtime = ts.Format("02 Jan 2006 15:04:05")
}
var url, size string
if rec.isDir {
url = gcsPath + inPath + rec.Name
size = "-"
} else {
url = gcsBaseURL + inPath + rec.Name
size = fmt.Sprintf("%v", rec.Size)
}
htmlGridItem(out, iconFile, url, rec.Name, size, mtime)
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/json/encode.go#L27-L29
|
func NewPrettyStreamEncoder(w io.Writer) *objconv.StreamEncoder {
return objconv.NewStreamEncoder(NewPrettyEmitter(w))
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/http.go#L49-L57
|
func EtagHash(data interface{}) (string, error) {
etag := sha256.New()
err := json.NewEncoder(etag).Encode(data)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", etag.Sum(nil)), nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/tracing.go#L121-L131
|
func CurrentSpan(ctx context.Context) *Span {
if sp := opentracing.SpanFromContext(ctx); sp != nil {
var injectable injectableSpan
if err := injectable.initFromOpenTracing(sp); err == nil {
span := Span(injectable)
return &span
}
// return empty span on error, instead of possibly a partially filled one
}
return &emptySpan
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/types.go#L155-L157
|
func (t *ScopeType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L776-L780
|
func (v Registration) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoServiceworker8(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L1188-L1192
|
func (v SetBypassCSPParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage13(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L455-L460
|
func (s *FileSequence) SetExt(ext string) {
if !strings.HasPrefix(ext, ".") {
ext = "." + ext
}
s.ext = ext
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L5251-L5255
|
func (v EventLoadEventFired) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage54(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/wrapper/options.go#L61-L65
|
func (o *Options) AddFlags(fs *flag.FlagSet) {
fs.StringVar(&o.ProcessLog, "process-log", "", "path to the log where stdout and stderr are streamed for the process we execute")
fs.StringVar(&o.MarkerFile, "marker-file", "", "file we write the return code of the process we execute once it has finished running")
fs.StringVar(&o.MetadataFile, "metadata-file", "", "path to the metadata file generated from the job")
}
|
https://github.com/giantswarm/certctl/blob/2a6615f61499cd09a8d5ced9a5fade322d2de254/service/pki/service.go#L34-L45
|
func NewService(config ServiceConfig) (Service, error) {
// Dependencies.
if config.VaultClient == nil {
return nil, microerror.Maskf(invalidConfigError, "Vault client must not be empty")
}
newService := &service{
ServiceConfig: config,
}
return newService, nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6849-L6858
|
func (u AuthenticatedMessage) GetV0() (result AuthenticatedMessageV0, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.V))
if armName == "V0" {
result = *u.V0
ok = true
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L2806-L2810
|
func (v *DOMNode) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomsnapshot12(&r, v)
return r.Error()
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/english/step1b.go#L9-L104
|
func step1b(w *snowballword.SnowballWord) bool {
suffix, suffixRunes := w.FirstSuffix("eedly", "ingly", "edly", "ing", "eed", "ed")
switch suffix {
case "":
// No suffix found
return false
case "eed", "eedly":
// Replace by ee if in R1
if len(suffixRunes) <= len(w.RS)-w.R1start {
w.ReplaceSuffixRunes(suffixRunes, []rune("ee"), true)
}
return true
case "ed", "edly", "ing", "ingly":
hasLowerVowel := false
for i := 0; i < len(w.RS)-len(suffixRunes); i++ {
if isLowerVowel(w.RS[i]) {
hasLowerVowel = true
break
}
}
if hasLowerVowel {
// This case requires a two-step transformation and, due
// to the way we've implemented the `ReplaceSuffix` method
// here, information about R1 and R2 would be lost between
// the two. Therefore, we need to keep track of the
// original R1 & R2, so that we may set them below, at the
// end of this case.
//
originalR1start := w.R1start
originalR2start := w.R2start
// Delete if the preceding word part contains a vowel
w.RemoveLastNRunes(len(suffixRunes))
// ...and after the deletion...
newSuffix, newSuffixRunes := w.FirstSuffix("at", "bl", "iz", "bb", "dd", "ff", "gg", "mm", "nn", "pp", "rr", "tt")
switch newSuffix {
case "":
// If the word is short, add "e"
if isShortWord(w) {
// By definition, r1 and r2 are the empty string for
// short words.
w.RS = append(w.RS, []rune("e")...)
w.R1start = len(w.RS)
w.R2start = len(w.RS)
return true
}
case "at", "bl", "iz":
// If the word ends "at", "bl" or "iz" add "e"
w.ReplaceSuffixRunes(newSuffixRunes, []rune(newSuffix+"e"), true)
case "bb", "dd", "ff", "gg", "mm", "nn", "pp", "rr", "tt":
// If the word ends with a double remove the last letter.
// Note that, "double" does not include all possible doubles,
// just those shown above.
//
w.RemoveLastNRunes(1)
}
// Because we did a double replacement, we need to fix
// R1 and R2 manually. This is just becase of how we've
// implemented the `ReplaceSuffix` method.
//
rsLen := len(w.RS)
if originalR1start < rsLen {
w.R1start = originalR1start
} else {
w.R1start = rsLen
}
if originalR2start < rsLen {
w.R2start = originalR2start
} else {
w.R2start = rsLen
}
return true
}
}
return false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/indexeddb.go#L64-L66
|
func (p *DeleteDatabaseParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandDeleteDatabase, p, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3067-L3071
|
func (v *GetRelayoutBoundaryReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom34(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/node.go#L153-L167
|
func (n *node) List() ([]*node, *v2error.Error) {
if !n.IsDir() {
return nil, v2error.NewError(v2error.EcodeNotDir, "", n.store.CurrentIndex)
}
nodes := make([]*node, len(n.Children))
i := 0
for _, node := range n.Children {
nodes[i] = node
i++
}
return nodes, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/animation.go#L72-L81
|
func (p *GetCurrentTimeParams) Do(ctx context.Context) (currentTime float64, err error) {
// execute
var res GetCurrentTimeReturns
err = cdp.Execute(ctx, CommandGetCurrentTime, p, &res)
if err != nil {
return 0, err
}
return res.CurrentTime, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/greenhouse/diskcache/cache.go#L47-L51
|
func NewCache(diskRoot string) *Cache {
return &Cache{
diskRoot: strings.TrimSuffix(diskRoot, string(os.PathListSeparator)),
}
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L277-L279
|
func (s Service) Status() (on bool, err error) {
return s.store.Status()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1606-L1610
|
func (v RedoParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom17(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/git/git.go#L266-L284
|
func (r *Repo) Am(path string) error {
r.logger.Infof("Applying %s.", path)
co := r.gitCommand("am", "--3way", path)
b, err := co.CombinedOutput()
if err == nil {
return nil
}
output := string(b)
r.logger.WithError(err).Infof("Patch apply failed with output: %s", output)
if b, abortErr := r.gitCommand("am", "--abort").CombinedOutput(); err != nil {
r.logger.WithError(abortErr).Warningf("Aborting patch apply failed with output: %s", string(b))
}
applyMsg := "The copy of the patch that failed is found in: .git/rebase-apply/patch"
if strings.Contains(output, applyMsg) {
i := strings.Index(output, applyMsg)
err = fmt.Errorf("%s", output[:i])
}
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L660-L664
|
func (v *ReleaseAnimationsParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoAnimation6(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2818-L2822
|
func (v HandleJavaScriptDialogParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage29(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L175-L180
|
func DecodeHTMLEntities(s string) string {
if Verbose {
fmt.Println("Use html.UnescapeString instead of DecodeHTMLEntities")
}
return html.UnescapeString(s)
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L76-L91
|
func New(handler Handler, flag int) *Logger {
var l = new(Logger)
l.level = LevelInfo
l.handler = handler
l.flag = flag
l.bufs = sync.Pool{
New: func() interface{} {
return make([]byte, 0, 1024)
},
}
return l
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/lease/lessor.go#L848-L856
|
func (l *Lease) Keys() []string {
l.mu.RLock()
keys := make([]string, 0, len(l.itemSet))
for k := range l.itemSet {
keys = append(keys, k.Key)
}
l.mu.RUnlock()
return keys
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dbase/text.go#L26-L34
|
func (glyphCache *GlyphCacheImp) Fetch(gc draw2d.GraphicContext, fontName string, chr rune) *Glyph {
if glyphCache.glyphs[fontName] == nil {
glyphCache.glyphs[fontName] = make(map[rune]*Glyph, 60)
}
if glyphCache.glyphs[fontName][chr] == nil {
glyphCache.glyphs[fontName][chr] = renderGlyph(gc, fontName, chr)
}
return glyphCache.glyphs[fontName][chr].Copy()
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction_envelope.go#L52-L61
|
func (b *TransactionEnvelopeBuilder) MutateTX(muts ...TransactionMutator) {
b.Init()
if b.Err != nil {
return
}
b.child.Mutate(muts...)
b.Err = b.child.Err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L138-L193
|
func (s *Schema) Ensure(db *sql.DB) (int, error) {
var current int
aborted := false
err := query.Transaction(db, func(tx *sql.Tx) error {
err := execFromFile(tx, s.path, s.hook)
if err != nil {
return errors.Wrapf(err, "failed to execute queries from %s", s.path)
}
err = ensureSchemaTableExists(tx)
if err != nil {
return err
}
current, err = queryCurrentVersion(tx)
if err != nil {
return err
}
if s.check != nil {
err := s.check(current, tx)
if err == ErrGracefulAbort {
// Abort the update gracefully, committing what
// we've done so far.
aborted = true
return nil
}
if err != nil {
return err
}
}
// When creating the schema from scratch, use the fresh dump if
// available. Otherwise just apply all relevant updates.
if current == 0 && s.fresh != "" {
_, err = tx.Exec(s.fresh)
if err != nil {
return fmt.Errorf("cannot apply fresh schema: %v", err)
}
} else {
err = ensureUpdatesAreApplied(tx, current, s.updates, s.hook)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return -1, err
}
if aborted {
return current, ErrGracefulAbort
}
return current, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L250-L269
|
func appInfo(w http.ResponseWriter, r *http.Request, t auth.Token) error {
a, err := getAppFromContext(r.URL.Query().Get(":app"), r)
if err != nil {
return err
}
canRead := permission.Check(t, permission.PermAppRead,
contextsForApp(&a)...,
)
if !canRead {
return permission.ErrUnauthorized
}
err = a.FillInternalAddresses(r.Context())
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
return json.NewEncoder(w).Encode(&a)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/pjutil.go#L126-L139
|
func PostsubmitSpec(p config.Postsubmit, refs prowapi.Refs) prowapi.ProwJobSpec {
pjs := specFromJobBase(p.JobBase)
pjs.Type = prowapi.PostsubmitJob
pjs.Context = p.Context
pjs.Report = !p.SkipReport
pjs.Refs = completePrimaryRefs(refs, p.JobBase)
if p.JenkinsSpec != nil {
pjs.JenkinsSpec = &prowapi.JenkinsSpec{
GitHubBranchSourceJob: p.JenkinsSpec.GitHubBranchSourceJob,
}
}
return pjs
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/logexporter/cmd/main.go#L70-L93
|
func checkConfigValidity() error {
glog.Info("Verifying if a valid config has been provided through the flags")
if *nodeName == "" {
return fmt.Errorf("Flag --node-name has its value unspecified")
}
if *gcsPath == "" {
return fmt.Errorf("Flag --gcs-path has its value unspecified")
}
if _, err := os.Stat(*gcloudAuthFilePath); err != nil {
return fmt.Errorf("Could not find the gcloud service account file: %v", err)
} else {
glog.Infof("Running gcloud auth activate-service-account --key-file=%s\n", *gcloudAuthFilePath)
cmd := exec.Command("gcloud", "auth", "activate-service-account", "--key-file="+*gcloudAuthFilePath)
var stderr, stdout bytes.Buffer
cmd.Stderr, cmd.Stdout = &stderr, &stdout
err = cmd.Run()
glog.Infof("Stdout:\n%s\n", stdout.String())
glog.Infof("Stderr:\n%s\n", stderr.String())
if err != nil {
return fmt.Errorf("Failed to activate gcloud service account: %v", err)
}
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L40-L43
|
func (p ContinueToLocationParams) WithTargetCallFrames(targetCallFrames ContinueToLocationTargetCallFrames) *ContinueToLocationParams {
p.TargetCallFrames = targetCallFrames
return &p
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/web/server.go#L142-L145
|
func NewLoggingServeMux(conf Config) *LoggingServeMux {
serveMux := http.NewServeMux()
return &LoggingServeMux{serveMux, conf}
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcawsprovisioner/types.go#L571-L574
|
func (this *RegionLaunchSpec) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decode29.go#L69-L91
|
func readVMCode(br *rarBitReader) ([]byte, error) {
n, err := br.readUint32()
if err != nil {
return nil, err
}
if n > maxCodeSize || n == 0 {
return nil, errInvalidFilter
}
buf := make([]byte, n)
err = br.readFull(buf)
if err != nil {
return nil, err
}
var x byte
for _, c := range buf[1:] {
x ^= c
}
// simple xor checksum on data
if x != buf[0] {
return nil, errInvalidFilter
}
return buf, nil
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/helpers.go#L49-L57
|
func A(m Model, field string) string {
// find field
f := Init(m).Meta().Fields[field]
if f == nil {
panic(fmt.Sprintf(`coal: field "%s" not found on "%s"`, field, m.Meta().Name))
}
return f.JSONKey
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/postscript/postscript.go#L36-L49
|
func Draw(gc draw2d.GraphicContext, filename string) {
// Open the postscript
src, err := os.OpenFile(filename, 0, 0)
if err != nil {
panic(err)
}
defer src.Close()
bytes, err := ioutil.ReadAll(src)
reader := strings.NewReader(string(bytes))
// Initialize and interpret the postscript
interpreter := ps.NewInterpreter(gc)
interpreter.Execute(reader)
}
|
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L475-L490
|
func (p *PubSub) announce(topic string, sub bool) {
subopt := &pb.RPC_SubOpts{
Topicid: &topic,
Subscribe: &sub,
}
out := rpcWithSubs(subopt)
for pid, peer := range p.peers {
select {
case peer <- out:
default:
log.Infof("Can't send announce message to peer %s: queue full; scheduling retry", pid)
go p.announceRetry(pid, topic, sub)
}
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/agent.go#L116-L120
|
func (ca *Agent) Config() *Config {
ca.mut.RLock()
defer ca.mut.RUnlock()
return ca.c
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L1009-L1011
|
func (p *StepOverParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandStepOver, nil, nil)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/op.go#L397-L399
|
func WithRange(endKey string) OpOption {
return func(op *Op) { op.end = []byte(endKey) }
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/node.go#L171-L183
|
func (n *node) GetChild(name string) (*node, *v2error.Error) {
if !n.IsDir() {
return nil, v2error.NewError(v2error.EcodeNotDir, n.Path, n.store.CurrentIndex)
}
child, ok := n.Children[name]
if ok {
return child, nil
}
return nil, nil
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/snowballword/snowballword.go#L301-L303
|
func (w *SnowballWord) RemoveFirstSuffix(suffixes ...string) (suffix string, suffixRunes []rune) {
return w.RemoveFirstSuffixIn(0, suffixes...)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L1791-L1795
|
func (v LayoutTreeNode) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomsnapshot7(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/func.go#L29-L34
|
func Func(s string, fn RendererFunc) Renderer {
return funcRenderer{
contentType: s,
renderFunc: fn,
}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/autogazelle/server_unix.go#L247-L256
|
func getAndClearWrittenDirs() []string {
dirSetMutex.Lock()
defer dirSetMutex.Unlock()
dirs := make([]string, 0, len(dirSet))
for d := range dirSet {
dirs = append(dirs, d)
}
dirSet = make(map[string]bool)
return dirs
}
|
https://github.com/ccding/go-config-reader/blob/8b6c2b50197f20da3b1c5944c274c173634dc056/config/config.go#L66-L102
|
func (c *Config) Read() error {
in, err := os.Open(c.filename)
if err != nil {
return err
}
defer in.Close()
scanner := bufio.NewScanner(in)
line := ""
section := ""
for scanner.Scan() {
if scanner.Text() == "" {
continue
}
if line == "" {
sec, ok := checkSection(scanner.Text())
if ok {
section = sec
continue
}
}
if checkComment(scanner.Text()) {
continue
}
line += scanner.Text()
if strings.HasSuffix(line, "\\") {
line = line[:len(line)-1]
continue
}
key, value, ok := checkLine(line)
if !ok {
return errors.New("WRONG: " + line)
}
c.Set(section, key, value)
line = ""
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L94-L98
|
func (v SetTimingParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoAnimation(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/greenhouse/diskutil/diskutil.go#L29-L39
|
func GetDiskUsage(path string) (percentBlocksFree float64, bytesFree, bytesUsed uint64, err error) {
var stat syscall.Statfs_t
err = syscall.Statfs(path, &stat)
if err != nil {
return 0, 0, 0, err
}
percentBlocksFree = float64(stat.Bfree) / float64(stat.Blocks) * 100
bytesFree = stat.Bfree * uint64(stat.Bsize)
bytesUsed = (stat.Blocks - stat.Bfree) * uint64(stat.Bsize)
return percentBlocksFree, bytesFree, bytesUsed, nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L80-L87
|
func (v *ValueStruct) EncodeTo(buf *bytes.Buffer) {
buf.WriteByte(v.Meta)
buf.WriteByte(v.UserMeta)
var enc [binary.MaxVarintLen64]byte
sz := binary.PutUvarint(enc[:], v.ExpiresAt)
buf.Write(enc[:sz])
buf.Write(v.Value)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_src.go#L75-L91
|
func (s *dirImageSource) GetSignatures(ctx context.Context, instanceDigest *digest.Digest) ([][]byte, error) {
if instanceDigest != nil {
return nil, errors.Errorf(`Manifests lists are not supported by "dir:"`)
}
signatures := [][]byte{}
for i := 0; ; i++ {
signature, err := ioutil.ReadFile(s.ref.signaturePath(i))
if err != nil {
if os.IsNotExist(err) {
break
}
return nil, err
}
signatures = append(signatures, signature)
}
return signatures, nil
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/apex/apex.go#L56-L62
|
func (w *apexInterfaceWrapper) MustParseLevel(s string) {
level, err := ParseLevel(s)
if err != nil {
w.WithError(err).WithField("level", s).Fatal("Could not parse log level")
}
w.Level = level
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L584-L606
|
func (c APIClient) PutObjectSplit(_r io.Reader) (objects []*pfs.Object, _ int64, retErr error) {
r := grpcutil.ReaderWrapper{_r}
w, err := c.newPutObjectSplitWriteCloser()
if err != nil {
return nil, 0, grpcutil.ScrubGRPC(err)
}
defer func() {
if err := w.Close(); err != nil && retErr == nil {
retErr = grpcutil.ScrubGRPC(err)
}
if retErr == nil {
objects = w.objects
}
}()
buf := grpcutil.GetBuffer()
defer grpcutil.PutBuffer(buf)
written, err := io.CopyBuffer(w, r, buf)
if err != nil {
return nil, 0, grpcutil.ScrubGRPC(err)
}
// return value set by deferred function
return nil, written, nil
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L84-L86
|
func (s *selectable) FindByLabel(text string) *Selection {
return newSelection(s.session, s.selectors.Append(target.Label, text).Single())
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/watcher_group.go#L164-L182
|
func (wg *watcherGroup) add(wa *watcher) {
wg.watchers.add(wa)
if wa.end == nil {
wg.keyWatchers.add(wa)
return
}
// interval already registered?
ivl := adt.NewStringAffineInterval(string(wa.key), string(wa.end))
if iv := wg.ranges.Find(ivl); iv != nil {
iv.Val.(watcherSet).add(wa)
return
}
// not registered, put in interval tree
ws := make(watcherSet)
ws.add(wa)
wg.ranges.Insert(ivl, ws)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L1348-L1352
|
func (v SetBreakpointByURLReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger14(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L615-L618
|
func (c *Client) ListOrgHooks(org string) ([]Hook, error) {
c.log("ListOrgHooks", org)
return c.listHooks(org, nil)
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L138-L140
|
func WithLogFunc(logf func(format string, a ...interface{})) Option {
return func(o *Options) { o.logf = logf }
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L120-L122
|
func (t *Tracer) Context(ctx context.Context) context.Context {
return opentracing.ContextWithSpan(ctx, t.Last())
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/errors.go#L17-L20
|
func IsOverQuota(err error) bool {
callErr, ok := err.(*internal.CallError)
return ok && callErr.Code == 4
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.