// +build amd64,darwin

package copy

import (
	"os"
	"syscall"
	"time"
)

func getTimeSpec(info os.FileInfo) timespec {
	stat := info.Sys().(*syscall.Stat_t)
	times := timespec{
		Mtime: info.ModTime(),
		Atime: time.Unix(stat.Atimespec.Sec, stat.Atimespec.Nsec),
		Ctime: time.Unix(stat.Ctimespec.Sec, stat.Ctimespec.Nsec),
	}
	return times
}

// +build darwin

package copy

import (
	"os"
	"syscall"
	"time"
)

func getTimeSpec(info os.FileInfo) timespec {
	stat := info.Sys().(*syscall.Stat_t)
	times := timespec{
		Mtime: info.ModTime(),
		Atime: time.Unix(stat.Atimespec.Sec, stat.Atimespec.Nsec),
		Ctime: time.Unix(stat.Ctimespec.Sec, stat.Ctimespec.Nsec),
	}
	return times
}

Fix build on Apple Silicon


package main

import (
	"reflect"
	"regexp"
	"testing"
)

var genMatcherTests = []struct {
	src string
	dst *regexp.Regexp
}{
	{"abc", regexp.MustCompile(`(abc)`)},
	{"abcdef", regexp.MustCompile(`(abcdef)`)},

	{"a,b", regexp.MustCompile(`(a|b)`)},
	{"a,bc,def", regexp.MustCompile(`(a|bc|def)`)},

	{"a\\,b", regexp.MustCompile(`(a,b)`)},
	{"a\\,bc\\,def", regexp.MustCompile(`(a,bc,def)`)},

	{"a\\,b,c", regexp.MustCompile(`(a,b|c)`)},
	{"a,bc\\,def", regexp.MustCompile(`(a|bc,def)`)},
}

func TestGenMatcher(t *testing.T) {
	for _, test := range genMatcherTests {
		expect := test.dst
		actual, err := newMatcher(test.src)
		if err != nil {
			t.Errorf("NewSubvert(%q) returns %q, want nil",
				test.src, err)
		}
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("%q: got %q, want %q",
				test.src, actual, expect)
		}
	}
}

package main

import (
	"reflect"
	"regexp"
	"testing"
)

var genMatcherTests = []struct {
	src string
	dst *regexp.Regexp
}{
	{`abc`, regexp.MustCompile(`(abc)`)},
	{`abcdef`, regexp.MustCompile(`(abcdef)`)},

	{`a,b`, regexp.MustCompile(`(a|b)`)},
	{`a,bc,def`, regexp.MustCompile(`(a|bc|def)`)},

	{`a\,b`, regexp.MustCompile(`(a,b)`)},
	{`a\,bc\,def`, regexp.MustCompile(`(a,bc,def)`)},

	{`a\,b,c`, regexp.MustCompile(`(a,b|c)`)},
	{`a,bc\,def`, regexp.MustCompile(`(a|bc,def)`)},
}

func TestGenMatcher(t *testing.T) {
	for _, test := range genMatcherTests {
		expect := test.dst
		actual, err := newMatcher(test.src)
		if err != nil {
			t.Errorf("NewSubvert(%q) returns %q, want nil",
				test.src, err)
		}
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("%q: got %q, want %q",
				test.src, actual, expect)
		}
	}
}

Use backquote in tests in newMatcherTests


package oauth

import (
	"bytes"
	"fmt"
)

var hex = "0123456789ABCDEF"

// encode percent-encodes a string as defined in RFC 3986.
func encode(s string) string {
	var buf bytes.Buffer
	for _, c := range []byte(s) {
		if isEncodable(c) {
			buf.WriteByte('%')
			buf.WriteByte(hex[c>>4])
			buf.WriteByte(hex[c&15])
		} else {
			buf.WriteByte(c)
		}
	}
	return buf.String()
}

func encodeQuoted(key, value string) string {
	return fmt.Sprintf("%s=\"%s\"", encode(key), encode(value))
}

