_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/host.go#L31-L44
|
func (h *Host) Disconnect() {
// TODO(c4milo): Return an error to the user given that this error
// may be thrown due to insufficient hardware resources
if h.handle == C.VIX_E_CANCELLED {
return
}
if &h.handle != nil &&
h.handle != C.VIX_INVALID_HANDLE {
C.VixHost_Disconnect(h.handle)
h.handle = C.VIX_INVALID_HANDLE
}
}
|
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/rbuf.go#L239-L253
|
func (b *FixedSizeRingBuf) WriteAndMaybeOverwriteOldestData(p []byte) (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/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/experiment/resultstore/upload.go#L44-L70
|
func upload(rsClient *resultstore.Client, inv resultstore.Invocation, target resultstore.Target, test resultstore.Test) (string, error) {
targetID := test.Name
const configID = resultstore.Default
invName, err := rsClient.Invocations().Create(inv)
if err != nil {
return "", fmt.Errorf("create invocation: %v", err)
}
targetName, err := rsClient.Targets(invName).Create(targetID, target)
if err != nil {
return resultstore.URL(invName), fmt.Errorf("create target: %v", err)
}
url := resultstore.URL(targetName)
_, err = rsClient.Configurations(invName).Create(configID)
if err != nil {
return url, fmt.Errorf("create configuration: %v", err)
}
ctName, err := rsClient.ConfiguredTargets(targetName, configID).Create(test.Action)
if err != nil {
return url, fmt.Errorf("create configured target: %v", err)
}
_, err = rsClient.Actions(ctName).Create("primary", test)
if err != nil {
return url, fmt.Errorf("create action: %v", err)
}
return url, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L272-L323
|
func (d *dumpClient) doImp(req *http.Request, hidden bool, ctx context.Context) (*http.Response, error) {
if req.URL.Scheme == "" {
if d.isInsecure() {
req.URL.Scheme = "http"
} else {
req.URL.Scheme = "https"
}
}
//set user-agent if one is not provided.
ua := req.Header.Get("User-Agent")
if ua == "" {
req.Header.Set("User-Agent", UA)
}
var reqBody []byte
startedAt := time.Now()
// prefer the X-Request-Id header as request token for logging, if present.
id := req.Header.Get(requestIdHeader)
if id == "" {
id = ShortToken()
}
log.Info("started", "id", id, req.Method, req.URL.String())
df := d.dumpFormat()
hide := (df == NoDump) || (hidden && !df.IsVerbose())
if !hide {
startedAt = time.Now()
reqBody = d.dumpRequest(req)
}
var resp *http.Response
var err error
if ctx == nil {
resp, err = d.Client.Do(req)
} else {
resp, err = ctxhttpDo(ctx, d.getClientWithoutTimeout(), req)
}
if urlError, ok := err.(*url.Error); ok {
if urlError.Err.Error() == noRedirectError {
err = nil
}
}
if err != nil {
return nil, err
}
if !hide {
d.dumpResponse(resp, req, reqBody)
}
log.Info("completed", "id", id, "status", resp.Status, "time", time.Since(startedAt).String())
return resp, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L578-L591
|
func (r *ProtocolLXD) DeleteStoragePoolVolume(pool string, volType string, name string) error {
if !r.HasExtension("storage") {
return fmt.Errorf("The server is missing the required \"storage\" API extension")
}
// Send the request
path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", url.QueryEscape(pool), url.QueryEscape(volType), url.QueryEscape(name))
_, _, err := r.query("DELETE", path, nil, "")
if err != nil {
return err
}
return nil
}
|
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/sentinel.go#L155-L175
|
func (s *Sentinel) Mux(listener net.Listener, opts ...netmux.Option) (*netmux.Netmux, error) {
s.Lock()
defer s.Unlock()
if s.started {
return nil, ErrAlreadyStarted
}
// create connection mux
mux, err := netmux.New(listener, opts...)
if err != nil {
return nil, err
}
// register server + shutdown
if err = s.Register(mux, mux, IgnoreListenerClosed, IgnoreNetOpError); err != nil {
return nil, err
}
return mux, nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/reader.go#L69-L89
|
func (r *Reader) ReadString(n int) string {
if r.err != nil {
return ""
}
var buf []byte
if n <= maxPoolStringLen {
buf = r.buf[:n]
} else {
buf = make([]byte, n)
}
var readN int
readN, r.err = io.ReadFull(r.reader, buf)
if readN < n {
return ""
}
s := string(buf)
return s
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L248-L252
|
func (c *ClusterTx) NodeAdd(name string, address string) (int64, error) {
columns := []string{"name", "address", "schema", "api_extensions"}
values := []interface{}{name, address, cluster.SchemaVersion, version.APIExtensionsCount()}
return query.UpsertObject(c.tx, "nodes", columns, values)
}
|
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/key.go#L274-L287
|
func UnmarshalPublicKey(data []byte) (PubKey, error) {
pmes := new(pb.PublicKey)
err := proto.Unmarshal(data, pmes)
if err != nil {
return nil, err
}
um, ok := PubKeyUnmarshallers[pmes.GetType()]
if !ok {
return nil, ErrBadKeyType
}
return um(pmes.GetData())
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L116-L125
|
func (s *FileStore) Status() (on bool, err error) {
_, err = os.Stat(s.filename)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L233-L248
|
func (db *DB) DropTable(table interface{}) error {
_, _, tableName, err := db.tableValueOf("DropTable", table)
if err != nil {
return err
}
query := fmt.Sprintf("DROP TABLE %s", db.dialect.Quote(tableName))
stmt, err := db.prepare(query)
if err != nil {
return err
}
defer stmt.Close()
if _, err = stmt.Exec(); err != nil {
return err
}
return nil
}
|
https://github.com/achiku/soapc/blob/cfbdfe6e4caffe57a9cba89996e8b1cedb512be0/client.go#L98-L140
|
func (b *Body) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
if b.Content == nil {
return xml.UnmarshalError("Content must be a pointer to a struct")
}
var (
token xml.Token
err error
consumed bool
)
Loop:
for {
if token, err = d.Token(); err != nil {
return err
}
if token == nil {
break
}
envelopeNameSpace := "http://schemas.xmlsoap.org/soap/envelope/"
switch se := token.(type) {
case xml.StartElement:
if consumed {
return xml.UnmarshalError(
"Found multiple elements inside SOAP body; not wrapped-document/literal WS-I compliant")
} else if se.Name.Space == envelopeNameSpace && se.Name.Local == "Fault" {
b.Fault = &Fault{}
b.Content = nil
err = d.DecodeElement(b.Fault, &se)
if err != nil {
return err
}
consumed = true
} else {
if err = d.DecodeElement(b.Content, &se); err != nil {
return err
}
consumed = true
}
case xml.EndElement:
break Loop
}
}
return nil
}
|
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/options/dag.go#L64-L69
|
func (dagOpts) Hash(hash string) DagPutOption {
return func(opts *DagPutSettings) error {
opts.Hash = hash
return nil
}
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L628-L643
|
func (db *DB) selectToValue(rows *sql.Rows, t reflect.Type) (reflect.Value, error) {
ptrN := 0
for ; t.Kind() == reflect.Ptr; ptrN++ {
t = t.Elem()
}
dest := reflect.New(t).Elem()
if rows.Next() {
if err := rows.Scan(dest.Addr().Interface()); err != nil {
return reflect.Value{}, err
}
}
for i := 0; i < ptrN; i++ {
dest = dest.Addr()
}
return dest, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/headlessexperimental/types.go#L48-L58
|
func (t *ScreenshotParamsFormat) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch ScreenshotParamsFormat(in.String()) {
case ScreenshotParamsFormatJpeg:
*t = ScreenshotParamsFormatJpeg
case ScreenshotParamsFormatPng:
*t = ScreenshotParamsFormatPng
default:
in.AddError(errors.New("unknown ScreenshotParamsFormat value"))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/indexeddb.go#L265-L274
|
func (p *RequestDatabaseParams) Do(ctx context.Context) (databaseWithObjectStores *DatabaseWithObjectStores, err error) {
// execute
var res RequestDatabaseReturns
err = cdp.Execute(ctx, CommandRequestDatabase, p, &res)
if err != nil {
return nil, err
}
return res.DatabaseWithObjectStores, nil
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/local_peer.go#L105-L111
|
func (peer *localPeer) doAddConnection(conn ourConnection, isRestartedPeer bool) error {
resultChan := make(chan error)
peer.actionChan <- func() {
resultChan <- peer.handleAddConnection(conn, isRestartedPeer)
}
return <-resultChan
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/proxy/server.go#L201-L280
|
func NewServer(cfg ServerConfig) Server {
s := &server{
lg: cfg.Logger,
from: cfg.From,
to: cfg.To,
tlsInfo: cfg.TLSInfo,
dialTimeout: cfg.DialTimeout,
bufferSize: cfg.BufferSize,
retryInterval: cfg.RetryInterval,
readyc: make(chan struct{}),
donec: make(chan struct{}),
errc: make(chan error, 16),
pauseAcceptc: make(chan struct{}),
pauseTxc: make(chan struct{}),
pauseRxc: make(chan struct{}),
}
_, fromPort, err := net.SplitHostPort(cfg.From.Host)
if err == nil {
s.fromPort, _ = strconv.Atoi(fromPort)
}
var toPort string
_, toPort, err = net.SplitHostPort(cfg.To.Host)
if err == nil {
s.toPort, _ = strconv.Atoi(toPort)
}
if s.dialTimeout == 0 {
s.dialTimeout = defaultDialTimeout
}
if s.bufferSize == 0 {
s.bufferSize = defaultBufferSize
}
if s.retryInterval == 0 {
s.retryInterval = defaultRetryInterval
}
if s.lg == nil {
s.lg = defaultLogger
}
close(s.pauseAcceptc)
close(s.pauseTxc)
close(s.pauseRxc)
if strings.HasPrefix(s.from.Scheme, "http") {
s.from.Scheme = "tcp"
}
if strings.HasPrefix(s.to.Scheme, "http") {
s.to.Scheme = "tcp"
}
addr := fmt.Sprintf(":%d", s.fromPort)
if s.fromPort == 0 { // unix
addr = s.from.Host
}
var ln net.Listener
if !s.tlsInfo.Empty() {
ln, err = transport.NewListener(addr, s.from.Scheme, &s.tlsInfo)
} else {
ln, err = net.Listen(s.from.Scheme, addr)
}
if err != nil {
s.errc <- err
s.Close()
return s
}
s.listener = ln
s.closeWg.Add(1)
go s.listenAndServe()
s.lg.Info("started proxying", zap.String("from", s.From()), zap.String("to", s.To()))
return s
}
|
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/parsed_query.go#L73-L90
|
func EncodeValue(buf *bytes.Buffer, value *querypb.BindVariable) {
if value.Type != querypb.Type_TUPLE {
// Since we already check for TUPLE, we don't expect an error.
v, _ := sqltypes.BindVariableToValue(value)
v.EncodeSQL(buf)
return
}
// It's a TUPLE.
buf.WriteByte('(')
for i, bv := range value.Values {
if i != 0 {
buf.WriteString(", ")
}
sqltypes.ProtoToValue(bv).EncodeSQL(buf)
}
buf.WriteByte(')')
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L87-L96
|
func (s *MemoryStore) Off() (changed bool, err error) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.on {
return
}
s.on = false
changed = true
return
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/listers/tsuru/v1/app.go#L38-L43
|
func (s *appLister) List(selector labels.Selector) (ret []*v1.App, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1.App))
})
return ret, err
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L308-L314
|
func (txn *Txn) Set(key, val []byte) error {
e := &Entry{
Key: key,
Value: val,
}
return txn.SetEntry(e)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/grpcutil/stream.go#L33-L50
|
func ChunkReader(r io.Reader, f func([]byte) error) (int, error) {
var total int
buf := GetBuffer()
defer PutBuffer(buf)
for {
n, err := r.Read(buf)
if n == 0 && err != nil {
if err == io.EOF {
return total, nil
}
return total, err
}
if err := f(buf[:n]); err != nil {
return total, err
}
total += n
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L251-L257
|
func (w *WriteBuffer) WriteString(s string) {
// NB(mmihic): Don't just call WriteBytes; that will make a double copy
// of the string due to the cast
if b := w.reserve(len(s)); b != nil {
copy(b, s)
}
}
|
https://github.com/ikawaha/kagome.ipadic/blob/fe03f87a0c7c32945d956fcfc934c3e11d5eb182/internal/dic/index.go#L121-L135
|
func ReadIndexTable(r io.Reader) (IndexTable, error) {
idx := IndexTable{}
d, err := da.Read(r)
if err != nil {
return idx, fmt.Errorf("read index error, %v", err)
}
idx.Da = d
dec := gob.NewDecoder(r)
if e := dec.Decode(&idx.Dup); e != nil {
return idx, fmt.Errorf("read index dup table error, %v", e)
}
return idx, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3client/v3client.go#L30-L51
|
func New(s *etcdserver.EtcdServer) *clientv3.Client {
c := clientv3.NewCtxClient(context.Background())
kvc := adapter.KvServerToKvClient(v3rpc.NewQuotaKVServer(s))
c.KV = clientv3.NewKVFromKVClient(kvc, c)
lc := adapter.LeaseServerToLeaseClient(v3rpc.NewQuotaLeaseServer(s))
c.Lease = clientv3.NewLeaseFromLeaseClient(lc, c, time.Second)
wc := adapter.WatchServerToWatchClient(v3rpc.NewWatchServer(s))
c.Watcher = &watchWrapper{clientv3.NewWatchFromWatchClient(wc, c)}
mc := adapter.MaintenanceServerToMaintenanceClient(v3rpc.NewMaintenanceServer(s))
c.Maintenance = clientv3.NewMaintenanceFromMaintenanceClient(mc, c)
clc := adapter.ClusterServerToClusterClient(v3rpc.NewClusterServer(s))
c.Cluster = clientv3.NewClusterFromClusterClient(clc, c)
// TODO: implement clientv3.Auth interface?
return c
}
|
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/view/template.go#L133-L138
|
func CloseWatcher() error {
for i := uint32(0); i < watcher.count; i++ {
watcher.closer <- true
}
return watcher.Close()
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L206-L210
|
func EnsureSuffixF(suffix string) func(string) string {
return func(s string) string {
return EnsureSuffix(s, suffix)
}
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L551-L557
|
func matchLen(x, y string) int {
i := 0
for i < len(x) && i < len(y) && x[i] == y[i] {
i++
}
return i
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L334-L337
|
func Match(s, pattern string) bool {
r := regexp.MustCompile(pattern)
return r.MatchString(s)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/client.go#L415-L426
|
func NewInCluster(options ...Option) (*APIClient, error) {
host, ok := os.LookupEnv("PACHD_SERVICE_HOST")
if !ok {
return nil, fmt.Errorf("PACHD_SERVICE_HOST not set")
}
port, ok := os.LookupEnv("PACHD_SERVICE_PORT")
if !ok {
return nil, fmt.Errorf("PACHD_SERVICE_PORT not set")
}
// create new pachctl client
return NewFromAddress(fmt.Sprintf("%s:%s", host, port), options...)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/collection/transaction.go#L63-L65
|
func NewSTM(ctx context.Context, c *v3.Client, apply func(STM) error) (*v3.TxnResponse, error) {
return newSTMSerializable(ctx, c, apply, false)
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive50.go#L339-L355
|
func (a *archive50) parseEncryptionBlock(b readBuf) error {
if ver := b.uvarint(); ver != 0 {
return errUnknownEncMethod
}
flags := b.uvarint()
keys, err := a.getKeys(&b)
if err != nil {
return err
}
if flags&enc5CheckPresent > 0 {
if err := checkPassword(&b, keys); err != nil {
return err
}
}
a.blockKey = keys[0]
return nil
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/reflect.go#L64-L75
|
func derefPointers(rv reflect.Value) (drv reflect.Value, isPtr bool, isNilPtr bool) {
for rv.Kind() == reflect.Ptr {
isPtr = true
if rv.IsNil() {
isNilPtr = true
return
}
rv = rv.Elem()
}
drv = rv
return
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_volumes_utils.go#L424-L468
|
func storagePoolVolumeUsedByGet(s *state.State, project, volumeName string, volumeTypeName string) ([]string, error) {
// Handle container volumes
if volumeTypeName == "container" {
cName, sName, snap := containerGetParentAndSnapshotName(volumeName)
if snap {
return []string{fmt.Sprintf("/%s/containers/%s/snapshots/%s", version.APIVersion, cName, sName)}, nil
}
return []string{fmt.Sprintf("/%s/containers/%s", version.APIVersion, cName)}, nil
}
// Handle image volumes
if volumeTypeName == "image" {
return []string{fmt.Sprintf("/%s/images/%s", version.APIVersion, volumeName)}, nil
}
// Look for containers using this volume
ctsUsingVolume, err := storagePoolVolumeUsedByContainersGet(s,
project, volumeName, volumeTypeName)
if err != nil {
return []string{}, err
}
volumeUsedBy := []string{}
for _, ct := range ctsUsingVolume {
volumeUsedBy = append(volumeUsedBy,
fmt.Sprintf("/%s/containers/%s", version.APIVersion, ct))
}
profiles, err := profilesUsingPoolVolumeGetNames(s.Cluster, volumeName, volumeTypeName)
if err != nil {
return []string{}, err
}
if len(volumeUsedBy) == 0 && len(profiles) == 0 {
return []string{}, nil
}
for _, pName := range profiles {
volumeUsedBy = append(volumeUsedBy, fmt.Sprintf("/%s/profiles/%s", version.APIVersion, pName))
}
return volumeUsedBy, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L346-L354
|
func (ap Approvers) GetCurrentApproversSet() sets.String {
currentApprovers := sets.NewString()
for approver := range ap.approvers {
currentApprovers.Insert(approver)
}
return currentApprovers
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approve.go#L607-L639
|
func optionsForRepo(config *plugins.Configuration, org, repo string) *plugins.Approve {
fullName := fmt.Sprintf("%s/%s", org, repo)
a := func() *plugins.Approve {
// First search for repo config
for _, c := range config.Approve {
if !strInSlice(fullName, c.Repos) {
continue
}
return &c
}
// If you don't find anything, loop again looking for an org config
for _, c := range config.Approve {
if !strInSlice(org, c.Repos) {
continue
}
return &c
}
// Return an empty config, and use plugin defaults
return &plugins.Approve{}
}()
if a.DeprecatedImplicitSelfApprove == nil && a.RequireSelfApproval == nil && config.UseDeprecatedSelfApprove {
no := false
a.DeprecatedImplicitSelfApprove = &no
}
if a.DeprecatedReviewActsAsApprove == nil && a.IgnoreReviewState == nil && config.UseDeprecatedReviewApprove {
no := false
a.DeprecatedReviewActsAsApprove = &no
}
return a
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage.go#L807-L826
|
func StorageProgressReader(op *operation, key string, description string) func(io.ReadCloser) io.ReadCloser {
return func(reader io.ReadCloser) io.ReadCloser {
if op == nil {
return reader
}
progress := func(progressInt int64, speedInt int64) {
progressWrapperRender(op, key, description, progressInt, speedInt)
}
readPipe := &ioprogress.ProgressReader{
ReadCloser: reader,
Tracker: &ioprogress.ProgressTracker{
Handler: progress,
},
}
return readPipe
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L308-L310
|
func (p *SetInspectModeParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetInspectMode, p, nil)
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/pdclient/dispenser_client.go#L25-L38
|
func (s *PDClient) GetTask(taskID string) (task TaskResponse, res *http.Response, err error) {
req, _ := s.createRequest("GET", fmt.Sprintf("%s/v1/task/%s", s.URL, taskID), bytes.NewBufferString(``))
if res, err = s.client.Do(req); err == nil && res.StatusCode == http.StatusOK {
resBodyBytes, _ := ioutil.ReadAll(res.Body)
json.Unmarshal(resBodyBytes, &task)
} else {
lo.G.Error("client Do Error: ", err)
lo.G.Error("client Res: ", res)
err = ErrInvalidDispenserResponse
}
return
}
|
https://github.com/ccding/go-config-reader/blob/8b6c2b50197f20da3b1c5944c274c173634dc056/config/config.go#L116-L122
|
func (c *Config) Set(section string, key string, value string) {
_, ok := c.config[section]
if !ok {
c.config[section] = make(map[string]string)
}
c.config[section][key] = value
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L711-L720
|
func (p *GetSearchResultsParams) Do(ctx context.Context) (nodeIds []cdp.NodeID, err error) {
// execute
var res GetSearchResultsReturns
err = cdp.Execute(ctx, CommandGetSearchResults, p, &res)
if err != nil {
return nil, err
}
return res.NodeIds, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/gcsartifact.go#L74-L80
|
func (a *GCSArtifact) Size() (int64, error) {
attrs, err := a.handle.Attrs(a.ctx)
if err != nil {
return 0, fmt.Errorf("error getting gcs attributes for artifact: %v", err)
}
return attrs.Size, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L1444-L1448
|
func (v *ScreenOrientation) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoEmulation15(&r, v)
return r.Error()
}
|
https://github.com/jda/go-loginshare/blob/31dab1f26ba16c171d196dbb7317ca0527d3d3e2/common.go#L55-L83
|
func (l *LoginShare) Request(w http.ResponseWriter, r *http.Request) {
lsr, err := l.validateRequest(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
log.Printf("invalid loginshare request from %s", r.RemoteAddr)
return
}
if l.interfaceAllowed(lsr.Interface) == false {
w.WriteHeader(http.StatusForbidden)
log.Printf("loginshare request from %s for unpermitted interface", r.RemoteAddr)
return
}
w.Header().Add("Content-Type", "application/xml")
xw := xml.NewEncoder(w)
resp, err := l.OnNewAuth(lsr)
if err != nil {
log.Printf("loginshare request from %s failed: %s", r.RemoteAddr, err)
resp.StaffRecord = Staff{} // make sure we don't give up any info if partially populated
resp.Result = 0
resp.Message = err.Error()
xw.Encode(resp)
return
}
xw.Encode(resp)
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L4292-L4296
|
func (v GetPlatformFontsForNodeReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss37(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/easyjson.go#L976-L980
|
func (v ClearDataForOriginParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoStorage11(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L120-L124
|
func (eC2Manager *EC2Manager) TerminateWorkerType(workerType string) error {
cd := tcclient.Client(*eC2Manager)
_, _, err := (&cd).APICall(nil, "DELETE", "/worker-types/"+url.QueryEscape(workerType)+"/resources", nil, nil)
return err
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/transports/stub.go#L23-L25
|
func (s stubTransport) ParseReference(reference string) (types.ImageReference, error) {
return nil, fmt.Errorf(`The transport "%s:" is not supported in this build`, string(s))
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/manifest.go#L171-L185
|
func AddDummyV2S1Signature(manifest []byte) ([]byte, error) {
key, err := libtrust.GenerateECP256PrivateKey()
if err != nil {
return nil, err // Coverage: This can fail only if rand.Reader fails.
}
js, err := libtrust.NewJSONSignature(manifest)
if err != nil {
return nil, err
}
if err := js.Sign(key); err != nil { // Coverage: This can fail basically only if rand.Reader fails.
return nil, err
}
return js.PrettySignature("signatures")
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gbytes/buffer.go#L59-L70
|
func BufferReader(reader io.Reader) *Buffer {
b := &Buffer{
lock: &sync.Mutex{},
}
go func() {
io.Copy(b, reader)
b.Close()
}()
return b
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/easyjson.go#L1241-L1245
|
func (v *GetFullAXTreeReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoAccessibility7(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/types.go#L96-L98
|
func (t StreamCompression) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/rbuf.go#L530-L539
|
func (f *FixedSizeRingBuf) DeleteMostRecentBytes(n int) {
if n <= 0 {
return
}
if n >= f.Readable {
f.Readable = 0
return
}
f.Readable -= n
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L240-L243
|
func (p DispatchMouseEventParams) WithPointerType(pointerType DispatchMouseEventPointerType) *DispatchMouseEventParams {
p.PointerType = pointerType
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2984-L2988
|
func (v GetSearchResultsParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom33(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/secret/agent.go#L35-L49
|
func (a *Agent) Start(paths []string) error {
secretsMap, err := LoadSecrets(paths)
if err != nil {
return err
}
a.secretsMap = secretsMap
// Start one goroutine for each file to monitor and update the secret's values.
for secretPath := range secretsMap {
go a.reloadSecret(secretPath)
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/adt/interval_tree.go#L104-L114
|
func (x *intervalNode) successor() *intervalNode {
if x.right != nil {
return x.right.min()
}
y := x.parent
for y != nil && x == y.right {
x = y
y = y.parent
}
return y
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/badger/cmd/bank.go#L181-L210
|
func seekTotal(txn *badger.Txn) ([]account, error) {
expected := uint64(numAccounts) * uint64(initialBal)
var accounts []account
var total uint64
for i := 0; i < numAccounts; i++ {
item, err := txn.Get(key(i))
if err != nil {
log.Printf("Error for account: %d. err=%v. key=%q\n", i, err, key(i))
return accounts, err
}
val, err := item.ValueCopy(nil)
if err != nil {
return accounts, err
}
acc := account{
Id: i,
Bal: toUint64(val),
}
accounts = append(accounts, acc)
total += acc.Bal
}
if total != expected {
log.Printf("Balance did NOT match up. Expected: %d. Received: %d",
expected, total)
atomic.AddInt32(&stopAll, 1)
return accounts, errFailure
}
return accounts, nil
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gomega_dsl.go#L213-L226
|
func EventuallyWithOffset(offset int, actual interface{}, intervals ...interface{}) AsyncAssertion {
if globalFailWrapper == nil {
panic(nilFailHandlerPanic)
}
timeoutInterval := defaultEventuallyTimeout
pollingInterval := defaultEventuallyPollingInterval
if len(intervals) > 0 {
timeoutInterval = toDuration(intervals[0])
}
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset)
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L85-L94
|
func FrameSet_String(id FrameSetId) (str *C.char) {
fs, ok := sFrameSets.Get(id)
if !ok {
str = C.CString("")
} else {
str = C.CString(fs.String())
}
// CString is freed by caller
return str
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L311-L321
|
func (c *Cluster) StorageVolumeCleanupImages(fingerprints []string) error {
stmt := fmt.Sprintf(
"DELETE FROM storage_volumes WHERE type=? AND name NOT IN %s",
query.Params(len(fingerprints)))
args := []interface{}{StoragePoolVolumeTypeImage}
for _, fingerprint := range fingerprints {
args = append(args, fingerprint)
}
err := exec(c.db, stmt, args...)
return err
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/raw/call.go#L113-L129
|
func CallV2(ctx context.Context, sc *tchannel.SubChannel, cArgs CArgs) (*CRes, error) {
call, err := sc.BeginCall(ctx, cArgs.Method, cArgs.CallOptions)
if err != nil {
return nil, err
}
arg2, arg3, res, err := WriteArgs(call, cArgs.Arg2, cArgs.Arg3)
if err != nil {
return nil, err
}
return &CRes{
Arg2: arg2,
Arg3: arg3,
AppError: res.ApplicationError(),
}, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/watchable_store.go#L236-L259
|
func (s *watchableStore) syncVictimsLoop() {
defer s.wg.Done()
for {
for s.moveVictims() != 0 {
// try to update all victim watchers
}
s.mu.RLock()
isEmpty := len(s.victims) == 0
s.mu.RUnlock()
var tickc <-chan time.Time
if !isEmpty {
tickc = time.After(10 * time.Millisecond)
}
select {
case <-tickc:
case <-s.victimc:
case <-s.stopc:
return
}
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/grpcproxy/cache/store.go#L158-L165
|
func (c *cache) Compact(revision int64) {
c.mu.Lock()
defer c.mu.Unlock()
if revision > c.compactedRev {
c.compactedRev = revision
}
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/levels.go#L936-L944
|
func (s *levelsController) appendIterators(
iters []y.Iterator, opt *IteratorOptions) []y.Iterator {
// Just like with get, it's important we iterate the levels from 0 on upward, to avoid missing
// data when there's a compaction.
for _, level := range s.levels {
iters = level.appendIterators(iters, opt)
}
return iters
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/angular.go#L40-L48
|
func path(a *gen.Action) string {
pattern := a.PathPatterns[0]
vars := pattern.Variables
ivars := make([]interface{}, len(vars))
for i, v := range vars {
ivars[i] = interface{}(":" + v)
}
return fmt.Sprintf(pattern.Pattern, ivars...)
}
|
https://github.com/tsuru/gnuflag/blob/86b8c1b864aadcf9c94d67bc607ce3f19cbb9aa2/flag.go#L863-L894
|
func (f *FlagSet) Parse(allowIntersperse bool, arguments []string) error {
f.parsed = true
f.procArgs = arguments
f.procFlag = ""
f.args = nil
f.allowIntersperse = allowIntersperse
for {
name, long, finished, err := f.parseOne()
if !finished {
if name != "" {
finished, err = f.parseFlagArg(name, long)
}
}
if err != nil {
switch f.errorHandling {
case ContinueOnError:
return err
case ExitOnError:
os.Exit(2)
case PanicOnError:
panic(err)
}
}
if !finished {
continue
}
if err == nil {
break
}
}
return nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/reqres.go#L195-L197
|
func (r *reqResReader) arg1Reader() (ArgReader, error) {
return r.argReader(false /* last */, reqResReaderPreArg1, reqResReaderPreArg2)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L1312-L1316
|
func (v *Key) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb10(&r, v)
return r.Error()
}
|
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/syslog.go#L35-L53
|
func (b *SyslogBackend) Log(level Level, calldepth int, rec *Record) error {
line := rec.Formatted(calldepth + 1)
switch level {
case CRITICAL:
return b.Writer.Crit(line)
case ERROR:
return b.Writer.Err(line)
case WARNING:
return b.Writer.Warning(line)
case NOTICE:
return b.Writer.Notice(line)
case INFO:
return b.Writer.Info(line)
case DEBUG:
return b.Writer.Debug(line)
default:
}
panic("unhandled log level")
}
|
https://github.com/suicidejack/throttled/blob/373909e862a27e2190015918229c2605b3221f1d/wait_group.go#L12-L18
|
func NewWaitGroup(throttle int) *WaitGroup {
return &WaitGroup{
outstanding: 0,
throttle: throttle,
completed: make(chan bool, throttle),
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/serviceworker.go#L75-L82
|
func DispatchSyncEvent(origin string, registrationID RegistrationID, tag string, lastChance bool) *DispatchSyncEventParams {
return &DispatchSyncEventParams{
Origin: origin,
RegistrationID: registrationID,
Tag: tag,
LastChance: lastChance,
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/expr.go#L13-L19
|
func Params(n int) string {
tokens := make([]string, n)
for i := 0; i < n; i++ {
tokens[i] = "?"
}
return fmt.Sprintf("(%s)", strings.Join(tokens, ", "))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L342-L345
|
func (p GetWindowForTargetParams) WithTargetID(targetID target.ID) *GetWindowForTargetParams {
p.TargetID = targetID
return &p
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/project/project.go#L119-L138
|
func processRegexMatches(matches []string) (string, string, bool, string) {
var shouldClear = false
proposedProject := matches[1]
proposedColumnName := ""
if len(matches) > 1 && proposedProject != clearKeyword {
proposedColumnName = matches[2]
}
// If command is to clear and the project is provided
if proposedProject == clearKeyword {
if len(matches) > 2 && matches[2] != "" {
proposedProject = matches[2]
shouldClear = true
} else {
msg := invalidNumArgs
return "", "", false, msg
}
}
return proposedProject, proposedColumnName, shouldClear, ""
}
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/s3gof3r.go#L149-L181
|
func (b *Bucket) url(bPath string, c *Config) (*url.URL, error) {
// parse versionID parameter from path, if included
// See https://github.com/rlmcpherson/s3gof3r/issues/84 for rationale
purl, err := url.Parse(bPath)
if err != nil {
return nil, err
}
var vals url.Values
if v := purl.Query().Get(versionParam); v != "" {
vals = make(url.Values)
vals.Add(versionParam, v)
bPath = strings.Split(bPath, "?")[0] // remove versionID from path
}
// handling for bucket names containing periods / explicit PathStyle addressing
// http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html for details
if strings.Contains(b.Name, ".") || c.PathStyle {
return &url.URL{
Host: b.S3.Domain,
Scheme: c.Scheme,
Path: path.Clean(fmt.Sprintf("/%s/%s", b.Name, bPath)),
RawQuery: vals.Encode(),
}, nil
} else {
return &url.URL{
Scheme: c.Scheme,
Path: path.Clean(fmt.Sprintf("/%s", bPath)),
Host: path.Clean(fmt.Sprintf("%s.%s", b.Name, b.S3.Domain)),
RawQuery: vals.Encode(),
}, nil
}
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/tree.go#L365-L500
|
func (n *node) getValue(path string, po Params, unescape bool) (handlers RouterHandlerChain, p Params, tsr bool) {
p = po
walk: // Outer loop for walking the tree
for {
if len(path) > len(n.path) {
if path[:len(n.path)] == n.path {
path = path[len(n.path):]
// If this node does not have a wildcard (param or catchAll)
// child, we can just look up the next child node and continue
// to walk down the tree
if !n.wildChild {
c := path[0]
for i := 0; i < len(n.indices); i++ {
if c == n.indices[i] {
n = n.children[i]
continue walk
}
}
// Nothing found.
// We can recommend to redirect to the same URL without a
// trailing slash if a leaf exists for that path.
tsr = path == "/" && n.handlers != nil
return
}
// handle wildcard child
n = n.children[0]
switch n.nType {
case param:
// find param end (either '/' or path end)
end := 0
for end < len(path) && path[end] != '/' {
end++
}
// save param value
if cap(p) < int(n.maxParams) {
p = make(Params, 0, n.maxParams)
}
i := len(p)
p = p[:i+1] // expand slice within preallocated capacity
p[i].Key = n.path[1:]
val := path[:end]
if unescape {
var err error
if p[i].Value, err = url.QueryUnescape(val); err != nil {
p[i].Value = val // fallback, in case of error
}
} else {
p[i].Value = val
}
// we need to go deeper!
if end < len(path) {
if len(n.children) > 0 {
path = path[end:]
n = n.children[0]
continue walk
}
// ... but we can't
tsr = len(path) == end+1
return
}
if handlers = n.handlers; handlers != nil {
return
}
if len(n.children) == 1 {
// No handle found. Check if a handle for this path + a
// trailing slash exists for TSR recommendation
n = n.children[0]
tsr = n.path == "/" && n.handlers != nil
}
return
case catchAll:
// save param value
if cap(p) < int(n.maxParams) {
p = make(Params, 0, n.maxParams)
}
i := len(p)
p = p[:i+1] // expand slice within preallocated capacity
p[i].Key = n.path[2:]
if unescape {
var err error
if p[i].Value, err = url.QueryUnescape(path); err != nil {
p[i].Value = path // fallback, in case of error
}
} else {
p[i].Value = path
}
handlers = n.handlers
return
default:
panic("invalid node type")
}
}
} else if path == n.path {
// We should have reached the node containing the handle.
// Check if this node has a handle registered.
if handlers = n.handlers; handlers != nil {
return
}
if path == "/" && n.wildChild && n.nType != root {
tsr = true
return
}
// No handle found. Check if a handle for this path + a
// trailing slash exists for trailing slash recommendation
for i := 0; i < len(n.indices); i++ {
if n.indices[i] == '/' {
n = n.children[i]
tsr = (len(n.path) == 1 && n.handlers != nil) ||
(n.nType == catchAll && n.children[0].handlers != nil)
return
}
}
return
}
// Nothing found. We can recommend to redirect to the same URL with an
// extra trailing slash if a leaf exists for that path
tsr = (path == "/") ||
(len(n.path) == len(path)+1 && n.path[len(path)] == '/' &&
path == n.path[:len(n.path)-1] && n.handlers != nil)
return
}
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/postscript/postscript.go#L16-L33
|
func Main(gc draw2d.GraphicContext, ext string) (string, error) {
gc.Save()
// flip the image
gc.Translate(0, 200)
gc.Scale(0.35, -0.35)
gc.Translate(70, -200)
// Tiger postscript drawing
tiger := samples.Resource("image", "tiger.ps", ext)
// Draw tiger
Draw(gc, tiger)
gc.Restore()
// Return the output filename
return samples.Output("postscript", ext), nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/backup.go#L145-L147
|
func (b *backup) Delete() error {
return doBackupDelete(b.state, b.name, b.container.Name())
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L502-L505
|
func (s *FileSequence) Copy() *FileSequence {
seq, _ := NewFileSequence(s.String())
return seq
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/wrappers.go#L22-L29
|
func WrapBuffaloHandler(h Handler) http.Handler {
a := New(Options{})
// it doesn't matter what we actually map it
// GET, POST, etc... we just need the underlying
// RouteInfo, which implements http.Handler
ri := a.GET("/", h)
return ri
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L450-L471
|
func NewAsset(aType AssetType, value interface{}) (result Asset, err error) {
result.Type = aType
switch AssetType(aType) {
case AssetTypeAssetTypeNative:
// void
case AssetTypeAssetTypeCreditAlphanum4:
tv, ok := value.(AssetAlphaNum4)
if !ok {
err = fmt.Errorf("invalid value, must be AssetAlphaNum4")
return
}
result.AlphaNum4 = &tv
case AssetTypeAssetTypeCreditAlphanum12:
tv, ok := value.(AssetAlphaNum12)
if !ok {
err = fmt.Errorf("invalid value, must be AssetAlphaNum12")
return
}
result.AlphaNum12 = &tv
}
return
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L304-L306
|
func (m *Message) Attach(filename string, settings ...FileSetting) {
m.attachments = m.appendFile(m.attachments, fileFromFilename(filename), settings)
}
|
https://github.com/heketi/tests/blob/f3775cbcefd6822086c729e3ce4b70ca85a5bd21/tempfile.go#L42-L59
|
func CreateFile(filename string, size int64) error {
buf := make([]byte, size)
// Create the file store some data
fp, err := os.Create(filename)
if err != nil {
return err
}
// Write the buffer
_, err = fp.Write(buf)
// Cleanup
fp.Close()
return err
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_image.go#L320-L334
|
func newImageDestination(imageRef storageReference) (*storageImageDestination, error) {
directory, err := ioutil.TempDir(tmpdir.TemporaryDirectoryForBigFiles(), "storage")
if err != nil {
return nil, errors.Wrapf(err, "error creating a temporary directory")
}
image := &storageImageDestination{
imageRef: imageRef,
directory: directory,
blobDiffIDs: make(map[digest.Digest]digest.Digest),
fileSizes: make(map[digest.Digest]int64),
filenames: make(map[digest.Digest]string),
SignatureSizes: []int{},
}
return image, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/job_history.go#L321-L338
|
func cropResults(a []int64, max int64) ([]int64, int, int) {
res := []int64{}
firstIndex := -1
lastIndex := 0
for i, v := range a {
if v <= max {
res = append(res, v)
if firstIndex == -1 {
firstIndex = i
}
lastIndex = i
if len(res) >= resultsPerPage {
break
}
}
}
return res, firstIndex, lastIndex
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/russian/step1.go#L84-L118
|
func removeAdjectivalEnding(word *snowballword.SnowballWord) bool {
// Remove adjectival endings. Start by looking for
// an adjective ending.
//
suffix, _ := word.RemoveFirstSuffixIn(word.RVstart,
"ими", "ыми", "его", "ого", "ему", "ому", "ее", "ие",
"ые", "ое", "ей", "ий", "ый", "ой", "ем", "им", "ым",
"ом", "их", "ых", "ую", "юю", "ая", "яя", "ою", "ею",
)
if suffix != "" {
// We found an adjective ending. Remove optional participle endings.
//
newSuffix, newSuffixRunes := word.FirstSuffixIn(word.RVstart, len(word.RS),
"ивш", "ывш", "ующ",
"ем", "нн", "вш", "ющ", "щ",
)
switch newSuffix {
case "ем", "нн", "вш", "ющ", "щ":
// These are "Group 1" participle endings.
// Group 1 endings must follow а (a) or я (ia) in RV.
if precededByARinRV(word, len(newSuffixRunes)) == false {
newSuffix = ""
}
}
if newSuffix != "" {
word.RemoveLastNRunes(len(newSuffixRunes))
}
return true
}
return false
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/networks.go#L582-L594
|
func (c *Cluster) NetworkRename(oldName string, newName string) error {
id, _, err := c.NetworkGet(oldName)
if err != nil {
return err
}
err = c.Transaction(func(tx *ClusterTx) error {
_, err = tx.tx.Exec("UPDATE networks SET name=? WHERE id=?", newName, id)
return err
})
return err
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L63-L76
|
func (r *MapErrorRegistry) AddMessageError(code int, message string) (*Error, error) {
if _, ok := r.errors[code]; ok {
return nil, ErrErrorAlreadyRegistered
}
if _, ok := r.handlers[code]; ok {
return nil, ErrErrorAlreadyRegistered
}
err := &Error{
Message: message,
Code: code,
}
r.errors[code] = err
return err, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/reporter/reporter.go#L75-L78
|
func (c *Client) Report(pj *v1.ProwJob) ([]*v1.ProwJob, error) {
// TODO(krzyzacy): ditch ReportTemplate, and we can drop reference to config.Getter
return []*v1.ProwJob{pj}, report.Report(c.gc, c.config().Plank.ReportTemplate, *pj, c.config().GitHubReporter.JobTypesToReport)
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L177-L254
|
func New() *Glg {
g := &Glg{
levelCounter: new(uint32),
buffer: sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, bufferSize))
},
},
}
atomic.StoreUint32(g.levelCounter, uint32(FATAL))
for lev, log := range map[LEVEL]*logger{
// standard out
PRINT: {
std: os.Stdout,
color: Colorless,
isColor: true,
mode: STD,
},
LOG: {
std: os.Stdout,
color: Colorless,
isColor: true,
mode: STD,
},
INFO: {
std: os.Stdout,
color: Green,
isColor: true,
mode: STD,
},
DEBG: {
std: os.Stdout,
color: Purple,
isColor: true,
mode: STD,
},
OK: {
std: os.Stdout,
color: Cyan,
isColor: true,
mode: STD,
},
WARN: {
std: os.Stdout,
color: Orange,
isColor: true,
mode: STD,
},
// error out
ERR: {
std: os.Stderr,
color: Red,
isColor: true,
mode: STD,
},
FAIL: {
std: os.Stderr,
color: Red,
isColor: true,
mode: STD,
},
FATAL: {
std: os.Stderr,
color: Red,
isColor: true,
mode: STD,
},
} {
log.tag = lev.String()
log.updateMode()
g.logger.Store(lev, log)
}
return g
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_transport.go#L180-L182
|
func (ref dirReference) signaturePath(index int) string {
return filepath.Join(ref.path, fmt.Sprintf("signature-%d", index+1))
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/user/user_vm.go#L35-L38
|
func IsAdmin(c context.Context) bool {
h := internal.IncomingHeaders(c)
return h.Get("X-AppEngine-User-Is-Admin") == "1"
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L203-L218
|
func RespondWith(statusCode int, body interface{}, optionalHeader ...http.Header) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if len(optionalHeader) == 1 {
copyHeader(optionalHeader[0], w.Header())
}
w.WriteHeader(statusCode)
switch x := body.(type) {
case string:
w.Write([]byte(x))
case []byte:
w.Write(x)
default:
Expect(body).Should(BeNil(), "Invalid type for body. Should be string or []byte.")
}
}
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/watermark.go#L95-L97
|
func (w *WaterMark) DoneMany(indices []uint64) {
w.markCh <- mark{index: 0, indices: indices, done: true}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/backend.go#L103-L112
|
func recoverSnapshotBackend(cfg ServerConfig, oldbe backend.Backend, snapshot raftpb.Snapshot) (backend.Backend, error) {
var cIndex consistentIndex
kv := mvcc.New(cfg.Logger, oldbe, &lease.FakeLessor{}, &cIndex)
defer kv.Close()
if snapshot.Metadata.Index <= kv.ConsistentIndex() {
return oldbe, nil
}
oldbe.Close()
return openSnapshotBackend(cfg, snap.New(cfg.Logger, cfg.SnapDir()), snapshot)
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/request.go#L77-L90
|
func (r *Request) UrlFor(path string, queryParams map[string][]string) *url.URL {
baseUrl := r.BaseUrl()
baseUrl.Path = path
if queryParams != nil {
query := url.Values{}
for k, v := range queryParams {
for _, vv := range v {
query.Add(k, vv)
}
}
baseUrl.RawQuery = query.Encode()
}
return baseUrl
}
|
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/config.go#L87-L98
|
func NewConfig() *Config {
c := &Config{
Config: *sarama.NewConfig(),
}
c.Group.PartitionStrategy = StrategyRange
c.Group.Offsets.Retry.Max = 3
c.Group.Offsets.Synchronization.DwellTime = c.Consumer.MaxProcessingTime
c.Group.Session.Timeout = 30 * time.Second
c.Group.Heartbeat.Interval = 3 * time.Second
c.Config.Version = minVersion
return c
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L232-L234
|
func (t ConnectionType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.