input
stringlengths 24
2.11k
| output
stringlengths 7
948
|
---|---|
package cli
import (
"fmt"
"github.com/dailymuse/git-fit/config"
"github.com/dailymuse/git-fit/transport"
"github.com/dailymuse/git-fit/util"
"io/ioutil"
"os"
)
func Gc(schema *config.Config, trans transport.Transport, args []string) | {
savedFiles := make(map[string]bool, len(schema.Files)*2)
for _, hash := range schema.Files {
savedFiles[hash] = true
}
allFiles, err := ioutil.ReadDir(".git/fit")
if err != nil {
util.Fatal("Could not read .git/fit: %s\n", err.Error())
}
for _, file := range allFiles {
_, ok := savedFiles[file.Name()]
if !ok {
path := fmt.Sprintf(".git/fit/%s", file.Name())
err = os.Remove(path)
if err != nil {
util.Error("Could not delete cached file %s: %s\n", path, err.Error())
}
}
}
} |
package session
import (
"github.com/gorilla/mux"
"github.com/rebel-l/sessionservice/src/authentication"
"github.com/rebel-l/sessionservice/src/configuration"
"github.com/rebel-l/sessionservice/src/storage"
log "github.com/sirupsen/logrus"
"net/http"
)
type Session struct {
Storage storage.Handler
Authentication *authentication.Authentication
Config *configuration.Service
}
func NewSession(
storage storage.Handler,
authentication *authentication.Authentication,
config *configuration.Service) *Session {
s := new(Session)
s.Storage = storage
s.Authentication = authentication
s.Config = config
return s
}
func (s *Session) handlerFactory(method string) http.Handler {
var handler func(http.ResponseWriter, *http.Request)
switch method {
case http.MethodPut:
put := NewPut(s)
handler = put.Handler
default:
log.Panicf("Method %s is not implemented", method)
return nil
}
return s.Authentication.Middleware(http.HandlerFunc(handler))
}
func (s *Session) Init(router *mux.Router) | {
log.Debug("Session endpoint: Init ...")
router.Handle("/session/", s.handlerFactory(http.MethodPut)).Methods(http.MethodPut)
log.Debug("Session endpoint: initialized!")
} |
package eventbreakpoints
import (
"context"
"github.com/chromedp/cdproto/cdp"
)
type SetInstrumentationBreakpointParams struct {
EventName string `json:"eventName"`
}
func SetInstrumentationBreakpoint(eventName string) *SetInstrumentationBreakpointParams {
return &SetInstrumentationBreakpointParams{
EventName: 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 (p *RemoveInstrumentationBreakpointParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandRemoveInstrumentationBreakpoint, p, nil)
}
const (
CommandSetInstrumentationBreakpoint = "EventBreakpoints.setInstrumentationBreakpoint"
CommandRemoveInstrumentationBreakpoint = "EventBreakpoints.removeInstrumentationBreakpoint"
)
func RemoveInstrumentationBreakpoint(eventName string) *RemoveInstrumentationBreakpointParams | {
return &RemoveInstrumentationBreakpointParams{
EventName: eventName,
}
} |
package menu
import "fmt"
type MenuFunc func()
type MenuEntry struct {
MenuText string
MenuSelector int
MenuFunction MenuFunc
StopRunning bool
}
func (entry MenuEntry) IsSelected(selector int) bool {
return entry.MenuSelector == selector
}
func (entry MenuEntry) PrintEntry() | {
fmt.Printf("%d - %v\n", entry.MenuSelector, entry.MenuText)
} |
package language
import (
"golang.org/x/net/context"
"google.golang.org/grpc/metadata"
)
func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {
out, _ := metadata.FromOutgoingContext(ctx)
out = out.Copy()
for _, md := range mds {
for k, v := range md {
out[k] = append(out[k], v...)
}
}
return metadata.NewOutgoingContext(ctx, out)
}
func DefaultAuthScopes() []string | {
return []string{
"https:www.googleapis.com/auth/cloud-platform",
}
} |
package db
import (
"github.com/globalsign/mgo"
"github.com/tsuru/config"
"github.com/tsuru/tsuru/db/storage"
)
const (
DefaultDatabaseURL = "127.0.0.1:27017"
DefaultDatabaseName = "gandalf"
)
type Storage struct {
*storage.Storage
}
func conn() (*storage.Storage, error) {
url, dbname := DbConfig()
return storage.Open(url, dbname)
}
func DbConfig() (string, string) {
url, _ := config.GetString("database:url")
if url == "" {
url = DefaultDatabaseURL
}
dbname, _ := config.GetString("database:name")
if dbname == "" {
dbname = DefaultDatabaseName
}
return url, dbname
}
func (s *Storage) Repository() *storage.Collection {
return s.Collection("repository")
}
func (s *Storage) User() *storage.Collection {
return s.Collection("user")
}
func (s *Storage) Key() *storage.Collection {
bodyIndex := mgo.Index{Key: []string{"body"}, Unique: true}
nameIndex := mgo.Index{Key: []string{"username", "name"}, Unique: true}
c := s.Collection("key")
c.EnsureIndex(bodyIndex)
c.EnsureIndex(nameIndex)
return c
}
func Conn() (*Storage, error) | {
var (
strg Storage
err error
)
strg.Storage, err = conn()
return &strg, err
} |
package watt
import (
"encoding/json"
"time"
"github.com/datawire/ambassador/pkg/consulwatch"
"github.com/datawire/ambassador/pkg/k8s"
)
type ConsulSnapshot struct {
Endpoints map[string]consulwatch.Endpoints `json:",omitempty"`
}
type Error struct {
Source string
Message string
Timestamp int64
}
func NewError(source, message string) Error {
return Error{Source: source, Message: message, Timestamp: time.Now().Unix()}
}
type Snapshot struct {
Consul ConsulSnapshot `json:",omitempty"`
Kubernetes map[string][]k8s.Resource `json:",omitempty"`
Errors map[string][]Error `json:",omitempty"`
}
func (s *ConsulSnapshot) DeepCopy() (*ConsulSnapshot, error) | {
jsonBytes, err := json.Marshal(s)
if err != nil {
return nil, err
}
res := &ConsulSnapshot{}
err = json.Unmarshal(jsonBytes, res)
return res, err
} |
package engine
import (
"time"
"github.com/aws/amazon-ecs-agent/agent/api"
)
type impossibleTransitionError struct {
state api.ContainerStatus
}
func (err *impossibleTransitionError) Error() string {
return "Cannot transition to " + err.state.String()
}
func (err *impossibleTransitionError) ErrorName() string { return "ImpossibleStateTransitionError" }
type DockerTimeoutError struct {
duration time.Duration
transition string
}
func (err *DockerTimeoutError) Error() string {
return "Could not transition to " + err.transition + "; timed out after waiting " + err.duration.String()
}
func (err *DockerTimeoutError) ErrorName() string { return "DockerTimeoutError" }
type ContainerVanishedError struct{}
func (err ContainerVanishedError) Error() string { return "No container matching saved ID found" }
func (err ContainerVanishedError) ErrorName() string { return "ContainerVanishedError" }
type CannotXContainerError struct {
transition string
msg string
}
func (err CannotXContainerError) Error() string { return err.msg }
func (err CannotXContainerError) ErrorName() string {
return "Cannot" + err.transition + "ContainerError"
}
type OutOfMemoryError struct{}
func (err OutOfMemoryError) Error() string { return "Container killed due to memory usage" }
func (err OutOfMemoryError) ErrorName() string { return "OutOfMemoryError" }
type DockerStateError struct {
dockerError string
name string
}
func NewDockerStateError(err string) DockerStateError {
return DockerStateError{
dockerError: err,
name: "DockerStateError",
}
}
func (err DockerStateError) Error() string {
return err.dockerError
}
func (err DockerStateError) ErrorName() string | {
return err.name
} |
package do
import (
"fmt"
"reflect"
)
func WaitForErrorChannels(ctx Context, channels ...<-chan error) (err error) {
cases := make([]reflect.SelectCase, len(channels)+1)
ctxDoneCaseIndex := len(channels)
for i, ch := range channels {
cases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ch)}
}
if ctx != nil {
cases[ctxDoneCaseIndex] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ctx.Done())}
}
remaining := len(channels)
for remaining > 0 {
i, value, ok := reflect.Select(cases)
if i == ctxDoneCaseIndex {
return ctx.Err()
} else if !value.IsNil() {
return value.Interface().(error)
} else if !ok {
return fmt.Errorf("WaitForErrorChannels attempted read from closed channel #%d", i)
}
cases[i].Chan = reflect.ValueOf(nil)
remaining--
}
return nil
}
func CheckChan(channel chan interface{}) (didRead bool, item interface{}) {
return nonBlockingChannelRead(channel)
}
func CheckStructChan(channel chan struct{}) (didRead bool) {
didRead, _ = nonBlockingChannelRead(channel)
return didRead
}
func nonBlockingChannelRead(channel interface{}) (didRead bool, item interface{}) {
rCase := reflect.SelectCase{
Chan: reflect.ValueOf(channel),
Dir: reflect.SelectRecv,
}
_, value, didRead := reflect.Select([]reflect.SelectCase{rCase})
return didRead, value.Interface()
}
func CheckErrChan(errChan chan error) (didRead bool, err error) | {
didRead, val := nonBlockingChannelRead(errChan)
return didRead, val.(error)
} |
package model
import (
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils"
"strings"
)
type RegisterServerAutoRecoveryResponse struct {
HttpStatusCode int `json:"-"`
}
func (o RegisterServerAutoRecoveryResponse) String() string | {
data, err := utils.Marshal(o)
if err != nil {
return "RegisterServerAutoRecoveryResponse struct{}"
}
return strings.Join([]string{"RegisterServerAutoRecoveryResponse", string(data)}, " ")
} |
package model
type Interface interface {
VisitString(name string, resume func())
VisitInt(name string, resume func())
VisitFloat(name string, resume func())
VisitBool(name string, resume func())
VisitPtr(name string, resume func())
VisitBytes(name string, resume func())
VisitSlice(name string, resume func())
VisitStruct(name string, fields []Field, resume func())
VisitStructField(field Field, resume func())
VisitMap(name string, resume func())
VisitCustom(name string, resume func())
VisitReference(name string, resume func())
}
type Visitor struct{}
func (self *Visitor) VisitString(name string, resume func()) {
resume()
}
func (self *Visitor) VisitInt(name string, resume func()) {
resume()
}
func (self *Visitor) VisitFloat(name string, resume func()) {
resume()
}
func (self *Visitor) VisitBool(name string, resume func()) {
resume()
}
func (self *Visitor) VisitPtr(name string, resume func()) {
resume()
}
func (self *Visitor) VisitBytes(name string, resume func()) {
resume()
}
func (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {
resume()
}
func (self *Visitor) VisitStructField(field Field, resume func()) {
resume()
}
func (self *Visitor) VisitMap(name string, resume func()) {
resume()
}
func (self *Visitor) VisitCustom(name string, resume func()) {
resume()
}
func (self *Visitor) VisitReference(name string, resume func()) {
resume()
}
type EmbeddedStructVisitor struct {
Interface
}
func (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {
resume()
}
func (self *Visitor) VisitSlice(name string, resume func()) | {
resume()
} |
package mock
import (
"fmt"
"time"
"github.com/cilium/cilium/pkg/lock"
)
type MockMetrics struct {
mutex lock.RWMutex
apiCall map[string]float64
rateLimit map[string]time.Duration
}
func NewMockMetrics() *MockMetrics {
return &MockMetrics{
apiCall: map[string]float64{},
rateLimit: map[string]time.Duration{},
}
}
func (m *MockMetrics) APICall(operation, status string) float64 {
m.mutex.RLock()
defer m.mutex.RUnlock()
return m.apiCall[fmt.Sprintf("operation=%s, status=%s", operation, status)]
}
func (m *MockMetrics) RateLimit(operation string) time.Duration {
m.mutex.RLock()
defer m.mutex.RUnlock()
return m.rateLimit[operation]
}
func (m *MockMetrics) ObserveRateLimit(operation string, delay time.Duration) {
m.mutex.Lock()
m.rateLimit[operation] += delay
m.mutex.Unlock()
}
func (m *MockMetrics) ObserveAPICall(operation, status string, duration float64) | {
m.mutex.Lock()
m.apiCall[fmt.Sprintf("operation=%s, status=%s", operation, status)] += duration
m.mutex.Unlock()
} |
package main
import (
fmtlog "log"
"time"
"github.com/BurntSushi/toml"
"github.com/emilevauge/traefik/provider"
"github.com/emilevauge/traefik/types"
)
type GlobalConfiguration struct {
Port string
GraceTimeOut int64
AccessLogsFile string
TraefikLogsFile string
Certificates []Certificate
LogLevel string
ProvidersThrottleDuration time.Duration
Docker *provider.Docker
File *provider.File
Web *WebProvider
Marathon *provider.Marathon
Consul *provider.Consul
Etcd *provider.Etcd
Zookeeper *provider.Zookepper
Boltdb *provider.BoltDb
}
type Certificate struct {
CertFile string
KeyFile string
}
func LoadFileConfig(file string) *GlobalConfiguration {
configuration := NewGlobalConfiguration()
if _, err := toml.DecodeFile(file, configuration); err != nil {
fmtlog.Fatalf("Error reading file: %s", err)
}
return configuration
}
type configs map[string]*types.Configuration
func NewGlobalConfiguration() *GlobalConfiguration | {
globalConfiguration := new(GlobalConfiguration)
globalConfiguration.Port = ":80"
globalConfiguration.GraceTimeOut = 10
globalConfiguration.LogLevel = "ERROR"
globalConfiguration.ProvidersThrottleDuration = time.Duration(2 * time.Second)
return globalConfiguration
} |
package runners
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"text/template"
"github.com/davecgh/go-spew/spew"
"github.com/kylelemons/godebug/pretty"
yaml "gopkg.in/yaml.v2"
)
func describeStruct(t interface{}, depth int) string {
prefix := strings.Repeat(" ", depth)
var out string
s := reflect.Indirect(reflect.ValueOf(t))
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
out = fmt.Sprintf("%s%s%s %s\n", out, prefix, typeOfT.Field(i).Name, typeOfT.Field(i).Type)
switch f.Type().Kind() {
case reflect.Struct, reflect.Ptr:
out = fmt.Sprintf("%s%s{\n", out, prefix)
out = fmt.Sprintf("%s%s", out, describeStruct(f.Interface(), depth+1))
out = fmt.Sprintf("%s%s}\n", out, prefix)
}
}
return out
}
func getFuncs() template.FuncMap | {
return template.FuncMap{
"pretty": func(i interface{}) string {
return pretty.Sprint(i)
},
"json": func(i interface{}) string {
json, _ := json.MarshalIndent(i, "", "\t")
return string(json)
},
"yaml": func(i interface{}) string {
yaml, _ := yaml.Marshal(i)
return string(yaml)
},
"spew": func(i interface{}) string {
return spew.Sprint(i)
},
"describe": func(i interface{}) string {
return describeStruct(i, 0)
},
}
} |
package vm
import (
"github.com/rancher/wrangler/pkg/generic"
"k8s.io/client-go/rest"
)
type Factory struct {
*generic.Factory
}
func NewFactoryFromConfigOrDie(config *rest.Config) *Factory {
f, err := NewFactoryFromConfig(config)
if err != nil {
panic(err)
}
return f
}
func NewFactoryFromConfig(config *rest.Config) (*Factory, error) {
return NewFactoryFromConfigWithOptions(config, nil)
}
func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) {
return NewFactoryFromConfigWithOptions(config, &FactoryOptions{
Namespace: namespace,
})
}
type FactoryOptions = generic.FactoryOptions
func (c *Factory) Vm() Interface {
return New(c.ControllerFactory())
}
func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) | {
f, err := generic.NewFactoryFromConfigWithOptions(config, opts)
return &Factory{
Factory: f,
}, err
} |
package locus
import (
"github.com/gocircuit/circuit/use/circuit"
)
type XLocus struct {
l *Locus
}
func (x XLocus) GetPeers() []*Peer {
return x.l.GetPeers()
}
func (x XLocus) Self() interface{} {
return x.l.Self()
}
type YLocus struct {
X circuit.PermX
}
func (y YLocus) GetPeers() map[string]*Peer {
r := make(map[string]*Peer)
for _, p := range y.X.Call("GetPeers")[0].([]*Peer) {
r[p.Key()] = p
}
return r
}
func (y YLocus) Self() *Peer {
return y.X.Call("Self")[0].(*Peer)
}
func init() | {
circuit.RegisterValue(XLocus{})
} |
package rfc
import (
"fmt"
"strings"
"github.com/zmap/zcrypto/x509"
"github.com/zmap/zlint/v3/lint"
"github.com/zmap/zlint/v3/util"
)
type extDuplicateExtension struct{}
func init() {
lint.RegisterLint(&lint.Lint{
Name: "e_ext_duplicate_extension",
Description: "A certificate MUST NOT include more than one instance of a particular extension",
Citation: "RFC 5280: 4.2",
Source: lint.RFC5280,
EffectiveDate: util.RFC2459Date,
Lint: &extDuplicateExtension{},
})
}
func (l *extDuplicateExtension) Initialize() error {
return nil
}
func (l *extDuplicateExtension) CheckApplies(cert *x509.Certificate) bool {
return cert.Version == 3
}
func (l *extDuplicateExtension) Execute(cert *x509.Certificate) *lint.LintResult | {
extensionOIDs := make(map[string]bool)
duplicateOIDs := make(map[string]bool)
for _, ext := range cert.Extensions {
oid := ext.Id.String()
if alreadySeen := extensionOIDs[oid]; alreadySeen {
duplicateOIDs[oid] = true
} else {
extensionOIDs[oid] = true
}
}
if len(duplicateOIDs) == 0 {
return &lint.LintResult{Status: lint.Pass}
}
var duplicateOIDsList []string
for oid := range duplicateOIDs {
duplicateOIDsList = append(duplicateOIDsList, oid)
}
return &lint.LintResult{
Status: lint.Error,
Details: fmt.Sprintf(
"The following extensions are duplicated: %s",
strings.Join(duplicateOIDsList, ", ")),
}
} |
package rest
import (
"time"
eventsapiv1beta1 "k8s.io/api/events/v1beta1"
"k8s.io/apiserver/pkg/registry/generic"
"k8s.io/apiserver/pkg/registry/rest"
genericapiserver "k8s.io/apiserver/pkg/server"
serverstorage "k8s.io/apiserver/pkg/server/storage"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/pkg/apis/events"
eventstore "k8s.io/kubernetes/pkg/registry/core/event/storage"
)
type RESTStorageProvider struct {
TTL time.Duration
}
func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) {
apiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(events.GroupName, legacyscheme.Registry, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)
if apiResourceConfigSource.VersionEnabled(eventsapiv1beta1.SchemeGroupVersion) {
apiGroupInfo.VersionedResourcesStorageMap[eventsapiv1beta1.SchemeGroupVersion.Version] = p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter)
apiGroupInfo.GroupMeta.GroupVersion = eventsapiv1beta1.SchemeGroupVersion
}
return apiGroupInfo, true
}
func (p RESTStorageProvider) GroupName() string {
return events.GroupName
}
func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage | {
storage := map[string]rest.Storage{}
eventsStorage := eventstore.NewREST(restOptionsGetter, uint64(p.TTL.Seconds()))
storage["events"] = eventsStorage
return storage
} |
package atomic
import (
"encoding/json"
"strconv"
"sync/atomic"
)
type Uint32 struct {
_ nocmp
v uint32
}
func NewUint32(val uint32) *Uint32 {
return &Uint32{v: val}
}
func (i *Uint32) Load() uint32 {
return atomic.LoadUint32(&i.v)
}
func (i *Uint32) Add(delta uint32) uint32 {
return atomic.AddUint32(&i.v, delta)
}
func (i *Uint32) Sub(delta uint32) uint32 {
return atomic.AddUint32(&i.v, ^(delta - 1))
}
func (i *Uint32) Inc() uint32 {
return i.Add(1)
}
func (i *Uint32) Dec() uint32 {
return i.Sub(1)
}
func (i *Uint32) CAS(old, new uint32) (swapped bool) {
return atomic.CompareAndSwapUint32(&i.v, old, new)
}
func (i *Uint32) Swap(val uint32) (old uint32) {
return atomic.SwapUint32(&i.v, val)
}
func (i *Uint32) MarshalJSON() ([]byte, error) {
return json.Marshal(i.Load())
}
func (i *Uint32) UnmarshalJSON(b []byte) error {
var v uint32
if err := json.Unmarshal(b, &v); err != nil {
return err
}
i.Store(v)
return nil
}
func (i *Uint32) String() string {
v := i.Load()
return strconv.FormatUint(uint64(v), 10)
}
func (i *Uint32) Store(val uint32) | {
atomic.StoreUint32(&i.v, val)
} |
package test_utils
import (
"fmt"
"simplejsondb/dbio"
)
type InMemoryDataFile struct {
Blocks [][]byte
CloseFunc func() error
ReadBlockFunc func(uint16, []byte) error
WriteBlockFunc func(uint16, []byte) error
}
func NewFakeDataFile(blocksCount int) *InMemoryDataFile {
blocks := [][]byte{}
for i := 0; i < blocksCount; i++ {
blocks = append(blocks, make([]byte, dbio.DATABLOCK_SIZE))
}
return NewFakeDataFileWithBlocks(blocks)
}
func NewFakeDataFileWithBlocks(blocks [][]byte) *InMemoryDataFile {
return &InMemoryDataFile{
Blocks: blocks,
CloseFunc: func() error {
return nil
},
WriteBlockFunc: func(id uint16, data []byte) error {
block := blocks[id]
for i := range block {
block[i] = data[i]
}
return nil
},
ReadBlockFunc: func(id uint16, data []byte) error {
if id < 0 || id >= uint16(len(blocks)) {
return fmt.Errorf("Invalid datablock requested: %d", id)
}
block := blocks[id]
for i := 0; i < len(block); i++ {
data[i] = block[i]
}
return nil
},
}
}
func (df *InMemoryDataFile) Close() error {
return df.CloseFunc()
}
func (df *InMemoryDataFile) ReadBlock(id uint16, data []byte) error {
return df.ReadBlockFunc(id, data)
}
func (df *InMemoryDataFile) WriteBlock(id uint16, data []byte) error | {
return df.WriteBlockFunc(id, data)
} |
package main
import (
"strings"
"testing"
)
func TestLogParser(t *testing.T) | {
fields := []string{"", "", "size", "", "", "duration", "method", "url", "", "", "mime_type", "agent"}
p := NewLogParser(strings.NewReader(ssvLog), NewSSVLexer(fields))
ch, err := p.Get()
if err != nil {
t.Fatalf("%v\n", err)
}
for r := range ch {
if r.Err() != nil {
t.Errorf("%v", r.Err())
}
}
} |
package server
var skipSystemMastersAuthorizer = false
func SkipSystemMastersAuthorizer() | {
skipSystemMastersAuthorizer = true
} |
package server
import (
"reflect"
"testing"
"github.com/cockroachdb/cockroach/gossip/resolver"
"github.com/cockroachdb/cockroach/util/leaktest"
)
func TestParseNodeAttributes(t *testing.T) {
defer leaktest.AfterTest(t)
ctx := NewContext()
ctx.Attrs = "attr1=val1::attr2=val2"
ctx.Stores = "mem=1"
ctx.GossipBootstrap = "self="
if err := ctx.Init("start"); err != nil {
t.Fatalf("Failed to initialize the context: %v", err)
}
expected := []string{"attr1=val1", "attr2=val2"}
if !reflect.DeepEqual(ctx.NodeAttributes.GetAttrs(), expected) {
t.Fatalf("Unexpected attributes: %v", ctx.NodeAttributes.GetAttrs())
}
}
func TestParseGossipBootstrapAddrs(t *testing.T) | {
defer leaktest.AfterTest(t)
ctx := NewContext()
ctx.GossipBootstrap = "localhost:12345,,localhost:23456"
ctx.Stores = "mem=1"
if err := ctx.Init("start"); err != nil {
t.Fatalf("Failed to initialize the context: %v", err)
}
r1, err := resolver.NewResolver(&ctx.Context, "tcp=localhost:12345")
if err != nil {
t.Fatal(err)
}
r2, err := resolver.NewResolver(&ctx.Context, "tcp=localhost:23456")
if err != nil {
t.Fatal(err)
}
expected := []resolver.Resolver{r1, r2}
if !reflect.DeepEqual(ctx.GossipBootstrapResolvers, expected) {
t.Fatalf("Unexpected bootstrap addresses: %v, expected: %v", ctx.GossipBootstrapResolvers, expected)
}
} |
package cmd
import (
"fmt"
"github.com/aptly-dev/aptly/deb"
"github.com/smira/commander"
)
func aptlySnapshotRename(cmd *commander.Command, args []string) error {
var (
err error
snapshot *deb.Snapshot
)
if len(args) != 2 {
cmd.Usage()
return commander.ErrCommandError
}
oldName, newName := args[0], args[1]
snapshot, err = context.CollectionFactory().SnapshotCollection().ByName(oldName)
if err != nil {
return fmt.Errorf("unable to rename: %s", err)
}
_, err = context.CollectionFactory().SnapshotCollection().ByName(newName)
if err == nil {
return fmt.Errorf("unable to rename: snapshot %s already exists", newName)
}
snapshot.Name = newName
err = context.CollectionFactory().SnapshotCollection().Update(snapshot)
if err != nil {
return fmt.Errorf("unable to rename: %s", err)
}
fmt.Printf("\nSnapshot %s -> %s has been successfully renamed.\n", oldName, newName)
return err
}
func makeCmdSnapshotRename() *commander.Command | {
cmd := &commander.Command{
Run: aptlySnapshotRename,
UsageLine: "rename <old-name> <new-name>",
Short: "renames snapshot",
Long: `
Command changes name of the snapshot. Snapshot name should be unique.
Example:
$ aptly snapshot rename wheezy-min wheezy-main
`,
}
return cmd
} |
package main
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"testing"
. "gopkg.in/check.v1"
)
func Test(t *testing.T) {
TestingT(t)
}
type CommonTests struct {
out *bytes.Buffer
d *Dispatcher
}
var _ = Suite(&CommonTests{})
func removeFilesInDir(dir string) error {
files, err := ioutil.ReadDir(dir)
if err != nil {
return err
}
for _, file := range files {
path := filepath.Join(dir, file.Name())
err = os.Remove(path)
if err != nil {
return err
}
}
return nil
}
func (t *CommonTests) SetUpTest(c *C) | {
t.out = new(bytes.Buffer)
t.d = &Dispatcher{stderr: t.out}
} |
import "sort"
type Schedule struct {
intervals []Interval
}
func (s *Schedule) Len() int {
return len(s.intervals)
}
func (s *Schedule) Swap(i, j int) {
s.intervals[i], s.intervals[j] = s.intervals[j], s.intervals[i]
}
func (s *Schedule) Check() bool {
for i:=0; i<len(s.intervals)-1; i++ {
if s.intervals[i].End > s.intervals[i+1].Start {
return false
}
}
return true
}
func canAttendMeetings(intervals []Interval) bool {
if len(intervals) <= 1 {
return true
}
s := Schedule{intervals}
sort.Sort(&s)
return s.Check()
}
func (s *Schedule) Less(i, j int) bool | {
if s.intervals[i].Start < s.intervals[j].Start {
return true
}
return false
} |
package sample
import (
"time"
"encoding/json"
)
type Datum struct {
Status string `json:"status"`
Timestamp time.Time `json:"timestamp"`
}
type Sample struct {
Key string `json:"key"`
Typ string `json:"type"`
Data Datum `json:"data"`
}
func Init() Sample {
sample := Sample{"sample","testing", Datum{"ok", time.Now()}}
return sample
}
func ConvertStatus(value int) string{
switch value {
case 1:
return "ok"
default:
return "error"
}
}
func (m *Sample) Json() string | {
result, _ := json.Marshal(m)
return string(result)
} |
package timeutil
import (
"time"
)
func SetTimeout(t time.Duration, callback func()) {
go func() {
time.Sleep(t)
callback()
}()
}
func SetInterval(t time.Duration, callback func() bool) {
go func() {
for {
time.Sleep(t)
if !callback() {
break
}
}
}()
}
func Nanosecond() int64 {
return time.Now().UnixNano()
}
func Microsecond() int64 {
return time.Now().UnixNano() / 1e3
}
func Millisecond() int64 {
return time.Now().UnixNano() / 1e6
}
func Second() int64 {
return time.Now().UnixNano() / 1e9
}
func Date() string {
return time.Now().Format("2006-01-02")
}
func Datetime() string {
return time.Now().Format("2006-01-02 15:04:05")
}
func StrToTime(format string, timestr string) (int64, error) {
t, err := time.Parse(format, timestr)
if err != nil {
return 0, err
}
return t.Unix(), nil
}
func Format(format string, timestamps ...int64) string | {
timestamp := Second()
if len(timestamps) > 0 {
timestamp = timestamps[0]
}
return time.Unix(timestamp, 0).Format(format)
} |
package dbr
import "bytes"
type Buffer interface {
WriteString(s string) (n int, err error)
String() string
WriteValue(v ...interface{}) (err error)
Value() []interface{}
}
type buffer struct {
bytes.Buffer
v []interface{}
}
func (b *buffer) WriteValue(v ...interface{}) error {
b.v = append(b.v, v...)
return nil
}
func (b *buffer) Value() []interface{} {
return b.v
}
func NewBuffer() Buffer | {
return &buffer{}
} |
package system
import (
"context"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/formatter"
"github.com/spf13/cobra"
)
type diskUsageOptions struct {
verbose bool
format string
}
func newDiskUsageCommand(dockerCli command.Cli) *cobra.Command {
var opts diskUsageOptions
cmd := &cobra.Command{
Use: "df [OPTIONS]",
Short: "Show docker disk usage",
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runDiskUsage(dockerCli, opts)
},
Annotations: map[string]string{"version": "1.25"},
}
flags := cmd.Flags()
flags.BoolVarP(&opts.verbose, "verbose", "v", false, "Show detailed information on space usage")
flags.StringVar(&opts.format, "format", "", "Pretty-print images using a Go template")
return cmd
}
func runDiskUsage(dockerCli command.Cli, opts diskUsageOptions) error | {
du, err := dockerCli.Client().DiskUsage(context.Background())
if err != nil {
return err
}
format := opts.format
if len(format) == 0 {
format = formatter.TableFormatKey
}
var bsz int64
for _, bc := range du.BuildCache {
if !bc.Shared {
bsz += bc.Size
}
}
duCtx := formatter.DiskUsageContext{
Context: formatter.Context{
Output: dockerCli.Out(),
Format: formatter.NewDiskUsageFormat(format, opts.verbose),
},
LayersSize: du.LayersSize,
BuilderSize: bsz,
BuildCache: du.BuildCache,
Images: du.Images,
Containers: du.Containers,
Volumes: du.Volumes,
Verbose: opts.verbose,
}
return duCtx.Write()
} |
package factor
import (
"github.com/jesand/stats"
"github.com/jesand/stats/dist"
"github.com/jesand/stats/variable"
)
type Factor interface {
Adjacent() []variable.RandomVariable
Score() float64
}
func NewDistFactor(vars []variable.RandomVariable, distr dist.Dist) *DistFactor {
return &DistFactor{
Vars: vars,
Dist: distr,
}
}
type DistFactor struct {
Vars []variable.RandomVariable
Dist dist.Dist
}
func (factor DistFactor) Score() float64 {
var (
numVars = factor.Dist.NumVars()
numParams = factor.Dist.NumParams()
)
if len(factor.Vars) != numVars+numParams {
panic(stats.ErrfFactorVarNum(numVars, numParams, len(factor.Vars)))
}
var (
vars = make([]float64, numVars)
params = make([]float64, numParams)
)
for i, rv := range factor.Vars {
if i < len(vars) {
vars[i] = rv.Val()
} else {
params[i-len(vars)] = rv.Val()
}
}
return factor.Dist.Score(vars, params)
}
func NewConstFactor(vars []variable.RandomVariable, value float64) *ConstFactor {
return &ConstFactor{
Vars: vars,
Value: value,
}
}
type ConstFactor struct {
Vars []variable.RandomVariable
Value float64
}
func (factor ConstFactor) Adjacent() []variable.RandomVariable {
return factor.Vars
}
func (factor ConstFactor) Score() float64 {
return factor.Value
}
func (factor DistFactor) Adjacent() []variable.RandomVariable | {
return factor.Vars
} |
package main
import (
"bytes"
"github.com/bitly/go-nsq"
)
type BackendQueue interface {
Put([]byte) error
ReadChan() chan []byte
Close() error
Delete() error
Depth() int64
Empty() error
}
type DummyBackendQueue struct {
readChan chan []byte
}
func NewDummyBackendQueue() BackendQueue {
return &DummyBackendQueue{readChan: make(chan []byte)}
}
func (d *DummyBackendQueue) Put([]byte) error {
return nil
}
func (d *DummyBackendQueue) ReadChan() chan []byte {
return d.readChan
}
func (d *DummyBackendQueue) Delete() error {
return nil
}
func (d *DummyBackendQueue) Depth() int64 {
return int64(0)
}
func (d *DummyBackendQueue) Empty() error {
return nil
}
func WriteMessageToBackend(buf *bytes.Buffer, msg *nsq.Message, bq BackendQueue) error {
buf.Reset()
err := msg.Write(buf)
if err != nil {
return err
}
err = bq.Put(buf.Bytes())
if err != nil {
return err
}
return nil
}
func (d *DummyBackendQueue) Close() error | {
return nil
} |
package context
import (
"github.com/julienschmidt/httprouter"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
"testing"
)
func TestGetterAndSetter(t *testing.T) | {
params := httprouter.Params{{"foo", "bar"}}
ctx := NewContextFromRouterParams(context.Background(), params)
assert.NotNil(t, ctx)
res, err := FetchRouterParamsFromContext(ctx, "foo")
assert.Nil(t, err)
assert.Equal(t, map[string]string{"foo": "bar"}, res)
_, err = FetchRouterParamsFromContext(context.Background(), "foo")
assert.NotNil(t, err)
} |
package utils
import (
"code.google.com/p/goauth2/oauth"
"github.com/google/go-github/github"
"github.com/pinterb/hsc/config"
)
type Utils struct {
client *github.Client
config *config.Config
Users *UserUtils
}
type Response struct {
*github.Response
}
func NewUtils(config *config.Config) *Utils {
client := github.NewClient(nil)
if config != nil {
t := &oauth.Transport{
Token: &oauth.Token{AccessToken: config.Token},
}
client = github.NewClient(t.Client())
}
u := &Utils{config: config, client: client}
u.Users = &UserUtils{Utils: u}
return u
}
func NewResponse(r *github.Response) *Response | {
resp := &Response{Response: r}
return resp
} |
package action
import (
"io/ioutil"
"net/http"
"strings"
"fmt"
)
type Http struct {
config *ActionConfig
}
func (h *Http) Run() (*Result, error) {
url := h.config.Params.GetString("url")
if url == "" {
return nil, fmt.Errorf("url parameter required")
}
method := h.config.Params.GetString("method")
if method == "" {
method = "GET"
} else {
method = strings.ToUpper(method)
}
client := &http.Client{}
h.config.Log.Debugf("%s %s", method, url)
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
result, err := h.genResult(resp)
if err != nil {
return nil, err
}
return result, nil
}
func NewHttp(config *ActionConfig) *Http {
return &Http{
config: config,
}
}
func (h *Http) genResult(resp *http.Response) (*Result, error) | {
data := make(map[string]interface{})
data["status-code"] = resp.StatusCode
data["headers"] = resp.Header
h.config.Log.Infof("%s %s -> %d", resp.Request.Method, resp.Request.URL.String(), resp.StatusCode)
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
data["raw-body"] = bodyBytes
data["body"] = string(bodyBytes)
return &Result{
Data: data,
}, nil
} |
package eventlistener
import (
"testing"
"github.com/docker/docker/api/types"
"golang.org/x/net/context"
"fmt"
"time"
"github.com/docker/docker/api/types/events"
)
func TestEventListener(t *testing.T) {
const labelToMonitor = "tugbot-test"
tsk := make(chan string, 10)
Register(dockerClientMock{}, labelToMonitor, tsk)
select {
case res := <-tsk:
fmt.Println("we recieved the die container id via the tasks chan: ", res)
case <-time.After(time.Second * 5):
t.Error("we did not recieved the die container id on the tasks chan after 5 sec!")
}
}
type dockerClientMock struct {}
func (d dockerClientMock) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) {
eventsChan := make(chan events.Message, 10)
errChan := make(chan error, 10)
event := events.Message{ Type: "container", Action: "die", }
eventsChan <- event
return eventsChan, errChan
}
func (d dockerClientMock) RegistryLogin(ctx context.Context, auth types.AuthConfig) (types.AuthResponse, error) {
panic("This function not suppose to be called")
}
func (d dockerClientMock) DiskUsage(ctx context.Context) (types.DiskUsage, error) {
panic("This function not suppose to be called")
}
func (d dockerClientMock) Ping(ctx context.Context) (bool, error) {
panic("This function not suppose to be called")
}
func (d dockerClientMock) Info(ctx context.Context) (types.Info, error) | {
panic("This function not suppose to be called")
} |
package command
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"google.golang.org/grpc"
"github.com/itslab-kyushu/simple-kvs/kvs"
"github.com/itslab-kyushu/sss/cfg"
"github.com/urfave/cli"
)
type getOpt struct {
Config *cfg.Config
Name string
OutputFile string
Log io.Writer
}
func CmdGet(c *cli.Context) (err error) {
if c.NArg() != 1 {
return cli.ShowSubcommandHelp(c)
}
conf, err := cfg.ReadConfig(c.String("config"))
if err != nil {
return
}
output := c.String("output")
if output == "" {
output = c.Args().First()
}
var log io.Writer
if c.GlobalBool("quiet") {
log = ioutil.Discard
} else {
log = os.Stderr
}
return cmdGet(&getOpt{
Config: conf,
Name: c.Args().First(),
OutputFile: output,
Log: log,
})
}
func cmdGet(opt *getOpt) (err error) | {
if opt.Config.NServers() == 0 {
return fmt.Errorf("No server information is given.")
}
fmt.Fprintln(opt.Log, "Downloading a file")
server := opt.Config.Servers[0]
conn, err := grpc.Dial(
fmt.Sprintf("%s:%d", server.Address, server.Port),
grpc.WithInsecure(),
grpc.WithCompressor(grpc.NewGZIPCompressor()),
grpc.WithDecompressor(grpc.NewGZIPDecompressor()),
)
if err != nil {
return
}
defer conn.Close()
client := kvs.NewKvsClient(conn)
value, err := client.Get(context.Background(), &kvs.Key{
Name: opt.Name,
})
if err != nil {
return
}
return ioutil.WriteFile(opt.OutputFile, value.Value, 0644)
} |
package douban
import (
"encoding/json"
"time"
"github.com/q191201771/chef_go/http"
)
type Book struct {
pubdate time.Time
Authors []string `json:"author"`
Title string `json:"title"`
PubDate string `json:"pubdate"`
ISBN10 string `json:"isbn10"`
Summary string `json:"summary"`
}
type Resp struct {
Count int `json:"count"`
Start int `json:"start"`
Total int `json:"total"`
Books []Book `json:"books"`
}
const PATH = "https://api.douban.com/v2/book/search"
func Fetch(bookname string) Book | {
var resp Resp
queries := map[string]string{
"q": bookname,
}
res, _, _ := http.Get(PATH, queries, nil, nil)
err := json.Unmarshal([]byte(res), &resp)
if err != nil {
panic(err)
}
return resp.Books[0]
} |
package match
import (
"reflect"
"testing"
)
func Match(t *testing.T, value interface{}) *Matcher {
return &Matcher{
t: t,
value: value,
}
}
func IsNil(t *testing.T, value interface{}) *Matcher {
return Match(t, value).IsNil()
}
func IsNotNil(t *testing.T, value interface{}) *Matcher {
return Match(t, value).IsNotNil()
}
func Equals(t *testing.T, value, other interface{}) *Matcher {
return Match(t, value).Equals(other)
}
func NotEquals(t *testing.T, value, other interface{}) *Matcher {
return Match(t, value).NotEquals(other)
}
func LessThan(t *testing.T, value, other interface{}) *Matcher {
return Match(t, value).LessThan(other)
}
func GreaterThan(t *testing.T, value, other interface{}) *Matcher {
return Match(t, value).GreaterThan(other)
}
func Contains(t *testing.T, value, other interface{}) *Matcher {
return Match(t, value).Contains(other)
}
func KindOf(t *testing.T, value interface{}, kind reflect.Kind) *Matcher {
return Match(t, value).KindOf(kind)
}
func Matches(t *testing.T, value interface{}, pattern string) *Matcher | {
return Match(t, value).Matches(pattern)
} |
package example
import (
"net/http"
"gopkg.in/gin-gonic/gin.v1"
)
func GinEngine() *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/", ginHelloHandler)
return r
}
func ginHelloHandler(c *gin.Context) | {
c.String(http.StatusOK, "Hello World")
} |
package string
import (
dss "github.com/emirpasic/gods/stacks/arraystack"
)
func Reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func ReverseNest1(s string) string {
r := []rune(s)
switchHeadTail(r)
return string(r)
}
func switchHeadTail(r []rune) {
if len(r) <= 1 {
return
}
bottom, top := 0, len(r)-1
r[bottom], r[top] = r[top], r[bottom]
switchHeadTail(r[bottom+1 : top])
}
func ReverseInStack(s string) string {
r := []rune(s)
stack := dss.New()
for i := 0; i < len(r); i++ {
stack.Push(r[i])
}
rs := make([]rune, len(r))
for i := 0; i < len(r); i++ {
v, _ := stack.Pop()
if v != nil {
rs[i] = v.(rune)
}
}
return string(rs)
}
func ReverseNest(s string) string | {
r := []rune(s)
if len(r) == 1 || len(r) == 0 {
return s
}
sub := ReverseNest(string(r[1:]))
return sub + string(r[0:1])
} |
package tequilapi
import (
"errors"
"fmt"
"net"
"net/http"
"strings"
)
type APIServer interface {
Wait() error
StartServing() error
Stop()
Address() (string, error)
}
type apiServer struct {
errorChannel chan error
handler http.Handler
listenAddress string
listener net.Listener
}
func NewServer(address string, port int, handler http.Handler, corsPolicy CorsPolicy) APIServer {
server := apiServer{
make(chan error, 1),
DisableCaching(ApplyCors(handler, corsPolicy)),
fmt.Sprintf("%s:%d", address, port),
nil}
return &server
}
func (server *apiServer) Stop() {
if server.listener == nil {
return
}
server.listener.Close()
}
func (server *apiServer) Wait() error {
return <-server.errorChannel
}
func (server *apiServer) StartServing() error {
var err error
server.listener, err = net.Listen("tcp", server.listenAddress)
if err != nil {
return err
}
go server.serve(server.handler)
return nil
}
func (server *apiServer) serve(handler http.Handler) {
server.errorChannel <- http.Serve(server.listener, handler)
}
func extractBoundAddress(listener net.Listener) (string, error) {
addr := listener.Addr()
parts := strings.Split(addr.String(), ":")
if len(parts) < 2 {
return "", errors.New("Unable to locate address: " + addr.String())
}
return addr.String(), nil
}
func (server *apiServer) Address() (string, error) | {
if server.listener == nil {
return "", errors.New("not bound")
}
return extractBoundAddress(server.listener)
} |
package tmdb
import (
"fmt"
)
type Changes struct {
Results []struct {
ID int
Adult bool
}
}
var changeOptions = map[string]struct{}{
"page": {},
"start_date": {},
"end_date": {}}
func (tmdb *TMDb) GetChangesMovie(options map[string]string) (*Changes, error) {
var movieChanges Changes
optionsString := getOptionsString(options, changeOptions)
uri := fmt.Sprintf("%s/movie/changes?api_key=%s%s", baseURL, tmdb.apiKey, optionsString)
result, err := getTmdb(uri, &movieChanges)
return result.(*Changes), err
}
func (tmdb *TMDb) GetChangesPerson(options map[string]string) (*Changes, error) {
var personChanges Changes
optionsString := getOptionsString(options, changeOptions)
uri := fmt.Sprintf("%s/person/changes?api_key=%s%s", baseURL, tmdb.apiKey, optionsString)
result, err := getTmdb(uri, &personChanges)
return result.(*Changes), err
}
func (tmdb *TMDb) GetChangesTv(options map[string]string) (*Changes, error) | {
var tvChanges Changes
optionsString := getOptionsString(options, changeOptions)
uri := fmt.Sprintf("%s/tv/changes?api_key=%s%s", baseURL, tmdb.apiKey, optionsString)
result, err := getTmdb(uri, &tvChanges)
return result.(*Changes), err
} |
package service
import (
"context"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestService_OnlineList(t *testing.T) {
Convey("online list", t, WithService(func(s *Service) {
data, err := s.OnlineList(context.Background())
So(err, ShouldBeNil)
Printf("%v", data)
}))
}
func TestService_OnlineArchiveCount(t *testing.T) | {
Convey("test online OnlineArchiveCount", t, WithService(func(s *Service) {
res := s.OnlineArchiveCount(context.Background())
So(res, ShouldNotBeNil)
}))
} |
package gc
import "strconv"
func _() {
var x [1]struct{}
_ = x[Pxxx-0]
_ = x[PEXTERN-1]
_ = x[PAUTO-2]
_ = x[PAUTOHEAP-3]
_ = x[PPARAM-4]
_ = x[PPARAMOUT-5]
_ = x[PFUNC-6]
}
const _Class_name = "PxxxPEXTERNPAUTOPAUTOHEAPPPARAMPPARAMOUTPFUNC"
var _Class_index = [...]uint8{0, 4, 11, 16, 25, 31, 40, 45}
func (i Class) String() string | {
if i >= Class(len(_Class_index)-1) {
return "Class(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Class_name[_Class_index[i]:_Class_index[i+1]]
} |
package main
type OffState struct {
statusLed Output
}
func NewOffState(statusLed Output) State {
s := OffState{statusLed: statusLed}
return &s
}
func (s *OffState) Event(m StateMachine, pin uint, value uint) {
if pin == GPIO_SWITCH_PIN && value == GPIO_SWITCH_ON {
m.Transit(STATE_WAITING)
}
}
func (s *OffState) Leave(m StateMachine) {}
func (s *OffState) String() string {
return "Off"
}
func (s *OffState) Enter(m StateMachine) | {
s.statusLed.Low()
} |
package cache
import (
"time"
utilcache "k8s.io/apimachinery/pkg/util/cache"
"k8s.io/apimachinery/pkg/util/clock"
)
type simpleCache struct {
cache *utilcache.Expiring
}
func newSimpleCache(clock clock.Clock) cache {
return &simpleCache{cache: utilcache.NewExpiringWithClock(clock)}
}
func (c *simpleCache) set(key string, value *cacheRecord, ttl time.Duration) {
c.cache.Set(key, value, ttl)
}
func (c *simpleCache) remove(key string) {
c.cache.Delete(key)
}
func (c *simpleCache) get(key string) (*cacheRecord, bool) | {
record, ok := c.cache.Get(key)
if !ok {
return nil, false
}
value, ok := record.(*cacheRecord)
return value, ok
} |
package protocol
import "sync"
var msgPool = sync.Pool{
New: func() interface{} {
header := Header([12]byte{})
header[0] = magicNumber
return &Message{
Header: &header,
}
},
}
func FreeMsg(msg *Message) {
if msg != nil {
msg.Reset()
msgPool.Put(msg)
}
}
var poolUint32Data = sync.Pool{
New: func() interface{} {
data := make([]byte, 4)
return &data
},
}
func GetPooledMsg() *Message | {
return msgPool.Get().(*Message)
} |
package main_test
import (
"testing"
"github.com/boltdb/bolt"
. "github.com/boltdb/bolt/cmd/bolt"
)
func TestBucketsDBNotFound(t *testing.T) {
SetTestMode(true)
output := run("buckets", "no/such/db")
equals(t, "stat no/such/db: no such file or directory", output)
}
func TestBuckets(t *testing.T) | {
SetTestMode(true)
open(func(db *bolt.DB, path string) {
db.Update(func(tx *bolt.Tx) error {
tx.CreateBucket([]byte("woojits"))
tx.CreateBucket([]byte("widgets"))
tx.CreateBucket([]byte("whatchits"))
return nil
})
db.Close()
output := run("buckets", path)
equals(t, "whatchits\nwidgets\nwoojits", output)
})
} |
package model
import (
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils"
"errors"
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter"
"strings"
)
type PrePaidServerSchedulerHints struct {
Group *string `json:"group,omitempty"`
Tenancy *PrePaidServerSchedulerHintsTenancy `json:"tenancy,omitempty"`
DedicatedHostId *string `json:"dedicated_host_id,omitempty"`
}
func (o PrePaidServerSchedulerHints) String() string {
data, err := utils.Marshal(o)
if err != nil {
return "PrePaidServerSchedulerHints struct{}"
}
return strings.Join([]string{"PrePaidServerSchedulerHints", string(data)}, " ")
}
type PrePaidServerSchedulerHintsTenancy struct {
value string
}
type PrePaidServerSchedulerHintsTenancyEnum struct {
SHARED PrePaidServerSchedulerHintsTenancy
DEDICATED PrePaidServerSchedulerHintsTenancy
}
func (c PrePaidServerSchedulerHintsTenancy) MarshalJSON() ([]byte, error) {
return utils.Marshal(c.value)
}
func (c *PrePaidServerSchedulerHintsTenancy) UnmarshalJSON(b []byte) error {
myConverter := converter.StringConverterFactory("string")
if myConverter != nil {
val, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), "\""))
if err == nil {
c.value = val.(string)
return nil
}
return err
} else {
return errors.New("convert enum data to string error")
}
}
func GetPrePaidServerSchedulerHintsTenancyEnum() PrePaidServerSchedulerHintsTenancyEnum | {
return PrePaidServerSchedulerHintsTenancyEnum{
SHARED: PrePaidServerSchedulerHintsTenancy{
value: "shared",
},
DEDICATED: PrePaidServerSchedulerHintsTenancy{
value: "dedicated",
},
}
} |
package proxy
import (
"store"
"utils"
)
const (
EFFICIENT_POOL_KEY = "EfficientPoolKey"
)
var (
efficientPool = InitEfficientPool()
)
type EfficientPool struct {
BasePool
Storage store.SetStringStorer
}
func InitEfficientPool() *EfficientPool {
return &EfficientPool{BasePool: *InitBasePool(), Storage: store.RedisSet{}}
}
func (pool *EfficientPool) Remove(proxy string) {
pool.Storage.Remove(EFFICIENT_POOL_KEY, proxy)
}
func Rand() (ok bool, proxy string) {
return efficientPool.Storage.Rand(EFFICIENT_POOL_KEY)
}
func Feedback(proxy string, ok bool, time int) {
stablePool.Add(proxy, utils.EscapeToTime(ok, time))
if !ok {
efficientPool.Remove(proxy)
}
}
func (pool *EfficientPool) Add(proxy string) | {
pool.Storage.Add(EFFICIENT_POOL_KEY, proxy)
} |
package models
import "encoding/binary"
type Page struct {
Prev bool
PrevVal int
Next bool
NextVal int
NextURL string
pages int
Pages []string
Total int
Count int
Skip int
}
func itob(v int) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(v))
return b
}
func SearchPagination(count int, page int, perPage int) Page | {
var pg Page
var total int
if count%perPage != 0 {
total = count/perPage + 1
} else {
total = count / perPage
}
if total < page {
page = total
}
if page == 1 {
pg.Prev = false
pg.Next = true
}
if page != 1 {
pg.Prev = true
}
if total > page {
pg.Next = true
}
if total == page {
pg.Next = false
}
var pgs = make([]string, total)
skip := perPage * (page - 1)
pg.Total = total
pg.Skip = skip
pg.Count = count
pg.NextVal = page + 1
pg.PrevVal = page - 1
pg.Pages = pgs
return pg
} |
package go_koans
func isPrimeNumber(possiblePrime int) bool {
for underPrime := 2; underPrime < possiblePrime; underPrime++ {
if possiblePrime%underPrime == 0 {
return false
}
}
return true
}
func aboutConcurrency() {
ch := make(chan int)
assert(__delete_me__)
assert(<-ch == 2)
assert(<-ch == 3)
assert(<-ch == 5)
assert(<-ch == 7)
assert(<-ch == 11)
}
func findPrimeNumbers(channel chan int) | {
for i := 2; ; i++ {
assert(i < 100)
}
} |
package v1beta1
import (
"context"
"github.com/google/knative-gcp/pkg/apis/duck"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"knative.dev/pkg/apis"
)
func (t *Topic) Validate(ctx context.Context) *apis.FieldError {
err := t.Spec.Validate(ctx).ViaField("spec")
if apis.IsInUpdate(ctx) {
original := apis.GetBaseline(ctx).(*Topic)
err = err.Also(t.CheckImmutableFields(ctx, original))
}
return err
}
func (current *Topic) CheckImmutableFields(ctx context.Context, original *Topic) *apis.FieldError {
if original == nil {
return nil
}
var errs *apis.FieldError
if diff := cmp.Diff(original.Spec, current.Spec,
cmpopts.IgnoreFields(TopicSpec{})); diff != "" {
errs = errs.Also(&apis.FieldError{
Message: "Immutable fields changed (-old +new)",
Paths: []string{"spec"},
Details: diff,
})
}
errs = duck.CheckImmutableAutoscalingClassAnnotations(¤t.ObjectMeta, &original.ObjectMeta, errs)
return duck.CheckImmutableClusterNameAnnotation(¤t.ObjectMeta, &original.ObjectMeta, errs)
}
func (ts *TopicSpec) Validate(ctx context.Context) *apis.FieldError | {
var errs *apis.FieldError
if ts.Topic == "" {
errs = errs.Also(
apis.ErrMissingField("topic"),
)
}
switch ts.PropagationPolicy {
case TopicPolicyCreateDelete, TopicPolicyCreateNoDelete, TopicPolicyNoCreateNoDelete:
default:
errs = errs.Also(
apis.ErrInvalidValue(ts.PropagationPolicy, "propagationPolicy"),
)
}
return errs
} |
package manual
import (
"os/exec"
)
type sshOption []string
var allocateTTY sshOption = []string{"-t"}
var commonSSHOptions = []string{"-o", "StrictHostKeyChecking no"}
func sshCommand(host string, command string, options ...sshOption) *exec.Cmd | {
args := append([]string{}, commonSSHOptions...)
for _, option := range options {
args = append(args, option...)
}
args = append(args, host, "--", command)
return exec.Command("ssh", args...)
} |
package oci
import (
"encoding/json"
"fmt"
"github.com/phoenix-io/phoenix-mon/plugins"
ps "github.com/shirou/gopsutil/process"
"io/ioutil"
)
type OCI struct {
process []plugin.Process
count int
}
type PState struct {
ID string `json:"id"`
Pid int `json:"init_process_pid"`
}
func init() {
plugin.Register("oci", &plugin.RegisteredPlugin{New: NewPlugin})
}
func (p *OCI) GetProcessList() ([]plugin.Process, error) {
var state PState
containers, _ := ioutil.ReadDir("/run/oci/")
for _, c := range containers {
data, err := ioutil.ReadFile("/run/oci/" + c.Name() + "/state.json")
if err != nil {
return p.process, fmt.Errorf("Error in reading file")
}
json.Unmarshal(data, &state)
name := fmt.Sprintf("%s %d",state.ID,p.count)
p.count++
p.process = append(p.process, plugin.Process{Pid: state.Pid, Name: name})
}
return p.process, nil
}
func (p *OCI) GetProcessStat(process plugin.Process) (plugin.Process, error) {
res, err := ps.NewProcess(int32(process.Pid))
if err != nil {
fmt.Println("Unable to Create Process Object")
}
memInfo, err := res.MemoryInfo()
if err != nil {
return process, fmt.Errorf("geting ppid error %v", err)
}
process.Memory = memInfo.RSS
return process, nil
}
func NewPlugin(pluginName string) (plugin.Plugin, error) | {
return &OCI{}, nil
} |
package sparta
import (
"context"
"github.com/aws/aws-lambda-go/lambdacontext"
)
func cloudWatchLogsProcessor(ctx context.Context,
props map[string]interface{}) error {
lambdaCtx, _ := lambdacontext.FromContext(ctx)
Logger().Info().
Str("RequestID", lambdaCtx.AwsRequestID).
Msg("CloudWatch log event")
Logger().Info().Msg("CloudWatch Log event received")
return nil
}
func ExampleCloudWatchLogsPermission() | {
var lambdaFunctions []*LambdaAWSInfo
cloudWatchLogsLambda, _ := NewAWSLambda(LambdaName(cloudWatchLogsProcessor),
cloudWatchLogsProcessor,
IAMRoleDefinition{})
cloudWatchLogsPermission := CloudWatchLogsPermission{}
cloudWatchLogsPermission.Filters = make(map[string]CloudWatchLogsSubscriptionFilter, 1)
cloudWatchLogsPermission.Filters["MyFilter"] = CloudWatchLogsSubscriptionFilter{
LogGroupName: "/aws/lambda/*",
}
cloudWatchLogsLambda.Permissions = append(cloudWatchLogsLambda.Permissions, cloudWatchLogsPermission)
lambdaFunctions = append(lambdaFunctions, cloudWatchLogsLambda)
mainErr := Main("CloudWatchLogs", "Registers for CloudWatch Logs", lambdaFunctions, nil, nil)
if mainErr != nil {
panic("Failed to invoke sparta.Main: %s" + mainErr.Error())
}
} |
package fake
import (
rest "k8s.io/client-go/rest"
testing "k8s.io/client-go/testing"
v1alpha1 "k8s.io/kops/pkg/client/clientset_generated/clientset/typed/kops/v1alpha1"
)
type FakeKopsV1alpha1 struct {
*testing.Fake
}
func (c *FakeKopsV1alpha1) Clusters(namespace string) v1alpha1.ClusterInterface {
return &FakeClusters{c, namespace}
}
func (c *FakeKopsV1alpha1) InstanceGroups(namespace string) v1alpha1.InstanceGroupInterface {
return &FakeInstanceGroups{c, namespace}
}
func (c *FakeKopsV1alpha1) SSHCredentials(namespace string) v1alpha1.SSHCredentialInterface {
return &FakeSSHCredentials{c, namespace}
}
func (c *FakeKopsV1alpha1) RESTClient() rest.Interface | {
var ret *rest.RESTClient
return ret
} |
package logger
import (
"io"
"log"
"os"
"github.com/influxdata/wlog"
)
func newTelegrafWriter(w io.Writer) io.Writer {
return &telegrafLog{
writer: wlog.NewWriter(w),
}
}
type telegrafLog struct {
writer io.Writer
}
func SetupLogging(debug, quiet bool, logfile string) {
if debug {
wlog.SetLevel(wlog.DEBUG)
}
if quiet {
wlog.SetLevel(wlog.ERROR)
}
var oFile *os.File
if logfile != "" {
if _, err := os.Stat(logfile); os.IsNotExist(err) {
if oFile, err = os.Create(logfile); err != nil {
log.Printf("E! Unable to create %s (%s), using stdout", logfile, err)
oFile = os.Stdout
}
} else {
if oFile, err = os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, os.ModeAppend); err != nil {
log.Printf("E! Unable to append to %s (%s), using stdout", logfile, err)
oFile = os.Stdout
}
}
} else {
oFile = os.Stdout
}
log.SetOutput(newTelegrafWriter(oFile))
}
func (t *telegrafLog) Write(p []byte) (n int, err error) | {
return t.writer.Write(p)
} |
package cpdf
import (
"io/ioutil"
)
type bookmarkable interface {
CombinedBookmarkList() string
LocalPath() string
Dir() string
}
func (c *Cpdf) addBookmarksArgs(job bookmarkable) {
c.addArgs("-add-bookmarks", infoPath(job))
}
func infoPath(job bookmarkable) string {
return job.Dir() + "bookmarks.info"
}
func writeBookmarkInfoFile(job bookmarkable) error | {
return ioutil.WriteFile(infoPath(job), []byte(job.CombinedBookmarkList()), 0644)
} |
package cmd
import (
"github.com/mgoltzsche/ctnr/bundle/builder"
"github.com/mgoltzsche/ctnr/model/oci"
"github.com/mgoltzsche/ctnr/run"
"github.com/spf13/cobra"
)
var (
execCmd = &cobra.Command{
Use: "exec [flags] CONTAINERID COMMAND",
Short: "Executes a process in a container",
Long: `Executes a process in a container.`,
Run: wrapRun(runExec),
}
)
func runExec(cmd *cobra.Command, args []string) (err error) {
if len(args) < 1 {
return usageError("No CONTAINERID argument specified")
}
if len(args) < 2 {
return usageError("No COMMAND argument specified")
}
if err := flagsBundle.SetBundleArgs(args); err != nil {
return err
}
service, err := flagsBundle.Read()
if err != nil {
return
}
spec := builder.NewSpecBuilder()
if err = oci.ToSpecProcess(&service.Process, flagPRootPath, &spec); err != nil {
return
}
manager, err := newContainerManager()
if err != nil {
return
}
container, err := manager.Get(args[0])
if err != nil {
return
}
sp, err := spec.Spec(container.Rootfs())
if err != nil {
return
}
proc, err := container.Exec(sp.Process, run.NewStdContainerIO())
if err != nil {
return
}
defer func() {
if e := proc.Close(); e != nil && err == nil {
err = e
}
}()
return proc.Wait()
}
func init() | {
flagsBundle.InitProcessFlags(execCmd.Flags())
flagsBundle.InitRunFlags(execCmd.Flags())
} |
package esbuilder
import "github.com/serulian/compiler/sourcemap"
type StatementBuilder interface {
WithMapping(mapping sourcemap.SourceMapping) SourceBuilder
mapping() (sourcemap.SourceMapping, bool)
emitSource(sb *sourceBuilder)
}
type statementNode interface {
emit(sb *sourceBuilder)
}
type statementBuilder struct {
statement statementNode
sourceMapping *sourcemap.SourceMapping
}
func (builder statementBuilder) mapping() (sourcemap.SourceMapping, bool) {
if builder.sourceMapping == nil {
return sourcemap.SourceMapping{}, false
}
return *builder.sourceMapping, true
}
func (builder statementBuilder) WithMapping(mapping sourcemap.SourceMapping) SourceBuilder {
builder.sourceMapping = &mapping
return builder
}
func (builder statementBuilder) emitSource(sb *sourceBuilder) | {
builder.statement.emit(sb)
} |
package datastore
import "strconv"
func _() {
var x [1]struct{}
_ = x[PTNull-0]
_ = x[PTInt-1]
_ = x[PTTime-2]
_ = x[PTBool-3]
_ = x[PTBytes-4]
_ = x[PTString-5]
_ = x[PTFloat-6]
_ = x[PTGeoPoint-7]
_ = x[PTKey-8]
_ = x[PTBlobKey-9]
_ = x[PTPropertyMap-10]
_ = x[PTUnknown-11]
}
const _PropertyType_name = "PTNullPTIntPTTimePTBoolPTBytesPTStringPTFloatPTGeoPointPTKeyPTBlobKeyPTPropertyMapPTUnknown"
var _PropertyType_index = [...]uint8{0, 6, 11, 17, 23, 30, 38, 45, 55, 60, 69, 82, 91}
func (i PropertyType) String() string | {
if i >= PropertyType(len(_PropertyType_index)-1) {
return "PropertyType(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _PropertyType_name[_PropertyType_index[i]:_PropertyType_index[i+1]]
} |
package syscall
import "unsafe"
func setTimespec(sec, nsec int64) Timespec {
return Timespec{Sec: sec, Nsec: nsec}
}
func SetKevent(k *Kevent_t, fd, mode, flags int) {
k.Ident = uint64(fd)
k.Filter = int16(mode)
k.Flags = uint16(flags)
}
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)
}
func setTimeval(sec, usec int64) Timeval | {
return Timeval{Sec: sec, Usec: usec}
} |
package gtimer
func (h *priorityQueueHeap) Len() int {
return len(h.array)
}
func (h *priorityQueueHeap) Less(i, j int) bool {
return h.array[i].priority < h.array[j].priority
}
func (h *priorityQueueHeap) Push(x interface{}) {
h.array = append(h.array, x.(priorityQueueItem))
}
func (h *priorityQueueHeap) Pop() interface{} {
length := len(h.array)
if length == 0 {
return nil
}
item := h.array[length-1]
h.array = h.array[0 : length-1]
return item
}
func (h *priorityQueueHeap) Swap(i, j int) | {
if len(h.array) == 0 {
return
}
h.array[i], h.array[j] = h.array[j], h.array[i]
} |
package plan
import (
"github.com/pingcap/tidb/expression"
)
func projectionCanBeEliminated(p *Projection) bool {
child := p.children[0].(PhysicalPlan)
if p.Schema().Len() != child.Schema().Len() {
return false
}
for i, expr := range p.Exprs {
col, ok := expr.(*expression.Column)
if !ok {
return false
}
if col.FromID != child.Schema().Columns[i].FromID || col.Position != child.Schema().Columns[i].Position {
return false
}
}
return true
}
func EliminateProjection(p PhysicalPlan) PhysicalPlan | {
switch plan := p.(type) {
case *Projection:
if !projectionCanBeEliminated(plan) {
break
}
child := plan.children[0].(PhysicalPlan)
child.SetSchema(plan.Schema())
RemovePlan(p)
p = EliminateProjection(child)
}
children := make([]Plan, 0, len(p.Children()))
for _, child := range p.Children() {
children = append(children, EliminateProjection(child.(PhysicalPlan)))
}
p.SetChildren(children...)
return p
} |
package characteristic
import (
"github.com/brutella/hc/model"
)
type HeatingCoolingMode struct {
*ByteCharacteristic
}
func NewHeatingCoolingMode(current model.HeatCoolModeType, charType CharType, permissions []string) *HeatingCoolingMode {
c := HeatingCoolingMode{NewByteCharacteristic(byte(current), permissions)}
c.Type = charType
return &c
}
func NewCurrentHeatingCoolingMode(current model.HeatCoolModeType) *HeatingCoolingMode {
return NewHeatingCoolingMode(current, CharTypeHeatingCoolingModeCurrent, PermsRead())
}
func NewTargetHeatingCoolingMode(current model.HeatCoolModeType) *HeatingCoolingMode {
return NewHeatingCoolingMode(current, CharTypeHeatingCoolingModeTarget, PermsAll())
}
func (c *HeatingCoolingMode) SetHeatingCoolingMode(mode model.HeatCoolModeType) {
c.SetByte(byte(mode))
}
func (c *HeatingCoolingMode) HeatingCoolingMode() model.HeatCoolModeType | {
return model.HeatCoolModeType(c.Byte())
} |
package fake
import (
"encoding/json"
"fmt"
"net/http"
"strings"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
)
type CFAPI struct {
server *ghttp.Server
}
type CFAPIConfig struct {
Routes map[string]Response
}
type Response struct {
Code int
Body interface{}
}
func NewCFAPI() *CFAPI {
server := ghttp.NewServer()
return &CFAPI{
server: server,
}
}
func (a *CFAPI) SetConfiguration(config CFAPIConfig) {
a.server.Reset()
for request, response := range config.Routes {
method, path := parseRequest(request)
responseBytes, err := json.Marshal(response.Body)
Expect(err).NotTo(HaveOccurred())
a.server.RouteToHandler(method, path, ghttp.RespondWith(response.Code, responseBytes))
}
}
func (a *CFAPI) Close() {
a.server.Close()
}
func (a *CFAPI) URL() string {
return a.server.URL()
}
func (a *CFAPI) ReceivedRequests() map[string][]*http.Request {
result := map[string][]*http.Request{}
for _, req := range a.server.ReceivedRequests() {
key := fmt.Sprintf("%s %s", req.Method, req.URL.Path)
result[key] = append(result[key], req)
}
return result
}
func parseRequest(request string) (string, string) | {
fields := strings.Split(request, " ")
Expect(fields).To(HaveLen(2))
return fields[0], fields[1]
} |
package astar
import (
"os"
"image"
)
import _ "image/png"
func openImage(filename string) (image.Image) {
f, err := os.Open(filename)
if err != nil {
return nil
}
defer f.Close()
img, _, _ := image.Decode(f)
return img
}
func GetMapFromImage(filename string) MapData {
img := openImage(filename)
if(img == nil) {
return nil
}
return parseImage(img)
}
func parseImage(img image.Image) MapData | {
max := uint32(65536-1)
bounds := img.Bounds()
map_data := NewMapData(bounds.Max.X, bounds.Max.Y)
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
r, g, b, a := img.At(x, y).RGBA()
if(r == max && g == max && b == max && a == max) {
map_data[x][bounds.Max.Y-1-y] = LAND
} else {
map_data[x][bounds.Max.Y-1-y] = WALL
}
}
}
return map_data
} |
package runconfig
import (
"fmt"
"io"
"io/ioutil"
"strings"
"github.com/hyperhq/hypercli/pkg/broadcaster"
"github.com/hyperhq/hypercli/pkg/ioutils"
)
type StreamConfig struct {
stdout *broadcaster.Unbuffered
stderr *broadcaster.Unbuffered
stdin io.ReadCloser
stdinPipe io.WriteCloser
}
func NewStreamConfig() *StreamConfig {
return &StreamConfig{
stderr: new(broadcaster.Unbuffered),
stdout: new(broadcaster.Unbuffered),
}
}
func (streamConfig *StreamConfig) Stdout() *broadcaster.Unbuffered {
return streamConfig.stdout
}
func (streamConfig *StreamConfig) Stderr() *broadcaster.Unbuffered {
return streamConfig.stderr
}
func (streamConfig *StreamConfig) Stdin() io.ReadCloser {
return streamConfig.stdin
}
func (streamConfig *StreamConfig) StdinPipe() io.WriteCloser {
return streamConfig.stdinPipe
}
func (streamConfig *StreamConfig) StdoutPipe() io.ReadCloser {
bytesPipe := ioutils.NewBytesPipe(nil)
streamConfig.stdout.Add(bytesPipe)
return bytesPipe
}
func (streamConfig *StreamConfig) StderrPipe() io.ReadCloser {
bytesPipe := ioutils.NewBytesPipe(nil)
streamConfig.stderr.Add(bytesPipe)
return bytesPipe
}
func (streamConfig *StreamConfig) NewInputPipes() {
streamConfig.stdin, streamConfig.stdinPipe = io.Pipe()
}
func (streamConfig *StreamConfig) NewNopInputPipe() {
streamConfig.stdinPipe = ioutils.NopWriteCloser(ioutil.Discard)
}
func (streamConfig *StreamConfig) CloseStreams() error | {
var errors []string
if streamConfig.stdin != nil {
if err := streamConfig.stdin.Close(); err != nil {
errors = append(errors, fmt.Sprintf("error close stdin: %s", err))
}
}
if err := streamConfig.stdout.Clean(); err != nil {
errors = append(errors, fmt.Sprintf("error close stdout: %s", err))
}
if err := streamConfig.stderr.Clean(); err != nil {
errors = append(errors, fmt.Sprintf("error close stderr: %s", err))
}
if len(errors) > 0 {
return fmt.Errorf(strings.Join(errors, "\n"))
}
return nil
} |
package swt
import "github.com/timob/javabind"
type EventsTraverseEventInterface interface {
EventsKeyEventInterface
}
type EventsTraverseEvent struct {
EventsKeyEvent
}
func (jbobject *EventsTraverseEvent) ToString() string {
jret, err := jbobject.CallMethod(javabind.GetEnv(), "toString", "java/lang/String")
if err != nil {
panic(err)
}
retconv := javabind.NewJavaToGoString()
dst := new(string)
retconv.Dest(dst)
if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
panic(err)
}
retconv.CleanUp()
return *dst
}
func (jbobject *EventsTraverseEvent) Detail() int {
jret, err := jbobject.GetField(javabind.GetEnv(), "detail", javabind.Int)
if err != nil {
panic(err)
}
return jret.(int)
}
func (jbobject *EventsTraverseEvent) SetFieldDetail(val int) {
err := jbobject.SetField(javabind.GetEnv(), "detail", val)
if err != nil {
panic(err)
}
}
func NewEventsTraverseEvent(a WidgetsEventInterface) (*EventsTraverseEvent) | {
conv_a := javabind.NewGoToJavaCallable()
if err := conv_a.Convert(a); err != nil {
panic(err)
}
obj, err := javabind.GetEnv().NewObject("org/eclipse/swt/events/TraverseEvent", conv_a.Value().Cast("org/eclipse/swt/widgets/Event"))
if err != nil {
panic(err)
}
conv_a.CleanUp()
x := &EventsTraverseEvent{}
x.Callable = &javabind.Callable{obj}
return x
} |
package check
type GoFmt struct {
Dir string
Filenames []string
}
func (g GoFmt) Weight() float64 {
return .35
}
func (g GoFmt) Percentage() (float64, []FileSummary, error) {
return GoTool(g.Dir, g.Filenames, []string{"gofmt", "-s", "-l"})
}
func (g GoFmt) Description() string {
return `Gofmt formats Go programs. We run <code>gofmt -s</code> on your code, where <code>-s</code> is for the <a href="https://golang.org/cmd/gofmt/#hdr-The_simplify_command">"simplify" command</a>`
}
func (g GoFmt) Name() string | {
return "gofmt"
} |
package models
import "fmt"
var RoomPool = make([] *Room, 0)
func AddRoom(r *Room) {
RoomPool = append(RoomPool, r)
}
func FindRoom(d string) (int, *Room) {
for i, v := range RoomPool {
if v.Name == d {
return i, v
}
}
return -1, &Room{}
}
func RemoveRoom(r *Room) {
index, _ := FindRoom(r.Name)
if index != -1 {
RoomPool = append(RoomPool[:index], RoomPool[index + 1:]...)
}
}
func RemoveClient(c *Client) {
for _, room := range RoomPool{
if room.Name == c.Room {
if room.HasClient(c) {
room.DeleteClient(c)
if room.ClientCount() == 0 {
RemoveRoom(room)
PoolBroadcast(NewMessage(map[string]string{
"connectedClients": fmt.Sprintf("%v", GetAllClients()),
"numberOfRooms": fmt.Sprintf("%v", GetNumberOfRooms()),
}))
}
}
}
}
}
func PoolBroadcast(m Message) {
for _, room := range RoomPool {
room.RoomBroadcast(m)
}
}
func GetAllClients() int {
clientSum := 0
for _, room := range RoomPool {
clientSum += len(room.ClientPool)
}
return clientSum
}
func GetNumberOfRooms() int{
return len(RoomPool)
}
func ListRooms() (int, []string) | {
pool := make([]string, 0)
for _, obj := range RoomPool {
pool = append(pool, obj.Name)
}
return len(RoomPool), pool
} |
package lwmq
import (
"fmt"
)
type MessageStore interface {
Messages(*Queue) ([]*Message, error)
AddMessage(*Message) error
PopMessages(*Queue) ([]*Message, error)
}
type MemoryMessageStore struct {
messages map[*Queue][]*Message
}
func NewMemoryMessageStore() *MemoryMessageStore {
s := &MemoryMessageStore{
messages: make(map[*Queue][]*Message),
}
return s
}
func (self *MemoryMessageStore) AddMessage(msg *Message) error {
if msg.Queue == nil {
err := fmt.Errorf("Can not store message without a queue")
return err
}
msg.Offline = true
self.messages[msg.Queue] = append(self.messages[msg.Queue], msg)
return nil
}
func (self *MemoryMessageStore) Messages(q *Queue) ([]*Message, error) {
messages, ok := self.messages[q]
if !ok {
return nil, fmt.Errorf("Unknown queue: %s", q.Id)
}
return messages, nil
}
func (self *MemoryMessageStore) PopMessages(q *Queue) ([]*Message, error) | {
messages, err := self.Messages(q)
if err != nil {
return nil, err
}
self.messages[q] = []*Message{}
return messages, nil
} |
package global
import (
"database/sql"
"encoding/json"
"html/template"
"io/ioutil"
"log"
)
var Templates *template.Template
var DB *sql.DB
var Config Configuration
type Configuration struct {
Port string
DbUser string
DbPassword string
DbName string
JWTtokenPassword string
}
func ParseTemplates() {
parsedTemplates, err := template.ParseGlob("templates/*.html")
if err != nil {
log.Fatal(err)
}
tmpl := template.Must(parsedTemplates, err)
Templates = tmpl
}
func ReadConfig() Configuration | {
data, err := ioutil.ReadFile("config.json")
if err != nil {
log.Fatal("Please add config.json file:", err)
}
config := Configuration{}
if err := json.Unmarshal(data, &config); err != nil {
log.Fatal("Please format configuration file correctly:", err)
}
ParseTemplates()
Config = config
return config
} |
package core
import (
"github.com/oracle/oci-go-sdk/common"
)
type UpdatePublicIpDetails struct {
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
DisplayName *string `mandatory:"false" json:"displayName"`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
PrivateIpId *string `mandatory:"false" json:"privateIpId"`
}
func (m UpdatePublicIpDetails) String() string | {
return common.PointerString(m)
} |
package decorators
import (
"fmt"
"os/exec"
"strings"
"github.com/antham/chyle/chyle/convh"
)
type shellConfig map[string]struct {
COMMAND string
ORIGKEY string
DESTKEY string
}
type shell struct {
COMMAND string
ORIGKEY string
DESTKEY string
}
func (s shell) execute(value string) (string, error) {
var result []byte
var err error
command := fmt.Sprintf(`echo "%s"|%s`, strings.Replace(value, `"`, `\"`, -1), s.COMMAND)
if result, err = exec.Command("sh", "-c", command).Output(); err != nil {
return "", fmt.Errorf("%s : command failed", command)
}
return string(result[:len(result)-1]), nil
}
func newShell(configs shellConfig) []Decorater {
results := []Decorater{}
for _, config := range configs {
results = append(results, shell(config))
}
return results
}
func (s shell) Decorate(commitMap *map[string]interface{}) (*map[string]interface{}, error) | {
var tmp interface{}
var value string
var ok bool
var err error
if tmp, ok = (*commitMap)[s.ORIGKEY]; !ok {
return commitMap, nil
}
if value, err = convh.ConvertToString(tmp); err != nil {
return commitMap, nil
}
if (*commitMap)[s.DESTKEY], err = s.execute(value); err != nil {
return commitMap, err
}
return commitMap, nil
} |
package common
import "math/big"
type _N_ [_S_]byte
func BytesTo_N_(b []byte) _N_ {
var h _N_
h.SetBytes(b)
return h
}
func StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }
func BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) }
func HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }
func (h _N_) Bytes() []byte { return h[:] }
func (h _N_) Big() *big.Int { return Bytes2Big(h[:]) }
func (h _N_) Hex() string { return "0x" + Bytes2Hex(h[:]) }
func (h *_N_) SetBytes(b []byte) {
if len(b) > len(h) {
b = b[len(b)-_S_:]
}
for i := len(b) - 1; i >= 0; i-- {
h[_S_-len(b)+i] = b[i]
}
}
func (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) }
func (h *_N_) Set(other _N_) {
for i, v := range other {
h[i] = v
}
}
func (h _N_) Str() string | { return string(h[:]) } |
package permute
import "testing"
func BenchmarkPermGenLex(b *testing.B) {
p := New(20)
for i := 0; i < b.N; i++ {
LexNext(p)
}
}
func BenchmarkPermGenHeap(b *testing.B) {
h := NewHeap(20)
var sw [2]int
for i := 0; i < b.N; i++ {
h.Next(&sw)
}
}
func BenchmarkPermGenEven(b *testing.B) {
h := NewPlainChangeFastGen(20)
var sw [2]int
for i := 0; i < b.N; i++ {
h.Next(&sw)
}
}
func BenchmarkPermGenSJT(b *testing.B) | {
h := NewPlainChangeGen(20)
var sw [2]int
for i := 0; i < b.N; i++ {
h.Next(&sw)
}
} |
package main
import (
"flag"
"github.com/jonasi/baller"
"os"
)
func init() {
methods["boxscore_advanced_v2"] = cmd_boxscore_advanced_v2
}
func cmd_boxscore_advanced_v2(cl *baller.Client) (interface{}, error) | {
var (
fs = flag.NewFlagSet("boxscore_advanced_v2", flag.ExitOnError)
verbose = fs.Bool("verbose", false, "")
options baller.BoxscoreAdvancedV2Options
)
fs.StringVar(&options.GameID, "GameID", "", "")
fs.IntVar(&options.StartPeriod, "StartPeriod", 0, "")
fs.IntVar(&options.EndPeriod, "EndPeriod", 0, "")
fs.IntVar(&options.StartRange, "StartRange", 0, "")
fs.IntVar(&options.EndRange, "EndRange", 0, "")
fs.IntVar(&options.RangeType, "RangeType", 0, "")
fs.Parse(os.Args[2:])
if *verbose {
cl.Logger = os.Stderr
}
return cl.BoxscoreAdvancedV2(&options)
} |
package seqnum
type Value uint32
type Size uint32
func (v Value) LessThan(w Value) bool {
return int32(v-w) < 0
}
func (v Value) LessThanEq(w Value) bool {
if v == w {
return true
}
return v.LessThan(w)
}
func (v Value) InRange(a, b Value) bool {
return v-a < b-a
}
func (v Value) InWindow(first Value, size Size) bool {
return v.InRange(first, first.Add(size))
}
func Overlap(a Value, b Size, x Value, y Size) bool {
return a.LessThan(x.Add(y)) && x.LessThan(a.Add(b))
}
func (v Value) Add(s Size) Value {
return v + Value(s)
}
func (v Value) Size(w Value) Size {
return Size(w - v)
}
func (v *Value) UpdateForward(s Size) | {
*v += Value(s)
} |
package auth
import (
authorizationapi "github.com/projectatomic/atomic-enterprise/pkg/authorization/api"
"github.com/projectatomic/atomic-enterprise/pkg/client"
)
type Review interface {
Users() []string
Groups() []string
}
type review struct {
response *authorizationapi.ResourceAccessReviewResponse
}
func (r *review) Users() []string {
return r.response.Users.List()
}
func (r *review) Groups() []string {
return r.response.Groups.List()
}
type Reviewer interface {
Review(name string) (Review, error)
}
type reviewer struct {
resourceAccessReviewsNamespacer client.ResourceAccessReviewsNamespacer
}
func (r *reviewer) Review(name string) (Review, error) {
resourceAccessReview := &authorizationapi.ResourceAccessReview{
Verb: "get",
Resource: "namespaces",
ResourceName: name,
}
response, err := r.resourceAccessReviewsNamespacer.ResourceAccessReviews(name).Create(resourceAccessReview)
if err != nil {
return nil, err
}
review := &review{
response: response,
}
return review, nil
}
func NewReviewer(resourceAccessReviewsNamespacer client.ResourceAccessReviewsNamespacer) Reviewer | {
return &reviewer{
resourceAccessReviewsNamespacer: resourceAccessReviewsNamespacer,
}
} |
package httpmux
import "net/http"
type ConfigOption interface {
Set(c *Config)
}
type ConfigOptionFunc func(c *Config)
func (f ConfigOptionFunc) Set(c *Config) { f(c) }
func WithPrefix(prefix string) ConfigOption {
return ConfigOptionFunc(func(c *Config) { c.Prefix = prefix })
}
func WithMiddleware(mw ...Middleware) ConfigOption {
return ConfigOptionFunc(func(c *Config) { c.Middleware = mw })
}
func WithMiddlewareFunc(mw ...MiddlewareFunc) ConfigOption {
return ConfigOptionFunc(func(c *Config) { c.UseFunc(mw...) })
}
func WithRedirectFixedPath(v bool) ConfigOption {
return ConfigOptionFunc(func(c *Config) { c.RedirectFixedPath = v })
}
func WithHandleMethodNotAllowed(v bool) ConfigOption {
return ConfigOptionFunc(func(c *Config) { c.HandleMethodNotAllowed = v })
}
func WithNotFound(f http.Handler) ConfigOption {
return ConfigOptionFunc(func(c *Config) { c.NotFound = f })
}
func WithMethodNotAllowed(f http.Handler) ConfigOption {
return ConfigOptionFunc(func(c *Config) { c.MethodNotAllowed = f })
}
func WithPanicHandler(f func(http.ResponseWriter, *http.Request, interface{})) ConfigOption {
return ConfigOptionFunc(func(c *Config) { c.PanicHandler = f })
}
func WithRedirectTrailingSlash(v bool) ConfigOption | {
return ConfigOptionFunc(func(c *Config) { c.RedirectTrailingSlash = v })
} |
package shutdown
import (
"log"
"os/exec"
"strconv"
)
func abort() {
run("/a")
}
func run(args ...string) {
cmd := exec.Command("shutdown", args...)
err := cmd.Run()
if err != nil {
log.Println("error: " + err.Error())
}
}
func start(sec int) | {
run("/s", "/t", strconv.Itoa(sec))
} |
package refmt
import (
"github.com/polydawn/refmt/obj"
"github.com/polydawn/refmt/obj/atlas"
"github.com/polydawn/refmt/shared"
)
func Clone(src, dst interface{}) error {
return CloneAtlased(src, dst, atlas.MustBuild())
}
func MustClone(src, dst interface{}) {
if err := Clone(src, dst); err != nil {
panic(err)
}
}
func CloneAtlased(src, dst interface{}, atl atlas.Atlas) error {
return NewCloner(atl).Clone(src, dst)
}
func MustCloneAtlased(src, dst interface{}, atl atlas.Atlas) {
if err := CloneAtlased(src, dst, atl); err != nil {
panic(err)
}
}
type Cloner interface {
Clone(src, dst interface{}) error
}
type cloner struct {
marshaller *obj.Marshaller
unmarshaller *obj.Unmarshaller
pump shared.TokenPump
}
func (c cloner) Clone(src, dst interface{}) error {
c.marshaller.Bind(src)
c.unmarshaller.Bind(dst)
return c.pump.Run()
}
func NewCloner(atl atlas.Atlas) Cloner | {
x := &cloner{
marshaller: obj.NewMarshaller(atl),
unmarshaller: obj.NewUnmarshaller(atl),
}
x.pump = shared.TokenPump{x.marshaller, x.unmarshaller}
return x
} |
package eventstreamapi
import (
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
)
type Marshaler interface {
MarshalEvent(protocol.PayloadMarshaler) (eventstream.Message, error)
}
type Encoder interface {
Encode(eventstream.Message) error
}
type EventWriter struct {
encoder Encoder
payloadMarshaler protocol.PayloadMarshaler
eventTypeFor func(Marshaler) (string, error)
}
func NewEventWriter(encoder Encoder, pm protocol.PayloadMarshaler, eventTypeFor func(Marshaler) (string, error),
) *EventWriter {
return &EventWriter{
encoder: encoder,
payloadMarshaler: pm,
eventTypeFor: eventTypeFor,
}
}
func (w *EventWriter) marshal(event Marshaler) (eventstream.Message, error) {
eventType, err := w.eventTypeFor(event)
if err != nil {
return eventstream.Message{}, err
}
msg, err := event.MarshalEvent(w.payloadMarshaler)
if err != nil {
return eventstream.Message{}, err
}
msg.Headers.Set(EventTypeHeader, eventstream.StringValue(eventType))
return msg, nil
}
func (w *EventWriter) WriteEvent(event Marshaler) error | {
msg, err := w.marshal(event)
if err != nil {
return err
}
return w.encoder.Encode(msg)
} |
package spotify
import (
"os"
"testing"
"github.com/laicosly/goth"
"github.com/stretchr/testify/assert"
)
func provider() *Provider {
return New(os.Getenv("SPOTIFY_KEY"), os.Getenv("SPOTIFY_SECRET"), "/foo", "user")
}
func Test_New(t *testing.T) {
t.Parallel()
a := assert.New(t)
p := provider()
a.Equal(p.ClientKey, os.Getenv("SPOTIFY_KEY"))
a.Equal(p.Secret, os.Getenv("SPOTIFY_SECRET"))
a.Equal(p.CallbackURL, "/foo")
}
func Test_ImplementsProvider(t *testing.T) {
t.Parallel()
a := assert.New(t)
a.Implements((*goth.Provider)(nil), provider())
}
func Test_SessionFromJSON(t *testing.T) {
t.Parallel()
a := assert.New(t)
p := provider()
session, err := p.UnmarshalSession(`{"AuthURL":"http://accounts.spotify.com/authorize","AccessToken":"1234567890"}`)
a.NoError(err)
s := session.(*Session)
a.Equal(s.AuthURL, "http://accounts.spotify.com/authorize")
a.Equal(s.AccessToken, "1234567890")
}
func Test_BeginAuth(t *testing.T) | {
t.Parallel()
a := assert.New(t)
p := provider()
session, err := p.BeginAuth("test_state")
s := session.(*Session)
a.NoError(err)
a.Contains(s.AuthURL, "accounts.spotify.com/authorize")
} |
package gapbuf
import "github.com/millere/jk/line"
type GapBuf struct {
buffer []*line.Line
gapStart int
gapEnd int
readPoint int
}
func New(size int) *GapBuf {
a := GapBuf{
buffer: make([]*line.Line, size),
gapStart: 0,
gapEnd: size,
}
return &a
}
func (a *GapBuf) Len() int {
return len(a.buffer) + a.gapStart - a.gapEnd
}
func (a *GapBuf) Insert(r rune, i int) {
}
func (a *GapBuf) moveGap(to int) {
}
func (a *GapBuf) At(i int) *line.Line | {
if i >= a.gapStart {
return a.buffer[i+a.gapEnd-a.gapStart]
} else {
return a.buffer[i]
}
} |
package stdlib
import (
"container/heap"
"reflect"
)
func init() {
Symbols["container/heap"] = map[string]reflect.Value{
"Fix": reflect.ValueOf(heap.Fix),
"Init": reflect.ValueOf(heap.Init),
"Pop": reflect.ValueOf(heap.Pop),
"Push": reflect.ValueOf(heap.Push),
"Remove": reflect.ValueOf(heap.Remove),
"Interface": reflect.ValueOf((*heap.Interface)(nil)),
"_Interface": reflect.ValueOf((*_container_heap_Interface)(nil)),
}
}
type _container_heap_Interface struct {
WLen func() int
WLess func(i int, j int) bool
WPop func() interface{}
WPush func(x interface{})
WSwap func(i int, j int)
}
func (W _container_heap_Interface) Len() int { return W.WLen() }
func (W _container_heap_Interface) Less(i int, j int) bool { return W.WLess(i, j) }
func (W _container_heap_Interface) Pop() interface{} { return W.WPop() }
func (W _container_heap_Interface) Push(x interface{}) { W.WPush(x) }
func (W _container_heap_Interface) Swap(i int, j int) | { W.WSwap(i, j) } |
package packages
import (
"fmt"
"github.com/alexandrecarlton/gogurt"
)
type PkgConfig struct{}
func (pkgconfig PkgConfig) URL(version string) string {
return fmt.Sprintf("https://pkgconfig.freedesktop.org/releases/pkg-config-%s.tar.gz", version)
}
func (pkgconfig PkgConfig) Build(config gogurt.Config) error {
configure := gogurt.ConfigureCmd{
Prefix: config.InstallDir(pkgconfig),
Args: []string{
"--disable-shared",
"--enable-static",
"--with-internal-glib",
},
}.Cmd()
if err := configure.Run(); err != nil {
return err
}
make := gogurt.MakeCmd{
Jobs: config.NumCores,
}.Cmd()
return make.Run()
}
func (pkgconfig PkgConfig) Install(config gogurt.Config) error {
makeInstall := gogurt.MakeCmd{
Args: []string{
"install",
},
}.Cmd()
return makeInstall.Run()
}
func (pkgconfig PkgConfig) Dependencies() []gogurt.Package {
return []gogurt.Package{}
}
func (pkgconfig PkgConfig) Name() string | {
return "pkg-config"
} |
package blanket_emulator
import (
"testing"
"github.com/ranmrdrakono/indika/loader/elf"
)
func TestRun(t *testing.T) | {
elf.Run("../samples/binutils/bin_O1/gdb")
} |
package main
import (
"io"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
type Client struct {
hub *Hub
ws *websocket.Conn
otherSide *Client
channelID uuid.UUID
remoteType string
params map[string][]string
wmu sync.Mutex
rmu sync.Mutex
}
func (c *Client) WriteMessage(msgType int, message []byte) (err error) {
c.wmu.Lock()
err = c.ws.WriteMessage(msgType, message)
c.wmu.Unlock()
return
}
func (c *Client) NextWriter(msgType int) (w io.WriteCloser, err error) {
c.wmu.Lock()
w, err = c.ws.NextWriter(msgType)
c.wmu.Unlock()
return
}
func (c *Client) ReadMessage() (msgType int, message []byte, err error) {
c.rmu.Lock()
msgType, message, err = c.ws.ReadMessage()
c.rmu.Unlock()
return
}
func (c *Client) NextReader() (msgType int, r io.Reader, err error) {
c.rmu.Lock()
msgType, r, err = c.ws.NextReader()
c.rmu.Unlock()
return
}
func (c *Client) SetWriteDeadline(t time.Time) (err error) {
c.wmu.Lock()
err = c.ws.SetWriteDeadline(t)
c.wmu.Unlock()
return
}
func (c *Client) SetReadDeadline(t time.Time) (err error) | {
c.rmu.Lock()
err = c.ws.SetReadDeadline(t)
c.rmu.Unlock()
return
} |
package main
import (
"log"
"time"
)
var ACTION_POTENTIAL_THRESHOLD int = 30
var DELAY_BETWEEN_FIRINGS time.Duration = 10
var SIGNAL_BUFFER_SIZE = 2048
type Neuron struct {
tag string
dendrite chan int
synapses []Synapse
potential int
}
func (n *Neuron) Fire() {
log.Println(n.tag, "Fired")
n.potential = 0
for _, synapse := range n.synapses {
select {
case synapse.channel <- synapse.weight:
default:
log.Println("Signal from", n.tag, "dropped")
}
time.Sleep(DELAY_BETWEEN_FIRINGS * time.Millisecond)
}
}
func (n *Neuron) HasReachedThreshold() bool {
return n.potential > ACTION_POTENTIAL_THRESHOLD
}
func (n *Neuron) Listen() {
for actionPotential := range n.dendrite {
n.potential += actionPotential
if n.HasReachedThreshold() {
n.Fire()
}
}
}
func (n *Neuron) AddSynapse(destination *Neuron, weight int) {
n.synapses = append(n.synapses, Synapse{destination.dendrite, weight})
}
func NewNeuron(tag string) Neuron | {
return Neuron{tag, make(chan int, SIGNAL_BUFFER_SIZE), []Synapse{}, 0}
} |
package graph
import (
"fmt"
"github.com/gonum/graph"
kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
)
var (
UnknownNodeKind = "UnknownNode"
)
var (
UnknownEdgeKind = "UnknownEdge"
ReferencedByEdgeKind = "ReferencedBy"
ContainsEdgeKind = "Contains"
)
func GetUniqueRuntimeObjectNodeName(nodeKind string, obj runtime.Object) UniqueName {
meta, err := kapi.ObjectMetaFor(obj)
if err != nil {
panic(err)
}
return UniqueName(fmt.Sprintf("%s|%s/%s", nodeKind, meta.Namespace, meta.Name))
}
func GetContainingNode(g Graph, containedNode graph.Node) graph.Node {
for _, node := range g.To(containedNode) {
edge := g.Edge(node, containedNode)
if g.EdgeKinds(edge).Has(ContainsEdgeKind) {
return node
}
}
return nil
}
func GetTopLevelContainerNode(g Graph, containedNode graph.Node) graph.Node | {
visited := map[int]bool{}
prevContainingNode := containedNode
for {
visited[prevContainingNode.ID()] = true
currContainingNode := GetContainingNode(g, prevContainingNode)
if currContainingNode == nil {
return prevContainingNode
}
if _, alreadyVisited := visited[currContainingNode.ID()]; alreadyVisited {
panic(fmt.Sprintf("contains cycle in %v", visited))
}
prevContainingNode = currContainingNode
}
panic(fmt.Sprintf("math failed %v", visited))
return nil
} |
package serialconsole
import original "github.com/Azure/azure-sdk-for-go/services/serialconsole/mgmt/2018-05-01/serialconsole"
const (
DefaultBaseURI = original.DefaultBaseURI
)
type BaseClient = original.BaseClient
type ConsoleClient = original.ConsoleClient
type DeploymentValidateResult = original.DeploymentValidateResult
type GetDisabledResult = original.GetDisabledResult
type GetResult = original.GetResult
type ListClient = original.ListClient
type ListConsoleClient = original.ListConsoleClient
type Operations = original.Operations
type SetDisabledResult = original.SetDisabledResult
func NewConsoleClient(subscriptionID string) ConsoleClient {
return original.NewConsoleClient(subscriptionID)
}
func NewConsoleClientWithBaseURI(baseURI string, subscriptionID string) ConsoleClient {
return original.NewConsoleClientWithBaseURI(baseURI, subscriptionID)
}
func NewListClient(subscriptionID string) ListClient {
return original.NewListClient(subscriptionID)
}
func NewListClientWithBaseURI(baseURI string, subscriptionID string) ListClient {
return original.NewListClientWithBaseURI(baseURI, subscriptionID)
}
func NewListConsoleClient(subscriptionID string) ListConsoleClient {
return original.NewListConsoleClient(subscriptionID)
}
func NewListConsoleClientWithBaseURI(baseURI string, subscriptionID string) ListConsoleClient {
return original.NewListConsoleClientWithBaseURI(baseURI, subscriptionID)
}
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
return original.NewWithBaseURI(baseURI, subscriptionID)
}
func UserAgent() string {
return original.UserAgent() + " profiles/preview"
}
func Version() string {
return original.Version()
}
func New(subscriptionID string) BaseClient | {
return original.New(subscriptionID)
} |
package permissions
import (
"path/filepath"
"util"
)
var globalPermissions *PermissionsLoader
func SetPath(permissions string) error {
if permissions != "default" {
pl, err := NewPermissionsLoader(permissions)
if err != nil {
return err
}
if globalPermissions != nil {
globalPermissions.Close()
}
globalPermissions = pl
if !pl.Get().Watch {
globalPermissions.Close()
}
} else {
if globalPermissions != nil {
globalPermissions.Close()
}
globalPermissions = nil
}
return nil
}
type PermissionsLoader struct {
Permissions *Permissions
Watcher *util.FileWatcher
}
func (pl *PermissionsLoader) Get() *Permissions {
if pl == nil {
return &Default
}
pl.Watcher.RLock()
defer pl.Watcher.RUnlock()
return pl.Permissions
}
func NewPermissionsLoader(filename string) (*PermissionsLoader, error) {
filename, err := filepath.Abs(filename)
if err != nil {
return nil, err
}
p, err := Load(filename)
if err != nil {
return nil, err
}
pl := &PermissionsLoader{
Permissions: p,
}
pl.Watcher, err = util.NewFileWatcher(filename, pl)
return pl, err
}
func (pl *PermissionsLoader) Reload() error {
p, err := Load(pl.Watcher.FileName)
if err != nil {
return err
}
pl.Watcher.Lock()
pl.Permissions = p
pl.Watcher.Unlock()
if !p.Watch {
pl.Close()
}
return nil
}
func (pl *PermissionsLoader) Close() {
pl.Watcher.Close()
}
func Get() *Permissions | {
if globalPermissions == nil {
return &Default
}
return globalPermissions.Get()
} |
package leetcode
func pow(x float64, n int) float64 {
if n == 1 {
return x
}
res := pow(x*x, n/2)
if n%2 == 1 {
res *= x
}
return res
}
func myPow(x float64, n int) float64 | {
if n == 0 {
return 1
}
flag := false
if n > 0 {
flag = true
} else {
n = -n
}
res := pow(x, n)
if !flag {
res = 1 / res
}
return res
} |
package websocket
type data struct {
Index int
Body []byte
Error error
}
func parseHeader(header []byte) (index int, ok bool) {
index = int(header[0])<<24 | int(header[1])<<16 | int(header[2])<<8 | int(header[3])
if ok = (header[0]&0x80 == 0); !ok {
index &= 0x7fffffff
}
return
}
func makeHeader(index int) (header [4]byte) | {
header[0] = byte(index >> 24 & 0xff)
header[1] = byte(index >> 16 & 0xff)
header[2] = byte(index >> 8 & 0xff)
header[3] = byte(index & 0xff)
return
} |
package terminal
import "fmt"
var ColorError int = 167
var ColorWarn int = 93
var ColorSuccess int = 82
var ColorNeutral int = 50
var BackgroundColorBlack = "\033[30;49m"
var BackgroundColorWhite = "\033[30;47m"
var ResetCode string = "\033[0m"
func Colorize(color int, msg string) string {
if !stdoutIsTTY {
return msg
}
return fmt.Sprintf("\033[0;1m\033[38;5;%dm%s%s", color, msg, ResetCode)
}
func BoldText(msg string) string | {
if !stdoutIsTTY {
return msg
}
return fmt.Sprintf("\033[1m%s\033[0m", msg)
} |
package testing
import "k8s.io/kubernetes/pkg/util/iptables"
type fake struct{}
func NewFake() *fake {
return &fake{}
}
func (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) {
return true, nil
}
func (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error {
return nil
}
func (*fake) EnsureRule(position iptables.RulePosition, table iptables.Table, chain iptables.Chain, args ...string) (bool, error) {
return true, nil
}
func (*fake) DeleteRule(table iptables.Table, chain iptables.Chain, args ...string) error {
return nil
}
func (*fake) IsIpv6() bool {
return false
}
func (*fake) Save(table iptables.Table) ([]byte, error) {
return make([]byte, 0), nil
}
func (*fake) SaveAll() ([]byte, error) {
return make([]byte, 0), nil
}
func (*fake) Restore(table iptables.Table, data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {
return nil
}
func (*fake) RestoreAll(data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {
return nil
}
func (*fake) AddReloadFunc(reloadFunc func()) {}
func (*fake) Destroy() {}
var _ = iptables.Interface(&fake{})
func (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error | {
return nil
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.