// isEncodable returns true if a given character should be percent-encoded
// according to RFC 3986.
func isEncodable(c byte) bool {
	// return false if c is an unreserved character (see RFC 3986 section 2.3)
	switch {
	case (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'):
		return false
	case c >= '0' && c <= '9':
		return false
	case c == '-' || c == '.' || c == '_' || c == '~':
		return false
	}
	return true
}

package oauth

import (
	"bytes"
	"fmt"
)

var hex = "0123456789ABCDEF"

// encode percent-encodes a string as defined in RFC 3986.
func encode(s string) string {
	var buf bytes.Buffer
	for _, c := range []byte(s) {
		if isEncodable(c) {
			if c == '+' {
				// replace plus-encoding with percent-encoding
				buf.WriteString("%2520")
			} else {
				buf.WriteByte('%')
				buf.WriteByte(hex[c>>4])
				buf.WriteByte(hex[c&15])
			}
		} else {
			buf.WriteByte(c)
		}
	}
	return buf.String()
}

func encodeQuoted(key, value string) string {
	return fmt.Sprintf("%s=\"%s\"", encode(key), encode(value))
}

// isEncodable returns true if a given character should be percent-encoded
// according to RFC 3986.
func isEncodable(c byte) bool {
	// return false if c is an unreserved character (see RFC 3986 section 2.3)
	switch {
	case (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'):
		return false
	case c >= '0' && c <= '9':
		return false
	case c == '-' || c == '.' || c == '_' || c == '~':
		return false
	}
	return true
}

Use percent encoding for calculating the signature


package registration

import (
	"github.com/opsee/portmapper"
)

const (
	ipFilePathDefault = "/gozer/state/ip"
	nsqdTopic         = "connected"
)

var (
	// The location of the file produced by OpenVPN containing the instance IP.
	IPFilePath string
)

func init() {
	IPFilePath = ipFilePathDefault
}

// /opsee.co/routes/customer_id/instance_id/svcname = ip:port

type connectedMessage struct {
	CustomerID string                `json:"customer_id"`
	BastionID  string                `json:"bastion_id"`
	InstanceID string                `json:"instance_id"`
	IPAddress  string                `json:"ip_address"`
	Services   []*portmapper.Service `json:"services"`
	Timestamp  int64                 `json:"timestamp"`
}

// Service provides registration with Opsee of components exposed by
// portmapper.
type Service interface {
	Start() error
	Stop() error
}

package registration

import (
	"github.com/opsee/portmapper"
)

const (
	ipFilePathDefault = "/gozer/state/ip"
	nsqdTopic         = "_.connected"
)

var (
	// The location of the file produced by OpenVPN containing the instance IP.
	IPFilePath string
)

func init() {
	IPFilePath = ipFilePathDefault
}

// /opsee.co/routes/customer_id/instance_id/svcname = ip:port

type connectedMessage struct {
	CustomerID string                `json:"customer_id"`
	BastionID  string                `json:"bastion_id"`
	InstanceID string                `json:"instance_id"`
	IPAddress  string                `json:"ip_address"`
	Services   []*portmapper.Service `json:"services"`
	Timestamp  int64                 `json:"timestamp"`
}

// Service provides registration with Opsee of components exposed by
// portmapper.
type Service interface {
	Start() error
	Stop() error
}

Send messages to broadcast connected topic.


package knsq

import (
	"io"
	"log"
	"net/http"
)

// FIXME: Use socket API instead of HTTP

// CreateTopic makes sure a topic exists on the given nsqd.
func CreateTopic(nsqd string, topic string) error {
	resp, err := http.Get("http://" + nsqd + "/create_topic?topic=" + topic)
	if resp != nil && resp.Body != nil {
		resp.Body.Close()
	}
	return err
}

// Send sends a message on a topic to the specified nsqd.
func Send(nsqd string, topic string, body io.Reader) error {
	reqURL := nsqd + "/put?topic=" + topic
	log.Printf("Sending %s message to: %s", topic, reqURL)
	resp, err := http.DefaultClient.Post(reqURL, "application/json", body)
	defer resp.Body.Close()
	return err
}

package knsq

import (
	"io"
	"log"
	"net/http"
	"net/url"
)

// TODO: Add socket implementation

type Client interface {
	// CreateTopic makes sure a topic exists on the given nsqd.
	CreateTopic(topic string) error
	// Send sends a message on a topic to the specified nsqd.
	Send(topic string, body io.Reader)
}

// HttpClient implements the Client interface using HTTP requests
type HttpClient struct {
	*url.URL
}

func (h HttpClient) CreateTopic(topic string) error {
	resp, err := http.Get(h.String() + "/create_topic?topic=" + topic)
	if resp != nil && resp.Body != nil {
		resp.Body.Close()
	}
	return err
}

func (h HttpClient) Send(topic string, body io.Reader) error {
	reqURL := h.String() + "/put?topic=" + topic
	log.Printf("Sending %s message to: %s", topic, reqURL)
	resp, err := http.DefaultClient.Post(reqURL, "application/json", body)
	if resp != nil && resp.Body != nil {
		defer resp.Body.Close()
	}
	return err
}

Refactor knsq to an interface


package srpc

import (
	"crypto/tls"
	"fmt"
	"os"
	"path"
	"strings"
)

func loadCertificates(directory string) ([]tls.Certificate, error) {
	dir, err := os.Open(directory)
	if err != nil {
		return nil, err
	}
	names, err := dir.Readdirnames(0)
	defer dir.Close()
	if err != nil {
		return nil, err
	}
	certs := make([]tls.Certificate, 0, len(names)/2)
	for _, name := range names {
		if !strings.HasSuffix(name, ".key") {
			continue
		}
		cert, err := tls.LoadX509KeyPair(
			path.Join(directory, name[:len(name)-3]+"cert"),
			path.Join(directory, name))
		if err != nil {
			return nil, fmt.Errorf("unable to load keypair: %s", err)
		}
		certs = append(certs, cert)
	}
	return certs, nil
}

package srpc

import (
	"crypto/tls"
	"fmt"
	"os"
	"path"
	"strings"
)

func loadCertificates(directory string) ([]tls.Certificate, error) {
	dir, err := os.Open(directory)
	if err != nil {
		return nil, err
	}
	names, err := dir.Readdirnames(0)
	defer dir.Close()
	if err != nil {
		return nil, err
	}
	certs := make([]tls.Certificate, 0, len(names)/2)
	for _, name := range names {
		if !strings.HasSuffix(name, ".key") {
			continue
		}
		cert, err := tls.LoadX509KeyPair(
			path.Join(directory, name[:len(name)-3]+"cert"),
			path.Join(directory, name))
		if err != nil {
			return nil, fmt.Errorf("unable to load keypair: %s", err)
		}
		certs = append(certs, cert)
	}
	if len(certs) < 1 {
		return nil, nil
	}
	return certs, nil
}

Return nil for empty cert slice in lib/srpc.LoadCertificates().


//go:build go1.18

package krpc

import (
	"testing"

	"github.com/anacrolix/torrent/bencode"
	qt "github.com/frankban/quicktest"
)

func Fuzz(f *testing.F) {
	f.Add([]byte("d1:rd2:id20:\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01e1:t1:t1:y1:re"))
	f.Fuzz(func(t *testing.T, b []byte) {
		c := qt.New(t)
		var m Msg
		err := bencode.Unmarshal(b, &m)
		if err != nil || m.T == "" || m.Y == "" {
			t.Skip()
		}
		if m.R != nil {
			if m.R.ID == [20]byte{} {
				c.Skip()
			}
		}
		b0, err := bencode.Marshal(m)
		c.Logf("%q -> %q", b, b0)
		c.Assert(err, qt.IsNil)
		c.Assert(string(b0), qt.Equals, string(b))
	})
}

//go:build go1.18
// +build go1.18

package krpc

import (
	"testing"

	"github.com/anacrolix/torrent/bencode"
	qt "github.com/frankban/quicktest"
)

func Fuzz(f *testing.F) {
	f.Add([]byte("d1:rd2:id20:\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01e1:t1:t1:y1:re"))
	f.Fuzz(func(t *testing.T, b []byte) {
		c := qt.New(t)
		var m Msg
		err := bencode.Unmarshal(b, &m)
		if err != nil || m.T == "" || m.Y == "" {
			t.Skip()
		}
		if m.R != nil {
			if m.R.ID == [20]byte{} {
				c.Skip()
			}
		}
		b0, err := bencode.Marshal(m)
		c.Logf("%q -> %q", b, b0)
		c.Assert(err, qt.IsNil)
		c.Assert(string(b0), qt.Equals, string(b))
	})
}

Add old-style build constraint for go1.16 compat


package scraper

import (
	"fmt"
	"os"
	"os/exec"
	"testing"
	"time"

	"github.com/pachyderm/pachyderm/src/client/pkg/require"
)

func TestScraper(t *testing.T) {
	wd, err := os.Getwd()
	require.NoError(t, err)
	fmt.Printf("wd: %s", wd)
	require.NoError(t, exec.Command("pachctl", "create-repo", "urls").Run())
	require.NoError(t, exec.Command("pachctl", "start-commit", "urls", "master").Run())
	putFileCmd := exec.Command("pachctl", "put-file", "urls", "master", "urls")
	urls, err := os.Open("urls")
	require.NoError(t, err)
	putFileCmd.Stdin = urls
	require.NoError(t, putFileCmd.Run())
	require.NoError(t, exec.Command("pachctl", "finish-commit", "urls", "master").Run())
	require.NoError(t, exec.Command("pachctl", "create-pipeline", "-f", "scraper.json").Run())
	time.Sleep(5 * time.Second)
	require.NoError(t, exec.Command("pachctl", "flush-commit", "urls/master").Run())
}

package scraper

import (
	"os"
	"os/exec"
	"testing"
	"time"

	"github.com/pachyderm/pachyderm/src/client/pkg/require"
)

func TestScraper(t *testing.T) {
	require.NoError(t, exec.Command("pachctl", "create-repo", "urls").Run())
	require.NoError(t, exec.Command("pachctl", "start-commit", "urls", "master").Run())
	putFileCmd := exec.Command("pachctl", "put-file", "urls", "master", "urls")
	urls, err := os.Open("urls")
	require.NoError(t, err)
	putFileCmd.Stdin = urls
	require.NoError(t, putFileCmd.Run())
	require.NoError(t, exec.Command("pachctl", "finish-commit", "urls", "master").Run())
	require.NoError(t, exec.Command("pachctl", "create-pipeline", "-f", "scraper.json").Run())
	time.Sleep(5 * time.Second)
	require.NoError(t, exec.Command("pachctl", "flush-commit", "urls/master").Run())
}

Remove debug print in test.


/*
  Demonstrate how to use channels and goroutines to keep the program alive.
  Iterate over a slice of numbers, passing each each i to a function
  that calculates the base10 log of i.
  We don't actually care what the return value is.
  Instead, the function just signals a channel that its work is done.

  Based on package documentation from golang.org.
  Code is licensed under a BSD license.
*/
package main

import (
	"fmt"
	"math/cmplx"
)

// print the decimal log of a number and signal completion
func getLog(c chan bool, i complex128) {
	fmt.Printf("%v Log: %v\n", i, cmplx.Log10(i)) // %v for any value
	c <- true                                     // Send signal to channel
}

func main() {
	// buffered channel of bool; doesn't need a receiver
	// this effectively makes the done channel a 'first in, first out' queue
	done := make(chan bool, 1)
	nums := []complex128{7, 8, cmplx.Sqrt(-9), 10} // slice literal

	for _, i := range nums { // _ = 0,1, ...; i = 7, 8, ...
		go getLog(done, i) // run getLog() as goroutine; don't wait for return
	}

	<-done // empty the 'done' channel, discarding its value
}

/*
  Demonstrate how to use channels and goroutines to keep the program alive.
  Iterate over a slice of numbers, passing each each i to a function
  that calculates the base10 log of i.
  We don't actually care what the return value is.
  Instead, the function just signals a channel that its work is done.

  Based on package documentation from golang.org.
  Code is licensed under a BSD license.
*/
package main

import (
	"fmt"
	"math/cmplx"
)

// print the decimal log of a number and signal completion
func getLog(c chan bool, i complex128) {
	fmt.Printf("%v Log: %v\n", i, cmplx.Log10(i)) // %v for any value
	c <- true                                     // Send signal to channel
}

func main() {
	// Buffered channel of bool.
	// Buffer size of 1 makes the done channel a semaphore.
	// All channels behave as a 'first in, first out' queue.
	done := make(chan bool, 1)
	nums := []complex128{7, 8, cmplx.Sqrt(-9), 10} // slice literal

	for _, i := range nums { // _ = 0,1, ...; i = 7, 8, ...
		go getLog(done, i) // run getLog() as goroutine; don't wait for return
	}

	<-done // empty the 'done' channel, discarding its value
}

Clarify demo code comment on channels


package entrevista_test

import (
	"fmt"

	"github.com/hoop33/entrevista"
)

func Example() {
	interview := entrevista.NewInterview()
	interview.ReadAnswer = func(question *entrevista.Question) (string, error) {
		return question.Key, nil
	}
	interview.Questions = []entrevista.Question{
		{
			Key:      "name",
			Text:     "Enter your name",
			Required: true,
		},
		{
			Key:           "email",
			Text:          "Enter your email address",
			DefaultAnswer: "john.doe@example.com",
		},
	}
	answers, err := interview.Run()

	if err == nil {
		for key, answer := range answers {
			fmt.Print(key, ":", answer, ";")
		}
	} else {
		fmt.Print(err.Error())
	}
	// Output: Enter your name: Enter your email address (john.doe@example.com): name:name;email:email;
}

package entrevista_test

import (
	"fmt"

	"github.com/hoop33/entrevista"
)

func Example() {
	interview := entrevista.NewInterview()
	interview.ReadAnswer = func(question *entrevista.Question) (string, error) {
		return question.Key, nil
	}
	interview.Questions = []entrevista.Question{
		{
			Key:      "name",
			Text:     "Enter your name",
			Required: true,
		},
		{
			Key:           "email",
			Text:          "Enter your email address",
			DefaultAnswer: "john.doe@example.com",
		},
	}
	answers, err := interview.Run()

	if err == nil {
		fmt.Print(answers["name"], ",", answers["email"])
	} else {
		fmt.Print(err.Error())
	}
	// Output: Enter your name: Enter your email address (john.doe@example.com): name,email
}

Fix example test--map iteration not ordered


package battery

import (
	"syscall"
	"unsafe"
)

var (
	modkernel32              = syscall.NewLazyDLL("kernel32")
	procGetSystemPowerStatus = modkernel32.NewProc("GetSystemPowerStatus")
)

type SYSTEM_POWER_STATUS struct {
	ACLineStatus        byte
	BatteryFlag         byte
	BatteryLifePercent  byte
	Reserved1           byte
	BatteryLifeTime     uint32
	BatteryFullLifeTime uint32
}

func Info() (int, bool, error) {
	var sps SYSTEM_POWER_STATUS
	_, r1, err := procGetSystemPowerStatus.Call(uintptr(unsafe.Pointer(&sps)))
	if r1 != 0 {
		if err != nil {
			return 0, false, err
		}
	}
	return int(sps.BatteryLifePercent), sps.ACLineStatus == 1, nil
}

package battery

import (
	"math"
	"syscall"
	"unsafe"
)

var (
	modkernel32              = syscall.NewLazyDLL("kernel32")
	procGetSystemPowerStatus = modkernel32.NewProc("GetSystemPowerStatus")
)

type SYSTEM_POWER_STATUS struct {
	ACLineStatus        byte
	BatteryFlag         byte
	BatteryLifePercent  byte
	Reserved1           byte
	BatteryLifeTime     uint32
	BatteryFullLifeTime uint32
}

func Info() (int, int, bool, error) {
	var sps SYSTEM_POWER_STATUS
	_, r1, err := procGetSystemPowerStatus.Call(uintptr(unsafe.Pointer(&sps)))
	if r1 != 0 {
		if err != nil {
			return 0, 0, false, err
		}
	}
	percent := int(sps.BatteryLifePercent)
	var elapsed int
	// BatteryLifeTime has MaxUint32 (2^32-1) when it cannot be detected.
	if sps.BatteryLifeTime != math.MaxUint32 {
		elapsed = int(float64(sps.BatteryLifeTime) / 60)
	}
	return percent, elapsed, sps.ACLineStatus == 1, nil
}

Add logic to show elapsed time in windows


package lru1

import "container/list"

type Item struct {
	key   string
	value string
}

type Cache struct {
	capacity int
	data     map[string]*list.Element
	lst      *list.List
}

func NewCache(capacity int) *Cache {
	cache := new(Cache)
	cache.capacity = capacity
	cache.data = make(map[string]*list.Element)
	return cache
}

func (c *Cache) Put(key, value string) {
	if len(c.data) == c.capacity {
		delete(c.data, c.lst.Back().Value.(*Item).key)
		c.lst.Remove(c.lst.Back())
	}
}

func (c *Cache) Get(key string) *Item {
	if c.data[key] != nil {
		c.lst.MoveToFront(c.data[key])
		return c.data[key].Value.(*Item)
	}
	return nil
}

// Package lru1 implement Least Recently Used based on doubly linked list.
package lru1

import "container/list"

// Item is an element in cache.
type Item struct {
	key   string
	value string
}

// Cache is a sized LRU cache.
type Cache struct {
	capacity int
	data     map[string]*list.Element
	lst      *list.List
}

// NewCache returns an initialized LRU cache.
func NewCache(capacity int) *Cache {
	cache := new(Cache)
	cache.capacity = capacity
	cache.data = make(map[string]*list.Element)
	return cache
}

// Put inserts new Item to cache.
// If cache is full removes oldest Item first.
func (c *Cache) Put(key, value string) {
	if len(c.data) == c.capacity {
		delete(c.data, c.lst.Back().Value.(*Item).key)
		c.lst.Remove(c.lst.Back())
	}
	c.data[key] = c.lst.PushFront(&Item{key, value})
}

// Get returns Item from cache by key.
// nil is returned if there is no such key in the cache.
func (c *Cache) Get(key string) *Item {
	if c.data[key] != nil {
		c.lst.MoveToFront(c.data[key])
		return c.data[key].Value.(*Item)
	}
	return nil
}

Fix adding Item to cache.


package channels

type DemandState struct {
	Rated        *float64 `json:"rated,omitempty"`        // rated maximum power, in Watts
	ObservedMax  *float64 `json:"observedMax,omitempty"`  // the observed max current power for this device
	Current      *float64 `json:"current,omitempty"`      // average power for current period
	Peak         *float64 `json:"peak,omitempty"`         // peak instantaneous power in averaging period
	Goal         *float64 `json:"goal,omitempty"`         // goal power for averaging period
	Controlled   *float64 `json:"controlled,omitempty"`   // average controlled power
	Uncontrolled *float64 `json:"uncontrolled,omitempty"` // average uncontrolled power
	Period       *int     `json:"period,omitempty"`       // averaging period, in secon
}

type DemandChannel struct {
	baseChannel
}

func NewDemandChannel() *DemandChannel {
	return &DemandChannel{
		baseChannel: baseChannel{protocol: "demand"},
	}
}

func (c *DemandChannel) SendState(demandState *DemandState) error {
	return c.SendEvent("state", demandState)
}

package channels

type DemandState struct {
	Rated        *float64 `json:"rated,omitempty"`        // rated maximum power, in Watts
	ObservedMax  *float64 `json:"observedMax,omitempty"`  // the observed max current power for this device
	Current      *float64 `json:"current,omitempty"`      // average power for current period
	Peak         *float64 `json:"peak,omitempty"`         // peak instantaneous power in averaging period
	Goal         *float64 `json:"goal,omitempty"`         // goal power for averaging period
	Controlled   *float64 `json:"controlled,omitempty"`   // average controlled power
	Uncontrolled *float64 `json:"uncontrolled,omitempty"` // average uncontrolled power
	Period       *int     `json:"period,omitempty"`       // averaging period, in seconds
	OnTicks      *int     `json:"onTicks,omitempty"`      // the number of seconds since last switch on
	OffTicks     *int     `json:"offTicks,omitempty"`     // the number of seconds since last switch off
}

type DemandChannel struct {
	baseChannel
}

func NewDemandChannel() *DemandChannel {
	return &DemandChannel{
		baseChannel: baseChannel{protocol: "demand"},
	}
}

func (c *DemandChannel) SendState(demandState *DemandState) error {
	return c.SendEvent("state", demandState)
}

Add onticks and offticks to model.


// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

// +build gccgo

package vsphere

const (
	providerType = "vsphere"
)

// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

// +build gccgo

// This file exists so that this package will remain importable under
// GCCGo. In particular, see provider/all/all.go. All other files in
// this package do not build under GCCGo (see lp:1440940).

package vsphere

const (
	providerType = "vsphere"
)

Add a comment explaining the reason for the build constraints.


package projects

import "time"

const (
	// GetSbomEndpoint is the current endpoint for retrieving an organization's SBOMs
	GetSbomEndpoint = "v1/project/getSBOM"
	// GetSbomsEndpoint is the current endpoint for retrieving an organization's SBOMs
	GetSbomsEndpoint = "v1/project/getSBOMs"
)

// SBOM represents a software list containing zero or more SBOMEntry objects.
type SBOM struct {
	ID         string      `json:"id"`
	Name       string      `json:"sbom_name"`
	Version    string      `json:"sbom_version"`
	Supplier   string      `json:"supplier_name"`
	SbomStatus string      `json:"sbom_status"`
	CreatedAt  time.Time   `json:"created_at"`
	UpdatedAt  time.Time   `json:"updated_at"`
	EntryCount int         `json:"entry_count"`
	Entries    []SBOMEntry `json:"entries"`
	TeamID     string      `json:"team_id"`
	OrgID      string      `json:"org_id"`
	RulesetID  string      `json:"ruleset_id"`
}

package projects

import "time"

const (
	// GetSbomEndpoint is the current endpoint for retrieving an organization's SBOMs
	GetSbomEndpoint = "v1/project/getSBOM"
	// GetSbomsEndpoint is the current endpoint for retrieving an organization's SBOMs
	GetSbomsEndpoint = "v1/project/getSBOMs"
)

// SBOMMetadata contains various piece of metadata about a particular SBOM
type SBOMMetadata struct {
	EntryCount                  int `json:"entry_count"`
	ResolvedEntryCount          int `json:"resolved_entry_count"`
	PartiallyResolvedEntryCount int `json:"partially_resolved_entry_count"`
	UnresolvedEntryCount        int `json:"unresolved_entry_count"`
}

// SBOM represents a software list containing zero or more SBOMEntry objects.
type SBOM struct {
	ID         string       `json:"id"`
	Name       string       `json:"sbom_name"`
	Version    string       `json:"sbom_version"`
	Supplier   string       `json:"supplier_name"`
	SbomStatus string       `json:"sbom_status"`
	CreatedAt  time.Time    `json:"created_at"`
	UpdatedAt  time.Time    `json:"updated_at"`
	EntryCount int          `json:"entry_count"`
	Metadata   SBOMMetadata `json:"metadata"`
	Entries    []SBOMEntry  `json:"entries"`
	TeamID     string       `json:"team_id"`
	OrgID      string       `json:"org_id"`
	RulesetID  string       `json:"ruleset_id"`
}

Add various counts to SBOMs


package core

import (
	"google.golang.org/grpc"
	"log"
	"os"
	msg "qpm.io/common/messages"
	"google.golang.org/grpc/credentials"
)

const (
	Version       = "0.0.1"
	PackageFile   = "qpm.json"
	SignatureFile = "qpm.asc"
	Vendor        = "vendor"
	Address       = "pkg.qpm.io:7000"
	LicenseFile   = "LICENSE"
)

type Context struct {
	Log    *log.Logger
	Client msg.QpmClient
}

func NewContext() *Context {
	log := log.New(os.Stderr, "QPM: ", log.LstdFlags)

	creds := credentials.NewClientTLSFromCert(nil, "")
	address := os.Getenv("SERVER")
	if address == "" {
		address = Address
	}
	conn, err := grpc.Dial(address, grpc.WithTransportCredentials(creds))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}

	return &Context{
		Log:    log,
		Client: msg.NewQpmClient(conn),
	}
}

package core

import (
	"google.golang.org/grpc"
	"log"
	"os"
	msg "qpm.io/common/messages"
	"google.golang.org/grpc/credentials"
	"fmt"
	"runtime"
)

const (
	Version       = "0.0.1"
	PackageFile   = "qpm.json"
	SignatureFile = "qpm.asc"
	Vendor        = "vendor"
	Address       = "pkg.qpm.io:7000"
	LicenseFile   = "LICENSE"
)

var UA = fmt.Sprintf("qpm/%v (%s; %s)", Version, runtime.GOOS, runtime.GOARCH)

type Context struct {
	Log    *log.Logger
	Client msg.QpmClient
}

func NewContext() *Context {
	log := log.New(os.Stderr, "QPM: ", log.LstdFlags)

	creds := credentials.NewClientTLSFromCert(nil, "")
	address := os.Getenv("SERVER")
	if address == "" {
		address = Address
	}
	conn, err := grpc.Dial(address, grpc.WithTransportCredentials(creds), grpc.WithUserAgent(UA))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}

	return &Context{
		Log:    log,
		Client: msg.NewQpmClient(conn),
	}
}

