_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/label_sync/main.go#L825-L833
func linkify(text string) string { // swap space with dash link := strings.Replace(text, " ", "-", -1) // discard some special characters discard, _ := regexp.Compile("[,/]") link = discard.ReplaceAllString(link, "") // lowercase return strings.ToLower(link) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L288-L499
func (r *ProtocolLXD) CopyContainer(source ContainerServer, container api.Container, args *ContainerCopyArgs) (RemoteOperation, error) { // Base request req := api.ContainersPost{ Name: container.Name, ContainerPut: container.Writable(), } req.Source.BaseImage = container.Config["volatile.base_image"] // Process the copy arguments if args != nil { // Sanity checks if args.ContainerOnly { if !r.HasExtension("container_only_migration") { return nil, fmt.Errorf("The target server is missing the required \"container_only_migration\" API extension") } if !source.HasExtension("container_only_migration") { return nil, fmt.Errorf("The source server is missing the required \"container_only_migration\" API extension") } } if shared.StringInSlice(args.Mode, []string{"push", "relay"}) { if !r.HasExtension("container_push") { return nil, fmt.Errorf("The target server is missing the required \"container_push\" API extension") } if !source.HasExtension("container_push") { return nil, fmt.Errorf("The source server is missing the required \"container_push\" API extension") } } if args.Mode == "push" && !source.HasExtension("container_push_target") { return nil, fmt.Errorf("The source server is missing the required \"container_push_target\" API extension") } if args.Refresh { if !r.HasExtension("container_incremental_copy") { return nil, fmt.Errorf("The target server is missing the required \"container_incremental_copy\" API extension") } if !source.HasExtension("container_incremental_copy") { return nil, fmt.Errorf("The source server is missing the required \"container_incremental_copy\" API extension") } } // Allow overriding the target name if args.Name != "" { req.Name = args.Name } req.Source.Live = args.Live req.Source.ContainerOnly = args.ContainerOnly req.Source.Refresh = args.Refresh } if req.Source.Live { req.Source.Live = container.StatusCode == api.Running } sourceInfo, err := source.GetConnectionInfo() if err != nil { return nil, fmt.Errorf("Failed to get source connection info: %v", err) } destInfo, err := r.GetConnectionInfo() if err != nil { return nil, fmt.Errorf("Failed to get destination connection info: %v", err) } // Optimization for the local copy case if destInfo.URL == sourceInfo.URL && destInfo.SocketPath == sourceInfo.SocketPath && (!r.IsClustered() || container.Location == r.clusterTarget || r.HasExtension("cluster_internal_copy")) { // Project handling if destInfo.Project != sourceInfo.Project { if !r.HasExtension("container_copy_project") { return nil, fmt.Errorf("The server is missing the required \"container_copy_project\" API extension") } req.Source.Project = sourceInfo.Project } // Local copy source fields req.Source.Type = "copy" req.Source.Source = container.Name // Copy the container op, err := r.CreateContainer(req) if err != nil { return nil, err } rop := remoteOperation{ targetOp: op, chDone: make(chan bool), } // Forward targetOp to remote op go func() { rop.err = rop.targetOp.Wait() close(rop.chDone) }() return &rop, nil } // Source request sourceReq := api.ContainerPost{ Migration: true, Live: req.Source.Live, ContainerOnly: req.Source.ContainerOnly, } // Push mode migration if args != nil && args.Mode == "push" { // Get target server connection information info, err := r.GetConnectionInfo() if err != nil { return nil, err } // Create the container req.Source.Type = "migration" req.Source.Mode = "push" req.Source.Refresh = args.Refresh op, err := r.CreateContainer(req) if err != nil { return nil, err } opAPI := op.Get() targetSecrets := map[string]string{} for k, v := range opAPI.Metadata { targetSecrets[k] = v.(string) } // Prepare the source request target := api.ContainerPostTarget{} target.Operation = opAPI.ID target.Websockets = targetSecrets target.Certificate = info.Certificate sourceReq.Target = &target return r.tryMigrateContainer(source, container.Name, sourceReq, info.Addresses) } // Get source server connection information info, err := source.GetConnectionInfo() if err != nil { return nil, err } op, err := source.MigrateContainer(container.Name, sourceReq) if err != nil { return nil, err } opAPI := op.Get() sourceSecrets := map[string]string{} for k, v := range opAPI.Metadata { sourceSecrets[k] = v.(string) } // Relay mode migration if args != nil && args.Mode == "relay" { // Push copy source fields req.Source.Type = "migration" req.Source.Mode = "push" // Start the process targetOp, err := r.CreateContainer(req) if err != nil { return nil, err } targetOpAPI := targetOp.Get() // Extract the websockets targetSecrets := map[string]string{} for k, v := range targetOpAPI.Metadata { targetSecrets[k] = v.(string) } // Launch the relay err = r.proxyMigration(targetOp.(*operation), targetSecrets, source, op.(*operation), sourceSecrets) if err != nil { return nil, err } // Prepare a tracking operation rop := remoteOperation{ targetOp: targetOp, chDone: make(chan bool), } // Forward targetOp to remote op go func() { rop.err = rop.targetOp.Wait() close(rop.chDone) }() return &rop, nil } // Pull mode migration req.Source.Type = "migration" req.Source.Mode = "pull" req.Source.Operation = opAPI.ID req.Source.Websockets = sourceSecrets req.Source.Certificate = info.Certificate return r.tryCreateContainer(req, info.Addresses) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L42-L45
func NewInstanceAuthenticator(token string, accountID int) Authenticator { builder := instanceLoginRequestBuilder{token: token, accountID: accountID} return newCookieSigner(&builder, accountID) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/backend/batch_tx.go#L88-L90
func (t *batchTx) UnsafePut(bucketName []byte, key []byte, value []byte) { t.unsafePut(bucketName, key, value, false) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/histogram.go#L56-L76
func newSizeHistogram() *sizeHistogram { // TODO(ibrahim): find appropriate bin size. keyBins := createHistogramBins(1, 16) valueBins := createHistogramBins(1, 30) return &sizeHistogram{ keySizeHistogram: histogramData{ bins: keyBins, countPerBin: make([]int64, len(keyBins)+1), max: math.MinInt64, min: math.MaxInt64, sum: 0, }, valueSizeHistogram: histogramData{ bins: valueBins, countPerBin: make([]int64, len(valueBins)+1), max: math.MinInt64, min: math.MaxInt64, sum: 0, }, } }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nodelist.go#L30-L39
func (l *NodeList) Keys() (keys [][]byte) { node := l.head for node != nil { key := (*Item)(node.Item()).Bytes() keys = append(keys, key) node = node.GetLink() } return }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/goimage.go#L11-L17
func DecodeImageMem(data []byte) *IplImage { buf := CreateMatHeader(1, len(data), CV_8U) buf.SetData(unsafe.Pointer(&data[0]), CV_AUTOSTEP) defer buf.Release() return DecodeImage(unsafe.Pointer(buf), CV_LOAD_IMAGE_UNCHANGED) }
https://github.com/fcavani/text/blob/023e76809b57fc8cfc80c855ba59537720821cb5/util.go#L27-L77
func Reticence(str string, length int) string { if length > len(str) { return str } var i int F: for i = len(str) - 1; i >= 0; i-- { switch str[i] { case ' ', ',', '?', ';', ':', '\'', '"', '!': if i <= length { break F } case '.': if i-2 >= 0 { s := str[i-2 : i] if s == ".." { i = i - 2 if i <= length { break F } } } if i <= length { break F } } } if i-1 > 0 { switch str[i-1] { case ' ', ',', '?', ';', ':', '\'', '"', '!': i-- case '.': if i-2 > 0 && str[i-2:i] == ".." { i -= 3 } } } if i >= 2 { if i+3 >= len(str) { return str } return str[:i] + "..." } if length >= 2 && length < len(str) { if length+3 >= len(str) { return str } return str[:length] + "..." } return str }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L2291-L2295
func (v *CloseTargetReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget26(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L462-L476
func cephRBDVolumeRename(clusterName string, poolName string, volumeType string, oldVolumeName string, newVolumeName string, userName string) error { _, err := shared.RunCommand( "rbd", "--id", userName, "--cluster", clusterName, "mv", fmt.Sprintf("%s/%s_%s", poolName, volumeType, oldVolumeName), fmt.Sprintf("%s/%s_%s", poolName, volumeType, newVolumeName)) if err != nil { return err } return nil }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/discovery/discovery.go#L18-L35
func DiscoverHTTP(endpoint string) ([]string, error) { res, err := http.Get(endpoint) if err != nil { return nil, fmt.Errorf("discovery: request failure: %s", err.Error()) } defer res.Body.Close() var ( tmp []service services []string ) if err := json.NewDecoder(res.Body).Decode(&tmp); err != nil { return nil, fmt.Errorf("discovery: request payload decoding failure: %s", err.Error()) } for _, s := range tmp { services = append(services, fmt.Sprintf("%s:%d", s.Address, s.Port)) } return services, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/types.go#L54-L72
func (t *CachedResponseType) UnmarshalEasyJSON(in *jlexer.Lexer) { switch CachedResponseType(in.String()) { case CachedResponseTypeBasic: *t = CachedResponseTypeBasic case CachedResponseTypeCors: *t = CachedResponseTypeCors case CachedResponseTypeDefault: *t = CachedResponseTypeDefault case CachedResponseTypeError: *t = CachedResponseTypeError case CachedResponseTypeOpaqueResponse: *t = CachedResponseTypeOpaqueResponse case CachedResponseTypeOpaqueRedirect: *t = CachedResponseTypeOpaqueRedirect default: in.AddError(errors.New("unknown CachedResponseType value")) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2486-L2490
func (v *GetPropertiesReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime21(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/logutil/zap_journal.go#L38-L40
func NewJournalWriter(wr io.Writer) (io.Writer, error) { return &journalWriter{Writer: wr}, systemd.DialJournal() }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1173-L1181
func (app *App) validateNew() error { if app.Name == InternalAppName || !validation.ValidateName(app.Name) { msg := "Invalid app name, your app should have at most 40 " + "characters, containing only lower case letters, numbers or dashes, " + "starting with a letter." return &tsuruErrors.ValidationError{Message: msg} } return app.validate() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/keypair/main.go#L104-L111
func MustParse(addressOrSeed string) KP { kp, err := Parse(addressOrSeed) if err != nil { panic(err) } return kp }
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/binding/binding.go#L222-L234
func ErrorHandler(errs Errors, resp http.ResponseWriter) { if errs.Count() > 0 { resp.Header().Set("Content-Type", "application/json; charset=utf-8") if _, ok := errs.Overall[DeserializationError]; ok { resp.WriteHeader(http.StatusBadRequest) } else { resp.WriteHeader(422) } errOutput, _ := json.Marshal(errs) resp.Write(errOutput) return } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3514-L3521
func (u AccountMergeResult) ArmForSwitch(sw int32) (string, bool) { switch AccountMergeResultCode(sw) { case AccountMergeResultCodeAccountMergeSuccess: return "SourceAccountBalance", true default: return "", true } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L697-L831
func (r *ProtocolLXD) ExecContainer(containerName string, exec api.ContainerExecPost, args *ContainerExecArgs) (Operation, error) { if exec.RecordOutput { if !r.HasExtension("container_exec_recording") { return nil, fmt.Errorf("The server is missing the required \"container_exec_recording\" API extension") } } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/exec", url.QueryEscape(containerName)), exec, "") if err != nil { return nil, err } opAPI := op.Get() // Process additional arguments if args != nil { // Parse the fds fds := map[string]string{} value, ok := opAPI.Metadata["fds"] if ok { values := value.(map[string]interface{}) for k, v := range values { fds[k] = v.(string) } } // Call the control handler with a connection to the control socket if args.Control != nil && fds["control"] != "" { conn, err := r.GetOperationWebsocket(opAPI.ID, fds["control"]) if err != nil { return nil, err } go args.Control(conn) } if exec.Interactive { // Handle interactive sections if args.Stdin != nil && args.Stdout != nil { // Connect to the websocket conn, err := r.GetOperationWebsocket(opAPI.ID, fds["0"]) if err != nil { return nil, err } // And attach stdin and stdout to it go func() { shared.WebsocketSendStream(conn, args.Stdin, -1) <-shared.WebsocketRecvStream(args.Stdout, conn) conn.Close() if args.DataDone != nil { close(args.DataDone) } }() } else { if args.DataDone != nil { close(args.DataDone) } } } else { // Handle non-interactive sessions dones := map[int]chan bool{} conns := []*websocket.Conn{} // Handle stdin if fds["0"] != "" { conn, err := r.GetOperationWebsocket(opAPI.ID, fds["0"]) if err != nil { return nil, err } conns = append(conns, conn) dones[0] = shared.WebsocketSendStream(conn, args.Stdin, -1) } // Handle stdout if fds["1"] != "" { conn, err := r.GetOperationWebsocket(opAPI.ID, fds["1"]) if err != nil { return nil, err } conns = append(conns, conn) dones[1] = shared.WebsocketRecvStream(args.Stdout, conn) } // Handle stderr if fds["2"] != "" { conn, err := r.GetOperationWebsocket(opAPI.ID, fds["2"]) if err != nil { return nil, err } conns = append(conns, conn) dones[2] = shared.WebsocketRecvStream(args.Stderr, conn) } // Wait for everything to be done go func() { for i, chDone := range dones { // Skip stdin, dealing with it separately below if i == 0 { continue } <-chDone } if fds["0"] != "" { if args.Stdin != nil { args.Stdin.Close() } // Empty the stdin channel but don't block on it as // stdin may be stuck in Read() go func() { <-dones[0] }() } for _, conn := range conns { conn.Close() } if args.DataDone != nil { close(args.DataDone) } }() } } return op, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/pr_history.go#L109-L130
func listJobBuilds(bucket storageBucket, jobPrefixes []string) []jobBuilds { jobch := make(chan jobBuilds) defer close(jobch) for i, jobPrefix := range jobPrefixes { go func(i int, jobPrefix string) { buildPrefixes, err := bucket.listSubDirs(jobPrefix) if err != nil { logrus.WithError(err).Warningf("Error getting builds for job %s", jobPrefix) } jobch <- jobBuilds{ name: path.Base(jobPrefix), buildPrefixes: buildPrefixes, } }(i, jobPrefix) } jobs := []jobBuilds{} for range jobPrefixes { job := <-jobch jobs = append(jobs, job) } return jobs }
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/decoder.go#L57-L60
func NewDecoder(reg Registry, r io.Reader) Decoder { var buf []byte return decoder{reg, DefaultMaxSize, bytes.NewBuffer(buf), bufio.NewReader(r)} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/deviceorientation/easyjson.go#L152-L156
func (v ClearDeviceOrientationOverrideParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDeviceorientation1(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/embed/config.go#L366-L421
func NewConfig() *Config { lpurl, _ := url.Parse(DefaultListenPeerURLs) apurl, _ := url.Parse(DefaultInitialAdvertisePeerURLs) lcurl, _ := url.Parse(DefaultListenClientURLs) acurl, _ := url.Parse(DefaultAdvertiseClientURLs) cfg := &Config{ MaxSnapFiles: DefaultMaxSnapshots, MaxWalFiles: DefaultMaxWALs, Name: DefaultName, SnapshotCount: etcdserver.DefaultSnapshotCount, SnapshotCatchUpEntries: etcdserver.DefaultSnapshotCatchUpEntries, MaxTxnOps: DefaultMaxTxnOps, MaxRequestBytes: DefaultMaxRequestBytes, GRPCKeepAliveMinTime: DefaultGRPCKeepAliveMinTime, GRPCKeepAliveInterval: DefaultGRPCKeepAliveInterval, GRPCKeepAliveTimeout: DefaultGRPCKeepAliveTimeout, TickMs: 100, ElectionMs: 1000, InitialElectionTickAdvance: true, LPUrls: []url.URL{*lpurl}, LCUrls: []url.URL{*lcurl}, APUrls: []url.URL{*apurl}, ACUrls: []url.URL{*acurl}, ClusterState: ClusterStateFlagNew, InitialClusterToken: "etcd-cluster", StrictReconfigCheck: DefaultStrictReconfigCheck, Metrics: "basic", EnableV2: DefaultEnableV2, CORS: map[string]struct{}{"*": {}}, HostWhitelist: map[string]struct{}{"*": {}}, AuthToken: "simple", BcryptCost: uint(bcrypt.DefaultCost), PreVote: false, // TODO: enable by default in v3.5 loggerMu: new(sync.RWMutex), logger: nil, Logger: "capnslog", DeprecatedLogOutput: []string{DefaultLogOutput}, LogOutputs: []string{DefaultLogOutput}, Debug: false, LogPkgLevels: "", } cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name) return cfg }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/webaudio/easyjson.go#L231-L235
func (v *EventContextDestroyed) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoWebaudio2(&r, v) return r.Error() }
https://github.com/OneOfOne/xxhash/blob/c1e3185f167680b62832a0a11938a04b1ab265fc/xxhash.go#L177-L182
func round64(h, v uint64) uint64 { h += v * prime64x2 h = rotl64_31(h) h *= prime64x1 return h }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L233-L242
func (p *CompileScriptParams) Do(ctx context.Context) (scriptID ScriptID, exceptionDetails *ExceptionDetails, err error) { // execute var res CompileScriptReturns err = cdp.Execute(ctx, CommandCompileScript, p, &res) if err != nil { return "", nil, err } return res.ScriptID, res.ExceptionDetails, nil }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/server.go#L175-L180
func (c *Client) StartServer(dcid, srvid string) (*http.Header, error) { url := serverPath(dcid, srvid) + "/start" ret := &http.Header{} err := c.client.Post(url, nil, ret, http.StatusAccepted) return ret, err }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L62-L65
func KeyFromIncomingContext(ctx context.Context) (string, error) { md := MetadataFromIncomingContext(ctx) return KeyFromMetadata(md) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/configuration.go#L190-L275
func nextConfiguration(current Configuration, currentIndex uint64, change configurationChangeRequest) (Configuration, error) { if change.prevIndex > 0 && change.prevIndex != currentIndex { return Configuration{}, fmt.Errorf("Configuration changed since %v (latest is %v)", change.prevIndex, currentIndex) } configuration := current.Clone() switch change.command { case AddStaging: // TODO: barf on new address? newServer := Server{ // TODO: This should add the server as Staging, to be automatically // promoted to Voter later. However, the promotion to Voter is not yet // implemented, and doing so is not trivial with the way the leader loop // coordinates with the replication goroutines today. So, for now, the // server will have a vote right away, and the Promote case below is // unused. Suffrage: Voter, ID: change.serverID, Address: change.serverAddress, } found := false for i, server := range configuration.Servers { if server.ID == change.serverID { if server.Suffrage == Voter { configuration.Servers[i].Address = change.serverAddress } else { configuration.Servers[i] = newServer } found = true break } } if !found { configuration.Servers = append(configuration.Servers, newServer) } case AddNonvoter: newServer := Server{ Suffrage: Nonvoter, ID: change.serverID, Address: change.serverAddress, } found := false for i, server := range configuration.Servers { if server.ID == change.serverID { if server.Suffrage != Nonvoter { configuration.Servers[i].Address = change.serverAddress } else { configuration.Servers[i] = newServer } found = true break } } if !found { configuration.Servers = append(configuration.Servers, newServer) } case DemoteVoter: for i, server := range configuration.Servers { if server.ID == change.serverID { configuration.Servers[i].Suffrage = Nonvoter break } } case RemoveServer: for i, server := range configuration.Servers { if server.ID == change.serverID { configuration.Servers = append(configuration.Servers[:i], configuration.Servers[i+1:]...) break } } case Promote: for i, server := range configuration.Servers { if server.ID == change.serverID && server.Suffrage == Staging { configuration.Servers[i].Suffrage = Voter break } } } // Make sure we didn't do something bad like remove the last voter if err := checkConfiguration(configuration); err != nil { return Configuration{}, err } return configuration, nil }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/generators/generate.go#L16-L57
func Generate(packagename string, fileBytes []byte, outputDir string) { b := preprocessJobManifest(fileBytes) objects := make(map[string]map[string]ObjectField) var properties []string for _, v := range b.recs { properties = append(properties, v.Orig) } for i := 0; i < b.max; i++ { for _, v := range b.recs { if v.Length-1 >= i { var structname = v.StructName(i, packagename, properties) var typeName = v.TypeName(i, properties) elementName := v.Slice[i] attributeName := FormatName(elementName) if _, ok := objects[structname]; !ok { objects[structname] = make(map[string]ObjectField) } if previousElement, ok := objects[structname][attributeName]; !ok { lo.G.Debug("Adding", attributeName, "to", structname, "with type", typeName) objects[structname][attributeName] = ObjectField{ ElementName: attributeName, ElementType: typeName, ElementAnnotation: createElementAnnotation(elementName), Meta: v.Yaml, } } else { if previousElement.ElementAnnotation != createElementAnnotation(elementName) { lo.G.Warning("******** Recommended creating custom yaml marshaller on", structname, "for", attributeName, " ********") previousElement.ElementAnnotation = "`yaml:\"-\"`" objects[structname][attributeName] = previousElement } } } } } structs := generateStructs(objects, packagename) writeStructsToDisk(structs, outputDir) }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/imgproc.go#L157-L163
func FitEllipse2(points unsafe.Pointer) Box2D { box := C.cvFitEllipse2(points) center := Point2D32f{float32(box.center.x), float32(box.center.y)} size := Size2D32f{float32(box.size.width), float32(box.size.height)} angle := float32(box.angle) return Box2D{center, size, angle} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L3368-L3372
func (v EventExecutionContextDestroyed) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime31(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/encode.go#L661-L698
func (e Encoder) EncodeMap(n int, f func(Encoder, Encoder) error) (err error) { if e.key { if e.key, err = false, e.Emitter.EmitMapValue(); err != nil { return } } if err = e.Emitter.EmitMapBegin(n); err != nil { return } encodeMap: for i := 0; n < 0 || i < n; i++ { if i != 0 { if err = e.Emitter.EmitMapNext(); err != nil { return } } e.key = true err = f( Encoder{Emitter: e.Emitter, SortMapKeys: e.SortMapKeys}, Encoder{Emitter: e.Emitter, SortMapKeys: e.SortMapKeys, key: true}, ) // Because internal calls don't use the exported methods they may not // reset this flag to false when expected, forcing the value here. e.key = false switch err { case nil: case End: break encodeMap default: return } } return e.Emitter.EmitMapEnd() }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/manifest.go#L116-L118
func openOrCreateManifestFile(dir string, readOnly bool) (ret *manifestFile, result Manifest, err error) { return helpOpenOrCreateManifestFile(dir, readOnly, manifestDeletionsRewriteThreshold) }
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L872-L879
func (p *PubSub) ListPeers(topic string) []peer.ID { out := make(chan []peer.ID) p.getPeers <- &listPeerReq{ resp: out, topic: topic, } return <-out }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L222-L224
func (m *Message) AddAlternativeWriter(contentType string, f func(io.Writer) error, settings ...PartSetting) { m.parts = append(m.parts, m.newPart(contentType, f, settings)) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L330-L427
func (db *DB) Close() (err error) { db.elog.Printf("Closing database") atomic.StoreInt32(&db.blockWrites, 1) // Stop value GC first. db.closers.valueGC.SignalAndWait() // Stop writes next. db.closers.writes.SignalAndWait() // Now close the value log. if vlogErr := db.vlog.Close(); vlogErr != nil { err = errors.Wrap(vlogErr, "DB.Close") } // Make sure that block writer is done pushing stuff into memtable! // Otherwise, you will have a race condition: we are trying to flush memtables // and remove them completely, while the block / memtable writer is still // trying to push stuff into the memtable. This will also resolve the value // offset problem: as we push into memtable, we update value offsets there. if !db.mt.Empty() { db.elog.Printf("Flushing memtable") for { pushedFlushTask := func() bool { db.Lock() defer db.Unlock() y.AssertTrue(db.mt != nil) select { case db.flushChan <- flushTask{mt: db.mt, vptr: db.vhead}: db.imm = append(db.imm, db.mt) // Flusher will attempt to remove this from s.imm. db.mt = nil // Will segfault if we try writing! db.elog.Printf("pushed to flush chan\n") return true default: // If we fail to push, we need to unlock and wait for a short while. // The flushing operation needs to update s.imm. Otherwise, we have a deadlock. // TODO: Think about how to do this more cleanly, maybe without any locks. } return false }() if pushedFlushTask { break } time.Sleep(10 * time.Millisecond) } } db.stopCompactions() // Force Compact L0 // We don't need to care about cstatus since no parallel compaction is running. if db.opt.CompactL0OnClose { err := db.lc.doCompact(compactionPriority{level: 0, score: 1.73}) switch err { case errFillTables: // This error only means that there might be enough tables to do a compaction. So, we // should not report it to the end user to avoid confusing them. case nil: db.opt.Infof("Force compaction on level 0 done") default: db.opt.Warningf("While forcing compaction on level 0: %v", err) } } if lcErr := db.lc.close(); err == nil { err = errors.Wrap(lcErr, "DB.Close") } db.elog.Printf("Waiting for closer") db.closers.updateSize.SignalAndWait() db.orc.Stop() db.elog.Finish() if db.dirLockGuard != nil { if guardErr := db.dirLockGuard.release(); err == nil { err = errors.Wrap(guardErr, "DB.Close") } } if db.valueDirGuard != nil { if guardErr := db.valueDirGuard.release(); err == nil { err = errors.Wrap(guardErr, "DB.Close") } } if manifestErr := db.manifest.close(); err == nil { err = errors.Wrap(manifestErr, "DB.Close") } // Fsync directories to ensure that lock file, and any other removed files whose directory // we haven't specifically fsynced, are guaranteed to have their directory entry removal // persisted to disk. if syncErr := syncDir(db.opt.Dir); err == nil { err = errors.Wrap(syncErr, "DB.Close") } if syncErr := syncDir(db.opt.ValueDir); err == nil { err = errors.Wrap(syncErr, "DB.Close") } return err }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_metadata.go#L320-L326
func getContainerTemplatePath(c container, filename string) (string, error) { if strings.Contains(filename, "/") { return "", fmt.Errorf("Invalid template filename") } return filepath.Join(c.Path(), "templates", filename), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/database/easyjson.go#L111-L115
func (v *GetDatabaseTableNamesReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDatabase(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1971-L1975
func (v *CreateTargetReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget22(&r, v) return r.Error() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4177-L4185
func (u OperationResultTr) MustAccountMergeResult() AccountMergeResult { val, ok := u.GetAccountMergeResult() if !ok { panic("arm AccountMergeResult is not set") } return val }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/peer.go#L314-L320
func (p *peer) Pause() { p.mu.Lock() defer p.mu.Unlock() p.paused = true p.msgAppReader.pause() p.msgAppV2Reader.pause() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L909-L916
func NewOfferEntryExt(v int32, value interface{}) (result OfferEntryExt, err error) { result.V = v switch int32(v) { case 0: // void } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2581-L2585
func (v GetPropertiesParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime22(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/multi.go#L51-L55
func (b *multiLogger) SetLevel(level Level, module string) { for _, backend := range b.backends { backend.SetLevel(level, module) } }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/default_context.go#L248-L262
func (d *DefaultContext) File(name string) (binding.File, error) { req := d.Request() if err := req.ParseMultipartForm(5 * 1024 * 1024); err != nil { return binding.File{}, err } f, h, err := req.FormFile(name) bf := binding.File{ File: f, FileHeader: h, } if err != nil { return bf, err } return bf, nil }
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/telsh/handler.go#L74-L101
func PromoteHandlerFunc(fn HandlerFunc, args ...string) Handler { stdin, stdinPipe := io.Pipe() stdoutPipe, stdout := io.Pipe() stderrPipe, stderr := io.Pipe() argsCopy := make([]string, len(args)) for i, datum := range args { argsCopy[i] = datum } handler := internalPromotedHandlerFunc{ err:nil, fn:fn, stdin:stdin, stdout:stdout, stderr:stderr, stdinPipe:stdinPipe, stdoutPipe:stdoutPipe, stderrPipe:stderrPipe, args:argsCopy, } return &handler }
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/security/nonce.go#L169-L177
func NonceValueFromRequest(r *http.Request) NonceStatus { if c := r.Context().Value(nonceValueKey); c != nil { if v, ok := c.(NonceStatus); ok { return v } } return NonceStatus{NonceNotRequested} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/animation.go#L272-L274
func (p *SetTimingParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetTiming, p, nil) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L729-L750
func restClientFor(config *restConfig) (*url.URL, *http.Client, error) { // REMOVED: Configurable GroupVersion, Codec // REMOVED: Configurable versionedAPIPath baseURL, err := defaultServerURLFor(config) if err != nil { return nil, nil, err } transport, err := transportFor(config) if err != nil { return nil, nil, err } var httpClient *http.Client if transport != http.DefaultTransport { httpClient = &http.Client{Transport: transport} } // REMOVED: Configurable QPS, Burst, ContentConfig // REMOVED: Actually returning a RESTClient object. return baseURL, httpClient, nil }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/rdy.go#L24-L39
func (c Rdy) Write(w *bufio.Writer) (err error) { if _, err = w.WriteString("RDY "); err != nil { err = errors.Wrap(err, "writing RDY command") return } b := strconv.AppendUint(make([]byte, 0, 64), uint64(c.Count), 10) b = append(b, '\n') if _, err = w.Write(b); err != nil { err = errors.Wrap(err, "writint RDY count") return } return }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/iaas.go#L28-L52
func machinesList(w http.ResponseWriter, r *http.Request, token auth.Token) error { machines, err := iaas.ListMachines() if err != nil { return err } contexts := permission.ContextsForPermission(token, permission.PermMachineRead) allowedIaaS := map[string]struct{}{} for _, c := range contexts { if c.CtxType == permTypes.CtxGlobal { allowedIaaS = nil break } if c.CtxType == permTypes.CtxIaaS { allowedIaaS[c.Value] = struct{}{} } } for i := 0; allowedIaaS != nil && i < len(machines); i++ { if _, ok := allowedIaaS[machines[i].Iaas]; !ok { machines = append(machines[:i], machines[i+1:]...) i-- } } w.Header().Add("Content-Type", "application/json") return json.NewEncoder(w).Encode(machines) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/connection.go#L701-L726
func (c *Connection) writeFrames(_ uint32) { for { select { case f := <-c.sendCh: if c.log.Enabled(LogLevelDebug) { c.log.Debugf("Writing frame %s", f.Header) } c.updateLastActivity(f) err := f.WriteOut(c.conn) c.opts.FramePool.Release(f) if err != nil { c.connectionError("write frames", err) return } case <-c.stopCh: // If there are frames in sendCh, we want to drain them. if len(c.sendCh) > 0 { continue } // Close the network once we're no longer writing frames. c.closeNetwork() return } } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/boskos.go#L130-L177
func handleAcquire(r *ranch.Ranch) http.HandlerFunc { return func(res http.ResponseWriter, req *http.Request) { logrus.WithField("handler", "handleStart").Infof("From %v", req.RemoteAddr) if req.Method != http.MethodPost { msg := fmt.Sprintf("Method %v, /acquire only accepts POST.", req.Method) logrus.Warning(msg) http.Error(res, msg, http.StatusMethodNotAllowed) return } // TODO(krzyzacy) - sanitize user input rtype := req.URL.Query().Get("type") state := req.URL.Query().Get("state") dest := req.URL.Query().Get("dest") owner := req.URL.Query().Get("owner") if rtype == "" || state == "" || dest == "" || owner == "" { msg := fmt.Sprintf("Type: %v, state: %v, dest: %v, owner: %v, all of them must be set in the request.", rtype, state, dest, owner) logrus.Warning(msg) http.Error(res, msg, http.StatusBadRequest) return } logrus.Infof("Request for a %v %v from %v, dest %v", state, rtype, owner, dest) resource, err := r.Acquire(rtype, state, dest, owner) if err != nil { logrus.WithError(err).Errorf("No available resource") http.Error(res, err.Error(), ErrorToStatus(err)) return } resJSON, err := json.Marshal(resource) if err != nil { logrus.WithError(err).Errorf("json.Marshal failed: %v, resource will be released", resource) http.Error(res, err.Error(), ErrorToStatus(err)) // release the resource, though this is not expected to happen. err = r.Release(resource.Name, state, owner) if err != nil { logrus.WithError(err).Warningf("unable to release resource %s", resource.Name) } return } logrus.Infof("Resource leased: %v", string(resJSON)) fmt.Fprint(res, string(resJSON)) } }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L743-L755
func (c Cursor) String() string { if c.cc == nil { return "" } b, err := proto.Marshal(c.cc) if err != nil { // The only way to construct a Cursor with a non-nil cc field is to // unmarshal from the byte representation. We panic if the unmarshal // succeeds but the marshaling of the unchanged protobuf value fails. panic(fmt.Sprintf("datastore: internal error: malformed cursor: %v", err)) } return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=") }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L44-L57
func (c MockSpanContext) WithBaggageItem(key, value string) MockSpanContext { var newBaggage map[string]string if c.Baggage == nil { newBaggage = map[string]string{key: value} } else { newBaggage = make(map[string]string, len(c.Baggage)+1) for k, v := range c.Baggage { newBaggage[k] = v } newBaggage[key] = value } // Use positional parameters so the compiler will help catch new fields. return MockSpanContext{c.TraceID, c.SpanID, c.Sampled, newBaggage} }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_zfs.go#L82-L94
func (s *storageZfs) StoragePoolInit() error { err := s.StorageCoreInit() if err != nil { return err } // Detect whether we have been given a zfs dataset as source. if s.pool.Config["zfs.pool_name"] != "" { s.dataset = s.pool.Config["zfs.pool_name"] } return nil }
https://github.com/apparentlymart/go-rundeck-api/blob/2c962acae81080a937c350a5bea054c239f27a81/rundeck/key.go#L25-L29
func (c *Client) GetKeyMeta(path string) (*KeyMeta, error) { k := &KeyMeta{} err := c.get([]string{"storage", "keys", path}, nil, k) return k, err }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1614-L1681
func (r *ProtocolLXD) ConsoleContainer(containerName string, console api.ContainerConsolePost, args *ContainerConsoleArgs) (Operation, error) { if !r.HasExtension("console") { return nil, fmt.Errorf("The server is missing the required \"console\" API extension") } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/console", url.QueryEscape(containerName)), console, "") if err != nil { return nil, err } opAPI := op.Get() if args == nil || args.Terminal == nil { return nil, fmt.Errorf("A terminal must be set") } if args.Control == nil { return nil, fmt.Errorf("A control channel must be set") } // Parse the fds fds := map[string]string{} value, ok := opAPI.Metadata["fds"] if ok { values := value.(map[string]interface{}) for k, v := range values { fds[k] = v.(string) } } var controlConn *websocket.Conn // Call the control handler with a connection to the control socket if fds["control"] == "" { return nil, fmt.Errorf("Did not receive a file descriptor for the control channel") } controlConn, err = r.GetOperationWebsocket(opAPI.ID, fds["control"]) if err != nil { return nil, err } go args.Control(controlConn) // Connect to the websocket conn, err := r.GetOperationWebsocket(opAPI.ID, fds["0"]) if err != nil { return nil, err } // Detach from console. go func(consoleDisconnect <-chan bool) { <-consoleDisconnect msg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "Detaching from console") // We don't care if this fails. This is just for convenience. controlConn.WriteMessage(websocket.CloseMessage, msg) controlConn.Close() }(args.ConsoleDisconnect) // And attach stdin and stdout to it go func() { shared.WebsocketSendStream(conn, args.Terminal, -1) <-shared.WebsocketRecvStream(args.Terminal, conn) conn.Close() }() return op, nil }
https://github.com/suicidejack/throttled/blob/373909e862a27e2190015918229c2605b3221f1d/wait_group.go#L27-L36
func (w *WaitGroup) Add() { w.outstanding++ if w.outstanding > w.throttle { select { case <-w.completed: w.outstanding-- return } } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/mex.go#L385-L406
func (mexset *messageExchangeSet) expireExchange(msgID uint32) { mexset.log.Debugf( "Removing %s message exchange %d due to timeout, cancellation or blackhole", mexset.name, msgID, ) mexset.Lock() // TODO(aniketp): explore if cancel can be called everytime we expire an exchange found, expired := mexset.deleteExchange(msgID) if found || expired { // Record in expiredExchanges if we deleted the exchange. mexset.expiredExchanges[msgID] = struct{}{} } mexset.Unlock() if expired { mexset.log.WithFields(LogField{"msgID", msgID}).Info("Exchange expired already") } mexset.onRemoved() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_pools_utils.go#L283-L293
func dbStoragePoolCreateAndUpdateCache(db *db.Cluster, poolName string, poolDescription string, poolDriver string, poolConfig map[string]string) (int64, error) { id, err := db.StoragePoolCreate(poolName, poolDescription, poolDriver, poolConfig) if err != nil { return id, err } // Update the storage drivers cache in api_1.0.go. storagePoolDriversCacheUpdate(db) return id, nil }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L548-L553
func Not(src, dst *IplImage) { C.cvNot( unsafe.Pointer(src), unsafe.Pointer(dst), ) }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/usermanagment.go#L198-L203
func (c *Client) DeleteGroup(groupid string) (*http.Header, error) { url := umGroupPath(groupid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &http.Header{} err := c.client.Delete(url, ret, http.StatusAccepted) return ret, err }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L245-L251
func (l *PeerList) exists(hostPort string) (*peerScore, bool) { l.RLock() ps, ok := l.peersByHostPort[hostPort] l.RUnlock() return ps, ok }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/main.go#L131-L134
func fileExists(file string) bool { _, err := os.Stat(file) return err == nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/http.go#L47-L58
func extractUploads(payload *APIParams) (uploads []*FileUpload) { for k, v := range *payload { if mpart, ok := v.(*FileUpload); ok { uploads = append(uploads, mpart) delete(*payload, k) } else if child_params, ok := v.(APIParams); ok { child_uploads := extractUploads(&child_params) uploads = append(uploads, child_uploads...) } } return uploads }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/statusreconciler/controller.go#L38-L57
func NewController(continueOnError bool, addedPresubmitBlacklist sets.String, prowJobClient prowv1.ProwJobInterface, githubClient *github.Client, configAgent *config.Agent, pluginAgent *plugins.ConfigAgent) *Controller { return &Controller{ continueOnError: continueOnError, addedPresubmitBlacklist: addedPresubmitBlacklist, prowJobTriggerer: &kubeProwJobTriggerer{ prowJobClient: prowJobClient, githubClient: githubClient, configAgent: configAgent, }, githubClient: githubClient, statusMigrator: &gitHubMigrator{ githubClient: githubClient, continueOnError: continueOnError, }, trustedChecker: &githubTrustedChecker{ githubClient: githubClient, pluginAgent: pluginAgent, }, } }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L298-L307
func (d *topologyGossipData) Merge(other GossipData) GossipData { names := make(peerNameSet) for name := range d.update { names[name] = struct{}{} } for name := range other.(*topologyGossipData).update { names[name] = struct{}{} } return &topologyGossipData{peers: d.peers, update: names} }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L2400-L2402
func (api *API) ReservedInstanceLocator(href string) *ReservedInstanceLocator { return &ReservedInstanceLocator{Href(href), api} }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/progress.go#L213-L227
func (in *inflights) add(inflight uint64) { if in.full() { panic("cannot add into a full inflights") } next := in.start + in.count size := in.size if next >= size { next -= size } if next >= len(in.buffer) { in.growBuf() } in.buffer[next] = inflight in.count++ }
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/encodable.go#L63-L69
func (tpl *TupleEqualityList) EncodeSQL(buf *bytes.Buffer) { if len(tpl.Columns) == 1 { tpl.encodeAsIn(buf) return } tpl.encodeAsEquality(buf) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/security/easyjson.go#L286-L290
func (v *SetIgnoreCertificateErrorsParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoSecurity1(&r, v) return r.Error() }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/frame.go#L69-L96
func ReadFrame(r *bufio.Reader) (frame Frame, err error) { var size int32 var ftype int32 if err = binary.Read(r, binary.BigEndian, &size); err != nil { err = errors.Wrap(err, "reading frame size") return } if err = binary.Read(r, binary.BigEndian, &ftype); err != nil { err = errors.Wrap(err, "reading frame type") return } switch size -= 4; FrameType(ftype) { case FrameTypeResponse: return readResponse(int(size), r) case FrameTypeError: return readError(int(size), r) case FrameTypeMessage: return readMessage(int(size), r) default: return readUnknownFrame(FrameType(ftype), int(size), r) } }
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L286-L288
func (l *Logger) Print(args ...interface{}) { l.Output(2, LevelTrace, fmt.Sprint(args...)) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/y.go#L171-L180
func FixedDuration(d time.Duration) string { str := fmt.Sprintf("%02ds", int(d.Seconds())%60) if d >= time.Minute { str = fmt.Sprintf("%02dm", int(d.Minutes())%60) + str } if d >= time.Hour { str = fmt.Sprintf("%02dh", int(d.Hours())) + str } return str }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/raftexample/httpapi.go#L105-L123
func serveHttpKVAPI(kv *kvstore, port int, confChangeC chan<- raftpb.ConfChange, errorC <-chan error) { srv := http.Server{ Addr: ":" + strconv.Itoa(port), Handler: &httpKVAPI{ store: kv, confChangeC: confChangeC, }, } go func() { if err := srv.ListenAndServe(); err != nil { log.Fatal(err) } }() // exit when raft goes down if err, ok := <-errorC; ok { log.Fatal(err) } }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L225-L234
func (mat *Mat) InitHeader(rows, cols, type_ int, data unsafe.Pointer, step int) { C.cvInitMatHeader( (*C.CvMat)(mat), C.int(rows), C.int(cols), C.int(type_), data, C.int(step), ) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/phony/phony.go#L29-L53
func SendHook(address, eventType string, payload, hmac []byte) error { req, err := http.NewRequest(http.MethodPost, address, bytes.NewBuffer(payload)) if err != nil { return err } req.Header.Set("X-GitHub-Event", eventType) req.Header.Set("X-GitHub-Delivery", "GUID") req.Header.Set("X-Hub-Signature", github.PayloadSignature(payload, hmac)) req.Header.Set("content-type", "application/json") c := &http.Client{} resp, err := c.Do(req) if err != nil { return err } defer resp.Body.Close() rb, err := ioutil.ReadAll(resp.Body) if err != nil { return err } if resp.StatusCode != 200 { return fmt.Errorf("response from hook has status %d and body %s", resp.StatusCode, string(bytes.TrimSpace(rb))) } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L122-L157
func (s *store) Get(nodePath string, recursive, sorted bool) (*Event, error) { var err *v2error.Error s.worldLock.RLock() defer s.worldLock.RUnlock() defer func() { if err == nil { s.Stats.Inc(GetSuccess) if recursive { reportReadSuccess(GetRecursive) } else { reportReadSuccess(Get) } return } s.Stats.Inc(GetFail) if recursive { reportReadFailure(GetRecursive) } else { reportReadFailure(Get) } }() n, err := s.internalGet(nodePath) if err != nil { return nil, err } e := newEvent(Get, nodePath, n.ModifiedIndex, n.CreatedIndex) e.EtcdIndex = s.CurrentIndex e.Node.loadInternalNode(n, recursive, sorted, s.clock) return e, nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L1013-L1144
func (r *Raft) appendEntries(rpc RPC, a *AppendEntriesRequest) { defer metrics.MeasureSince([]string{"raft", "rpc", "appendEntries"}, time.Now()) // Setup a response resp := &AppendEntriesResponse{ RPCHeader: r.getRPCHeader(), Term: r.getCurrentTerm(), LastLog: r.getLastIndex(), Success: false, NoRetryBackoff: false, } var rpcErr error defer func() { rpc.Respond(resp, rpcErr) }() // Ignore an older term if a.Term < r.getCurrentTerm() { return } // Increase the term if we see a newer one, also transition to follower // if we ever get an appendEntries call if a.Term > r.getCurrentTerm() || r.getState() != Follower { // Ensure transition to follower r.setState(Follower) r.setCurrentTerm(a.Term) resp.Term = a.Term } // Save the current leader r.setLeader(ServerAddress(r.trans.DecodePeer(a.Leader))) // Verify the last log entry if a.PrevLogEntry > 0 { lastIdx, lastTerm := r.getLastEntry() var prevLogTerm uint64 if a.PrevLogEntry == lastIdx { prevLogTerm = lastTerm } else { var prevLog Log if err := r.logs.GetLog(a.PrevLogEntry, &prevLog); err != nil { r.logger.Warn(fmt.Sprintf("Failed to get previous log: %d %v (last: %d)", a.PrevLogEntry, err, lastIdx)) resp.NoRetryBackoff = true return } prevLogTerm = prevLog.Term } if a.PrevLogTerm != prevLogTerm { r.logger.Warn(fmt.Sprintf("Previous log term mis-match: ours: %d remote: %d", prevLogTerm, a.PrevLogTerm)) resp.NoRetryBackoff = true return } } // Process any new entries if len(a.Entries) > 0 { start := time.Now() // Delete any conflicting entries, skip any duplicates lastLogIdx, _ := r.getLastLog() var newEntries []*Log for i, entry := range a.Entries { if entry.Index > lastLogIdx { newEntries = a.Entries[i:] break } var storeEntry Log if err := r.logs.GetLog(entry.Index, &storeEntry); err != nil { r.logger.Warn(fmt.Sprintf("Failed to get log entry %d: %v", entry.Index, err)) return } if entry.Term != storeEntry.Term { r.logger.Warn(fmt.Sprintf("Clearing log suffix from %d to %d", entry.Index, lastLogIdx)) if err := r.logs.DeleteRange(entry.Index, lastLogIdx); err != nil { r.logger.Error(fmt.Sprintf("Failed to clear log suffix: %v", err)) return } if entry.Index <= r.configurations.latestIndex { r.configurations.latest = r.configurations.committed r.configurations.latestIndex = r.configurations.committedIndex } newEntries = a.Entries[i:] break } } if n := len(newEntries); n > 0 { // Append the new entries if err := r.logs.StoreLogs(newEntries); err != nil { r.logger.Error(fmt.Sprintf("Failed to append to logs: %v", err)) // TODO: leaving r.getLastLog() in the wrong // state if there was a truncation above return } // Handle any new configuration changes for _, newEntry := range newEntries { r.processConfigurationLogEntry(newEntry) } // Update the lastLog last := newEntries[n-1] r.setLastLog(last.Index, last.Term) } metrics.MeasureSince([]string{"raft", "rpc", "appendEntries", "storeLogs"}, start) } // Update the commit index if a.LeaderCommitIndex > 0 && a.LeaderCommitIndex > r.getCommitIndex() { start := time.Now() idx := min(a.LeaderCommitIndex, r.getLastIndex()) r.setCommitIndex(idx) if r.configurations.latestIndex <= idx { r.configurations.committed = r.configurations.latest r.configurations.committedIndex = r.configurations.latestIndex } r.processLogs(idx, nil) metrics.MeasureSince([]string{"raft", "rpc", "appendEntries", "processLogs"}, start) } // Everything went well, set success resp.Success = true r.setLastContact() return }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_compare.go#L272-L296
func coalesceAdjacentRecords(name string, recs []reportRecord) (groups []diffStats) { var prevCase int // Arbitrary index into which case last occurred lastStats := func(i int) *diffStats { if prevCase != i { groups = append(groups, diffStats{Name: name}) prevCase = i } return &groups[len(groups)-1] } for _, r := range recs { switch rv := r.Value; { case rv.NumIgnored > 0 && rv.NumSame+rv.NumDiff == 0: lastStats(1).NumIgnored++ case rv.NumDiff == 0: lastStats(1).NumIdentical++ case rv.NumDiff > 0 && !rv.ValueY.IsValid(): lastStats(2).NumRemoved++ case rv.NumDiff > 0 && !rv.ValueX.IsValid(): lastStats(2).NumInserted++ default: lastStats(2).NumModified++ } } return groups }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fix.go#L73-L116
func squashCgoLibrary(c *config.Config, f *rule.File) { // Find the default cgo_library and go_library rules. var cgoLibrary, goLibrary *rule.Rule for _, r := range f.Rules { if r.Kind() == "cgo_library" && r.Name() == "cgo_default_library" && !r.ShouldKeep() { if cgoLibrary != nil { log.Printf("%s: when fixing existing file, multiple cgo_library rules with default name found", f.Path) continue } cgoLibrary = r continue } if r.Kind() == "go_library" && r.Name() == defaultLibName { if goLibrary != nil { log.Printf("%s: when fixing existing file, multiple go_library rules with default name referencing cgo_library found", f.Path) } goLibrary = r continue } } if cgoLibrary == nil { return } if !c.ShouldFix { log.Printf("%s: cgo_library is deprecated. Run 'gazelle fix' to squash with go_library.", f.Path) return } if goLibrary == nil { cgoLibrary.SetKind("go_library") cgoLibrary.SetName(defaultLibName) cgoLibrary.SetAttr("cgo", true) return } if err := rule.SquashRules(cgoLibrary, goLibrary, f.Path); err != nil { log.Print(err) return } goLibrary.DelAttr("embed") goLibrary.SetAttr("cgo", true) cgoLibrary.Delete() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/wal/wal.go#L508-L578
func Verify(lg *zap.Logger, walDir string, snap walpb.Snapshot) error { var metadata []byte var err error var match bool rec := &walpb.Record{} names, nameIndex, err := selectWALFiles(lg, walDir, snap) if err != nil { return err } // open wal files in read mode, so that there is no conflict // when the same WAL is opened elsewhere in write mode rs, _, closer, err := openWALFiles(lg, walDir, names, nameIndex, false) if err != nil { return err } // create a new decoder from the readers on the WAL files decoder := newDecoder(rs...) for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) { switch rec.Type { case metadataType: if metadata != nil && !bytes.Equal(metadata, rec.Data) { return ErrMetadataConflict } metadata = rec.Data case crcType: crc := decoder.crc.Sum32() // Current crc of decoder must match the crc of the record. // We need not match 0 crc, since the decoder is a new one at this point. if crc != 0 && rec.Validate(crc) != nil { return ErrCRCMismatch } decoder.updateCRC(rec.Crc) case snapshotType: var loadedSnap walpb.Snapshot pbutil.MustUnmarshal(&loadedSnap, rec.Data) if loadedSnap.Index == snap.Index { if loadedSnap.Term != snap.Term { return ErrSnapshotMismatch } match = true } // We ignore all entry and state type records as these // are not necessary for validating the WAL contents case entryType: case stateType: default: return fmt.Errorf("unexpected block type %d", rec.Type) } } if closer != nil { closer() } // We do not have to read out all the WAL entries // as the decoder is opened in read mode. if err != io.EOF && err != io.ErrUnexpectedEOF { return err } if !match { return ErrSnapshotNotFound } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/types.go#L81-L83
func (t *InspectMode) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L1689-L1714
func forceDeleteLock(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { appName := r.URL.Query().Get(":app") a, err := getAppFromContext(appName, r) if err != nil { return err } allowed := permission.Check(t, permission.PermAppAdminUnlock, contextsForApp(&a)..., ) if !allowed { return permission.ErrUnauthorized } evt, err := event.New(&event.Opts{ Target: appTarget(appName), Kind: permission.PermAppAdminUnlock, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(&a)...), }) if err != nil { return err } defer func() { evt.Done(err) }() app.ReleaseApplicationLock(a.Name) return nil }
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/float.go#L116-L119
func (f *Float) SetValid(v float64) { f.Float64 = v f.Valid = true }
https://github.com/pantheon-systems/go-certauth/blob/8764720d23a5034dd9fab090815b7859463c68f6/certauth.go#L178-L190
func (a *Auth) ValidateOU(verifiedCert *x509.Certificate) error { var failed []string for _, ou := range a.opt.AllowedOUs { for _, clientOU := range verifiedCert.Subject.OrganizationalUnit { if ou == clientOU { return nil } failed = append(failed, clientOU) } } return fmt.Errorf("cert failed OU validation for %v, Allowed: %v", failed, a.opt.AllowedOUs) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L1924-L1928
func (v *SetCookieReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork14(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/config.go#L195-L200
func (c *ServerConfig) hasLocalMember() error { if urls := c.InitialPeerURLsMap[c.Name]; urls == nil { return fmt.Errorf("couldn't find local name %q in the initial cluster configuration", c.Name) } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/config.go#L1447-L1461
func SetPostsubmitRegexes(ps []Postsubmit) error { for i, j := range ps { b, err := setBrancherRegexes(j.Brancher) if err != nil { return fmt.Errorf("could not set branch regexes for %s: %v", j.Name, err) } ps[i].Brancher = b c, err := setChangeRegexes(j.RegexpChangeMatcher) if err != nil { return fmt.Errorf("could not set change regexes for %s: %v", j.Name, err) } ps[i].RegexpChangeMatcher = c } return nil }
https://github.com/google/shlex/blob/c34317bd91bf98fab745d77b03933cf8769299fe/shlex.go#L126-L134
func newDefaultClassifier() tokenClassifier { t := tokenClassifier{} t.addRuneClass(spaceRunes, spaceRuneClass) t.addRuneClass(escapingQuoteRunes, escapingQuoteRuneClass) t.addRuneClass(nonEscapingQuoteRunes, nonEscapingQuoteRuneClass) t.addRuneClass(escapeRunes, escapeRuneClass) t.addRuneClass(commentRunes, commentRuneClass) return t }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/symbols.go#L53-L55
func (s LexSymbolSorter) Less(i, j int) bool { return s.list[i].Priority > s.list[j].Priority }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/touch.go#L23-L40
func (c Touch) Write(w *bufio.Writer) (err error) { if _, err = w.WriteString("TOUCH "); err != nil { err = errors.Wrap(err, "writing TOUCH command") return } if _, err = c.MessageID.WriteTo(w); err != nil { err = errors.Wrap(err, "writing TOUCH message ID") return } if err = w.WriteByte('\n'); err != nil { err = errors.Wrap(err, "writing TOUCH command") return } return }
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/cascade.go#L155-L228
func cascadeSaveWithConfig(conf *CascadeConfig, doc Document) (*mgo.ChangeInfo, error) { // Create a new map with just the props to cascade data := conf.Data switch conf.RelType { case REL_ONE: if len(conf.OldQuery) > 0 { update1 := map[string]map[string]interface{}{ "$set": map[string]interface{}{}, } if len(conf.ThroughProp) > 0 { update1["$set"][conf.ThroughProp] = nil } else { for _, p := range conf.Properties { update1["$set"][p] = nil } } ret, err := conf.Collection.Collection().UpdateAll(conf.OldQuery, update1) if conf.RemoveOnly { return ret, err } } update := make(map[string]interface{}) if len(conf.ThroughProp) > 0 { m := bson.M{} m[conf.ThroughProp] = data update["$set"] = m } else { update["$set"] = data } // Just update return conf.Collection.Collection().UpdateAll(conf.Query, update) case REL_MANY: update1 := map[string]map[string]interface{}{ "$pull": map[string]interface{}{}, } q := bson.M{} for _, f := range conf.ReferenceQuery { q[f.BsonName] = f.Value } update1["$pull"][conf.ThroughProp] = q if len(conf.OldQuery) > 0 { ret, err := conf.Collection.Collection().UpdateAll(conf.OldQuery, update1) if conf.RemoveOnly { return ret, err } } // Remove self from current relations, so we can replace it conf.Collection.Collection().UpdateAll(conf.Query, update1) update2 := map[string]map[string]interface{}{ "$push": map[string]interface{}{}, } update2["$push"][conf.ThroughProp] = data return conf.Collection.Collection().UpdateAll(conf.Query, update2) } return &mgo.ChangeInfo{}, errors.New("Invalid relation type") }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/types.go#L62-L76
func (t *VersionRunningStatus) UnmarshalEasyJSON(in *jlexer.Lexer) { switch VersionRunningStatus(in.String()) { case VersionRunningStatusStopped: *t = VersionRunningStatusStopped case VersionRunningStatusStarting: *t = VersionRunningStatusStarting case VersionRunningStatusRunning: *t = VersionRunningStatusRunning case VersionRunningStatusStopping: *t = VersionRunningStatusStopping default: in.AddError(errors.New("unknown VersionRunningStatus value")) } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/rsssh/main.go#L148-L176
func serverArray(client *cm15.API, name string) []*cm15.Instance { serverArrayLocator := client.ServerArrayLocator("/api/server_arrays") serverArrays, err := serverArrayLocator.Index(rsapi.APIParams{"view": "default", "filter": []string{"name==" + name}}) if err != nil { fail("Failed to retrieve server array: %v\n", err.Error()) } if len(serverArrays) == 0 { fail("Could not find server array with name: %v\n", name) } else if len(serverArrays) != 1 { fail("More than one server array found with name: %v\n", name) } array := serverArrays[0] var instancesHref string for _, l := range array.Links { if l["rel"] == "current_instances" { instancesHref = l["href"] break } } instanceLocator := client.InstanceLocator(instancesHref) instances, err := instanceLocator.Index(rsapi.APIParams{}) if err != nil { fail("Failed to retrieve current instances of the server array: %v\n", err.Error()) } if len(instances) == 0 { fail("No instances found in server array: %v\n", name) } return instances }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L854-L867
func (app *App) RemoveUnits(n uint, process string, w io.Writer) error { prov, err := app.getProvisioner() if err != nil { return err } w = app.withLogWriter(w) err = prov.RemoveUnits(app, n, process, w) rebuild.RoutesRebuildOrEnqueue(app.Name) quotaErr := app.fixQuota() if err != nil { return err } return quotaErr }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L109-L112
func (p DispatchKeyEventParams) WithAutoRepeat(autoRepeat bool) *DispatchKeyEventParams { p.AutoRepeat = autoRepeat return &p }
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/integers.go#L308-L395
func (b *TupleBuilder) PutUint64(field string, value uint64) (wrote uint64, err error) { // field type should be if err = b.typeCheck(field, Uint64Field); err != nil { return 0, err } if value < math.MaxUint8 { // minimum bytes is 2 (type code + value) if b.available() < 2 { return 0, xbinary.ErrOutOfRange } // write type code b.buffer[b.pos] = byte(UnsignedLong8Code.OpCode) // write value b.buffer[b.pos+1] = byte(value) // set field offset b.offsets[field] = b.pos // incr pos b.pos += 2 return 2, nil } else if value < math.MaxUint16 { // write value // length check performed by xbinary wrote, err = xbinary.LittleEndian.PutUint16(b.buffer, b.pos+1, uint16(value)) if err != nil { return 0, err } // write type code b.buffer[b.pos] = byte(UnsignedLong16Code.OpCode) // set field offset b.offsets[field] = b.pos // incr pos b.pos += 3 // wrote 3 bytes return 3, nil } else if value < math.MaxUint32 { // write value // length check performed by xbinary wrote, err = xbinary.LittleEndian.PutUint32(b.buffer, b.pos+1, uint32(value)) if err != nil { return 0, err } // write type code b.buffer[b.pos] = byte(UnsignedLong32Code.OpCode) // set field offset b.offsets[field] = b.pos // incr pos b.pos += 5 // wrote 5 bytes return 5, nil } // write value // length check performed by xbinary wrote, err = xbinary.LittleEndian.PutUint64(b.buffer, b.pos+1, value) if err != nil { return 0, err } // write type code b.buffer[b.pos] = byte(UnsignedLong64Code.OpCode) // set field offset b.offsets[field] = b.pos // incr pos b.pos += 9 // wrote 9 bytes return 9, nil }