input
stringlengths 24
2.11k
| output
stringlengths 7
948
|
---|---|
package lua
type Metatable struct {
IndexFunc Function
NewindexFunc Function
TostringFunc Function
GCFunc Function
}
func (this *Metatable) Index() Function {
return this.IndexFunc
}
func (this *Metatable) Newindex() Function {
return this.NewindexFunc
}
func (this *Metatable) GC() Function {
return this.GCFunc
}
func (this *Metatable) Tostring() Function | {
return this.TostringFunc
} |
package external
import (
"github.com/Aptomi/aptomi/pkg/external/secrets"
"github.com/Aptomi/aptomi/pkg/external/users"
)
type Data struct {
UserLoader users.UserLoader
SecretLoader secrets.SecretLoader
}
func NewData(userLoader users.UserLoader, secretLoader secrets.SecretLoader) *Data | {
return &Data{
UserLoader: userLoader,
SecretLoader: secretLoader,
}
} |
package category
import (
"context"
"flag"
"fmt"
"io"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vapi/tags"
)
type ls struct {
*flags.ClientFlag
*flags.OutputFlag
}
func init() {
cli.Register("tags.category.ls", &ls{})
}
func (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
cmd.OutputFlag.Register(ctx, f)
}
func (cmd *ls) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
return cmd.OutputFlag.Process(ctx)
}
type lsResult []tags.Category
func (r lsResult) Write(w io.Writer) error {
for _, c := range r {
fmt.Fprintln(w, c.Name)
}
return nil
}
func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {
c, err := cmd.RestClient()
if err != nil {
return err
}
l, err := tags.NewManager(c).GetCategories(ctx)
if err != nil {
return err
}
return cmd.WriteResult(lsResult(l))
}
func (cmd *ls) Description() string | {
return `List all categories.
Examples:
govc tags.category.ls
govc tags.category.ls -json | jq .`
} |
package zk2topo
import (
"path"
"sort"
"golang.org/x/net/context"
)
func (zs *Server) ListDir(ctx context.Context, cell, dirPath string) ([]string, error) | {
conn, root, err := zs.connForCell(ctx, cell)
if err != nil {
return nil, err
}
zkPath := path.Join(root, dirPath)
children, _, err := conn.Children(ctx, zkPath)
if err != nil {
return nil, convertError(err)
}
sort.Strings(children)
return children, nil
} |
package export
import (
"bytes"
"database/sql"
"strings"
"github.com/pingcap/errors"
tcontext "github.com/pingcap/tidb/dumpling/context"
)
type TableDataIR interface {
Start(*tcontext.Context, *sql.Conn) error
Rows() SQLRowIter
Close() error
RawRows() *sql.Rows
}
type TableMeta interface {
DatabaseName() string
TableName() string
ColumnCount() uint
ColumnTypes() []string
ColumnNames() []string
SelectedField() string
SelectedLen() int
SpecialComments() StringIter
ShowCreateTable() string
ShowCreateView() string
AvgRowLength() uint64
HasImplicitRowID() bool
}
type SQLRowIter interface {
Decode(RowReceiver) error
Next()
Error() error
HasNext() bool
Close() error
}
type RowReceiverStringer interface {
RowReceiver
Stringer
}
type Stringer interface {
WriteToBuffer(*bytes.Buffer, bool)
WriteToBufferInCsv(*bytes.Buffer, bool, *csvOption)
}
type RowReceiver interface {
BindAddress([]interface{})
}
func decodeFromRows(rows *sql.Rows, args []interface{}, row RowReceiver) error {
row.BindAddress(args)
if err := rows.Scan(args...); err != nil {
rows.Close()
return errors.Trace(err)
}
return nil
}
type StringIter interface {
Next() string
HasNext() bool
}
type MetaIR interface {
SpecialComments() StringIter
TargetName() string
MetaSQL() string
}
func setTableMetaFromRows(rows *sql.Rows) (TableMeta, error) | {
tps, err := rows.ColumnTypes()
if err != nil {
return nil, errors.Trace(err)
}
nms, err := rows.Columns()
if err != nil {
return nil, errors.Trace(err)
}
for i := range nms {
nms[i] = wrapBackTicks(nms[i])
}
return &tableMeta{
colTypes: tps,
selectedField: strings.Join(nms, ","),
selectedLen: len(nms),
specCmts: []string{"/*!40101 SET NAMES binary*/;"},
}, nil
} |
package common
import (
"fmt"
v3 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3"
"github.com/rancher/rancher/pkg/ref"
"github.com/sirupsen/logrus"
)
func GetRuleID(groupID string, ruleName string) string {
return fmt.Sprintf("%s_%s", groupID, ruleName)
}
func GetGroupID(namespace, name string) string {
return fmt.Sprintf("%s:%s", namespace, name)
}
func GetAlertManagerSecretName(appName string) string {
return fmt.Sprintf("alertmanager-%s", appName)
}
func GetAlertManagerDaemonsetName(appName string) string {
return fmt.Sprintf("alertmanager-%s", appName)
}
func formatProjectDisplayName(projectDisplayName, projectID string) string {
return fmt.Sprintf("%s (ID: %s)", projectDisplayName, projectID)
}
func GetClusterDisplayName(clusterName string, clusterLister v3.ClusterLister) string {
cluster, err := clusterLister.Get("", clusterName)
if err != nil {
logrus.Warnf("Failed to get cluster for %s: %v", clusterName, err)
return clusterName
}
return formatClusterDisplayName(cluster.Spec.DisplayName, clusterName)
}
func GetProjectDisplayName(projectID string, projectLister v3.ProjectLister) string {
clusterName, projectName := ref.Parse(projectID)
project, err := projectLister.Get(clusterName, projectName)
if err != nil {
logrus.Warnf("Failed to get project %s: %v", projectID, err)
return projectID
}
return formatProjectDisplayName(project.Spec.DisplayName, projectID)
}
func formatClusterDisplayName(clusterDisplayName, clusterID string) string | {
return fmt.Sprintf("%s (ID: %s)", clusterDisplayName, clusterID)
} |
package iso20022
type RemittanceInformation8 struct {
RemittanceIdentification *Max35Text `xml:"RmtId,omitempty"`
Unstructured []*Max140Text `xml:"Ustrd,omitempty"`
Structured []*StructuredRemittanceInformation10 `xml:"Strd,omitempty"`
OriginalPaymentInformation *OriginalPaymentInformation6 `xml:"OrgnlPmtInf"`
}
func (r *RemittanceInformation8) SetRemittanceIdentification(value string) {
r.RemittanceIdentification = (*Max35Text)(&value)
}
func (r *RemittanceInformation8) AddUnstructured(value string) {
r.Unstructured = append(r.Unstructured, (*Max140Text)(&value))
}
func (r *RemittanceInformation8) AddStructured() *StructuredRemittanceInformation10 {
newValue := new(StructuredRemittanceInformation10)
r.Structured = append(r.Structured, newValue)
return newValue
}
func (r *RemittanceInformation8) AddOriginalPaymentInformation() *OriginalPaymentInformation6 | {
r.OriginalPaymentInformation = new(OriginalPaymentInformation6)
return r.OriginalPaymentInformation
} |
package client_test
import (
"github.com/jdextraze/go-gesclient/client"
"testing"
)
func TestWrongExpectedVersion_Error(t *testing.T) {
if client.WrongExpectedVersion.Error() != "Wrong expected version" {
t.FailNow()
}
}
func TestStreamDeleted_Error(t *testing.T) {
if client.StreamDeleted.Error() != "Stream deleted" {
t.FailNow()
}
}
func TestAccessDenied_Error(t *testing.T) {
if client.AccessDenied.Error() != "Access denied" {
t.FailNow()
}
}
func TestAuthenticationError_Error(t *testing.T) {
if client.AuthenticationError.Error() != "Authentication error" {
t.FailNow()
}
}
func TestBadRequest_Error(t *testing.T) {
if client.BadRequest.Error() != "Bad request" {
t.FailNow()
}
}
func TestServerError_Error(t *testing.T) {
err := client.NewServerError("")
if err.Error() != "Unexpected error on server: <no message>" {
t.FailNow()
}
err = client.NewServerError("test")
if err.Error() != "Unexpected error on server: test" {
t.FailNow()
}
}
func TestNotModified_Error(t *testing.T) {
err := client.NewNotModified("test")
if err.Error() != "Stream not modified: test" {
t.FailNow()
}
}
func TestInvalidTransaction_Error(t *testing.T) | {
if client.InvalidTransaction.Error() != "Invalid transaction" {
t.FailNow()
}
} |
package main
import (
"encoding/json"
"log"
"os"
"path/filepath"
"time"
)
type Player struct {
log *os.File
logTime time.Time
decoder *json.Decoder
dir string
offset time.Duration
}
func (p *Player) Reset() error {
n := p.Then()
p.logTime = logTime(n)
filename := logFileName(n)
if p.log != nil {
p.log.Close()
}
log.Printf("Playing file %s\n", filename)
var err error
p.log, err = os.Open(filepath.Join(p.dir, filename))
if err != nil {
return err
}
p.decoder = json.NewDecoder(p.log)
return nil
}
func (p *Player) Playback(t time.Time) error {
log.Printf("Playing back starting at %s\n", t)
p.offset = time.Now().Sub(t)
err := p.Reset()
if err != nil {
return err
}
for {
var m Msg
err := p.decoder.Decode(&m)
if err != nil {
return err
}
d := m.Timestamp.Time.Sub(p.Then())
debugf("difference is %f seconds", d.Seconds())
if d > 0 {
time.Sleep(d)
}
m.Print()
}
}
func (p *Player) Then() time.Time {
return time.Now().Add(-p.offset)
}
func (p *Player) Close() error {
p.decoder = nil
return p.log.Close()
}
func NewPlayer(dir string) *Player | {
var p Player
p.dir = dir
return &p
} |
package bigcache
func convertMBToBytes(value int) int {
return value * 1024 * 1024
}
func isPowerOfTwo(number int) bool {
return (number & (number - 1)) == 0
}
func max(a, b int) int | {
if a > b {
return a
}
return b
} |
package nodes
import (
"encoding/json"
"sync"
)
type Name struct {
TaxID string `json:"TaxID"`
Names []NameItem `json:"Names"`
}
type NameItem struct {
Name string `json:"Name"`
UniqueName string `json:"UniqueName"`
NameClass string `json:"NameClass"`
}
func (name Name) ToJSON() (string, error) {
s, err := json.Marshal(name)
return string(s), err
}
func NameFromArgs(items []string) Name {
if len(items) != 4 {
return Name{}
}
return Name{
TaxID: items[0],
Names: []NameItem{
NameItem{
Name: items[1],
UniqueName: items[2],
NameClass: items[3],
}},
}
}
func MergeNames(names ...Name) Name {
if len(names) < 2 {
return names[0]
}
name := names[0]
for _, another := range names[1:] {
if another.TaxID != name.TaxID {
continue
}
for _, anotherNameItem := range another.Names {
name.Names = append(name.Names, anotherNameItem)
}
}
return name
}
var Names map[string]Name
var mutex1 = &sync.Mutex{}
func SetNames(names map[string]Name) {
mutex1.Lock()
Names = names
mutex1.Unlock()
}
func NameFromJSON(s string) (Name, error) | {
var name Name
err := json.Unmarshal([]byte(s), &name)
return name, err
} |
package main
import (
"fmt"
"strings"
)
func WordCount(s string) map[string]int {
result := make(map[string]int)
for _, v := range strings.Fields(s) {
_, ok := result[v]
if ok == false {
result[v] = 0
}
result[v]++
}
return result
}
func map_operations() | {
m := make(map[string]int)
m["Answer"] = 42
fmt.Println("The value:", m["Answer"])
m["Answer"] = 48
fmt.Println("The value:", m["Answer"])
delete(m, "Answer")
fmt.Println("The value:", m["Answer"])
v, ok := m["Answer"]
fmt.Println("The value:", v, "Present?", ok)
} |
package methods
import (
"encoding/json"
"log"
"time"
"github.com/barnettzqg/journey/configuration"
"github.com/barnettzqg/journey/database"
"github.com/barnettzqg/journey/slug"
"github.com/barnettzqg/journey/structure"
)
var Blog *structure.Blog
var assetPath = []byte("/assets/")
func UpdateActiveTheme(activeTheme string, userId int64) error {
err := database.UpdateActiveTheme(activeTheme, time.Now(), userId)
if err != nil {
return err
}
err = GenerateBlog()
if err != nil {
log.Panic("Error: couldn't generate blog data:", err)
}
return nil
}
func GenerateBlog() error {
if Blog != nil {
Blog.Lock()
defer Blog.Unlock()
}
blog, err := database.RetrieveBlog()
if err != nil {
return err
}
blog.Url = []byte(configuration.Config.Url)
blog.AssetPath = assetPath
for index, _ := range blog.NavigationItems {
blog.NavigationItems[index].Slug = slug.Generate(blog.NavigationItems[index].Label, "navigation")
}
Blog = blog
return nil
}
func UpdateBlog(b *structure.Blog, userId int64) error | {
navigation, err := json.Marshal(b.NavigationItems)
if err != nil {
return err
}
err = database.UpdateSettings(b.Title, b.Description, b.Logo, b.Cover, b.PostsPerPage, b.ActiveTheme, navigation, time.Now(), userId)
if err != nil {
return err
}
err = GenerateBlog()
if err != nil {
log.Panic("Error: couldn't generate blog data:", err)
}
return nil
} |
package contentutil
import (
"context"
"github.com/containerd/containerd/content"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/remotes"
"github.com/pkg/errors"
)
type pushingIngester struct {
p remotes.Pusher
}
func (i *pushingIngester) Writer(ctx context.Context, opts ...content.WriterOpt) (content.Writer, error) {
var wOpts content.WriterOpts
for _, opt := range opts {
if err := opt(&wOpts); err != nil {
return nil, err
}
}
if wOpts.Ref == "" {
return nil, errors.Wrap(errdefs.ErrInvalidArgument, "ref must not be empty")
}
contentWriter, err := i.p.Push(ctx, wOpts.Desc)
if err != nil {
return nil, err
}
return &writer{
Writer: contentWriter,
contentWriterRef: wOpts.Ref,
}, nil
}
type writer struct {
content.Writer
contentWriterRef string
}
func (w *writer) Status() (content.Status, error) {
st, err := w.Writer.Status()
if err != nil {
return st, err
}
if w.contentWriterRef != "" {
st.Ref = w.contentWriterRef
}
return st, nil
}
func FromPusher(p remotes.Pusher) content.Ingester | {
return &pushingIngester{
p: p,
}
} |
package async
import (
"reflect"
)
func FilterParallel(data interface{}, routine Routine, callbacks ...Done) {
var routines []Routine
d := reflect.ValueOf(data)
for i := 0; i < d.Len(); i++ {
v := d.Index(i).Interface()
routines = append(routines, func(id int) Routine {
return func(done Done, args ...interface{}) {
done = func(original Done) Done {
return func(err error, args ...interface{}) {
if args[0] != false {
original(err, v)
return
}
original(err)
}
}(done)
routine(done, v, id)
}
}(i))
}
Parallel(routines, callbacks...)
}
func Filter(data interface{}, routine Routine, callbacks ...Done) | {
var (
routines []Routine
results []interface{}
)
d := reflect.ValueOf(data)
for i := 0; i < d.Len(); i++ {
v := d.Index(i).Interface()
routines = append(routines, func(id int) Routine {
return func(done Done, args ...interface{}) {
done = func(original Done) Done {
return func(err error, args ...interface{}) {
if args[0] != false {
results = append(results, v)
}
if id == (d.Len() - 1) {
original(err, results...)
return
}
original(err, args...)
}
}(done)
routine(done, v, id)
}
}(i))
}
Waterfall(routines, callbacks...)
} |
package command
import (
"bytes"
"fmt"
"github.com/hashicorp/serf/serf"
"github.com/mitchellh/cli"
)
type VersionCommand struct {
Revision string
Version string
VersionPrerelease string
Ui cli.Ui
}
func (c *VersionCommand) Run(_ []string) int {
var versionString bytes.Buffer
fmt.Fprintf(&versionString, "Serf v%s", c.Version)
if c.VersionPrerelease != "" {
fmt.Fprintf(&versionString, ".%s", c.VersionPrerelease)
if c.Revision != "" {
fmt.Fprintf(&versionString, " (%s)", c.Revision)
}
}
c.Ui.Output(versionString.String())
c.Ui.Output(fmt.Sprintf("Agent Protocol: %d (Understands back to: %d)",
serf.ProtocolVersionMax, serf.ProtocolVersionMin))
return 0
}
func (c *VersionCommand) Synopsis() string {
return "Prints the Serf version"
}
func (c *VersionCommand) Help() string | {
return ""
} |
package bunyan
import "os"
type Sink interface {
Write(record Record) error
}
type funcSink struct {
write func(record Record) error
}
func (sink *funcSink) Write(record Record) error {
return sink.write(record)
}
func NilSink() Sink {
return SinkFunc(func(record Record) error {
return nil
})
}
func InfoSink(target Sink, info Info) Sink {
return SinkFunc(func(record Record) error {
record.SetIfNot(info.Key(), info.Value())
return target.Write(record)
})
}
func StdoutSink() Sink {
return NewJsonSink(os.Stdout)
}
func FileSink(path string) Sink {
const flags = os.O_CREATE | os.O_APPEND | os.O_WRONLY
file, e := os.OpenFile(path, flags, 0666)
if e != nil {
panic(e)
}
return NewJsonSink(file)
}
func SinkFunc(write func(record Record) error) Sink | {
return &funcSink{write}
} |
package models
import "time"
type KeyType struct {
ID int
Key string
Created time.Time
Expires bool
}
type Keys []KeyType
func (f Keys) Len() int {
return len(f)
}
func (f Keys) Swap(i, j int) {
f[i], f[j] = f[j], f[i]
}
func (f Keys) Less(i, j int) bool | {
return f[i].ID < f[j].ID
} |
package container
import (
"github.com/e154/smart-home/models"
"github.com/e154/smart-home/system/backup"
)
func NewBackupConfig(cfg *models.AppConfig) *backup.BackupConfig | {
return &backup.BackupConfig{
Path: cfg.SnapshotDir,
PgUser: cfg.PgUser,
PgPass: cfg.PgPass,
PgHost: cfg.PgHost,
PgName: cfg.PgName,
PgPort: cfg.PgPort,
}
} |
package master
import ()
type frame struct {
job *job
slaveName string
frame int
data []byte
progress byte
completed bool
}
func NewFrame(job *job, fr int) *frame {
return &frame{
job: job,
slaveName: "",
frame: fr,
data: nil,
progress: 0,
completed: false,
}
}
func (f *frame) Job() *job {
return f.job
}
func (f *frame) SlaveName() string {
return f.slaveName
}
func (f *frame) Frame() int {
return f.frame
}
func (f *frame) AlignedFrame() int {
return f.frame + f.Job().Start()
}
func (f *frame) Data() []byte {
return f.data
}
func (f *frame) Progress() byte {
return f.progress
}
func (f *frame) Completed() bool {
return f.completed
}
func (f *frame) File() []byte {
return f.Job().File()
}
func (f *frame) SetSlaveName(slaveName string) {
f.slaveName = slaveName
}
func (f *frame) SetData(data []byte) {
f.data = data
}
func (f *frame) SetProgress(progress byte) {
f.progress = progress
}
func (f *frame) Reset() {
f.SetSlaveName("")
f.SetData(nil)
f.SetProgress(0)
f.SetCompleted(false)
}
func (f *frame) SetCompleted(completed bool) | {
f.completed = completed
if completed {
f.SetProgress(100)
}
} |
package dfa
import (
"fmt"
"unicode"
)
func eachRangeInCharClass(name string, visit func(lo, hi rune)) error {
table := unicode.Categories[name]
if table == nil {
table = unicode.Scripts[name]
if table == nil {
return fmt.Errorf("character class %s not exists", name)
}
}
for _, xr := range table.R16 {
eachRangeWithStride(rune(xr.Lo), rune(xr.Hi), rune(xr.Stride), visit)
}
for _, xr := range table.R32 {
eachRangeWithStride(rune(xr.Lo), rune(xr.Hi), rune(xr.Stride), visit)
}
return nil
}
func eachRangeWithStride(lo, hi, stride rune, visit func(lo, hi rune)) {
if stride == 1 {
visit(lo, hi)
} else {
for c := lo; c <= hi; c += stride {
visit(c, c)
}
}
}
func charClass(name string) (m *M, err error) | {
ms := []*M{}
err = eachRangeInCharClass(name, func(lo, hi rune) {
ms = append(ms, Between(lo, hi))
})
if err != nil {
return nil, err
}
m, err = orMany(ms)
if err != nil {
return nil, err
}
return m.minimize()
} |
package mcore
import (
"log"
)
type StringKeyValueMap map[string]string
func NewStringKeyValueMap() StringKeyValueMap {
return make(map[string]string)
}
func (c StringKeyValueMap) Put(key, value string) {
c[key] = value
}
func (c StringKeyValueMap) IsContain(key string) bool {
_, ok := c[key]
return ok
}
func (c StringKeyValueMap) GetString(key string) string {
return c.GetStringWithDefault(key, "")
}
func (c StringKeyValueMap) GetStringWithDefault(key, defaultValue string) string {
if c.IsContain(key) {
return c[key]
}
log.Printf("Error: not contains key: %s", key)
return defaultValue
}
func (c StringKeyValueMap) GetInt(key string) int {
return String(c.GetString(key)).ToIntNoError()
}
func (c StringKeyValueMap) GetBool(key string) bool | {
return String(c.GetString(key)).ToBool()
} |
package format
import (
"reflect"
"strconv"
)
func Any(value interface{}) string {
return formatAtom(reflect.ValueOf(value))
}
func formatAtom(v reflect.Value) string | {
switch v.Kind() {
case reflect.Invalid:
return "invalid"
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64:
return strconv.FormatInt(v.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return strconv.FormatUint(v.Uint(), 10)
case reflect.Bool:
return strconv.FormatBool(v.Bool())
case reflect.String:
return strconv.Quote(v.String())
case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Slice, reflect.Map:
return v.Type().String() + " 0x" +
strconv.FormatUint(uint64(v.Pointer()), 16)
default:
return v.Type().String() + " value"
}
} |
package bigquery
import (
"fmt"
"github.com/viant/endly"
"github.com/viant/endly/system/cloud/gcp"
"google.golang.org/api/bigquery/v2"
)
var clientKey = (*CtxClient)(nil)
type CtxClient struct {
*gcp.AbstractClient
service *bigquery.Service
}
func (s *CtxClient) SetService(service interface{}) error {
var ok bool
s.service, ok = service.(*bigquery.Service)
if !ok {
return fmt.Errorf("unable to set service: %T", service)
}
return nil
}
func (s *CtxClient) Service() interface{} {
return s.service
}
func InitRequest(context *endly.Context, rawRequest map[string]interface{}) error {
config, err := gcp.InitCredentials(context, rawRequest)
if err != nil {
return err
}
client, err := getClient(context)
if err != nil {
return err
}
gcp.UpdateActionRequest(rawRequest, config, client)
return nil
}
func getClient(context *endly.Context) (gcp.CtxClient, error) {
return GetClient(context)
}
func GetClient(context *endly.Context) (*CtxClient, error) | {
client := &CtxClient{
AbstractClient: &gcp.AbstractClient{},
}
err := gcp.GetClient(context, bigquery.New, clientKey, &client, bigquery.CloudPlatformScope, bigquery.BigqueryScope, bigquery.BigqueryInsertdataScope)
return client, err
} |
package iotcentral
import "github.com/Azure/azure-sdk-for-go/version"
func Version() string {
return version.Number
}
func UserAgent() string | {
return "Azure-SDK-For-Go/" + Version() + " iotcentral/2021-06-01"
} |
package resources
import (
"sort"
"encoding/json"
"github.com/mitchellh/mapstructure"
)
type AWSServerlessApplication_Location struct {
String *string
ApplicationLocation *AWSServerlessApplication_ApplicationLocation
}
func (r AWSServerlessApplication_Location) value() interface{} {
if r.String != nil {
return r.String
}
ret := []interface{}{}
if r.ApplicationLocation != nil {
ret = append(ret, *r.ApplicationLocation)
}
sort.Sort(byJSONLength(ret))
if len(ret) > 0 {
return ret[0]
}
return nil
}
func (r *AWSServerlessApplication_Location) UnmarshalJSON(b []byte) error {
var typecheck interface{}
if err := json.Unmarshal(b, &typecheck); err != nil {
return err
}
switch val := typecheck.(type) {
case string:
r.String = &val
case map[string]interface{}:
mapstructure.Decode(val, &r.ApplicationLocation)
case []interface{}:
}
return nil
}
func (r AWSServerlessApplication_Location) MarshalJSON() ([]byte, error) | {
return json.Marshal(r.value())
} |
package repository
import (
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/cache"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/setting"
)
func CacheRef(repo *models.Repository, gitRepo *git.Repository, fullRefName string) error {
if !setting.CacheService.LastCommit.Enabled {
return nil
}
commit, err := gitRepo.GetCommit(fullRefName)
if err != nil {
return err
}
commitsCount, err := cache.GetInt64(repo.GetCommitsCountCacheKey(getRefName(fullRefName), true), commit.CommitsCount)
if err != nil {
return err
}
if commitsCount < setting.CacheService.LastCommit.CommitsCount {
return nil
}
commitCache := git.NewLastCommitCache(repo.FullName(), gitRepo, setting.LastCommitCacheTTLSeconds, cache.GetCache())
return commitCache.CacheCommit(commit)
}
func getRefName(fullRefName string) string | {
if strings.HasPrefix(fullRefName, git.TagPrefix) {
return fullRefName[len(git.TagPrefix):]
} else if strings.HasPrefix(fullRefName, git.BranchPrefix) {
return fullRefName[len(git.BranchPrefix):]
}
return ""
} |
package sortedmap
import (
"testing"
"github.com/umpc/go-sortedmap/asc"
)
func insertRecord(b *testing.B) {
records := randRecords(1)
sm := New(0, asc.Time)
b.ResetTimer()
for i := 0; i < b.N; i++ {
sm.Insert(records[0].Key, records[0].Val)
b.StopTimer()
records = randRecords(1)
sm = New(0, asc.Time)
b.StartTimer()
}
}
func batchInsertRecords(b *testing.B, n int) {
records := randRecords(n)
sm := New(0, asc.Time)
b.ResetTimer()
for i := 0; i < b.N; i++ {
sm.BatchInsert(records)
b.StopTimer()
records = randRecords(n)
sm = New(0, asc.Time)
b.StartTimer()
}
}
func BenchmarkInsert1Record(b *testing.B) {
insertRecord(b)
}
func BenchmarkBatchInsert10Records(b *testing.B) {
batchInsertRecords(b, 10)
}
func BenchmarkBatchInsert1000Records(b *testing.B) {
batchInsertRecords(b, 1000)
}
func BenchmarkBatchInsert10000Records(b *testing.B) {
batchInsertRecords(b, 10000)
}
func BenchmarkBatchInsert100Records(b *testing.B) | {
batchInsertRecords(b, 100)
} |
package block
type NoopLeaseManager struct{}
func (n *NoopLeaseManager) UnregisterLeaser(leaser Leaser) error {
return nil
}
func (n *NoopLeaseManager) OpenLease(
leaser Leaser,
descriptor LeaseDescriptor,
state LeaseState,
) error {
return nil
}
func (n *NoopLeaseManager) OpenLatestLease(
leaser Leaser,
descriptor LeaseDescriptor,
) (LeaseState, error) {
return LeaseState{}, nil
}
func (n *NoopLeaseManager) UpdateOpenLeases(
descriptor LeaseDescriptor,
state LeaseState,
) (UpdateLeasesResult, error) {
return UpdateLeasesResult{}, nil
}
func (n *NoopLeaseManager) SetLeaseVerifier(leaseVerifier LeaseVerifier) error {
return nil
}
func (n *NoopLeaseManager) RegisterLeaser(leaser Leaser) error | {
return nil
} |
package main
import (
"github.com/codegangsta/martini-contrib/render"
"github.com/luan/godo/godo"
"net/http"
)
type ProjectsController struct{}
func (c *ProjectsController) List(r render.Render) {
projects, _ := godo.NewProjectManager().FindAllWithTasks()
r.HTML(200, "projects", projects)
}
func (c *ProjectsController) Create(req *http.Request, r render.Render) | {
p := godo.NewProject(req.FormValue("name"))
godo.NewProjectManager().Add(&p)
r.Redirect("/projects", 301)
} |
package parsex
import (
"errors"
"fmt"
"io"
)
type ParsexError struct {
Pos int
Message string
}
func (err ParsexError) Error() string {
return fmt.Sprintf("pos %d :\n%s",
err.Pos, err.Message)
}
type ParsexState interface {
Next(pred func(int, interface{}) (interface{}, error)) (x interface{}, err error)
Pos() int
SeekTo(int)
Trap(message string, args ...interface{}) error
}
type StateInMemory struct {
buffer []interface{}
pos int
}
func (this *StateInMemory) Next(pred func(int, interface{}) (interface{}, error)) (x interface{}, err error) {
buffer := (*this).buffer
if (*this).pos < len(buffer) {
x := buffer[(*this).pos]
output, err := pred((*this).pos, x)
if err == nil {
(*this).pos++
return output, nil
} else {
return x, err
}
} else {
return nil, io.EOF
}
}
func (this *StateInMemory) Pos() int {
return (*this).pos
}
func (this *StateInMemory) SeekTo(pos int) {
end := len((*this).buffer)
if pos < 0 || pos > end {
message := fmt.Sprintf("%d out range [0, %d]", pos, end)
panic(errors.New(message))
}
(*this).pos = pos
}
func (this *StateInMemory) Trap(message string, args ...interface{}) error {
return ParsexError{(*this).pos,
fmt.Sprintf(message, args...)}
}
func NewStateInMemory(buffer []interface{}) *StateInMemory | {
return &StateInMemory{buffer, 0}
} |
package main
import (
"fmt"
"github.com/ian-kent/go-log/log"
"github.com/ian-kent/gotcha/http"
"strconv"
)
func pkgindex(session *http.Session) {
if _, ok := session.Stash["repo"]; !ok {
session.RenderNotFound()
return
}
repo := session.Stash["repo"].(string)
for fname, _ := range indexes {
if _, ok := indexes[fname][repo]; !ok && repo != "SmartPAN" {
session.RenderNotFound()
return
}
}
if g, ok := session.Stash["gz"]; ok {
if len(g.(string)) > 0 {
session.Response.Headers.Set("Content-Type", "application/gzip")
session.Response.Send()
session.Response.Gzip()
session.Response.Headers.Remove("Content-Encoding")
log.Debug("Using gzip")
}
}
session.Response.WriteText("File: 02packages.details.txt\n")
session.Response.WriteText("Description: Package names found in directory " + repo + "/authors/id\n")
session.Response.WriteText("Columns: package name, version, path\n")
session.Response.WriteText("Written-By: SmartPAN (from GoPAN)\n")
session.Response.WriteText("Line-Count: " + strconv.Itoa(summary.Packages) + "\n")
session.Response.WriteText("\n")
if repo == "SmartPAN" {
for _, pkg := range packages {
writepkgindex(session, pkg)
}
} else {
for _, pkg := range idxpackages[repo] {
writepkgindex(session, pkg)
}
}
}
func writepkgindex(session *http.Session, pkgspace *PkgSpace) | {
if len(pkgspace.Packages) > 0 {
latest := pkgspace.Packages[0]
if len(latest.Version) == 0 {
latest.Version = "undef"
}
session.Response.WriteText(fmt.Sprintf("%-40s %-10s %s\n", pkgspace.FullName(), latest.Version, latest.Package.AuthorURL()))
}
if len(pkgspace.Children) > 0 {
for _, ps := range pkgspace.Children {
writepkgindex(session, ps)
}
}
} |
package main
import (
"fmt"
"github.com/mrcsparker/ifin/service"
)
func main() {
fmt.Println(welcome())
controller := service.Flow{}
fmt.Println(controller.GetAboutInfo())
}
func welcome() string | {
return "[ifin]"
} |
package eventbreakpoints
import (
"context"
"github.com/chromedp/cdproto/cdp"
)
type SetInstrumentationBreakpointParams struct {
EventName string `json:"eventName"`
}
func (p *SetInstrumentationBreakpointParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetInstrumentationBreakpoint, p, nil)
}
type RemoveInstrumentationBreakpointParams struct {
EventName string `json:"eventName"`
}
func RemoveInstrumentationBreakpoint(eventName string) *RemoveInstrumentationBreakpointParams {
return &RemoveInstrumentationBreakpointParams{
EventName: eventName,
}
}
func (p *RemoveInstrumentationBreakpointParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandRemoveInstrumentationBreakpoint, p, nil)
}
const (
CommandSetInstrumentationBreakpoint = "EventBreakpoints.setInstrumentationBreakpoint"
CommandRemoveInstrumentationBreakpoint = "EventBreakpoints.removeInstrumentationBreakpoint"
)
func SetInstrumentationBreakpoint(eventName string) *SetInstrumentationBreakpointParams | {
return &SetInstrumentationBreakpointParams{
EventName: eventName,
}
} |
package pointer
import "time"
func DefaultBool(value *bool, defaultValue bool) *bool {
if value == nil {
return &defaultValue
}
return value
}
func DefaultDuration(value *time.Duration, defaultValue time.Duration) *time.Duration {
if value == nil {
return &defaultValue
}
return value
}
func DefaultFloat64(value *float64, defaultValue float64) *float64 {
if value == nil {
return &defaultValue
}
return value
}
func DefaultString(value *string, defaultValue string) *string {
if value == nil {
return &defaultValue
}
return value
}
func DefaultStringArray(value *[]string, defaultValue []string) *[]string {
if value == nil {
return &defaultValue
}
return value
}
func DefaultTime(value *time.Time, defaultValue time.Time) *time.Time {
if value == nil {
return &defaultValue
}
return value
}
func DefaultInt(value *int, defaultValue int) *int | {
if value == nil {
return &defaultValue
}
return value
} |
package lease
type block struct {
leaseName string
unblock chan struct{}
abort <-chan struct{}
}
func (b block) invoke(ch chan<- block) error {
for {
select {
case <-b.abort:
return errStopped
case ch <- b:
ch = nil
case <-b.unblock:
return nil
}
}
}
type blocks map[string][]chan struct{}
func (b blocks) add(block block) {
b[block.leaseName] = append(b[block.leaseName], block.unblock)
}
func (b blocks) unblock(leaseName string) | {
unblocks := b[leaseName]
delete(b, leaseName)
for _, unblock := range unblocks {
close(unblock)
}
} |
package grace
import "net/http"
type ServeMux struct {
http.ServeMux
}
func NewServeMux() *ServeMux { return &ServeMux{*http.NewServeMux()} }
var DefaultServeMux = NewServeMux()
func (sm *ServeMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) | {
sm.Handle(pattern, HandlerFunc(handler))
} |
package remotestate
import (
"context"
"github.com/r3labs/terraform/backend"
"github.com/r3labs/terraform/helper/schema"
"github.com/r3labs/terraform/state"
"github.com/r3labs/terraform/state/remote"
"github.com/r3labs/terraform/terraform"
)
type Backend struct {
*schema.Backend
ConfigureFunc func(ctx context.Context) (remote.Client, error)
client remote.Client
}
func (b *Backend) Configure(rc *terraform.ResourceConfig) error {
b.Backend.ConfigureFunc = func(ctx context.Context) error {
c, err := b.ConfigureFunc(ctx)
if err != nil {
return err
}
b.client = c
return nil
}
return b.Backend.Configure(rc)
}
func (b *Backend) States() ([]string, error) {
return nil, backend.ErrNamedStatesNotSupported
}
func (b *Backend) DeleteState(name string) error {
return backend.ErrNamedStatesNotSupported
}
func (b *Backend) State(name string) (state.State, error) | {
if b.client == nil {
panic("nil remote client")
}
if name != backend.DefaultStateName {
return nil, backend.ErrNamedStatesNotSupported
}
s := &remote.State{Client: b.client}
return s, nil
} |
package rotaryLogger
import (
"fmt"
"io"
"log"
"os"
"strconv"
"time"
)
var Logger *log.Logger
var file os.File
func StartLogger(logLocation string) {
file, err := os.OpenFile(logLocation+"0.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatal("Failed to open Logger file", err)
}
multi := io.MultiWriter(file, os.Stdout)
Logger = log.New(multi,
"",
log.Ldate|log.Ltime|log.Lshortfile)
}
func logRotator(logAmount int, logLocation string) {
if _, err := os.Stat(logLocation + strconv.Itoa(logAmount) + ".log"); os.IsNotExist(err) {
os.Remove(logLocation + strconv.Itoa(logAmount) + ".log")
}
for i := 2; i != -1; i-- {
fmt.Println(logLocation + strconv.Itoa(i) + ".log")
if _, err := os.Stat(logLocation + strconv.Itoa(i) + ".log"); err == nil {
os.Rename(logLocation+strconv.Itoa(i)+".log", logLocation+strconv.Itoa(i+1)+".log")
}
}
}
func StartLoggerWRotation(logAmount int, logLocation string, rotationPeriod time.Duration) | {
logRotator(logAmount, logLocation)
StartLogger(logLocation)
ticker := time.NewTicker(rotationPeriod)
go func() {
for _ = range ticker.C {
Logger.Println("Rotating Logs")
Logger = log.New(os.Stdout,
"",
log.Ldate|log.Ltime|log.Lshortfile)
logRotator(logAmount, logLocation)
StartLogger(logLocation)
}
}()
} |
package s0132
import (
"github.com/peterstace/project-euler/number"
)
func Answer() interface{} {
return SumPrimeFactors(40, 10e9)
}
func repunit(k, m int) int {
if k == 1 {
return 1
}
if k%2 == 0 {
half := repunit(k/2, m)
return (tenPow(k/2, m)*half + half) % m
} else {
return (10*repunit(k-1, m) + 1) % m
}
}
func tenPow(k, m int) int {
if k == 0 {
return 1
}
if k%2 == 0 {
half := tenPow(k/2, m)
return (half * half) % m
} else {
return (10 * tenPow(k-1, m)) % m
}
}
func SumPrimeFactors(numFactors int, k int) int | {
var factorsFound int
var sum int
nthPrime := number.MakeSieveBackedNthPrime()
for i := 0; factorsFound < numFactors; i++ {
p := nthPrime(i)
if repunit(k, p) == 0 {
factorsFound++
sum += p
}
}
return sum
} |
package api
import (
"context"
"fmt"
"github.com/google/gapid/core/data/id"
"github.com/google/gapid/core/image"
"github.com/google/gapid/gapil/constset"
)
type API interface {
Name() string
Index() uint8
ID() ID
ConstantSets() *constset.Pack
GetFramebufferAttachmentInfo(
ctx context.Context,
after []uint64,
state *GlobalState,
thread uint64,
attachment FramebufferAttachment) (width, height, index uint32, format *image.Format, err error)
Context(state *GlobalState, thread uint64) Context
CreateCmd(name string) Cmd
}
type ID id.ID
func (i ID) IsValid() bool { return id.ID(i).IsValid() }
func (i ID) String() string { return id.ID(i).String() }
type APIObject interface {
API() API
}
var apis = map[ID]API{}
var indices = map[uint8]bool{}
func Register(api API) {
id := api.ID()
if _, present := apis[id]; present {
panic(fmt.Errorf("API %s registered more than once", id))
}
apis[id] = api
index := api.Index()
if _, present := indices[index]; present {
panic(fmt.Errorf("API %s used an occupied index %d", id, index))
}
indices[index] = true
}
func Find(id ID) API | {
return apis[id]
} |
package vcl
import (
. "github.com/ying32/govcl/vcl/api"
. "github.com/ying32/govcl/vcl/types"
)
type (
NSObject uintptr
NSWindow uintptr
NSURL uintptr
)
func (f *TForm) PlatformWindow() NSWindow {
r, _, _ := NSWindow_FromForm.Call(f.instance)
return NSWindow(r)
}
func (n NSWindow) TitleVisibility() NSWindowTitleVisibility {
r, _, _ := NSWindow_titleVisibility.Call(uintptr(n))
return NSWindowTitleVisibility(r)
}
func (n NSWindow) SetTitleVisibility(flag NSWindowTitleVisibility) {
NSWindow_setTitleVisibility.Call(uintptr(n), uintptr(flag))
}
func (n NSWindow) TitleBarAppearsTransparent() bool {
r, _, _ := NSWindow_titlebarAppearsTransparent.Call(uintptr(n))
return DBoolToGoBool(r)
}
func (n NSWindow) SetTitleBarAppearsTransparent(flag bool) {
NSWindow_setTitlebarAppearsTransparent.Call(uintptr(n), GoBoolToDBool(flag))
}
func (n NSWindow) SetRepresentedURL(url NSURL) {
NSWindow_setRepresentedURL.Call(uintptr(n), uintptr(url))
}
func (n NSWindow) StyleMask() uint {
r, _, _ := NSWindow_styleMask.Call(uintptr(n))
return uint(r)
}
func (n NSWindow) SetStyleMask(mask uint) {
NSWindow_setStyleMask.Call(uintptr(n), uintptr(mask))
}
func HandleToPlatformHandle(h HWND) NSObject | {
return NSObject(h)
} |
package main
import (
"fmt"
)
func main() {
args := []int{5, 2, 6, 1}
fmt.Println(countSmaller(args))
}
func countSmaller(nums []int) []int | {
var nums2 []int
for i, numb := range nums {
timeCount := 0
for ii := i; ii < len(nums); ii++ {
if nums[ii] < numb {
timeCount = timeCount + 1
}
}
nums2 = append(nums2, timeCount)
}
return nums2
} |
package engine
type Novel struct {
Name string
LastUpdateTime string
Author string
MenuURL string
IconURL string
NewestLastChapterName string
Description string
Menus []*Menu
Chapters []*Chapter
}
type Menu struct {
Name string
URL string
}
type Chapter struct {
Title string
Content string
}
func (novel *Novel) AddMenu(menu *Menu) {
novel.Menus = append(novel.Menus, menu)
}
func (novel *Novel) AddChapter(chapter *Chapter) {
novel.Chapters = append(novel.Chapters, chapter)
}
func NewChapter(title, content string) *Chapter {
return &Chapter{title, content}
}
func NewMenu(name, url string) *Menu | {
return &Menu{name, url}
} |
package block
type NoopLeaseManager struct{}
func (n *NoopLeaseManager) RegisterLeaser(leaser Leaser) error {
return nil
}
func (n *NoopLeaseManager) UnregisterLeaser(leaser Leaser) error {
return nil
}
func (n *NoopLeaseManager) OpenLatestLease(
leaser Leaser,
descriptor LeaseDescriptor,
) (LeaseState, error) {
return LeaseState{}, nil
}
func (n *NoopLeaseManager) UpdateOpenLeases(
descriptor LeaseDescriptor,
state LeaseState,
) (UpdateLeasesResult, error) {
return UpdateLeasesResult{}, nil
}
func (n *NoopLeaseManager) SetLeaseVerifier(leaseVerifier LeaseVerifier) error {
return nil
}
func (n *NoopLeaseManager) OpenLease(
leaser Leaser,
descriptor LeaseDescriptor,
state LeaseState,
) error | {
return nil
} |
package config
import (
"encoding/json"
"os"
)
type Config struct {
BindAddress string `json:"bindAddress"`
ImageDirectory string `json:"imageDirectory"`
DbProtocol string `json:"dbProtocol"`
DbAddress string `json:"dbAddress"`
DbName string `json:"dbName"`
DbUser string `json:"dbUser"`
DbPassword string `json:"dbPassword"`
AuthToken string `json:"authToken"`
}
func LoadConfig(path string) (*Config, error) | {
file, openErr := os.Open(path)
if openErr != nil {
return nil, openErr
}
defer file.Close()
decoder := json.NewDecoder(file)
config := Config{}
decodeErr := decoder.Decode(&config)
return &config, decodeErr
} |
package render
import (
"fmt"
"net/http"
)
type Redirect struct {
Code int
Request *http.Request
Location string
}
func (r Redirect) Render(w http.ResponseWriter) error | {
if r.Code < 300 || r.Code > 308 {
panic(fmt.Sprintf("Cannot redirect with status code %d", r.Code))
}
http.Redirect(w, r.Request, r.Location, r.Code)
return nil
} |
package main
import (
"os"
"fmt"
"bufio"
"encoding/hex"
)
func check(e error) {
if e != nil {
fmt.Printf("Error: %s\n", e.Error())
os.Exit(0)
}
}
func get_hex_data(filename string) [][]byte {
file, err := os.Open(filename)
check(err)
var data [][]byte
scan := bufio.NewScanner(file)
for scan.Scan() {
temp, err := hex.DecodeString(scan.Text())
check(err)
data = append(data, temp)
}
return data
}
func main() {
fmt.Println("Cryptopals Set 1")
fmt.Println("================")
fmt.Println("Challenge 8")
fmt.Println("-----------")
block_size := 16
crypts := get_hex_data("data/8.txt")
low := len(crypts[0]) / block_size
msg := ""
for _, crypt := range crypts {
chunks := chunk(crypt, block_size)
temp := make(map[string] int)
for _, c := range chunks {
temp[string(c)] = 0
}
if len(temp) < low {
low = len(temp)
msg = string(crypt)
}
}
for _, c := range chunk([]byte(msg), 16) {
fmt.Printf("%x\n", c)
}
}
func chunk(data []byte, size int) [][]byte | {
var chunks [][]byte
for i:=0; i<len(data); i=i+size {
chunks = append(chunks, data[i:i+size])
}
return chunks
} |
package routetemplate
import (
"fmt"
"reflect"
)
var routeTemplates []RouteTemplate
func Add(template string) (err error) {
routeTemplate, _ := Parse(template)
routeTemplates = append(routeTemplates, routeTemplate)
return nil
}
func GetMatchedTemplateString(url string) (template string, err error) {
template = ""
for _, value := range routeTemplates {
wasMatched, _ := IsMatch(url, value)
if wasMatched {
template = value.TemplatePath
break
}
}
return template, nil
}
func GetMatchTemplate(url string) (routeTemplateMatch RouteTemplateMatch, err error) {
routeTemplateMatch = RouteTemplateMatch{}
for _, value := range routeTemplates {
wasMatched, _ := IsMatch(url, value)
if wasMatched {
routeTemplateMatch, _ = BindVariables(url, value)
break
}
}
return routeTemplateMatch, nil
}
func AddRoute(name string, method string, urlTemplate string, handler interface{}) {
fmt.Printf("%q\n", handler)
var x reflect.Value
if fv, ok := handler.(reflect.Value); ok {
x = fv
} else {
x = reflect.ValueOf(handler)
}
args := make([]reflect.Value, 0, 0)
x.Call(args)
fmt.Printf("%q\n", x)
}
func GetAllTemplates() (templates []RouteTemplate, err error) {
return routeTemplates, nil
}
func ClearAllTemplates() (err error) {
routeTemplates = make([]RouteTemplate, 0)
return nil
}
func GetMatchedTemplate(url string) (template string, err error) | {
template = ""
for _, value := range routeTemplates {
wasMatched, _ := IsMatch(url, value)
if wasMatched {
template = value.TemplatePath
break
}
}
return template, nil
} |
package models
import (
"github.com/go-swagger/go-swagger/errors"
"github.com/go-swagger/go-swagger/httpkit/validate"
"github.com/go-swagger/go-swagger/strfmt"
)
type Ticket struct {
EventID string `json:"event_id,omitempty"`
Num int32 `json:"num,omitempty"`
}
func (m *Ticket) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateEventID(formats); err != nil {
res = append(res, err)
}
if err := m.validateNum(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *Ticket) validateEventID(formats strfmt.Registry) error {
if err := validate.RequiredString("event_id", "body", string(m.EventID)); err != nil {
return err
}
return nil
}
func (m *Ticket) validateNum(formats strfmt.Registry) error | {
if err := validate.Required("num", "body", int32(m.Num)); err != nil {
return err
}
return nil
} |
package cgzip
import "C"
import (
"hash"
"unsafe"
)
type adler32Hash struct {
adler C.uLong
}
func NewAdler32() hash.Hash32 {
a := &adler32Hash{}
a.Reset()
return a
}
func (a *adler32Hash) Write(p []byte) (n int, err error) {
if len(p) > 0 {
a.adler = C.adler32(a.adler, (*C.Bytef)(unsafe.Pointer(&p[0])), (C.uInt)(len(p)))
}
return len(p), nil
}
func (a *adler32Hash) Reset() {
a.adler = C.adler32(0, (*C.Bytef)(unsafe.Pointer(nil)), 0)
}
func (a *adler32Hash) Size() int {
return 4
}
func (a *adler32Hash) BlockSize() int {
return 1
}
func (a *adler32Hash) Sum32() uint32 {
return uint32(a.adler)
}
func Adler32Combine(adler1, adler2 uint32, len2 int) uint32 {
return uint32(C.adler32_combine(C.uLong(adler1), C.uLong(adler2), C.z_off_t(len2)))
}
func (a *adler32Hash) Sum(b []byte) []byte | {
s := a.Sum32()
b = append(b, byte(s>>24))
b = append(b, byte(s>>16))
b = append(b, byte(s>>8))
b = append(b, byte(s))
return b
} |
package database
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
type TerminateDbSystemRequest struct {
DbSystemId *string `mandatory:"true" contributesTo:"path" name:"dbSystemId"`
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
RequestMetadata common.RequestMetadata
}
func (request TerminateDbSystemRequest) String() string {
return common.PointerString(request)
}
func (request TerminateDbSystemRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
func (request TerminateDbSystemRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
type TerminateDbSystemResponse struct {
RawResponse *http.Response
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response TerminateDbSystemResponse) String() string {
return common.PointerString(response)
}
func (response TerminateDbSystemResponse) HTTPResponse() *http.Response | {
return response.RawResponse
} |
package routes
import (
"k8s.io/kubernetes/pkg/genericapiserver/server/mux"
"github.com/emicklei/go-restful/swagger"
)
type Swagger struct {
Config *swagger.Config
}
func (s Swagger) Install(c *mux.APIContainer) | {
s.Config.WebServices = c.RegisteredWebServices()
swagger.RegisterSwaggerService(*s.Config, c.Container)
} |
package store
import (
"github.com/docker/docker/pkg/plugins"
)
func FindWithCapability(capability string) ([]CompatPlugin, error) {
pl, err := plugins.GetAll(capability)
if err != nil {
return nil, err
}
result := make([]CompatPlugin, len(pl))
for i, p := range pl {
result[i] = p
}
return result, nil
}
func LookupWithCapability(name, capability string, _ int) (CompatPlugin, error) | {
return plugins.Get(name, capability)
} |
package notmain
import (
"testing"
"github.com/letsencrypt/boulder/test"
)
func TestLineValidAccepts(t *testing.T) {
err := lineValid("2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: kKG6cwA Caught SIGTERM")
test.AssertNotError(t, err, "errored on valid checksum")
}
func TestLineValidRejects(t *testing.T) {
err := lineValid("2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxxxxx Caught SIGTERM")
test.AssertError(t, err, "didn't error on invalid checksum")
}
func TestLineValidNonOurobouros(t *testing.T) {
err := lineValid("2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxxxxx Caught SIGTERM")
test.AssertError(t, err, "didn't error on invalid checksum")
selfOutput := "2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 log-validator[1337]: xxxxxxx " + err.Error()
err2 := lineValid(selfOutput)
test.AssertNotError(t, err2, "expected no error when feeding lineValid's error output into itself")
}
func TestLineValidRejectsNotAChecksum(t *testing.T) | {
err := lineValid("2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxx Caught SIGTERM")
test.AssertError(t, err, "didn't error on invalid checksum")
test.AssertErrorIs(t, err, errInvalidChecksum)
} |
package figure
import (
"fmt"
"log"
"net/http"
"strconv"
"strings"
)
const signature = "flf2"
const reverseFlag = "1"
var charDelimiters = [3]string{"@", "#", "$"}
var hardblanksBlacklist = [2]byte{'a', '2'}
func getFile(name string) (file http.File) {
filePath := fmt.Sprintf("%s.flf", name)
file, err := AssetFS().Open(filePath)
if err != nil {
log.Fatalf("invalid font name:%s.",err)
}
return file
}
func getHeight(metadata string) int {
datum := strings.Fields(metadata)[1]
height, _ := strconv.Atoi(datum)
return height
}
func getBaseline(metadata string) int {
datum := strings.Fields(metadata)[2]
baseline, _ := strconv.Atoi(datum)
return baseline
}
func getReverse(metadata string) bool {
data := strings.Fields(metadata)
return len(data) > 6 && data[6] == reverseFlag
}
func lastCharLine(text string, height int) bool {
endOfLine, length := " ", 2
if height == 1 && len(text) > 0 {
length = 1
}
if len(text) >= length {
endOfLine = text[len(text)-length:]
}
return endOfLine == strings.Repeat(charDelimiters[0], length) ||
endOfLine == strings.Repeat(charDelimiters[1], length) ||
endOfLine == strings.Repeat(charDelimiters[2], length)
}
func getHardblank(metadata string) byte | {
datum := strings.Fields(metadata)[0]
hardblank := datum[len(datum)-1]
if hardblank == hardblanksBlacklist[0] || hardblank == hardblanksBlacklist[1] {
return ' '
} else {
return hardblank
}
} |
package lib2048
import (
"fmt"
"time"
)
type Direction int
const layout = "15:04:05.12"
const (
Up Direction = iota + 1
Left
Down
Right
)
type Move struct {
Time time.Time
Direction Direction
}
func NewMove(dir Direction) *Move {
return &Move{time.Now(), dir}
}
func (m *Move) String() string | {
var moveString string
switch m.Direction {
case Up:
moveString = "Up"
case Down:
moveString = "Down"
case Left:
moveString = "Left"
case Right:
moveString = "Right"
}
return fmt.Sprintf("'%s': %s", m.Time.Format(layout), moveString)
} |
package azure
import (
"errors"
"fmt"
"os"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/kubernetes/test/e2e/framework"
"k8s.io/legacy-cloud-providers/azure"
)
func init() {
framework.RegisterProvider("azure", newProvider)
}
type Provider struct {
framework.NullProvider
azureCloud *azure.Cloud
}
func (p *Provider) DeleteNode(node *v1.Node) error {
return errors.New("not implemented yet")
}
func (p *Provider) CreatePD(zone string) (string, error) {
pdName := fmt.Sprintf("%s-%s", framework.TestContext.Prefix, string(uuid.NewUUID()))
_, diskURI, _, err := p.azureCloud.CreateVolume(pdName, "" , "" , "" , 1 )
if err != nil {
return "", err
}
return diskURI, nil
}
func (p *Provider) DeletePD(pdName string) error {
if err := p.azureCloud.DeleteVolume(pdName); err != nil {
framework.Logf("failed to delete Azure volume %q: %v", pdName, err)
return err
}
return nil
}
func (p *Provider) EnableAndDisableInternalLB() (enable, disable func(svc *v1.Service)) {
enable = func(svc *v1.Service) {
svc.ObjectMeta.Annotations = map[string]string{azure.ServiceAnnotationLoadBalancerInternal: "true"}
}
disable = func(svc *v1.Service) {
svc.ObjectMeta.Annotations = map[string]string{azure.ServiceAnnotationLoadBalancerInternal: "false"}
}
return
}
func newProvider() (framework.ProviderInterface, error) | {
if framework.TestContext.CloudConfig.ConfigFile == "" {
return nil, fmt.Errorf("config-file must be specified for Azure")
}
config, err := os.Open(framework.TestContext.CloudConfig.ConfigFile)
if err != nil {
framework.Logf("Couldn't open cloud provider configuration %s: %#v",
framework.TestContext.CloudConfig.ConfigFile, err)
}
defer config.Close()
azureCloud, err := azure.NewCloud(config)
return &Provider{
azureCloud: azureCloud.(*azure.Cloud),
}, err
} |
package serviceaccess_test
import (
"github.com/cloudfoundry/cli/cf/i18n"
"github.com/cloudfoundry/cli/cf/i18n/detection"
"github.com/cloudfoundry/cli/testhelpers/configuration"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestServiceAccess(t *testing.T) | {
config := configuration.NewRepositoryWithDefaults()
i18n.T = i18n.Init(config, &detection.JibberJabberDetector{})
RegisterFailHandler(Fail)
RunSpecs(t, "Service Access Suite")
} |
package syscall
func setTimespec(sec, nsec int64) Timespec {
return Timespec{Sec: sec, Nsec: nsec}
}
func setTimeval(sec, usec int64) Timeval {
return Timeval{Sec: sec, Usec: usec}
}
func (iov *Iovec) SetLen(length int) {
iov.Len = uint64(length)
}
func (msghdr *Msghdr) SetControllen(length int) {
msghdr.Controllen = uint32(length)
}
func (cmsg *Cmsghdr) SetLen(length int) {
cmsg.Len = uint32(length)
}
const RTM_LOCK = 0x8
const SYS___SYSCTL = SYS_SYSCTL
func SetKevent(k *Kevent_t, fd, mode, flags int) | {
k.Ident = uint64(fd)
k.Filter = int16(mode)
k.Flags = uint16(flags)
} |
package common
import (
"encoding/binary"
"sort"
)
type Uint64Slice []uint64
func (p Uint64Slice) Len() int { return len(p) }
func (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }
func (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p Uint64Slice) Sort() { sort.Sort(p) }
func (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }
func PutUint64LE(dest []byte, i uint64) {
binary.LittleEndian.PutUint64(dest, i)
}
func GetUint64LE(src []byte) uint64 {
return binary.LittleEndian.Uint64(src)
}
func PutUint64BE(dest []byte, i uint64) {
binary.BigEndian.PutUint64(dest, i)
}
func GetUint64BE(src []byte) uint64 {
return binary.BigEndian.Uint64(src)
}
func PutInt64LE(dest []byte, i int64) {
binary.LittleEndian.PutUint64(dest, uint64(i))
}
func GetInt64LE(src []byte) int64 {
return int64(binary.LittleEndian.Uint64(src))
}
func PutInt64BE(dest []byte, i int64) {
binary.BigEndian.PutUint64(dest, uint64(i))
}
func GetInt64BE(src []byte) int64 {
return int64(binary.BigEndian.Uint64(src))
}
func SearchUint64s(a []uint64, x uint64) int | {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
} |
package nom
import (
"encoding/gob"
"fmt"
)
const (
PortFlood UID = "Ports.PortBcast"
PortAll UID = "Ports.PortAll"
)
type PacketIn struct {
Node UID
InPort UID
BufferID PacketBufferID
Packet Packet
}
func (in PacketIn) String() string {
return fmt.Sprintf("packet in on switch %s port %s", in.Node, in.InPort)
}
type PacketOut struct {
Node UID
InPort UID
BufferID PacketBufferID
Packet Packet
Actions []Action
}
type Packet []byte
func (p Packet) DstMAC() MACAddr {
return MACAddr{p[0], p[1], p[2], p[3], p[4], p[5]}
}
type PacketBufferID uint32
func init() {
gob.Register(Packet{})
gob.Register(PacketBufferID(0))
gob.Register(PacketIn{})
gob.Register(PacketOut{})
}
func (p Packet) SrcMAC() MACAddr | {
return MACAddr{p[6], p[7], p[8], p[9], p[10], p[11]}
} |
package testlib
import (
"os"
"testing"
"github.com/stretchr/testify/require"
)
func Mktmp(tb testing.TB) string | {
tb.Helper()
folder := tb.TempDir()
current, err := os.Getwd()
require.NoError(tb, err)
require.NoError(tb, os.Chdir(folder))
tb.Cleanup(func() {
require.NoError(tb, os.Chdir(current))
})
return folder
} |
package dml_test
import (
"encoding/xml"
"testing"
"baliance.com/gooxml/schema/soo/dml"
)
func TestCT_TablePartStyleConstructor(t *testing.T) {
v := dml.NewCT_TablePartStyle()
if v == nil {
t.Errorf("dml.NewCT_TablePartStyle must return a non-nil value")
}
if err := v.Validate(); err != nil {
t.Errorf("newly constructed dml.CT_TablePartStyle should validate: %s", err)
}
}
func TestCT_TablePartStyleMarshalUnmarshal(t *testing.T) | {
v := dml.NewCT_TablePartStyle()
buf, _ := xml.Marshal(v)
v2 := dml.NewCT_TablePartStyle()
xml.Unmarshal(buf, v2)
} |
package migrations
import "xorm.io/xorm"
func addEmailHashTable(x *xorm.Engine) error | {
type EmailHash struct {
Hash string `xorm:"pk varchar(32)"`
Email string `xorm:"UNIQUE NOT NULL"`
}
return x.Sync2(new(EmailHash))
} |
package xmlkey
import (
"bytes"
"encoding/base64"
"encoding/xml"
"math/big"
)
type (
keyXML struct {
XMLName xml.Name `xml:"RSAKeyValue"`
publicKeyXML
privateKeyXML
}
publicKeyXML struct {
Modulus, Exponent *bigInt
}
privateKeyXML struct {
P, Q, DP, DQ, D, InverseQ *bigInt
}
bigInt struct{ *big.Int }
)
func (k keyXML) HasPublicKey() bool {
return allNotEmpty(k.Exponent, k.Modulus)
}
func (k keyXML) HasPrivateKey() bool {
return allNotEmpty(k.D, k.DP, k.DQ, k.InverseQ, k.P, k.Q)
}
func (bi *bigInt) UnmarshalText(text []byte) error {
bs := make([]byte, base64.StdEncoding.DecodedLen(len(text)))
if _, err := base64.StdEncoding.Decode(bs, text); err != nil {
return err
}
if bi.Int == nil {
bi.Int = new(big.Int)
}
bi.Int.SetBytes(bytes.TrimRight(bs, "\x00"))
return nil
}
func (bi *bigInt) MarshalText() ([]byte, error) {
text := make([]byte, base64.StdEncoding.EncodedLen(len(bi.Bytes())))
base64.StdEncoding.Encode(text, bi.Bytes())
return text, nil
}
func (bi bigInt) BigInt() *big.Int {
return bi.Int
}
func (bi bigInt) Integer() int {
return int(bi.Int64())
}
func (bi bigInt) IsEmpty() bool {
return bi.Int == nil
}
func allNotEmpty(bis ...*bigInt) bool | {
for _, bi := range bis {
if bi == nil || bi.IsEmpty() {
return false
}
}
return true
} |
package blanket_emulator
import (
"fmt"
)
type Event interface {
Hash() uint64
Inspect() string
}
type ReturnEvent uint64
type ReadEvent uint64
type WriteEvent struct {
Addr uint64
Value uint64
}
type SyscallEvent uint64
type InvalidInstructionEvent uint64
func (addr ReadEvent) Hash() uint64 {
return ReadEventHash(uint64(addr))
}
func (s SyscallEvent) Hash() uint64 {
return SysEventHash(uint64(s))
}
func (s ReturnEvent) Hash() uint64 {
return ReturnEventHash(uint64(s))
}
func (s InvalidInstructionEvent) Hash() uint64 {
return InvalidInstructionEventHash(uint64(s))
}
func (addr ReadEvent) Inspect() string {
return fmt.Sprintf("Read([%x])", addr)
}
func (addr ReturnEvent) Inspect() string {
return fmt.Sprintf("Return([%x])", addr)
}
func (s WriteEvent) Inspect() string {
return fmt.Sprintf("Write([%x]=%x)", s.Addr, s.Value)
}
func (s SyscallEvent) Inspect() string {
return fmt.Sprintf("Sys(%x)", s)
}
func (s InvalidInstructionEvent) Inspect() string {
return fmt.Sprintf("InvalidOpcode([%x])", s)
}
func (s WriteEvent) Hash() uint64 | {
return WriteEventHash(s.Addr, s.Value)
} |
package cli
import "github.com/scaleway/scaleway-cli/pkg/commands"
var cmdRm = &Command{
Exec: runRm,
UsageLine: "rm [OPTIONS] SERVER [SERVER...]",
Description: "Remove one or more servers",
Help: "Remove one or more servers.",
Examples: `
$ scw rm myserver
$ scw rm -f myserver
$ scw rm my-stopped-server my-second-stopped-server
$ scw rm $(scw ps -q)
$ scw rm $(scw ps | grep mysql | awk '{print $1}')
`,
}
func init() {
cmdRm.Flag.BoolVar(&rmHelp, []string{"h", "-help"}, false, "Print usage")
cmdRm.Flag.BoolVar(&rmForce, []string{"f", "-force"}, false, "Force the removal of a server")
}
var rmHelp bool
var rmForce bool
func runRm(cmd *Command, rawArgs []string) error | {
if rmHelp {
return cmd.PrintUsage()
}
if len(rawArgs) < 1 {
return cmd.PrintShortUsage()
}
args := commands.RmArgs{
Servers: rawArgs,
Force: rmForce,
}
ctx := cmd.GetContext(rawArgs)
return commands.RunRm(ctx, args)
} |
package srcobj
import (
"fmt"
"io"
)
type DrawChar string
func (dc DrawChar) Dump(w io.Writer) error | {
_, err := fmt.Fprintf(w, `"%s"`, string(dc))
return err
} |
package gen
import (
"regexp"
"strings"
)
func ReplaceSearchCallback(code []byte, modelName string) []byte {
rSearchCallback, _ := regexp.Compile("SearchCallback")
result := rSearchCallback.ReplaceAll(code, []byte("SearchCallback"+strings.Title(modelName)))
return result
}
func RemovePackage(code []byte) []byte {
rPackage, _ := regexp.Compile("package collection")
result := rPackage.ReplaceAll(code, make([]byte, 0))
return result
}
func ReplaceGrizzlyId(code []byte, customType string) []byte {
gICollections, _ := regexp.Compile("GrizzlyId")
result := gICollections.ReplaceAll(code, []byte(strings.Title(customType)))
return result
}
func InjectImports(code []byte, imports []string) (result []byte) {
result = code[:]
for _, i := range imports {
result = append([]byte("\nimport \""+i+"\"\n"), code...)
}
return result
}
func ReplaceImports(code []byte) []byte | {
rICollections, _ := regexp.Compile("(import \"sort\")")
result := rICollections.ReplaceAll(code, []byte(""))
return result
} |
package main
import (
"fmt"
"github.com/jackytck/projecteuler/tools"
)
func isSumOfTwoAbundant(n int, a []bool) bool {
var ret bool
for i := 1; i < n; i++ {
if a[i] && a[n-i] {
ret = true
break
}
}
return ret
}
func solve() int {
var sum int
ab := make([]bool, 28124)
for i := 12; i <= 28123; i++ {
ab[i] = isAbundant(i)
}
for i := 1; i <= 28123; i++ {
if !isSumOfTwoAbundant(i, ab) {
sum += i
}
}
return sum
}
func main() {
fmt.Println(solve())
}
func isAbundant(n int) bool | {
return tools.SumDivisors(n) > n
} |
package middleware
import (
"github.com/drone/drone/shared/model"
"github.com/zenazn/goji/web"
)
func UserToC(c *web.C, user *model.User) {
c.Env["user"] = user
}
func RoleToC(c *web.C, role *model.Perm) {
c.Env["role"] = role
}
func ToUser(c *web.C) *model.User {
var v = c.Env["user"]
if v == nil {
return nil
}
u, ok := v.(*model.User)
if !ok {
return nil
}
return u
}
func ToRepo(c *web.C) *model.Repo {
var v = c.Env["repo"]
if v == nil {
return nil
}
r, ok := v.(*model.Repo)
if !ok {
return nil
}
return r
}
func ToRole(c *web.C) *model.Perm {
var v = c.Env["role"]
if v == nil {
return nil
}
p, ok := v.(*model.Perm)
if !ok {
return nil
}
return p
}
func RepoToC(c *web.C, repo *model.Repo) | {
c.Env["repo"] = repo
} |
package ast
import "monkey/token"
type StringLiteral struct {
Token token.Token
Value string
}
func (s *StringLiteral) expressionNode() {}
func (s *StringLiteral) TokenLiteral() string { return s.Token.Literal }
func (s *StringLiteral) String() string { return s.Token.Literal }
type InterpolatedString struct {
Token token.Token
Value string
ExprMap map[byte]Expression
}
func (is *InterpolatedString) expressionNode() {}
func (is *InterpolatedString) String() string { return is.Token.Literal }
func (is *InterpolatedString) TokenLiteral() string | { return is.Token.Literal } |
package handlers
import (
"github.com/bbiskup/edify-web/defs"
"html/template"
"log"
"net/http"
)
var indexTemplates *template.Template
func init() {
indexTemplates = template.Must(template.ParseFiles(
defs.TemplatePaths("layout.html", "navbar.html", "index.html")...,
))
}
func Index(w http.ResponseWriter, r *http.Request) | {
err := indexTemplates.ExecuteTemplate(w, "layout", nil)
if err != nil {
log.Printf("Error executing template: %s", err)
}
} |
package tristate
type StateValue int
const (
TRISTATE_SUCCESS StateValue = iota
TRISTATE_FAILRUE
TRISTATE_UNKNOWN
)
type TriState struct {
State StateValue
Err error
}
func NewSuccess() *TriState {
return nil
}
func NewUnknown(err error) *TriState {
if err == nil {
panic("error not set")
}
return &TriState{TRISTATE_UNKNOWN, err}
}
func NewFailure(err error) *TriState {
if err == nil {
panic("error not set")
}
return &TriState{TRISTATE_FAILRUE, err}
}
func (state *TriState) Error() string {
return state.Err.Error()
}
func (state *TriState) IsFailure() bool {
return state != nil && state.State == TRISTATE_FAILRUE
}
func (state *TriState) IsUnknown() bool {
return state != nil && state.State == TRISTATE_UNKNOWN
}
func (state *TriState) IsSuccess() bool | {
return state == nil || state.State == TRISTATE_SUCCESS
} |
package v1beta2
import (
v1beta2 "github.com/enmasseproject/enmasse/pkg/apis/admin/v1beta2"
"github.com/enmasseproject/enmasse/pkg/client/clientset/versioned/scheme"
rest "k8s.io/client-go/rest"
)
type AdminV1beta2Interface interface {
RESTClient() rest.Interface
AddressPlansGetter
AddressSpacePlansGetter
}
type AdminV1beta2Client struct {
restClient rest.Interface
}
func (c *AdminV1beta2Client) AddressPlans(namespace string) AddressPlanInterface {
return newAddressPlans(c, namespace)
}
func (c *AdminV1beta2Client) AddressSpacePlans(namespace string) AddressSpacePlanInterface {
return newAddressSpacePlans(c, namespace)
}
func NewForConfigOrDie(c *rest.Config) *AdminV1beta2Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
func New(c rest.Interface) *AdminV1beta2Client {
return &AdminV1beta2Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1beta2.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = scheme.Codecs.WithoutConversion()
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
func (c *AdminV1beta2Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}
func NewForConfig(c *rest.Config) (*AdminV1beta2Client, error) | {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &AdminV1beta2Client{client}, nil
} |
package http
import (
"go-common/app/admin/main/app/model/language"
bm "go-common/library/net/http/blademaster"
)
func languages(c *bm.Context) {
c.JSON(langSvc.Languages(c))
}
func addOrup(c *bm.Context) {
var (
err error
v = &language.Param{}
)
if err = c.Bind(v); err != nil {
return
}
if v.ID > 0 {
err = langSvc.Update(c, v)
} else {
err = langSvc.Insert(c, v)
}
c.JSON(nil, err)
}
func langByID(c *bm.Context) | {
v := &language.Param{}
if err := c.Bind(v); err != nil {
return
}
c.JSON(langSvc.LangByID(c, v.ID))
} |
package log
import (
"os"
"testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
)
func TestLogFile(t *testing.T) {
fileLogWrite := NewFileWriter()
require.NotNil(t, fileLogWrite)
t.Cleanup(func() {
err := fileLogWrite.Close()
assert.NoError(t, err)
err = os.Remove(fileLogWrite.Filename)
assert.NoError(t, err)
})
fileLogWrite.Filename = "grafana_test.log"
err := fileLogWrite.Init()
require.NoError(t, err)
assert.Zero(t, fileLogWrite.maxlinesCurlines)
t.Run("adding lines", func(t *testing.T) {
err := fileLogWrite.WriteLine("test1\n")
require.NoError(t, err)
err = fileLogWrite.WriteLine("test2\n")
require.NoError(t, err)
err = fileLogWrite.WriteLine("test3\n")
require.NoError(t, err)
assert.Equal(t, 3, fileLogWrite.maxlinesCurlines)
})
}
func (w *FileLogWriter) WriteLine(line string) error | {
_, err := w.Write([]byte(line))
return err
} |
package udp
import (
"encoding/binary"
"github.com/davyxu/cellnet/codec"
)
const (
MTU = 1472
packetLen = 2
MsgIDLen = 2
HeaderSize = MsgIDLen + MsgIDLen
)
func RecvPacket(pktData []byte) (msg interface{}, err error) | {
if len(pktData) < packetLen {
return nil, nil
}
datasize := binary.LittleEndian.Uint16(pktData)
if int(datasize) != len(pktData) || datasize > MTU {
return nil, nil
}
msgid := binary.LittleEndian.Uint16(pktData[packetLen:])
msgData := pktData[HeaderSize:]
msg, _, err = codec.DecodeMessage(int(msgid), msgData)
if err != nil {
return nil, err
}
return
} |
package packer
import (
"bytes"
"fmt"
)
var GitCommit string
const Version = "0.5.3"
const VersionPrerelease = "dev"
type versionCommand byte
func (versionCommand) Help() string {
return `usage: packer version
Outputs the version of Packer that is running. There are no additional
command-line flags for this command.`
}
func (versionCommand) Run(env Environment, args []string) int {
env.Ui().Machine("version", Version)
env.Ui().Machine("version-prelease", VersionPrerelease)
env.Ui().Machine("version-commit", GitCommit)
env.Ui().Say(VersionString())
return 0
}
func (versionCommand) Synopsis() string {
return "print Packer version"
}
func VersionString() string | {
var versionString bytes.Buffer
fmt.Fprintf(&versionString, "Packer v%s", Version)
if VersionPrerelease != "" {
fmt.Fprintf(&versionString, ".%s", VersionPrerelease)
if GitCommit != "" {
fmt.Fprintf(&versionString, " (%s)", GitCommit)
}
}
return versionString.String()
} |
package learn
import (
"fmt"
)
type List struct {
Data interface{}
Nextnode *List
}
func myPrint(t interface{}) {
fmt.Println(t)
}
func (l *List) ListLength() int {
var i int = 0
n := l
for n.Nextnode != nil {
i++
n = n.Nextnode
}
return i + 1
}
func (l *List) GetEle(i int) (ele interface{}) {
if i < 0 || i > l.ListLength() {
return nil
}
cur := l
j := 1
for cur.Nextnode != nil {
if j == i {
return cur.Data
}
j++
cur = cur.Nextnode
}
if cur != nil && j == i {
return cur.Data
}
return nil
}
func (l *List) ListDelete(i int) bool {
p := l
j := 1
for j < i && p != nil {
j++
p = p.Nextnode
}
if p == nil || j > i {
return false
}
p.Nextnode = p.Nextnode.Nextnode
return true
}
func (l *List) ListAll() (all string) {
p := l
for p != nil {
all += fmt.Sprintf("%v+", p.Data)
p = p.Nextnode
}
return all
}
func (l *List) ListInsert(i int, ele interface{}) bool | {
var s List
if i < 0 || i > l.ListLength() {
return false
}
s.Data = ele
p := l
j := 1
for j < i && p != nil {
j++
p = p.Nextnode
}
if p != nil && j <= i {
s.Nextnode = p.Nextnode
p.Nextnode = &s
} else {
return false
}
return true
} |
package vhosts
import (
"net/http"
"strings"
"sync"
)
type VirtualHosts struct {
vhosts map[string]http.Handler
mu sync.RWMutex
}
func NewVirtualHosts(vhosts map[string]http.Handler) *VirtualHosts {
v := &VirtualHosts{}
for hosts, h := range vhosts {
for _, host := range strings.Split(hosts, " ") {
if host != "" {
v.HandleHost(h, host)
}
}
}
return v
}
func (v *VirtualHosts) HandleHost(handler http.Handler, hosts ...string) {
v.mu.Lock()
defer v.mu.Unlock()
if v.vhosts == nil {
v.vhosts = make(map[string]http.Handler)
}
for _, host := range hosts {
for _, h := range strings.Split(host, " ") {
if h = strings.TrimSpace(h); h != "" {
v.vhosts[h] = handler
}
}
}
}
func (v *VirtualHosts) ServeHTTP(w http.ResponseWriter, r *http.Request) | {
v.mu.RLock()
defer v.mu.RUnlock()
if v.vhosts != nil {
if handler, ok := v.vhosts[r.Host]; ok && handler != nil {
handler.ServeHTTP(w, r)
return
}
}
http.NotFound(w, r)
} |
package bytealg
const MaxBruteForce = 0
func Index(a, b []byte) int {
panic("unimplemented")
}
func Cutover(n int) int {
panic("unimplemented")
}
func IndexString(s, substr string) int | {
n := len(substr)
c0 := substr[0]
c1 := substr[1]
i := 0
t := len(s) - n + 1
fails := 0
for i < t {
if s[i] != c0 {
o := IndexByteString(s[i:t], c0)
if o < 0 {
return -1
}
i += o
}
if s[i+1] == c1 && s[i:i+n] == substr {
return i
}
i++
fails++
if fails >= 4+i>>4 && i < t {
j := IndexRabinKarp(s[i:], substr)
if j < 0 {
return -1
}
return i + j
}
}
return -1
} |
package util
import (
"strings"
"github.com/spf13/viper"
)
const EnvPrefix = "GSD"
func InitViper(v *viper.Viper, subViperName string) {
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
if subViperName != "" {
v.SetEnvPrefix(EnvPrefix + "_" + strings.ToUpper(subViperName))
} else {
v.SetEnvPrefix(EnvPrefix)
}
v.SetTypeByDefaultValue(true)
v.AutomaticEnv()
}
func GetSubViper(v *viper.Viper, key string) *viper.Viper | {
n := v.Sub(key)
if n == nil {
n = viper.New()
}
InitViper(n, key)
return n
} |
package blobstoredbstatesnapshotio
import (
"fmt"
"golang.org/x/net/context"
"github.com/nyaxt/otaru/metadata"
)
func generateBlobpath() string {
return fmt.Sprintf("%s_SimpleSSLocator", metadata.INodeDBSnapshotBlobpathPrefix)
}
var simplesslocatorTxID int64
type SimpleSSLocator struct{}
func (SimpleSSLocator) Locate(history int) (string, int64, error) {
return generateBlobpath(), simplesslocatorTxID, nil
}
func (SimpleSSLocator) Put(blobpath string, txid int64) error {
simplesslocatorTxID = txid
return nil
}
func (SimpleSSLocator) DeleteOld(ctx context.Context, threshold int, dryRun bool) ([]string, error) {
return []string{}, nil
}
func (SimpleSSLocator) GenerateBlobpath() string | {
return generateBlobpath()
} |
package cli
import (
"errors"
"fmt"
"log"
"github.com/alexyer/ghost/client"
)
func ObtainClient(host string, port int) (*client.GhostClient, error) {
addr := fmt.Sprintf("%s:%d", host, port)
return connect(addr, "tcp")
}
func connect(addr, network string) (*client.GhostClient, error) {
c := client.New(&client.Options{
Addr: addr,
Network: network,
})
if _, err := c.Ping(); err != nil {
return nil, errors.New(fmt.Sprintf("cli-ghost: cannot obtain connection to %s", addr))
}
log.Printf("Connection to %s is successfull.", addr)
return c, nil
}
func ObtainUnixSocketClient(socket string) (*client.GhostClient, error) | {
return connect(socket, "unix")
} |
package test
import "github.com/tidepool-org/platform/test"
func NewAccessToken() string {
return test.RandomStringFromRangeAndCharset(256, 256, test.CharsetAlphaNumeric)
}
func NewSessionToken() string {
return test.RandomStringFromRangeAndCharset(256, 256, test.CharsetAlphaNumeric)
}
func NewRestrictedToken() string {
return test.RandomStringFromRangeAndCharset(40, 40, test.CharsetAlphaNumeric)
}
func NewServiceSecret() string | {
return test.RandomStringFromRangeAndCharset(128, 128, test.CharsetAlphaNumeric)
} |
package account
import (
"flag"
"golang.org/x/net/context"
"github.com/vmware/govmomi/govc/cli"
)
type update struct {
*AccountFlag
}
func init() {
cli.Register("host.account.update", &update{})
}
func (cmd *update) Process(ctx context.Context) error {
if err := cmd.AccountFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *update) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.AccountFlag.HostAccountManager(ctx)
if err != nil {
return err
}
return m.Update(ctx, &cmd.HostAccountSpec)
}
func (cmd *update) Register(ctx context.Context, f *flag.FlagSet) | {
cmd.AccountFlag, ctx = newAccountFlag(ctx)
cmd.AccountFlag.Register(ctx, f)
} |
package byteorder
import (
"encoding/binary"
"net"
"testing"
. "gopkg.in/check.v1"
)
func Test(t *testing.T) {
TestingT(t)
}
type ByteorderSuite struct{}
var _ = Suite(&ByteorderSuite{})
func (b *ByteorderSuite) TestHostToNetwork(c *C) {
switch Native {
case binary.LittleEndian:
c.Assert(HostToNetwork16(0xAABB), Equals, uint16(0xBBAA))
c.Assert(HostToNetwork32(0xAABBCCDD), Equals, uint32(0xDDCCBBAA))
case binary.BigEndian:
c.Assert(HostToNetwork16(0xAABB), Equals, uint16(0xAABB))
c.Assert(HostToNetwork32(0xAABBCCDD), Equals, uint32(0xAABBCCDD))
}
}
func (b *ByteorderSuite) TestNetIPv4ToHost32(c *C) {
switch Native {
case binary.LittleEndian:
c.Assert(NetIPv4ToHost32(net.ParseIP("10.11.129.91")), Equals, uint32(0x5b810b0a))
c.Assert(NetIPv4ToHost32(net.ParseIP("10.11.138.214")), Equals, uint32(0xd68a0b0a))
case binary.BigEndian:
c.Assert(NetIPv4ToHost32(net.ParseIP("10.11.129.91")), Equals, uint32(0x0a0b815b))
c.Assert(NetIPv4ToHost32(net.ParseIP("10.11.138.214")), Equals, uint32(0x0a0b8ad6))
}
}
func (b *ByteorderSuite) TestNativeIsInitialized(c *C) | {
c.Assert(Native, NotNil)
} |
package core
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
type UpdateDedicatedVmHostRequest struct {
DedicatedVmHostId *string `mandatory:"true" contributesTo:"path" name:"dedicatedVmHostId"`
UpdateDedicatedVmHostDetails `contributesTo:"body"`
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
RequestMetadata common.RequestMetadata
}
func (request UpdateDedicatedVmHostRequest) String() string {
return common.PointerString(request)
}
func (request UpdateDedicatedVmHostRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
func (request UpdateDedicatedVmHostRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
type UpdateDedicatedVmHostResponse struct {
RawResponse *http.Response
DedicatedVmHost `presentIn:"body"`
Etag *string `presentIn:"header" name:"etag"`
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response UpdateDedicatedVmHostResponse) HTTPResponse() *http.Response {
return response.RawResponse
}
func (response UpdateDedicatedVmHostResponse) String() string | {
return common.PointerString(response)
} |
package throttler
import (
"vitess.io/vitess/go/sync2"
)
type MaxRateModule struct {
maxRate sync2.AtomicInt64
rateUpdateChan chan<- struct{}
}
func NewMaxRateModule(maxRate int64) *MaxRateModule {
return &MaxRateModule{
maxRate: sync2.NewAtomicInt64(maxRate),
}
}
func (m *MaxRateModule) Start(rateUpdateChan chan<- struct{}) {
m.rateUpdateChan = rateUpdateChan
}
func (m *MaxRateModule) Stop() {}
func (m *MaxRateModule) SetMaxRate(rate int64) {
m.maxRate.Set(rate)
m.rateUpdateChan <- struct{}{}
}
func (m *MaxRateModule) MaxRate() int64 | {
return m.maxRate.Get()
} |
package main
import (
"fmt"
"os"
"time"
"github.com/go-redis/redis"
"github.com/jasonlvhit/gocron"
)
type locker struct {
cache *redis.Client
}
func (s *locker) Lock(key string) (success bool, err error) {
res, err := s.cache.SetNX(key, time.Now().String(), time.Second*15).Result()
if err != nil {
return false, err
}
return res, nil
}
func (s *locker) Unlock(key string) error {
return s.cache.Del(key).Err()
}
func main() {
l := &locker{
redis.NewClient(&redis.Options{
Addr: "localhost:6379",
}),
}
gocron.SetLocker(l)
arg := "Some Name"
args := os.Args[1:]
if len(args) > 0 {
arg = args[0]
}
gocron.Every(1).Second().Lock().Do(lockedTask, arg)
<-gocron.Start()
}
func lockedTask(name string) | {
fmt.Printf("Hello, %s!\n", name)
t := time.NewTicker(time.Millisecond * 100)
c := make(chan struct{})
time.AfterFunc(time.Second*5, func() {
close(c)
})
for {
select {
case <-t.C:
fmt.Print(".")
case <-c:
fmt.Println()
return
}
}
} |
package identity
import (
"github.com/oracle/oci-go-sdk/v46/common"
"net/http"
)
type ListTaggingWorkRequestErrorsRequest struct {
WorkRequestId *string `mandatory:"true" contributesTo:"path" name:"workRequestId"`
Page *string `mandatory:"false" contributesTo:"query" name:"page"`
Limit *int `mandatory:"false" contributesTo:"query" name:"limit"`
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
RequestMetadata common.RequestMetadata
}
func (request ListTaggingWorkRequestErrorsRequest) String() string {
return common.PointerString(request)
}
func (request ListTaggingWorkRequestErrorsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
func (request ListTaggingWorkRequestErrorsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
func (request ListTaggingWorkRequestErrorsRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
type ListTaggingWorkRequestErrorsResponse struct {
RawResponse *http.Response
Items []TaggingWorkRequestErrorSummary `presentIn:"body"`
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
RetryAfter *float32 `presentIn:"header" name:"retry-after"`
OpcNextPage *string `presentIn:"header" name:"opc-next-page"`
}
func (response ListTaggingWorkRequestErrorsResponse) HTTPResponse() *http.Response {
return response.RawResponse
}
func (response ListTaggingWorkRequestErrorsResponse) String() string | {
return common.PointerString(response)
} |
package main
import (
"strconv"
"strings"
)
func ParseForCommands(line string) string {
switch line {
case ":g":
SelectGuild()
line = ""
case ":c":
SelectChannel()
line = ""
default:
}
if strings.HasPrefix(line, ":m") {
AmountStr := strings.Split(line, " ")
if len(AmountStr) < 2 {
Msg(ErrorMsg, "[:m] No Arguments \n")
return ""
}
Amount, err := strconv.Atoi(AmountStr[1])
if err != nil {
Msg(ErrorMsg, "[:m] Argument Error: %s \n", err)
return ""
}
Msg(InfoMsg, "Printing last %d messages!\n", Amount)
State.RetrieveMessages(Amount)
PrintMessages(Amount)
line = ""
}
return line
}
func SelectGuild() {
State.Enabled = false
SelectGuildMenu()
SelectChannelMenu()
State.Enabled = true
ShowContent()
}
func SelectChannel() | {
State.Enabled = false
SelectChannelMenu()
State.Enabled = true
ShowContent()
} |
package backoff
import (
"context"
"time"
)
type BackOffContext interface {
BackOff
Context() context.Context
}
type backOffContext struct {
BackOff
ctx context.Context
}
func WithContext(b BackOff, ctx context.Context) BackOffContext {
if ctx == nil {
panic("nil context")
}
if b, ok := b.(*backOffContext); ok {
return &backOffContext{
BackOff: b.BackOff,
ctx: ctx,
}
}
return &backOffContext{
BackOff: b,
ctx: ctx,
}
}
func (b *backOffContext) Context() context.Context {
return b.ctx
}
func (b *backOffContext) NextBackOff() time.Duration {
select {
case <-b.ctx.Done():
return Stop
default:
}
next := b.BackOff.NextBackOff()
if deadline, ok := b.ctx.Deadline(); ok && deadline.Sub(time.Now()) < next {
return Stop
}
return next
}
func ensureContext(b BackOff) BackOffContext | {
if cb, ok := b.(BackOffContext); ok {
return cb
}
return WithContext(b, context.Background())
} |
package state
import (
"net/url"
"gopkg.in/juju/charm.v3"
)
type charmDoc struct {
URL *charm.URL `bson:"_id"`
Meta *charm.Meta
Config *charm.Config
Actions *charm.Actions
BundleURL *url.URL
BundleSha256 string
PendingUpload bool
Placeholder bool
}
type Charm struct {
st *State
doc charmDoc
}
func newCharm(st *State, cdoc *charmDoc) (*Charm, error) {
return &Charm{st: st, doc: *cdoc}, nil
}
func (c *Charm) String() string {
return c.doc.URL.String()
}
func (c *Charm) Revision() int {
return c.doc.URL.Revision
}
func (c *Charm) Meta() *charm.Meta {
return c.doc.Meta
}
func (c *Charm) Config() *charm.Config {
return c.doc.Config
}
func (c *Charm) Actions() *charm.Actions {
return c.doc.Actions
}
func (c *Charm) BundleURL() *url.URL {
return c.doc.BundleURL
}
func (c *Charm) BundleSha256() string {
return c.doc.BundleSha256
}
func (c *Charm) IsUploaded() bool {
return !c.doc.PendingUpload
}
func (c *Charm) IsPlaceholder() bool {
return c.doc.Placeholder
}
func (c *Charm) URL() *charm.URL | {
clone := *c.doc.URL
return &clone
} |
package dax
type Grapher interface {
GetParent() Grapher
AddChild(child Grapher)
GetChildren() []Grapher
}
type nodeStack struct {
nodes []Grapher
}
func (s *nodeStack) Init() {
s.nodes = make([]Grapher, 0, 16)
}
func (s *nodeStack) Empty() bool {
return len(s.nodes) == 0
}
func (s *nodeStack) Push(n Grapher) {
s.nodes = append(s.nodes, n)
}
func (s *nodeStack) Pop() Grapher {
i := len(s.nodes) - 1
n := s.nodes[i]
s.nodes[i] = nil
s.nodes = s.nodes[:i]
return n
}
type SceneGraph struct {
Node
}
func NewSceneGraph() *SceneGraph {
sg := new(SceneGraph)
sg.Init()
return sg
}
func (sg *SceneGraph) Init() {
sg.Node.Init()
}
func (sg *SceneGraph) updateWorldTransform() {
sg.Node.updateWorldTransform(false)
}
func (sg *SceneGraph) Traverse() <-chan Grapher {
ch := make(chan Grapher)
go func() {
var stack nodeStack
stack.Init()
stack.Push(sg)
for !stack.Empty() {
n := stack.Pop()
ch <- n
children := n.GetChildren()
for i := len(children) - 1; i >= 0; i-- {
stack.Push(children[i])
}
}
close(ch)
}()
return ch
}
func (sg *SceneGraph) Draw(fb Framebuffer) {
fb.render().drawSceneGraph(fb, sg)
}
func (sg *SceneGraph) Update(time float64) | {
sg.updateWorldTransform()
} |
package internal
import G "github.com/ionous/sashimi/game"
type PendingChain struct {
src *GameEventAdapter
}
func (c PendingChain) Then(cb G.Callback) {
if c.src != nil {
chain := ChainedCallback{c.src.data, cb}
chain.Run(c.src.Game)
}
}
func NewPendingChain(src *GameEventAdapter, _ Future) PendingChain | {
return PendingChain{src}
} |
package query
func shouldEscape(c byte) bool {
if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' {
return false
}
switch c {
case '-', '_', '.', '~':
return false
}
return true
}
func Escape(s string) string | {
hexCount := 0
for i := 0; i < len(s); i++ {
c := s[i]
if shouldEscape(c) {
hexCount++
}
}
if hexCount == 0 {
return s
}
t := make([]byte, len(s)+2*hexCount)
j := 0
for i := 0; i < len(s); i++ {
switch c := s[i]; {
case shouldEscape(c):
t[j] = '%'
t[j+1] = "0123456789ABCDEF"[c>>4]
t[j+2] = "0123456789ABCDEF"[c&15]
j += 3
default:
t[j] = s[i]
j++
}
}
return string(t)
} |
package protobuf
import "github.com/m3db/m3x/pool"
const (
defaultInitBufferSize = 2880
defaultMaxUnaggregatedMessageSize = 50 * 1024 * 1024
)
type UnaggregatedOptions interface {
SetBytesPool(value pool.BytesPool) UnaggregatedOptions
BytesPool() pool.BytesPool
SetInitBufferSize(value int) UnaggregatedOptions
InitBufferSize() int
SetMaxMessageSize(value int) UnaggregatedOptions
MaxMessageSize() int
}
type unaggregatedOptions struct {
bytesPool pool.BytesPool
initBufferSize int
maxMessageSize int
}
func NewUnaggregatedOptions() UnaggregatedOptions {
p := pool.NewBytesPool(nil, nil)
p.Init()
return &unaggregatedOptions{
bytesPool: p,
initBufferSize: defaultInitBufferSize,
maxMessageSize: defaultMaxUnaggregatedMessageSize,
}
}
func (o *unaggregatedOptions) SetBytesPool(value pool.BytesPool) UnaggregatedOptions {
opts := *o
opts.bytesPool = value
return &opts
}
func (o *unaggregatedOptions) SetInitBufferSize(value int) UnaggregatedOptions {
opts := *o
opts.initBufferSize = value
return &opts
}
func (o *unaggregatedOptions) InitBufferSize() int {
return o.initBufferSize
}
func (o *unaggregatedOptions) SetMaxMessageSize(value int) UnaggregatedOptions {
opts := *o
opts.maxMessageSize = value
return &opts
}
func (o *unaggregatedOptions) MaxMessageSize() int {
return o.maxMessageSize
}
func (o *unaggregatedOptions) BytesPool() pool.BytesPool | {
return o.bytesPool
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.