Send a user agent to the server.


package base

// IDInferable represents models that have IDs that can be infered by names.
type IDInferable interface {
	InferID(cn Connection) error
	GetNames(cn Connection, name string) ([]string, error)
}

package base

// IDInferable represents models that have IDs that can be infered from names
// through communicating the server.
type IDInferable interface {
	// After InferID has been completed, all the IDs possible have to have
	// been infered from names.
	InferID(cn Connection) error
	// GetNames exists for the purpose of getting the list of names of entities.
	// The name argument is a field that points to an entity name.
	GetNames(cn Connection, name string) ([]string, error)
}

Document the IDInferable interface and its methods


package hackedu

import (
	"encoding/json"
	"fmt"
	"net/http"

	"appengine"
)

type School struct {
	Name     string `json:"latitude,omitempty"`
	Location Location
}

type Location struct {
	Latitude  float32 `json:"latitude,omitempty"`
	Longitude float32 `json:"longitude,omitempty"`
}

func Schools(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	austin := School{
		Name: "Austin High School",
		Location: Location{
			Latitude:  30.27382,
			Longitude: -97.76745,
		},
	}

	thunderridge := School{
		Name: "Thunderridge High School",
		Location: Location{
			Latitude:  39.5347968,
			Longitude: -105.01200670000003,
		},
	}

	schools := []School{austin, thunderridge}

	bytes, err := json.Marshal(schools)
	if err != nil {
		serveError(c, w, err)
	}

	fmt.Println(string(bytes))

	w.Write(bytes)
}

package hackedu

import (
	"encoding/json"
	"fmt"
	"net/http"

	"appengine"
)

type School struct {
	Name     string   `json:"name,omitempty"`
	Location Location `json:"location,omitempty"`
}

type Location struct {
	Latitude  float32 `json:"latitude,omitempty"`
	Longitude float32 `json:"longitude,omitempty"`
}

func Schools(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	austin := School{
		Name: "Austin High School",
		Location: Location{
			Latitude:  30.27382,
			Longitude: -97.76745,
		},
	}

	thunderridge := School{
		Name: "Thunderridge High School",
		Location: Location{
			Latitude:  39.5347968,
			Longitude: -105.01200670000003,
		},
	}

	schools := []School{austin, thunderridge}

	bytes, err := json.Marshal(schools)
	if err != nil {
		serveError(c, w, err)
	}

	fmt.Println(string(bytes))

	w.Write(bytes)
}

Use the correct JSON keys for School structs.


package main

import "code.google.com/p/gcfg"

// Config is config
type Config struct {
	Telegram struct {
		Token    string
		Username string
	}
}

func getConfig() (Config, error) {
	var cfg Config
	err := gcfg.ReadFileInto(&cfg, "./config.cfg")
	return cfg, err
}

package main

import "gopkg.in/gcfg.v1"

// Config is config
type Config struct {
	Telegram struct {
		Token    string
		Username string
	}
}

func getConfig() (Config, error) {
	var cfg Config
	err := gcfg.ReadFileInto(&cfg, "/tmp/config.cfg")
	return cfg, err
}

Change imprort name of gcfg to make project compile


/*
i-sudoku is an interactive command-line sudoku tool
*/

package main

import (
	"github.com/jkomoros/sudoku"
	"github.com/nsf/termbox-go"
	"log"
	"strings"
)

type mainModel struct {
	grid *sudoku.Grid
}

func main() {
	if err := termbox.Init(); err != nil {
		log.Fatal("Termbox initialization failed:", err)
	}
	defer termbox.Close()

	model := &mainModel{
		sudoku.NewGrid(),
	}

	model.grid.Fill()

	draw(model)

mainloop:
	for {
		switch ev := termbox.PollEvent(); ev.Type {
		case termbox.EventKey:
			switch ev.Key {
			case termbox.KeyEsc, termbox.KeyCtrlC:
				break mainloop
			}
		}
		draw(model)
	}
}

func draw(model *mainModel) {
	drawGrid(model.grid)
	termbox.Flush()
}

func drawGrid(grid *sudoku.Grid) {
	for y, line := range strings.Split(grid.Diagram(), "\n") {
		for x, ch := range line {
			termbox.SetCell(x, y, ch, termbox.ColorGreen, termbox.ColorDefault)
		}
	}
}

/*
i-sudoku is an interactive command-line sudoku tool
*/

package main

import (
	"github.com/jkomoros/sudoku"
	"github.com/nsf/termbox-go"
	"log"
	"strings"
)

type mainModel struct {
	grid *sudoku.Grid
}

func main() {
	if err := termbox.Init(); err != nil {
		log.Fatal("Termbox initialization failed:", err)
	}
	defer termbox.Close()

	model := &mainModel{
		sudoku.NewGrid(),
	}

	model.grid.Fill()

	draw(model)

mainloop:
	for {
		switch ev := termbox.PollEvent(); ev.Type {
		case termbox.EventKey:
			switch ev.Key {
			case termbox.KeyEsc, termbox.KeyCtrlC:
				break mainloop
			}
		}
		draw(model)
	}
}

func draw(model *mainModel) {
	drawGrid(model.grid)
	termbox.Flush()
}

func drawGrid(grid *sudoku.Grid) {
	for y, line := range strings.Split(grid.Diagram(), "\n") {
		x := 0
		//The first number in range will be byte offset, but for some items like the bullet, it's two bytes.
		//But what we care about is that each item is a character.
		for _, ch := range line {
			termbox.SetCell(x, y, ch, termbox.ColorGreen, termbox.ColorDefault)
			x++
		}
	}
}

Fix rendering of the sudoku puzzle.


package leetcode

// 199. Binary Tree Right Side View
func rightSideView(root *TreeNode) []int {
	if root == nil {
		return []int{}
	}
	res := []int{}
	list := []*TreeNode{root}
	for len(list) > 0 {
		res = append(res, list[len(list)-1].Val)
		nextList := make([]*TreeNode, 0)
		for _, node := range list {
			if node.Left != nil {
				nextList = append(nextList, node.Left)
			}
			if node.Right != nil {
				nextList = append(nextList, node.Right)
			}
		}
		list = nextList
	}

	return res
}

package leetcode

import "container/list"

// 199. Binary Tree Right Side View
func rightSideView(root *TreeNode) []int {
	if root == nil {
		return []int{}
	}
	res := []int{}
	list := []*TreeNode{root}
	for len(list) > 0 {
		res = append(res, list[len(list)-1].Val)
		nextList := make([]*TreeNode, 0)
		for _, node := range list {
			if node.Left != nil {
				nextList = append(nextList, node.Left)
			}
			if node.Right != nil {
				nextList = append(nextList, node.Right)
			}
		}
		list = nextList
	}

	return res
}

// 199. Binary Tree Right Side View by container/list
func rightSideView2(root *TreeNode) []int {
	if root == nil {
		return []int{}
	}
	res := []int{}
	l := list.New()
	l.PushBack(root)
	for l.Len() > 0 {
		front := l.Front().Value.(*TreeNode)
		res = append(res, front.Val)
		nextList := list.New()
		for el := l.Front(); el != nil; el = l.Front() {
			node := el.Value.(*TreeNode)
			if node.Right != nil {
				nextList.PushBack(node.Right)
			}
			if node.Left != nil {
				nextList.PushBack(node.Left)
			}
			l.Remove(el)
		}
		l = nextList
	}

	return res
}

Add 199. Binary Tree Right Side View with list


package model

import "regexp"

type Route struct {
	Id       int64  `json:"-"`
	Name     string `json:"name"`
	Pattern  string `json:"pattern"`
	Broker   string `json:"broker"`
	From     string `json:"from" db:"fromName"`
	IsActive bool   `json:"is_active"`
	broker   Broker
	regex    *regexp.Regexp
}

func NewRoute(name, pattern string, broker Broker, isActive bool) *Route {
	return &Route{
		Name:     name,
		Pattern:  pattern,
		Broker:   broker.Name(),
		IsActive: isActive,
		broker:   broker,
		regex:    regexp.MustCompile(pattern),
	}
}

func (r *Route) SetBroker(broker Broker) *Route {
	r.broker = broker
	return r
}

func (r *Route) GetBroker() Broker {
	return r.broker
}

func (r *Route) SetFrom(from string) *Route {
	r.From = from
	return r
}

func (r *Route) Match(recipient string) bool {
	return r.IsActive && r.regex.MatchString(recipient)
}

package model

import "regexp"

type Route struct {
	Id       int64  `json:"-"`
	Name     string `json:"name"`
	Pattern  string `json:"pattern"`
	Broker   string `json:"broker"`
	From     string `json:"from" db:"fromName"`
	IsActive bool   `json:"is_active" db:"isActive"`
	broker   Broker
	regex    *regexp.Regexp
}

func NewRoute(name, pattern string, broker Broker, isActive bool) *Route {
	return &Route{
		Name:     name,
		Pattern:  pattern,
		Broker:   broker.Name(),
		IsActive: isActive,
		broker:   broker,
		regex:    regexp.MustCompile(pattern),
	}
}

func (r *Route) SetBroker(broker Broker) *Route {
	r.broker = broker
	return r
}

func (r *Route) GetBroker() Broker {
	return r.broker
}

func (r *Route) SetFrom(from string) *Route {
	r.From = from
	return r
}

func (r *Route) Match(recipient string) bool {
	return r.IsActive && r.regex.MatchString(recipient)
}

Fix the db tag of model.Route


package medtronic

import (
	"log"
	"time"
)

const (
	Wakeup CommandCode = 0x5D
)

func (pump *Pump) Wakeup() {
	pump.Model()
	if pump.Error() == nil {
		return
	}
	log.Printf("waking pump")
	const (
		// Older pumps should have RF enabled to increase the
		// frequency with which they listen for wakeups.
		numWakeups = 75
		xmitDelay  = 35 * time.Millisecond
	)
	packet := commandPacket(Wakeup, nil)
	for i := 0; i < numWakeups; i++ {
		pump.Radio.Send(packet)
		time.Sleep(xmitDelay)
	}
	n := pump.Retries()
	pump.SetRetries(1)
	defer pump.SetRetries(n)
	t := pump.Timeout()
	pump.SetTimeout(10 * time.Second)
	defer pump.SetTimeout(t)
	pump.Execute(Wakeup, nil)
}

package medtronic

import (
	"log"
	"time"
)

const (
	Wakeup CommandCode = 0x5D
)

func (pump *Pump) Wakeup() {
	pump.Model()
	if pump.Error() == nil {
		return
	}
	pump.SetError(nil)
	log.Printf("waking pump")
	const (
		// Older pumps should have RF enabled to increase the
		// frequency with which they listen for wakeups.
		numWakeups = 100
		xmitDelay  = 10 * time.Millisecond
	)
	packet := commandPacket(Wakeup, nil)
	for i := 0; i < numWakeups; i++ {
		pump.Radio.Send(packet)
		time.Sleep(xmitDelay)
	}
	n := pump.Retries()
	pump.SetRetries(1)
	defer pump.SetRetries(n)
	t := pump.Timeout()
	pump.SetTimeout(10 * time.Second)
	defer pump.SetTimeout(t)
	pump.Execute(Wakeup, nil)
}

