input
stringlengths 24
2.11k
| output
stringlengths 7
948
|
---|---|
package main
import (
"fmt"
"github.com/devfeel/dotweb"
"github.com/devfeel/dotweb/cache"
"github.com/devfeel/dotweb/framework/file"
"strconv"
)
func main() {
app := dotweb.New()
app.SetLogPath(file.GetCurrentDirectory())
InitRoute(app.HttpServer)
app.SetCache(cache.NewRuntimeCache())
err := app.Cache().Set("g", "gv", 20)
if err != nil {
fmt.Println("Cache Set ", err)
}
port := 8080
fmt.Println("dotweb.StartServer => " + strconv.Itoa(port))
err = app.StartServer(port)
fmt.Println("dotweb.StartServer error => ", err)
}
type UserInfo struct {
UserName string
Sex int
}
func One(ctx dotweb.Context) error {
g, err := ctx.Cache().GetString("g")
if err != nil {
g = err.Error()
}
_, err = ctx.Cache().Incr("count")
return ctx.WriteString("One [" + g + "] " + fmt.Sprint(err))
}
func InitRoute(server *dotweb.HttpServer) {
server.Router().GET("/1", One)
server.Router().GET("/2", Two)
}
func Two(ctx dotweb.Context) error | {
g, err := ctx.Cache().GetString("g")
if err != nil {
g = err.Error()
}
_, err = ctx.Cache().Incr("count")
c, _ := ctx.Cache().GetString("count")
return ctx.WriteString("Two [" + g + "] [" + c + "] " + fmt.Sprint(err))
} |
package wire_test
import (
"bytes"
"io"
)
type fixedWriter struct {
b []byte
pos int
}
func (w *fixedWriter) Write(p []byte) (n int, err error) {
lenp := len(p)
if w.pos+lenp > cap(w.b) {
return 0, io.ErrShortWrite
}
n = lenp
w.pos += copy(w.b[w.pos:], p)
return
}
func (w *fixedWriter) Bytes() []byte {
return w.b
}
func newFixedWriter(max int) io.Writer {
b := make([]byte, max, max)
fw := fixedWriter{b, 0}
return &fw
}
type fixedReader struct {
buf []byte
pos int
iobuf *bytes.Buffer
}
func (fr *fixedReader) Read(p []byte) (n int, err error) {
n, err = fr.iobuf.Read(p)
fr.pos += n
return
}
func newFixedReader(max int, buf []byte) io.Reader | {
b := make([]byte, max, max)
if buf != nil {
copy(b[:], buf)
}
iobuf := bytes.NewBuffer(b)
fr := fixedReader{b, 0, iobuf}
return &fr
} |
package main
import (
"io/ioutil"
"log"
"net/http"
"os"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
auditinstall "k8s.io/apiserver/pkg/apis/audit/install"
auditv1 "k8s.io/apiserver/pkg/apis/audit/v1"
"k8s.io/apiserver/pkg/audit"
)
var (
encoder runtime.Encoder
decoder runtime.Decoder
)
func main() {
scheme := runtime.NewScheme()
auditinstall.Install(scheme)
serializer := json.NewSerializer(json.DefaultMetaFactory, scheme, scheme, false)
encoder = audit.Codecs.EncoderForVersion(serializer, auditv1.SchemeGroupVersion)
decoder = audit.Codecs.UniversalDecoder(auditv1.SchemeGroupVersion)
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handler(w http.ResponseWriter, req *http.Request) | {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Printf("could not read request body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
el := &auditv1.EventList{}
if err := runtime.DecodeInto(decoder, body, el); err != nil {
log.Printf("failed decoding buf: %b, apiVersion: %s", body, auditv1.SchemeGroupVersion)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer req.Body.Close()
for _, event := range el.Items {
err := encoder.Encode(&event, os.Stdout)
if err != nil {
log.Printf("could not encode audit event: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusOK)
} |
package database
import "database/sql"
var db *sql.DB
func OpenDB() {
openSQLite()
}
func Query(s string, args ...interface{}) (*sql.Rows, error) {
rows, err := db.Query(s, args...)
if err != nil {
return nil, err
}
return rows, nil
}
func Exec(s string, args ...interface{}) (sql.Result, error) {
res, err := db.Exec(s, args...)
if err != nil {
return nil, err
}
return res, nil
}
func openSQLite() | {
var err error
db, err = sql.Open("sqlite3", "adnalerts.db?loc.auto")
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
panic(err)
}
} |
package main
import (
"bufio"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"time"
)
func read2(path string) string {
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
r := bufio.NewReader(fi)
chunks := make([]byte, 1024, 1024)
buf := make([]byte, 1024)
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if 0 == n {
break
}
chunks = append(chunks, buf[:n]...)
}
return string(chunks)
}
func read3(path string) string {
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
fd, err := ioutil.ReadAll(fi)
return string(fd)
}
func main() {
flag.Parse()
file := flag.Arg(0)
f, err := ioutil.ReadFile(file)
if err != nil {
fmt.Printf("%s\n", err)
panic(err)
}
fmt.Println(string(f))
start := time.Now()
read3(file)
t1 := time.Now()
fmt.Printf("Cost time %v\n", t1.Sub(start))
read1(file)
t2 := time.Now()
fmt.Printf("Cost time %v\n", t2.Sub(t1))
read2(file)
t3 := time.Now()
fmt.Printf("Cost time %v\n", t3.Sub(t2))
}
func read1(path string) string | {
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
chunks := make([]byte, 1024, 1024)
buf := make([]byte, 1024)
for {
n, err := fi.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if 0 == n {
break
}
chunks = append(chunks, buf[:n]...)
}
return string(chunks)
} |
package segment
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/checkr/flagr/swagger_gen/models"
)
const DeleteSegmentOKCode int = 200
type DeleteSegmentOK struct {
}
func NewDeleteSegmentOK() *DeleteSegmentOK {
return &DeleteSegmentOK{}
}
func (o *DeleteSegmentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType)
rw.WriteHeader(200)
}
type DeleteSegmentDefault struct {
_statusCode int
Payload *models.Error `json:"body,omitempty"`
}
func NewDeleteSegmentDefault(code int) *DeleteSegmentDefault {
if code <= 0 {
code = 500
}
return &DeleteSegmentDefault{
_statusCode: code,
}
}
func (o *DeleteSegmentDefault) WithStatusCode(code int) *DeleteSegmentDefault {
o._statusCode = code
return o
}
func (o *DeleteSegmentDefault) SetStatusCode(code int) {
o._statusCode = code
}
func (o *DeleteSegmentDefault) SetPayload(payload *models.Error) {
o.Payload = payload
}
func (o *DeleteSegmentDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err)
}
}
}
func (o *DeleteSegmentDefault) WithPayload(payload *models.Error) *DeleteSegmentDefault | {
o.Payload = payload
return o
} |
package dns
import (
"strings"
)
const etcHostsFile = "C:/Windows/System32/drivers/etc/hosts"
func getDNSServerList() []string {
output := runCommand("powershell", "-Command", "(Get-DnsClientServerAddress).ServerAddresses")
if len(output) > 0 {
return strings.Split(output, "\r\n")
}
panic("Could not find DNS Server list!")
}
func getDNSSuffixList() []string | {
output := runCommand("powershell", "-Command", "(Get-DnsClient)[0].SuffixSearchList")
if len(output) > 0 {
return strings.Split(output, "\r\n")
}
panic("Could not find DNS search list!")
} |
package iiif
import (
"strconv"
)
type Rotation struct {
Mirror bool
Degrees float64
}
func StringToRotation(p string) Rotation {
r := Rotation{}
if p[0:1] == "!" {
r.Mirror = true
p = p[1:]
}
r.Degrees, _ = strconv.ParseFloat(p, 64)
if r.Degrees == 360 {
r.Degrees = 0
}
return r
}
func (r Rotation) Valid() bool | {
return r.Degrees >= 0 && r.Degrees < 360
} |
package math
func Ceil(x float64) float64 { return -Floor(-x) }
func Trunc(x float64) float64 {
if x == 0 || x != x || x > MaxFloat64 || x < -MaxFloat64 {
return x
}
d, _ := Modf(x)
return d
}
func Floor(x float64) float64 | {
if x == 0 || x != x || x > MaxFloat64 || x < -MaxFloat64 {
return x
}
if x < 0 {
d, fract := Modf(-x)
if fract != 0.0 {
d = d + 1
}
return -d
}
d, _ := Modf(x)
return d
} |
package ast
import (
"fmt"
"github.com/rhysd/gocaml/token"
"github.com/rhysd/locerr"
)
type printPath struct {
total int
}
func (v *printPath) VisitTopdown(e Expr) Visitor {
fmt.Printf("\n -> %s (topdown)", e.Name())
return v
}
func (v *printPath) VisitBottomup(e Expr) {
fmt.Printf("\n -> %s (bottomup)", e.Name())
}
func Example() | {
src := locerr.NewDummySource("")
rootOfAST := &Let{
LetToken: &token.Token{File: src},
Symbol: NewSymbol("test"),
Bound: &Int{
Token: &token.Token{File: src},
Value: 42,
},
Body: &Add{
Left: &VarRef{
Token: &token.Token{File: src},
Symbol: NewSymbol("test"),
},
Right: &Float{
Token: &token.Token{File: src},
Value: 3.14,
},
},
}
ast := &AST{Root: rootOfAST}
v := &printPath{0}
fmt.Println("ROOT")
Visit(v, ast.Root)
Println(ast)
} |
package fs
import (
"crypto/md5"
"fmt"
"path/filepath"
"runtime"
"strings"
)
const (
WindowsTempPrefix = "~syncthing~"
UnixTempPrefix = ".syncthing."
)
var TempPrefix string
const maxFilenameLength = 160 - len(UnixTempPrefix) - len(".tmp")
func IsTemporary(name string) bool {
name = filepath.Base(name)
if strings.HasPrefix(name, WindowsTempPrefix) ||
strings.HasPrefix(name, UnixTempPrefix) {
return true
}
return false
}
func TempName(name string) string {
tdir := filepath.Dir(name)
tbase := filepath.Base(name)
if len(tbase) > maxFilenameLength {
hash := md5.New()
hash.Write([]byte(name))
tbase = fmt.Sprintf("%x", hash.Sum(nil))
}
tname := fmt.Sprintf("%s%s.tmp", TempPrefix, tbase)
return filepath.Join(tdir, tname)
}
func init() | {
if runtime.GOOS == "windows" {
TempPrefix = WindowsTempPrefix
} else {
TempPrefix = UnixTempPrefix
}
} |
package writer
import (
"bytes"
"encoding/binary"
"hash/crc32"
"github.com/rameshvarun/ups/common"
)
func WriteVariableLengthInteger(value uint64) []byte {
var data []byte
x := value & 0x7f
value >>= 7
for value != 0 {
data = append(data, byte(x))
value--
x = value & 0x7f
value >>= 7
}
data = append(data, byte(0x80|x))
return data
}
func WriteUPS(data *common.PatchData) []byte | {
var buffer bytes.Buffer
buffer.Write(common.Signature)
buffer.Write(WriteVariableLengthInteger(data.InputFileSize))
buffer.Write(WriteVariableLengthInteger(data.OutputFileSize))
for _, block := range data.PatchBlocks {
buffer.Write(WriteVariableLengthInteger(block.RelativeOffset))
buffer.Write(block.Data)
buffer.WriteByte(0)
}
binary.Write(&buffer, binary.LittleEndian, data.InputChecksum)
binary.Write(&buffer, binary.LittleEndian, data.OutputChecksum)
checksum := crc32.ChecksumIEEE(buffer.Bytes())
binary.Write(&buffer, binary.LittleEndian, checksum)
return buffer.Bytes()
} |
package glw
import "golang.org/x/mobile/gl"
type A2fv gl.Attrib
func (a A2fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }
func (a A2fv) Pointer() {
a.Enable()
ctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)
}
type A3fv gl.Attrib
func (a A3fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }
func (a A3fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }
func (a A3fv) Pointer() {
a.Enable()
ctx.VertexAttribPointer(gl.Attrib(a), 3, gl.FLOAT, false, 0, 0)
}
type A4fv gl.Attrib
func (a A4fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }
func (a A4fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }
func (a A4fv) Pointer() {
a.Enable()
ctx.VertexAttribPointer(gl.Attrib(a), 4, gl.FLOAT, false, 0, 0)
}
func (a A2fv) Enable() | { ctx.EnableVertexAttribArray(gl.Attrib(a)) } |
package dummy
import (
"log"
"sync"
"time"
"github.com/svenwiltink/go-musicbot/pkg/music"
)
type SongPlayer struct {
lock sync.Mutex
}
func (player *SongPlayer) CanPlay(song music.Song) bool {
return true
}
func (player *SongPlayer) Wait() {
player.lock.Lock()
defer player.lock.Unlock()
time.Sleep(time.Second * 10)
}
func (player *SongPlayer) Play() error {
player.lock.Lock()
defer player.lock.Unlock()
log.Printf("resuming playback")
return nil
}
func (player *SongPlayer) Pause() error {
player.lock.Lock()
defer player.lock.Unlock()
log.Printf("pausing playback")
return nil
}
func NewSongPlayer() *SongPlayer {
return &SongPlayer{}
}
func (player *SongPlayer) PlaySong(song music.Song) error | {
player.lock.Lock()
defer player.lock.Unlock()
log.Printf("starting playback of %s", song.Name)
return nil
} |
package role
import (
"github.com/watermint/toolbox/domain/dropbox/api/dbx_auth"
"github.com/watermint/toolbox/domain/dropbox/api/dbx_conn"
"github.com/watermint/toolbox/domain/dropbox/model/mo_user"
"github.com/watermint/toolbox/domain/dropbox/service/sv_adminrole"
"github.com/watermint/toolbox/domain/dropbox/service/sv_member"
"github.com/watermint/toolbox/infra/control/app_control"
"github.com/watermint/toolbox/infra/recipe/rc_exec"
"github.com/watermint/toolbox/infra/recipe/rc_recipe"
)
type Clear struct {
Peer dbx_conn.ConnScopedTeam
Email string
}
func (z *Clear) Preset() {
z.Peer.SetScopes(
dbx_auth.ScopeMembersRead,
dbx_auth.ScopeMembersWrite,
)
}
func (z *Clear) Test(c app_control.Control) error {
return rc_exec.ExecMock(c, &Clear{}, func(r rc_recipe.Recipe) {
m := r.(*Clear)
m.Email = "jo@example.com"
})
}
func (z *Clear) Exec(c app_control.Control) error | {
member, err := sv_member.New(z.Peer.Context()).ResolveByEmail(z.Email)
if err != nil {
return err
}
_, err = sv_adminrole.New(z.Peer.Context()).UpdateRole(mo_user.NewUserSelectorByTeamMemberId(member.TeamMemberId), []string{})
if err != nil {
return err
}
return nil
} |
package testhelpers
import "github.com/go-kit/kit/metrics"
type CollectingCounter struct {
CounterValue float64
LastLabelValues []string
}
func (c *CollectingCounter) With(labelValues ...string) metrics.Counter {
c.LastLabelValues = labelValues
return c
}
func (c *CollectingCounter) Add(delta float64) {
c.CounterValue += delta
}
type CollectingGauge struct {
GaugeValue float64
LastLabelValues []string
}
func (g *CollectingGauge) With(labelValues ...string) metrics.Gauge {
g.LastLabelValues = labelValues
return g
}
func (g *CollectingGauge) Set(value float64) {
g.GaugeValue = value
}
func (g *CollectingGauge) Add(delta float64) {
g.GaugeValue = delta
}
type CollectingHealthCheckMetrics struct {
Gauge *CollectingGauge
}
func NewCollectingHealthCheckMetrics() *CollectingHealthCheckMetrics {
return &CollectingHealthCheckMetrics{&CollectingGauge{}}
}
func (m *CollectingHealthCheckMetrics) BackendServerUpGauge() metrics.Gauge | {
return m.Gauge
} |
package xenserver
import (
"time"
"github.com/hashicorp/terraform/helper/schema"
)
func dataSourceXenServerPifs() *schema.Resource {
return &schema.Resource{
Read: dataSourceXenServerPifsRead,
Schema: map[string]*schema.Schema{
"uuids": &schema.Schema{
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func dataSourceXenServerPifsRead(d *schema.ResourceData, meta interface{}) error | {
c := meta.(*Connection)
pifUUIDs := make([]string, 0)
if pifs, err := c.client.PIF.GetAllRecords(c.session); err == nil {
for _, pif := range pifs {
pifUUIDs = append(pifUUIDs, pif.UUID)
}
}
d.SetId(time.Now().UTC().String())
d.Set("uuids", pifUUIDs)
return nil
} |
package mediaservices
import (
"github.com/Azure/go-autorest/autorest"
)
const (
APIVersion = "2015-10-01"
DefaultBaseURI = "https:management.azure.com"
)
type ManagementClient struct {
autorest.Client
BaseURI string
APIVersion string
SubscriptionID string
}
func New(subscriptionID string) ManagementClient {
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
}
func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient | {
return ManagementClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
APIVersion: APIVersion,
SubscriptionID: subscriptionID,
}
} |
package proxy
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"github.com/fsouza/go-dockerclient"
. "github.com/weaveworks/weave/common"
)
type createExecInterceptor struct {
client *docker.Client
withIPAM bool
}
func (i *createExecInterceptor) InterceptRequest(r *http.Request) error {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
r.Body.Close()
options := docker.CreateExecOptions{}
if err := json.Unmarshal(body, &options); err != nil {
return err
}
container, err := inspectContainerInPath(i.client, r.URL.Path)
if err != nil {
return err
}
if cidrs, ok := weaveCIDRsFromConfig(container.Config); ok || i.withIPAM {
Info.Printf("Exec in container %s with WEAVE_CIDR \"%s\"", container.ID, strings.Join(cidrs, " "))
cmd := append(weaveWaitEntrypoint, "-s")
options.Cmd = append(cmd, options.Cmd...)
}
if err := marshalRequestBody(r, options); err != nil {
return err
}
return nil
}
func (i *createExecInterceptor) InterceptResponse(r *http.Response) error | {
return nil
} |
package v1beta1
import (
v1beta1 "k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
type PodSecurityPolicyLister interface {
List(selector labels.Selector) (ret []*v1beta1.PodSecurityPolicy, err error)
Get(name string) (*v1beta1.PodSecurityPolicy, error)
PodSecurityPolicyListerExpansion
}
type podSecurityPolicyLister struct {
indexer cache.Indexer
}
func (s *podSecurityPolicyLister) List(selector labels.Selector) (ret []*v1beta1.PodSecurityPolicy, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1beta1.PodSecurityPolicy))
})
return ret, err
}
func (s *podSecurityPolicyLister) Get(name string) (*v1beta1.PodSecurityPolicy, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1beta1.Resource("podsecuritypolicy"), name)
}
return obj.(*v1beta1.PodSecurityPolicy), nil
}
func NewPodSecurityPolicyLister(indexer cache.Indexer) PodSecurityPolicyLister | {
return &podSecurityPolicyLister{indexer: indexer}
} |
package ovnmodel
import (
"encoding/json"
"fmt"
"github.com/skydive-project/skydive/graffiti/getter"
"github.com/skydive-project/skydive/graffiti/graph"
)
type LoadBalancerHealthCheck struct {
UUID string `ovsdb:"_uuid" json:",omitempty" `
ExternalIDs map[string]string `ovsdb:"external_ids" json:",omitempty" `
Options map[string]string `ovsdb:"options" json:",omitempty" `
Vip string `ovsdb:"vip" json:",omitempty" `
ExternalIDsMeta graph.Metadata `json:",omitempty" field:"Metadata"`
OptionsMeta graph.Metadata `json:",omitempty" field:"Metadata"`
}
func (t *LoadBalancerHealthCheck) Metadata() graph.Metadata {
t.ExternalIDsMeta = graph.NormalizeValue(t.ExternalIDs).(map[string]interface{})
t.OptionsMeta = graph.NormalizeValue(t.Options).(map[string]interface{})
return graph.Metadata{
"Type": "LoadBalancerHealthCheck",
"Manager": "ovn",
"UUID": t.GetUUID(),
"Name": t.GetName(),
"OVN": t,
}
}
func (t *LoadBalancerHealthCheck) GetName() string {
if name := t.UUID; name != "" {
return name
}
return t.GetUUID()
}
func LoadBalancerHealthCheckDecoder(raw json.RawMessage) (getter.Getter, error) {
var t LoadBalancerHealthCheck
if err := json.Unmarshal(raw, &t); err != nil {
return nil, fmt.Errorf("unable to unmarshal LoadBalancerHealthCheck metadata %s: %s", string(raw), err)
}
return &t, nil
}
func (t *LoadBalancerHealthCheck) GetUUID() string | {
return t.UUID
} |
package main
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/lightstep/lightstep-tracer-cpp/lightstep-tracer-common"
"io"
)
func computeFieldTypeNumber(field uint64, wireType uint64) uint64 {
return (field << 3) | wireType
}
func readReporter(reader *bufio.Reader) (*collectorpb.Reporter, error) {
reporter := &collectorpb.Reporter{}
return reporter, readEmbeddedMessage(reader, 1, reporter)
}
func readAuth(reader *bufio.Reader) (*collectorpb.Auth, error) {
auth := &collectorpb.Auth{}
return auth, readEmbeddedMessage(reader, 2, auth)
}
func readInternalMetrics(reader *bufio.Reader) (*collectorpb.InternalMetrics, error) {
internalMetrics := &collectorpb.InternalMetrics{}
return internalMetrics, readEmbeddedMessage(reader, 6, internalMetrics)
}
func ReadStreamHeader(reader *bufio.Reader) (*collectorpb.ReportRequest, error) {
reporter, err := readReporter(reader)
if err != nil {
return nil, err
}
auth, err := readAuth(reader)
if err != nil {
return nil, err
}
internalMetrics, err := readInternalMetrics(reader)
if err != nil {
return nil, err
}
result := &collectorpb.ReportRequest{
Reporter: reporter,
Auth: auth,
InternalMetrics: internalMetrics,
}
return result, nil
}
func ReadSpan(reader *bufio.Reader) (*collectorpb.Span, error) {
span := &collectorpb.Span{}
return span, readEmbeddedMessage(reader, 3, span)
}
func readEmbeddedMessage(reader *bufio.Reader, field uint64, message proto.Message) error | {
fieldType, err := binary.ReadUvarint(reader)
if err != nil {
return err
}
if expectedFieldType := computeFieldTypeNumber(field, proto.WireBytes); fieldType != expectedFieldType {
return errors.New(fmt.Sprintf("Unexpected fieldType %d number for Reporter: expected %d", fieldType,
expectedFieldType))
}
length, err := binary.ReadUvarint(reader)
if err != nil {
return err
}
buffer := make([]byte, length)
_, err = io.ReadFull(reader, buffer)
if err != nil {
return err
}
return proto.Unmarshal(buffer, message)
} |
package glw
import "golang.org/x/mobile/gl"
type A2fv gl.Attrib
func (a A2fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }
func (a A2fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }
func (a A2fv) Pointer() {
a.Enable()
ctx.VertexAttribPointer(gl.Attrib(a), 2, gl.FLOAT, false, 0, 0)
}
type A3fv gl.Attrib
func (a A3fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }
func (a A3fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }
type A4fv gl.Attrib
func (a A4fv) Enable() { ctx.EnableVertexAttribArray(gl.Attrib(a)) }
func (a A4fv) Disable() { ctx.DisableVertexAttribArray(gl.Attrib(a)) }
func (a A4fv) Pointer() {
a.Enable()
ctx.VertexAttribPointer(gl.Attrib(a), 4, gl.FLOAT, false, 0, 0)
}
func (a A3fv) Pointer() | {
a.Enable()
ctx.VertexAttribPointer(gl.Attrib(a), 3, gl.FLOAT, false, 0, 0)
} |
package main
import (
"reflect"
)
type Person struct {
name string "namestr"
age int
}
func ShowTag(i interface{}) {
switch t := reflect.TypeOf(i); t.Kind() {
case reflect.Ptr:
tag := t.Elem().Field(0).Tag
println(tag)
}
}
func main() {
p := new(Person)
p.name = "test"
p.age = 18
ShowTag(p)
show(p)
}
func show(i interface{}) | {
switch i.(type) {
case *Person:
t := reflect.TypeOf(i)
v := reflect.ValueOf(i)
tag := t.Elem().Field(0).Tag
name := v.Elem().Field(0).String()
age := v.Elem().Field(1).Int()
println(tag)
println(name)
println(age)
}
} |
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) Address() (string, error) {
if server.listener == nil {
return "", errors.New("not bound")
}
return extractBoundAddress(server.listener)
}
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
} |
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 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)
},
}
}
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
} |
package sign
import (
"dfss"
cAPI "dfss/dfssc/api"
pAPI "dfss/dfssp/api"
"dfss/dfsst/entities"
"dfss/net"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
type clientServer struct {
incomingPromises chan interface{}
incomingSignatures chan interface{}
}
func getServerErrorCode(c chan interface{}, in interface{}) *pAPI.ErrorCode {
if c != nil {
c <- in
return &pAPI.ErrorCode{Code: pAPI.ErrorCode_SUCCESS}
}
return &pAPI.ErrorCode{Code: pAPI.ErrorCode_INTERR}
}
func (s *clientServer) TreatPromise(ctx context.Context, in *cAPI.Promise) (*pAPI.ErrorCode, error) {
valid, _, _, _ := entities.IsRequestValid(ctx, []*cAPI.Promise{in})
if !valid {
return &pAPI.ErrorCode{Code: pAPI.ErrorCode_SUCCESS}, nil
}
return getServerErrorCode(s.incomingPromises, in), nil
}
func (s *clientServer) TreatSignature(ctx context.Context, in *cAPI.Signature) (*pAPI.ErrorCode, error) {
return getServerErrorCode(s.incomingSignatures, in), nil
}
func (m *SignatureManager) GetServer() *grpc.Server {
server := net.NewServer(m.auth.Cert, m.auth.Key, m.auth.CA)
m.cServerIface = clientServer{}
cAPI.RegisterClientServer(server, &m.cServerIface)
return server
}
func (s *clientServer) Discover(ctx context.Context, in *cAPI.Hello) (*cAPI.Hello, error) | {
return &cAPI.Hello{Version: dfss.Version}, nil
} |
package resolver
var (
m = make(map[string]Builder)
defaultScheme = "passthrough"
)
func Get(scheme string) Builder {
if b, ok := m[scheme]; ok {
return b
}
if b, ok := m[defaultScheme]; ok {
return b
}
return nil
}
func SetDefaultScheme(scheme string) {
defaultScheme = scheme
}
type AddressType uint8
const (
Backend AddressType = iota
GRPCLB
)
type Address struct {
Addr string
Type AddressType
ServerName string
Metadata interface{}
}
type BuildOption struct {
}
type ClientConn interface {
NewAddress(addresses []Address)
NewServiceConfig(serviceConfig string)
}
type Target struct {
Scheme string
Authority string
Endpoint string
}
type Builder interface {
Build(target Target, cc ClientConn, opts BuildOption) (Resolver, error)
Scheme() string
}
type ResolveNowOption struct{}
type Resolver interface {
ResolveNow(ResolveNowOption)
Close()
}
func UnregisterForTesting(scheme string) {
delete(m, scheme)
}
func Register(b Builder) | {
m[b.Scheme()] = b
} |
package bst
import (
"math"
"github.com/catorpilor/leetcode/utils"
)
func helper(node *utils.TreeNode, min, max int) bool {
if node == nil {
return true
}
if node.Val <= min || node.Val >= max {
return false
}
return helper(node.Left, min, node.Val) && helper(node.Right, node.Val, max)
}
func IsValidBST(root *utils.TreeNode) bool | {
return helper(root, math.MinInt64, math.MaxInt64)
} |
package master
import (
"fmt"
"log"
"net/http"
auth "github.com/abbot/go-http-auth"
"github.com/h2oai/steam/master/az"
)
type DefaultAz struct {
directory az.Directory
}
func NewDefaultAz(directory az.Directory) *DefaultAz {
return &DefaultAz{directory}
}
func (a *DefaultAz) Authenticate(username string) string {
pz, err := a.directory.Lookup(username)
if err != nil {
log.Printf("User %s read failed: %s\n", username, err)
return ""
}
if pz == nil {
log.Printf("User %s does not exist\n", username)
return ""
}
return pz.Password()
}
func (a *DefaultAz) Identify(r *http.Request) (az.Principal, error) {
username := r.Header.Get(auth.AuthUsernameHeader)
pz, err := a.directory.Lookup(username)
if err != nil {
return nil, err
}
if pz == nil {
return nil, fmt.Errorf("User %s does not exist\n", username)
}
return pz, nil
}
func serveNoop(w http.ResponseWriter, r *http.Request) {}
func authNoop(user, realm string) string | { return "" } |
package Utils
import (
"fmt"
"testing"
)
func TestGzip(t *testing.T) {
mergeBuf := MergeBinary([]byte("i am first words"), []byte("i am second words"))
gzip, err := FastGZipMsg(mergeBuf, true)
if err != nil {
t.Fail()
return
}
unzip, err := FastUnGZipMsg(gzip, true)
if err != nil {
t.Fail()
return
}
splitBuf := SplitBinary(unzip)
for _, v := range splitBuf {
fmt.Println(string(v))
}
}
func TestBinary(t *testing.T) | {
mergeBuf := MergeBinary([]byte("i am first words"), []byte("i am second words"))
splitBuf := SplitBinary(mergeBuf)
for _, v := range splitBuf {
fmt.Println(string(v))
}
} |
package font
import (
"bytes"
)
var alias = map[rune]string{
0x2764: "\u2665",
0x0001f499: "\u2665",
0x0001f49a: "\u2665",
0x0001f49b: "\u2665",
0x0001f49c: "\u2665",
0x0001f49d: "\u2665",
0x0001F601: ":|",
0x0001F602: ":)",
0x0001F603: ":D",
}
type Font struct {
width int
height int
bitmap map[rune][]byte
}
func ExpandAlias(text string) string {
var f func(b *bytes.Buffer, s string)
f = func(b *bytes.Buffer, s string) {
for _, c := range s {
m, ok := alias[c]
if ok {
f(b, m)
} else {
b.WriteRune(c)
}
}
}
b := new(bytes.Buffer)
f(b, text)
return b.String()
}
func (f *Font) Height() int {
return f.height
}
func (f *Font) Bitmap(c rune) []byte {
return f.bitmap[c]
}
func (f *Font) Width() int | {
return f.width
} |
package v1alpha1_test
import (
"reflect"
"testing"
"k8s.io/api/scheduling/v1alpha1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/kubernetes/pkg/api/legacyscheme"
apiv1 "k8s.io/api/core/v1"
utilfeature "k8s.io/apiserver/pkg/util/feature"
featuregatetesting "k8s.io/component-base/featuregate/testing"
_ "k8s.io/kubernetes/pkg/api/testapi"
"k8s.io/kubernetes/pkg/features"
)
func roundTrip(t *testing.T, obj runtime.Object) runtime.Object {
codec := legacyscheme.Codecs.LegacyCodec(v1alpha1.SchemeGroupVersion)
data, err := runtime.Encode(codec, obj)
if err != nil {
t.Errorf("%v\n %#v", err, obj)
return nil
}
obj2, err := runtime.Decode(codec, data)
if err != nil {
t.Errorf("%v\nData: %s\nSource: %#v", err, string(data), obj)
return nil
}
obj3 := reflect.New(reflect.TypeOf(obj).Elem()).Interface().(runtime.Object)
err = legacyscheme.Scheme.Convert(obj2, obj3, nil)
if err != nil {
t.Errorf("%v\nSource: %#v", err, obj2)
return nil
}
return obj3
}
func TestSetDefaultPreempting(t *testing.T) | {
priorityClass := &v1alpha1.PriorityClass{}
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.NonPreemptingPriority, true)()
output := roundTrip(t, runtime.Object(priorityClass)).(*v1alpha1.PriorityClass)
if output.PreemptionPolicy == nil || *output.PreemptionPolicy != apiv1.PreemptLowerPriority {
t.Errorf("Expected PriorityClass.Preempting value: %+v\ngot: %+v\n", apiv1.PreemptLowerPriority, output.PreemptionPolicy)
}
} |
package sdk
import (
"context"
"time"
)
var NowTime func() time.Time
var Sleep func(time.Duration)
var SleepWithContext func(context.Context, time.Duration) error
func sleepWithContext(ctx context.Context, dur time.Duration) error {
t := time.NewTimer(dur)
defer t.Stop()
select {
case <-t.C:
break
case <-ctx.Done():
return ctx.Err()
}
return nil
}
func noOpSleepWithContext(context.Context, time.Duration) error {
return nil
}
func noOpSleep(time.Duration) {}
func TestingUseNopSleep() func() {
SleepWithContext = noOpSleepWithContext
Sleep = noOpSleep
return func() {
SleepWithContext = sleepWithContext
Sleep = time.Sleep
}
}
func TestingUseReferenceTime(referenceTime time.Time) func() {
NowTime = func() time.Time {
return referenceTime
}
return func() {
NowTime = time.Now
}
}
func init() | {
NowTime = time.Now
Sleep = time.Sleep
SleepWithContext = sleepWithContext
} |
package main
import (
"fmt"
"testing"
)
func bats(l, d, n int, s []string) (c int) {
var t int
tx := 6 - d
for i := 6; i <= l-6; i += d {
if i > tx-d {
i = tx
if t == n {
tx = l - 6 + d
} else {
fmt.Sscanf(s[t], "%d", &tx)
t++
}
} else {
c++
}
}
return c
}
func TestBats(t *testing.T) | {
if r := bats(22, 2, 2, []string{"9", "11"}); r != 3 {
t.Errorf("failed: bats 22 2 2 9 11 is 3, got %d",
r)
}
if r := bats(835, 125, 1, []string{"113"}); r != 5 {
t.Errorf("failed: bats 835 125 1 113 is 5, got %d",
r)
}
if r := bats(47, 5, 0, []string{}); r != 8 {
t.Errorf("failed: bats 475 5 0 is 8, got %d",
r)
}
} |
package resource
import (
"errors"
"strings"
"time"
)
type Item struct {
ID interface{}
ETag string
Updated time.Time
Payload map[string]interface{}
}
type ItemList struct {
Total int
Page int
Items []*Item
}
func NewItem(payload map[string]interface{}) (*Item, error) {
id, found := payload["id"]
if !found {
return nil, errors.New("Missing ID field")
}
etag, err := genEtag(payload)
if err != nil {
return nil, err
}
item := &Item{
ID: id,
ETag: etag,
Updated: time.Now(),
Payload: payload,
}
return item, nil
}
func getField(payload map[string]interface{}, name string) interface{} {
path := strings.SplitN(name, ".", 2)
if value, found := payload[path[0]]; found {
if len(path) == 2 {
if subPayload, ok := value.(map[string]interface{}); ok {
return getField(subPayload, path[1])
}
return nil
}
return value
}
return nil
}
func (i Item) GetField(name string) interface{} | {
return getField(i.Payload, name)
} |
package core
import (
"fmt"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
"github.com/tendermint/tendermint/types"
. "github.com/tendermint/tmlibs/common"
)
func BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResultBlockchainInfo, error) {
if maxHeight == 0 {
maxHeight = blockStore.Height()
} else {
maxHeight = MinInt(blockStore.Height(), maxHeight)
}
if minHeight == 0 {
minHeight = MaxInt(1, maxHeight-20)
} else {
minHeight = MaxInt(minHeight, maxHeight-20)
}
logger.Debug("BlockchainInfoHandler", "maxHeight", maxHeight, "minHeight", minHeight)
blockMetas := []*types.BlockMeta{}
for height := maxHeight; height >= minHeight; height-- {
blockMeta := blockStore.LoadBlockMeta(height)
blockMetas = append(blockMetas, blockMeta)
}
return &ctypes.ResultBlockchainInfo{blockStore.Height(), blockMetas}, nil
}
func Commit(height int) (*ctypes.ResultCommit, error) {
if height == 0 {
return nil, fmt.Errorf("Height must be greater than 0")
}
storeHeight := blockStore.Height()
if height > storeHeight {
return nil, fmt.Errorf("Height must be less than or equal to the current blockchain height")
}
header := blockStore.LoadBlockMeta(height).Header
if height == storeHeight {
commit := blockStore.LoadSeenCommit(height)
return &ctypes.ResultCommit{header, commit, false}, nil
}
commit := blockStore.LoadBlockCommit(height)
return &ctypes.ResultCommit{header, commit, true}, nil
}
func Block(height int) (*ctypes.ResultBlock, error) | {
if height == 0 {
return nil, fmt.Errorf("Height must be greater than 0")
}
if height > blockStore.Height() {
return nil, fmt.Errorf("Height must be less than the current blockchain height")
}
blockMeta := blockStore.LoadBlockMeta(height)
block := blockStore.LoadBlock(height)
return &ctypes.ResultBlock{blockMeta, block}, nil
} |
package account
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
}
type DescribeProjectArgs struct{}
type DescribeProjectResponse struct {
Response
Data []Project `json:"data"`
}
type Project struct {
ProjectName string `json:"projectName"`
ProjectId int `json:"projectId"`
CreateTime string `json:"createTime"`
CreatorUin int `json:"creatorUin"`
ProjectInfo string `json:"projectInfo"`
}
func (client *Client) DescribeProject(args *DescribeProjectArgs) (*DescribeProjectResponse, error) | {
response := &DescribeProjectResponse{}
err := client.Invoke("DescribeProject", args, response)
if err != nil {
return &DescribeProjectResponse{}, err
}
return response, nil
} |
package v1
type EnvVarSourceApplyConfiguration struct {
FieldRef *ObjectFieldSelectorApplyConfiguration `json:"fieldRef,omitempty"`
ResourceFieldRef *ResourceFieldSelectorApplyConfiguration `json:"resourceFieldRef,omitempty"`
ConfigMapKeyRef *ConfigMapKeySelectorApplyConfiguration `json:"configMapKeyRef,omitempty"`
SecretKeyRef *SecretKeySelectorApplyConfiguration `json:"secretKeyRef,omitempty"`
}
func EnvVarSource() *EnvVarSourceApplyConfiguration {
return &EnvVarSourceApplyConfiguration{}
}
func (b *EnvVarSourceApplyConfiguration) WithFieldRef(value *ObjectFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {
b.FieldRef = value
return b
}
func (b *EnvVarSourceApplyConfiguration) WithResourceFieldRef(value *ResourceFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {
b.ResourceFieldRef = value
return b
}
func (b *EnvVarSourceApplyConfiguration) WithConfigMapKeyRef(value *ConfigMapKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {
b.ConfigMapKeyRef = value
return b
}
func (b *EnvVarSourceApplyConfiguration) WithSecretKeyRef(value *SecretKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration | {
b.SecretKeyRef = value
return b
} |
package gbcrypto
import "testing"
func TestDecrypt(t *testing.T) | {
secretKey := "SecretKey"
message := "Pz3cJ61A4Dw4vTFcqWN6t39pyWyOGCQe9F0="
expected := "encrypt me"
cryptography := Cryptography{}
decrypted := cryptography.Decrypt(secretKey, message)
if decrypted != expected {
t.Errorf("Expected %v, got %v", expected, decrypted)
}
} |
package v1
import (
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type ContainerStateRunningApplyConfiguration struct {
StartedAt *v1.Time `json:"startedAt,omitempty"`
}
func ContainerStateRunning() *ContainerStateRunningApplyConfiguration {
return &ContainerStateRunningApplyConfiguration{}
}
func (b *ContainerStateRunningApplyConfiguration) WithStartedAt(value v1.Time) *ContainerStateRunningApplyConfiguration | {
b.StartedAt = &value
return b
} |
package smtp
import (
"errors"
"testing"
)
type EmailRecorder struct {
from string
to []string
msg []byte
}
type SMTPMock struct {
r *EmailRecorder
err error
}
func (s *SMTPMock) SendMail(from string, to []string, msg []byte) error {
s.r = &EmailRecorder{from, to, msg}
return s.err
}
func TestMailService(t *testing.T) {
mailService := MailService{}
var i interface{} = &mailService
_, ok := i.(IMailService)
if !ok {
t.Fatalf("MailService must implement IMailService")
}
}
func TestSendNormal(t *testing.T) {
body := "From: john@doe.com\r\n" +
"To: jane@doe.com\r\n" +
"Subject: test\r\n" +
"\r\n" +
"message\r\n"
s := SMTPMock{err: nil}
mailService := NewMailService(&s)
err := mailService.Send("message", "test", "john@doe.com", "jane@doe.com")
if err != nil {
t.Fatalf("Mustn't return an error")
}
if string(s.r.msg) != body {
t.Errorf("wrong message body.\n\nexpected: %s\n got: %s", body, s.r.msg)
}
}
func TestSendError(t *testing.T) | {
err := errors.New("Error")
s := SMTPMock{err: err}
mailService := NewMailService(&s)
err = mailService.Send("message", "test", "john@doe.com", "jane@doe.com")
if err == nil {
t.Fatalf("Must return an error")
}
} |
package data
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNote(t *testing.T) {
acc := AccountNew("mail@example.com")
user, err := acc.Store()
assert.Nil(t, err)
note := NoteNew(user.ID, "example content")
assert.False(t, note.IsStored())
assert.Equal(t, "example content", note.Text)
assert.Equal(t, user.ID, note.Account)
note, err = note.Store()
if assert.Nil(t, err) {
assert.True(t, note.IsStored())
}
user.Remove()
}
func TestNoteList(t *testing.T) {
acc := AccountNew("mail@example.com")
user, err := acc.Store()
assert.Nil(t, err)
note := NoteNew(user.ID, "This is a note!")
note, err = note.Store()
assert.Nil(t, err)
note2 := NoteNew(user.ID, "This is a second note!")
note2, err = note2.Store()
assert.Nil(t, err)
list, err := NoteListByAccount(user.ID)
assert.Nil(t, err)
assert.Equal(t, 2, len(list))
user.Remove()
}
func TestNoteLimit(t *testing.T) | {
acc := AccountNew("mail@example.com")
user, err := acc.Store()
assert.Nil(t, err)
note := NoteNew(user.ID, "This is a note! This is a note! This is a note! This is a note! This is a note! This is a note! This is a note!")
assert.False(t, note.IsStored())
assert.Equal(t, user.ID, note.Account)
note, err = note.Store()
assert.NotNil(t, err)
user.Remove()
} |
package portmapper
import (
"fmt"
"strings"
"sync"
"github.com/golang/glog"
)
type PortMap struct {
containerIP string
containerPort int
}
func newPortMap(containerip string, containerport int) *PortMap {
return &PortMap{
containerIP: containerip,
containerPort: containerport,
}
}
type PortSet map[int]*PortMap
type PortMapper struct {
tcpMap PortSet
udpMap PortSet
mutex sync.Mutex
}
func New() *PortMapper {
return &PortMapper{PortSet{}, PortSet{}, sync.Mutex{}}
}
func (p *PortMapper) ReleaseMap(protocol string, hostPort int) error {
p.mutex.Lock()
defer p.mutex.Unlock()
var pset PortSet
if strings.EqualFold(protocol, "udp") {
pset = p.udpMap
} else {
pset = p.tcpMap
}
_, ok := pset[hostPort]
if !ok {
glog.Errorf("Host port %d has not been used", hostPort)
}
delete(pset, hostPort)
return nil
}
func (p *PortMapper) AllocateMap(protocol string, hostPort int,
containerIP string, ContainerPort int) error | {
p.mutex.Lock()
defer p.mutex.Unlock()
var pset PortSet
if strings.EqualFold(protocol, "udp") {
pset = p.udpMap
} else {
pset = p.tcpMap
}
e, ok := pset[hostPort]
if ok {
return fmt.Errorf("Host port %d had already been used, %s %d",
hostPort, e.containerIP, e.containerPort)
}
allocated := newPortMap(containerIP, ContainerPort)
pset[hostPort] = allocated
return nil
} |
package rest
import "net/http"
type StaticResource struct {
ResourceBase
result *Result
self Link
}
func NewStaticResource(result *Result, self Link) Resource {
return &StaticResource{
result: result,
self: self,
}
}
func StaticContent(content []byte, contentType string, selfHref string) Resource {
return NewStaticResource(
Ok().AddHeader("Content-Type", contentType).WithBody(content),
SimpleLink(selfHref),
)
}
func (r StaticResource) Self() Link {
return r.self
}
func (r StaticResource) Get(request *http.Request) (interface{}, error) | {
return r.result, nil
} |
package client
import (
"encoding/json"
"io"
"os"
)
func encodeJSON(w io.Writer, v interface{}) {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
enc.Encode(v)
}
func dump(v interface{}) | {
encodeJSON(os.Stdout, v)
} |
package main
import (
"time"
"github.com/PalmStoneGames/polymer"
)
func init() {
polymer.Register("tick-timer", &Timer{})
}
type Timer struct {
*polymer.Proto
Time time.Time `polymer:"bind"`
}
func (t *Timer) Created() {
go func() {
for {
t.Time = time.Now()
t.Notify("time")
time.Sleep(time.Millisecond * 100)
}
}()
}
func main() {}
func (t *Timer) ComputeTime() string | {
return t.Time.String()
} |
package dialects
import (
"fmt"
"strings"
)
type Filter interface {
Do(sql string) string
}
type SeqFilter struct {
Prefix string
Start int
}
func convertQuestionMark(sql, prefix string, start int) string {
var buf strings.Builder
var beginSingleQuote bool
var index = start
for _, c := range sql {
if !beginSingleQuote && c == '?' {
buf.WriteString(fmt.Sprintf("%s%v", prefix, index))
index++
} else {
if c == '\'' {
beginSingleQuote = !beginSingleQuote
}
buf.WriteRune(c)
}
}
return buf.String()
}
func (s *SeqFilter) Do(sql string) string | {
return convertQuestionMark(sql, s.Prefix, s.Start)
} |
package v1
import context "context"
import proto "github.com/golang/protobuf/proto"
import "go-common/library/net/rpc/liverpc"
var _ proto.Message
type CaptchaRPCClient interface {
Create(ctx context.Context, req *CaptchaCreateReq, opts ...liverpc.CallOption) (resp *CaptchaCreateResp, err error)
}
type captchaRPCClient struct {
client *liverpc.Client
}
func (c *captchaRPCClient) Create(ctx context.Context, in *CaptchaCreateReq, opts ...liverpc.CallOption) (*CaptchaCreateResp, error) {
out := new(CaptchaCreateResp)
err := doRPCRequest(ctx, c.client, 1, "Captcha.create", in, out, opts)
if err != nil {
return nil, err
}
return out, nil
}
func doRPCRequest(ctx context.Context, client *liverpc.Client, version int, method string, in, out proto.Message, opts []liverpc.CallOption) (err error) {
err = client.Call(ctx, version, method, in, out, opts...)
return
}
func NewCaptchaRPCClient(client *liverpc.Client) CaptchaRPCClient | {
return &captchaRPCClient{
client: client,
}
} |
package assets
import (
"fmt"
"github.com/iceburg-instance/database"
"github.com/iceburg-instance/database/models/terrain"
)
type HeightData struct {
HeightVals []terrain.HeightTuple
}
func GetHeight() (*HeightData, error) | {
qString := terrain.GetAllString()
rows, err := database.Query(qString)
if err != nil {
fmt.Println(err)
return nil, err
}
defer rows.Close()
var heightSlice []terrain.HeightTuple
var heightTuple terrain.HeightTuple
for rows.Next() {
heightTuple = terrain.HeightTuple{}
if err := rows.Scan(&heightTuple.Id, &heightTuple.Height); err != nil {
fmt.Println(err)
return nil, err
}
heightSlice = append(heightSlice, heightTuple)
}
return &HeightData{HeightVals: heightSlice}, nil
} |
package blocker
import "sort"
type sources []string
func (s *sources) Add(source string) {
n := sort.SearchStrings(*s, source)
if n < len(*s) && (*s)[n] == source {
return
}
*s = append(*s, "")
copy((*s)[n+1:], (*s)[n:])
(*s)[n] = source
}
func (s *sources) Remove(source string) bool {
if s == nil {
return false
}
n := sort.SearchStrings(*s, source)
if n < len(*s) && (*s)[n] == source {
*s = append((*s)[:n], (*s)[n+1:]...)
return true
}
return false
}
func (s *sources) Len() int {
return len(*s)
}
func newSources(s ...string) *sources {
ret := sources(s)
return &ret
}
func (s *sources) Has(source string) bool | {
if s == nil {
return false
}
n := sort.SearchStrings(*s, source)
if n < len(*s) && (*s)[n] == source {
return true
}
return false
} |
package adal
import (
"fmt"
"net/url"
)
const (
activeDirectoryAPIVersion = "1.0"
)
type OAuthConfig struct {
AuthorityEndpoint url.URL
AuthorizeEndpoint url.URL
TokenEndpoint url.URL
DeviceCodeEndpoint url.URL
}
func (oac OAuthConfig) IsZero() bool {
return oac == OAuthConfig{}
}
func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) {
if err := validateStringParam(activeDirectoryEndpoint, "activeDirectoryEndpoint"); err != nil {
return nil, err
}
const activeDirectoryEndpointTemplate = "%s/oauth2/%s?api-version=%s"
u, err := url.Parse(activeDirectoryEndpoint)
if err != nil {
return nil, err
}
authorityURL, err := u.Parse(tenantID)
if err != nil {
return nil, err
}
authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", activeDirectoryAPIVersion))
if err != nil {
return nil, err
}
tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", activeDirectoryAPIVersion))
if err != nil {
return nil, err
}
deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", activeDirectoryAPIVersion))
if err != nil {
return nil, err
}
return &OAuthConfig{
AuthorityEndpoint: *authorityURL,
AuthorizeEndpoint: *authorizeURL,
TokenEndpoint: *tokenURL,
DeviceCodeEndpoint: *deviceCodeURL,
}, nil
}
func validateStringParam(param, name string) error | {
if len(param) == 0 {
return fmt.Errorf("parameter '" + name + "' cannot be empty")
}
return nil
} |
package main
import (
"fmt"
"time"
)
func createServer() error {
c, err := getClient()
if err != nil {
return err
}
sb := c.NewServerBuilder()
sb.Addr("127.0.0.1:8080").HTTPBackend().MaxQPS(100)
sb.CheckHTTPCode("/check/path", time.Second*10, time.Second*30)
sb.CircuitBreakerCheckPeriod(time.Second)
sb.CircuitBreakerCloseToHalfTimeout(time.Second * 60)
sb.CircuitBreakerHalfTrafficRate(10)
sb.CircuitBreakerHalfToCloseCondition(2)
sb.CircuitBreakerHalfToOpenCondition(90)
id, err := sb.Commit()
if err != nil {
return err
}
fmt.Printf("server id is: %d", id)
c.AddBind(1, id)
c.RemoveBind(1, id)
c.AddBind(2, id)
return nil
}
func updateServer(id uint64) error {
c, err := getClient()
if err != nil {
return err
}
svr, err := c.GetServer(id)
if err != nil {
return err
}
sb := c.NewServerBuilder()
sb.Use(*svr)
sb.MaxQPS(1000)
sb.NoCircuitBreaker()
sb.NoHeathCheck()
_, err = sb.Commit()
return err
}
func deleteServer(id uint64) error | {
c, err := getClient()
if err != nil {
return err
}
return c.RemoveServer(id)
} |
package miniredis
import (
"reflect"
"testing"
)
func assert(tb testing.TB, condition bool, msg string, v ...interface{}) {
tb.Helper()
if !condition {
tb.Errorf(msg, v...)
}
}
func equals(tb testing.TB, exp, act interface{}) {
tb.Helper()
if !reflect.DeepEqual(exp, act) {
tb.Errorf("expected: %#v got: %#v", exp, act)
}
}
func mustFail(tb testing.TB, err error, want string) {
tb.Helper()
if err == nil {
tb.Errorf("expected an error, but got a nil")
}
if have := err.Error(); have != want {
tb.Errorf("have %q, want %q", have, want)
}
}
func ok(tb testing.TB, err error) | {
tb.Helper()
if err != nil {
tb.Errorf("unexpected error: %s", err.Error())
}
} |
package main
import (
"encoding/json"
"time"
)
type Monitor interface {
GetVariables() []string
GetValues([]string) map[string]interface{}
}
var monitorDrivers = make(map[string]func(*json.RawMessage) Monitor)
func AddMonitorDriver(monitor string, constructor func(*json.RawMessage) Monitor) {
monitorDrivers[monitor] = constructor
}
type MonitorTrack struct {
Variables map[string]*MonitorTrackVariable
Interval int
timer *time.Timer
}
func newMonitorTrack() *MonitorTrack {
return &MonitorTrack{
Variables: make(map[string]*MonitorTrackVariable),
}
}
type MonitorTrackVariable struct {
History int
Data []interface{}
}
func (mt *MonitorTrack) Start(monitor Monitor) {
go func() {
mt.timer = time.NewTimer(time.Duration(1) * time.Second)
for _ = range mt.timer.C {
if mt.Interval > 0 {
mt.timer.Reset(time.Second * time.Duration(mt.Interval))
}
variables := []string{}
for variable := range mt.Variables {
variables = append(variables, variable)
}
values := monitor.GetValues(variables)
for variable, vt := range mt.Variables {
vt.Data = append(vt.Data, values[variable])
if len(vt.Data) > vt.History {
vt.Data = vt.Data[len(vt.Data)-vt.History:]
}
}
}
}()
}
func (mt *MonitorTrack) SetTrack(variable string, history int) | {
track, ok := mt.Variables[variable]
if !ok && history > 0 {
track = &MonitorTrackVariable{}
mt.Variables[variable] = track
}
if history == 0 && ok {
delete(mt.Variables, variable)
return
}
track.History = history
} |
package cmd
import (
"errors"
"os"
"github.com/codegangsta/cli"
"github.com/DevMine/srctool/config"
"github.com/DevMine/srctool/log"
)
func Delete(c *cli.Context) {
if !c.Args().Present() {
deleteAll(c.Bool("dry"))
} else {
if err := deleteParser(genParserName(c.Args().First()), c.Bool("dry"), true); err != nil {
log.Fatal(err)
}
}
}
func deleteParser(parserName string, dryMode bool, verbose bool) error {
parserPath := config.ParserPath(parserName)
if _, err := os.Stat(parserPath); os.IsNotExist(err) {
log.Debug(err)
return errors.New(parserName + " is not installed")
}
if dryMode {
log.Info("parser path:", parserPath)
return nil
}
log.Debug("removing ", parserPath)
if err := os.RemoveAll(parserPath); err != nil {
log.Debug(err)
return errors.New("failed to remove " + parserName)
}
if verbose {
log.Success(parserName, " successfully removed")
}
return nil
}
func deleteAll(dryMode bool) | {
parsers := getInstalledParsers()
for _, parser := range parsers {
if err := deleteParser(genParserName(parser), dryMode, true); err != nil {
log.Fail(err)
}
}
} |
package router
import (
"net/http"
"strconv"
"time"
"github.com/ewhal/nyaa/db"
"github.com/ewhal/nyaa/model"
"github.com/ewhal/nyaa/service/captcha"
"github.com/ewhal/nyaa/service/torrent"
"github.com/ewhal/nyaa/util"
"github.com/ewhal/nyaa/util/languages"
"github.com/ewhal/nyaa/util/log"
"github.com/gorilla/mux"
)
func PostCommentHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
userCaptcha := captcha.Extract(r)
if !captcha.Authenticate(userCaptcha) {
http.Error(w, "bad captcha", 403)
}
currentUser := GetUser(r)
content := p.Sanitize(r.FormValue("comment"))
idNum_, err := strconv.Atoi(id)
var idNum uint = uint(idNum_)
var userId uint = 0
if currentUser.Id > 0 {
userId = currentUser.Id
}
comment := model.Comment{TorrentId: idNum, UserId: userId, Content: content, CreatedAt: time.Now()}
err = db.ORM.Create(&comment).Error
if err != nil {
util.SendError(w, err, 500)
return
}
url, err := Router.Get("view_torrent").URL("id", id)
if err == nil {
http.Redirect(w, r, url.String(), 302)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func ViewHandler(w http.ResponseWriter, r *http.Request) | {
vars := mux.Vars(r)
id := vars["id"]
torrent, err := torrentService.GetTorrentById(id)
if err != nil {
NotFoundHandler(w, r)
return
}
b := torrent.ToJson()
htv := ViewTemplateVariables{b, captcha.Captcha{CaptchaID: captcha.GetID()}, NewSearchForm(), Navigation{}, GetUser(r), r.URL, mux.CurrentRoute(r)}
languages.SetTranslationFromRequest(viewTemplate, r, "en-us")
err = viewTemplate.ExecuteTemplate(w, "index.html", htv)
if err != nil {
log.Errorf("ViewHandler(): %s", err)
}
} |
package model
import (
"go-common/app/service/main/archive/model/archive"
)
type ArcToView struct {
*archive.Archive3
Page *archive.Page3 `json:"page,omitempty"`
Count int `json:"count"`
Cid int64 `json:"cid"`
Progress int64 `json:"progress"`
AddTime int64 `json:"add_at"`
}
type WebArcToView struct {
*archive.View3
BangumiInfo *Bangumi `json:"bangumi,omitempty"`
Cid int64 `json:"cid"`
Progress int64 `json:"progress"`
AddTime int64 `json:"add_at"`
}
type ToView struct {
Aid int64 `json:"aid,omitempty"`
Unix int64 `json:"now,omitempty"`
}
type ToViews []*ToView
func (h ToViews) Len() int { return len(h) }
func (h ToViews) Less(i, j int) bool { return h[i].Unix > h[j].Unix }
func (h ToViews) Swap(i, j int) | { h[i], h[j] = h[j], h[i] } |
package helpers
import (
"fmt"
"gopkg.in/ini.v1"
"runtime"
)
type Distro struct {
Family string
InitSystem string
Version string
}
func (d *Distro) SetInitSystem() error {
switch d.Family {
case "debian":
d.InitSystem = "systemd"
case "centos":
d.InitSystem = "sysv"
default:
return fmt.Errorf("Unknown Init system for distribution: %s", d.Family)
}
return nil
}
func GetDistro() (*Distro, error) {
d := Distro{}
if runtime.GOOS == "linux" {
i, err := ini.Load([]byte(""), "/etc/os-release")
section, err := i.Section("").GetKey("ID_LIKE")
if err != nil {
return nil, err
}
err = d.SetFamily(section.String())
if err != nil {
return nil, err
}
err = d.SetInitSystem()
if err != nil {
return nil, err
}
}
return &d, nil
}
func (d *Distro) SetFamily(family string) error | {
switch family {
case "debian":
d.Family = family
case "centos":
d.Family = family
default:
return fmt.Errorf("Unknown Linux distribution: %s", family)
}
return nil
} |
package helper
import (
"bufio"
"net"
)
type BufConn struct {
net.Conn
BR *bufio.Reader
}
func (c *BufConn) Peek(n int) ([]byte, error) {
return c.BR.Peek(n)
}
func (c *BufConn) Read(b []byte) (n int, err error) {
return c.BR.Read(b)
}
func (c *BufConn) Reset(conn net.Conn) {
c.Conn = conn
}
func NewBufConn(c net.Conn, r *bufio.Reader) *BufConn {
conn := &BufConn{Conn: c}
conn.BR = r
if nil == r {
conn.BR = bufio.NewReader(c)
}
return conn
}
func (c *BufConn) Write(b []byte) (n int, err error) | {
return c.Conn.Write(b)
} |
package main
import (
"flag"
"io/ioutil"
"os"
"path"
"gopkg.in/yaml.v1"
)
const (
CONFIG_SUBDIR = "mcmd"
DEFAULT_KNOWN_HOSTS_FILE = "$HOME/.ssh/known_hosts"
)
type HostConfig struct {
User string
Privatekey string
Hosts []string
}
func loadConfig() HostConfig {
rawYaml := readHostfile()
var result HostConfig
err := yaml.Unmarshal(rawYaml, &result)
if err != nil {
errLogger.Fatalln("Error parsing hostfile:", err)
}
return result
}
func getConfigLocationCandidates(configFileParam string) []string {
configRoot, err := os.UserConfigDir()
if err != nil {
errLogger.Fatalf("no user config dir found")
}
configDir := path.Join(configRoot, CONFIG_SUBDIR)
return []string{configFileParam,
path.Join(configDir, configFileParam+".yml"),
path.Join(configDir, configFileParam+".yaml")}
}
func exists(filename string) bool {
_, err := os.Stat(filename)
return !os.IsNotExist(err)
}
func getContents(filename string) []byte {
fileContents, err := ioutil.ReadFile(filename)
if err != nil {
errLogger.Fatalln(err)
}
return fileContents
}
func readHostfile() []byte | {
configFileParam := flag.Arg(0)
for _, file := range getConfigLocationCandidates(configFileParam) {
if exists(file) {
return getContents(file)
}
}
errLogger.Fatalf("hostfile %s not found", configFileParam)
return nil
} |
package main
import (
"encoding/json"
"github.com/bitly/go-nsq"
"log"
"time"
)
var (
Publisher *MsgPublisher
)
type MsgPublisher struct {
usr User
writer *nsq.Writer
}
func init() {
Publisher = &MsgPublisher{
writer: nsq.NewWriter("106.186.31.48:4150"),
}
}
func (publisher *MsgPublisher) SetLoginUsr(_usr User) error {
if Publisher == nil {
Publisher = &MsgPublisher{
writer: nsq.NewWriter("106.186.31.48:4150"),
}
}
Publisher.usr = _usr
Publisher.usr.Pwd = "xxxx"
return nil
}
func (mp *MsgPublisher) WriteAsync(topic, msg string, responseChan chan *nsq.WriterTransaction) error {
m := Message{
Topic: topic,
Type: MSG_TYPE_CHAT,
Body: MessageBody{
From: mp.usr,
Msg: msg,
},
}
msgBytes, _ := json.Marshal(m)
log.Println("PublishAsync.msg = ", string(msgBytes))
return mp.writer.PublishAsync(topic, msgBytes, responseChan, "")
}
func (mp *MsgPublisher) Stop() {
mp.writer.Stop()
}
func (mp *MsgPublisher) Write(topic, msg string) (int32, []byte, error) | {
m := Message{
Topic: topic,
Type: MSG_TYPE_CHAT,
Time: time.Now().Format("2006-01-02 15:04:05"),
Body: MessageBody{
From: mp.usr,
Msg: msg,
},
}
msgBytes, _ := json.Marshal(m)
log.Println("Publish.msg = ", string(msgBytes))
return mp.writer.Publish(topic, msgBytes)
} |
package storage
import (
"encoding/json"
"github.com/rynorris/website/server/site"
"github.com/rynorris/website/server/storage"
)
const dummyKey = "site-configuration"
type Service struct {
storage storage.Service
}
func NewService(storage storage.Service) *Service {
return &Service{
storage: storage,
}
}
func (s *Service) Put(site site.Site) error {
blob, err := json.Marshal(site)
if err != nil {
return err
}
return s.storage.Put(dummyKey, blob)
}
func (s *Service) Get() (site.Site, error) | {
site := site.Site{}
blob, err := s.storage.Get(dummyKey)
if err != nil {
return site, err
}
err = json.Unmarshal(blob, &site)
return site, err
} |
package logger
import (
"fmt"
"log"
"gopkg.in/clever/kayvee-go.v2"
)
type M map[string]interface{}
func Info(title string, data M) {
logWithLevel(title, kayvee.Info, data)
}
func Trace(title string, data M) {
logWithLevel(title, kayvee.Trace, data)
}
func Critical(title string, data M) {
logWithLevel(title, kayvee.Critical, data)
}
func Error(title string, err error) {
logWithLevel(title, kayvee.Error, M{"error": fmt.Sprint(err)})
}
func ErrorDetailed(title string, err error, extras M) {
extras["error"] = fmt.Sprint(err)
logWithLevel(title, kayvee.Error, extras)
}
func logWithLevel(title string, level kayvee.LogLevel, data M) {
formatted := kayvee.FormatLog("moredis", level, title, data)
log.Println(formatted)
}
func Warning(title string, data M) | {
logWithLevel(title, kayvee.Warning, data)
} |
package metrics
import (
"sync"
prom "github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
)
const (
sandboxGuageName = "bundlelib_sandbox"
)
var (
once sync.Once
collector *Collector
)
type Collector struct {
Sandbox prom.Gauge
}
func recoverMetricPanic() {
if r := recover(); r != nil {
log.Errorf("Recovering from metric function - %v", r)
}
}
func RegisterCollector() {
once.Do(func() {
collector = &Collector{
Sandbox: prom.NewGauge(prom.GaugeOpts{
Name: sandboxGuageName,
Help: "Guage of all sandbox namespaces that are active.",
}),
}
err := prom.Register(collector)
if err != nil {
log.Errorf("unable to register collector with prometheus: %v", err)
}
})
}
func SandboxDeleted() {
defer recoverMetricPanic()
collector.Sandbox.Dec()
}
func (c Collector) Describe(ch chan<- *prom.Desc) {
c.Sandbox.Describe(ch)
}
func (c Collector) Collect(ch chan<- prom.Metric) {
c.Sandbox.Collect(ch)
}
func SandboxCreated() | {
defer recoverMetricPanic()
collector.Sandbox.Inc()
} |
package openstack
import (
"fmt"
"github.com/gophercloud/gophercloud"
tokens2 "github.com/gophercloud/gophercloud/openstack/identity/v2/tokens"
tokens3 "github.com/gophercloud/gophercloud/openstack/identity/v3/tokens"
)
type ErrEndpointNotFound struct{ gophercloud.BaseError }
func (e ErrEndpointNotFound) Error() string {
return "No suitable endpoint could be found in the service catalog."
}
type ErrInvalidAvailabilityProvided struct{ gophercloud.ErrInvalidInput }
func (e ErrInvalidAvailabilityProvided) Error() string {
return fmt.Sprintf("Unexpected availability in endpoint query: %s", e.Value)
}
type ErrMultipleMatchingEndpointsV2 struct {
gophercloud.BaseError
Endpoints []tokens2.Endpoint
}
type ErrMultipleMatchingEndpointsV3 struct {
gophercloud.BaseError
Endpoints []tokens3.Endpoint
}
func (e ErrMultipleMatchingEndpointsV3) Error() string {
return fmt.Sprintf("Discovered %d matching endpoints: %#v", len(e.Endpoints), e.Endpoints)
}
type ErrNoAuthURL struct{ gophercloud.ErrInvalidInput }
func (e ErrNoAuthURL) Error() string {
return "Environment variable OS_AUTH_URL needs to be set."
}
type ErrNoUsername struct{ gophercloud.ErrInvalidInput }
func (e ErrNoUsername) Error() string {
return "Environment variable OS_USERNAME needs to be set."
}
type ErrNoPassword struct{ gophercloud.ErrInvalidInput }
func (e ErrNoPassword) Error() string {
return "Environment variable OS_PASSWORD needs to be set."
}
func (e ErrMultipleMatchingEndpointsV2) Error() string | {
return fmt.Sprintf("Discovered %d matching endpoints: %#v", len(e.Endpoints), e.Endpoints)
} |
package sandglass
import (
"fmt"
"github.com/hashicorp/serf/serf"
"github.com/sandglass/sandglass-grpc/go/sgproto"
"google.golang.org/grpc"
)
type Node struct {
ID string
Name string
IP string
GRPCAddr string
RAFTAddr string
HTTPAddr string
Status serf.MemberStatus
conn *grpc.ClientConn
sgproto.BrokerServiceClient
sgproto.InternalServiceClient
}
func (n *Node) Dial() (err error) {
n.conn, err = grpc.Dial(n.GRPCAddr, grpc.WithInsecure())
if err != nil {
return err
}
n.BrokerServiceClient = sgproto.NewBrokerServiceClient(n.conn)
n.InternalServiceClient = sgproto.NewInternalServiceClient(n.conn)
return nil
}
func (n *Node) Close() error {
if n.conn == nil {
return nil
}
if err := n.conn.Close(); err != nil {
return err
}
n.conn = nil
return nil
}
func (n *Node) String() string {
return fmt.Sprintf("%s(%s)", n.Name, n.GRPCAddr)
}
func (n *Node) IsAlive() bool | {
return n.conn != nil
} |
package gorm
import (
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
type GR struct {
DB *gorm.DB
ServerInfo
}
type ServerInfo struct {
host string
port uint16
dbname string
user string
pass string
}
var dbInfo GR
func New(host, dbname, user, pass string, port uint16) error {
var err error
if dbInfo.DB == nil {
dbInfo.host = host
dbInfo.port = port
dbInfo.dbname = dbname
dbInfo.user = user
dbInfo.pass = pass
dbInfo.DB, err = dbInfo.Connection()
}
if err != nil {
return err
}
return nil
}
func GetDB() *GR {
if dbInfo.DB == nil {
panic(errors.New("DB instance is nil"))
}
return &dbInfo
}
func (gr *GR) Connection() (*gorm.DB, error) {
return gorm.Open("mysql", gr.getDsn())
}
func (gr *GR) Close() {
gr.DB.Close()
}
func (gr *GR) getDsn() string | {
param := "?charset=utf8&parseTime=True&loc=Local"
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s%s",
gr.user, gr.pass, gr.host, gr.port, gr.dbname, param)
} |
package cluster_health
import (
"fmt"
"os"
"testing"
mbtest "github.com/elastic/beats/metricbeat/mb/testing"
)
func TestData(t *testing.T) {
f := mbtest.NewEventFetcher(t, getConfig())
err := mbtest.WriteEvent(f, t)
if err != nil {
t.Fatal("write", err)
}
}
func getConfig() map[string]interface{} {
return map[string]interface{}{
"module": "ceph",
"metricsets": []string{"cluster_health"},
"hosts": getTestCephHost(),
}
}
const (
cephDefaultHost = "127.0.0.1"
cephDefaultPort = "5000"
)
func getTestCephHost() string {
return fmt.Sprintf("%v:%v",
getenv("CEPH_HOST", cephDefaultHost),
getenv("CEPH_PORT", cephDefaultPort),
)
}
func getenv(name, defaultValue string) string {
return strDefault(os.Getenv(name), defaultValue)
}
func strDefault(a, defaults string) string | {
if len(a) == 0 {
return defaults
}
return a
} |
package config
import (
"encoding/json"
"io/ioutil"
"github.com/hauke96/sigolo"
)
type ConfigLoader struct {
topicConfig *TopicConfig
serverConfig *ServerConfig
}
func (cl *ConfigLoader) loadTopics(filename string) {
data, err := ioutil.ReadFile(filename)
if err != nil {
sigolo.Error("Error reading " + filename)
sigolo.Error("\n\nAhhh, *urg*, I'm sorry but there was a really bad error inside of me. Above the stack trace is a message marked with [FATAL], you'll find some information there.\nIf not, feel free to contact my maker via:\n\n goms@hauke-stieler.de\n\nI hope my death .. . eh ... crash is only an exception and will be fixed soon ... my power ... leaves me ... good bye ... x.x")
sigolo.Error(err.Error())
}
cl.topicConfig = &TopicConfig{}
json.Unmarshal(data, cl.topicConfig)
}
func (cl *ConfigLoader) GetConfig() Config {
return Config{
TopicConfig: *cl.topicConfig,
ServerConfig: *cl.serverConfig,
}
}
func (cl *ConfigLoader) LoadConfig(filename string) | {
data, err := ioutil.ReadFile(filename)
if err != nil {
sigolo.Error("Error reading " + filename)
sigolo.Error("\n\nAhhh, *urg*, I'm sorry but there was a really bad error inside of me. Above the stack trace is a message marked with [FATAL], you'll find some information there.\nIf not, feel free to contact my maker via:\n\n goms@hauke-stieler.de\n\nI hope my death .. . eh ... crash is only an exception and will be fixed soon ... my power ... leaves me ... good bye ... x.x")
sigolo.Fatal(err.Error())
}
cl.serverConfig = &ServerConfig{}
json.Unmarshal(data, cl.serverConfig)
cl.loadTopics(cl.serverConfig.TopicLocation)
} |
package rancher
import (
"github.com/Sirupsen/logrus"
"github.com/docker/libcompose/logger"
"github.com/docker/libcompose/lookup"
"github.com/docker/libcompose/project"
)
func NewProject(context *Context) (*project.Project, error) | {
context.ConfigLookup = &lookup.FileConfigLookup{}
context.EnvironmentLookup = &lookup.OsEnvLookup{}
context.LoggerFactory = logger.NewColorLoggerFactory()
context.ServiceFactory = &RancherServiceFactory{
Context: context,
}
p := project.NewProject(&context.Context)
err := p.Parse()
if err != nil {
return nil, err
}
if err = context.open(); err != nil {
logrus.Errorf("Failed to open project %s: %v", p.Name, err)
return nil, err
}
context.SidekickInfo = NewSidekickInfo(p)
return p, err
} |
package command
import (
"fmt"
"os"
"github.com/coreos/etcd/client"
)
const (
ExitSuccess = iota
ExitError
ExitBadConnection
ExitInvalidInput
ExitBadFeature
ExitInterrupted
ExitIO
ExitBadArgs = 128
)
func ExitWithError(code int, err error) | {
fmt.Fprintln(os.Stderr, "Error:", err)
if cerr, ok := err.(*client.ClusterError); ok {
fmt.Fprintln(os.Stderr, cerr.Detail())
}
os.Exit(code)
} |
package cmd
import (
"fmt"
"github.com/fatih/color"
out "github.com/plouc/go-gitlab-client/cli/output"
"github.com/plouc/go-gitlab-client/gitlab"
"github.com/spf13/cobra"
)
func fetchSshKeys() {
color.Yellow("Fetching current user ssh keys…")
o := &gitlab.PaginationOptions{}
o.Page = page
o.PerPage = perPage
loader.Start()
collection, meta, err := client.CurrentUserSshKeys(o)
loader.Stop()
if err != nil {
fmt.Println(err.Error())
return
}
if len(collection.Items) == 0 {
color.Red("No ssh key found")
} else {
out.SshKeys(output, outputFormat, collection)
}
printMeta(meta, true)
handlePaginatedResult(meta, fetchSshKeys)
}
var listSshKeysCmd = &cobra.Command{
Use: "ssh-keys",
Aliases: []string{"sk"},
Short: "List current user ssh keys",
Run: func(cmd *cobra.Command, args []string) {
fetchSshKeys()
},
}
func init() | {
listCmd.AddCommand(listSshKeysCmd)
} |
package tests
import (
"context"
"fmt"
"math/rand"
"net/http"
"os"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
var (
client *github.Client
auth bool
)
func init() {
token := os.Getenv("GITHUB_AUTH_TOKEN")
if token == "" {
print("!!! No OAuth token. Some tests won't run. !!!\n\n")
client = github.NewClient(nil)
} else {
tc := oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
))
client = github.NewClient(tc)
auth = true
}
vars := []string{envKeyGitHubUsername, envKeyGitHubPassword, envKeyClientID, envKeyClientSecret}
for _, v := range vars {
value := os.Getenv(v)
if value == "" {
print("!!! " + fmt.Sprintf(msgEnvMissing, v) + " !!!\n\n")
}
}
}
func checkAuth(name string) bool {
if !auth {
fmt.Printf("No auth - skipping portions of %v\n", name)
}
return auth
}
func createRandomTestRepository(owner string, autoinit bool) (*github.Repository, error) | {
var repoName string
for {
repoName = fmt.Sprintf("test-%d", rand.Int())
_, resp, err := client.Repositories.Get(owner, repoName)
if err != nil {
if resp.StatusCode == http.StatusNotFound {
break
}
return nil, err
}
}
repo, _, err := client.Repositories.Create("", &github.Repository{Name: github.String(repoName), AutoInit: github.Bool(autoinit)})
if err != nil {
return nil, err
}
return repo, nil
} |
package assets
import (
"fmt"
)
const (
analyticsScript = `<script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', %s);
ga('send', 'pageview');</script>`
)
func init() {
Register("analytics", googleAnalytics)
}
func googleAnalytics(m *Manager, names []string, options Options) ([]*Asset, error) | {
if len(names) != 1 && len(names) != 2 {
return nil, fmt.Errorf("analytics requires either 1 or 2 arguments (either \"UA-XXXXXX-YY, mysite.com\" or just \"UA-XXXXXX-YY\" - without quotes in both cases")
}
key := names[0]
if key == "" {
return nil, nil
}
var arg string
if len(names) == 2 {
arg = fmt.Sprintf("'%s', '%s'", key, names[1])
} else {
arg = fmt.Sprintf("'%s'", key)
}
return []*Asset{
&Asset{
Name: "google-analytics.js",
Position: Bottom,
HTML: fmt.Sprintf(analyticsScript, arg),
},
}, nil
} |
package conway
import (
"fmt"
)
func Example_singleCell() {
var p = Population{cells: map[Cell]int{
Cell{0, 0}: 0,
},
popNumber: 0,
}
p.Next()
fmt.Println(p)
}
func Example_twoCells() {
var p = Population{cells: map[Cell]int{
Cell{0, 0}: 0,
Cell{0, 1}: 0,
},
popNumber: 0,
}
p.Next()
fmt.Println(p)
}
func Example_blinker() | {
var p = Population{cells: map[Cell]int{
Cell{0, 0}: 0,
Cell{0, 1}: 0,
Cell{0, -1}: 0,
},
popNumber: 0,
}
p.SaveToFile("blinker0.log")
p.Next()
p.SaveToFile("blinker1.log")
fmt.Println(len(p.cells))
} |
package handle
import (
"net/http"
)
type HTTPErrorPipeline struct {
Code int
Message string
Global GlobalPipeline
}
func ReturnError(w http.ResponseWriter, code int) int {
w.WriteHeader(code)
tpl, _ := OpenTemplate(ERROR_TPL)
tpl.Execute(w, NewError(code, http.StatusText(code)))
return code
}
func NewError(code int, message string) HTTPErrorPipeline | {
return HTTPErrorPipeline{
Code: code,
Message: message,
Global: DefaultGlobalPipeline,
}
} |
package rest
type Method int
const (
GET Method = 1 + iota
POST
PUT
DELETE
)
var method = [...]string{
"GET",
"POST",
"PUT",
"DELETE",
}
func (m Method) String() string | { return method[m-1] } |
package commons
import "net/http"
func HttpUnauthorized(w http.ResponseWriter) {
HttpError(w, http.StatusUnauthorized)
}
func HttpBadRequest(w http.ResponseWriter) {
HttpError(w, http.StatusBadRequest)
}
func HttpError(w http.ResponseWriter, code int) {
http.Error(w, http.StatusText(code), code)
}
func HttpCheckError(err error, status int, w http.ResponseWriter) {
if err != nil {
HttpError(w, status)
}
}
func HttpNoContent(w http.ResponseWriter) | {
HttpError(w, http.StatusNoContent)
} |
package etcd2
import (
"fmt"
"time"
"github.com/coreos/etcd/client"
"golang.org/x/net/context"
)
type Etcd2Connect struct {
etcd2 client.Client
}
func NewEtcd2Connect(etcd2EndPoint string) (*Etcd2Connect, error) {
c, err := client.New(client.Config{
Endpoints: []string{fmt.Sprintf("http://%s", etcd2EndPoint)},
Transport: client.DefaultTransport,
HeaderTimeoutPerRequest: time.Second,
})
if err != nil {
return nil, err
}
return &Etcd2Connect{etcd2: c}, nil
}
func (e *Etcd2Connect) Set(data map[string]string) error {
kapi := client.NewKeysAPI(e.etcd2)
for k, v := range data {
if _, err := kapi.Set(context.Background(), k, v, nil); err != nil {
return err
}
}
return nil
}
func (e *Etcd2Connect) Get(data map[string]string) (map[string]string, error) {
kapi := client.NewKeysAPI(e.etcd2)
result := make(map[string]string)
for k := range data {
resp, err := kapi.Get(context.Background(), k, nil)
if err != nil {
return nil, err
}
result[k] = resp.Node.Value
}
return result, nil
}
func (e *Etcd2Connect) Make(data map[string]string) error | {
kapi := client.NewKeysAPI(e.etcd2)
opts := &client.SetOptions{PrevExist: client.PrevNoExist}
for k, v := range data {
if _, err := kapi.Set(context.Background(), k, v, opts); err != nil {
return err
}
}
return nil
} |
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/APTrust/bagman/bagman"
"github.com/APTrust/bagman/workers"
"io/ioutil"
"os"
)
func main() {
jsonFile := flag.String("file", "", "JSON file to load")
procUtil := workers.CreateProcUtil("aptrust")
procUtil.MessageLog.Info("apt_retry started")
bagRecorder := workers.NewBagRecorder(procUtil)
if jsonFile == nil {
fmt.Println("apt_retry tries to re-send metadata to Fluctus")
fmt.Println("Usage: apt_retry -file=path/to/file.json -config=some_config")
os.Exit(0)
}
fmt.Println(*jsonFile)
result := loadJsonFile(*jsonFile)
result.ErrorMessage = ""
bagRecorder.RunWithoutNsq(result)
}
func loadJsonFile(jsonFile string) (*bagman.ProcessResult) | {
bytes, err := ioutil.ReadFile(jsonFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot read file '%s': %v\n", jsonFile, err)
os.Exit(1)
}
var result bagman.ProcessResult
err = json.Unmarshal(bytes, &result)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot convert JSON to object: %v\n", err)
os.Exit(1)
}
return &result
} |
package core
import (
"fmt"
"github.com/spf13/viper"
)
type writeStdout struct {
}
func (s *writeStdout) Write(dirname, filename, content, contentType, contentEncoding string,
metadata map[string]*string) error {
fmt.Printf("--- %s/%s ---\n", dirname, filename)
fmt.Printf("%s\n", content)
return nil
}
func NewWriteStdout(cfg *viper.Viper) (interface{}, error) | {
return &writeStdout{}, nil
} |
package even
func Even(i int) bool | {
return i%2 == 0
} |
package fabric
func contains(s []DGNode, i DGNode) bool {
for _, v := range s {
if i.ID() == v.ID() {
return true
}
}
return false
}
func ContainsNode(l NodeList, n Node) bool {
for _, v := range l {
if v.ID() == n.ID() {
return true
}
}
return false
}
func ContainsEdge(l EdgeList, e Edge) bool {
for _, v := range l {
if v.ID() == e.ID() {
return true
}
}
return false
}
func containsVirtual(s []Virtual, i Virtual) bool | {
for _, v := range s {
if i.ID() == v.ID() {
return true
}
}
return false
} |
package command
import (
"fmt"
"io/ioutil"
"os"
"path"
"runtime"
"time"
getter "github.com/hashicorp/go-getter"
"github.com/hashicorp/nomad/helper/discover"
)
func fetchBinary(bin string) (string, error) {
nomadBinaryDir, err := ioutil.TempDir("", "")
if err != nil {
return "", fmt.Errorf("failed to create temp dir: %v", err)
}
if bin == "" {
bin, err = discover.NomadExecutable()
if err != nil {
return "", fmt.Errorf("failed to discover nomad binary: %v", err)
}
}
dest := path.Join(nomadBinaryDir, "nomad")
if runtime.GOOS == "windows" {
dest = dest + ".exe"
}
if err = getter.GetFile(dest, bin); err != nil {
return "", fmt.Errorf("failed to get nomad binary: %v", err)
}
return nomadBinaryDir, nil
}
func procWaitTimeout(p *os.Process, d time.Duration) error | {
stop := make(chan struct{})
go func() {
p.Wait()
stop <- struct{}{}
}()
select {
case <-stop:
return nil
case <-time.NewTimer(d).C:
return fmt.Errorf("timeout waiting for process %d to exit", p.Pid)
}
} |
package main
import (
"fmt"
)
type ListOfInt []int
type IntMonad struct {
NeutralElement int
AssocFunc func(int, int) int
}
func main() {
var list = ListOfInt{-2, -1, 2, 2, 3}
monad := IntMonad{0, func(x, y int) int { return x + y }}
fmt.Printf("List %v: Fold(monad) yields %v\n", list, list.Fold(monad))
}
func (list ListOfInt) Fold(monad IntMonad) int | {
out := monad.NeutralElement
for _, i := range list {
out = monad.AssocFunc(out, i)
}
return out
} |
package datasource
import (
"fmt"
"time"
"github.com/golang/glog"
cadvisorClient "github.com/google/cadvisor/client"
cadvisor "github.com/google/cadvisor/info/v1"
"k8s.io/heapster/sources/api"
)
type cadvisorSource struct{}
func (self *cadvisorSource) getAllContainers(client *cadvisorClient.Client, start, end time.Time) (subcontainers []*api.Container, root *api.Container, err error) {
allContainers, err := client.SubcontainersInfo("/",
&cadvisor.ContainerInfoRequest{Start: start, End: end})
if err != nil {
return nil, nil, err
}
for _, containerInfo := range allContainers {
container := self.parseStat(&containerInfo)
if containerInfo.Name == "/" {
root = container
} else {
subcontainers = append(subcontainers, container)
}
}
return subcontainers, root, nil
}
func (self *cadvisorSource) GetAllContainers(host Host, start, end time.Time) (subcontainers []*api.Container, root *api.Container, err error) {
url := fmt.Sprintf("http:%s:%d/", host.IP, host.Port)
client, err := cadvisorClient.NewClient(url)
if err != nil {
return
}
subcontainers, root, err = self.getAllContainers(client, start, end)
if err != nil {
glog.Errorf("failed to get stats from cadvisor %q - %v\n", url, err)
}
return
}
func (self *cadvisorSource) parseStat(containerInfo *cadvisor.ContainerInfo) *api.Container | {
container := &api.Container{
Name: containerInfo.Name,
Spec: containerInfo.Spec,
Stats: sampleContainerStats(containerInfo.Stats),
}
if len(containerInfo.Aliases) > 0 {
container.Name = containerInfo.Aliases[0]
}
return container
} |
package indexdb
import (
"fmt"
"github.com/eleme/banshee/models"
"github.com/eleme/banshee/util"
)
func encode(idx *models.Index) []byte {
score := util.ToFixed(idx.Score, 5)
average := util.ToFixed(idx.Average, 5)
s := fmt.Sprintf("%d:%s:%s", idx.Stamp, score, average)
return []byte(s)
}
func decode(value []byte, idx *models.Index) error | {
n, err := fmt.Sscanf(string(value), "%d:%f:%f", &idx.Stamp, &idx.Score, &idx.Average)
if err != nil {
return err
}
if n != 3 {
return ErrCorrupted
}
return nil
} |
package server
import (
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/gorilla/websocket"
)
func TestWsHandler(t *testing.T) {
expectedResponse := []byte("acknowledged")
server := httptest.NewServer(serverEngine())
defer server.Close()
URL, err := url.Parse(server.URL + "/ws")
if err != nil {
t.Errorf("could not parse server URL: %s", err)
}
URL.Scheme = "ws"
conn, _, err := websocket.DefaultDialer.Dial(URL.String(), nil)
if err != nil {
t.Errorf("expected to create websocket connection with success instead: %s", err)
}
if err := conn.WriteMessage(websocket.TextMessage, []byte("test")); err != nil {
t.Errorf("could not write message: %s", err)
}
_, observed, err := conn.ReadMessage()
if err != nil {
t.Errorf("cannot read message: %v", err)
}
if string(observed) != string(expectedResponse) {
t.Errorf("expected server response: %s, observed: %s",
string(expectedResponse), string(observed))
}
}
func TestIndexHandler(t *testing.T) | {
server := httptest.NewServer(serverEngine())
defer server.Close()
resp, err := http.Get(server.URL)
if err != nil {
t.Errorf("could not make get request to server")
}
expectedStatus := 200
if resp.StatusCode != expectedStatus {
t.Errorf("expected status code: %d, observed: %d",
resp.StatusCode, expectedStatus)
}
} |
package service
import (
"context"
"sync"
"go-common/app/service/main/assist/conf"
"go-common/app/service/main/assist/dao/account"
"go-common/app/service/main/assist/dao/assist"
"go-common/app/service/main/assist/dao/message"
"go-common/library/log"
"go-common/library/queue/databus"
)
type Service struct {
c *conf.Config
ass *assist.Dao
acc *account.Dao
msg *message.Dao
relationSub *databus.Databus
cacheChan chan func()
wg sync.WaitGroup
}
func (s *Service) Ping(c context.Context) (err error) {
if err = s.ass.Ping(c); err != nil {
log.Error("s.ass.Dao.Ping err(%v)", err)
}
return
}
func (s *Service) asyncCache(f func()) {
select {
case s.cacheChan <- f:
default:
log.Warn("assist cacheproc chan full")
}
}
func (s *Service) cacheproc() {
for {
f := <-s.cacheChan
f()
}
}
func (s *Service) Close() {
s.relationSub.Close()
s.wg.Wait()
}
func New(c *conf.Config) *Service | {
s := &Service{
c: c,
ass: assist.New(c),
acc: account.New(c),
msg: message.New(c),
cacheChan: make(chan func(), 1024),
relationSub: databus.New(c.RelationSub),
}
s.wg.Add(1)
go s.relationConsumer()
s.wg.Add(1)
go s.cacheproc()
return s
} |
package instructions
import (
"fmt"
"github.com/bongo227/goory/types"
"github.com/bongo227/goory/value"
)
type CondBr struct {
block value.Value
name string
condition value.Value
trueBlock value.Value
falseBlock value.Value
}
func NewCondBr(block value.Value, name string, condition value.Value, trueBlock value.Value, falseBlock value.Value) *CondBr {
if !condition.Type().Equal(types.NewBoolType()) {
panic("condition is not a bool type")
}
if !trueBlock.Type().Equal(types.NewBlockType()) {
panic("trueBlock is not a block type")
}
if !falseBlock.Type().Equal(types.NewBlockType()) {
panic("falseBlock is not a block type")
}
return &CondBr{block, name, condition, trueBlock, falseBlock}
}
func (i *CondBr) Block() value.Value {
return i.block
}
func (i *CondBr) IsTerminator() bool {
return true
}
func (i *CondBr) Ident() string {
return "%" + i.name
}
func (i *CondBr) Llvm() string {
return fmt.Sprintf("br i1 %s, label %%%s, label %%%s",
i.condition.Ident(),
i.trueBlock.Ident(),
i.falseBlock.Ident())
}
func (i *CondBr) Type() types.Type | {
return types.VOID
} |
package bsu
import (
"crypto/tls"
"net/http"
"testing"
"github.com/hashicorp/packer/builder/osc/common"
builderT "github.com/hashicorp/packer/helper/builder/testing"
"github.com/outscale/osc-go/oapi"
)
func TestBuilderAcc_basic(t *testing.T) {
builderT.Test(t, builderT.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Builder: &Builder{},
Template: testBuilderAccBasic,
SkipArtifactTeardown: true,
})
}
func testAccPreCheck(t *testing.T) {
}
const testBuilderAccBasic = `
{
"builders": [{
"type": "test",
"region": "eu-west-2",
"vm_type": "t2.micro",
"source_omi": "ami-65efcc11",
"ssh_username": "outscale",
"omi_name": "packer-test {{timestamp}}"
}]
}
`
func testOAPIConn() (*oapi.Client, error) | {
access := &common.AccessConfig{RawRegion: "us-east-1"}
clientConfig, err := access.Config()
if err != nil {
return nil, err
}
skipClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
return oapi.NewClient(clientConfig, skipClient), nil
} |
package app
import (
"fmt"
"net/http"
)
type collect struct{
url string
controller func(w http.ResponseWriter, r *http.Request) bool
}
func render(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "text/html")
routes := Routes()
url := r.URL.Path
for _, element := range routes{
if url == element.url {
element.controller(w, r)
return
}
}
fmt.Fprintf(w, "<h1>Error 404</h1>")
}
func api(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "application/json")
routes := Routes()
url := r.URL.Path
for _, element := range routes{
if url == element.url {
element.controller(w, r)
return
}
}
fmt.Fprintf(w, "{\"error\":true}")
}
func Server(port int, host string) | {
mux := http.NewServeMux()
mux.HandleFunc( "/" , func(w http.ResponseWriter, r *http.Request){
render(w, r)
})
mux.HandleFunc( "/api/" , func(w http.ResponseWriter, r *http.Request){
api(w, r)
})
println( fmt.Sprintf("Starting exodo server on port %d", port))
http.ListenAndServe(fmt.Sprintf("%s:%d",host, port), mux)
} |
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 }
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
}
func (err CannotXContainerError) ErrorName() string | {
return "Cannot" + err.transition + "ContainerError"
} |
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 Date() string {
return time.Now().Format("2006-01-02")
}
func Datetime() string {
return time.Now().Format("2006-01-02 15:04:05")
}
func Format(format string, timestamps ...int64) string {
timestamp := Second()
if len(timestamps) > 0 {
timestamp = timestamps[0]
}
return time.Unix(timestamp, 0).Format(format)
}
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 Second() int64 | {
return time.Now().UnixNano() / 1e9
} |
package iso
import (
"context"
"fmt"
"log"
"github.com/hashicorp/packer-plugin-sdk/multistep"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
parallelscommon "github.com/hashicorp/packer/builder/parallels/common"
)
type stepAttachISO struct{}
func (s *stepAttachISO) Cleanup(state multistep.StateBag) {
if _, ok := state.GetOk("attachedIso"); !ok {
return
}
driver := state.Get("driver").(parallelscommon.Driver)
ui := state.Get("ui").(packersdk.Ui)
vmName := state.Get("vmName").(string)
log.Println("Detaching ISO from the default CD/DVD ROM device...")
command := []string{
"set", vmName,
"--device-set", "cdrom0",
"--image", "", "--disconnect", "--enable",
}
if err := driver.Prlctl(command...); err != nil {
ui.Error(fmt.Sprintf("Error detaching ISO: %s", err))
}
}
func (s *stepAttachISO) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction | {
driver := state.Get("driver").(parallelscommon.Driver)
isoPath := state.Get("iso_path").(string)
ui := state.Get("ui").(packersdk.Ui)
vmName := state.Get("vmName").(string)
ui.Say("Attaching ISO to the default CD/DVD ROM device...")
command := []string{
"set", vmName,
"--device-set", "cdrom0",
"--image", isoPath,
"--enable", "--connect",
}
if err := driver.Prlctl(command...); err != nil {
err := fmt.Errorf("Error attaching ISO: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
state.Put("attachedIso", true)
return multistep.ActionContinue
} |
package tempconv
import "testing"
func TestFToC(t *testing.T) {
var f Fahrenheit = 95
c := FToC(f)
if c != Celsius(35) {
t.Errorf(`FToC(%g) == %g failed`, f, c)
}
}
func TestCToK(t *testing.T) {
var c Celsius = 37
k := CToK(c)
if k != Kelvin(310.15) {
t.Errorf(`CToK(%g) == %g failed`, c, k)
}
}
func TestKToC(t *testing.T) {
var k Kelvin = 1000
c := KToC(k)
if c != Celsius(726.85) {
t.Errorf(`KToC(%g) == %g failed`, k, c)
}
}
func TestCToF(t *testing.T) | {
var c Celsius = 37
f := CToF(c)
if f != Fahrenheit(98.6) {
t.Errorf(`CToF(%g) == %g failed`, c, f)
}
} |
package fasthttpradix
import (
"github.com/valyala/fasthttp"
rr "github.com/byte-mug/golibs/radixroute"
"strings"
)
func NormPath(str string) string {
return "/"+strings.Trim(str,"/")+"/"
}
func InvalidPath(ctx *fasthttp.RequestCtx) {
ctx.SetBody([]byte("404 Not Found\n"))
ctx.SetStatusCode(fasthttp.StatusNotFound)
}
type handling struct{
handle fasthttp.RequestHandler
}
type Router struct{
routes map[string]*rr.Tree
}
func (r *Router) getOrCreate(m string) *rr.Tree {
t := r.routes[m]
if t!=nil { return t }
if r.routes==nil { r.routes = make(map[string]*rr.Tree) }
r.routes[m] = rr.New()
return r.routes[m]
}
func (r *Router) Handle(method string,path string,handler fasthttp.RequestHandler) {
if handler==nil { panic("handler must not be nil") }
h := &handling{handler}
cpath := []byte(NormPath(path))
bpath := cpath[:len(cpath)-1]
if method=="" {
method = "DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT"
}
for _,m := range strings.Split(method,",") {
rrt := r.getOrCreate(m)
rrt.InsertRoute(bpath,h)
rrt.InsertRoute(cpath,h)
}
}
func (r *Router) RequestHandler(ctx *fasthttp.RequestCtx) | {
t := r.routes[string(ctx.Method())]
if t==nil {
InvalidPath(ctx)
return
}
i,_ := t.Get(ctx.Path(),ctx.SetUserValue)
h,ok := i.(*handling)
if !ok {
InvalidPath(ctx)
return
}
h.handle(ctx)
} |
package validator
import (
"fmt"
"github.com/pivotal-cf/pivnet-resource/concourse"
)
type CheckValidator struct {
input concourse.CheckRequest
}
func NewCheckValidator(input concourse.CheckRequest) *CheckValidator {
return &CheckValidator{
input: input,
}
}
func (v CheckValidator) Validate() error | {
if v.input.Source.APIToken == "" {
return fmt.Errorf("%s must be provided", "api_token")
}
if v.input.Source.ProductSlug == "" {
return fmt.Errorf("%s must be provided", "product_slug")
}
return nil
} |
package multiwriter
import (
"io"
)
type multiWriter []io.Writer
func New(w ...io.Writer) io.Writer {
return multiWriter(w)
}
func send(w io.Writer, p []byte, done chan<- result) {
var res result
res.n, res.err = w.Write(p)
if res.n < len(p) && res.err == nil {
res.err = io.ErrShortWrite
}
done <- res
}
type result struct {
n int
err error
}
func (mw multiWriter) Write(p []byte) (int, error) | {
done := make(chan result, len(mw))
for _, w := range mw {
go send(w, p, done)
}
endResult := result{n: len(p)}
for _ = range mw {
res := <-done
if res.err != nil && (endResult.err == nil || res.n < endResult.n) {
endResult = res
}
}
return endResult.n, endResult.err
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.