_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2547-L2568
|
func (c *Client) ListMilestones(org, repo string) ([]Milestone, error) {
c.log("ListMilestones", org)
if c.fake {
return nil, nil
}
path := fmt.Sprintf("/repos/%s/%s/milestones", org, repo)
var milestones []Milestone
err := c.readPaginatedResults(
path,
acceptNone,
func() interface{} {
return &[]Milestone{}
},
func(obj interface{}) {
milestones = append(milestones, *(obj.(*[]Milestone))...)
},
)
if err != nil {
return nil, err
}
return milestones, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L282-L286
|
func (v SetPressureNotificationsSuppressedParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoMemory3(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/easyjson.go#L117-L121
|
func (v *RGBA) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCdp(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/coverage/diff/diff.go#L53-L74
|
func findChanges(baseList *calculation.CoverageList, newList *calculation.CoverageList) []*coverageChange {
var changes []*coverageChange
baseFilesMap := toMap(baseList)
for _, newCov := range newList.Group {
baseCov, ok := baseFilesMap[newCov.Name]
var baseRatio float32
if !ok {
baseRatio = -1
} else {
baseRatio = baseCov.Ratio()
}
newRatio := newCov.Ratio()
if isChangeSignificant(baseRatio, newRatio) {
changes = append(changes, &coverageChange{
name: newCov.Name,
baseRatio: baseRatio,
newRatio: newRatio,
})
}
}
return changes
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L557-L579
|
func (c APIClient) PutObject(_r io.Reader, tags ...string) (object *pfs.Object, _ int64, retErr error) {
r := grpcutil.ReaderWrapper{_r}
w, err := c.newPutObjectWriteCloser(tags...)
if err != nil {
return nil, 0, grpcutil.ScrubGRPC(err)
}
defer func() {
if err := w.Close(); err != nil && retErr == nil {
retErr = grpcutil.ScrubGRPC(err)
}
if retErr == nil {
object = w.object
}
}()
buf := grpcutil.GetBuffer()
defer grpcutil.PutBuffer(buf)
written, err := io.CopyBuffer(w, r, buf)
if err != nil {
return nil, 0, grpcutil.ScrubGRPC(err)
}
// return value set by deferred function
return nil, written, nil
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L250-L260
|
func (f *InclusiveRange) Index(value int) int {
closest := f.closestInRange(value, f.start, f.End(), f.step)
if closest != value {
return -1
}
idx := (value - f.start) / f.step
if idx < 0 {
idx *= -1
}
return idx
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/ctors.go#L295-L300
|
func (api *TelegramBotAPI) NewOutgoingCallbackQueryResponse(queryID string) *OutgoingCallbackQueryResponse {
return &OutgoingCallbackQueryResponse{
api: api,
CallbackQueryID: queryID,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2233-L2237
|
func (v GlobalLexicalScopeNamesParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime20(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/io/easyjson.go#L248-L252
|
func (v *ReadReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoIo2(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/resources_config_crd.go#L133-L139
|
func (in *ResourcesConfigCollection) SetItems(objects []Object) {
var items []*ResourcesConfigObject
for _, b := range objects {
items = append(items, b.(*ResourcesConfigObject))
}
in.Items = items
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L6817-L6821
|
func (v *AddRuleParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss64(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/logrusutil/logrusutil.go#L34-L45
|
func NewDefaultFieldsFormatter(
wrappedFormatter logrus.Formatter, defaultFields logrus.Fields,
) *DefaultFieldsFormatter {
res := &DefaultFieldsFormatter{
WrappedFormatter: wrappedFormatter,
DefaultFields: defaultFields,
}
if res.WrappedFormatter == nil {
res.WrappedFormatter = &logrus.JSONFormatter{}
}
return res
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/move.go#L191-L239
|
func moveClusterContainer(conf *config.Config, sourceResource, destResource, target string) error {
// Parse the source.
sourceRemote, sourceName, err := conf.ParseRemote(sourceResource)
if err != nil {
return err
}
// Parse the destination.
_, destName, err := conf.ParseRemote(destResource)
if err != nil {
return err
}
// Make sure we have a container or snapshot name.
if sourceName == "" {
return fmt.Errorf(i18n.G("You must specify a source container name"))
}
// The destination name is optional.
if destName == "" {
destName = sourceName
}
// Connect to the source host
source, err := conf.GetContainerServer(sourceRemote)
if err != nil {
return errors.Wrap(err, i18n.G("Failed to connect to cluster member"))
}
// Check that it's a cluster
if !source.IsClustered() {
return fmt.Errorf(i18n.G("The source LXD instance is not clustered"))
}
// The migrate API will do the right thing when passed a target.
source = source.UseTarget(target)
req := api.ContainerPost{Name: destName, Migration: true}
op, err := source.MigrateContainer(sourceName, req)
if err != nil {
return errors.Wrap(err, i18n.G("Migration API failure"))
}
err = op.Wait()
if err != nil {
return errors.Wrap(err, i18n.G("Migration operation failure"))
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/client/client.go#L112-L124
|
func (c *Client) Acquire(rtype, state, dest string) (*common.Resource, error) {
r, err := c.acquire(rtype, state, dest)
if err != nil {
return nil, err
}
c.lock.Lock()
defer c.lock.Unlock()
if r != nil {
c.storage.Add(*r)
}
return r, nil
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nodetable/table.go#L58-L60
|
func CompareNodeTable(a, b unsafe.Pointer) int {
return int(uintptr(a)) - int(uintptr(b))
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/english/common.go#L92-L103
|
func r1r2(word *snowballword.SnowballWord) (r1start, r2start int) {
specialPrefix, _ := word.FirstPrefix("gener", "commun", "arsen")
if specialPrefix != "" {
r1start = len(specialPrefix)
} else {
r1start = romance.VnvSuffix(word, isLowerVowel, 0)
}
r2start = romance.VnvSuffix(word, isLowerVowel, r1start)
return
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/get_apps_app_routes_parameters.go#L110-L113
|
func (o *GetAppsAppRoutesParams) WithApp(app string) *GetAppsAppRoutesParams {
o.SetApp(app)
return o
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L416-L465
|
func (m *Nitro) Close() {
// Wait until all snapshot iterators have finished
for s := m.snapshots.GetStats(); int(s.NodeCount) != 0; s = m.snapshots.GetStats() {
time.Sleep(time.Millisecond)
}
m.hasShutdown = true
// Acquire gc chan ownership
// This will make sure that no other goroutine will write to gcchan
for !atomic.CompareAndSwapInt32(&m.isGCRunning, 0, 1) {
time.Sleep(time.Millisecond)
}
close(m.gcchan)
buf := dbInstances.MakeBuf()
defer dbInstances.FreeBuf(buf)
dbInstances.Delete(unsafe.Pointer(m), CompareNitro, buf, &dbInstances.Stats)
if m.useMemoryMgmt {
buf := m.snapshots.MakeBuf()
defer m.snapshots.FreeBuf(buf)
m.shutdownWg1.Wait()
close(m.freechan)
m.shutdownWg2.Wait()
// Manually free up all nodes
iter := m.store.NewIterator(m.iterCmp, buf)
defer iter.Close()
var lastNode *skiplist.Node
iter.SeekFirst()
if iter.Valid() {
lastNode = iter.GetNode()
iter.Next()
}
for lastNode != nil {
m.freeItem((*Item)(lastNode.Item()))
m.store.FreeNode(lastNode, &m.store.Stats)
lastNode = nil
if iter.Valid() {
lastNode = iter.GetNode()
iter.Next()
}
}
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/net.go#L139-L177
|
func IsAddressCovered(address1, address2 string) bool {
if address1 == address2 {
return true
}
host1, port1, err := net.SplitHostPort(address1)
if err != nil {
return false
}
host2, port2, err := net.SplitHostPort(address2)
if err != nil {
return false
}
// If the ports are different, then address1 is clearly not covered by
// address2.
if port2 != port1 {
return false
}
// If address2 is using an IPv4 wildcard for the host, then address2 is
// only covered if it's an IPv4 address.
if host2 == "0.0.0.0" {
ip := net.ParseIP(host1)
if ip != nil && ip.To4() != nil {
return true
}
return false
}
// If address2 is using an IPv6 wildcard for the host, then address2 is
// always covered.
if host2 == "::" || host2 == "" {
return true
}
return false
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcauth/tcauth.go#L728-L731
|
func (auth *Auth) WebsocktunnelToken_SignedURL(wstAudience, wstClient string, duration time.Duration) (*url.URL, error) {
cd := tcclient.Client(*auth)
return (&cd).SignedURL("/websocktunnel/"+url.QueryEscape(wstAudience)+"/"+url.QueryEscape(wstClient), nil, duration)
}
|
https://github.com/ikawaha/kagome.ipadic/blob/fe03f87a0c7c32945d956fcfc934c3e11d5eb182/cmd/kagome/server/cmd.go#L54-L63
|
func newOption(w io.Writer, eh flag.ErrorHandling) (o *option) {
o = &option{
flagSet: flag.NewFlagSet(CommandName, eh),
}
// option settings
o.flagSet.StringVar(&o.http, "http", ":6060", "HTTP service address")
o.flagSet.StringVar(&o.udic, "udic", "", "user dictionary")
o.flagSet.StringVar(&o.sysdic, "sysdic", "normal", "system dictionary type (normal|simple)")
return
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/download.go#L75-L77
|
func (e *Engine) Download(ctx context.Context, name string, r io.Reader) Renderer {
return Download(ctx, name, r)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/maintenance/aws-janitor/resources/nat_gateway.go#L36-L61
|
func (NATGateway) MarkAndSweep(sess *session.Session, acct string, region string, set *Set) error {
svc := ec2.New(sess, &aws.Config{Region: aws.String(region)})
inp := &ec2.DescribeNatGatewaysInput{}
if err := svc.DescribeNatGatewaysPages(inp, func(page *ec2.DescribeNatGatewaysOutput, _ bool) bool {
for _, gw := range page.NatGateways {
g := &natGateway{
Account: acct,
Region: region,
ID: *gw.NatGatewayId,
}
if set.Mark(g) {
inp := &ec2.DeleteNatGatewayInput{NatGatewayId: gw.NatGatewayId}
if _, err := svc.DeleteNatGateway(inp); err != nil {
klog.Warningf("%v: delete failed: %v", g.ARN(), err)
}
}
}
return true
}); err != nil {
return err
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/lease_command.go#L28-L41
|
func NewLeaseCommand() *cobra.Command {
lc := &cobra.Command{
Use: "lease <subcommand>",
Short: "Lease related commands",
}
lc.AddCommand(NewLeaseGrantCommand())
lc.AddCommand(NewLeaseRevokeCommand())
lc.AddCommand(NewLeaseTimeToLiveCommand())
lc.AddCommand(NewLeaseListCommand())
lc.AddCommand(NewLeaseKeepAliveCommand())
return lc
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L527-L559
|
func (c *Cluster) StoragePoolCreate(poolName string, poolDescription string, poolDriver string, poolConfig map[string]string) (int64, error) {
var id int64
err := c.Transaction(func(tx *ClusterTx) error {
result, err := tx.tx.Exec("INSERT INTO storage_pools (name, description, driver, state) VALUES (?, ?, ?, ?)", poolName, poolDescription, poolDriver, storagePoolCreated)
if err != nil {
return err
}
id, err = result.LastInsertId()
if err != nil {
return err
}
// Insert a node-specific entry pointing to ourselves.
columns := []string{"storage_pool_id", "node_id"}
values := []interface{}{id, c.nodeID}
_, err = query.UpsertObject(tx.tx, "storage_pools_nodes", columns, values)
if err != nil {
return err
}
err = storagePoolConfigAdd(tx.tx, id, c.nodeID, poolConfig)
if err != nil {
return err
}
return nil
})
if err != nil {
id = -1
}
return id, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L282-L289
|
func StorageVolumeConfigClear(tx *sql.Tx, volumeID int64) error {
_, err := tx.Exec("DELETE FROM storage_volumes_config WHERE storage_volume_id=?", volumeID)
if err != nil {
return err
}
return nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6598-L6606
|
func (u StellarMessage) MustTxSetHash() Uint256 {
val, ok := u.GetTxSetHash()
if !ok {
panic("arm TxSetHash is not set")
}
return val
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/domdebugger.go#L50-L53
|
func (p GetEventListenersParams) WithPierce(pierce bool) *GetEventListenersParams {
p.Pierce = pierce
return &p
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/util.go#L94-L130
|
func endpointMemoryMetrics(host string) float64 {
residentMemoryKey := "process_resident_memory_bytes"
var residentMemoryValue string
if !strings.HasPrefix(host, `http://`) {
host = "http://" + host
}
url := host + "/metrics"
resp, err := http.Get(url)
if err != nil {
fmt.Println(fmt.Sprintf("fetch error: %v", err))
return 0.0
}
byts, readerr := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if readerr != nil {
fmt.Println(fmt.Sprintf("fetch error: reading %s: %v", url, readerr))
return 0.0
}
for _, line := range strings.Split(string(byts), "\n") {
if strings.HasPrefix(line, residentMemoryKey) {
residentMemoryValue = strings.TrimSpace(strings.TrimPrefix(line, residentMemoryKey))
break
}
}
if residentMemoryValue == "" {
fmt.Println(fmt.Sprintf("could not find: %v", residentMemoryKey))
return 0.0
}
residentMemoryBytes, parseErr := strconv.ParseFloat(residentMemoryValue, 64)
if parseErr != nil {
fmt.Println(fmt.Sprintf("parse error: %v", parseErr))
return 0.0
}
return residentMemoryBytes
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L54-L63
|
func (p *CollectClassNamesFromSubtreeParams) Do(ctx context.Context) (classNames []string, err error) {
// execute
var res CollectClassNamesFromSubtreeReturns
err = cdp.Execute(ctx, CommandCollectClassNamesFromSubtree, p, &res)
if err != nil {
return nil, err
}
return res.ClassNames, nil
}
|
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/shell.go#L203-L206
|
func (s *Shell) Pins() (map[string]PinInfo, error) {
var raw struct{ Keys map[string]PinInfo }
return raw.Keys, s.Request("pin/ls").Exec(context.Background(), &raw)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L156-L167
|
func (m *Member) Defrag() error {
cli, err := m.CreateEtcdClient()
if err != nil {
return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint)
}
defer cli.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
_, err = cli.Defragment(ctx, m.EtcdClientEndpoint)
cancel()
return err
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L193-L195
|
func (m *Message) SetBody(contentType, body string, settings ...PartSetting) {
m.SetBodyWriter(contentType, newCopier(body), settings...)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/docker/config/config.go#L120-L144
|
func getPathToAuth(sys *types.SystemContext) (string, error) {
if sys != nil {
if sys.AuthFilePath != "" {
return sys.AuthFilePath, nil
}
if sys.RootForImplicitAbsolutePaths != "" {
return filepath.Join(sys.RootForImplicitAbsolutePaths, fmt.Sprintf(defaultPerUIDPathFormat, os.Getuid())), nil
}
}
runtimeDir := os.Getenv("XDG_RUNTIME_DIR")
if runtimeDir != "" {
// This function does not in general need to separately check that the returned path exists; that’s racy, and callers will fail accessing the file anyway.
// We are checking for os.IsNotExist here only to give the user better guidance what to do in this special case.
_, err := os.Stat(runtimeDir)
if os.IsNotExist(err) {
// This means the user set the XDG_RUNTIME_DIR variable and either forgot to create the directory
// or made a typo while setting the environment variable,
// so return an error referring to $XDG_RUNTIME_DIR instead of xdgRuntimeDirPath inside.
return "", errors.Wrapf(err, "%q directory set by $XDG_RUNTIME_DIR does not exist. Either create the directory or unset $XDG_RUNTIME_DIR.", runtimeDir)
} // else ignore err and let the caller fail accessing xdgRuntimeDirPath.
return filepath.Join(runtimeDir, xdgRuntimeDirPath), nil
}
return fmt.Sprintf(defaultPerUIDPathFormat, os.Getuid()), nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/logger.go#L34-L39
|
func (opt *Options) Errorf(format string, v ...interface{}) {
if opt.Logger == nil {
return
}
opt.Logger.Errorf(format, v...)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/yaml/config.go#L44-L91
|
func NewConfig(fpath string) (*clientv3.Config, error) {
b, err := ioutil.ReadFile(fpath)
if err != nil {
return nil, err
}
yc := &yamlConfig{}
err = yaml.Unmarshal(b, yc)
if err != nil {
return nil, err
}
if yc.InsecureTransport {
return &yc.Config, nil
}
var (
cert *tls.Certificate
cp *x509.CertPool
)
if yc.Certfile != "" && yc.Keyfile != "" {
cert, err = tlsutil.NewCert(yc.Certfile, yc.Keyfile, nil)
if err != nil {
return nil, err
}
}
if yc.TrustedCAfile != "" {
cp, err = tlsutil.NewCertPool([]string{yc.TrustedCAfile})
if err != nil {
return nil, err
}
}
tlscfg := &tls.Config{
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: yc.InsecureSkipTLSVerify,
RootCAs: cp,
}
if cert != nil {
tlscfg.Certificates = []tls.Certificate{*cert}
}
yc.Config.TLS = tlscfg
return &yc.Config, nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/template.go#L177-L180
|
func Template(c string, names ...string) Renderer {
e := New(Options{})
return e.Template(c, names...)
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/smtp.go#L73-L139
|
func (d *Dialer) Dial() (SendCloser, error) {
conn, err := NetDialTimeout("tcp", addr(d.Host, d.Port), d.Timeout)
if err != nil {
return nil, err
}
if d.SSL {
conn = tlsClient(conn, d.tlsConfig())
}
c, err := smtpNewClient(conn, d.Host)
if err != nil {
return nil, err
}
if d.Timeout > 0 {
conn.SetDeadline(time.Now().Add(d.Timeout))
}
if d.LocalName != "" {
if err := c.Hello(d.LocalName); err != nil {
return nil, err
}
}
if !d.SSL && d.StartTLSPolicy != NoStartTLS {
ok, _ := c.Extension("STARTTLS")
if !ok && d.StartTLSPolicy == MandatoryStartTLS {
err := StartTLSUnsupportedError{
Policy: d.StartTLSPolicy}
return nil, err
}
if ok {
if err := c.StartTLS(d.tlsConfig()); err != nil {
c.Close()
return nil, err
}
}
}
if d.Auth == nil && d.Username != "" {
if ok, auths := c.Extension("AUTH"); ok {
if strings.Contains(auths, "CRAM-MD5") {
d.Auth = smtp.CRAMMD5Auth(d.Username, d.Password)
} else if strings.Contains(auths, "LOGIN") &&
!strings.Contains(auths, "PLAIN") {
d.Auth = &loginAuth{
username: d.Username,
password: d.Password,
host: d.Host,
}
} else {
d.Auth = smtp.PlainAuth("", d.Username, d.Password, d.Host)
}
}
}
if d.Auth != nil {
if err = c.Auth(d.Auth); err != nil {
c.Close()
return nil, err
}
}
return &smtpSender{c, conn, d}, nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L279-L283
|
func NewAccountId(aType CryptoKeyType, value interface{}) (result AccountId, err error) {
u, err := NewPublicKey(aType, value)
result = AccountId(u)
return
}
|
https://github.com/Jeffail/tunny/blob/4921fff29480bad359ad2fb3271fb461c8ffe1fc/tunny.go#L131-L137
|
func NewFunc(n int, f func(interface{}) interface{}) *Pool {
return New(n, func() Worker {
return &closureWorker{
processor: f,
}
})
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/dockercommon/commands.go#L22-L24
|
func ArchiveDeployCmds(app provision.App, archiveURL string) []string {
return buildCmds(app, "deploy", "archive", archiveURL)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L152-L156
|
func (v *StackTraceID) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime1(&r, v)
return r.Error()
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/param_analyzer.go#L371-L379
|
func nativeNameFromPath(path string) string {
native := path
matches := childPathRegexp.FindStringSubmatch(path)
if matches != nil {
native = matches[1]
}
return native
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L83-L85
|
func (gc *GraphicContext) StrokeString(text string) (cursor float64) {
return gc.StrokeStringAt(text, 0, 0)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L241-L243
|
func (x *Index) Delete(c context.Context, id string) error {
return x.DeleteMulti(c, []string{id})
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/worker/simple.go#L109-L119
|
func (w Simple) PerformIn(job Job, d time.Duration) error {
go func() {
select {
case <-time.After(d):
w.Perform(job)
case <-w.ctx.Done():
w.cancel()
}
}()
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/docker_schema1.go#L102-L104
|
func (m *manifestSchema1) UpdatedImageNeedsLayerDiffIDs(options types.ManifestUpdateOptions) bool {
return (options.ManifestMIMEType == manifest.DockerV2Schema2MediaType || options.ManifestMIMEType == imgspecv1.MediaTypeImageManifest)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/common/common.go#L105-L111
|
func NewResourcesFromConfig(e ResourceEntry) []Resource {
var resources []Resource
for _, name := range e.Names {
resources = append(resources, NewResource(name, e.Type, e.State, "", time.Time{}))
}
return resources
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/definition.go#L207-L244
|
func (a *APIAnalyzer) addType(ec EvalCtx, dt *gen.ObjectDataType, r Ref) {
a.api.NeedJSON = true
if a.refByType[dt.TypeName] == r.ID() {
return
}
if other, ok := a.api.Types[dt.TypeName]; ok {
if !ec.IsResult {
// If its an input parameter, fix the collision by amending this types name
dt.TypeName += "Param"
if a.refByType[dt.TypeName] == r.ID() {
return
}
}
oldFields := []string{}
newFields := []string{}
for _, f := range other.Fields {
oldFields = append(oldFields, f.Name)
}
for _, f := range dt.Fields {
newFields = append(newFields, f.Name)
}
use := "Old"
if len(newFields) > len(oldFields) {
use = "New"
}
if strings.Join(oldFields, ",") != strings.Join(newFields, ",") {
warn("Warning: Type collision when adding new type %s!\n New: id %s fields %v\n Old: id %s fields %v\n Using %s, which has more fields\n",
dt.TypeName, r.ID(), newFields, a.refByType[dt.TypeName], oldFields, use)
}
if use == "Old" {
return
}
}
dbg("DEBUG NEW TYPE %s\n", prettify(dt))
a.refByType[dt.TypeName] = r.ID()
a.api.Types[dt.TypeName] = dt
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/router.go#L21-L30
|
func MakeRouter(routes ...*Route) (App, error) {
r := &router{
Routes: routes,
}
err := r.start()
if err != nil {
return nil, err
}
return r, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/admin/server/server.go#L14-L21
|
func NewAPIServer(address string, storageRoot string, clusterInfo *admin.ClusterInfo) APIServer {
return &apiServer{
Logger: log.NewLogger("admin.API"),
address: address,
storageRoot: storageRoot,
clusterInfo: clusterInfo,
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/storage.go#L239-L271
|
func (ms *MemoryStorage) Append(entries []pb.Entry) error {
if len(entries) == 0 {
return nil
}
ms.Lock()
defer ms.Unlock()
first := ms.firstIndex()
last := entries[0].Index + uint64(len(entries)) - 1
// shortcut if there is no new entry.
if last < first {
return nil
}
// truncate compacted entries
if first > entries[0].Index {
entries = entries[first-entries[0].Index:]
}
offset := entries[0].Index - ms.ents[0].Index
switch {
case uint64(len(ms.ents)) > offset:
ms.ents = append([]pb.Entry{}, ms.ents[:offset]...)
ms.ents = append(ms.ents, entries...)
case uint64(len(ms.ents)) == offset:
ms.ents = append(ms.ents, entries...)
default:
raftLogger.Panicf("missing log entry [last: %d, append at: %d]",
ms.lastIndex(), entries[0].Index)
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/profiler.go#L254-L263
|
func (p *TakePreciseCoverageParams) Do(ctx context.Context) (result []*ScriptCoverage, err error) {
// execute
var res TakePreciseCoverageReturns
err = cdp.Execute(ctx, CommandTakePreciseCoverage, nil, &res)
if err != nil {
return nil, err
}
return res.Result, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/fetcher/client.go#L188-L227
|
func (client *Client) FetchIssueEvents(issueID int, latest *int, c chan *github.IssueEvent) {
opt := &github.ListOptions{PerPage: 100}
githubClient, err := client.getGitHubClient()
if err != nil {
close(c)
glog.Error(err)
return
}
count := 0
for {
client.limitsCheckAndWait()
events, resp, err := githubClient.Issues.ListIssueEvents(
context.Background(),
client.Org,
client.Project,
issueID,
opt,
)
if err != nil {
glog.Errorf("ListIssueEvents failed: %s. Retrying...", err)
time.Sleep(time.Second)
continue
}
for _, event := range events {
c <- event
count++
}
if resp.NextPage == 0 || (latest != nil && hasID(events, *latest)) {
break
}
opt.Page = resp.NextPage
}
glog.Infof("Fetched %d events.", count)
close(c)
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/structs.go#L35-L40
|
func (p valuePointer) Encode(b []byte) []byte {
binary.BigEndian.PutUint32(b[:4], p.Fid)
binary.BigEndian.PutUint32(b[4:8], p.Len)
binary.BigEndian.PutUint32(b[8:12], p.Offset)
return b[:vptrSize]
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/introspection.go#L505-L534
|
func (ch *Channel) registerInternal() {
endpoints := []struct {
name string
handler func([]byte) interface{}
}{
{"_gometa_introspect", ch.handleIntrospection},
{"_gometa_runtime", handleInternalRuntime},
}
tchanSC := ch.GetSubChannel("tchannel")
for _, ep := range endpoints {
// We need ep in our closure.
ep := ep
handler := func(ctx context.Context, call *InboundCall) {
var arg2, arg3 []byte
if err := NewArgReader(call.Arg2Reader()).Read(&arg2); err != nil {
return
}
if err := NewArgReader(call.Arg3Reader()).Read(&arg3); err != nil {
return
}
if err := NewArgWriter(call.Response().Arg2Writer()).Write(nil); err != nil {
return
}
NewArgWriter(call.Response().Arg3Writer()).WriteJSON(ep.handler(arg3))
}
ch.Register(HandlerFunc(handler), ep.name)
tchanSC.Register(HandlerFunc(handler), ep.name)
}
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L250-L269
|
func (v *VM) GuestOS() (string, error) {
var err C.VixError = C.VIX_OK
var os *C.char
err = C.get_property(v.handle,
C.VIX_PROPERTY_VM_GUESTOS,
unsafe.Pointer(&os))
defer C.Vix_FreeBuffer(unsafe.Pointer(os))
if C.VIX_OK != err {
return "", &Error{
Operation: "vm.GuestOS",
Code: int(err & 0xFFFF),
Text: C.GoString(C.Vix_GetErrorText(err, nil)),
}
}
return C.GoString(os), nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L982-L986
|
func (v *StopRuleUsageTrackingParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss7(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L6505-L6509
|
func (v EventRequestServedFromCache) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork51(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxtype.go#L526-L528
|
func (r *Rect) TL() Point {
return Point{int(r.x), int(r.y)}
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/recorder.go#L45-L52
|
func (w *recorderResponseWriter) WriteHeader(code int) {
w.ResponseWriter.WriteHeader(code)
if w.wroteHeader {
return
}
w.statusCode = code
w.wroteHeader = true
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L1301-L1306
|
func WriteDashboardAssets(encoder Encoder, opts *AssetOpts) error {
if err := encoder.Encode(DashService(opts)); err != nil {
return err
}
return encoder.Encode(DashDeployment(opts))
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4603-L4610
|
func NewStellarValueExt(v int32, value interface{}) (result StellarValueExt, err error) {
result.V = v
switch int32(v) {
case 0:
// void
}
return
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/image/image.go#L31-L54
|
func ServingURL(c context.Context, key appengine.BlobKey, opts *ServingURLOptions) (*url.URL, error) {
req := &pb.ImagesGetUrlBaseRequest{
BlobKey: (*string)(&key),
}
if opts != nil && opts.Secure {
req.CreateSecureUrl = &opts.Secure
}
res := &pb.ImagesGetUrlBaseResponse{}
if err := internal.Call(c, "images", "GetUrlBase", req, res); err != nil {
return nil, err
}
// The URL may have suffixes added to dynamically resize or crop:
// - adding "=s32" will serve the image resized to 32 pixels, preserving the aspect ratio.
// - adding "=s32-c" is the same as "=s32" except it will be cropped.
u := *res.Url
if opts != nil && opts.Size > 0 {
u += fmt.Sprintf("=s%d", opts.Size)
if opts.Crop {
u += "-c"
}
}
return url.Parse(u)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L634-L637
|
func (c *Cluster) ImageAliasRename(id int, name string) error {
err := exec(c.db, "UPDATE images_aliases SET name=? WHERE id=?", name, id)
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L673-L677
|
func (v *SetInspectModeParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoOverlay8(&r, v)
return r.Error()
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/event.go#L220-L248
|
func eventBlockRemove(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
if !permission.Check(t, permission.PermEventBlockRemove) {
return permission.ErrUnauthorized
}
uuid := r.URL.Query().Get(":uuid")
if !bson.IsObjectIdHex(uuid) {
msg := fmt.Sprintf("uuid parameter is not ObjectId: %s", uuid)
return &errors.HTTP{Code: http.StatusBadRequest, Message: msg}
}
objID := bson.ObjectIdHex(uuid)
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypeEventBlock, Value: objID.Hex()},
Kind: permission.PermEventBlockRemove,
Owner: t,
CustomData: []map[string]interface{}{
{"name": "ID", "value": objID.Hex()},
},
Allowed: event.Allowed(permission.PermEventBlockReadEvents),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
err = event.RemoveBlock(objID)
if _, ok := err.(*event.ErrActiveEventBlockNotFound); ok {
return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/types.go#L142-L144
|
func (t RecordMode) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/assetfs/filesystem.go#L82-L88
|
func (fs *AssetFileSystem) NameSpace(nameSpace string) Interface {
if fs.nameSpacedFS == nil {
fs.nameSpacedFS = map[string]Interface{}
}
fs.nameSpacedFS[nameSpace] = &AssetFileSystem{}
return fs.nameSpacedFS[nameSpace]
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L1129-L1133
|
func (v *GetBrowserSamplingProfileReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoMemory12(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L6548-L6552
|
func (v CollectClassNamesReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss61(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L601-L670
|
func (c *ClusterTx) ProfileCreate(object Profile) (int64, error) {
// Check if a profile with the same key exists.
exists, err := c.ProfileExists(object.Project, object.Name)
if err != nil {
return -1, errors.Wrap(err, "Failed to check for duplicates")
}
if exists {
return -1, fmt.Errorf("This profile already exists")
}
args := make([]interface{}, 3)
// Populate the statement arguments.
args[0] = object.Project
args[1] = object.Name
args[2] = object.Description
// Prepared statement to use.
stmt := c.stmt(profileCreate)
// Execute the statement.
result, err := stmt.Exec(args...)
if err != nil {
return -1, errors.Wrap(err, "Failed to create profile")
}
id, err := result.LastInsertId()
if err != nil {
return -1, errors.Wrap(err, "Failed to fetch profile ID")
}
// Insert config reference.
stmt = c.stmt(profileCreateConfigRef)
for key, value := range object.Config {
_, err := stmt.Exec(id, key, value)
if err != nil {
return -1, errors.Wrap(err, "Insert config for profile")
}
}
// Insert devices reference.
for name, config := range object.Devices {
typ, ok := config["type"]
if !ok {
return -1, fmt.Errorf("No type for device %s", name)
}
typCode, err := dbDeviceTypeToInt(typ)
if err != nil {
return -1, errors.Wrapf(err, "Device type code for %s", typ)
}
stmt = c.stmt(profileCreateDevicesRef)
result, err := stmt.Exec(id, name, typCode)
if err != nil {
return -1, errors.Wrapf(err, "Insert device %s", name)
}
deviceID, err := result.LastInsertId()
if err != nil {
return -1, errors.Wrap(err, "Failed to fetch device ID")
}
stmt = c.stmt(profileCreateDevicesConfigRef)
for key, value := range config {
_, err := stmt.Exec(deviceID, key, value)
if err != nil {
return -1, errors.Wrap(err, "Insert config for profile")
}
}
}
return id, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/database/easyjson.go#L819-L823
|
func (v *Database) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDatabase8(&r, v)
return r.Error()
}
|
https://github.com/tehnerd/gnl2go/blob/101b5c6e2d44eb00fbfe85917ffc0bf95249977b/gnl2go.go#L447-L530
|
func DeserializeSerDes(serdesType string, list []byte) (SerDes, error) {
switch serdesType {
case "U8Type":
attr := new(U8Type)
err := attr.Deserialize(list)
if err != nil {
return nil, err
}
return attr, nil
case "U16Type":
attr := new(U16Type)
err := attr.Deserialize(list)
if err != nil {
return nil, err
}
return attr, nil
case "U32Type":
attr := new(U32Type)
err := attr.Deserialize(list)
if err != nil {
return nil, err
}
return attr, nil
case "U64Type":
attr := new(U64Type)
err := attr.Deserialize(list)
if err != nil {
return nil, err
}
return attr, nil
case "I32Type":
attr := new(I32Type)
err := attr.Deserialize(list)
if err != nil {
return nil, err
}
return attr, nil
case "Net16Type":
attr := new(Net16Type)
err := attr.Deserialize(list)
if err != nil {
return nil, err
}
return attr, nil
case "Net32Type":
attr := new(Net32Type)
err := attr.Deserialize(list)
if err != nil {
return nil, err
}
return attr, nil
case "NulStringType":
attr := new(NulStringType)
err := attr.Deserialize(list)
if err != nil {
return nil, err
}
return attr, nil
case "IgnoreType":
attr := new(IgnoreType)
return attr, nil
case "BinaryType":
attr := new(BinaryType)
//binary always return nil, no point to check err != nil
attr.Deserialize(list)
return attr, nil
/*
XXX(tehnerd): dangerous assumption that we either have basic types (above) or it's
a nested attribute's list. havent tested in prod yet
*/
default:
atl, exists := ATLName2ATL[serdesType]
if !exists {
return nil, fmt.Errorf("serdes doesnt exists. type: %v\n", serdesType)
}
attr := CreateAttrListType(atl)
err := attr.Deserialize(list)
if err != nil {
return nil, err
}
return &attr, nil
}
return nil, nil
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcevents/tcevents.go#L96-L100
|
func (events *Events) Ping() error {
cd := tcclient.Client(*events)
_, _, err := (&cd).APICall(nil, "GET", "/ping", nil, nil)
return err
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/pretty/pretty.go#L13-L17
|
func UnescapeHTML(s string) string {
s = strings.Replace(s, "\\u003c", "<", -1)
s = strings.Replace(s, "\\u003e", ">", -1)
return s
}
|
https://github.com/scorredoira/email/blob/c1787f8317a847a7adc13673be80723268e6e639/email.go#L137-L222
|
func (m *Message) Bytes() []byte {
buf := bytes.NewBuffer(nil)
buf.WriteString("From: " + m.From.String() + "\r\n")
t := time.Now()
buf.WriteString("Date: " + t.Format(time.RFC1123Z) + "\r\n")
buf.WriteString("To: " + strings.Join(m.To, ",") + "\r\n")
if len(m.Cc) > 0 {
buf.WriteString("Cc: " + strings.Join(m.Cc, ",") + "\r\n")
}
//fix Encode
var coder = base64.StdEncoding
var subject = "=?UTF-8?B?" + coder.EncodeToString([]byte(m.Subject)) + "?="
buf.WriteString("Subject: " + subject + "\r\n")
if len(m.ReplyTo) > 0 {
buf.WriteString("Reply-To: " + m.ReplyTo + "\r\n")
}
buf.WriteString("MIME-Version: 1.0\r\n")
// Add custom headers
if len(m.Headers) > 0 {
for _, header := range m.Headers {
buf.WriteString(fmt.Sprintf("%s: %s\r\n", header.Key, header.Value))
}
}
boundary := "f46d043c813270fc6b04c2d223da"
if len(m.Attachments) > 0 {
buf.WriteString("Content-Type: multipart/mixed; boundary=" + boundary + "\r\n")
buf.WriteString("\r\n--" + boundary + "\r\n")
}
buf.WriteString(fmt.Sprintf("Content-Type: %s; charset=utf-8\r\n\r\n", m.BodyContentType))
buf.WriteString(m.Body)
buf.WriteString("\r\n")
if len(m.Attachments) > 0 {
for _, attachment := range m.Attachments {
buf.WriteString("\r\n\r\n--" + boundary + "\r\n")
if attachment.Inline {
buf.WriteString("Content-Type: message/rfc822\r\n")
buf.WriteString("Content-Disposition: inline; filename=\"" + attachment.Filename + "\"\r\n\r\n")
buf.Write(attachment.Data)
} else {
ext := filepath.Ext(attachment.Filename)
mimetype := mime.TypeByExtension(ext)
if mimetype != "" {
mime := fmt.Sprintf("Content-Type: %s\r\n", mimetype)
buf.WriteString(mime)
} else {
buf.WriteString("Content-Type: application/octet-stream\r\n")
}
buf.WriteString("Content-Transfer-Encoding: base64\r\n")
buf.WriteString("Content-Disposition: attachment; filename=\"=?UTF-8?B?")
buf.WriteString(coder.EncodeToString([]byte(attachment.Filename)))
buf.WriteString("?=\"\r\n\r\n")
b := make([]byte, base64.StdEncoding.EncodedLen(len(attachment.Data)))
base64.StdEncoding.Encode(b, attachment.Data)
// write base64 content in lines of up to 76 chars
for i, l := 0, len(b); i < l; i++ {
buf.WriteByte(b[i])
if (i+1)%76 == 0 {
buf.WriteString("\r\n")
}
}
}
buf.WriteString("\r\n--" + boundary)
}
buf.WriteString("--")
}
return buf.Bytes()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L895-L899
|
func (v *SetBreakpointsActiveParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger9(&r, v)
return r.Error()
}
|
https://github.com/fujiwara/fluent-agent-hydra/blob/f5c1c02a0b892cf5c08918ec2ff7bbca71cc7e4f/hydra/in_tail.go#L148-L204
|
func (t *InTail) Run(c *Context) {
c.InputProcess.Add(1)
defer c.InputProcess.Done()
t.messageCh = c.MessageCh
t.monitorCh = c.MonitorCh
c.StartProcess.Done()
if t.eventCh == nil {
err := t.TailStdin(c)
if err != nil {
if _, ok := err.(Signal); ok {
log.Println("[info]", err)
} else {
log.Println("[error]", err)
}
return
}
}
log.Println("[info] Trying trail file", t.filename)
f, err := t.newTrailFile(SEEK_TAIL, c)
if err != nil {
if _, ok := err.(Signal); ok {
log.Println("[info]", err)
} else {
log.Println("[error]", err)
}
return
}
for {
for {
err := t.watchFileEvent(f, c)
if err != nil {
if _, ok := err.(Signal); ok {
log.Println("[info]", err)
return
} else {
log.Println("[warning]", err)
break
}
}
}
// re open file
var err error
f, err = t.newTrailFile(SEEK_HEAD, c)
if err != nil {
if _, ok := err.(Signal); ok {
log.Println("[info]", err)
} else {
log.Println("[error]", err)
}
return
}
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L235-L250
|
func (m *Member) WriteHealthKey() error {
cli, err := m.CreateEtcdClient()
if err != nil {
return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint)
}
defer cli.Close()
// give enough time-out in case expensive requests (range/delete) are pending
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_, err = cli.Put(ctx, "health", "good")
cancel()
if err != nil {
return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint)
}
return nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/actions/actions.go#L16-L25
|
func New(opts *Options) (*genny.Generator, error) {
g := genny.New()
if err := opts.Validate(); err != nil {
return g, err
}
g.RunFn(construct(opts))
return g, nil
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gomega_dsl.go#L101-L110
|
func InterceptGomegaFailures(f func()) []string {
originalHandler := globalFailWrapper.Fail
failures := []string{}
RegisterFailHandler(func(message string, callerSkip ...int) {
failures = append(failures, message)
})
f()
RegisterFailHandler(originalHandler)
return failures
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L7684-L7688
|
func (v AddCompilationCacheParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage85(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/platform.go#L205-L229
|
func platformInfo(w http.ResponseWriter, r *http.Request, t auth.Token) error {
name := r.URL.Query().Get(":name")
canUsePlat := permission.Check(t, permission.PermPlatformUpdate) ||
permission.Check(t, permission.PermPlatformCreate)
if !canUsePlat {
return permission.ErrUnauthorized
}
platform, err := servicemanager.Platform.FindByName(name)
if err == appTypes.ErrPlatformNotFound {
return &tErrors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
if err != nil {
return err
}
images, err := servicemanager.PlatformImage.ListImagesOrDefault(name)
if err != nil {
return err
}
msg := map[string]interface{}{
"platform": platform,
"images": images,
}
w.Header().Set("Content-Type", "application/json")
return json.NewEncoder(w).Encode(msg)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/profiler.go#L212-L214
|
func (p *StopPreciseCoverageParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandStopPreciseCoverage, nil, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L361-L370
|
func (p *GetBoxModelParams) Do(ctx context.Context) (model *BoxModel, err error) {
// execute
var res GetBoxModelReturns
err = cdp.Execute(ctx, CommandGetBoxModel, p, &res)
if err != nil {
return nil, err
}
return res.Model, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L637-L640
|
func (p SearchInResponseBodyParams) WithIsRegex(isRegex bool) *SearchInResponseBodyParams {
p.IsRegex = isRegex
return &p
}
|
https://github.com/fujiwara/fluent-agent-hydra/blob/f5c1c02a0b892cf5c08918ec2ff7bbca71cc7e4f/hydra/out_forward.go#L24-L40
|
func NewOutForward(configServers []*ConfigServer) (*OutForward, error) {
loggers := make([]*fluent.Fluent, len(configServers))
for i, server := range configServers {
logger, err := fluent.New(fluent.Config{Server: server.Address()})
if err != nil {
log.Println("[warning]", err)
} else {
log.Println("[info] Server", server.Address(), "connected")
}
loggers[i] = logger
logger.Send([]byte{})
}
return &OutForward{
loggers: loggers,
sent: 0,
}, nil
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L280-L289
|
func FileSequence_Copy(id FileSeqId) FileSeqId {
fs, ok := sFileSeqs.Get(id)
if !ok {
return 0
}
copyFs, _ := fileseq.NewFileSequence(fs.String())
copyId := sFileSeqs.Add(copyFs)
return copyId
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L123-L133
|
func (m *Mapping) RefFields() []*Field {
fields := []*Field{}
for _, field := range m.Fields {
if field.Type.Code == TypeSlice || field.Type.Code == TypeMap {
fields = append(fields, field)
}
}
return fields
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L639-L643
|
func (v PrepareForLeakDetectionParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoMemory6(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L184-L189
|
func (p *Page) ClearCookies() error {
if err := p.session.DeleteCookies(); err != nil {
return fmt.Errorf("failed to clear cookies: %s", err)
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L951-L955
|
func (v SetFontFamiliesParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage10(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/docker_schema2.go#L168-L175
|
func Schema2FromComponents(config Schema2Descriptor, layers []Schema2Descriptor) *Schema2 {
return &Schema2{
SchemaVersion: 2,
MediaType: DockerV2Schema2MediaType,
ConfigDescriptor: config,
LayersDescriptors: layers,
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4869-L4877
|
func (u LedgerUpgrade) MustNewBaseFee() Uint32 {
val, ok := u.GetNewBaseFee()
if !ok {
panic("arm NewBaseFee is not set")
}
return val
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1959-L1963
|
func (v CreateTargetReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget22(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L73-L77
|
func (v SetShowViewportSizeOnResizeParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoOverlay(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/adamzy/cedar-go/blob/80a9c64b256db37ac20aff007907c649afb714f1/api.go#L201-L214
|
func (da *Cedar) PrefixPredict(key []byte, num int) (ids []int) {
root, err := da.Jump(key, 0)
if err != nil {
return
}
for from, err := da.begin(root); err == nil; from, err = da.next(from, root) {
ids = append(ids, from)
num--
if num == 0 {
return
}
}
return
}
|
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nsqlookup/consul.go#L61-L89
|
func NewConsulEngine(config ConsulConfig) *ConsulEngine {
if len(config.Address) == 0 {
config.Address = DefaultConsulAddress
}
if len(config.Namespace) == 0 {
config.Namespace = DefaultConsulNamespace
}
if config.NodeTimeout == 0 {
config.NodeTimeout = DefaultLocalEngineNodeTimeout
}
if config.TombstoneTimeout == 0 {
config.TombstoneTimeout = DefaultLocalEngineTombstoneTimeout
}
if !strings.Contains(config.Address, "://") {
config.Address = "http://" + config.Address
}
return &ConsulEngine{
client: http.Client{Transport: config.Transport},
address: config.Address,
namespace: config.Namespace,
nodeTimeout: config.NodeTimeout,
tombTimeout: config.TombstoneTimeout,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L134-L143
|
func (p *CreateStyleSheetParams) Do(ctx context.Context) (styleSheetID StyleSheetID, err error) {
// execute
var res CreateStyleSheetReturns
err = cdp.Execute(ctx, CommandCreateStyleSheet, p, &res)
if err != nil {
return "", err
}
return res.StyleSheetID, nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.