Clear error after no response


package maker

import (
	"strings"
	"testing"
)

func check(value, pattern string, t *testing.T) {
	if value != pattern {
		t.Fatalf("Value %s did not match expected pattern %s", value, pattern)
	}
}

func TestLines(t *testing.T) {
	docs := []string{`// TestMethod is great`}
	code := `func TestMethod() string {return "I am great"}`
	method := Method{Code: code, Docs: docs}
	lines := method.Lines()
	check(lines[0], "// TestMethod is great", t)
	check(lines[1], "func TestMethod() string {return \"I am great\"}", t)
}

func TestParseStruct(t *testing.T) {
	src := []byte(`package main

	    import (
		"fmt"
	    )

	    // Person ...
	    type Person struct {
		name string
	    }

	    // Name ...
	    func (p *Person) Name() string {
		return p.name
	    }`)
	methods, imports := ParseStruct(src, "Person", true)
	check(methods[0].Code, "Name() string", t)
	imp := imports[0]
	trimmedImp := strings.TrimSpace(imp)
	expected := "\"fmt\""
	check(trimmedImp, expected, t)
}

func Test

Delete a trailing beginning of another test case


package transports

import (
  "log"
)

type DummyMarshaler struct {
}

func (marshaler DummyMarshaler) Marshal(i *interface{}) (error, interface{}) {
  log.Println("** DummyMarshaler, input", *i)
  var err error
	return err, []byte("aa")
}

func (marshaler DummyMarshaler) Unmarshal() {
	return
}

package transports

import (
  // "log"
)

type DummyMarshaler struct {
}

func (marshaler DummyMarshaler) Marshal(i *interface{}) (error, interface{}) {
  var err error
	return err, *i
}

func (marshaler DummyMarshaler) Unmarshal() {
	return
}

Return the original value from DummyMarshaler


// +build !windows

package gottyclient

import (
	"encoding/json"
	"fmt"
	"golang.org/x/sys/unix"
	"os"
	"os/signal"
	"syscall"
)

func notifySignalSIGWINCH(c chan<- os.Signal) {
	signal.Notify(c, syscall.SIGWINCH)
}

func resetSignalSIGWINCH() {
	signal.Reset(syscall.SIGWINCH)
}

func syscallTIOCGWINSZ() ([]byte, error) {
	ws, err := unix.IoctlGetWinsize(0, 0)
	if err != nil {
		return nil, fmt.Errorf("ioctl error: %v", err)
	}
	b, err := json.Marshal(ws)
	if err != nil {
		return nil, fmt.Errorf("json.Marshal error: %v", err)
	}
	return b, err
}

// +build !windows

package gottyclient

import (
	"encoding/json"
	"fmt"
	"golang.org/x/sys/unix"
	"os"
	"os/signal"
	"syscall"
)

func notifySignalSIGWINCH(c chan<- os.Signal) {
	signal.Notify(c, syscall.SIGWINCH)
}

func resetSignalSIGWINCH() {
	signal.Reset(syscall.SIGWINCH)
}

func syscallTIOCGWINSZ() ([]byte, error) {
	ws, err := unix.IoctlGetWinsize(0, 0)
	if err != nil {
		return nil, fmt.Errorf("ioctl error: %v", err)
	}
	tws := winsize{Rows: ws.Row, Columns: ws.Col}
	b, err := json.Marshal(tws)
	if err != nil {
		return nil, fmt.Errorf("json.Marshal error: %v", err)
	}
	return b, err
}

Fix bug when resizing terminal


package model

// Customer is a model in the "customers" table.
type Customer struct {
	ID   int     `json:"id"`
	Name *string `json:"name" gorm:"not null"`
}

// Order is a model in the "orders" table.
type Order struct {
	ID       int     `json:"id"`
	Subtotal float64 `json:"subtotal" gorm:"type:decimal(18,2)"`

	Customer   Customer `json:"customer" gorm:"ForeignKey:CustomerID"`
	CustomerID int      `json:"-"`

	Products []Product `json:"products" gorm:"many2many:order_products"`
}

// Product is a model in the "products" table.
type Product struct {
	ID    int     `json:"id"`
	Name  *string `json:"name"  gorm:"not null;unique"`
	Price float64 `json:"price" gorm:"type:decimal(18,2)"`
}

package model

// Customer is a model in the "customers" table.
type Customer struct {
	ID   int     `json:"id,omitempty"`
	Name *string `json:"name" gorm:"not null"`
}

// Order is a model in the "orders" table.
type Order struct {
	ID       int     `json:"id,omitempty"`
	Subtotal float64 `json:"subtotal" gorm:"type:decimal(18,2)"`

	Customer   Customer `json:"customer" gorm:"ForeignKey:CustomerID"`
	CustomerID int      `json:"-"`

	Products []Product `json:"products" gorm:"many2many:order_products"`
}

// Product is a model in the "products" table.
type Product struct {
	ID    int     `json:"id,omitempty"`
	Name  *string `json:"name"  gorm:"not null;unique"`
	Price float64 `json:"price" gorm:"type:decimal(18,2)"`
}

Add omitempty to id fields


// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

// +build !linux

package diskmanager

import (
	"github.com/juju/juju/storage"
	"github.com/juju/juju/version"
)

var blockDeviceInUse = func(storage.BlockDevice) (bool, error) {
	panic("not supported")
}

func listBlockDevices() ([]storage.BlockDevice, error) {
	// Return an empty list each time.
	return nil, nil
}

func init() {
	logger.Infof(
		"block device support has not been implemented for %s",
		version.Current.OS,
	)
	DefaultListBlockDevices = listBlockDevices
}

// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

// +build !linux

package diskmanager

import (
	"runtime"

	"github.com/juju/juju/storage"
	"github.com/juju/juju/version"
)

var blockDeviceInUse = func(storage.BlockDevice) (bool, error) {
	panic("not supported")
}

func listBlockDevices() ([]storage.BlockDevice, error) {
	// Return an empty list each time.
	return nil, nil
}

func init() {
	logger.Infof(
		"block device support has not been implemented for %s",
		runtime.GOOS,
	)
	DefaultListBlockDevices = listBlockDevices
}

Fix compile failure for windows.


package buffalo

import (
	"net/http"

	"github.com/gorilla/sessions"
)

// Session wraps the "github.com/gorilla/sessions" API
// in something a little cleaner and a bit more useable.
type Session struct {
	Session *sessions.Session
	req     *http.Request
	res     http.ResponseWriter
}

// Save the current session
func (s *Session) Save() error {
	return s.Session.Save(s.req, s.res)
}

// Get a value from the current session
func (s *Session) Get(name interface{}) interface{} {
	return s.Session.Values[name]
}

// Set a value onto the current session. If a value with that name
// already exists it will be overridden with the new value.
func (s *Session) Set(name, value interface{}) {
	s.Session.Values[name] = value
}

// Delete a value from the current session.
func (s *Session) Delete(name interface{}) {
	delete(s.Session.Values, name)
}

// Get a session using a request and response.
func (a *App) getSession(r *http.Request, w http.ResponseWriter) *Session {
	session, _ := a.SessionStore.Get(r, a.SessionName)
	return &Session{
		Session: session,
		req:     r,
		res:     w,
	}
}

package buffalo

import (
	"net/http"

	"github.com/gorilla/sessions"
)

// Session wraps the "github.com/gorilla/sessions" API
// in something a little cleaner and a bit more useable.
type Session struct {
	Session *sessions.Session
	req     *http.Request
	res     http.ResponseWriter
}

// Save the current session.
func (s *Session) Save() error {
	return s.Session.Save(s.req, s.res)
}

// Get a value from the current session.
func (s *Session) Get(name interface{}) interface{} {
	return s.Session.Values[name]
}

// Set a value onto the current session. If a value with that name
// already exists it will be overridden with the new value.
func (s *Session) Set(name, value interface{}) {
	s.Session.Values[name] = value
}

// Delete a value from the current session.
func (s *Session) Delete(name interface{}) {
	delete(s.Session.Values, name)
}

// Get a session using a request and response.
func (a *App) getSession(r *http.Request, w http.ResponseWriter) *Session {
	session, _ := a.SessionStore.Get(r, a.SessionName)
	return &Session{
		Session: session,
		req:     r,
		res:     w,
	}
}

Add punctuation to be consistent


package options

import (
	"github.com/spf13/pflag"
)

type Config struct {
	Master                string
	KubeConfig            string
	ProviderName          string
	ClusterName           string
	LoadbalancerImageName string
}

func NewConfig() *Config {
	return &Config{
		Master:                "",
		KubeConfig:            "",
		ProviderName:          "",
		ClusterName:           "",
		LoadbalancerImageName: "appscode/haproxy:1.7.0-k8s",
	}
}

func (s *Config) AddFlags(fs *pflag.FlagSet) {
	fs.StringVar(&s.Master, "master", s.Master, "The address of the Kubernetes API server (overrides any value in kubeconfig)")
	fs.StringVar(&s.KubeConfig, "kubeconfig", s.KubeConfig, "Path to kubeconfig file with authorization information (the master location is set by the master flag).")

	fs.StringVarP(&s.ProviderName, "cloud-provider", "c", s.ProviderName, "Name of cloud provider")
	fs.StringVarP(&s.ClusterName, "cluster-name", "k", s.ClusterName, "Name of Kubernetes cluster")
	fs.StringVarP(&s.LoadbalancerImageName, "haproxy-image", "h", s.LoadbalancerImageName, "haproxy image name to be run")
}

package options

import (
	"github.com/spf13/pflag"
)

type Config struct {
	Master                string
	KubeConfig            string
	ProviderName          string
	ClusterName           string
	LoadbalancerImageName string
}

func NewConfig() *Config {
	return &Config{
		Master:                "",
		KubeConfig:            "",
		ProviderName:          "",
		ClusterName:           "",
		LoadbalancerImageName: "appscode/haproxy:1.7.2-k8s",
	}
}

func (s *Config) AddFlags(fs *pflag.FlagSet) {
	fs.StringVar(&s.Master, "master", s.Master, "The address of the Kubernetes API server (overrides any value in kubeconfig)")
	fs.StringVar(&s.KubeConfig, "kubeconfig", s.KubeConfig, "Path to kubeconfig file with authorization information (the master location is set by the master flag).")

	fs.StringVarP(&s.ProviderName, "cloud-provider", "c", s.ProviderName, "Name of cloud provider")
	fs.StringVarP(&s.ClusterName, "cluster-name", "k", s.ClusterName, "Name of Kubernetes cluster")
	fs.StringVarP(&s.LoadbalancerImageName, "haproxy-image", "h", s.LoadbalancerImageName, "haproxy image name to be run")
}

Set default HAproxy to 1.7.2-k8s


package acgen

import (
	"io"
	"strings"
	"text/template"
)

func init() {
	RegisterGenerator("tcsh", generateTcshCompletion)
}

type tcsh struct {
	Name string
	Opt  string
}

func newTcsh(c *Command) (t *tcsh, err error) {
	opts := make([]string, 0)
	for _, flag := range c.Flags {
		for _, opt := range flag.Long {
			opts = append(opts, opt)
		}
	}
	return &tcsh{
		Name: c.Name,
		Opt:  strings.Join(opts, " "),
	}, nil
}

var tcshTemplate = template.Must(template.New("tcsh").Parse(`
complete {{.Name}} 'c/--/({{.Opt}})/'
`[1:]))

func generateTcshCompletion(w io.Writer, c *Command) error {
	t, err := newTcsh(c)
	if err != nil {
		return err
	}
	return tcshTemplate.Execute(w, t)
}

package acgen

import (
	"io"
	"strings"
	"text/template"
)

func init() {
	RegisterGenerator("tcsh", generateTcshCompletion)
}

type tcsh struct {
	Name string
	Opt  string
}

func newTcsh(c *Command) (t *tcsh, err error) {
	var opts []string
	for _, flag := range c.Flags {
		for _, opt := range flag.Long {
			opts = append(opts, opt)
		}
	}
	return &tcsh{
		Name: c.Name,
		Opt:  strings.Join(opts, " "),
	}, nil
}

var tcshTemplate = template.Must(template.New("tcsh").Parse(`
complete {{.Name}} 'c/--/({{.Opt}})/'
`[1:]))

func generateTcshCompletion(w io.Writer, c *Command) error {
	t, err := newTcsh(c)
	if err != nil {
		return err
	}
	return tcshTemplate.Execute(w, t)
}

Use var instead of make


package httpclient_test

import (
	"fmt"
	"net/http"

	"gnd.la/net/httpclient"
)

func ExampleIter() {
	// Passing nil only works on non-App Engine and while
	// running tests. Usually you should pass a *app.Context
	// to httpclient.New.
	c := httpclient.New(nil)
	req, err := http.NewRequest("GET", "http://httpbin.org/redirect/3", nil)
	if err != nil {
		panic(err)
	}
	iter := c.Iter(req)
	// Don't forget to close the Iter after you're done with it
	defer iter.Close()
	var urls []string
	for iter.Next() {
		urls = append(urls, iter.Response().URL().String())
	}
	// iter.Assert() could also be used here
	if err := iter.Err(); err != nil {
		panic(err)
	}
	fmt.Println("Last", iter.Response().URL())
	fmt.Println("Intermediate", urls)
	// Output:
	// Last http://httpbin.org/get
	// Intermediate [http://httpbin.org/redirect/3 http://httpbin.org/redirect/2 http://httpbin.org/redirect/1]
}

