_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/identity.go#L39-L55
|
func ModuleHostname(c context.Context, module, version, instance string) (string, error) {
req := &modpb.GetHostnameRequest{}
if module != "" {
req.Module = &module
}
if version != "" {
req.Version = &version
}
if instance != "" {
req.Instance = &instance
}
res := &modpb.GetHostnameResponse{}
if err := internal.Call(c, "modules", "GetHostname", req, res); err != nil {
return "", err
}
return *res.Hostname, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L135-L151
|
func (e *Endpoints) NetworkUpdateCert(cert *shared.CertInfo) {
e.mu.Lock()
defer e.mu.Unlock()
e.cert = cert
listener, ok := e.listeners[network]
if !ok {
return
}
listener.(*networkListener).Config(cert)
// Update the cluster listener too, if enabled.
listener, ok = e.listeners[cluster]
if !ok {
return
}
listener.(*networkListener).Config(cert)
}
|
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/memory.go#L214-L222
|
func (b *ChannelMemoryBackend) Stop() {
b.mu.Lock()
if b.running == true {
b.running = false
b.events <- eventStop
}
b.mu.Unlock()
b.stopWg.Wait()
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/api.go#L284-L296
|
func (api *TelegramBotAPI) GetFile(fileID string) (*FileResponse, error) {
resp := &FileResponse{}
_, err := api.c.getQuerystring(getFile, resp, map[string]string{"file_id": fileID})
if err != nil {
return nil, err
}
err = check(&resp.baseResponse)
if err != nil {
return nil, err
}
return resp, nil
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpclog/grpc.go#L78-L92
|
func UnaryClientInterceptor(log ttnlog.Interface) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (err error) {
log := getLog(log).WithField("method", method)
log = log.WithFields(FieldsFromOutgoingContext(ctx))
start := time.Now()
err = invoker(ctx, method, req, reply, cc, opts...)
log = log.WithField("duration", time.Since(start))
if err != nil {
log.WithError(err).Debug("rpc-client: call failed")
return
}
log.Debug("rpc-client: call done")
return
}
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/local_peer.go#L81-L100
|
func (peer *localPeer) createConnection(localAddr string, peerAddr string, acceptNewPeer bool, logger Logger) error {
if err := peer.checkConnectionLimit(); err != nil {
return err
}
localTCPAddr, err := net.ResolveTCPAddr("tcp", localAddr)
if err != nil {
return err
}
remoteTCPAddr, err := net.ResolveTCPAddr("tcp", peerAddr)
if err != nil {
return err
}
tcpConn, err := net.DialTCP("tcp", localTCPAddr, remoteTCPAddr)
if err != nil {
return err
}
connRemote := newRemoteConnection(peer.Peer, nil, peerAddr, true, false)
startLocalConnection(connRemote, tcpConn, peer.router, acceptNewPeer, logger)
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/rsssh/main.go#L139-L145
|
func buildAliases(sshConfig []SSHConfig, sshOptions, sshUser string) string {
var aliases string
for _, conf := range sshConfig {
aliases = aliases + fmt.Sprintf("alias %v='ssh %v %v@%v'\n", conf.Name, sshOptions, sshUser, conf.IPAddress)
}
return aliases
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/errorutil/aggregate.go#L37-L52
|
func NewAggregate(errlist ...error) Aggregate {
if len(errlist) == 0 {
return nil
}
// In case of input error list contains nil
var errs []error
for _, e := range errlist {
if e != nil {
errs = append(errs, e)
}
}
if len(errs) == 0 {
return nil
}
return aggregate(errs)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/ranch/storage.go#L103-L119
|
func (s *Storage) GetResources() ([]common.Resource, error) {
var resources []common.Resource
items, err := s.resources.List()
if err != nil {
return resources, err
}
for _, i := range items {
var res common.Resource
res, err = common.ItemToResource(i)
if err != nil {
return nil, err
}
resources = append(resources, res)
}
sort.Stable(common.ResourceByUpdateTime(resources))
return resources, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/informers/externalversions/factory.go#L39-L41
|
func NewSharedInformerFactory(client versioned.Interface, defaultResync time.Duration) SharedInformerFactory {
return NewFilteredSharedInformerFactory(client, defaultResync, v1.NamespaceAll, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/easyjson.go#L521-L525
|
func (v RequestMemoryDumpParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoTracing3(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/parse.go#L237-L253
|
func (p *Parser) Parse(args []string) error {
// If -h or --help were specified then print usage
for _, arg := range args {
if arg == "-h" || arg == "--help" {
return ErrHelp
}
if arg == "--version" {
return ErrVersion
}
if arg == "--" {
break
}
}
// Process all command line arguments
return process(p.specs, args)
}
|
https://github.com/skyrings/skyring-common/blob/d1c0bb1cbd5ed8438be1385c85c4f494608cde1e/monitoring/graphitemanager/graphite_manager.go#L465-L485
|
func (tsdbm GraphiteManager) PushToDb(metrics map[string]map[string]string, hostName string, port int) error {
data := make([]graphite.Metric, 1)
for tableName, valueMap := range metrics {
for timestamp, value := range valueMap {
timeInt, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil {
return fmt.Errorf("Failed to parse timestamp %v of metric tableName %v.Error: %v", timestamp, tableName, err.Error())
}
data = append(data, graphite.Metric{Name: tableName, Value: value, Timestamp: timeInt})
}
}
Graphite, err := graphite.NewGraphite(hostName, port)
if err != nil {
return fmt.Errorf("%v", err)
}
Graphite.SendMetrics(data)
if err := Graphite.Disconnect(); err != nil {
logger.Get().Warning("Failed to disconnect the graphite conn.Error %v", err)
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L5883-L5887
|
func (v EventStyleSheetChanged) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss52(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L237-L243
|
func (ws writeSet) puts() []v3.Op {
puts := make([]v3.Op, 0, len(ws))
for _, v := range ws {
puts = append(puts, v.op)
}
return puts
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/english/common.go#L31-L49
|
func trimLeftApostrophes(word *snowballword.SnowballWord) {
var (
numApostrophes int
r rune
)
for numApostrophes, r = range word.RS {
// Check for "'", which is unicode code point 39
if r != 39 {
break
}
}
if numApostrophes > 0 {
word.RS = word.RS[numApostrophes:]
word.R1start = word.R1start - numApostrophes
word.R2start = word.R2start - numApostrophes
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/accessibility.go#L85-L88
|
func (p GetPartialAXTreeParams) WithObjectID(objectID runtime.RemoteObjectID) *GetPartialAXTreeParams {
p.ObjectID = objectID
return &p
}
|
https://github.com/alternaDev/go-avatar-gen/blob/b5ca997c0389dc8ce22e1a95087647aa4bb25b57/generator.go#L89-L101
|
func WriteImageToHTTP(w http.ResponseWriter, img image.Image) error {
buffer := new(bytes.Buffer)
if err := png.Encode(buffer, img); err != nil {
return err
}
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
if _, err := w.Write(buffer.Bytes()); err != nil {
return err
}
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L474-L476
|
func (api *API) LoginControlLocator(href string) *LoginControlLocator {
return &LoginControlLocator{Href(href), api}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L2175-L2179
|
func (v *ClearObjectStoreParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb19(&r, v)
return r.Error()
}
|
https://github.com/tylerb/gls/blob/e606233f194d6c314156dc6a35f21a42a470c6f6/gls.go#L106-L111
|
func unlinkGRs() {
childID := curGoroutineID()
dataLock.Lock()
delete(data, childID)
dataLock.Unlock()
}
|
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/ast.go#L3395-L3406
|
func Backtick(in string) string {
var buf bytes.Buffer
buf.WriteByte('`')
for _, c := range in {
buf.WriteRune(c)
if c == '`' {
buf.WriteByte('`')
}
}
buf.WriteByte('`')
return buf.String()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/fetcher.go#L140-L148
|
func (f *Fetcher) Fetch(db *gorm.DB) error {
if err := f.fetchRecentIssues(db); err != nil {
return err
}
if err := f.fetchRecentEventsAndComments(db); err != nil {
return err
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/systeminfo/easyjson.go#L265-L269
|
func (v GetProcessInfoParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoSysteminfo2(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/digitalocean/droplet/model.go#L37-L131
|
func (m *Model) Resources() map[int]cloud.Resource {
if len(m.cachedResources) > 0 {
return m.cachedResources
}
r := make(map[int]cloud.Resource)
i := 0
// ---- [SSH Key] ----
r[i] = &resources.SSH{
Shared: resources.Shared{
Name: m.known.Name,
},
}
i++
machineConfigs := m.known.MachineProviderConfigs()
for _, machineConfig := range machineConfigs {
serverPool := machineConfig.ServerPool
// ---- [Droplet] ----
r[i] = &resources.Droplet{
Shared: resources.Shared{
Name: serverPool.Name,
},
ServerPool: serverPool,
}
i++
}
for _, machineConfig := range machineConfigs {
serverPool := machineConfig.ServerPool
for _, firewall := range serverPool.Firewalls {
// ---- [Firewall] ----
f := &resources.Firewall{
Shared: resources.Shared{
Name: serverPool.Name,
CloudID: firewall.Identifier,
},
Tags: []string{serverPool.Name},
ServerPool: serverPool,
}
for _, rule := range firewall.IngressRules {
var src *resources.Sources
if _, _, err := net.ParseCIDR(rule.IngressSource); err == nil {
src = &resources.Sources{
Addresses: []string{rule.IngressSource},
}
} else if ip := net.ParseIP(rule.IngressSource); ip != nil {
src = &resources.Sources{
Addresses: []string{rule.IngressSource},
}
} else {
src = &resources.Sources{
Tags: []string{rule.IngressSource},
}
}
InboundRule := resources.InboundRule{
Protocol: rule.IngressProtocol,
PortRange: rule.IngressToPort,
Source: src,
}
f.InboundRules = append(f.InboundRules, InboundRule)
}
for _, rule := range firewall.EgressRules {
var dest *resources.Destinations
if _, _, err := net.ParseCIDR(rule.EgressDestination); err == nil {
dest = &resources.Destinations{
Addresses: []string{rule.EgressDestination},
}
} else if ip := net.ParseIP(rule.EgressDestination); ip != nil {
dest = &resources.Destinations{
Addresses: []string{rule.EgressDestination},
}
} else {
dest = &resources.Destinations{
Tags: []string{rule.EgressDestination},
}
}
OutboundRule := resources.OutboundRule{
Protocol: rule.EgressProtocol,
PortRange: rule.EgressToPort,
Destinations: dest,
}
f.OutboundRules = append(f.OutboundRules, OutboundRule)
}
r[i] = f
i++
}
}
m.cachedResources = r
return m.cachedResources
}
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/s3gof3r.go#L90-L95
|
func New(domain string, keys Keys) *S3 {
if domain == "" {
domain = DefaultDomain
}
return &S3{domain, keys}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L231-L236
|
func (h *dbHashTree) List(path string, f func(*NodeProto) error) error {
path = clean(path)
return h.View(func(tx *bolt.Tx) error {
return list(tx, path, f)
})
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/client.go#L232-L239
|
func (c *dummyClient) Update(obj Object) (Object, error) {
_, ok := c.objects[obj.GetName()]
if !ok {
return nil, fmt.Errorf("cannot find object %s", obj.GetName())
}
c.objects[obj.GetName()] = obj
return obj, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L61-L65
|
func (v WaitForDebuggerParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/inspector/easyjson.go#L57-L61
|
func (v EventTargetReloadedAfterCrash) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoInspector(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L235-L238
|
func (p SetDeviceMetricsOverrideParams) WithPositionX(positionX int64) *SetDeviceMetricsOverrideParams {
p.PositionX = positionX
return &p
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/http.go#L206-L252
|
func (client *Client) APICall(payload interface{}, method, route string, result interface{}, query url.Values) (interface{}, *CallSummary, error) {
rawPayload := []byte{}
var err error
if reflect.ValueOf(payload).IsValid() && !reflect.ValueOf(payload).IsNil() {
rawPayload, err = json.Marshal(payload)
if err != nil {
cs := &CallSummary{
HTTPRequestObject: payload,
}
return result,
cs,
&APICallException{
CallSummary: cs,
RootCause: err,
}
}
}
callSummary, err := client.Request(rawPayload, method, route, query)
callSummary.HTTPRequestObject = payload
if err != nil {
// If context failed during this request, then we should just return that error
if client.Context != nil && client.Context.Err() != nil {
return result, callSummary, client.Context.Err()
}
return result,
callSummary,
&APICallException{
CallSummary: callSummary,
RootCause: err,
}
}
// if result is passed in as nil, it means the API defines no response body
// json
if reflect.ValueOf(result).IsValid() && !reflect.ValueOf(result).IsNil() {
err = json.Unmarshal([]byte(callSummary.HTTPResponseBody), &result)
}
if err != nil {
return result,
callSummary,
&APICallException{
CallSummary: callSummary,
RootCause: err,
}
}
return result, callSummary, nil
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/types/pact_reification_request.go#L18-L32
|
func (m *PactReificationRequest) Validate() error {
m.Args = []string{}
body, err := json.Marshal(m.Message)
if err != nil {
return err
}
m.Args = append(m.Args, []string{
"reify",
string(body),
}...)
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/migration/wsproto.go#L59-L71
|
func ProtoSendControl(ws *websocket.Conn, err error) {
message := ""
if err != nil {
message = err.Error()
}
msg := MigrationControl{
Success: proto.Bool(err == nil),
Message: proto.String(message),
}
ProtoSend(ws, &msg)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.mapper.go#L661-L776
|
func (c *ClusterTx) ContainerDevicesRef(filter ContainerFilter) (map[string]map[string]map[string]map[string]string, error) {
// Result slice.
objects := make([]struct {
Project string
Name string
Device string
Type int
Key string
Value string
}, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Project != "" {
criteria["Project"] = filter.Project
}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
if filter.Parent != "" {
criteria["Parent"] = filter.Parent
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Project"] != nil && criteria["Name"] != nil {
stmt = c.stmt(containerDevicesRefByProjectAndName)
args = []interface{}{
filter.Project,
filter.Name,
}
} else if criteria["Project"] != nil && criteria["Node"] != nil {
stmt = c.stmt(containerDevicesRefByProjectAndNode)
args = []interface{}{
filter.Project,
filter.Node,
}
} else if criteria["Node"] != nil {
stmt = c.stmt(containerDevicesRefByNode)
args = []interface{}{
filter.Node,
}
} else if criteria["Project"] != nil {
stmt = c.stmt(containerDevicesRefByProject)
args = []interface{}{
filter.Project,
}
} else {
stmt = c.stmt(containerDevicesRef)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, struct {
Project string
Name string
Device string
Type int
Key string
Value string
}{})
return []interface{}{
&objects[i].Project,
&objects[i].Name,
&objects[i].Device,
&objects[i].Type,
&objects[i].Key,
&objects[i].Value,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch ref for containers")
}
// Build index by primary name.
index := map[string]map[string]map[string]map[string]string{}
for _, object := range objects {
_, ok := index[object.Project]
if !ok {
subIndex := map[string]map[string]map[string]string{}
index[object.Project] = subIndex
}
item, ok := index[object.Project][object.Name]
if !ok {
item = map[string]map[string]string{}
}
index[object.Project][object.Name] = item
config, ok := item[object.Device]
if !ok {
// First time we see this device, let's int the config
// and add the type.
deviceType, err := dbDeviceTypeToString(object.Type)
if err != nil {
return nil, errors.Wrapf(
err, "unexpected device type code '%d'", object.Type)
}
config = map[string]string{}
config["type"] = deviceType
item[object.Device] = config
}
if object.Key != "" {
config[object.Key] = object.Value
}
}
return index, nil
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/request.go#L52-L73
|
func (r *Request) BaseUrl() *url.URL {
scheme := r.URL.Scheme
if scheme == "" {
scheme = "http"
}
// HTTP sometimes gives the default scheme as HTTP even when used with TLS
// Check if TLS is not nil and given back https scheme
if scheme == "http" && r.TLS != nil {
scheme = "https"
}
host := r.Host
if len(host) > 0 && host[len(host)-1] == '/' {
host = host[:len(host)-1]
}
return &url.URL{
Scheme: scheme,
Host: host,
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/ls_command.go#L80-L90
|
func rPrint(c *cli.Context, n *client.Node) {
if n.Dir && c.Bool("p") {
fmt.Println(fmt.Sprintf("%v/", n.Key))
} else {
fmt.Println(n.Key)
}
for _, node := range n.Nodes {
rPrint(c, node)
}
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L485-L494
|
func (db *DB) Begin() error {
tx, err := db.db.Begin()
if err != nil {
return err
}
db.m.Lock()
defer db.m.Unlock()
db.tx = tx
return nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/hyperbahn/client.go#L175-L185
|
func (c *Client) Advertise(otherServices ...tchannel.Registrar) error {
c.getServiceNames(otherServices)
if err := c.initialAdvertise(); err != nil {
return err
}
c.opts.Handler.On(Advertised)
go c.advertiseLoop()
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L989-L993
|
func (v PictureTile) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoLayertree9(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/common/common.go#L171-L178
|
func (ud *UserData) UnmarshalJSON(data []byte) error {
tmpMap := UserDataMap{}
if err := json.Unmarshal(data, &tmpMap); err != nil {
return err
}
ud.FromMap(tmpMap)
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L865-L885
|
func (c *Cluster) ImageGetPoolNamesFromIDs(poolIDs []int64) ([]string, error) {
var poolName string
query := "SELECT name FROM storage_pools WHERE id=?"
poolNames := []string{}
for _, poolID := range poolIDs {
inargs := []interface{}{poolID}
outargs := []interface{}{poolName}
result, err := queryScan(c.db, query, inargs, outargs)
if err != nil {
return []string{}, err
}
for _, r := range result {
poolNames = append(poolNames, r[0].(string))
}
}
return poolNames, nil
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fileinfo.go#L463-L484
|
func expandSrcDir(str string, srcdir string) (string, bool) {
// "\" delimited paths cause safeCgoName to fail
// so convert native paths with a different delimiter
// to "/" before starting (eg: on windows).
srcdir = filepath.ToSlash(srcdir)
if srcdir == "" {
srcdir = "."
}
// Spaces are tolerated in ${SRCDIR}, but not anywhere else.
chunks := strings.Split(str, "${SRCDIR}")
if len(chunks) < 2 {
return str, safeCgoName(str, false)
}
ok := true
for _, chunk := range chunks {
ok = ok && (chunk == "" || safeCgoName(chunk, false))
}
ok = ok && (srcdir == "" || safeCgoName(srcdir, true))
res := strings.Join(chunks, srcdir)
return res, ok && res != ""
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/smtp/config.go#L68-L73
|
func GetSMTP(source interface{}, environment string) (smtp Config, err error) {
var smtpEnvironment SMTPEnvironment
i, err := config.Get(source, environment, &smtpEnvironment)
smtp = i.(Config)
return
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/raft.go#L415-L419
|
func (r *raftNode) advanceTicks(ticks int) {
for i := 0; i < ticks; i++ {
r.tick()
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1331-L1335
|
func (v *EventResetProfiles) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeapprofiler15(&r, v)
return r.Error()
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/geometry/geometry.go#L109-L136
|
func Arc(gc draw2d.GraphicContext, xc, yc, width, height float64) {
// draw an arc
xc += width / 2
yc += height / 2
radiusX, radiusY := width/2, height/2
startAngle := 45 * (math.Pi / 180.0) /* angles are specified */
angle := 135 * (math.Pi / 180.0) /* clockwise in radians */
gc.SetLineWidth(width / 10)
gc.SetLineCap(draw2d.ButtCap)
gc.SetStrokeColor(image.Black)
gc.MoveTo(xc+math.Cos(startAngle)*radiusX, yc+math.Sin(startAngle)*radiusY)
gc.ArcTo(xc, yc, radiusX, radiusY, startAngle, angle)
gc.Stroke()
// fill a circle
gc.SetStrokeColor(color.NRGBA{255, 0x33, 0x33, 0x80})
gc.SetFillColor(color.NRGBA{255, 0x33, 0x33, 0x80})
gc.SetLineWidth(width / 20)
gc.MoveTo(xc+math.Cos(startAngle)*radiusX, yc+math.Sin(startAngle)*radiusY)
gc.LineTo(xc, yc)
gc.LineTo(xc-radiusX, yc)
gc.Stroke()
gc.MoveTo(xc, yc)
gc.ArcTo(xc, yc, width/10.0, height/10.0, 0, 2*math.Pi)
gc.Fill()
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L177-L179
|
func (gc *GraphicContext) FillStringAt(text string, x, y float64) (cursor float64) {
return gc.CreateStringPath(text, x, y)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3rpc/watch.go#L572-L584
|
func FiltersFromRequest(creq *pb.WatchCreateRequest) []mvcc.FilterFunc {
filters := make([]mvcc.FilterFunc, 0, len(creq.Filters))
for _, ft := range creq.Filters {
switch ft {
case pb.WatchCreateRequest_NOPUT:
filters = append(filters, filterNoPut)
case pb.WatchCreateRequest_NODELETE:
filters = append(filters, filterNoDelete)
default:
}
}
return filters
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/animation.go#L222-L224
|
func (p *SetPausedParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetPaused, p, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1612-L1616
|
func (v *EventHeapStatsUpdate) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeapprofiler18(&r, v)
return r.Error()
}
|
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/sanitize.go#L33-L53
|
func isPathSafe(s string) error {
u, err := url.Parse(s)
if err != nil {
return err
}
e, err := url.PathUnescape(u.Path)
if err != nil {
return err
}
if strings.Contains(e, "..") {
return fmt.Errorf(errorMessage)
}
if !whitelistPattern.MatchString(e) {
return fmt.Errorf(errorMessage)
}
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/memory/memory.go#L125-L145
|
func (mem *cache) CandidateLocations(transport types.ImageTransport, scope types.BICTransportScope, primaryDigest digest.Digest, canSubstitute bool) []types.BICReplacementCandidate {
mem.mutex.Lock()
defer mem.mutex.Unlock()
res := []prioritize.CandidateWithTime{}
res = mem.appendReplacementCandidates(res, transport, scope, primaryDigest)
var uncompressedDigest digest.Digest // = ""
if canSubstitute {
if uncompressedDigest = mem.uncompressedDigestLocked(primaryDigest); uncompressedDigest != "" {
otherDigests := mem.digestsByUncompressed[uncompressedDigest] // nil if not present in the map
for d := range otherDigests {
if d != primaryDigest && d != uncompressedDigest {
res = mem.appendReplacementCandidates(res, transport, scope, d)
}
}
if uncompressedDigest != primaryDigest {
res = mem.appendReplacementCandidates(res, transport, scope, uncompressedDigest)
}
}
}
return prioritize.DestructivelyPrioritizeReplacementCandidates(res, primaryDigest, uncompressedDigest)
}
|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L423-L428
|
func (o *ListByteOption) Set(value string) error {
val := ByteOption{}
val.Set(value)
*o = append(*o, val)
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L1344-L1431
|
func getRBDMappedDevPath(clusterName string, poolName string, volumeType string,
volumeName string, doMap bool, userName string) (string, int) {
files, err := ioutil.ReadDir("/sys/devices/rbd")
if err != nil {
if os.IsNotExist(err) {
if doMap {
goto mapImage
}
return "", 0
}
return "", -1
}
for _, f := range files {
if !f.IsDir() {
continue
}
fName := f.Name()
idx, err := strconv.ParseUint(fName, 10, 64)
if err != nil {
continue
}
tmp := fmt.Sprintf("/sys/devices/rbd/%s/pool", fName)
contents, err := ioutil.ReadFile(tmp)
if err != nil {
if os.IsNotExist(err) {
continue
}
return "", -1
}
detectedPoolName := strings.TrimSpace(string(contents))
if detectedPoolName != poolName {
continue
}
tmp = fmt.Sprintf("/sys/devices/rbd/%s/name", fName)
contents, err = ioutil.ReadFile(tmp)
if err != nil {
if os.IsNotExist(err) {
continue
}
return "", -1
}
typedVolumeName := fmt.Sprintf("%s_%s", volumeType, volumeName)
detectedVolumeName := strings.TrimSpace(string(contents))
if detectedVolumeName != typedVolumeName {
continue
}
tmp = fmt.Sprintf("/sys/devices/rbd/%s/snap", fName)
contents, err = ioutil.ReadFile(tmp)
if err != nil {
if os.IsNotExist(err) {
return fmt.Sprintf("/dev/rbd%d", idx), 1
}
return "", -1
}
detectedSnapName := strings.TrimSpace(string(contents))
if detectedSnapName != "-" {
continue
}
return fmt.Sprintf("/dev/rbd%d", idx), 1
}
if !doMap {
return "", 0
}
mapImage:
devPath, err := cephRBDVolumeMap(clusterName, poolName,
volumeName, volumeType, userName)
if err != nil {
return "", -1
}
return strings.TrimSpace(devPath), 2
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L290-L299
|
func (s *FakeTaskManager) SaveTask(t *taskmanager.Task) (*taskmanager.Task, error) {
if s.ExpireEmitter != nil {
s.ExpireEmitter <- t.Expires
}
if s.SpyTaskSaved != nil {
*s.SpyTaskSaved = *t
}
return t, s.ReturnedErr
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/set_headers.go#L23-L30
|
func NewSetHeadersHandler(h http.Handler, headers map[string]string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for header, value := range headers {
w.Header().Set(header, value)
}
h.ServeHTTP(w, r)
})
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L786-L799
|
func defaultServerURLFor(config *restConfig) (*url.URL, error) {
// TODO: move the default to secure when the apiserver supports TLS by default
// config.Insecure is taken to mean "I want HTTPS but don't bother checking the certs against a CA."
hasCA := len(config.CAFile) != 0 || len(config.CAData) != 0
hasCert := len(config.CertFile) != 0 || len(config.CertData) != 0
defaultTLS := hasCA || hasCert || config.Insecure
host := config.Host
if host == "" {
host = "localhost"
}
// REMOVED: Configurable APIPath, GroupVersion
return defaultServerURL(host, defaultTLS)
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/decode.go#L43-L78
|
func (d Decoder) Decode(v interface{}) error {
to := reflect.ValueOf(v)
if d.off != 0 {
var err error
if d.off, err = 0, d.Parser.ParseMapValue(d.off-1); err != nil {
return err
}
}
if !to.IsValid() {
// This special case for a nil value is used to make it possible to
// discard decoded values.
_, err := d.decodeInterface(to)
return err
}
// Optimization for ValueDecoder, in practice tho it's also handled in the
// methods that are based on reflection.
switch x := v.(type) {
case ValueDecoder:
return x.DecodeValue(d)
}
if to.Kind() == reflect.Ptr {
// In most cases the method receives a pointer, but we may also have to
// support types that aren't pointers but implement ValueDecoder, or
// types that have got adapters set.
// If we're not in either of those cases the code will likely panic when
// the value is set because it won't be addressable.
to = to.Elem()
}
_, err := d.decode(to)
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L787-L791
|
func (v *KeyframesRule) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoAnimation7(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/easyjson.go#L685-L689
|
func (v *Event) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoBackgroundservice6(&r, v)
return r.Error()
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/modules.go#L210-L219
|
func findGoTool() string {
path := "go" // rely on PATH by default
if goroot, ok := os.LookupEnv("GOROOT"); ok {
path = filepath.Join(goroot, "bin", "go")
}
if runtime.GOOS == "windows" {
path += ".exe"
}
return path
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/respond.go#L63-L65
|
func FormatICResponse(ic github.IssueComment, s string) string {
return FormatResponseRaw(ic.Body, ic.HTMLURL, ic.User.Login, s)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L238-L247
|
func (p *CreateIsolatedWorldParams) Do(ctx context.Context) (executionContextID runtime.ExecutionContextID, err error) {
// execute
var res CreateIsolatedWorldReturns
err = cdp.Execute(ctx, CommandCreateIsolatedWorld, p, &res)
if err != nil {
return 0, err
}
return res.ExecutionContextID, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L83-L87
|
func (v *SetVirtualTimePolicyReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoEmulation(&r, v)
return r.Error()
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/mock_client.go#L50-L52
|
func (p *mockClient) StopServer(server *types.MockServer) (*types.MockServer, error) {
return p.StopServerResponse, p.StopServerError
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/cluster_util.go#L35-L49
|
func isMemberBootstrapped(lg *zap.Logger, cl *membership.RaftCluster, member string, rt http.RoundTripper, timeout time.Duration) bool {
rcl, err := getClusterFromRemotePeers(lg, getRemotePeerURLs(cl, member), timeout, false, rt)
if err != nil {
return false
}
id := cl.MemberByName(member).ID
m := rcl.Member(id)
if m == nil {
return false
}
if len(m.ClientURLs) > 0 {
return true
}
return false
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/coding/quotedprint.go#L26-L64
|
func (qp *QPCleaner) Read(dest []byte) (n int, err error) {
// Ensure room to write a byte or =XX string.
destLen := len(dest) - 3
// Loop over bytes in qp.in ByteReader.
for n < destLen {
b, err := qp.in.ReadByte()
if err != nil {
return n, err
}
switch {
case b == '=':
// Pass valid hex bytes through.
hexBytes, err := qp.in.Peek(2)
if err != nil && err != io.EOF {
return 0, err
}
if validHexBytes(hexBytes) {
dest[n] = b
n++
} else {
s := fmt.Sprintf("=%02X", b)
n += copy(dest[n:], s)
}
case b == '\t' || b == '\r' || b == '\n':
// Valid special character.
dest[n] = b
n++
case b < ' ' || '~' < b:
// Invalid character, render quoted-printable into buffer.
s := fmt.Sprintf("=%02X", b)
n += copy(dest[n:], s)
default:
// Acceptable character.
dest[n] = b
n++
}
}
return n, err
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L220-L222
|
func (s *MockSpan) LogFields(fields ...log.Field) {
s.logFieldsWithTimestamp(time.Now(), fields...)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/ranch/storage.go#L74-L76
|
func (s *Storage) AddResource(resource common.Resource) error {
return s.resources.Add(resource)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/init.go#L342-L368
|
func initDataClusterApply(d lxd.ContainerServer, config *initDataCluster) error {
if config == nil || !config.Enabled {
return nil
}
// Get the current cluster configuration
currentCluster, etag, err := d.GetCluster()
if err != nil {
return errors.Wrap(err, "Failed to retrieve current cluster config")
}
// Check if already enabled
if !currentCluster.Enabled {
// Configure the cluster
op, err := d.UpdateCluster(config.ClusterPut, etag)
if err != nil {
return errors.Wrap(err, "Failed to configure cluster")
}
err = op.Wait()
if err != nil {
return errors.Wrap(err, "Failed to configure cluster")
}
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L8284-L8288
|
func (v ClearBrowserCookiesParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork64(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L67-L80
|
func (r *ReadBuffer) ReadByte() (byte, error) {
if r.err != nil {
return 0, r.err
}
if len(r.remaining) < 1 {
r.err = ErrEOF
return 0, r.err
}
b := r.remaining[0]
r.remaining = r.remaining[1:]
return b, nil
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/boundary.go#L40-L83
|
func (b *boundaryReader) Read(dest []byte) (n int, err error) {
if b.buffer.Len() >= len(dest) {
// This read request can be satisfied entirely by the buffer
return b.buffer.Read(dest)
}
peek, err := b.r.Peek(peekBufferSize)
peekEOF := (err == io.EOF)
if err != nil && !peekEOF && err != bufio.ErrBufferFull {
// Unexpected error
return 0, errors.WithStack(err)
}
var nCopy int
idx, complete := locateBoundary(peek, b.nlPrefix)
if idx != -1 {
// Peeked boundary prefix, read until that point
nCopy = idx
if !complete && nCopy == 0 {
// Incomplete boundary, move past it
nCopy = 1
}
} else {
// No boundary found, move forward a safe distance
if nCopy = len(peek) - len(b.nlPrefix) - 1; nCopy <= 0 {
nCopy = 0
if peekEOF {
// No more peek space remaining and no boundary found
return 0, errors.WithStack(io.ErrUnexpectedEOF)
}
}
}
if nCopy > 0 {
if _, err = io.CopyN(b.buffer, b.r, int64(nCopy)); err != nil {
return 0, errors.WithStack(err)
}
}
n, err = b.buffer.Read(dest)
if err == io.EOF && !complete {
// Only the buffer is empty, not the boundaryReader
return n, nil
}
return n, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L268-L272
|
func (v TextBoxSnapshot) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomsnapshot(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/log/field.go#L126-L132
|
func Error(err error) Field {
return Field{
key: "error",
fieldType: errorType,
interfaceVal: err,
}
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol.go#L73-L106
|
func (params protocolIntroParams) doIntro() (res protocolIntroResults, err error) {
if err = params.Conn.SetDeadline(time.Now().Add(headerTimeout)); err != nil {
return
}
if res.Version, err = params.exchangeProtocolHeader(); err != nil {
return
}
var pubKey, privKey *[32]byte
if params.Password != nil {
if pubKey, privKey, err = generateKeyPair(); err != nil {
return
}
}
if err = params.Conn.SetWriteDeadline(time.Time{}); err != nil {
return
}
if err = params.Conn.SetReadDeadline(time.Now().Add(tcpHeartbeat * 2)); err != nil {
return
}
switch res.Version {
case 1:
err = res.doIntroV1(params, pubKey, privKey)
case 2:
err = res.doIntroV2(params, pubKey, privKey)
default:
panic("unhandled protocol version")
}
return
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/api_client.go#L57-L64
|
func New(endpoint string, errorRegistry ErrorRegistry) *Client {
return &Client{
Endpoint: endpoint,
ErrorRegistry: errorRegistry,
KeyHeader: DefaultKeyHeader,
HTTPClient: http.DefaultClient,
}
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/storage/postgres/storage.go#L273-L296
|
func (s *Storage) Abandon(ctx context.Context, accessToken string) (bool, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "postgres.storage.abandon")
defer span.Finish()
start := time.Now()
labels := prometheus.Labels{"query": "abandon"}
result, err := s.db.ExecContext(ctx, s.queryAbandon, accessToken)
s.incQueries(labels, start)
if err != nil {
s.incError(labels)
return false, err
}
affected, err := result.RowsAffected()
if err != nil {
return false, err
}
if affected == 0 {
return false, storage.ErrSessionNotFound
}
return true, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L751-L755
|
func (v *StopPreciseCoverageParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler8(&r, v)
return r.Error()
}
|
https://github.com/insionng/martini/blob/2d0ba5dc75fe9549c10e2f71927803a11e5e4957/context.go#L34-L63
|
func ContextRender(cookiesecret string, options ...RenderOptions) Handler {
return func(w http.ResponseWriter, req *http.Request, c Context) {
rd := Renderor(w, req, c, options...)
if rd.Data["RequestStartTime"] != nil {
rd.Data["RequestTimes"] = time.Since(rd.Data["RequestStartTime"].(time.Time)).Nanoseconds() / 1e6
rd.Data["RequestStartTime"] = nil //set zero to clean up the RequestStartTime
}
ctx := &Cotex{req, map[string]string{}, cookiesecret, w, rd}
//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.Form[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.Cotex
c.Map(rd)
c.Map(ctx)
c.Next()
}
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/skl/skl.go#L489-L495
|
func (s *UniIterator) Rewind() {
if !s.reversed {
s.iter.SeekToFirst()
} else {
s.iter.SeekToLast()
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/report/report.go#L110-L127
|
func ShouldReport(pj prowapi.ProwJob, validTypes []prowapi.ProwJobType) bool {
valid := false
for _, t := range validTypes {
if pj.Spec.Type == t {
valid = true
}
}
if !valid {
return false
}
if !pj.Spec.Report {
return false
}
return true
}
|
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/consumer.go#L66-L82
|
func (c *ConsumerConfig) defaults() {
if c.MaxInFlight == 0 {
c.MaxInFlight = DefaultMaxInFlight
}
if c.DialTimeout == 0 {
c.DialTimeout = DefaultDialTimeout
}
if c.ReadTimeout == 0 {
c.ReadTimeout = DefaultReadTimeout
}
if c.WriteTimeout == 0 {
c.WriteTimeout = DefaultWriteTimeout
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/deck/jobs/jobs.go#L80-L86
|
func NewJobAgent(kc serviceClusterClient, plClients map[string]PodLogClient, cfg config.Getter) *JobAgent {
return &JobAgent{
kc: kc,
pkcs: plClients,
config: cfg,
}
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/etcd_store.go#L712-L775
|
func applyCompare(kv mvcc.KV, c *etcdserverpb.Compare) (int64, bool) {
ckvs, rev, err := kv.Range(c.Key, nil, 1, 0)
if err != nil {
if err == mvcc.ErrTxnIDMismatch {
panic("unexpected txn ID mismatch error")
}
return rev, false
}
var ckv mvccpb.KeyValue
if len(ckvs) != 0 {
ckv = ckvs[0]
} else {
// Use the zero value of ckv normally. However...
if c.Target == etcdserverpb.Compare_VALUE {
// Always fail if we're comparing a value on a key that doesn't exist.
// We can treat non-existence as the empty set explicitly, such that
// even a key with a value of length 0 bytes is still a real key
// that was written that way
return rev, false
}
}
// -1 is less, 0 is equal, 1 is greater
var result int
switch c.Target {
case etcdserverpb.Compare_VALUE:
tv, _ := c.TargetUnion.(*etcdserverpb.Compare_Value)
if tv != nil {
result = bytes.Compare(ckv.Value, tv.Value)
}
case etcdserverpb.Compare_CREATE:
tv, _ := c.TargetUnion.(*etcdserverpb.Compare_CreateRevision)
if tv != nil {
result = compareInt64(ckv.CreateRevision, tv.CreateRevision)
}
case etcdserverpb.Compare_MOD:
tv, _ := c.TargetUnion.(*etcdserverpb.Compare_ModRevision)
if tv != nil {
result = compareInt64(ckv.ModRevision, tv.ModRevision)
}
case etcdserverpb.Compare_VERSION:
tv, _ := c.TargetUnion.(*etcdserverpb.Compare_Version)
if tv != nil {
result = compareInt64(ckv.Version, tv.Version)
}
}
switch c.Result {
case etcdserverpb.Compare_EQUAL:
if result != 0 {
return rev, false
}
case etcdserverpb.Compare_GREATER:
if result != 1 {
return rev, false
}
case etcdserverpb.Compare_LESS:
if result != -1 {
return rev, false
}
}
return rev, true
}
|
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/lyra2.go#L95-L106
|
func initState() []uint64 {
state := make([]uint64, 16)
state[8] = blake2bIV[0]
state[9] = blake2bIV[1]
state[10] = blake2bIV[2]
state[11] = blake2bIV[3]
state[12] = blake2bIV[4]
state[13] = blake2bIV[5]
state[14] = blake2bIV[6]
state[15] = blake2bIV[7]
return state
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/node.go#L372-L399
|
func listUnitsByNode(w http.ResponseWriter, r *http.Request, t auth.Token) error {
address := r.URL.Query().Get(":address")
_, node, err := node.FindNode(address)
if err != nil {
if err == provision.ErrNodeNotFound {
return &tsuruErrors.HTTP{
Code: http.StatusNotFound,
Message: err.Error(),
}
}
return err
}
hasAccess := permission.Check(t, permission.PermNodeRead,
permission.Context(permTypes.CtxPool, node.Pool()))
if !hasAccess {
return permission.ErrUnauthorized
}
units, err := node.Units()
if err != nil {
return err
}
if len(units) == 0 {
w.WriteHeader(http.StatusNoContent)
return nil
}
w.Header().Set("Content-Type", "application/json")
return json.NewEncoder(w).Encode(units)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cert.go#L45-L77
|
func KeyPairAndCA(dir, prefix string, kind CertKind) (*CertInfo, error) {
certFilename := filepath.Join(dir, prefix+".crt")
keyFilename := filepath.Join(dir, prefix+".key")
// Ensure that the certificate exists, or create a new one if it does
// not.
err := FindOrGenCert(certFilename, keyFilename, kind == CertClient)
if err != nil {
return nil, err
}
// Load the certificate.
keypair, err := tls.LoadX509KeyPair(certFilename, keyFilename)
if err != nil {
return nil, err
}
// If available, load the CA data as well.
caFilename := filepath.Join(dir, prefix+".ca")
var ca *x509.Certificate
if PathExists(caFilename) {
ca, err = ReadCert(caFilename)
if err != nil {
return nil, err
}
}
info := &CertInfo{
keypair: keypair,
ca: ca,
}
return info, nil
}
|
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/stagePlanner.go#L648-L659
|
func elideLiterals(root *evaluationStage) *evaluationStage {
if root.leftStage != nil {
root.leftStage = elideLiterals(root.leftStage)
}
if root.rightStage != nil {
root.rightStage = elideLiterals(root.rightStage)
}
return elideStage(root)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/job_history.go#L150-L160
|
func readJSON(bucket storageBucket, key string, data interface{}) error {
rawData, err := bucket.readObject(key)
if err != nil {
return fmt.Errorf("failed to read %s: %v", key, err)
}
err = json.Unmarshal(rawData, &data)
if err != nil {
return fmt.Errorf("failed to parse %s: %v", key, err)
}
return nil
}
|
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/syslog.go#L28-L32
|
func NewSyslogBackendPriority(prefix string, priority syslog.Priority) (b *SyslogBackend, err error) {
var w *syslog.Writer
w, err = syslog.New(priority, prefix)
return &SyslogBackend{w}, err
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/client.go#L92-L126
|
func readResponse(response *tchannel.OutboundCallResponse, resp thrift.TStruct) (map[string]string, bool, error) {
reader, err := response.Arg2Reader()
if err != nil {
return nil, false, err
}
headers, err := ReadHeaders(reader)
if err != nil {
return nil, false, err
}
if err := argreader.EnsureEmpty(reader, "reading response headers"); err != nil {
return nil, false, err
}
if err := reader.Close(); err != nil {
return nil, false, err
}
success := !response.ApplicationError()
reader, err = response.Arg3Reader()
if err != nil {
return headers, success, err
}
if err := ReadStruct(reader, resp); err != nil {
return headers, success, err
}
if err := argreader.EnsureEmpty(reader, "reading response body"); err != nil {
return nil, false, err
}
return headers, success, reader.Close()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/types/set.go#L78-L84
|
func (us *unsafeSet) Equals(other Set) bool {
v1 := sort.StringSlice(us.Values())
v2 := sort.StringSlice(other.Values())
v1.Sort()
v2.Sort()
return reflect.DeepEqual(v1, v2)
}
|
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L155-L197
|
func Analyzed(data json.RawMessage, version string) (*Document, error) {
if version == "" {
version = "2.0"
}
if version != "2.0" {
return nil, fmt.Errorf("spec version %q is not supported", version)
}
raw := data
trimmed := bytes.TrimSpace(data)
if len(trimmed) > 0 {
if trimmed[0] != '{' && trimmed[0] != '[' {
yml, err := swag.BytesToYAMLDoc(trimmed)
if err != nil {
return nil, fmt.Errorf("analyzed: %v", err)
}
d, err := swag.YAMLToJSON(yml)
if err != nil {
return nil, fmt.Errorf("analyzed: %v", err)
}
raw = d
}
}
swspec := new(spec.Swagger)
if err := json.Unmarshal(raw, swspec); err != nil {
return nil, err
}
origsqspec, err := cloneSpec(swspec)
if err != nil {
return nil, err
}
d := &Document{
Analyzer: analysis.New(swspec),
schema: spec.MustLoadSwagger20Schema(),
spec: swspec,
raw: raw,
origSpec: origsqspec,
}
return d, nil
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L118-L120
|
func (gc *GraphicContext) ClearRect(x1, y1, x2, y2 int) {
clearRect(gc, float64(x1), float64(y1), float64(x2), float64(y2))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/easyjson.go#L70-L74
|
func (v SetXHRBreakpointParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomdebugger(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L286-L290
|
func (v SetShowHitTestBordersParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoOverlay3(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/route.go#L177-L182
|
func (m *Route) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L512-L514
|
func (p *SetEffectivePropertyValueForNodeParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetEffectivePropertyValueForNode, p, nil)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.