input
stringlengths 24
2.11k
| output
stringlengths 7
948
|
---|---|
package reveldi
type Container struct {
services map[string]Service
}
type Service interface{}
func (c *Container) Register(name string, serviceStruct Service) {
if len(c.services) == 0 {
c.services = make(map[string]Service)
}
c.services[name] = serviceStruct
}
func (c *Container) Get(name string) Service | {
return c.services[name]
} |
package classReader
import "math"
type ConstantIntegerInfo struct {
val int32
}
func (self *ConstantIntegerInfo) readInfo(reader *ClassReader) {
bytes := reader.readUint32()
self.val = int32(bytes)
}
func (self *ConstantIntegerInfo) Value() int32 {
return self.val
}
type ConstantFloatInfo struct {
val float32
}
func (self *ConstantFloatInfo) readInfo(reader *ClassReader) {
bytes := reader.readUint32()
self.val = math.Float32frombits(bytes)
}
func (self *ConstantFloatInfo) Value() float32 {
return self.val
}
type ConstantLongInfo struct {
val int64
}
func (self *ConstantLongInfo) readInfo(reader *ClassReader) {
bytes := reader.readUint64()
self.val = int64(bytes)
}
func (self *ConstantLongInfo) Value() int64 {
return self.val
}
type ConstantDoubleInfo struct {
val float64
}
func (self *ConstantDoubleInfo) Value() float64 {
return self.val
}
func (self *ConstantDoubleInfo) readInfo(reader *ClassReader) | {
bytes := reader.readUint64()
self.val = math.Float64frombits(bytes)
} |
package client
import (
authorizationapi "github.com/openshift/origin/pkg/authorization/api"
)
type SubjectAccessReviewsNamespacer interface {
SubjectAccessReviews(namespace string) SubjectAccessReviewInterface
}
type ClusterSubjectAccessReviews interface {
ClusterSubjectAccessReviews() SubjectAccessReviewInterface
}
type SubjectAccessReviewInterface interface {
Create(policy *authorizationapi.SubjectAccessReview) (*authorizationapi.SubjectAccessReviewResponse, error)
}
type subjectAccessReviews struct {
r *Client
ns string
}
func newSubjectAccessReviews(c *Client, namespace string) *subjectAccessReviews {
return &subjectAccessReviews{
r: c,
ns: namespace,
}
}
func (c *subjectAccessReviews) Create(policy *authorizationapi.SubjectAccessReview) (result *authorizationapi.SubjectAccessReviewResponse, err error) {
result = &authorizationapi.SubjectAccessReviewResponse{}
err = c.r.Post().Namespace(c.ns).Resource("subjectAccessReviews").Body(policy).Do().Into(result)
return
}
type clusterSubjectAccessReviews struct {
r *Client
}
func newClusterSubjectAccessReviews(c *Client) *clusterSubjectAccessReviews {
return &clusterSubjectAccessReviews{
r: c,
}
}
func (c *clusterSubjectAccessReviews) Create(policy *authorizationapi.SubjectAccessReview) (result *authorizationapi.SubjectAccessReviewResponse, err error) | {
result = &authorizationapi.SubjectAccessReviewResponse{}
err = c.r.Post().Resource("subjectAccessReviews").Body(policy).Do().Into(result)
return
} |
package logging
import (
"bytes"
"encoding/json"
"log"
"net/http"
"net/http/httputil"
"strings"
)
type transport struct {
name string
transport http.RoundTripper
}
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
if IsDebugOrHigher() {
reqData, err := httputil.DumpRequestOut(req, true)
if err == nil {
log.Printf("[DEBUG] "+logReqMsg, t.name, prettyPrintJsonLines(reqData))
} else {
log.Printf("[ERROR] %s API Request error: %#v", t.name, err)
}
}
resp, err := t.transport.RoundTrip(req)
if err != nil {
return resp, err
}
if IsDebugOrHigher() {
respData, err := httputil.DumpResponse(resp, true)
if err == nil {
log.Printf("[DEBUG] "+logRespMsg, t.name, prettyPrintJsonLines(respData))
} else {
log.Printf("[ERROR] %s API Response error: %#v", t.name, err)
}
}
return resp, nil
}
func NewTransport(name string, t http.RoundTripper) *transport {
return &transport{name, t}
}
const logReqMsg = `%s API Request Details:
---[ REQUEST ]---------------------------------------
%s
-----------------------------------------------------`
const logRespMsg = `%s API Response Details:
---[ RESPONSE ]--------------------------------------
%s
-----------------------------------------------------`
func prettyPrintJsonLines(b []byte) string | {
parts := strings.Split(string(b), "\n")
for i, p := range parts {
if b := []byte(p); json.Valid(b) {
var out bytes.Buffer
json.Indent(&out, b, "", " ")
parts[i] = out.String()
}
}
return strings.Join(parts, "\n")
} |
package common
import (
"strconv"
)
func Atof32(s string) float64 {
f, err := strconv.ParseFloat(s, 32)
if err != nil {
panic(InputErr(err.Error()))
}
return float64(f)
}
func Atoi(s string) int {
i, err := strconv.Atoi(s)
if err != nil {
panic(InputErr(err.Error()))
}
return i
}
func Atob(str string) bool {
b, err := strconv.ParseBool(str)
if err != nil {
panic(InputErr(err.Error()))
}
return b
}
func Atoi64(str string) int64 {
i, err := strconv.ParseInt(str, 10, 64)
if err != nil {
panic(InputErr(err.Error()))
}
return i
}
func Atof64(str string) float64 | {
i, err := strconv.ParseFloat(str, 64)
if err != nil {
panic(InputErr(err.Error()))
}
return i
} |
package s0081
import (
"github.com/peterstace/project-euler/graph"
)
type matrix [][]int
func parameterised(m matrix) interface{} {
g, start, end := matrixToGraph(m)
return g.ShortestPath(start)[end]
}
func matrixToGraph(m matrix) (g graph.WeightedDigraph, start int, end int) {
g = graph.NewOrderZeroWeightedDigraph()
n := len(m)
node := func(i, j int) int {
return i*n + j
}
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if i > 0 {
g.AddEdge(node(i-1, j), node(i, j), float64(m[i][j]))
}
if j > 0 {
g.AddEdge(node(i, j-1), node(i, j), float64(m[i][j]))
}
}
}
g.AddEdge(-1, node(0, 0), float64(m[0][0]))
return g, -1, node(n-1, n-1)
}
func Answer() interface{} | {
return parameterised(data)
} |
package run_model
import (
strfmt "github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
type APIPipelineRuntime struct {
PipelineManifest string `json:"pipeline_manifest,omitempty"`
WorkflowManifest string `json:"workflow_manifest,omitempty"`
}
func (m *APIPipelineRuntime) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
func (m *APIPipelineRuntime) UnmarshalBinary(b []byte) error {
var res APIPipelineRuntime
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}
func (m *APIPipelineRuntime) Validate(formats strfmt.Registry) error | {
return nil
} |
package btcec
import (
secp "github.com/decred/dcrd/dcrec/secp256k1/v4"
)
type JacobianPoint = secp.JacobianPoint
func MakeJacobianPoint(x, y, z *FieldVal) JacobianPoint {
return secp.MakeJacobianPoint(x, y, z)
}
func DecompressY(x *FieldVal, odd bool, resultY *FieldVal) bool {
return secp.DecompressY(x, odd, resultY)
}
func DoubleNonConst(p, result *JacobianPoint) {
secp.DoubleNonConst(p, result)
}
func ScalarBaseMultNonConst(k *ModNScalar, result *JacobianPoint) {
secp.ScalarBaseMultNonConst(k, result)
}
func ScalarMultNonConst(k *ModNScalar, point, result *JacobianPoint) {
secp.ScalarMultNonConst(k, point, result)
}
func AddNonConst(p1, p2, result *JacobianPoint) | {
secp.AddNonConst(p1, p2, result)
} |
package internalversion
import (
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
admissionregistration "k8s.io/kubernetes/pkg/apis/admissionregistration"
)
type ValidatingWebhookConfigurationLister interface {
List(selector labels.Selector) (ret []*admissionregistration.ValidatingWebhookConfiguration, err error)
Get(name string) (*admissionregistration.ValidatingWebhookConfiguration, error)
ValidatingWebhookConfigurationListerExpansion
}
type validatingWebhookConfigurationLister struct {
indexer cache.Indexer
}
func NewValidatingWebhookConfigurationLister(indexer cache.Indexer) ValidatingWebhookConfigurationLister {
return &validatingWebhookConfigurationLister{indexer: indexer}
}
func (s *validatingWebhookConfigurationLister) Get(name string) (*admissionregistration.ValidatingWebhookConfiguration, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(admissionregistration.Resource("validatingwebhookconfiguration"), name)
}
return obj.(*admissionregistration.ValidatingWebhookConfiguration), nil
}
func (s *validatingWebhookConfigurationLister) List(selector labels.Selector) (ret []*admissionregistration.ValidatingWebhookConfiguration, err error) | {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*admissionregistration.ValidatingWebhookConfiguration))
})
return ret, err
} |
package machinelearningservices
import (
"github.com/Azure/go-autorest/autorest"
)
const (
DefaultBaseURI = "https:management.azure.com"
)
type BaseClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
func New(subscriptionID string) BaseClient {
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
}
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient | {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
} |
package console
import (
"github.com/cgrates/cgrates/apier/v1"
"github.com/cgrates/cgrates/engine"
"github.com/cgrates/cgrates/utils"
)
func init() {
c := &CmdGetDataCost{
name: "datacost",
rpcMethod: "ApierV1.GetDataCost",
clientArgs: []string{"Direction", "Category", "Tenant", "Account", "Subject", "StartTime", "Usage"},
}
commands[c.Name()] = c
c.CommandExecuter = &CommandExecuter{c}
}
type CmdGetDataCost struct {
name string
rpcMethod string
rpcParams *v1.AttrGetDataCost
clientArgs []string
*CommandExecuter
}
func (self *CmdGetDataCost) Name() string {
return self.name
}
func (self *CmdGetDataCost) RpcParams() interface{} {
if self.rpcParams == nil {
self.rpcParams = &v1.AttrGetDataCost{Direction: utils.OUT}
}
return self.rpcParams
}
func (self *CmdGetDataCost) PostprocessRpcParams() error {
return nil
}
func (self *CmdGetDataCost) RpcResult() interface{} {
return &engine.DataCost{}
}
func (self *CmdGetDataCost) ClientArgs() []string {
return self.clientArgs
}
func (self *CmdGetDataCost) RpcMethod() string | {
return self.rpcMethod
} |
package app
import (
. "strconv"
"time"
)
type User struct {
Id int64
Nom string
Prenom string
Email string
Password string
CreatedAt time.Time
UpdatedAt time.Time
}
func (u User) Save() {
db.Save(&u)
}
func (u User) Update() {
db.First(&u, &u.Id).Update(&u)
}
func (u User) GetById() User {
db.Where("id = ?", Itoa(int(u.Id))).Find(&u)
return u
}
func (u User) GetList() []User {
var users []User
db.Find(&users)
return users
}
func (u User) Delete() | {
db.Delete(&u)
} |
package internal
import (
. "github.com/signal18/replication-manager/goofys/api/common"
. "gopkg.in/check.v1"
"github.com/jacobsa/fuse"
)
type AwsTest struct {
s3 *S3Backend
}
var _ = Suite(&AwsTest{})
func (s *AwsTest) SetUpSuite(t *C) {
var err error
s.s3, err = NewS3("", &FlagStorage{}, &S3Config{
Region: "us-east-1",
})
t.Assert(err, IsNil)
}
func (s *AwsTest) TestBucket404(t *C) {
s.s3.bucket = RandStringBytesMaskImprSrc(64)
err, isAws := s.s3.detectBucketLocationByHEAD()
t.Assert(err, Equals, fuse.ENOENT)
t.Assert(isAws, Equals, true)
}
func (s *AwsTest) TestRegionDetection(t *C) | {
s.s3.bucket = "goofys-eu-west-1.signal18/replication-manager.xyz"
err, isAws := s.s3.detectBucketLocationByHEAD()
t.Assert(err, IsNil)
t.Assert(*s.s3.awsConfig.Region, Equals, "eu-west-1")
t.Assert(isAws, Equals, true)
} |
package fake
import (
v1beta1 "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/clients/generated/client/clientset/versioned/typed/cloudscheduler/v1beta1"
rest "k8s.io/client-go/rest"
testing "k8s.io/client-go/testing"
)
type FakeCloudschedulerV1beta1 struct {
*testing.Fake
}
func (c *FakeCloudschedulerV1beta1) RESTClient() rest.Interface {
var ret *rest.RESTClient
return ret
}
func (c *FakeCloudschedulerV1beta1) CloudSchedulerJobs(namespace string) v1beta1.CloudSchedulerJobInterface | {
return &FakeCloudSchedulerJobs{c, namespace}
} |
package s2
var (
_ Shape = (*PointVector)(nil)
)
type PointVector []Point
func (p *PointVector) NumEdges() int { return len(*p) }
func (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} }
func (p *PointVector) ReferencePoint() ReferencePoint { return OriginReferencePoint(false) }
func (p *PointVector) NumChains() int { return len(*p) }
func (p *PointVector) Chain(i int) Chain { return Chain{i, 1} }
func (p *PointVector) ChainEdge(i, j int) Edge { return Edge{(*p)[i], (*p)[j]} }
func (p *PointVector) Dimension() int { return 0 }
func (p *PointVector) IsEmpty() bool { return defaultShapeIsEmpty(p) }
func (p *PointVector) IsFull() bool { return defaultShapeIsFull(p) }
func (p *PointVector) typeTag() typeTag { return typeTagPointVector }
func (p *PointVector) privateInterface() {}
func (p *PointVector) ChainPosition(e int) ChainPosition | { return ChainPosition{e, 0} } |
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 New(subscriptionID string) BaseClient {
return original.New(subscriptionID)
}
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 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 NewListConsoleClient(subscriptionID string) ListConsoleClient | {
return original.NewListConsoleClient(subscriptionID)
} |
package resources
import "github.com/awslabs/goformation/cloudformation/policies"
type AWSIoTAnalyticsPipeline_DeviceShadowEnrich struct {
Attribute string `json:"Attribute,omitempty"`
Name string `json:"Name,omitempty"`
Next string `json:"Next,omitempty"`
RoleArn string `json:"RoleArn,omitempty"`
ThingName string `json:"ThingName,omitempty"`
_deletionPolicy policies.DeletionPolicy
_dependsOn []string
_metadata map[string]interface{}
}
func (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) AWSCloudFormationType() string {
return "AWS::IoTAnalytics::Pipeline.DeviceShadowEnrich"
}
func (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) DependsOn() []string {
return r._dependsOn
}
func (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDependsOn(dependencies []string) {
r._dependsOn = dependencies
}
func (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetMetadata(metadata map[string]interface{}) {
r._metadata = metadata
}
func (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDeletionPolicy(policy policies.DeletionPolicy) {
r._deletionPolicy = policy
}
func (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) Metadata() map[string]interface{} | {
return r._metadata
} |
package gaerecords
import (
"testing"
)
func TestSetIDAndGetID(t *testing.T) | {
people := CreateTestModel()
person := people.New()
assertEqual(t, NoIDValue, person.ID())
assertEqual(t, person, person.setID(123))
assertEqual(t, int64(123), person.ID())
} |
package test
import (
"io/ioutil"
)
func Fixture(path string) string | {
contents, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
return string(contents)
} |
package ai
import (
"context"
"sync"
)
type Loader func(context.Context) (map[int64]int64, error)
type AI struct {
whites map[int64]int64
sync.RWMutex
}
func New() (a *AI) {
return &AI{
whites: make(map[int64]int64),
}
}
func (a *AI) White(mid int64) (num int64, ok bool) {
a.RLock()
defer a.RUnlock()
num, ok = a.whites[mid]
return
}
func (a *AI) LoadWhite(c context.Context, loader Loader) (err error) | {
var (
whites map[int64]int64
)
if whites, err = loader(c); err != nil {
return
}
a.Lock()
a.whites = whites
a.Unlock()
return
} |
package main
import (
"github.com/nprog/SkyEye/common"
"github.com/nprog/SkyEye/libnet"
"github.com/nprog/SkyEye/log"
"encoding/json"
"sync"
"time"
)
func Test() {
rti := common.NewMachineInfo()
rti.GetInfo()
temp, err := json.Marshal(rti)
if err != nil {
log.Error(err.Error())
return
}
log.Info(string(temp))
}
type OnlineCfg struct {
RealtimeInfo []string
RealtimeInfoCycle int64
}
type Collection struct {
onlineCfg *OnlineCfg
session *libnet.Session
changeCfg bool
changeCfgMutex sync.Mutex
}
func (c *Collection) sendMachineInfo() {
log.V(1).Info("sendMachineInfo")
}
func (c *Collection) sendRealtimeInfoLoop() {
log.Info("sendRealtimeInfoLoop")
timer := time.NewTicker(5 * time.Second)
ttl := time.After(10 * time.Second)
bkloop:
for {
select {
case <-timer.C:
if c.changeCfg {
c.changeCfg = false
break bkloop
}
case <-ttl:
break
}
}
log.Info("re config RealtimeInfoLoop.")
c.sendRealtimeInfoLoop()
}
func (c *Collection) sendFastRealtimeInfoLoop() {
}
func NewCollection() *Collection | {
return &Collection{}
} |
package action
import (
"io/ioutil"
"net/http"
"strings"
"fmt"
)
type Http struct {
config *ActionConfig
}
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
}
func NewHttp(config *ActionConfig) *Http {
return &Http{
config: config,
}
}
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
} |
package v1
type ConfigMapProjectionApplyConfiguration struct {
LocalObjectReferenceApplyConfiguration `json:",inline"`
Items []KeyToPathApplyConfiguration `json:"items,omitempty"`
Optional *bool `json:"optional,omitempty"`
}
func ConfigMapProjection() *ConfigMapProjectionApplyConfiguration {
return &ConfigMapProjectionApplyConfiguration{}
}
func (b *ConfigMapProjectionApplyConfiguration) WithName(value string) *ConfigMapProjectionApplyConfiguration {
b.Name = &value
return b
}
func (b *ConfigMapProjectionApplyConfiguration) WithOptional(value bool) *ConfigMapProjectionApplyConfiguration {
b.Optional = &value
return b
}
func (b *ConfigMapProjectionApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *ConfigMapProjectionApplyConfiguration | {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithItems")
}
b.Items = append(b.Items, *values[i])
}
return b
} |
package credentials
import (
"strings"
"github.com/docker/docker/cliconfig/configfile"
"github.com/docker/engine-api/types"
)
type fileStore struct {
file *configfile.ConfigFile
}
func NewFileStore(file *configfile.ConfigFile) Store {
return &fileStore{
file: file,
}
}
func (c *fileStore) Erase(serverAddress string) error {
delete(c.file.AuthConfigs, serverAddress)
return c.file.Save()
}
func (c *fileStore) Get(serverAddress string) (types.AuthConfig, error) {
authConfig, ok := c.file.AuthConfigs[serverAddress]
if !ok {
for registry, ac := range c.file.AuthConfigs {
if serverAddress == convertToHostname(registry) {
return ac, nil
}
}
authConfig = types.AuthConfig{}
}
return authConfig, nil
}
func (c *fileStore) GetAll() (map[string]types.AuthConfig, error) {
return c.file.AuthConfigs, nil
}
func (c *fileStore) Store(authConfig types.AuthConfig) error {
c.file.AuthConfigs[authConfig.ServerAddress] = authConfig
return c.file.Save()
}
func convertToHostname(url string) string | {
stripped := url
if strings.HasPrefix(url, "http://") {
stripped = strings.Replace(url, "http://", "", 1)
} else if strings.HasPrefix(url, "https://") {
stripped = strings.Replace(url, "https://", "", 1)
}
nameParts := strings.SplitN(stripped, "/", 2)
return nameParts[0]
} |
package spnego
import (
"encoding/base64"
"fmt"
"net/http"
"strings"
"github.com/apcera/gssapi"
)
func CheckSPNEGONegotiate(lib *gssapi.Lib, h http.Header, name string) (present bool, token *gssapi.Buffer) {
var err error
defer func() {
if err != nil {
lib.Debug(fmt.Sprintf("CheckSPNEGONegotiate: %v", err))
}
}()
v := h.Get(name)
if len(v) == 0 || !strings.HasPrefix(v, "Negotiate") {
return false, nil
}
present = true
tbytes, err := base64.StdEncoding.DecodeString(strings.TrimSpace(v[len("Negotiate"):]))
if err != nil {
return false, nil
}
if len(tbytes) > 0 {
token, err = lib.MakeBufferBytes(tbytes)
if err != nil {
return false, nil
}
}
return present, token
}
func AddSPNEGONegotiate(h http.Header, name string, token *gssapi.Buffer) | {
if name == "" {
return
}
v := "Negotiate"
if token.Length() != 0 {
data := token.Bytes()
v = v + " " + base64.StdEncoding.EncodeToString(data)
}
h.Set(name, v)
} |
package resources
import "github.com/awslabs/goformation/cloudformation/policies"
type AWSBatchJobDefinition_NodeRangeProperty struct {
Container *AWSBatchJobDefinition_ContainerProperties `json:"Container,omitempty"`
TargetNodes string `json:"TargetNodes,omitempty"`
_deletionPolicy policies.DeletionPolicy
_dependsOn []string
_metadata map[string]interface{}
}
func (r *AWSBatchJobDefinition_NodeRangeProperty) AWSCloudFormationType() string {
return "AWS::Batch::JobDefinition.NodeRangeProperty"
}
func (r *AWSBatchJobDefinition_NodeRangeProperty) DependsOn() []string {
return r._dependsOn
}
func (r *AWSBatchJobDefinition_NodeRangeProperty) SetDependsOn(dependencies []string) {
r._dependsOn = dependencies
}
func (r *AWSBatchJobDefinition_NodeRangeProperty) Metadata() map[string]interface{} {
return r._metadata
}
func (r *AWSBatchJobDefinition_NodeRangeProperty) SetDeletionPolicy(policy policies.DeletionPolicy) {
r._deletionPolicy = policy
}
func (r *AWSBatchJobDefinition_NodeRangeProperty) SetMetadata(metadata map[string]interface{}) | {
r._metadata = metadata
} |
package versioned
import (
"fmt"
securityv1 "github.com/openshift/client-go/security/clientset/versioned/typed/security/v1"
discovery "k8s.io/client-go/discovery"
rest "k8s.io/client-go/rest"
flowcontrol "k8s.io/client-go/util/flowcontrol"
)
type Interface interface {
Discovery() discovery.DiscoveryInterface
SecurityV1() securityv1.SecurityV1Interface
}
type Clientset struct {
*discovery.DiscoveryClient
securityV1 *securityv1.SecurityV1Client
}
func (c *Clientset) SecurityV1() securityv1.SecurityV1Interface {
return c.securityV1
}
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
if c == nil {
return nil
}
return c.DiscoveryClient
}
func NewForConfigOrDie(c *rest.Config) *Clientset {
var cs Clientset
cs.securityV1 = securityv1.NewForConfigOrDie(c)
cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)
return &cs
}
func New(c rest.Interface) *Clientset {
var cs Clientset
cs.securityV1 = securityv1.New(c)
cs.DiscoveryClient = discovery.NewDiscoveryClient(c)
return &cs
}
func NewForConfig(c *rest.Config) (*Clientset, error) | {
configShallowCopy := *c
if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {
if configShallowCopy.Burst <= 0 {
return nil, fmt.Errorf("Burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0")
}
configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)
}
var cs Clientset
var err error
cs.securityV1, err = securityv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
return &cs, nil
} |
package validation
import (
"testing"
"time"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"
)
func TestWaitForNodeToBeReady(t *testing.T) {
conditions := []v1.NodeCondition{{Type: "Ready", Status: "True"}}
nodeName := "node-foo"
nodeAA := setupNodeAA(t, conditions, nodeName)
test, err := nodeAA.WaitForNodeToBeReady(nodeName)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if test != true {
t.Fatalf("unexpected error WaitForNodeToBeReady Failed: %v", test)
}
}
func setupNodeAA(t *testing.T, conditions []v1.NodeCondition, nodeName string) *NodeAPIAdapter {
node := &v1.Node{
ObjectMeta: metav1.ObjectMeta{Name: nodeName},
Spec: v1.NodeSpec{Unschedulable: false},
Status: v1.NodeStatus{Conditions: conditions},
}
c := fake.NewSimpleClientset(node)
nodeAA, err := NewNodeAPIAdapter(c, time.Duration(10)*time.Millisecond)
if err != nil {
t.Fatalf("unexpected error building NodeAPIAdapter: %v", err)
}
return nodeAA
}
func TestWaitForNodeToBeNotReady(t *testing.T) | {
conditions := []v1.NodeCondition{{Type: "Ready", Status: "False"}}
nodeName := "node-foo"
nodeAA := setupNodeAA(t, conditions, nodeName)
test, err := nodeAA.WaitForNodeToBeNotReady(nodeName)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if test != true {
t.Fatalf("unexpected error WaitForNodeToBeNotReady Failed: %v", test)
}
} |
package api
type FormatsResponse struct {
Formats []string `json:"formats"`
}
func (a *API) getFormats(ctx *context) {
ctx.Success(FormatsResponse{Formats: a.c.formats.Keys()})
}
type LeechTypesResponse struct {
LeechTypes []string `json:"leech_types"`
}
type MediaResponse struct {
Media []string `json:"media"`
}
func (a *API) getMedia(ctx *context) {
ctx.Success(MediaResponse{Media: a.c.media.Keys()})
}
type ReleaseGroupTypesResponse struct {
ReleaseGroupTypes []string `json:"release_group_types"`
}
func (a *API) getReleaseGroupTypes(ctx *context) {
ctx.Success(ReleaseGroupTypesResponse{ReleaseGroupTypes: a.c.releaseGroupTypes.Keys()})
}
type ReleasePropertiesResponse struct {
ReleaseProperties []string `json:"release_properties"`
}
func (a *API) getReleaseProperties(ctx *context) {
ctx.Success(ReleasePropertiesResponse{ReleaseProperties: a.c.releaseProperties.Keys()})
}
type ReleaseRolesResponse struct {
ReleaseRoles []string `json:"release_roles"`
}
func (a *API) getReleaseRoles(ctx *context) {
ctx.Success(ReleaseRolesResponse{ReleaseRoles: a.c.releaseRoles.Keys()})
}
type PrivilegesResponse struct {
Privileges []string `json:"privileges"`
}
func (a *API) getPrivileges(ctx *context) {
ctx.Success(PrivilegesResponse{Privileges: a.c.privileges.Keys()})
}
func (a *API) getLeechTypes(ctx *context) | {
ctx.Success(LeechTypesResponse{LeechTypes: a.c.leechTypes.Keys()})
} |
package platform
var IsPartnerBuild = true
func GuessMimeTypeByBuffer(buf []byte) (mimeType string, err error) {
return "mime type disabled", nil
}
func GuessMimeType(absPath string) (mimeType string, err error) | {
return "mime type disabled", nil
} |
package core
import (
"encoding/json"
"github.com/oracle/oci-go-sdk/common"
)
type UpdateComputeImageCapabilitySchemaDetails struct {
DisplayName *string `mandatory:"false" json:"displayName"`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
SchemaData map[string]ImageCapabilitySchemaDescriptor `mandatory:"false" json:"schemaData"`
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
}
func (m *UpdateComputeImageCapabilitySchemaDetails) UnmarshalJSON(data []byte) (e error) {
model := struct {
DisplayName *string `json:"displayName"`
FreeformTags map[string]string `json:"freeformTags"`
SchemaData map[string]imagecapabilityschemadescriptor `json:"schemaData"`
DefinedTags map[string]map[string]interface{} `json:"definedTags"`
}{}
e = json.Unmarshal(data, &model)
if e != nil {
return
}
var nn interface{}
m.DisplayName = model.DisplayName
m.FreeformTags = model.FreeformTags
m.SchemaData = make(map[string]ImageCapabilitySchemaDescriptor)
for k, v := range model.SchemaData {
nn, e = v.UnmarshalPolymorphicJSON(v.JsonData)
if e != nil {
return e
}
if nn != nil {
m.SchemaData[k] = nn.(ImageCapabilitySchemaDescriptor)
} else {
m.SchemaData[k] = nil
}
}
m.DefinedTags = model.DefinedTags
return
}
func (m UpdateComputeImageCapabilitySchemaDetails) String() string | {
return common.PointerString(m)
} |
package clipboard
import (
"time"
)
type Duration struct {
time.Duration
}
func (d Duration) MarshalText() ([]byte, error) {
return []byte(d.String()), nil
}
func (d *Duration) UnmarshalText(text []byte) error | {
var err error
d.Duration, err = time.ParseDuration(string(text))
return err
} |
package main
import (
"fmt"
"strings"
)
type talker interface {
talk() string
}
func shout(t talker) {
louder := strings.ToUpper(t.talk())
fmt.Println(louder)
}
type laser int
type rover string
func (r rover) talk() string {
return string(r)
}
func main() {
r := rover("whir whir")
shout(r)
}
func (l laser) talk() string | {
return strings.Repeat("toot ", int(l))
} |
package caller
import (
"fmt"
"path/filepath"
"regexp"
"testing"
)
func TestCallResolver(t *testing.T) {
cr := NewCallResolver(0, regexp.MustCompile(`resolver_test\.go.*$`))
for i := 0; i < 2; i++ {
if l := len(cr.cache); l != i {
t.Fatalf("cache has %d entries, expected %d", l, i)
}
file, _, fun := func() (string, int, string) {
return cr.Lookup(1)
}()
if file != "resolver_test.go" {
t.Fatalf("wrong file '%s'", file)
}
if fun != "TestCallResolver" {
t.Fatalf("unexpected caller reported: %s", fun)
}
}
}
func BenchmarkFormatedCaller(b *testing.B) {
for i := 0; i < b.N; i++ {
file, line, _ := Lookup(1)
s := fmt.Sprintf("%s:%d", file, line)
if testing.Verbose() {
b.Log(s)
}
}
}
func BenchmarkSimpleCaller(b *testing.B) {
for i := 0; i < b.N; i++ {
file, line, _ := Lookup(1)
if testing.Verbose() {
s := fmt.Sprintf("%s:%d", file, line)
b.Log(s)
}
}
}
func TestDefaultCallResolver(t *testing.T) | {
defer func() { defaultCallResolver.cache = map[uintptr]*cachedLookup{} }()
for i := 0; i < 2; i++ {
if l := len(defaultCallResolver.cache); l != i {
t.Fatalf("cache has %d entries, expected %d", l, i)
}
file, _, fun := Lookup(0)
if fun != "TestDefaultCallResolver" {
t.Fatalf("unexpected caller reported: %s", fun)
}
if file != filepath.Join("util", "caller", "resolver_test.go") {
t.Fatalf("wrong file '%s'", file)
}
}
} |
package resistor
func Rpara(resists ...float64) (Rtotal float64) {
for _, r := range resists {
Rtotal = Rtotal + recip(r)
}
return
}
func Rser(resists ...float64) (Rtotal float64) | {
for _, r := range resists {
Rtotal = Rtotal + r
}
return
} |
package routers
import (
"code.google.com/p/go.crypto/bcrypt"
"github.com/codegangsta/martini-contrib/render"
"github.com/martini-contrib/sessions"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"net/http"
)
func AdminUpdatePassword(req *http.Request, r render.Render, db *mgo.Database) {
pass := req.FormValue("password")
verify := req.FormValue("verify")
if pass == verify {
hashedPass, _ := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost)
info, err := db.C("id").Upsert(bson.M{"email": "admin@vim-tips.com"}, bson.M{"$set": bson.M{"password": hashedPass, "email": "admin@vim-tips.com"}})
if err == nil {
if info.Updated >= 0 {
r.HTML(200, "admin/password", map[string]interface{}{
"IsPost": true,
"IsPassword": true,
"IsSuccess": true}, render.HTMLOptions{Layout: "admin/layout"})
}
}
} else {
r.HTML(200, "admin/password", map[string]interface{}{
"IsPost": true,
"IsPassword": true,
"IsSuccess": false}, render.HTMLOptions{Layout: "admin/layout"})
}
}
func AdminPassword(r render.Render, s sessions.Session) | {
r.HTML(200, "admin/password", map[string]interface{}{
"IsPassword": true}, render.HTMLOptions{Layout: "admin/layout"})
} |
package main
import (
"fmt"
"os"
"go.pedge.io/dockerplugin"
"go.pedge.io/dockervolume"
)
func main() {
if err := do(); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
os.Exit(1)
}
os.Exit(0)
}
func do() error | {
return dockervolume.NewTCPServer(
newVolumeDriver("/tmp/dockervolume-example-mount"),
"dockervolume-example",
":6789",
dockerplugin.ServerOptions{},
).Serve()
} |
package sysstats
import (
"os/exec"
"strconv"
"strings"
)
type LoadAvg map[string]float64
func getLoadAvg() (loadAvg LoadAvg, err error) | {
out, err := exec.Command(`sysctl`, `-n`, `vm.loadavg`).Output()
if err != nil {
return nil, err
}
loadAvg = LoadAvg{}
fields := strings.Fields(string(out))
for i := 1; i < 4; i++ {
load, err := strconv.ParseFloat(fields[i], 64)
if err != nil {
return nil, err
}
switch i {
case 1:
loadAvg[`avg1`] = load
case 2:
loadAvg[`avg5`] = load
case 3:
loadAvg[`avg15`] = load
}
}
return loadAvg, nil
} |
package kusto
import (
"github.com/Azure/go-autorest/autorest"
)
const (
DefaultBaseURI = "https:management.azure.com"
)
type BaseClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
func New(subscriptionID string) BaseClient {
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
}
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient | {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
} |
package helpers
import (
"bytes"
"errors"
"runtime"
)
func BytesToUint16(field [2]byte) uint16 {
return uint16(field[0])<<8 | uint16(field[1])
}
func Uint16ToBytes(value uint16) [2]byte {
byte0 := byte(value >> 8)
byte1 := byte(0x00ff & value)
return [2]byte{byte0, byte1}
}
func GetBytes(b *bytes.Buffer, n int) []byte {
slice := make([]byte, n)
nread, err := b.Read(slice)
if err != nil || nread != n {
panic(errors.New("Unexpected end of data."))
}
return slice
}
func HandleErrorPanic(err *error, functionName string) {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
perr := r.(error)
*err = errors.New(functionName + ": " + perr.Error())
}
}
func GetByte(b *bytes.Buffer) byte | {
byte, err := b.ReadByte()
if err != nil {
panic(errors.New("Unexpected end of data"))
}
return byte
} |
package main
import (
"fmt"
)
type Player struct {
ID string
Name string
Health int
Hunger int
CriticalHunger bool
NextAction int
Dead bool
}
func NewPlayer(ID, name string) *Player {
return &Player{ID, name, 100, 0, false, 0, false}
}
func (p *Player) String() string {
return fmt.Sprintf("[%-12s](HP: %3d)<Hunger: %3d>", p.Name, p.Health, p.Hunger)
}
func (p *Player) AddHunger(amount int) int {
p.Hunger += amount
if p.Hunger >= 100 {
p.Hunger = 100
if p.CriticalHunger {
return 2
}
p.CriticalHunger = true
return 1
}
if p.Hunger <= 0 {
p.Hunger = 0
}
return 0
}
func (p *Player) AddHealth(amount int) bool | {
p.Health += amount
if p.Health > 100 {
p.Health = 100
}
if p.Health <= 0 {
p.Health = 0
p.Dead = true
return true
}
return false
} |
package reports
import (
"time"
"github.com/rafaeljusto/druns/core/db"
)
type Service struct {
sqler db.SQLer
}
func (s Service) IncomingPerGroup(month time.Time, classValue float64) ([]Incoming, error) {
dao := newDAO(s.sqler)
return dao.incomingPerGroup(month, classValue)
}
func NewService(sqler db.SQLer) Service | {
return Service{sqler}
} |
package udt
import (
"io"
)
type ack2Packet struct {
h header
ackSeqNo uint32
}
func (p *ack2Packet) sendTime() (ts uint32) {
return p.h.ts
}
func (p *ack2Packet) writeTo(w io.Writer) (err error) {
if err := p.h.writeTo(w, ack2, p.ackSeqNo); err != nil {
return err
}
return
}
func (p *ack2Packet) readFrom(r io.Reader) (err error) {
p.ackSeqNo, err = p.h.readFrom(r)
return
}
func (p *ack2Packet) socketId() (sockId uint32) | {
return p.h.dstSockId
} |
package types
import (
"net"
)
type IPv4 [4]byte
func (v4 IPv4) String() string {
return v4.IP().String()
}
func (v4 *IPv4) DeepCopyInto(out *IPv4) {
copy(out[:], v4[:])
return
}
func (v4 IPv4) IP() net.IP | {
return v4[:]
} |
package event
import (
"fmt"
"sync/atomic"
"time"
)
type Increment struct {
Name string
Value int64
}
func (e *Increment) StatClass() string {
return "counter"
}
func (e *Increment) Update(e2 Event) error {
if e.Type() != e2.Type() {
return fmt.Errorf("statsd event type conflict: %s vs %s ", e.String(), e2.String())
}
atomic.AddInt64(&e.Value, e2.Payload().(int64))
return nil
}
func (e *Increment) Reset() {
e.Value = 0
}
func (e Increment) Payload() interface{} {
return e.Value
}
func (e Increment) Stats(tick time.Duration) []string {
return []string{fmt.Sprintf("%s:%d|c", e.Name, e.Value)}
}
func (e *Increment) SetKey(key string) {
e.Name = key
}
func (e Increment) Type() int {
return EventIncr
}
func (e Increment) TypeString() string {
return "Increment"
}
func (e Increment) String() string {
return fmt.Sprintf("{Type: %s, Key: %s, Value: %d}", e.TypeString(), e.Name, e.Value)
}
func (e Increment) Key() string | {
return e.Name
} |
package atc
import (
"errors"
multierror "github.com/hashicorp/go-multierror"
)
type AuthFlags struct {
NoAuth bool `long:"no-really-i-dont-want-any-auth" description:"Ignore warnings about not configuring auth"`
BasicAuth BasicAuthFlag `group:"Basic Authentication" namespace:"basic-auth"`
}
type BasicAuthFlag struct {
Username string `long:"username" description:"Username to use for basic auth."`
Password string `long:"password" description:"Password to use for basic auth."`
}
func (auth *BasicAuthFlag) IsConfigured() bool {
return auth.Username != "" || auth.Password != ""
}
func (auth *BasicAuthFlag) Validate() error | {
var errs *multierror.Error
if auth.Username == "" {
errs = multierror.Append(
errs,
errors.New("must specify --basic-auth-username to use basic auth."),
)
}
if auth.Password == "" {
errs = multierror.Append(
errs,
errors.New("must specify --basic-auth-password to use basic auth."),
)
}
return errs.ErrorOrNil()
} |
package cmd
type readDirOpts struct {
count int
followDirSymlink bool
}
func readDir(dirPath string) (entries []string, err error) {
return readDirWithOpts(dirPath, readDirOpts{count: -1})
}
func readDirN(dirPath string, count int) (entries []string, err error) | {
return readDirWithOpts(dirPath, readDirOpts{count: count})
} |
package v1
import (
common "github.com/kubeflow/common/pkg/apis/common/v1"
"k8s.io/apimachinery/pkg/runtime"
)
func Int32(v int32) *int32 {
return &v
}
func addDefaultingFuncs(scheme *runtime.Scheme) error {
return RegisterDefaults(scheme)
}
func setDefaultsTypeLauncher(spec *common.ReplicaSpec) {
if spec != nil && spec.RestartPolicy == "" {
spec.RestartPolicy = DefaultRestartPolicy
}
}
func SetDefaults_MPIJob(mpiJob *MPIJob) {
if mpiJob.Spec.CleanPodPolicy == nil {
none := common.CleanPodPolicyNone
mpiJob.Spec.CleanPodPolicy = &none
}
setDefaultsTypeLauncher(mpiJob.Spec.MPIReplicaSpecs[MPIReplicaTypeLauncher])
setDefaultsTypeWorker(mpiJob.Spec.MPIReplicaSpecs[MPIReplicaTypeWorker])
}
func setDefaultsTypeWorker(spec *common.ReplicaSpec) | {
if spec != nil && spec.RestartPolicy == "" {
spec.RestartPolicy = DefaultRestartPolicy
}
} |
package problems
import "fmt"
func partitionDfs(data []byte, i int, buf *[]string, out *[][]string) {
if i == len(data) {
m := make([]string, len(*buf))
copy(m, *buf)
*out = append(*out, m)
return
}
var isPalindrome func (data []byte, s int, e int) bool
isPalindrome = func (data []byte, s int, e int) bool {
i, j := s, e
for i < j {
if data[i] != data[j] {
return false
} else {
i++
j--
}
}
return true
}
for k := i; k < len(data); k++ {
if isPalindrome(data, i, k) {
*buf = append(*buf, string(data[i:k + 1]))
partitionDfs(data, k + 1, buf, out)
*buf = (*buf)[:len(*buf) - 1]
}
}
}
func partition(s string) [][]string {
var buf []string
var out [][]string
partitionDfs([]byte(s), 0, &buf, &out)
return out
}
func Partition() | {
fmt.Printf("<131> ")
fmt.Println(partition("aabc"))
} |
package queue
import "context"
type Client struct {
Content []byte
err error
}
func (c *Client) Push(ctx context.Context, content []byte) error {
if c.err != nil {
return c.err
}
c.Content = content
return nil
}
func NewClient(options ...func(*Client)) *Client {
c := &Client{}
for _, option := range options {
option(c)
}
return c
}
func ClientError(err error) func(*Client) | {
return func(c *Client) {
c.err = err
}
} |
package goku
import (
"runtime"
"testing"
"time"
)
type TestReader struct{}
func (self TestReader) Read() ([]Message, error) {
time.Sleep(10 * time.Millisecond)
return []Message{"Hello"}, nil
}
type TestWriter struct {
msgs []Message
}
func TestNewQueueSetupReader(t *testing.T) {
t.Parallel()
q := NewQueue(&TestReader{}, nil)
select {
case <-q.Sender():
break
case <-time.After(100 * time.Millisecond):
t.Fatal("Timeout expired")
}
}
func TestNewQueueSetsupWriter(t *testing.T) {
t.Parallel()
writer := &TestWriter{}
q := NewQueue(nil, writer)
q.Receiver() <- "Hello"
q.Receiver() <- "World"
runtime.Gosched()
if count := len(writer.msgs); count != 2 {
t.Errorf("messages written == %d, want 2", count)
}
}
func (self *TestWriter) Write(msgs []Message) error | {
for _, msg := range msgs {
self.msgs = append(self.msgs, msg)
}
return nil
} |
package externalversions
import (
"fmt"
schema "k8s.io/apimachinery/pkg/runtime/schema"
cache "k8s.io/client-go/tools/cache"
v1beta1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1"
)
type GenericInformer interface {
Informer() cache.SharedIndexInformer
Lister() cache.GenericLister
}
type genericInformer struct {
informer cache.SharedIndexInformer
resource schema.GroupResource
}
func (f *genericInformer) Lister() cache.GenericLister {
return cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)
}
func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {
switch resource {
case v1beta1.SchemeGroupVersion.WithResource("apiservices"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Apiregistration().V1beta1().APIServices().Informer()}, nil
}
return nil, fmt.Errorf("no informer found for %v", resource)
}
func (f *genericInformer) Informer() cache.SharedIndexInformer | {
return f.informer
} |
package parse
import (
"strings"
)
func indent(s string, character string, size int) string {
indent := strings.Repeat(character, size)
lines := strings.Split(s, newLine)
for k, v := range lines {
if len(v) > 0 {
lines[k] = indent + v
}
}
return strings.Join(lines, newLine)
}
func EqualSlicesFoldPrefix(a, prefix []string) bool {
l, lprefix := len(a), len(prefix)
switch {
case lprefix == 0:
return true
case l < lprefix:
return false
case l > lprefix:
return EqualSlicesFold(a[:lprefix], prefix)
default:
return EqualSlicesFold(a, prefix)
}
}
func EqualSlicesFoldSuffix(a, suffix []string) bool {
l, lsuffix := len(a), len(suffix)
switch {
case lsuffix == 0:
return true
case l < lsuffix:
return false
case l > lsuffix:
return EqualSlicesFold(a[l-lsuffix:], suffix)
default:
return EqualSlicesFold(a, suffix)
}
}
func EqualSlicesFold(a, b []string) bool {
if len(a) != len(b) {
return false
}
for k := range a {
if !strings.EqualFold(a[k], b[k]) {
return false
}
}
return true
}
func EqualSlicesFoldSome(a []string, b ...[]string) bool | {
if len(a) == 0 && len(b) == 0 {
return true
}
for k := range b {
if EqualSlicesFold(a, b[k]) {
return true
}
}
return false
} |
package main
import (
"fmt"
"os"
"sort"
)
func main() {
in, _ := os.Open("11455.in")
defer in.Close()
out, _ := os.Create("11455.out")
defer out.Close()
var kase int
sides := make([]int, 4)
for fmt.Fscanf(in, "%d", &kase); kase > 0; kase-- {
fmt.Fscanf(in, "%d%d%d%d", &sides[0], &sides[1], &sides[2], &sides[3])
fmt.Fprintln(out, solve(sides))
}
}
func solve(sides []int) string | {
sort.Ints(sides)
if sides[0] == sides[1] && sides[2] == sides[3] {
if sides[1] == sides[2] {
return "square"
}
return "rectangle"
}
if sides[3] > sides[0]+sides[1]+sides[2] {
return "banana"
}
return "quadrangle"
} |
package route
import (
"io"
"net/http"
"regexp"
"strings"
)
var ()
type Route struct {
Path string
System int
S0 NullRoute
S1 StringRoute
S2 ControllerRoute
S3 FilesystemRoute
S4 FunctionRoute
}
func NewRoute(path string, system int) Route {
return Route{path, system, NullRoute{}, StringRoute{}, ControllerRoute{}, FilesystemRoute{}, FunctionRoute{}}
}
func (r *Route) Read(w http.ResponseWriter, req *http.Request) {
result := ""
switch r.System {
case 0:
result = ""
case 1:
result = r.S1.String
case 2:
case 3:
result = r.S3.FileContent
case 4:
result = r.S4.Function()
}
io.Copy(w, strings.NewReader(result))
}
func ValidStringRoute(str string) bool | {
routeStringRegexp := `^\/([a-zA-Z0-9](\/)*)*\s(null|str .*|fs .*)$`
r, _ := regexp.Compile(routeStringRegexp)
if r.MatchString(str) {
return true
}
return false
} |
package project
import (
"testing"
)
func TestTrimSpaceAndNonPrintable_space(t *testing.T) {
t.Parallel()
extraChars := " state \r\t"
want := "state"
got := TrimSpaceAndNonPrintable(extraChars)
if want != got {
t.Fatalf("wrong trim, want: %q got: %q", want, got)
}
}
func TestTrimSpace_unicode(t *testing.T) {
t.Parallel()
extraChars := "state\uFEFF"
want := "state"
got := TrimSpace(extraChars)
if want != got {
t.Fatalf("wrong trim, want: %q got: %q", want, got)
}
}
func TestTrimSpace_space(t *testing.T) {
t.Parallel()
extraChars := " state \r\t"
want := "state"
got := TrimSpace(extraChars)
if want != got {
t.Fatalf("wrong trim, want: %q got: %q", want, got)
}
}
func TestTrimSpaceAndNonPrintable_unicode(t *testing.T) | {
t.Parallel()
extraChars := "state\uFEFF"
want := "state"
got := TrimSpaceAndNonPrintable(extraChars)
if want != got {
t.Fatalf("wrong trim, want: %q got: %q", want, got)
}
} |
package main
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"os/signal"
"strings"
"sync"
"syscall"
)
type threadSafePrintliner struct {
l sync.Mutex
w io.Writer
}
func newThreadSafePrintliner(w io.Writer) *threadSafePrintliner {
return &threadSafePrintliner{w: w}
}
func (p *threadSafePrintliner) println(s string) {
p.l.Lock()
fmt.Fprintln(p.w, s)
p.l.Unlock()
}
func readQuery(r io.Reader) string {
s, _ := ioutil.ReadAll(r)
return strings.TrimSpace(strings.Replace(string(s), "\n", " ", -1))
}
func awaitSignal(cancel context.CancelFunc) {
signals := make(chan os.Signal)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
<-signals
cancel()
}
func trimEmpty(s []string) []string | {
var r = make([]string, 0)
for _, str := range s {
if str != "" {
r = append(r, str)
}
}
return r
} |
package http
import (
"go-common/app/admin/main/tv/model"
bm "go-common/library/net/http/blademaster"
)
func mangoList(c *bm.Context) {
c.JSON(tvSrv.MangoList(c))
}
func mangoAdd(c *bm.Context) {
param := new(struct {
IDs []int64 `form:"rids,split" validate:"required,min=1,dive,gt=0"`
RType int `form:"rtype" validate:"required,min=1,max=2"`
})
if err := c.Bind(param); err != nil {
return
}
c.JSON(tvSrv.MangoAdd(c, param.RType, param.IDs))
}
func mangoEdit(c *bm.Context) {
param := new(model.ReqMangoEdit)
if err := c.Bind(param); err != nil {
return
}
c.JSON(nil, tvSrv.MangoEdit(c, param))
}
func mangoPub(c *bm.Context) {
param := new(struct {
IDs []int64 `form:"ids,split" validate:"required,min=1,dive,gt=0"`
})
if err := c.Bind(param); err != nil {
return
}
c.JSON(nil, tvSrv.MangoPub(c, param.IDs))
}
func mangoDel(c *bm.Context) | {
param := new(struct {
ID int64 `form:"id" validate:"required,min=1,gt=0"`
})
if err := c.Bind(param); err != nil {
return
}
c.JSON(nil, tvSrv.MangoDel(c, param.ID))
} |
package containerregistry
import (
"context"
"github.com/sacloud/libsacloud/v2/helper/service"
"github.com/sacloud/libsacloud/v2/sacloud"
)
func (s *Service) DeleteWithContext(ctx context.Context, req *DeleteRequest) error {
if err := req.Validate(); err != nil {
return err
}
client := sacloud.NewContainerRegistryOp(s.caller)
if err := client.Delete(ctx, req.ID); err != nil {
return service.HandleNotFoundError(err, !req.FailIfNotFound)
}
return nil
}
func (s *Service) Delete(req *DeleteRequest) error | {
return s.DeleteWithContext(context.Background(), req)
} |
package global
import (
"fmt"
)
const (
versionMajor = 0
versionMinor = 0
versionPatch = 8
)
func Version() string | {
return fmt.Sprintf("tgen v%d.%d.%d", versionMajor, versionMinor, versionPatch)
} |
package gofixedfield
import (
"io/ioutil"
"strings"
)
const (
EOLUnix = "\n"
EOLMac = "\r"
EOLDOS = "\r\n"
)
var DecimalComma bool
func RecordsFromFile(filename string, eolstyle string) ([]string, error) | {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return strings.Split(string(data), eolstyle), nil
} |
package heckle
import (
"log"
"strings"
"github.com/ianremmler/bort"
)
var (
retorts = retortMap{}
)
type retortMap map[string]string
func setup() error {
if err := bort.GetConfig(&struct{ Retorts retortMap }{retorts}); err != nil {
return err
}
for watch, retort := range retorts {
if _, err := bort.RegisterMatcher(bort.PrivMsg, watch, responder(retort)); err != nil {
log.Println(err)
}
}
return nil
}
func init() {
bort.RegisterSetup(setup)
}
func responder(retort string) bort.HandleFunc | {
return func(in, out *bort.Message) error {
out.Type = bort.PrivMsg
out.Text = strings.Replace(retort, "%m", in.Match, -1)
return nil
}
} |
package opt
import (
"encoding/json"
"reflect"
)
type DisableTypoToleranceOnAttributesOption struct {
value []string
}
func DisableTypoToleranceOnAttributes(v ...string) *DisableTypoToleranceOnAttributesOption {
return &DisableTypoToleranceOnAttributesOption{v}
}
func (o *DisableTypoToleranceOnAttributesOption) Get() []string {
if o == nil {
return []string{}
}
return o.value
}
func (o DisableTypoToleranceOnAttributesOption) MarshalJSON() ([]byte, error) {
return json.Marshal(o.value)
}
func (o *DisableTypoToleranceOnAttributesOption) Equal(o2 *DisableTypoToleranceOnAttributesOption) bool {
if o == nil {
return o2 == nil || reflect.DeepEqual(o2.value, []string{})
}
if o2 == nil {
return o == nil || reflect.DeepEqual(o.value, []string{})
}
return reflect.DeepEqual(o.value, o2.value)
}
func DisableTypoToleranceOnAttributesEqual(o1, o2 *DisableTypoToleranceOnAttributesOption) bool {
return o1.Equal(o2)
}
func (o *DisableTypoToleranceOnAttributesOption) UnmarshalJSON(data []byte) error | {
if string(data) == "null" {
o.value = []string{}
return nil
}
return json.Unmarshal(data, &o.value)
} |
package internal
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error | {
return errors.New(values...).Path("Transport", "Internet", "Internal")
} |
package contract
import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
)
func sha3(in ...[]byte) []byte {
out := make([]byte, len(in)*32)
for i, input := range in {
copy(out[i*32:i*32+32], common.LeftPadBytes(input, 32))
}
return crypto.Sha3(out)
}
func makeChannelName(from, to common.Address) []byte | {
return sha3(from[:], to[:])
} |
package fritz
import (
"unicode/utf16"
"unicode/utf8"
)
func utf8To16LE(p []byte) []byte {
bs := make([]byte, 0, 2*len(p))
pos := 0
for pos < len(p) {
bytes, size := consumeNextRune(p[pos:])
pos += size
bs = append(bs, bytes...)
}
return bs
}
func consumeNextRune(p []byte) ([]byte, int) | {
r, size := utf8.DecodeRune(p)
if r <= 0xffff {
return []byte{uint8(r), uint8(r >> 8)}, size
}
r1, r2 := utf16.EncodeRune(r)
return []byte{uint8(r1), uint8(r1 >> 8), uint8(r2), uint8(r2 >> 8)}, size
} |
package main
import . "g2d"
var arena = NewArena(Point{480, 360})
var a1 = NewAlien(arena, Point{40, 40})
var a2 = NewAlien(arena, Point{80, 80})
type Alien struct {
arena *Arena
x, y, w, h int
xmin, xmax int
dx, dy int
}
func NewAlien(arena *Arena, pos Point) *Alien {
a := &Alien{arena, pos.X, pos.Y, 20, 20, pos.X, pos.X+150, 5, 5}
arena.Add(a)
return a
}
func (a *Alien) Move() {
if a.xmin <= a.x+a.dx && a.x+a.dx <= a.xmax {
a.x += a.dx
} else {
a.dx = -a.dx
a.y += a.dy
}
}
func (a *Alien) Position() Point {
return Point{a.x, a.y}
}
func (a *Alien) Symbol() Point {
return Point{0, 0}
}
func (a *Alien) Collide(other Actor) {
}
func tick() {
ClearCanvas()
arena.MoveAll()
for _, actor := range arena.Actors() {
FillRect(actor.Position(), actor.Size())
}
}
func main() {
InitCanvas(arena.Size())
MainLoop(tick)
}
func (a *Alien) Size() Point | {
return Point{a.w, a.h}
} |
package internal
import (
"fmt"
"net/http"
"golang.org/x/net/context"
)
type ContextKey string
const userAgent = "gcloud-golang/0.1"
type Transport struct {
Base http.RoundTripper
}
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
req = cloneRequest(req)
ua := req.Header.Get("User-Agent")
if ua == "" {
ua = userAgent
} else {
ua = fmt.Sprintf("%s;%s", ua, userAgent)
}
req.Header.Set("User-Agent", ua)
return t.Base.RoundTrip(req)
}
func ProjID(ctx context.Context) string {
return ctx.Value(ContextKey("base")).(map[string]interface{})["project_id"].(string)
}
func Namespace(ctx context.Context) string {
v := ctx.Value(ContextKey("namespace"))
if v == nil {
return ""
} else {
return v.(string)
}
}
func HttpClient(ctx context.Context) *http.Client {
return ctx.Value(ContextKey("base")).(map[string]interface{})["http_client"].(*http.Client)
}
func cloneRequest(r *http.Request) *http.Request | {
r2 := new(http.Request)
*r2 = *r
r2.Header = make(http.Header)
for k, s := range r.Header {
r2.Header[k] = s
}
return r2
} |
package logging_test
import (
"cloud.google.com/go/logging/apiv2"
"golang.org/x/net/context"
loggingpb "google.golang.org/genproto/googleapis/logging/v2"
)
func ExampleNewConfigClient() {
ctx := context.Background()
c, err := logging.NewConfigClient(ctx)
if err != nil {
}
_ = c
}
func ExampleConfigClient_GetSink() {
ctx := context.Background()
c, err := logging.NewConfigClient(ctx)
if err != nil {
}
req := &loggingpb.GetSinkRequest{
}
resp, err := c.GetSink(ctx, req)
if err != nil {
}
_ = resp
}
func ExampleConfigClient_CreateSink() {
ctx := context.Background()
c, err := logging.NewConfigClient(ctx)
if err != nil {
}
req := &loggingpb.CreateSinkRequest{
}
resp, err := c.CreateSink(ctx, req)
if err != nil {
}
_ = resp
}
func ExampleConfigClient_UpdateSink() {
ctx := context.Background()
c, err := logging.NewConfigClient(ctx)
if err != nil {
}
req := &loggingpb.UpdateSinkRequest{
}
resp, err := c.UpdateSink(ctx, req)
if err != nil {
}
_ = resp
}
func ExampleConfigClient_DeleteSink() {
ctx := context.Background()
c, err := logging.NewConfigClient(ctx)
if err != nil {
}
req := &loggingpb.DeleteSinkRequest{
}
err = c.DeleteSink(ctx, req)
if err != nil {
}
}
func ExampleConfigClient_ListSinks() | {
ctx := context.Background()
c, err := logging.NewConfigClient(ctx)
if err != nil {
}
req := &loggingpb.ListSinksRequest{
}
it := c.ListSinks(ctx, req)
for {
resp, err := it.Next()
if err != nil {
break
}
_ = resp
}
} |
package middleware
import (
"time"
log "github.com/Sirupsen/logrus"
"gopkg.in/macaron.v1"
"github.com/containerops/configure"
)
func logger() macaron.Handler | {
return func(ctx *macaron.Context) {
if configure.GetString("runmode") == "dev" {
log.Info("------------------------------------------------------------------------------")
log.Info(time.Now().String())
}
log.WithFields(log.Fields{
"Method": ctx.Req.Method,
"URL": ctx.Req.RequestURI,
}).Info(ctx.Req.Header)
}
} |
package authorization
import (
"github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest"
)
const (
APIVersion = "2015-01-01"
DefaultBaseURI = "https:management.azure.com"
)
type ManagementClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {
return ManagementClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
}
func New(subscriptionID string) ManagementClient | {
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
} |
package http_handlers
import (
"fmt"
"github.com/go-martini/martini"
"net/http"
)
func GetCaches() func(
martini.Context,
martini.Params,
http.ResponseWriter,
*http.Request,
) {
return HttpHandler(
[]string{
AUTH_REQUIRED,
},
func(h *Http) {
h.SetResponse(
h.session.Caches,
)
},
)
}
func RegisterCache() func(
martini.Context,
martini.Params,
http.ResponseWriter,
*http.Request,
) {
return HttpHandler(
[]string{
AUTH_REQUIRED,
},
func(h *Http) {
h.SetResponseCreatedObject(
h.session.CreateCache(),
)
},
)
}
func GetCache() func(
martini.Context,
martini.Params,
http.ResponseWriter,
*http.Request,
) | {
return HttpHandler(
[]string{
AUTH_REQUIRED,
CACHE_REQUIRED,
},
func(h *Http) {
if c := h.session.GetCache(
h.vars["cache_id"],
); c != nil {
h.SetResponse(
c,
)
} else {
h.AddError(
fmt.Errorf(
`Cache not found`,
),
404,
)
}
},
)
} |
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 DefaultInt(value *int, defaultValue int) *int {
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
} |
package ratelimiter
import "time"
var domainLimitMap = make(map[string]*Limiter)
type Limiter struct {
nextChan chan bool
apiLimit time.Duration
}
func New(domain string, apiLimit time.Duration) *Limiter {
if _, ok := domainLimitMap[domain]; !ok {
domainLimitMap[domain] = &Limiter{
nextChan: make(chan bool),
apiLimit: apiLimit,
}
domainLimitMap[domain].next()
}
return domainLimitMap[domain]
}
func (limiter *Limiter) Wait() {
<-limiter.nextChan
limiter.next()
}
func (limiter *Limiter) next() | {
go func(l *Limiter) {
ticker := time.NewTimer(l.apiLimit)
<-ticker.C
ticker.Stop()
l.nextChan <- true
}(limiter)
} |
package cfsb
import (
"fmt"
"github.com/wayneeseguin/rdpg-agent/log"
"github.com/wayneeseguin/rdpg-agent/rdpg"
)
type PlanDetails struct {
Cost string `json:"cost"`
Bullets []map[string]string `json:"bullets"`
DisplayName string `json:"displayname"`
}
type Plan struct {
Id string `db:"id"`
PlanId string `db:"plan_id" json:"id"`
Name string `db:"name" json:"name"`
Description string `db:"description" json:"description"`
Metadata PlanDetails `json:"metadata"`
MgmtDbUri string `json:""`
}
func FindPlan(planId string) (plan *Plan, err error) | {
r := rdpg.New()
r.OpenDB("rdpg")
plan = &Plan{}
sq := `SELECT id,name,description FROM cfsb.plans WHERE id=$1 LIMIT 1;`
err = r.DB.Get(&plan, sq, planId)
if err != nil {
log.Error(fmt.Sprintf("cfsb.FindPlan(%s) %s", planId, err))
}
r.DB.Close()
return plan, err
} |
package models
import (
"testing"
"github.com/golib/assert"
uuid "github.com/satori/go.uuid"
)
func Test_NewUserModel(t *testing.T) {
assertion := assert.New(t)
var (
username = uuid.NewV4().String()
email = "tes1@test.com"
password = uuid.NewV4().String()
desc = uuid.NewV4().String()
)
user := User.NewUserModel(username, email, password, desc)
assertion.Equal(username, user.Username)
assertion.Equal(email, user.Email)
assertion.Equal(password, user.Password)
assertion.Equal(UserStatusInactive, user.Status)
assertion.Equal(desc, user.Description)
}
func Test_User_FindByEmail(t *testing.T) {
assertion := assert.New(t)
var (
username = uuid.NewV4().String()
email = "test2@test.com"
password = uuid.NewV4().String()
desc = uuid.NewV4().String()
)
user := User.NewUserModel(username, email, password, desc)
err := user.Save()
assertion.Nil(err)
user.Save()
assertion.Nil(err)
userNew, err := User.FindByEmail(email)
assertion.Nil(err)
assertion.Equal(user.Id, userNew.Id)
}
func Test_User_FindByUsername(t *testing.T) | {
assertion := assert.New(t)
var (
username = uuid.NewV4().String()
email = "test3@test.com"
password = uuid.NewV4().String()
desc = uuid.NewV4().String()
)
user := User.NewUserModel(username, email, password, desc)
err := user.Save()
assertion.Nil(err)
userNew, err := User.FindByUsername(username)
assertion.Nil(err)
assertion.Equal(user.Id, userNew.Id)
} |
package openstacktasks
import (
"encoding/json"
"k8s.io/kops/upup/pkg/fi"
)
type realFloatingIP FloatingIP
func (o *FloatingIP) UnmarshalJSON(data []byte) error {
var jsonName string
if err := json.Unmarshal(data, &jsonName); err == nil {
o.Name = &jsonName
return nil
}
var r realFloatingIP
if err := json.Unmarshal(data, &r); err != nil {
return err
}
*o = FloatingIP(r)
return nil
}
var _ fi.HasLifecycle = &FloatingIP{}
func (o *FloatingIP) SetLifecycle(lifecycle fi.Lifecycle) {
o.Lifecycle = &lifecycle
}
var _ fi.HasName = &FloatingIP{}
func (o *FloatingIP) GetName() *string {
return o.Name
}
func (o *FloatingIP) SetName(name string) {
o.Name = &name
}
func (o *FloatingIP) String() string {
return fi.TaskAsString(o)
}
func (o *FloatingIP) GetLifecycle() *fi.Lifecycle | {
return o.Lifecycle
} |
package timeseriesinsights
import (
"github.com/Azure/go-autorest/autorest"
)
const (
DefaultBaseURI = "https:management.azure.com"
)
type BaseClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
func New(subscriptionID string) BaseClient {
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
}
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient | {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
} |
package qr
import (
"github.com/m3o/m3o-go/client"
)
type QrService struct {
client *client.Client
}
func (t *QrService) Generate(request *GenerateRequest) (*GenerateResponse, error) {
rsp := &GenerateResponse{}
return rsp, t.client.Call("qr", "Generate", request, rsp)
}
type GenerateRequest struct {
Size int64 `json:"size,string"`
Text string `json:"text"`
}
type GenerateResponse struct {
Qr string `json:"qr"`
}
func NewQrService(token string) *QrService | {
return &QrService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
} |
package logutils
import (
"github.com/stretchr/testify/mock"
)
type MockLog struct {
mock.Mock
}
func NewMockLog() *MockLog {
return &MockLog{}
}
func (m *MockLog) Fatalf(format string, args ...interface{}) {
mArgs := []interface{}{format}
m.Called(append(mArgs, args...)...)
}
func (m *MockLog) Panicf(format string, args ...interface{}) {
mArgs := []interface{}{format}
m.Called(append(mArgs, args...)...)
}
func (m *MockLog) Errorf(format string, args ...interface{}) {
mArgs := []interface{}{format}
m.Called(append(mArgs, args...)...)
}
func (m *MockLog) Infof(format string, args ...interface{}) {
mArgs := []interface{}{format}
m.Called(append(mArgs, args...)...)
}
func (m *MockLog) Child(name string) Log {
m.Called(name)
return m
}
func (m *MockLog) SetLevel(level LogLevel) {
m.Called(level)
}
func (m *MockLog) Warnf(format string, args ...interface{}) | {
mArgs := []interface{}{format}
m.Called(append(mArgs, args...)...)
} |
package libra
import (
"bytes"
"fmt"
"io"
)
type validator struct {
name string
program
stdin io.Reader
}
func (v validator) Name() string {
return v.name
}
func (v validator) Run() Status {
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
v.program.cmd.Stdin = v.stdin
v.program.cmd.Stdout = stdout
v.program.cmd.Stderr = stderr
res := v.program.Run()
if res.Code != OK {
return Status{
Code: RE,
Msg: fmt.Sprintf("%v", stderr.String()),
}
}
return res
}
type valJob struct {
abstractJob
inputs []Input
}
type Input interface {
Name() string
Reader() io.Reader
}
func ValJob(src Src, inputs []Input) Job {
ret := valJob{}
ret.src = src
ret.inputs = inputs
return ret
}
func (job valJob) Subtasks() []Task | {
ret := make([]Task, len(job.inputs))
for i, v := range job.inputs {
prog, _ := newProgram(job.src.Exec)
ret[i] = validator{name: v.Name(), program: prog, stdin: v.Reader()}
}
return ret
} |
package example
import (
"testing"
"github.com/remogatto/prettytest"
"launchpad.net/gocheck"
)
type testSuite struct {
prettytest.Suite
}
func (t *testSuite) TestTrueIsTrue() {
t.True(true)
}
func (t *testSuite) TestEquality() {
t.Equal("awesome", "awesome")
}
func (t *testSuite) TestNot() {
t.Not(t.Path("foo"))
}
func (t *testSuite) TestGoCheck() {
t.Check("foo", gocheck.Equals, "foo")
}
func (t *testSuite) TestMustFail() {
t.Error("This test must fail.")
t.MustFail()
}
func (t *testSuite) TestInequality() {
t.Equal("awesome", "ugly")
t.MustFail()
}
func TestRunner(t *testing.T) | {
prettytest.Run(
t,
new(testSuite),
)
} |
package config
import (
"encoding/xml"
)
type defXMLReader struct {
opts ReaderOptions
}
func NewXMLReader(opts ...ReaderOptionFunc) Reader {
r := &defXMLReader{}
for _, o := range opts {
o(&r.opts)
}
return r
}
func (p *defXMLReader) Read(model interface{}) error {
data, err := ReadXMLFile(p.opts.filename)
if err != nil {
return err
}
return ParseXMLConfig(data, model)
}
func (*defXMLReader) ParseData(data []byte, model interface{}) error {
return ParseXMLConfig(data, model)
}
func ReadXMLFile(name string) ([]byte, error) {
data, _, err := filesRepo.Read(name)
if err != nil {
return nil, err
}
return data, nil
}
func ParseXMLConfig(data []byte, model interface{}) error {
return xml.Unmarshal(data, model)
}
func (*defXMLReader) Dump(v interface{}) ([]byte, error) | {
return xml.Marshal(v)
} |
package worker
import (
"github.com/stitchfix/flotilla-os/config"
"os"
"testing"
"time"
)
func TestGetPollInterval(t *testing.T) | {
conf, _ := config.NewConfig(nil)
expected := time.Duration(500) * time.Millisecond
os.Setenv("WORKER_RETRY_INTERVAL", "500ms")
interval, err := GetPollInterval("retry", conf)
if err != nil {
t.Errorf(err.Error())
}
if interval != expected {
t.Errorf("Expected interval: [%v] but was [%v]", expected, interval)
}
} |
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) 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
}
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
} |
package fgae
import(
"golang.org/x/net/context"
"github.com/skypies/util/gcp/ds"
fdb "github.com/skypies/flightdb"
)
type FlightIterator ds.Iterator
func NewFlightIterator(ctx context.Context, p ds.DatastoreProvider, fq *FQuery) *FlightIterator {
it := ds.NewIterator(ctx, p, (*ds.Query)(fq), fdb.IndexedFlightBlob{})
return (*FlightIterator)(it)
}
func (fi *FlightIterator)Err() error {
it := (*ds.Iterator)(fi)
return it.Err()
}
func (fi *FlightIterator)Flight() *fdb.Flight {
blob := fdb.IndexedFlightBlob{}
it := (*ds.Iterator)(fi)
keyer := it.Val(&blob)
f, err := blob.ToFlight(keyer.Encode())
if err != nil {
it.SetErr(err)
return nil
}
return f
}
func (fi *FlightIterator)Iterate(ctx context.Context) bool | {
it := (*ds.Iterator)(fi)
return it.Iterate(ctx)
} |
package check
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCompare(t *testing.T) {
assert := assert.New(t)
set1 := make(stringSet)
set1.add("bar")
set1.add("foo")
set2 := make(stringSet)
set2.add("foo")
set2.add("bar")
set3 := make(stringSet)
set3.add("foo")
set3.add("baz")
assert.Equal(set1, set2)
assert.Equal(set2, set1)
assert.NotEqual(set1, set3)
}
func TestString(t *testing.T) | {
assert := assert.New(t)
set := make(stringSet)
set.add("bar")
set.add("xx")
set.add("foo")
assert.Equal("bar, foo, xx", set.String())
} |
package gocleanup
import (
"os"
"os/signal"
"syscall"
)
var cleanupFuncs []func()
var capturingSignals bool
func Register(f func()) {
cleanupFuncs = append(cleanupFuncs, f)
if !capturingSignals {
capturingSignals = true
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM)
<-c
Exit(1)
}()
}
}
func Exit(status int) {
Cleanup()
os.Exit(status)
}
func Cleanup() | {
for _, f := range cleanupFuncs {
f()
}
cleanupFuncs = []func(){}
} |
package goque
import (
"bytes"
"encoding/binary"
"encoding/gob"
)
type Item struct {
ID uint64
Key []byte
Value []byte
}
func (i *Item) ToString() string {
return string(i.Value)
}
type PriorityItem struct {
ID uint64
Priority uint8
Key []byte
Value []byte
}
func (pi *PriorityItem) ToString() string {
return string(pi.Value)
}
func (pi *PriorityItem) ToObject(value interface{}) error {
buffer := bytes.NewBuffer(pi.Value)
dec := gob.NewDecoder(buffer)
return dec.Decode(value)
}
func idToKey(id uint64) []byte {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, id)
return key
}
func keyToID(key []byte) uint64 {
return binary.BigEndian.Uint64(key)
}
func (i *Item) ToObject(value interface{}) error | {
buffer := bytes.NewBuffer(i.Value)
dec := gob.NewDecoder(buffer)
return dec.Decode(value)
} |
package token_test
import (
"testing"
"github.com/hyperledger/fabric/core/handlers/validation/token"
"github.com/stretchr/testify/assert"
)
func TestValidation_Validate(t *testing.T) {
factory := &token.ValidationFactory{}
plugin := factory.New()
err := plugin.Init()
assert.NoError(t, err)
err = plugin.Validate(nil, "", 0, 0, nil)
assert.NoError(t, err)
}
func TestValidationFactory_New(t *testing.T) | {
factory := &token.ValidationFactory{}
plugin := factory.New()
assert.NotNil(t, plugin)
} |
package client
import (
"fmt"
"strings"
"golang.org/x/net/context"
Cli "github.com/docker/docker/cli"
flag "github.com/docker/docker/pkg/mflag"
)
func (cli *DockerCli) CmdWait(args ...string) error | {
cmd := Cli.Subcmd("wait", []string{"CONTAINER [CONTAINER...]"}, Cli.DockerCommands["wait"].Description, true)
cmd.Require(flag.Min, 1)
cmd.ParseFlags(args, true)
var errs []string
for _, name := range cmd.Args() {
status, err := cli.client.ContainerWait(context.Background(), name)
if err != nil {
errs = append(errs, err.Error())
} else {
fmt.Fprintf(cli.out, "%d\n", status)
}
}
if len(errs) > 0 {
return fmt.Errorf("%s", strings.Join(errs, "\n"))
}
return nil
} |
package window_test
import (
"fmt"
"time"
"github.com/kurin/blazer/x/window"
)
type Accumulator struct {
w *window.Window
}
func (a Accumulator) Add(s string) {
a.w.Insert([]string{s})
}
func (a Accumulator) All() []string {
v := a.w.Reduce()
return v.([]string)
}
func NewAccum(size time.Duration) Accumulator {
r := func(i, j interface{}) interface{} {
a, ok := i.([]string)
if !ok {
a = nil
}
b, ok := j.([]string)
if !ok {
b = nil
}
for _, s := range b {
a = append(a, s)
}
return a
}
return Accumulator{w: window.New(size, time.Second, r)}
}
func Example_accumulator() | {
a := NewAccum(time.Minute)
a.Add("this")
a.Add("is")
a.Add("that")
fmt.Printf("total: %v\n", a.All())
} |
package utils
import (
"golang.org/x/crypto/ssh"
)
type SshClient interface {
Close() error
ExecCommand(command string) (string, error)
}
type awsSshClient struct {
client *ssh.Client
}
func GetSshClient(username string, privateKey []byte, ip string) (*awsSshClient, error) {
signer, err := ssh.ParsePrivateKey(privateKey)
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
}
client, err := ssh.Dial("tcp", ip+":22", config)
return &awsSshClient{client: client}, err
}
func (sshClient *awsSshClient) Close() error {
return sshClient.client.Close()
}
func (sshClient *awsSshClient) ExecCommand(command string) (string, error) | {
session, err := sshClient.client.NewSession()
if err != nil {
}
defer session.Close()
output, err := session.Output(command)
return string(output), err
} |
package result
type Classic struct {
id int
fitness float64
err error
stop bool
}
func (r Classic) ID() int { return r.id }
func (r Classic) Fitness() float64 { return r.fitness }
func (r Classic) Err() error { return r.err }
func (r Classic) Stop() bool { return r.stop }
func New(id int, fitness float64, err error, stop bool) Classic | {
return Classic{id, fitness, err, stop}
} |
package endpoints
import (
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/shared"
)
func (e *Endpoints) Up(config *Config) error {
return e.up(config)
}
func (e *Endpoints) DevLxdSocketPath() string {
e.mu.RLock()
defer e.mu.RUnlock()
listener := e.listeners[devlxd]
return listener.Addr().String()
}
func (e *Endpoints) LocalSocketPath() string {
e.mu.RLock()
defer e.mu.RUnlock()
listener := e.listeners[local]
return listener.Addr().String()
}
func (e *Endpoints) NetworkAddressAndCert() (string, *shared.CertInfo) {
return e.NetworkAddress(), e.cert
}
func (e *Endpoints) SystemdListenFDsStart(start int) {
e.mu.Lock()
defer e.mu.Unlock()
e.systemdListenFDsStart = start
}
func Unstarted() *Endpoints | {
return &Endpoints{
systemdListenFDsStart: util.SystemdListenFDsStart,
}
} |
package rule
import (
"go/ast"
"github.com/mgechev/revive/lint"
)
type NestedStructs struct{}
func (r *NestedStructs) Name() string {
return "nested-structs"
}
type lintNestedStructs struct {
fileAST *ast.File
onFailure func(lint.Failure)
}
func (l *lintNestedStructs) Visit(n ast.Node) ast.Visitor {
switch v := n.(type) {
case *ast.FuncDecl:
if v.Body != nil {
ast.Walk(l, v.Body)
}
return nil
case *ast.Field:
if _, ok := v.Type.(*ast.StructType); ok {
l.onFailure(lint.Failure{
Failure: "no nested structs are allowed",
Category: "style",
Node: v,
Confidence: 1,
})
break
}
}
return l
}
func (r *NestedStructs) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure | {
var failures []lint.Failure
if len(arguments) > 0 {
panic(r.Name() + " doesn't take any arguments")
}
walker := &lintNestedStructs{
fileAST: file.AST,
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
}
ast.Walk(walker, file.AST)
return failures
} |
package clock
import "time"
var Work Clock
func init() {
Work = New()
}
func Now() time.Time {
return Work.Now()
}
func Since(t time.Time) time.Duration {
return Work.Now().Sub(t)
}
func After(d time.Duration) <-chan time.Time {
return Work.After(d)
}
func Tick(d time.Duration) <-chan time.Time {
return Work.Tick(d)
}
func Ticker(d time.Duration) *time.Ticker {
return Work.Ticker(d)
}
type Clock interface {
Now() time.Time
Sleep(d time.Duration)
After(d time.Duration) <-chan time.Time
Tick(d time.Duration) <-chan time.Time
Ticker(d time.Duration) *time.Ticker
}
type Mock interface {
Clock
Set(t time.Time) Mock
Add(d time.Duration) Mock
Freeze() Mock
IsFrozen() bool
Unfreeze() Mock
Close()
}
func Sleep(d time.Duration) | {
Work.Sleep(d)
} |
package main
import "fmt"
const (
a = iota
b
c
d
e
)
var x = []int{1, 2, 3}
func f(x int, len *byte) {
*len = byte(x)
}
func whatis1(x interface{}) string {
xx := x
switch xx.(type) {
default:
return fmt.Sprint("default ", xx)
case int, int8, int16, int32:
return fmt.Sprint("signed ", xx)
case int64:
return fmt.Sprint("signed64 ", xx.(int64))
case uint, uint8, uint16, uint32:
return fmt.Sprint("unsigned ", xx)
case uint64:
return fmt.Sprint("unsigned64 ", xx.(uint64))
case nil:
return fmt.Sprint("nil ", xx)
}
panic("not reached")
}
func check(x interface{}, s string) {
w := whatis(x)
if w != s {
fmt.Println("whatis", x, "=>", w, "!=", s)
panic("fail")
}
w = whatis1(x)
if w != s {
fmt.Println("whatis1", x, "=>", w, "!=", s)
panic("fail")
}
}
func main() {
check(1, "signed 1")
check(uint(1), "unsigned 1")
check(int64(1), "signed64 1")
check(uint64(1), "unsigned64 1")
check(1.5, "default 1.5")
check(nil, "nil <nil>")
}
func whatis(x interface{}) string | {
switch xx := x.(type) {
default:
return fmt.Sprint("default ", xx)
case int, int8, int16, int32:
return fmt.Sprint("signed ", xx)
case int64:
return fmt.Sprint("signed64 ", int64(xx))
case uint, uint8, uint16, uint32:
return fmt.Sprint("unsigned ", xx)
case uint64:
return fmt.Sprint("unsigned64 ", uint64(xx))
case nil:
return fmt.Sprint("nil ", xx)
}
panic("not reached")
} |
package models
import (
"github.com/go-swagger/go-swagger/errors"
"github.com/go-swagger/go-swagger/strfmt"
"github.com/go-swagger/go-swagger/swag"
)
type NotificationPageableResult struct {
Content []*Notification `json:"content,omitempty"`
First bool `json:"first,omitempty"`
Last bool `json:"last,omitempty"`
Number int32 `json:"number,omitempty"`
NumberOfElements int32 `json:"numberOfElements,omitempty"`
ServerTime int64 `json:"serverTime,omitempty"`
Size int32 `json:"size,omitempty"`
TotalElements int32 `json:"totalElements,omitempty"`
TotalPages int32 `json:"totalPages,omitempty"`
}
func (m *NotificationPageableResult) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateContent(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *NotificationPageableResult) validateContent(formats strfmt.Registry) error | {
if swag.IsZero(m.Content) {
return nil
}
for i := 0; i < len(m.Content); i++ {
if m.Content[i] != nil {
if err := m.Content[i].Validate(formats); err != nil {
return err
}
}
}
return nil
} |
package fileinterface
import (
"testing"
"errors"
)
func TestDelete(t *testing.T) {
err := Delete("dummyfile")
if err != nil {
t.Error(err)
}
}
func TestOpen(t *testing.T) {
if f, err := Open("sample.database"); err != nil {
t.Error(err)
} else if err = Close(f); err != nil {
t.Error(err)
}
}
func TestRead(t *testing.T) {
var block *Block
if f, err := Open("sample.database"); err != nil {
t.Error(err)
} else if block, err = Read(f, 5); err != nil {
t.Error(err)
} else if err = Close(f); err != nil {
t.Error(err)
}
for i:=0; i<Blocksize; i++ {
if block[i] != byte(i & 0xFF) {
t.Error(errors.New("block has unexpected value"))
break
}
}
}
func TestLength(t *testing.T) {
}
func TestWrite(t *testing.T) {
var block Block
for i:=0; i<Blocksize; i++ {
block[i]= byte(i & 0xFF)
}
if f, err := Open("sample.database"); err != nil {
t.Error(err)
} else if err := Write(f, 5, &block); err != nil {
t.Error(err)
} else if err = Close(f); err != nil {
t.Error(err)
}
}
func TestLS(t *testing.T) {
}
func TestCreate(t *testing.T) | {
var f FID
var err error
if f, err = Create("dummyfile"); err != nil {
t.Error(err)
} else {
if err = Close(f); err != nil {
t.Error(err)
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.