package httpclient_test

import (
	"fmt"
	"net/http"

	"gnd.la/net/httpclient"
)

func ExampleIter() {
	// Passing nil only works on non-App Engine and while
	// running tests. Usually you should pass a *app.Context
	// to httpclient.New.
	c := httpclient.New(nil)
	req, err := http.NewRequest("GET", "http://httpbin.org/relative-redirect/3", nil)
	if err != nil {
		panic(err)
	}
	iter := c.Iter(req)
	// Don't forget to close the Iter after you're done with it
	defer iter.Close()
	var urls []string
	for iter.Next() {
		urls = append(urls, iter.Response().URL().String())
	}
	// iter.Assert() could also be used here
	if err := iter.Err(); err != nil {
		panic(err)
	}
	fmt.Println("Last", iter.Response().URL())
	fmt.Println("Intermediate", urls)
	// Output:
	// Last http://httpbin.org/get
	// Intermediate [http://httpbin.org/relative-redirect/3 http://httpbin.org/relative-redirect/2 http://httpbin.org/relative-redirect/1]
}

Update URLs in ExampleIter to match the changes in httpbin's API


package models

import (
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

type Setting struct {
	Database struct {
		Host       string
		DbName     string
		TokenTable string
		UserTable  string
	}
}

var Set Setting

func LoadSettings() error {
	text, err := ioutil.ReadFile("./settings.yml")
	if err != nil {
		return err
	}

	if err = yaml.Unmarshal(text, &Set); err != nil {
		return err
	}

	return nil
}

package models

import (
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

type Setting struct {
	Database struct {
		Host       string
		DbName     string
		TokenTable string
		UserTable  string
	}
	Ssl struct {
		Key         string
		Sertificate string
	}
	Router struct {
		Register string
		Login    string
		Validate string
	}
}

var Set Setting

func LoadSettings() error {
	text, err := ioutil.ReadFile("./settings.yml")
	if err != nil {
		return err
	}

	if err = yaml.Unmarshal(text, &Set); err != nil {
		return err
	}

	return nil
}

Add Ssl config. Add Router config.


package html

import (
	"fmt"
	"io"
	"syscall"
	"time"
)

var startTime time.Time = time.Now()

func writeHeader(writer io.Writer) {
	fmt.Fprintf(writer, "Start time: %s
\n", startTime)
	uptime := time.Since(startTime)
	fmt.Fprintf(writer, "Uptime: %s
\n", uptime)
	var rusage syscall.Rusage
	syscall.Getrusage(syscall.RUSAGE_SELF, &rusage)
	cpuTime := rusage.Utime.Sec + rusage.Stime.Sec
	fmt.Fprintf(writer, "CPU Time: %d%%
\n",
		cpuTime*100/int64(uptime.Seconds()))
}

package html

import (
	"fmt"
	"github.com/Symantec/Dominator/lib/format"
	"io"
	"runtime"
	"syscall"
	"time"
)

var startTime time.Time = time.Now()

func writeHeader(writer io.Writer) {
	fmt.Fprintf(writer, "Start time: %s
\n", startTime)
	uptime := time.Since(startTime)
	fmt.Fprintf(writer, "Uptime: %s
\n", uptime)
	var rusage syscall.Rusage
	syscall.Getrusage(syscall.RUSAGE_SELF, &rusage)
	cpuTime := rusage.Utime.Sec + rusage.Stime.Sec
	fmt.Fprintf(writer, "CPU Time: %d%%
\n",
		cpuTime*100/int64(uptime.Seconds()))
	var memStats runtime.MemStats
	runtime.ReadMemStats(&memStats)
	fmt.Fprintf(writer, "Allocated memory: %s
\n",
		format.FormatBytes(memStats.Alloc))
}

Add allocated memory to HTML status pages.


package fetcher

import "os"

// FileReseter implements WriteReseter for an *os.File instance
type FileReseter struct {
	*os.File
}

// Reset will truncate the file and seek to the beginning.
func (f *FileReseter) Reset() error {
	err := f.Truncate(0)
	if err != nil {
		return err
	}
	_, err = f.Seek(0, 0)
	return err
}

package fetcher

import "io"

// File interface as implemented by *os.File
type File interface {
	Truncate(size int64) error
	io.Seeker
	io.Writer
}

// FileReseter implements WriteReseter for an *os.File instance
type FileReseter struct {
	File
}

// Reset will truncate the file and seek to the beginning.
func (f *FileReseter) Reset() error {
	err := f.Truncate(0)
	if err != nil {
		return err
	}
	_, err = f.Seek(0, 0)
	return err
}

Define interface wrapping io.File for FileReseter


package digitalocean

import (
	"testing"

	"github.com/mitchellh/packer/packer"
)

func TestArtifact_Impl(t *testing.T) {
	var raw interface{}
	raw = &Artifact{}
	if _, ok := raw.(packer.Artifact); !ok {
		t.Fatalf("Artifact should be artifact")
	}
}

func TestArtifactId(t *testing.T) {
	a := &Artifact{"packer-foobar", 42, "San Francisco", nil}
	expected := "San Francisco:42"

	if a.Id() != expected {
		t.Fatalf("artifact ID should match: %v", expected)
	}
}

func TestArtifactString(t *testing.T) {
	a := &Artifact{"packer-foobar", 42, "San Francisco", nil}
	expected := "A snapshot was created: 'packer-foobar' (ID: 42) in region 'San Francisco'"

	if a.String() != expected {
		t.Fatalf("artifact string should match: %v", expected)
	}
}

package digitalocean

import (
	"testing"

	"github.com/mitchellh/packer/packer"
)

func TestArtifact_Impl(t *testing.T) {
	var raw interface{}
	raw = &Artifact{}
	if _, ok := raw.(packer.Artifact); !ok {
		t.Fatalf("Artifact should be artifact")
	}
}

func TestArtifactId(t *testing.T) {
	a := &Artifact{"packer-foobar", 42, "sfo", nil}
	expected := "sfo:42"

	if a.Id() != expected {
		t.Fatalf("artifact ID should match: %v", expected)
	}
}

func TestArtifactString(t *testing.T) {
	a := &Artifact{"packer-foobar", 42, "sfo", nil}
	expected := "A snapshot was created: 'packer-foobar' (ID: 42) in region 'sfo'"

	if a.String() != expected {
		t.Fatalf("artifact string should match: %v", expected)
	}
}

Change test to use something that looks like a real region code


package livestatus

import (
	"net"
)

const bufferSize = 1024

// Client represents a Livestatus client instance.
type Client struct {
	network string
	address string
	dialer  *net.Dialer
	conn    net.Conn
}

// NewClient creates a new Livestatus client instance.
func NewClient(network, address string) *Client {
	return NewClientWithDialer(network, address, new(net.Dialer))
}

// NewClientWithDialer creates a new Livestatus client instance using a provided network dialer.
func NewClientWithDialer(network, address string, dialer *net.Dialer) *Client {
	return &Client{
		network: network,
		address: address,
		dialer:  dialer,
	}
}

// Close closes any remaining connection.
func (c *Client) Close() {
	if c.conn != nil {
		c.conn.Close()
		c.conn = nil
	}
}

// Exec executes a given Livestatus query.
func (c *Client) Exec(r Request) (*Response, error) {
	var err error

	// Initialize connection if none available
	if c.conn == nil {
		c.conn, err = c.dialer.Dial(c.network, c.address)
		if err != nil {
			return nil, err
		}

		if !r.keepAlive() {
			defer c.Close()
		}
	}

	return r.handle(c.conn)
}

package livestatus

import (
	"net"
)

const bufferSize = 1024

// Client represents a Livestatus client instance.
type Client struct {
	network string
	address string
	dialer  *net.Dialer
	conn    net.Conn
}

// NewClient creates a new Livestatus client instance.
func NewClient(network, address string) *Client {
	return NewClientWithDialer(network, address, new(net.Dialer))
}

// NewClientWithDialer creates a new Livestatus client instance using a provided network dialer.
func NewClientWithDialer(network, address string, dialer *net.Dialer) *Client {
	return &Client{
		network: network,
		address: address,
		dialer:  dialer,
	}
}

// Close closes any remaining connection.
func (c *Client) Close() {
	if c.conn != nil {
		c.conn.Close()
		c.conn = nil
	}
}

// Exec executes a given Livestatus query.
func (c *Client) Exec(r Request) (*Response, error) {
	var err error

	// Initialize connection if none available
	if c.conn == nil {
		c.conn, err = c.dialer.Dial(c.network, c.address)
		if err != nil {
			return nil, err
		}

		if r.keepAlive() {
			c.conn.(*net.TCPConn).SetKeepAlive(true)
		} else {
			defer c.Close()
		}
	}

	return r.handle(c.conn)
}

Add missing keepalive on TCP connection


package buildlog

import (
	"fmt"
	"log"

	"github.com/mattes/migrate"
	"github.com/mattes/migrate/database/postgres"
	_ "github.com/mattes/migrate/source/file"
)

type migrationLogger struct {
}

func (m migrationLogger) Verbose() bool {
	return false
}

func (m migrationLogger) Printf(format string, v ...interface{}) {
	s := fmt.Sprintf(format, v...)
	log.Printf("[db migration] %s", s)
}

func (bl *BuildLog) MigrateDb() error {
	driver, err := postgres.WithInstance(bl.db, &postgres.Config{})
	if err != nil {
		return err
	}

	m, err := migrate.NewWithDatabaseInstance("file://migrations", "postgres", driver)
	if err != nil {
		return err
	}

	m.Log = migrationLogger{}

	err = m.Up()
	if err != migrate.ErrNoChange {
		return err
	}

	return nil
}

package buildlog

import (
	"fmt"
	"log"
	"os"

	"github.com/mattes/migrate"
	"github.com/mattes/migrate/database/postgres"
	_ "github.com/mattes/migrate/source/file"
)

type migrationLogger struct {
}

func (m migrationLogger) Verbose() bool {
	return false
}

func (m migrationLogger) Printf(format string, v ...interface{}) {
	s := fmt.Sprintf(format, v...)
	log.Printf("[db migration] %s", s)
}

func (bl *BuildLog) MigrateDb() error {
	driver, err := postgres.WithInstance(bl.db, &postgres.Config{})
	if err != nil {
		return err
	}

	source := os.Getenv("DB_MIGRATIONS_SOURCE_URI")
	if source == "" {
		source = "file://migrations"
	}
	log.Printf("Using DB migrations file from %s\n", source)

	m, err := migrate.NewWithDatabaseInstance(source, "postgres", driver)
	if err != nil {
		return err
	}

	m.Log = migrationLogger{}

	err = m.Up()
	if err != migrate.ErrNoChange {
		return err
	}

	return nil
}

Allow DB migrations source path customization


package ssh

import "os"

type C struct {
	User string
	Host string
	HostKeyFun  func([]byte)os.Error
	PasswordFun func()string
}

func New(C C) (*Client,os.Error) {
	c,e := connect(C.Host)
	if e != nil { return nil,e }
	writeKexInit(c)
	b,e := readPacket(c)
	c.skex = make([]byte, len(b))
	copy(c.skex, b)
	if e!=nil { return nil,e }
	k,e := parseKexInit(c,b[1:])
	Log(6,"%v",k)
	if e!=nil { return nil,e }
	e = dh(c,k,&C)
	if e!=nil { return nil,e }

	client := &Client{ssh: c}
	for C.PasswordFun!=nil && !password(c,C.User, C.PasswordFun()) {}
	startClientLoop(client)
	return client, nil
}

package ssh

import "os"

type C struct {
	User string
	Host string
	HostKeyFun  func([]byte)os.Error
	PasswordFun func()(string,os.Error)
}

func New(C C) (*Client,os.Error) {
	c,e := connect(C.Host)
	if e != nil { return nil,e }
	writeKexInit(c)
	b,e := readPacket(c)
	c.skex = make([]byte, len(b))
	copy(c.skex, b)
	if e!=nil { return nil,e }
	k,e := parseKexInit(c,b[1:])
	Log(6,"%v",k)
	if e!=nil { return nil,e }
	e = dh(c,k,&C)
	if e!=nil { return nil,e }

	client := &Client{ssh: c}
	for C.PasswordFun!=nil {
		pass,err := C.PasswordFun()
		if err!=nil {
			return nil,err
		}
		if password(c,C.User, pass) {
			break
		}
	}
	startClientLoop(client)
	return client, nil
}

Allow PasswordFun to return an error


package config

import (
	"encoding/json"
	"github.com/snormore/gologger"
	"io/ioutil"
)

type Config interface{}

func Register(name string, c Config) error {
	return nil
}

type Configurable struct {
	Config interface{}
}

func Read(filePath string, conf *Config) error {
	logger.Info("Loading configuration from %s...", filePath)
	configJson, err := ioutil.ReadFile(filePath)
	if err != nil {
		return err
	}
	return ReadJson(configJson, conf)
}

func ReadJson(configJson []byte, conf *Config) error {
	return json.Unmarshal(configJson, conf)
}

package config

import (
	"encoding/json"
	"github.com/snormore/gologger"
	"io/ioutil"
)

type Config interface{}

func Register(name string, c Config) error {
	return nil
}

type Configurable struct {
	Config interface{}
}

func Init(filePath string) (*Config, error) {
	return Read(filePath)
}

func Read(filePath string) (*Config, error) {
	logger.Info("Loading configuration from %s...", filePath)
	configJson, err := ioutil.ReadFile(filePath)
	if err != nil {
		return nil, err
	}
	return ReadJson(configJson)
}

func ReadJson(configJson []byte) (*Config, error) {
	conf := new(Config)
	err := json.Unmarshal(configJson, conf)
	return conf, err
}

Refactor to return Config, error pair.


package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"github.com/katnegermis/pocketmine-rcon"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Printf("Usage: ./rcon address password")
		return
	}
	addr := os.Args[1]
	pass := os.Args[2]

	conn, err := rcon.NewConnection(addr, pass)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("Successfully logged in at %s!\n", addr)

	prompt()
	stdin := bufio.NewReader(os.Stdin)
	input := ""
	for {
		if input, err = stdin.ReadString('\n'); err != nil {
			fmt.Println(err)
			return
		}
		input = strings.Trim(input[:len(input)-1], " ")
		if input == ".exit" {
			break
		}
		if len(input) == 0 {
			prompt()
			continue
		}

		r, err := conn.SendCommand(input)
		if err != nil {
			fmt.Printf("Error: %s\n", err)
			prompt()
			continue
		}

		fmt.Printf("Server:\n%s\n", r)
		prompt()
	}
}

func prompt() {
	fmt.Print("Enter command:\n>")
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"github.com/katnegermis/pocketmine-rcon"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Printf("Usage: ./rcon address password")
		return
	}
	addr := os.Args[1]
	pass := os.Args[2]

	conn, err := rcon.NewConnection(addr, pass)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("Successfully logged in at %s!\n", addr)

	prompt()
	stdin := bufio.NewReader(os.Stdin)
	input := ""
	for {
		if input, err = stdin.ReadString('\n'); err != nil {
			fmt.Println(err)
			return
		}
		input = strings.TrimSuffix(input, "\r\n")
		input = strings.Trim(input[:len(input)-1], " ")
		if input == ".exit" {
			break
		}
		if len(input) == 0 {
			prompt()
			continue
		}

		r, err := conn.SendCommand(input)
		if err != nil {
			fmt.Printf("Error: %s\n", err)
			prompt()
			continue
		}

		fmt.Printf("Server:\n%s\n", r)
		prompt()
	}
}

func prompt() {
	fmt.Print("Enter command:\n>")
}

Add trimsuffix to remove windows line endings


// Package tracing consolidates the setup logic for using opencensus tracing and exporting the
// metrics.
package tracing

import (
	"time"

	"contrib.go.opencensus.io/exporter/stackdriver"
	"go.opencensus.io/trace"
	"go.skia.org/infra/go/skerr"
)

// Initialize sets up trace options and exporting for this application. It will sample the given
// proportion of traces. All traces will have the given key-value pairs attached.
func Initialize(traceSampleProportion float64, projectID string, defaultAttrs map[string]interface{}) error {
	exporter, err := stackdriver.NewExporter(stackdriver.Options{
		ProjectID: projectID,
		// Use 10 times the default
		TraceSpansBufferMaxBytes: 80_000_000,
		// It is not clear what the default interval is. One minute seems to be a good value since
		// that is the same as our Prometheus metrics are reported.
		ReportingInterval:      time.Minute,
		DefaultTraceAttributes: defaultAttrs,
	})
	if err != nil {
		return skerr.Wrap(err)
	}

	trace.RegisterExporter(exporter)
	sampler := trace.ProbabilitySampler(traceSampleProportion)
	trace.ApplyConfig(trace.Config{DefaultSampler: sampler})
	return nil
}

// Package tracing consolidates the setup logic for using opencensus tracing and exporting the
// metrics to https://cloud.google.com/trace. In order to authenticate to the correct API, any
// service account that uses this package must have the Cloud Trace Agent Role in gcp.
package tracing

import (
	"time"

	"contrib.go.opencensus.io/exporter/stackdriver"
	"go.opencensus.io/trace"
	"go.skia.org/infra/go/skerr"
)

// Initialize sets up trace options and exporting for this application. It will sample the given
// proportion of traces. All traces will have the given key-value pairs attached.
func Initialize(traceSampleProportion float64, projectID string, defaultAttrs map[string]interface{}) error {
	exporter, err := stackdriver.NewExporter(stackdriver.Options{
		ProjectID: projectID,
		// Use 10 times the default
		TraceSpansBufferMaxBytes: 80_000_000,
		// It is not clear what the default interval is. One minute seems to be a good value since
		// that is the same as our Prometheus metrics are reported.
		ReportingInterval:      time.Minute,
		DefaultTraceAttributes: defaultAttrs,
	})
	if err != nil {
		return skerr.Wrap(err)
	}

	trace.RegisterExporter(exporter)
	sampler := trace.ProbabilitySampler(traceSampleProportion)
	trace.ApplyConfig(trace.Config{DefaultSampler: sampler})
	return nil
}

Add required service account permission to docs


// +build windows,unit

// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
//	http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.

package config

import (
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestParseGMSACapability(t *testing.T) {
	os.Setenv("ECS_GMSA_SUPPORTED", "False")
	defer os.Unsetenv("ECS_GMSA_SUPPORTED")

	assert.False(t, parseGMSACapability())
}

func TestParseBooleanEnvVar(t *testing.T) {
	os.Setenv("EXAMPLE_SETTING", "True")
	defer os.Unsetenv("EXAMPLE_SETTING")

	assert.True(t, parseBooleanDefaultFalseConfig("EXAMPLE_SETTING"))
	assert.True(t, parseBooleanDefaultTrueConfig("EXAMPLE_SETTING"))

	os.Setenv("EXAMPLE_SETTING", "False")
	assert.False(t, parseBooleanDefaultFalseConfig("EXAMPLE_SETTING"))
	assert.False(t, parseBooleanDefaultTrueConfig("EXAMPLE_SETTING"))
}

Add a test for upper-to-lower conversion on parsing Windows env vars


// goslow is a slow HTTP server that responds with errors.
// Visit https://github.com/alexandershov/goslow for more details.
package main

import (
	"log"
)

// main starts a slow HTTP server that responds with errors.
func main() {
	config := NewConfigFromArgs()
	server := NewServer(config)

	log.Fatal(server.ListenAndServe())
}

// goslow is a slow HTTP server that responds with errors.
// Visit https://github.com/alexandershov/goslow for more details.
package main

import (
	"log"
	"runtime"
)

// main starts a slow HTTP server that responds with errors.
func main() {
	// GOMAXPROCS call is ignored if NumCPU returns 1 (GOMAXPROCS(0) doesn't change anything)
	runtime.GOMAXPROCS(runtime.NumCPU() / 2)

	config := NewConfigFromArgs()
	server := NewServer(config)

	log.Fatal(server.ListenAndServe())
}

Use half of available CPUs


package system

import (
	"fmt"
	"syscall"

	"github.com/buildkite/agent/v3/logger"
)

func VersionDump(_ logger.Logger) (string, error) {
	dll := syscall.MustLoadDLL("kernel32.dll")
	p := dll.MustFindProc("GetVersion")
	v, _, _ := p.Call()

	return fmt.Sprintf("Windows version %d.%d (Build %d)\n", byte(v), uint8(v>>8), uint16(v>>16)), nil
}

package system

import (
	"fmt"
	"github.com/buildkite/agent/v3/logger"
	"golang.org/x/sys/windows"
)

func VersionDump(_ logger.Logger) (string, error) {
	info := windows.RtlGetVersion()

	return fmt.Sprintf("Windows version %d.%d (Build %d)\n", info.MajorVersion, info.MinorVersion, info.BuildNumber), nil
}

Update the way we detect windows versions


package comments

import (
	"log"
	"os"

	"github.com/google/go-github/github"
)

var (
	pendingFeedbackLabel = "pending-feedback"

	HandlerPendingFeedbackLabel = func(client *github.Client, event github.IssueCommentEvent) error {
		// if the comment is from the issue author & issue has the "pending-feedback", remove the label

		if os.Getenv("AUTO_REPLY_DEBUG") == "true" {
			log.Println("received event:", event)
		}

		if *event.Sender.ID == *event.Issue.User.ID && hasLabel(event.Issue.Labels, pendingFeedbackLabel) {
			owner, name, number := *event.Repo.Owner.Login, *event.Repo.Name, *event.Issue.Number
			_, err := client.Issues.RemoveLabelForIssue(owner, name, number, pendingFeedbackLabel)
			if err != nil {
				log.Printf("[pending_feedback_label]: error removing label (%s/%s#%d): %v", owner, name, number, err)
				return err
			}
			return nil
		}
		return nil
	}
)

func hasLabel(labels []github.Label, desiredLabel string) bool {
	for _, label := range labels {
		if *label.Name == desiredLabel {
			return true
		}
	}
	return false
}

package comments

import (
	"log"
	"os"

	"github.com/google/go-github/github"
)

var (
	pendingFeedbackLabel = "pending-feedback"

	HandlerPendingFeedbackLabel = func(client *github.Client, event github.IssueCommentEvent) error {
		// if the comment is from the issue author & issue has the "pending-feedback", remove the label

		if os.Getenv("AUTO_REPLY_DEBUG") == "true" {
			log.Println("[pending_feedback_label]: received event:", event)
		}

		if *event.Sender.ID == *event.Issue.User.ID && hasLabel(event.Issue.Labels, pendingFeedbackLabel) {
			owner, name, number := *event.Repo.Owner.Login, *event.Repo.Name, *event.Issue.Number
			_, err := client.Issues.RemoveLabelForIssue(owner, name, number, pendingFeedbackLabel)
			if err != nil {
				log.Printf("[pending_feedback_label]: error removing label (%s/%s#%d): %v", owner, name, number, err)
				return err
			}
			return nil
		}
		return nil
	}
)

func hasLabel(labels []github.Label, desiredLabel string) bool {
	for _, label := range labels {
		if *label.Name == desiredLabel {
			return true
		}
	}
	return false
}

Add label so we know where it came from


package raftor

import (
	"github.com/coreos/etcd/raft/raftpb"
	"golang.org/x/net/context"
)

// Applier applies either a snapshot or entries in a Commit object
type Applier interface {

	// Apply processes commit messages after being processed by Raft
	Apply() chan Commit
}

// Commit is used to send to the cluster to save either a snapshot or log entries.
type Commit struct {
	Entries  []raftpb.Entry
	Snapshot raftpb.Snapshot
	Context  context.Context
}

package raftor

import (
	"time"

	"github.com/coreos/etcd/raft"
	"github.com/coreos/etcd/raft/raftpb"
	"golang.org/x/net/context"
)

// Commit is used to send to the cluster to save either a snapshot or log entries.
type Commit struct {
	State    RaftState
	Entries  []raftpb.Entry
	Snapshot raftpb.Snapshot
	Messages []raftpb.Message
	Context  context.Context
}

// RaftState describes the state of the Raft cluster for each commit
type RaftState struct {
	CommitID             uint64
	Vote                 uint64
	Term                 uint64
	Lead                 uint64
	LastLeadElectionTime time.Time
	RaftState            raft.StateType
}

// Applier applies either a snapshot or entries in a Commit object
type Applier interface {

	// Apply processes commit messages after being processed by Raft
	Apply() chan Commit
}

Add RaftState and []raftpb.Message to Commit struct


package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"
)

const VERSION = "0.1.0"

var clientDir string

func init() {
	clientEnv := os.Getenv("CLIENT")
	flag.StringVar(&clientDir, "client", clientEnv, "the directory where the client data is stored")
}

func main() {
	flag.Parse()
	fmt.Printf("resolutionizerd %s starting...\n", VERSION)
	fmt.Printf("listening on port %s\n", os.Getenv("PORT"))

	if clientDir == "" {
		clientDir = os.Getenv("CLIENT")
	}

	fmt.Printf("client root: %s\n", clientDir)

	if _, err := os.Stat(clientDir); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	http.Handle("/", http.FileServer(http.Dir(clientDir)))

	if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"
	"github.com/gorilla/handlers"
)

const VERSION = "0.1.0"

var clientDir string

func init() {
	clientEnv := os.Getenv("CLIENT")
	flag.StringVar(&clientDir, "client", clientEnv, "the directory where the client data is stored")
}

func main() {
	flag.Parse()
	fmt.Printf("resolutionizerd %s starting...\n", VERSION)
	fmt.Printf("listening on port %s\n", os.Getenv("PORT"))

	if clientDir == "" {
		clientDir = os.Getenv("CLIENT")
	}

	fmt.Printf("client root: %s\n", clientDir)

	if _, err := os.Stat(clientDir); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	http.Handle("/", handlers.CombinedLoggingHandler(os.Stdout, http.FileServer(http.Dir(clientDir))))

	if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

Add a logging wrapper around the file server.


package kace

type node struct {
	val   rune
	end   bool
	links []*node
}

func newNode() *node {
	return &node{links: make([]*node, 0)}
}

func (n *node) add(rs []rune) {
	cur := n
	for _, v := range rs {
		link := cur.linkByVal(v)
		if link == nil {
			link = newNode()
			cur.links = append(cur.links, link)
		}
		cur = link
	}
}

func (n *node) find(rs []rune) bool {
	cur := n
	for _, v := range rs {
		cur = cur.linkByVal(v)
		if cur == nil {
			return false
		}
	}

	return cur.end
}

func (n *node) linkByVal(val rune) *node {
	for _, v := range n.links {
		if v.val == val {
			return v
		}
	}

	return nil
}

package kace

type node struct {
	val   rune
	end   bool
	links []*node
}

func newNode(val rune, isEnd bool) *node {
	return &node{
		val:   val,
		end:   isEnd,
		links: make([]*node, 0),
	}
}

func (n *node) add(rs []rune) {
	cur := n
	for k, v := range rs {
		isEnd := k == len(rs)-1

		link := cur.linkByVal(v)
		if link == nil {
			link = newNode(v, isEnd)
			cur.links = append(cur.links, link)
		}

		cur = link
	}
}

func (n *node) find(rs []rune) bool {
	cur := n
	for _, v := range rs {
		cur = cur.linkByVal(v)
		if cur == nil {
			return false
		}
	}

	return cur.end
}

func (n *node) linkByVal(val rune) *node {
	for _, v := range n.links {
		if v.val == val {
			return v
		}
	}

	return nil
}

Fix newNode assignments and find logic.


package zero

import (
	"fmt"

	"github.com/tj/go-debug"
)

type Key string

type Args struct {
	Key   Key
	Type  string
	Value interface{}
}

const (
	String = "string"
	Number = "number"
	Array  = "array"
)

const (
	RowSplitter    = "|"
	ColumnSplitter = ","
)

var d = debug.Debug("zero")

var index = make(map[Key]string)

func add(key Key, kind string) {
	d("associating key %s to type %s", key, kind)
	index[key] = kind
}

func which(key Key) (string, error) {
	d("pulling type of key %s", key)
	if v, exists := index[key]; exists {
		d("key found in map")
		return v, nil
	}
	return "", fmt.Errorf("not found")
}

package zero

import (
	"fmt"

	"github.com/tj/go-debug"
)

type Key string

type Args struct {
	Key   Key
	Type  string
	Value interface{}
}

const (
	String = "string"
	Number = "number"
	Array  = "array"
)

const (
	RowSplitter    = "|"
	ColumnSplitter = ","
)

var d = debug.Debug("zero")

var index = make(map[Key]string)

func add(key Key, kind string) {
	d("associating key %s to type %s", key, kind)
	index[key] = kind
}

func which(key Key) (string, error) {
	d("pulling type of key %s", key)
	if v, exists := index[key]; exists {
		return v, nil
	}
	return "", fmt.Errorf("key %s not found", key)
}

Make error message a bit verbose


package async

import (
  "container/list"
  "sync"
)

/*

  Used to contain the Routine functions to be processed

  This list inherits http://golang.org/pkg/container/list/ and contains all
  of the functionality that it contains, with a minor tweak to Remove. Instead
  of Remove returning the element, it returns our routine. This is used to
  ensure that our Routine is removed from the list before it's ran, and
  therefore isn't able to be called again.

*/
type List struct {
  *list.List

  Wait sync.WaitGroup
}

/*
  Create a new list
*/
func New() *List {
  return &List{
    List: list.New(),
  }
}

/*
  Add a Routine function to the current list
*/
func (l *List) Add(routine Routine) (*List, *list.Element) {
  element := l.PushBack(routine)
  return l, element
}

/*
  Add multiple Routine functions to the current list
*/
func (l *List) Multiple(routines ...Routine) (*List, []*list.Element) {
  var (
    elements = make([]*list.Element, 0)
  )

  for i := 0; i < len(routines); i++ {
    _, e := l.Add(routines[i])
    elements = append(elements, e)
  }

  return l, elements
}

/*
  Remove an element from the current list
*/
func (l *List) Remove(element *list.Element) (*List, Routine) {
  routine := l.List.Remove(element).(Routine)
  return l, routine
}

package async

import (
  "container/list"
  "sync"
)

/*

  Used to contain the Routine functions to be processed

  This list inherits https://godoc.org/container/list and contains all
  of the functionality that it contains, with a minor tweak to Remove. Instead
  of Remove returning the element, it returns our routine. This is used to
  ensure that our Routine is removed from the list before it's ran, and
  therefore isn't able to be called again.

*/
type List struct {
  *list.List

  Wait sync.WaitGroup
}

/*
  Create a new list
*/
func New() *List {
  return &List{
    List: list.New(),
  }
}

/*
  Add a Routine function to the current list
*/
func (l *List) Add(routine Routine) (*List, *list.Element) {
  element := l.PushBack(routine)
  return l, element
}

/*
  Add multiple Routine functions to the current list
*/
func (l *List) Multiple(routines ...Routine) (*List, []*list.Element) {
  var (
    elements = make([]*list.Element, 0)
  )

  for i := 0; i < len(routines); i++ {
    _, e := l.Add(routines[i])
    elements = append(elements, e)
  }

  return l, elements
}

/*
  Remove an element from the current list
*/
func (l *List) Remove(element *list.Element) (*List, Routine) {
  routine := l.List.Remove(element).(Routine)
  return l, routine
}

Replace golang.org link with godoc.org link


package main

import (
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
)

// Errors & warnings are deliberately suppressed as tidy throws warnings very easily
func Tidy(r io.Reader, xmlIn bool) ([]byte, error) {
	f, err := ioutil.TempFile("/tmp", "sajari-convert-")
	if err != nil {
		log.Println("TempFile:", err)
		return nil, err
	}
	defer os.Remove(f.Name())
	io.Copy(f, r)

	var output []byte
	if xmlIn {
		output, err = exec.Command("tidy", "-xml", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
	} else {
		output, err = exec.Command("tidy", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
	}

	if err != nil && err.Error() != "exit status 1" {
		return nil, err
	}
	return output, nil
}

package main

import (
	"io"
	"io/ioutil"
	"os"
	"os/exec"
)

// Errors & warnings are deliberately suppressed as tidy throws warnings very easily
func Tidy(r io.Reader, xmlIn bool) ([]byte, error) {
	f, err := ioutil.TempFile("/tmp", "sajari-convert-")
	if err != nil {
		return nil, err
	}
	defer os.Remove(f.Name())
	io.Copy(f, r)

	var output []byte
	if xmlIn {
		output, err = exec.Command("tidy", "-xml", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
	} else {
		output, err = exec.Command("tidy", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
	}

	if err != nil && err.Error() != "exit status 1" {
		return nil, err
	}
	return output, nil
}

Remove unnecessary log from Tidy.


package campbx

// Ticker
//
// Sample response
//
//     {"Last Trade":"244.99","Best Bid":"236.38","Best Ask":"244.99"}
type Ticker struct {
	LastTrade float32 `json:"Last Trade,string"`
	Bid       float32 `json:"Best Bid,string"`
	Ask       float32 `json:"Best Ask,string"`
}

// OrderBook represents the full order book returned by the API.
//
// Sample response/structure
//
//     { "Asks":[ [ 244.99, 0.990 ], ... ], "Bids":[ [ 236.38, 0.020 ], ... ] }
type OrderBook struct {
	Asks []Order `json:"Asks"`
	Bids []Order `json:"Bids"`
}

// Order represents the price and quanty of an individual Order, or the summary
// of multiple Orders (as in the case of an Order Book)
type Order struct {
	Price    float32
	Quantity float32
}

package campbx

// Ticker
//
// Sample response
//
//     {"Last Trade":"244.99","Best Bid":"236.38","Best Ask":"244.99"}
type Ticker struct {
	LastTrade float32 `json:"Last Trade,string"`
	Bid       float32 `json:"Best Bid,string"`
	Ask       float32 `json:"Best Ask,string"`
}

// OrderBook represents the full order book returned by the API.
//
// Sample response/structure
//
//     { "Asks":[ [ 244.99, 0.990 ], ... ], "Bids":[ [ 236.38, 0.020 ], ... ] }
type OrderBook struct {
	Asks []Order `json:"Asks"`
	Bids []Order `json:"Bids"`
}

// Order represents the price and quanty of an individual Order, or the summary
// of multiple Orders (as in the case of an Order Book)
type Order struct {
	Price    float32 `json:"price"`
	Quantity float32 `json:"amount"`
}

Add JSON struct tags to Order.


package cf_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/pivotal-cf-experimental/cf-test-helpers/cf"
)

var _ = Describe("NewUserContext", func() {

	var createUser = func() cf.UserContext {
		return cf.NewUserContext("http://FAKE_API.example.com", "FAKE_USERNAME", "FAKE_PASSWORD", "FAKE_ORG", "FAKE_SPACE")
	}

	It("returns a UserContext struct", func() {
		Expect(createUser()).To(BeAssignableToTypeOf(cf.UserContext{}))
	})

	It("sets UserContext.ApiUrl", func() {
		Expect(createUser().ApiUrl).To(Equal("http://FAKE_API.example.com"))
	})

	It("sets UserContext.name", func() {
		Expect(createUser().Username).To(Equal("FAKE_USERNAME"))
	})

	It("sets UserContext.password", func() {
		Expect(createUser().Password).To(Equal("FAKE_PASSWORD"))
	})

	It("sets UserContext.org", func() {
		Expect(createUser().Org).To(Equal("FAKE_ORG"))
	})

	It("sets UserContext.space", func() {
		Expect(createUser().Space).To(Equal("FAKE_SPACE"))
	})
})

package cf_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/pivotal-cf-experimental/cf-test-helpers/cf"
)

var _ = Describe("NewUserContext", func() {

	var createUser = func() cf.UserContext {
		return cf.NewUserContext("http://FAKE_API.example.com", "FAKE_USERNAME", "FAKE_PASSWORD", "FAKE_ORG", "FAKE_SPACE")
	}

	It("returns a UserContext struct", func() {
		Expect(createUser()).To(BeAssignableToTypeOf(cf.UserContext{}))
	})

	It("sets UserContext.ApiUrl", func() {
		Expect(createUser().ApiUrl).To(Equal("http://FAKE_API.example.com"))
	})

	It("sets UserContext.Username", func() {
		Expect(createUser().Username).To(Equal("FAKE_USERNAME"))
	})

	It("sets UserContext.Password", func() {
		Expect(createUser().Password).To(Equal("FAKE_PASSWORD"))
	})

	It("sets UserContext.Org", func() {
		Expect(createUser().Org).To(Equal("FAKE_ORG"))
	})

	It("sets UserContext.Space", func() {
		Expect(createUser().Space).To(Equal("FAKE_SPACE"))
	})
})

Fix spec descriptions Fix spec descriptions to match property names


package waldo

import "math"

// Sample represents data drawn from some distribution.  To compute
// the Wald statistics we need to have a point estimator function
// (e.g., the maximum likelihood estimator (MLE))
// as well as the sampling distribution's variance.  Recall
// that the sampling distribution is defined as the distribution of
// the point estimator.
type Sample interface {
	Estimator() float64
	Variance() float64
}

// sample converts a pair (param estimate, variance) into
// a Sample implementation.
type sample struct {
	mle      float64
	variance float64
}

func (s sample) Estimator() float64 { return s.mle }
func (s sample) Variance() float64  { return s.variance }

// NewSample converts a sample parameter estimate and variance into a
// struct that implements the Sample interface.
func NewSample(estimate, variance float64) Sample {
	return sample{mle: estimate, variance: variance}
}

// StandardError computes an estimate for the standard error
// of a point estimator, as encoded in a Sample.
// The standard error is the standard deviation of the estimator's distribution.
// SInce the variance of this distribution is estimated, hence the overall
// calculation itself is an estimate.
func StandardError(s Sample) float64 {
	return math.Pow(s.Variance(), 0.5)
}

package waldo

import "math"

// Sample represents data drawn from some distribution.  To compute
// the Wald statistics we need to have a point estimator function
// (e.g., the maximum likelihood estimator (MLE))
// as well as the sampling distribution's variance.  Recall
// that the sampling distribution is defined as the distribution of
// the point estimator.
//
// The estimator in question should be
// asymptotically normal, which is to say that the difference between
// the estimator (as a random variable of the data size) and the parameter
// being estimated over the standard error of the estimator converges
// in distribution to a standard normal distribution.
type Sample interface {
	Estimator() float64
	Variance() float64
}

// sample converts a pair (param estimate, variance) into
// a Sample implementation.
type sample struct {
	mle      float64
	variance float64
}

func (s sample) Estimator() float64 { return s.mle }
func (s sample) Variance() float64  { return s.variance }

// NewSample converts a sample parameter estimate and variance into a
// struct that implements the Sample interface.
func NewSample(estimate, variance float64) Sample {
	return sample{mle: estimate, variance: variance}
}

// StandardError computes an estimate for the standard error
// of a point estimator, as encoded in a Sample.
// The standard error is the standard deviation of the estimator's distribution.
// SInce the variance of this distribution is estimated, hence the overall
// calculation itself is an estimate.
func StandardError(s Sample) float64 {
	return math.Pow(s.Variance(), 0.5)
}

Add comments about asymptotic normality.


package instana

// SpanContext holds the basic Span metadata.
type SpanContext struct {
	// A probabilistically unique identifier for a [multi-span] trace.
	TraceID uint64

	// A probabilistically unique identifier for a span.
	SpanID uint64

	// Whether the trace is sampled.
	Sampled bool

	// The span's associated baggage.
	Baggage map[string]string // initialized on first use
}

// ForeachBaggageItem belongs to the opentracing.SpanContext interface
func (c SpanContext) ForeachBaggageItem(handler func(k, v string) bool) {
	for k, v := range c.Baggage {
		if !handler(k, v) {
			break
		}
	}
}

// WithBaggageItem returns an entirely new SpanContext with the
// given key:value baggage pair set.
func (c SpanContext) WithBaggageItem(key, val string) SpanContext {
	var newBaggage map[string]string
	if c.Baggage == nil {
		newBaggage = map[string]string{key: val}
	} else {
		newBaggage = make(map[string]string, len(c.Baggage)+1)
		for k, v := range c.Baggage {
			newBaggage[k] = v
		}
		newBaggage[key] = val
	}
	// Use positional parameters so the compiler will help catch new fields.
	return SpanContext{c.TraceID, c.SpanID, c.Sampled, newBaggage}
}

package instana

// SpanContext holds the basic Span metadata.
type SpanContext struct {
	// A probabilistically unique identifier for a [multi-span] trace.
	TraceID int64

	// A probabilistically unique identifier for a span.
	SpanID int64

	// Whether the trace is sampled.
	Sampled bool

	// The span's associated baggage.
	Baggage map[string]string // initialized on first use
}

// ForeachBaggageItem belongs to the opentracing.SpanContext interface
func (c SpanContext) ForeachBaggageItem(handler func(k, v string) bool) {
	for k, v := range c.Baggage {
		if !handler(k, v) {
			break
		}
	}
}

// WithBaggageItem returns an entirely new SpanContext with the
// given key:value baggage pair set.
func (c SpanContext) WithBaggageItem(key, val string) SpanContext {
	var newBaggage map[string]string
	if c.Baggage == nil {
		newBaggage = map[string]string{key: val}
	} else {
		newBaggage = make(map[string]string, len(c.Baggage)+1)
		for k, v := range c.Baggage {
			newBaggage[k] = v
		}
		newBaggage[key] = val
	}
	// Use positional parameters so the compiler will help catch new fields.
	return SpanContext{c.TraceID, c.SpanID, c.Sampled, newBaggage}
}

Store IDs as signed integers


package sqlstmt

import (
	"database/sql"
)

// DB is the interface that wraps the database access methods
// used by this package.
//
// The *DB and *Tx types in the standard library package "database/sql"
// both implement this interface.
type DB interface {
	// Exec executes a query without returning any rows.
	// The args are for any placeholder parameters in the query.
	Exec(query string, args ...interface{}) (sql.Result, error)

	// Query executes a query that returns rows, typically a SELECT.
	// The args are for any placeholder parameters in the query.
	Query(query string, args ...interface{}) (*sql.Rows, error)
}

// SQLLogger is an interface for logging SQL statements executed
// by the sqlstmt package.
type SQLLogger interface {
	// LogSQL is called by the sqlstmt package after it executes an SQL query or statement.
	//
	// The query and args variables provide the query and associated arguments supplied to
	// the database server.  The rowsAffected and err variables provide a summary of the
	// query results. If the number of rows affected cannot be determined for any reason,
	// then rowsAffected is set to -1.
	LogSQL(query string, args []interface{}, rowsAffected int, err error)
}

package sqlstmt

import (
	"database/sql"
)

// DB is the interface that wraps the database access methods
// used by this package.
//
// The *DB and *Tx types in the standard library package "database/sql"
// both implement this interface.
type DB interface {
	// Exec executes a query without returning any rows.
	// The args are for any placeholder parameters in the query.
	Exec(query string, args ...interface{}) (sql.Result, error)

	// Query executes a query that returns rows, typically a SELECT.
	// The args are for any placeholder parameters in the query.
	Query(query string, args ...interface{}) (*sql.Rows, error)
}

// SQLLogger is an interface for logging SQL statements executed
// by the sqlstmt package.
type SQLLogger interface {
	// LogSQL is called by the sqlstmt package after it executes
	// an SQL query or statement.
	//
	// The query and args variables provide the query and associated
	// arguments supplied to the database server.  The rowsAffected
	// and err variables provide a summary of the query results.
	// If the number of rows affected cannot be determined for any reason,
	// then rowsAffected is set to -1.
	LogSQL(query string, args []interface{}, rowsAffected int, err error)
}

Reformat SQLLogger comments to fit in godoc HTML page.


package main

import (
	"testing"
)

func sumOfPrimesBelow(x int) int {
	sieve := make([]bool, x)
	for i:=0; i<x; i++ {
		sieve[i] = true
	}
	sieve[0] = false
	sieve[1] = false

	for i:=2; i<x; i++ {
		if sieve[i] == false {
			continue
		}
		for j:=2*i; j<x; j+=i {
			sieve[j] = false
		}

	}

	sum := 0
	for i:=2; i<x; i++ {
		if sieve[i] {
			sum += i;
		}
	}
	return sum
}

func TestSumOfPrimesBelow2M(t *testing.T) {
	x := sumOfPrimesBelow(2000000)
	answer := 142913828922
	if x != answer {
		t.Errorf("result = %v, want %v", x, answer)
	}

}

func BenchmarkSumOfPrimesBelow2M(b *testing.B) {
	for i := 0; i < b.N; i++ {
		sumOfPrimesBelow(2000000)
	}
}

Add benchmarking code to Prob 10


package rpcd

import (
	"github.com/Symantec/Dominator/dom/herd"
	"github.com/Symantec/Dominator/lib/srpc"
	"log"
)

type rpcType struct {
	herd   *herd.Herd
	logger *log.Logger
}

func Setup(herd *herd.Herd, logger *log.Logger) {
	rpcObj := &rpcType{
		herd:   herd,
		logger: logger}
	srpc.RegisterName("Dominator", rpcObj)
}

package rpcd

import (
	"github.com/Symantec/Dominator/dom/herd"
	"github.com/Symantec/Dominator/lib/log"
	"github.com/Symantec/Dominator/lib/srpc"
)

type rpcType struct {
	herd   *herd.Herd
	logger log.Logger
}

func Setup(herd *herd.Herd, logger log.Logger) {
	rpcObj := &rpcType{
		herd:   herd,
		logger: logger}
	srpc.RegisterName("Dominator", rpcObj)
}

Change dom/rpcd.Setup() to use log.Logger interface type.


package bbolt

import "unsafe"

func unsafeAdd(base unsafe.Pointer, offset uintptr) unsafe.Pointer {
	return unsafe.Pointer(uintptr(base) + offset)
}

func unsafeIndex(base unsafe.Pointer, offset uintptr, elemsz uintptr, n int) unsafe.Pointer {
	return unsafe.Pointer(uintptr(base) + offset + uintptr(n)*elemsz)
}

func unsafeByteSlice(base unsafe.Pointer, offset uintptr, i, j int) []byte {
	return (*[maxAllocSize]byte)(unsafeAdd(base, offset))[i:j:j]
}

package bbolt

import "unsafe"

func unsafeAdd(base unsafe.Pointer, offset uintptr) unsafe.Pointer {
	return unsafe.Pointer(uintptr(base) + offset)
}

func unsafeIndex(base unsafe.Pointer, offset uintptr, elemsz uintptr, n int) unsafe.Pointer {
	return unsafe.Pointer(uintptr(base) + offset + uintptr(n)*elemsz)
}

func unsafeByteSlice(base unsafe.Pointer, offset uintptr, i, j int) []byte {
	// See: https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
	//
	// This memory is not allocated from C, but it is unmanaged by Go's
	// garbage collector and should behave similarly, and the compiler
	// should produce similar code.  Note that this conversion allows a
	// subslice to begin after the base address, with an optional offset,
	// while the URL above does not cover this case and only slices from
	// index 0.  However, the wiki never says that the address must be to
	// the beginning of a C allocation (or even that malloc was used at
	// all), so this is believed to be correct.
	return (*[maxAllocSize]byte)(unsafeAdd(base, offset))[i:j:j]
}

Comment the byte slice conversion


package integration_tests

import (
	"testing"
)

func TestConnection(t *testing.T) {
	listen := NewNodeBinary(BinaryOptions{Listen: "[::1]:9999", Fake_money: true})
	listen.Start()
	defer listen.KillAndPrint(t)
	listen_id, err := WaitForID(listen)
	if err != nil {
		t.Fatal(err)
	}

	connect := NewNodeBinary(BinaryOptions{
		Listen:     "[::1]:9998",
		Connect:    []string{"[::1]:9999"},
		Fake_money: true})
	connect.Start()
	defer connect.KillAndPrint(t)
	connect_id, err := WaitForID(connect)

	err = WaitForConnection(listen, connect_id)
	if err != nil {
		t.Fatal(err)
	}
	err = WaitForConnection(connect, listen_id)
	if err != nil {
		t.Fatal(err)
	}
}

package integration_tests

import (
	"testing"
)

func TestConnection(t *testing.T) {
	listen := NewNodeBinary(BinaryOptions{Listen: "[::1]:9999", Fake_money: true})
	listen.Start()
	defer listen.KillAndPrint(t)
	listen_id, err := WaitForID(listen)
	if err != nil {
		t.Fatal(err)
	}

	connect := NewNodeBinary(BinaryOptions{
		Listen:     "[::1]:9998",
		Connect:    []string{"[::1]:9999"},
		Fake_money: true})
	connect.Start()
	defer connect.KillAndPrint(t)
	connect_id, err := WaitForID(connect)
	if err != nil {
	  t.Fatal(err)
	}

	err = WaitForConnection(listen, connect_id)
	if err != nil {
		t.Fatal(err)
	}
	err = WaitForConnection(connect, listen_id)
	if err != nil {
		t.Fatal(err)
	}
}

Check an error that was being ignored.


package main

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"

	"github.com/squaremo/flux/common/store"
	"github.com/squaremo/flux/common/store/etcdstore"
)

func main() {
	store := etcdstore.NewFromEnv()
	var topCmd = &cobra.Command{
		Use:   "fluxctl",
		Short: "control flux",
		Long:  `Define services and enrol instances in them`,
	}
	addSubCommands(topCmd, store)
	if err := topCmd.Execute(); err != nil {
		exitWithErrorf(err.Error())
	}
}

func addSubCommand(c commandOpts, cmd *cobra.Command, st store.Store) {
	c.setStore(st)
	cmd.AddCommand(c.makeCommand())
}

func addSubCommands(cmd *cobra.Command, store store.Store) {
	addSubCommand(&addOpts{}, cmd, store)
	addSubCommand(&listOpts{}, cmd, store)
	addSubCommand(&queryOpts{}, cmd, store)
	addSubCommand(&rmOpts{}, cmd, store)
	addSubCommand(&selectOpts{}, cmd, store)
	addSubCommand(&deselectOpts{}, cmd, store)
}

func exitWithErrorf(format string, vals ...interface{}) {
	fmt.Fprintf(os.Stderr, format, vals...)
	os.Exit(1)
}

package main

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"

	"github.com/squaremo/flux/common/store"
	"github.com/squaremo/flux/common/store/etcdstore"
)

func main() {
	store := etcdstore.NewFromEnv()
	var topCmd = &cobra.Command{
		Use:   "fluxctl",
		Short: "control flux",
		Long:  `Define services and enrol instances in them`,
	}
	addSubCommands(topCmd, store)
	if err := topCmd.Execute(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func addSubCommand(c commandOpts, cmd *cobra.Command, st store.Store) {
	c.setStore(st)
	cmd.AddCommand(c.makeCommand())
}

func addSubCommands(cmd *cobra.Command, store store.Store) {
	addSubCommand(&addOpts{}, cmd, store)
	addSubCommand(&listOpts{}, cmd, store)
	addSubCommand(&queryOpts{}, cmd, store)
	addSubCommand(&rmOpts{}, cmd, store)
	addSubCommand(&selectOpts{}, cmd, store)
	addSubCommand(&deselectOpts{}, cmd, store)
}

Print a newline after an error message


package main

import (
	"net/http"
)

type ResponseWriter interface {
	Header() http.Header
	Write([]byte) (int, error)
	WriteHeader(int)
}

type Route struct {
	Name        string
	Method      string
	Pattern     string
	HandlerFunc http.HandlerFunc
}

type Routes []Route

var routes = Routes{
	Route{
		"Index",
		"GET",
		"/",
		Index,
	},
	Route{
		"PostIndex",
		"GET",
		"/api/posts",
		PostIndex,
	},
	Route{
		"PostCreate",
		"POST",
		"/api/posts",
		PostCreate,
	},
	Route{
		"PostShow",
		"GET",
		"/api/posts/{postId}",
		PostShow,
	},
	Route{
		"PostDelete",
		"DELETE",
		"/api/posts/{postId}",
		PostDelete,
	},
}

package main

import (
	"net/http"
)

type ResponseWriter interface {
	Header() http.Header
	Write([]byte) (int, error)
	WriteHeader(int)
}

type Route struct {
	Name        string
	Method      string
	Pattern     string
	HandlerFunc http.HandlerFunc
}

type Routes []Route

var routes = Routes{
	Route{
		"Index",
		"GET",
		"/",
		Index,
	},
	Route{
		"PostIndex",
		"GET",
		"/api/posts",
		PostIndex,
	},
	Route{
		"PostCreate",
		"POST",
		"/api/posts",
		PostCreate,
	},
	Route{
		"PostShow",
		"GET",
		"/api/posts/{postId}",
		PostShow,
	},
	Route{
		"PostUpdate",
		"PUT",
		"/api/posts/{postId}",
		PostUpdate,
	},
	Route{
		"PostDelete",
		"DELETE",
		"/api/posts/{postId}",
		PostDelete,
	},
}

Add route for updating a post