_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/store.go#L104-L110
func (rp *redisProvider) UpExpire(sid string) error { var err error redisPool.Exec(func(c *redis.Client) { err = c.Expire(sid, sessExpire).Err() }) return err }
https://github.com/drone/drone-plugin-go/blob/d6109f644c5935c22620081b4c234bb2263743c7/plugin/param.go#L75-L94
func (p ParamSet) Parse() error { raw := map[string]json.RawMessage{} err := json.NewDecoder(p.reader).Decode(&raw) if err != nil { return err } for key, val := range p.params { data, ok := raw[key] if !ok { continue } err := json.Unmarshal(data, val) if err != nil { return fmt.Errorf("Unable to unarmshal %s. %s", key, err) } } return nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/portforwarder.go#L177-L182
func (f *PortForwarder) RunForDashWebSocket(localPort uint16) error { if localPort == 0 { localPort = dashWebSocketLocalPort } return f.Run("dash", localPort, 8081) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L250-L254
func (v ShapeOutsideInfo) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom1(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L249-L251
func (s *oAuthSigner) CanAuthenticate(host string) error { return testAuth(s, s.client, host, false) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L433-L442
func isPathParam(p string, pathPatterns []*gen.PathPattern) bool { for _, pattern := range pathPatterns { for _, v := range pattern.Variables { if p == v { return true } } } return false }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/fake_open_wrapper.go#L96-L98
func (o *FakeOpenPluginWrapper) ReceiveComment(comment sql.Comment) []Point { return o.plugin.ReceiveComment(comment) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/client.go#L183-L189
func newDummyClient(t Type) *dummyClient { c := &dummyClient{ t: t, objects: make(map[string]Object), } return c }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/pretty/pretty.go#L229-L231
func CompactPrintBranch(b *pfs.Branch) string { return fmt.Sprintf("%s@%s", b.Repo.Name, b.Name) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/cmd/tsurud/checker.go#L40-L45
func checkProvisioner() error { if value, _ := config.Get("provisioner"); value == defaultProvisionerName || value == "" { return checkDocker() } return nil }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/region.go#L20-L25
func (r region) Address() core.Address { if r.typ.Kind != KindPtr { panic("can't ask for the Address of a non-pointer " + r.typ.Name) } return r.p.proc.ReadPtr(r.a) }
https://github.com/Jeffail/tunny/blob/4921fff29480bad359ad2fb3271fb461c8ffe1fc/tunny.go#L119-L127
func New(n int, ctor func() Worker) *Pool { p := &Pool{ ctor: ctor, reqChan: make(chan workRequest), } p.SetSize(n) return p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/easyjson.go#L984-L988
func (v *BackendNode) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCdp3(&r, v) return r.Error() }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/mnemosyned/session_manager.go#L123-L142
func (sm *sessionManager) Context(ctx context.Context, req *empty.Empty) (*mnemosynerpc.ContextResponse, error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { return nil, status.Errorf(codes.InvalidArgument, "missing metadata in context, access token cannot be retrieved") } if len(md[mnemosyne.AccessTokenMetadataKey]) == 0 { return nil, status.Errorf(codes.InvalidArgument, "missing access token in metadata") } at := md[mnemosyne.AccessTokenMetadataKey][0] res, err := sm.Get(ctx, &mnemosynerpc.GetRequest{AccessToken: at}) if err != nil { return nil, err } return &mnemosynerpc.ContextResponse{ Session: res.Session, }, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/ancestry/ancestry.go#L20-L51
func Parse(s string) (string, int) { sepIndex := strings.IndexAny(s, "^~") if sepIndex == -1 { return s, 0 } // Find the separator, which is either "^" or "~" sep := s[sepIndex] strAfterSep := s[sepIndex+1:] // Try convert the string after the separator to an int. intAfterSep, err := strconv.Atoi(strAfterSep) // If it works, return if err == nil { return s[:sepIndex], intAfterSep } // Otherwise, we check if there's a sequence of separators, as in // "master^^^^" or "master~~~~" for i := sepIndex + 1; i < len(s); i++ { if s[i] != sep { // If we find a character that's not the separator, as in // "master~whatever", then we return. return s, 0 } } // Here we've confirmed that the commit ID ends with a sequence of // (the same) separators and therefore uses the correct ancestry // syntax. return s[:sepIndex], len(s) - sepIndex }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/wrap.go#L210-L216
func (m *Method) CallList(reqStruct string) string { args := []string{"ctx"} for _, arg := range m.Arguments() { args = append(args, reqStruct+"."+arg.ArgStructName()) } return strings.Join(args, ", ") }
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/incoming.go#L376-L385
func (u *Update) Type() UpdateType { if u.Message != nil { return MessageUpdate } else if u.InlineQuery != nil { return InlineQueryUpdate } else if u.ChosenInlineResult != nil { return ChosenInlineResultUpdate } return UnknownUpdate }
https://github.com/r3labs/sse/blob/2f90368216802092e9ed520c43e974e11d50438d/client.go#L54-L93
func (c *Client) Subscribe(stream string, handler func(msg *Event)) error { operation := func() error { resp, err := c.request(stream) if err != nil { return err } defer resp.Body.Close() reader := NewEventStreamReader(resp.Body) for { // Read each new line and process the type of event event, err := reader.ReadEvent() if err != nil { if err == io.EOF { return nil } // run user specified disconnect function if c.disconnectcb != nil { c.disconnectcb(c) } return err } // If we get an error, ignore it. if msg, err := c.processEvent(event); err == nil { if len(msg.ID) > 0 { c.EventID = string(msg.ID) } else { msg.ID = []byte(c.EventID) } handler(msg) } } } return backoff.Retry(operation, backoff.NewExponentialBackOff()) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L499-L503
func (v SetShowAdHighlightsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoOverlay6(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/qor/roles/blob/d6375609fe3e5da46ad3a574fae244fb633e79c1/role.go#L49-L51
func (role *Role) Allow(mode PermissionMode, roles ...string) *Permission { return role.NewPermission().Allow(mode, roles...) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/introspection.go#L455-L467
func (l *PeerList) IntrospectList(opts *IntrospectionOptions) []SubPeerScore { var peers []SubPeerScore l.RLock() for _, ps := range l.peerHeap.peerScores { peers = append(peers, SubPeerScore{ HostPort: ps.Peer.hostPort, Score: ps.score, }) } l.RUnlock() return peers }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L5396-L5398
func (api *API) MultiCloudImageLocator(href string) *MultiCloudImageLocator { return &MultiCloudImageLocator{Href(href), api} }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/log/field.go#L90-L96
func Uint32(key string, val uint32) Field { return Field{ key: key, fieldType: uint32Type, numericVal: int64(val), } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L1344-L1348
func (v SetStyleTextsReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss11(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cmd/ask.go#L120-L124
func askQuestion(question, defaultAnswer string) string { fmt.Printf(question) return readAnswer(defaultAnswer) }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/fbuf.go#L130-L144
func (b *Float64RingBuf) WriteAndMaybeOverwriteOldestData(p []float64) (n int, err error) { writeCapacity := b.N - b.Readable if len(p) > writeCapacity { b.Advance(len(p) - writeCapacity) } startPos := 0 if len(p) > b.N { startPos = len(p) - b.N } n, err = b.Write(p[startPos:]) if err != nil { return n, err } return len(p), nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_networks.go#L36-L50
func (r *ProtocolLXD) GetNetworks() ([]api.Network, error) { if !r.HasExtension("network") { return nil, fmt.Errorf("The server is missing the required \"network\" API extension") } networks := []api.Network{} // Fetch the raw value _, err := r.queryStruct("GET", "/networks?recursion=1", nil, "", &networks) if err != nil { return nil, err } return networks, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/gw/rpc.pb.gw.go#L1452-L1454
func RegisterMaintenanceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterMaintenanceHandlerClient(ctx, mux, etcdserverpb.NewMaintenanceClient(conn)) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/team_token.go#L48-L74
func tokenInfo(w http.ResponseWriter, r *http.Request, t auth.Token) error { tokenID := r.URL.Query().Get(":token_id") if tokenID == "" { w.WriteHeader(http.StatusBadRequest) return nil } teamToken, err := servicemanager.TeamToken.Info(tokenID, t) if err == authTypes.ErrTeamTokenNotFound { return &errors.HTTP{ Code: http.StatusNotFound, Message: err.Error(), } } if err != nil { return err } allowed := permission.Check(t, permission.PermTeamTokenRead, permission.Context(permTypes.CtxTeam, teamToken.Team), ) if !allowed { return permission.ErrUnauthorized } w.Header().Set("Content-Type", "application/json") return json.NewEncoder(w).Encode(teamToken) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L138-L155
func (r *ProtocolLXD) GetStoragePoolVolumeSnapshots(pool string, volumeType string, volumeName string) ([]api.StorageVolumeSnapshot, error) { if !r.HasExtension("storage_api_volume_snapshots") { return nil, fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } snapshots := []api.StorageVolumeSnapshot{} path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s/snapshots?recursion=1", url.QueryEscape(pool), url.QueryEscape(volumeType), url.QueryEscape(volumeName)) _, err := r.queryStruct("GET", path, nil, "", &snapshots) if err != nil { return nil, err } return snapshots, nil }
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/security/controller.go#L160-L189
func (c *OAuth2Controller) Authorize(w http.ResponseWriter, r *http.Request) { clientID := r.URL.Query().Get("client_id") responsetype := r.URL.Query().Get("response_type") redirectURI := r.URL.Query().Get("redirect_uri") userID := r.URL.Query().Get("user_id") if len(redirectURI) == 0 { app, _ := c.ApplicationManager.GetByClientID(clientID) redirectURI = app.Callback } if len(redirectURI) == 0 { log.Print("Pas de paramètre redirect_uri") // return an error code ? } else { if strings.Compare(responsetype, "code") == 0 { code, err := EncodeOAuth2Code(clientID, redirectURI, userID, c.cnf.Jwt.Key) if err != nil { log.Printf("Error: %v", err) } data := map[string]string{ "redirectURI": redirectURI, "code": code, } js, _ := json.Marshal(data) w.Write(js) } else { log.Print("Pas de paramètre code") //return a Token } } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/trigger/trigger.go#L156-L186
func TrustedUser(ghc trustedUserClient, trigger plugins.Trigger, user, org, repo string) (bool, error) { // First check if user is a collaborator, assuming this is allowed if !trigger.OnlyOrgMembers { if ok, err := ghc.IsCollaborator(org, repo, user); err != nil { return false, fmt.Errorf("error in IsCollaborator: %v", err) } else if ok { return true, nil } } // TODO(fejta): consider dropping support for org checks in the future. // Next see if the user is an org member if member, err := ghc.IsMember(org, user); err != nil { return false, fmt.Errorf("error in IsMember(%s): %v", org, err) } else if member { return true, nil } // Determine if there is a second org to check if trigger.TrustedOrg == "" || trigger.TrustedOrg == org { return false, nil // No trusted org and/or it is the same } // Check the second trusted org. member, err := ghc.IsMember(trigger.TrustedOrg, user) if err != nil { return false, fmt.Errorf("error in IsMember(%s): %v", trigger.TrustedOrg, err) } return member, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/audits/easyjson.go#L106-L110
func (v *GetEncodedResponseReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoAudits(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_cluster.go#L27-L44
func (r *ProtocolLXD) UpdateCluster(cluster api.ClusterPut, ETag string) (Operation, error) { if !r.HasExtension("clustering") { return nil, fmt.Errorf("The server is missing the required \"clustering\" API extension") } if cluster.ServerAddress != "" || cluster.ClusterPassword != "" || len(cluster.MemberConfig) > 0 { if !r.HasExtension("clustering_join") { return nil, fmt.Errorf("The server is missing the required \"clustering_join\" API extension") } } op, _, err := r.queryOperation("PUT", "/cluster", cluster, "") if err != nil { return nil, err } return op, nil }
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/router.go#L61-L70
func NewRouters() *Routers { return &Routers{ s: make(map[string]struct { r router.Router v view.View h HandlerFunc }), l: list.New(), } }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fileinfo.go#L111-L148
func (g tagGroup) check(c *config.Config, os, arch string) bool { goConf := getGoConfig(c) for _, t := range g { if strings.HasPrefix(t, "!!") { // bad syntax, reject always return false } not := strings.HasPrefix(t, "!") if not { t = t[1:] } if isIgnoredTag(t) { // Release tags are treated as "unknown" and are considered true, // whether or not they are negated. continue } var match bool if _, ok := rule.KnownOSSet[t]; ok { if os == "" { return false } match = os == t } else if _, ok := rule.KnownArchSet[t]; ok { if arch == "" { return false } match = arch == t } else { match = goConf.genericTags[t] } if not { match = !match } if !match { return false } } return true }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L42-L49
func NewPage(url string, options ...Option) (*Page, error) { pageOptions := config{}.Merge(options) session, err := api.OpenWithClient(url, pageOptions.Capabilities(), pageOptions.HTTPClient) if err != nil { return nil, fmt.Errorf("failed to connect to WebDriver: %s", err) } return newPage(session), nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L495-L499
func Flush(c context.Context) error { req := &pb.MemcacheFlushRequest{} res := &pb.MemcacheFlushResponse{} return internal.Call(c, "memcache", "FlushAll", req, res) }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/http.go#L53-L60
func HTTPStatusCode(err error) int { e, ok := err.(Error) if ok { return e.Type().HTTPStatusCode() } return http.StatusInternalServerError }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/frame.go#L155-L162
func (f *Frame) ReadIn(r io.Reader) error { header := make([]byte, FrameHeaderSize) if _, err := io.ReadFull(r, header); err != nil { return err } return f.ReadBody(header, r) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L318-L324
func (c *Client) measure(method, path string, code int, start time.Time) { if c.metrics == nil { return } c.metrics.RequestLatency.WithLabelValues(method, path).Observe(time.Since(start).Seconds()) c.metrics.Requests.WithLabelValues(method, path, fmt.Sprintf("%d", code)).Inc() }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssd/codegen_client.go#L75-L77
func (r *Schedule) Locator(api *API) *ScheduleLocator { return api.ScheduleLocator(r.Href) }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/mm/malloc.go#L78-L85
func FreeOSMemory() error { errCode := int(C.mm_free2os()) if errCode != 0 { return fmt.Errorf("status: %d", errCode) } return nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/oci.go#L77-L91
func (m *OCI1) UpdateLayerInfos(layerInfos []types.BlobInfo) error { if len(m.Layers) != len(layerInfos) { return errors.Errorf("Error preparing updated manifest: layer count changed from %d to %d", len(m.Layers), len(layerInfos)) } original := m.Layers m.Layers = make([]imgspecv1.Descriptor, len(layerInfos)) for i, info := range layerInfos { m.Layers[i].MediaType = original[i].MediaType m.Layers[i].Digest = info.Digest m.Layers[i].Size = info.Size m.Layers[i].Annotations = info.Annotations m.Layers[i].URLs = info.URLs } return nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/account_id.go#L29-L42
func (aid *AccountId) Equals(other AccountId) bool { if aid.Type != other.Type { return false } switch aid.Type { case CryptoKeyTypeKeyTypeEd25519: l := aid.MustEd25519() r := other.MustEd25519() return l == r default: panic(fmt.Errorf("Unknown account id type: %v", aid.Type)) } }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/apps_wrapper.go#L34-L51
func (m *AppsWrapper) Validate(formats strfmt.Registry) error { var res []error if err := m.validateApps(formats); err != nil { // prop res = append(res, err) } if err := m.validateError(formats); err != nil { // prop res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3480-L3483
func (e AccountMergeResultCode) ValidEnum(v int32) bool { _, ok := accountMergeResultCodeMap[v] return ok }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util.go#L599-L612
func DeepCopy(src, dest interface{}) error { buff := new(bytes.Buffer) enc := gob.NewEncoder(buff) dec := gob.NewDecoder(buff) if err := enc.Encode(src); err != nil { return err } if err := dec.Decode(dest); err != nil { return err } return nil }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/js.go#L9-L12
func JavaScript(names ...string) Renderer { e := New(Options{}) return e.JavaScript(names...) }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L691-L698
func SubtractWithMask(src1, src2, dst, mask *IplImage) { C.cvSub( unsafe.Pointer(src1), unsafe.Pointer(src2), unsafe.Pointer(dst), unsafe.Pointer(mask), ) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L1810-L1814
func (v *DeleteDatabaseParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb16(&r, v) return r.Error() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6106-L6125
func NewPeerAddressIp(aType IpAddrType, value interface{}) (result PeerAddressIp, err error) { result.Type = aType switch IpAddrType(aType) { case IpAddrTypeIPv4: tv, ok := value.([4]byte) if !ok { err = fmt.Errorf("invalid value, must be [4]byte") return } result.Ipv4 = &tv case IpAddrTypeIPv6: tv, ok := value.([16]byte) if !ok { err = fmt.Errorf("invalid value, must be [16]byte") return } result.Ipv6 = &tv } return }
https://github.com/abh/geoip/blob/07cea4480daa3f28edd2856f2a0490fbe83842eb/geoip.go#L258-L275
func GetRegionName(countryCode, regionCode string) string { cc := C.CString(countryCode) defer C.free(unsafe.Pointer(cc)) rc := C.CString(regionCode) defer C.free(unsafe.Pointer(rc)) region := C.GeoIP_region_name_by_code(cc, rc) if region == nil { return "" } // it's a static string constant, don't free this regionName := C.GoString(region) return regionName }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/log/types.go#L145-L159
func (t *Level) UnmarshalEasyJSON(in *jlexer.Lexer) { switch Level(in.String()) { case LevelVerbose: *t = LevelVerbose case LevelInfo: *t = LevelInfo case LevelWarning: *t = LevelWarning case LevelError: *t = LevelError default: in.AddError(errors.New("unknown Level value")) } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/fileutil/fileutil.go#L48-L58
func TouchDirAll(dir string) error { // If path is already a directory, MkdirAll does nothing // and returns nil. err := os.MkdirAll(dir, PrivateDirMode) if err != nil { // if mkdirAll("a/text") and "text" is not // a directory, this will return syscall.ENOTDIR return err } return IsDirWriteable(dir) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L400-L403
func (p SetGeolocationOverrideParams) WithAccuracy(accuracy float64) *SetGeolocationOverrideParams { p.Accuracy = accuracy return &p }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/server.go#L223-L240
func (s *Server) Handle(ctx context.Context, call *tchannel.InboundCall) { op := call.MethodString() service, method, ok := getServiceMethod(op) if !ok { log.Fatalf("Handle got call for %s which does not match the expected call format", op) } s.RLock() handler, ok := s.handlers[service] s.RUnlock() if !ok { log.Fatalf("Handle got call for service %v which is not registered", service) } if err := s.handle(ctx, handler, method, call); err != nil { s.onError(call, err) } }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L492-L521
func QueueStats(c context.Context, queueNames []string) ([]QueueStatistics, error) { req := &pb.TaskQueueFetchQueueStatsRequest{ QueueName: make([][]byte, len(queueNames)), } for i, q := range queueNames { if q == "" { q = "default" } req.QueueName[i] = []byte(q) } res := &pb.TaskQueueFetchQueueStatsResponse{} if err := internal.Call(c, "taskqueue", "FetchQueueStats", req, res); err != nil { return nil, err } qs := make([]QueueStatistics, len(res.Queuestats)) for i, qsg := range res.Queuestats { qs[i] = QueueStatistics{ Tasks: int(*qsg.NumTasks), } if eta := *qsg.OldestEtaUsec; eta > -1 { qs[i].OldestETA = time.Unix(0, eta*1e3) } if si := qsg.ScannerInfo; si != nil { qs[i].Executed1Minute = int(*si.ExecutedLastMinute) qs[i].InFlight = int(si.GetRequestsInFlight()) qs[i].EnforcedRate = si.GetEnforcedRate() } } return qs, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/info.go#L18-L23
func info(w http.ResponseWriter, r *http.Request) error { data := map[string]string{} data["version"] = Version w.Header().Set("Content-Type", "application/json") return json.NewEncoder(w).Encode(data) }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L339-L349
func txPrint(st *State) { arg := st.sa if arg == nil { st.Warnf("Use of nil to print\n") } else if reflect.ValueOf(st.sa).Type() != rawStringType { st.AppendOutputString(html.EscapeString(interfaceToString(arg))) } else { st.AppendOutputString(interfaceToString(arg)) } st.Advance() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd.go#L110-L115
func (r *ProtocolLXD) RawQuery(method string, path string, data interface{}, ETag string) (*api.Response, string, error) { // Generate the URL url := fmt.Sprintf("%s%s", r.httpHost, path) return r.rawQuery(method, url, data, ETag) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L621-L630
func (p *QueryObjectsParams) Do(ctx context.Context) (objects *RemoteObject, err error) { // execute var res QueryObjectsReturns err = cdp.Execute(ctx, CommandQueryObjects, p, &res) if err != nil { return nil, err } return res.Objects, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/log/easyjson.go#L95-L99
func (v *ViolationSetting) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoLog(&r, v) return r.Error() }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/object.go#L164-L179
func (p *Process) FindObject(a core.Address) (Object, int64) { // Round down to the start of an object. h := p.findHeapInfo(a) if h == nil { // Not in Go heap, or in a span // that doesn't hold Go objects (freed, stacks, ...) return 0, 0 } x := h.base.Add(a.Sub(h.base) / h.size * h.size) // Check if object is marked. h = p.findHeapInfo(x) if h.mark>>(uint64(x)%heapInfoSize/8)&1 == 0 { // free or garbage return 0, 0 } return Object(x), a.Sub(x) }
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/web/web.go#L33-L52
func ContextWithCookieSecret(secret string) martini.Handler { return func(w http.ResponseWriter, req *http.Request, mc martini.Context) { ctx := &Context{req, map[string]string{}, secret, w} //set some default headers tm := time.Now().UTC() //ignore errors from ParseForm because it's usually harmless. req.ParseForm() if len(req.Form) > 0 { for k, v := range req.Form { ctx.Params[k] = v[0] } } ctx.SetHeader("Date", webTime(tm), true) //Set the default content-type ctx.SetHeader("Content-Type", "text/html; charset=utf-8", true) // set martini context for web.Context mc.Map(ctx) } }
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L246-L255
func (pool *Pool) Wait() { working_pipe := make(chan bool) for { pool.working_wanted_pipe <- working_pipe if !<-working_pipe { break } time.Sleep(pool.interval * time.Millisecond) } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/netutil/isolate_linux.go#L23-L31
func DropPort(port int) error { cmdStr := fmt.Sprintf("sudo iptables -A OUTPUT -p tcp --destination-port %d -j DROP", port) if _, err := exec.Command("/bin/sh", "-c", cmdStr).Output(); err != nil { return err } cmdStr = fmt.Sprintf("sudo iptables -A INPUT -p tcp --destination-port %d -j DROP", port) _, err := exec.Command("/bin/sh", "-c", cmdStr).Output() return err }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L87-L96
func (peers *Peers) OnGC(callback func(*Peer)) { peers.Lock() defer peers.Unlock() // Although the array underlying peers.onGC might be accessed // without holding the lock in unlockAndNotify, we don't // support removing callbacks, so a simple append here is // safe. peers.onGC = append(peers.onGC, callback) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L877-L879
func (c *putFileClient) PutFile(repoName string, commitID string, path string, reader io.Reader) (_ int, retErr error) { return c.PutFileSplit(repoName, commitID, path, pfs.Delimiter_NONE, 0, 0, 0, false, reader) }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tchooks/types.go#L614-L617
func (this *TriggerHookResponse) MarshalJSON() ([]byte, error) { x := json.RawMessage(*this) return (&x).MarshalJSON() }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/gocv/gocv_calib3d.go#L81-L88
func GcvRodrigues(src *mat64.Dense) (dst *mat64.Dense) { gcvSrc := Mat64ToGcvMat(src) gcvDst := NewGcvMat() GcvRodrigues_(gcvSrc, gcvDst) dst = GcvMatToMat64(gcvDst) return dst }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage.go#L601-L603
func getSnapshotMountPoint(project, poolName string, snapshotName string) string { return shared.VarPath("storage-pools", poolName, "containers-snapshots", projectPrefix(project, snapshotName)) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/lenses/lenses.go#L130-L133
func LastNLines(a Artifact, n int64) ([]string, error) { // 300B, a reasonable log line length, probably a bit more scalable than a hard-coded value return LastNLinesChunked(a, n, 300*n+1) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/parse.go#L18-L31
func Packages() (map[string]*ast.Package, error) { packages := map[string]*ast.Package{} for _, name := range defaultPackages { pkg, err := lex.Parse(name) if err != nil { return nil, errors.Wrapf(err, "Parse %q", name) } parts := strings.Split(name, "/") packages[parts[len(parts)-1]] = pkg } return packages, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L760-L764
func (v GetTargetsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget7(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L385-L388
func (p EvaluateParams) WithTimeout(timeout TimeDelta) *EvaluateParams { p.Timeout = timeout return &p }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/worker/simple.go#L61-L65
func (w *Simple) Start(ctx context.Context) error { w.Logger.Info("Starting Simple Background Worker") w.ctx, w.cancel = context.WithCancel(ctx) return nil }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/ipblock.go#L72-L77
func (c *Client) ReleaseIPBlock(ipblockid string) (*http.Header, error) { url := ipblockPath(ipblockid) ret := &http.Header{} err := c.client.Delete(url, ret, http.StatusAccepted) return ret, err }
https://github.com/jasoncapehart/go-sgd/blob/a7e66bc0f279ada654e9a927ba1347ee8510585d/sgd.go#L86-L95
func LinearLoss(x, θ []float64, y, σ float64) float64 { // log((1/(2*pi*sigma**2))**0.5*exp(-1/(2*σ**2)*(y-w*x)**2)) σ2 := math.Pow(σ, 2) z := math.Pow(1.0/(2*math.Pi*σ2), 0.5) yest := 0.0 for i, xi := range x { yest += θ[i] * xi } return -math.Log(z * math.Exp(-1/(2*σ2)*math.Pow((y-yest), 2))) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/audits/types.go#L31-L33
func (t GetEncodedResponseEncoding) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/migrate_container.go#L230-L315
func (s *migrationSourceWs) preDumpLoop(args *preDumpLoopArgs) (bool, error) { // Do a CRIU pre-dump criuMigrationArgs := CriuMigrationArgs{ cmd: lxc.MIGRATE_PRE_DUMP, stop: false, actionScript: false, preDumpDir: args.preDumpDir, dumpDir: args.dumpDir, stateDir: args.checkpointDir, function: "migration", } logger.Debugf("Doing another pre-dump in %s", args.preDumpDir) final := args.final err := s.container.Migrate(&criuMigrationArgs) if err != nil { return final, err } // Send the pre-dump. ctName, _, _ := containerGetParentAndSnapshotName(s.container.Name()) state := s.container.DaemonState() err = RsyncSend(ctName, shared.AddSlash(args.checkpointDir), s.criuConn, nil, args.rsyncFeatures, args.bwlimit, state.OS.ExecPath) if err != nil { return final, err } // Read the CRIU's 'stats-dump' file dumpPath := shared.AddSlash(args.checkpointDir) dumpPath += shared.AddSlash(args.dumpDir) written, skipped_parent, err := readCriuStatsDump(dumpPath) if err != nil { return final, err } logger.Debugf("CRIU pages written %d", written) logger.Debugf("CRIU pages skipped %d", skipped_parent) total_pages := written + skipped_parent percentage_skipped := int(100 - ((100 * written) / total_pages)) logger.Debugf("CRIU pages skipped percentage %d%%", percentage_skipped) // threshold is the percentage of memory pages that needs // to be pre-copied for the pre-copy migration to stop. var threshold int tmp := s.container.ExpandedConfig()["migration.incremental.memory.goal"] if tmp != "" { threshold, _ = strconv.Atoi(tmp) } else { // defaults to 70% threshold = 70 } if percentage_skipped > threshold { logger.Debugf("Memory pages skipped (%d%%) due to pre-copy is larger than threshold (%d%%)", percentage_skipped, threshold) logger.Debugf("This was the last pre-dump; next dump is the final dump") final = true } // If in pre-dump mode, the receiving side // expects a message to know if this was the // last pre-dump logger.Debugf("Sending another header") sync := migration.MigrationSync{ FinalPreDump: proto.Bool(final), } data, err := proto.Marshal(&sync) if err != nil { return final, err } err = s.criuConn.WriteMessage(websocket.BinaryMessage, data) if err != nil { s.sendControl(err) return final, err } logger.Debugf("Sending another header done") return final, nil }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/connection_maker.go#L132-L139
func (cm *connectionMaker) ForgetConnections(peers []string) { cm.actionChan <- func() bool { for _, peer := range peers { delete(cm.directPeers, peer) } return true } }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/routes.go#L82-L84
func (r *routes) Broadcast(name PeerName) []PeerName { return r.lookupOrCalculate(name, &r.broadcast, true) }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L113-L122
func (p MailBuilder) Header(name, value string) MailBuilder { // Copy existing header map h := textproto.MIMEHeader{} for k, v := range p.header { h[k] = v } h.Add(name, value) p.header = h return p }
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/snowballword/snowballword.go#L42-L63
func (w *SnowballWord) ReplaceSuffix(suffix, replacement string, force bool) bool { var ( doReplacement bool suffixRunes []rune ) if force { doReplacement = true suffixRunes = []rune(suffix) } else { var foundSuffix string foundSuffix, suffixRunes = w.FirstSuffix(suffix) if foundSuffix == suffix { doReplacement = true } } if doReplacement == false { return false } w.ReplaceSuffixRunes(suffixRunes, []rune(replacement), true) return true }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L1361-L1365
func (v *SetCPUThrottlingRateParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoEmulation14(&r, v) return r.Error() }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/etcd_store.go#L94-L111
func (s *etcdStore) Range(ctx context.Context, req *etcdserverpb.RangeRequest) (*etcdserverpb.RangeResponse, error) { ireq := etcdserverpb.InternalRaftRequest{ID: <-s.idgen, Range: req} msgc, errc, err := s.proposeInternalRaftRequest(ireq) if err != nil { return nil, err } select { case <-ctx.Done(): s.cancelInternalRaftRequest(ireq) return nil, ctx.Err() case msg := <-msgc: return msg.(*etcdserverpb.RangeResponse), nil case err := <-errc: return nil, err case <-s.quitc: return nil, errStopped } }
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/EvaluableExpression.go#L54-L84
func NewEvaluableExpressionFromTokens(tokens []ExpressionToken) (*EvaluableExpression, error) { var ret *EvaluableExpression var err error ret = new(EvaluableExpression) ret.QueryDateFormat = isoDateFormat err = checkBalance(tokens) if err != nil { return nil, err } err = checkExpressionSyntax(tokens) if err != nil { return nil, err } ret.tokens, err = optimizeTokens(tokens) if err != nil { return nil, err } ret.evaluationStages, err = planStages(ret.tokens) if err != nil { return nil, err } ret.ChecksTypes = true return ret, nil }
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/binding/binding.go#L332-L334
func (self Errors) Count() int { return len(self.Overall) + len(self.Fields) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L610-L614
func (v SkipWaitingParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoServiceworker6(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L33-L49
func VerifyRequest(method string, path interface{}, rawQuery ...string) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { Expect(req.Method).Should(Equal(method), "Method mismatch") switch p := path.(type) { case types.GomegaMatcher: Expect(req.URL.Path).Should(p, "Path mismatch") default: Expect(req.URL.Path).Should(Equal(path), "Path mismatch") } if len(rawQuery) > 0 { values, err := url.ParseQuery(rawQuery[0]) Expect(err).ShouldNot(HaveOccurred(), "Expected RawQuery is malformed") Expect(req.URL.Query()).Should(Equal(values), "RawQuery mismatch") } } }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/watermark.go#L84-L87
func (w *WaterMark) BeginMany(indices []uint64) { atomic.StoreUint64(&w.lastIndex, indices[len(indices)-1]) w.markCh <- mark{index: 0, indices: indices, done: false} }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/socket/socket_vm.go#L32-L38
func DialTimeout(ctx context.Context, protocol, addr string, timeout time.Duration) (*Conn, error) { conn, err := net.DialTimeout(protocol, addr, timeout) if err != nil { return nil, err } return &Conn{conn}, nil }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/mnemosyned/service.go#L33-L54
func initJaeger(service, node, agentAddress string, log *zap.Logger) (opentracing.Tracer, io.Closer, error) { cfg := &config.Configuration{ Sampler: &config.SamplerConfig{ Type: "const", Param: 1, }, Tags: []opentracing.Tag{{ Key: constant.Subsystem + ".listen", Value: node, }}, Reporter: &config.ReporterConfig{ LogSpans: true, LocalAgentHostPort: agentAddress, }, } tracer, closer, err := cfg.New(service, config.Logger(zapjaeger.NewLogger(log))) if err != nil { return nil, nil, err } return tracer, closer, nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L92-L99
func protoToItem(p *pb.MemcacheGetResponse_Item) *Item { return &Item{ Key: string(p.Key), Value: p.Value, Flags: p.GetFlags(), casID: p.GetCasId(), } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L261-L268
func NewFakeClient(deckURL string) *Client { return &Client{ namespace: "default", deckURL: deckURL, client: &http.Client{}, fake: true, } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/server_access_control.go#L53-L65
func (ac *AccessController) IsHostWhitelisted(host string) bool { ac.hostWhitelistMu.RLock() defer ac.hostWhitelistMu.RUnlock() if len(ac.HostWhitelist) == 0 { // allow all return true } _, ok := ac.HostWhitelist["*"] if ok { return true } _, ok = ac.HostWhitelist[host] return ok }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L147-L149
func (db *DB) Limit(lim int) *Condition { return newCondition(db).Limit(lim) }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/dialect.go#L251-L291
func (d *PostgresDialect) SQLType(v interface{}, autoIncrement bool, size uint64) (name string, allowNull bool) { switch v.(type) { case bool: return "boolean", false case *bool, sql.NullBool: return "boolean", true case int8, int16, uint8, uint16: return d.smallint(autoIncrement), false case *int8, *int16, *uint8, *uint16: return d.smallint(autoIncrement), true case int, int32, uint, uint32: return d.integer(autoIncrement), false case *int, *int32, *uint, *uint32: return d.integer(autoIncrement), true case int64, uint64: return d.bigint(autoIncrement), false case *int64, *uint64, sql.NullInt64: return d.bigint(autoIncrement), true case string: return d.varchar(size), false case *string, sql.NullString: return d.varchar(size), true case []byte: return "bytea", true case time.Time: return "timestamp with time zone", false case *time.Time: return "timestamp with time zone", true case Rat: return fmt.Sprintf("numeric(%d, %d)", decimalPrecision, decimalScale), false case *Rat: return fmt.Sprintf("numeric(%d, %d)", decimalPrecision, decimalScale), true case Float32, Float64: return "double precision", false case *Float32, *Float64: return "double precision", true case float32, *float32, float64, *float64, sql.NullFloat64: panic(ErrUsingFloatType) } panic(fmt.Errorf("PostgresDialect: unsupported SQL type: %T", v)) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/branch_protection.go#L184-L192
func (o Org) GetRepo(name string) *Repo { r, ok := o.Repos[name] if ok { r.Policy = o.Apply(r.Policy) } else { r.Policy = o.Policy } return &r }