package main

import (
	"flag"
	"fmt"
	"log"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

type user struct {
	name     string
	email    string
	url      string
	username string
}

func main() {
	url := flag.String("github_url", "", "github url you want to scrape")
	flag.Parse()
	githubURL := *url
	doc, err := goquery.NewDocument(githubURL)
	if err != nil {
		log.Fatal(err)
	}

	if strings.Contains(githubURL, "/orgs/") {
		scrapeOrganization(doc, githubURL)
	} else if strings.Contains(githubURL, "/search?") {
		scrapeSearch(doc, githubURL)
	} else if strings.Contains(githubURL, "/stargazers") {
		fmt.Println("Stargazer URL. Beginning to scrape.")
		scrapeStarGazers(doc, githubURL)
	} else {
		scrapeProfile(doc)
	}
}

package main

import (
	"flag"
	"fmt"
	"log"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

type user struct {
	name     string
	email    string
	url      string
	username string
}

func main() {
	url := flag.String("github_url", "", "github url you want to scrape")
	flag.Parse()
	githubURL := *url
	doc, err := goquery.NewDocument(githubURL)
	if err != nil {
		log.Fatal(err)
	}

	if strings.Contains(githubURL, "/orgs/") {
		fmt.Println("Organization URL. Beginning to scrape.")
		scrapeOrganization(doc, githubURL)
	} else if strings.Contains(githubURL, "/search?") {
		fmt.Println("Search URL. Beginning to scrape.")
		scrapeSearch(doc, githubURL)
	} else if strings.Contains(githubURL, "/stargazers") {
		fmt.Println("Stargazer URL. Beginning to scrape.")
		scrapeStarGazers(doc, githubURL)
	} else {
		fmt.Println("Single profile URL. Beginning to scrape.")
		scrapeProfile(doc)
	}
}

Add some output to let users know what is about to be scraped.


package hammock

import (
	"fmt"

	"github.com/mikebell-org/go-couchdb"
)

type CouchDB struct {
	couchdb.CouchDB
}

func Database(host, database, username, password string) (*CouchDB, error) {

	db, err := couchdb.Database(host, database, username, password)

	return &CouchDB{*db}, err
}

func Sync(db *CouchDB, path string) (changes []string, err error) {

	// TODO: implement a document freezing option

	disk_data := newDesignDocCollection()

	if err = disk_data.loadFromDisk(path); err == nil {

		for doc_name, document := range disk_data.Documents {

			db_data := newDesignDocument(doc_name)

			if err = db.GetDocument(&db_data, fmt.Sprintf("%v", doc_name)); err != nil {

				changes = append(changes, fmt.Sprintf("Design document %v is missing", doc_name))
			}

			if updated, doc_changes := db_data.update(document); updated {

				changes = append(changes, doc_changes...)

				if success, e := db.PutDocument(db_data, doc_name); e != nil || !success.OK {

					err = e
					return
				}
			}
		}
	}

	return
}

package hammock

import (
	"fmt"

	"github.com/mikebell-org/go-couchdb"
)

type CouchDB struct {
	couchdb.CouchDB
}

func Database(host, database, username, password string) (*CouchDB, error) {

	db, err := couchdb.Database(host, database, username, password)

	return &CouchDB{*db}, err
}

func Sync(db *CouchDB, path string) (changes []string, err error) {

	// TODO: implement a document freezing option

	disk_data := newDesignDocCollection()

	if err = disk_data.loadFromDisk(path); err == nil {

		for doc_name, document := range disk_data.Documents {

			db_data := newDesignDocument(doc_name)

			if err = db.GetDocument(&db_data, fmt.Sprintf("%v", doc_name)); err != nil {

				changes = append(changes, fmt.Sprintf("Design document %v is missing", doc_name))
				err = nil
			}

			if updated, doc_changes := db_data.update(document); updated {

				changes = append(changes, doc_changes...)

				if success, e := db.PutDocument(db_data, doc_name); e != nil || !success.OK {

					err = e
					return
				}
			}
		}
	}

	return
}

Reset err after call to GetDocument()


package gorduino

import (
	"github.com/kraman/go-firmata"
)

type Gorduino struct {
	pins   map[byte]bool
	client *firmata.FirmataClient
	work   func()
}

func NewGorduino(port string, pins ...byte) *Gorduino {
	g := new(Gorduino)
	g.pins = make(map[byte]bool)
	g.client, _ = firmata.NewClient(port, 57600)
	for _, pin := range pins {
		g.pins[pin] = false
		g.client.SetPinMode(pin, firmata.Output)
	}
	return g
}

func (g *Gorduino) On(p byte) {
	g.client.DigitalWrite(uint(p), true)
}

func (g *Gorduino) Off(p byte) {
	g.client.DigitalWrite(uint(p), false)
}

func (g *Gorduino) Toggle(p byte) {
	g.pins[p] = !g.pins[p]
	g.client.DigitalWrite(uint(p), g.pins[p])
}

package gorduino

import (
	"github.com/tarm/goserial"
	"github.com/yanzay/go-firmata"
)

type Gorduino struct {
	pins   map[byte]bool
	client *firmata.FirmataClient
	work   func()
}

func NewGorduino(port string, pins ...byte) (*Gorduino, error) {
	g := new(Gorduino)
	g.pins = make(map[byte]bool)

	c := &serial.Config{Name: port, Baud: 57600}
	conn, err := serial.OpenPort(c)
	if err != nil {
		return nil, err
	}

	g.client, _ = firmata.NewClient(conn)

	for _, pin := range pins {
		g.pins[pin] = false
		g.client.SetPinMode(pin, firmata.Output)
	}
	return g, nil
}

func (g *Gorduino) On(p byte) {
	g.client.DigitalWrite(uint(p), true)
}

func (g *Gorduino) Off(p byte) {
	g.client.DigitalWrite(uint(p), false)
}

func (g *Gorduino) Toggle(p byte) {
	g.pins[p] = !g.pins[p]
	g.client.DigitalWrite(uint(p), g.pins[p])
}

Add serial adaptor and error handling.


package restic

import (
	"log"
	"net"
	"os"
)

// Addr implements net.Addr for stdin/stdout.
type Addr struct{}

// Network returns the network type as a string.
func (a Addr) Network() string {
	return "stdio"
}

func (a Addr) String() string {
	return "stdio"
}

// StdioConn implements a net.Conn via stdin/stdout.
type StdioConn struct {
	stdin  *os.File
	stdout *os.File
}

func (s *StdioConn) Read(p []byte) (int, error) {
	return s.stdin.Read(p)
}

func (s *StdioConn) Write(p []byte) (int, error) {
	return s.stdout.Write(p)
}

// Close closes both streams.
func (s *StdioConn) Close() error {
	log.Printf("Server.Close()\n")
	err1 := s.stdin.Close()
	err2 := s.stdout.Close()
	if err1 != nil {
		return err1
	}
	return err2
}

// LocalAddr returns nil.
func (s *StdioConn) LocalAddr() net.Addr {
	return Addr{}
}

// RemoteAddr returns nil.
func (s *StdioConn) RemoteAddr() net.Addr {
	return Addr{}
}

package restic

import (
	"net"
	"os"
)

// Addr implements net.Addr for stdin/stdout.
type Addr struct{}

// Network returns the network type as a string.
func (a Addr) Network() string {
	return "stdio"
}

func (a Addr) String() string {
	return "stdio"
}

// StdioConn implements a net.Conn via stdin/stdout.
type StdioConn struct {
	stdin  *os.File
	stdout *os.File
}

func (s *StdioConn) Read(p []byte) (int, error) {
	return s.stdin.Read(p)
}

func (s *StdioConn) Write(p []byte) (int, error) {
	return s.stdout.Write(p)
}

// Close closes both streams.
func (s *StdioConn) Close() error {
	err1 := s.stdin.Close()
	err2 := s.stdout.Close()
	if err1 != nil {
		return err1
	}
	return err2
}

// LocalAddr returns nil.
func (s *StdioConn) LocalAddr() net.Addr {
	return Addr{}
}

// RemoteAddr returns nil.
func (s *StdioConn) RemoteAddr() net.Addr {
	return Addr{}
}

Remove log message on Close


package weedharvester

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

type master struct {
	url string
}
type assignment struct {
	Count     int    `json:"count"`
	Fid       string `json:"fid"`
	URL       string `json:"url"`
	PublicURL string `json:"publicUrl"`
}

func (m *master) Assign() assignment {
	completeURL := m.url + "/dir/assign"
	response, err := http.Get(completeURL)
	if err != nil {
		panic(fmt.Sprintf("Error: Unable to ask for assignment at: %s", completeURL))
	}

	assign := assignment{}

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		panic(err)
	}
	json.Unmarshal(body, &assign)

	return assign
}

func (m *master) Find() (url string) {
	return "http://docker:8080"
}

package weedharvester

import (
	"fmt"
	"net/http"
)

type master struct {
	url string
}
type assignment struct {
	Count     int    `json:"count"`
	Fid       string `json:"fid"`
	URL       string `json:"url"`
	PublicURL string `json:"publicUrl"`
}

func (m *master) Assign() assignment {
	completeURL := m.url + "/dir/assign"
	response, err := http.Get(completeURL)
	if err != nil {
		panic(fmt.Sprintf("Error: Unable to ask for assignment at: %s", completeURL))
	}

	assign := assignment{}
	decodeJSON(response.Body, &assign)

	return assign
}

func (m *master) Find() (url string) {
	return "http://docker:8080"
}

Use json decoder instead of marshalling


package harness

import (
	log "github.com/Sirupsen/logrus"
	"github.com/prometheus/client_golang/prometheus"
)

type MetricRegistry struct {
	metrics map[string]prometheus.Collector
}

func newRegistry() *MetricRegistry {
	return &MetricRegistry{
		metrics: make(map[string]prometheus.Collector),
	}
}

func (reg *MetricRegistry) Register(name string, metric prometheus.Collector) {
	log.Infof("metric registered;name:<%s>", name)
	reg.metrics[name] = metric
	prometheus.MustRegister(metric)
}

func (reg *MetricRegistry) Unregister(name string) {
	if metric := reg.metrics[name]; metric != nil {
		log.Infof("metric unregistered;name:<%s>", name)
		prometheus.Unregister(metric)
		delete(reg.metrics, name)
	}
}

func (reg *MetricRegistry) Get(name string) prometheus.Collector {
	return reg.metrics[name]
}

func (reg *MetricRegistry) Reset() {
	for _, metric := range reg.metrics {
		if vec, ok := metric.(*prometheus.MetricVec); ok {
			vec.Reset()
		}
	}
}

package harness

import (
	log "github.com/Sirupsen/logrus"
	"github.com/prometheus/client_golang/prometheus"
)

type MetricRegistry struct {
	metrics map[string]prometheus.Collector
}

func newRegistry() *MetricRegistry {
	return &MetricRegistry{
		metrics: make(map[string]prometheus.Collector),
	}
}

func (reg *MetricRegistry) Register(name string, metric prometheus.Collector) {
	log.Infof("metric registered;name:<%s>", name)
	reg.metrics[name] = metric
	prometheus.MustRegister(metric)
}

func (reg *MetricRegistry) Unregister(name string) {
	if metric := reg.metrics[name]; metric != nil {
		log.Infof("metric unregistered;name:<%s>", name)
		prometheus.Unregister(metric)
		delete(reg.metrics, name)
	}
}

func (reg *MetricRegistry) Get(name string) prometheus.Collector {
	return reg.metrics[name]
}

// Since prometheus.MetricVec is a struct but not interface,
// need to intrduce an interface to check if we can call Reset() on a metric.
type resettable interface {
	Reset()
}

func (reg *MetricRegistry) Reset() {
	for name, metric := range reg.metrics {
		if vec, ok := metric.(resettable); ok {
			log.Debugf("resetting metric;name:<%s>", name)
			vec.Reset()
		}
	}
}

Fix a bug that metrics wans't reset properly


// +build builtin_assets

package main

import (
	"context"
	"net/http"
	"path"
	"path/filepath"
	"strings"
)

const (
	httpDefaultPath = "html/index.html"
)

func (w *httpWorker) httpHandleAsset(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
	var ct string

	// Stop handling assets if frontend is disabled
	if w.disableFrontend {
		rw.WriteHeader(http.StatusForbidden)
		return
	}

	// Get file data from built-in assets
	filePath := strings.TrimPrefix(r.URL.Path, "/assets/")
	if strings.HasSuffix(filePath, "/") || filepath.Ext(filePath) == "" {
		filePath = httpDefaultPath
	}

	data, err := Asset(filePath)
	if err != nil {
		rw.WriteHeader(http.StatusNotFound)
		return
	}

	// Get asset content type
	switch path.Ext(filePath) {
	case ".css":
		ct = "text/css"

	case ".js":
		ct = "text/javascript"

	default:
		ct = http.DetectContentType(data)
	}

	rw.Header().Set("Content-Type", ct)
	rw.WriteHeader(http.StatusOK)
	rw.Write(data)
}

// +build builtin_assets

package main

import (
	"context"
	"net/http"
	"path"
	"path/filepath"
	"strings"
)

const (
	httpDefaultPath = "html/index.html"
)

func (w *httpWorker) httpHandleAsset(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
	var ct string

	// Stop handling assets if frontend is disabled
	if !w.enableFrontend {
		rw.WriteHeader(http.StatusForbidden)
		return
	}

	// Get file data from built-in assets
	filePath := strings.TrimPrefix(r.URL.Path, "/assets/")
	if strings.HasSuffix(filePath, "/") || filepath.Ext(filePath) == "" {
		filePath = httpDefaultPath
	}

	data, err := Asset(filePath)
	if err != nil {
		rw.WriteHeader(http.StatusNotFound)
		return
	}

	// Get asset content type
	switch path.Ext(filePath) {
	case ".css":
		ct = "text/css"

	case ".js":
		ct = "text/javascript"

	default:
		ct = http.DetectContentType(data)
	}

	rw.Header().Set("Content-Type", ct)
	rw.WriteHeader(http.StatusOK)
	rw.Write(data)
}

Fix failing build in 'builtin_assets' mode


package jsonconfig

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

// Parser must implement ParseJSON
type Parser interface {
	ParseJSON([]byte) error
}

// Load the JSON config file
func Load(configFile string, p Parser) {
	var err error
	var input = io.ReadCloser(os.Stdin)
	if input, err = os.Open(configFile); err != nil {
		log.Fatalln(err)
	}

	// Read the config file
	jsonBytes, err := ioutil.ReadAll(input)
	input.Close()
	if err != nil {
		log.Fatalln(err)
	}

	// Parse the config
	if err := p.ParseJSON(jsonBytes); err != nil {
		log.Fatalln("Could not parse %q: %v", configFile, err)
	}
}

package jsonconfig

import (
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
)

// Parser must implement ParseJSON
type Parser interface {
	ParseJSON([]byte) error
}

// Load the JSON config file
func Load(configFile string, p Parser) {
	var err error
	var absPath string
	var input = io.ReadCloser(os.Stdin)
	if absPath, err = filepath.Abs(configFile); err != nil {
		log.Fatalln(err)
	}

	if input, err = os.Open(absPath); err != nil {
		log.Fatalln(err)
	}

	// Read the config file
	jsonBytes, err := ioutil.ReadAll(input)
	input.Close()
	if err != nil {
		log.Fatalln(err)
	}

	// Parse the config
	if err := p.ParseJSON(jsonBytes); err != nil {
		log.Fatalln("Could not parse %q: %v", configFile, err)
	}
}

Use relative path to load config.json to fix file not found


package dev

import (
	"crypto/tls"
	"net/http"
	"puma/httputil"
	"time"
)

func (h *HTTPServer) ServeTLS() error {
	proxy := &httputil.ReverseProxy{
		Director:      h.director,
		Transport:     h.transport,
		FlushInterval: 1 * time.Second,
		Debug:         h.Debug,
	}

	certCache := NewCertCache()

	tlsConfig := &tls.Config{
		GetCertificate: certCache.GetCertificate,
	}

	serv := http.Server{
		Addr:      h.TLSAddress,
		Handler:   proxy,
		TLSConfig: tlsConfig,
	}

	return serv.ListenAndServeTLS("", "")
}

func (h *HTTPServer) Serve() error {
	proxy := &httputil.ReverseProxy{
		Director:      h.director,
		Transport:     h.transport,
		FlushInterval: 1 * time.Second,
		Debug:         h.Debug,
	}

	serv := http.Server{
		Addr:    h.Address,
		Handler: proxy,
	}

	return serv.ListenAndServe()
}

package dev

import (
	"crypto/tls"
	"net/http"
)

func (h *HTTPServer) ServeTLS() error {
	certCache := NewCertCache()

	tlsConfig := &tls.Config{
		GetCertificate: certCache.GetCertificate,
	}

	serv := http.Server{
		Addr:      h.TLSAddress,
		Handler:   h,
		TLSConfig: tlsConfig,
	}

	return serv.ListenAndServeTLS("", "")
}

func (h *HTTPServer) Serve() error {
	serv := http.Server{
		Addr:    h.Address,
		Handler: h,
	}

	return serv.ListenAndServe()
}

Use correct handler on linux


package main_test

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

	"testing"
)

func TestGithubReviewHelper(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "GithubReviewHelper Suite")
}

package main_test

import (
	"io/ioutil"
	"log"

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

	"testing"
)

func TestGithubReviewHelper(t *testing.T) {
	RegisterFailHandler(Fail)
	log.SetOutput(ioutil.Discard)
	RunSpecs(t, "GithubReviewHelper Suite")
}

Disable logging for the tests


package main

import (
	"fmt"
	"log"
	"net/http"
	"time"
)

func loggingMiddleware(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		t1 := time.Now()
		next.ServeHTTP(w, r)
		t2 := time.Now()
		log.Printf("[%s] %q %v\n", r.Method, r.URL.String(), t2.Sub(t1))
	}
	return http.HandlerFunc(fn)
}

func helloWorld(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, world!\n")
}

func main() {
	helloWorldHandler := http.HandlerFunc(helloWorld)
	http.Handle("/hello", loggingMiddleware(helloWorldHandler))
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

package main

import (
	"fmt"
	"log"
	"net/http"
	"net/url"
	"time"
)

func loggingMiddleware(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		t1 := time.Now()
		next.ServeHTTP(w, r)
		t2 := time.Now()
		log.Printf("[%s] %q %v\n", r.Method, r.URL.String(), t2.Sub(t1))
	}
	return http.HandlerFunc(fn)
}

func helloWorld(w http.ResponseWriter, r *http.Request) {
	log.Print(url.QueryEscape("Hello, World"))
	fmt.Fprint(w, "Hello, world!\n")
}

func main() {
	helloWorldHandler := http.HandlerFunc(helloWorld)
	http.Handle("/hello", loggingMiddleware(helloWorldHandler))
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

Add more logging in example


// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Command fortuned runs a daemon that implements the Fortune interface.
package main

import (
	"flag"
	"log"

	"v.io/v23"
	"v.io/v23/security"
	"v.io/x/ref/examples/fortune"
	"v.io/x/ref/lib/signals"

	// The v23.Init call below will use the generic runtime factory.
	_ "v.io/x/ref/runtime/factories/generic"
)

var (
	name = flag.String("name", "", "Name for fortuned in default mount table")
)

func main() {
	ctx, shutdown := v23.Init()
	defer shutdown()

	authorizer := security.DefaultAuthorizer()
	impl := newImpl()
	service := fortune.FortuneServer(impl)

	ctx, server, err := v23.WithNewServer(ctx, *name, service, authorizer)
	if err != nil {
		log.Panic("Failure creating server: ", err)
	}
	log.Printf("Listening at: %v\n", server.Status().Endpoints[0])

	<-signals.ShutdownOnSignals(ctx)
}

// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Command fortuned runs a daemon that implements the Fortune interface.
package main

import (
	"flag"
	"log"

	"v.io/v23"
	"v.io/v23/security"
	"v.io/x/ref/examples/fortune"
	"v.io/x/ref/lib/signals"

	// The v23.Init call below will use the roaming runtime factory.
	_ "v.io/x/ref/runtime/factories/roaming"
)

var (
	name = flag.String("name", "", "Name for fortuned in default mount table")
)

func main() {
	ctx, shutdown := v23.Init()
	defer shutdown()

	authorizer := security.DefaultAuthorizer()
	impl := newImpl()
	service := fortune.FortuneServer(impl)

	ctx, server, err := v23.WithNewServer(ctx, *name, service, authorizer)
	if err != nil {
		log.Panic("Failure creating server: ", err)
	}
	log.Printf("Listening at: %v\n", server.Status().Endpoints[0])

	<-signals.ShutdownOnSignals(ctx)
}

Use the roaming and not the generic runtime factory


package main

import (
	"fmt"
	"os"
)

func main() {
	env := &environment{
		values: map[object]object{
			scmSymbol("true"):  TRUE,
			scmSymbol("false"): FALSE,
		},
	}

	for _, proc := range makePrimitives(env) {
		env.values[scmSymbol(proc.name)] = proc
	}

	currentScanner = newScanner(os.Stdin)

	for {
		fmt.Printf("> ")
		fmt.Printf("%s\n", eval(read(), env))
	}
}

package main

import (
	"flag"
	"fmt"
	"os"
)

func main() {
	var (
		sicp = flag.Bool("sicp", false, "enter directly to sicp evaluator")
	)

	flag.Parse()

	env := &environment{
		values: map[object]object{
			scmSymbol("true"):  TRUE,
			scmSymbol("false"): FALSE,
		},
	}

	for _, proc := range makePrimitives(env) {
		env.values[scmSymbol(proc.name)] = proc
	}

	currentScanner = newScanner(os.Stdin)

	if *sicp {
		env.values[scmSymbol("load-file!")].(primitive).Call(&cell{
			car: scmString("aim.lisp"),
			cdr: NIL,
		})

		return
	}

	for {
		fmt.Printf("> ")
		fmt.Printf("%s\n", eval(read(), env))
	}
}

Add sicp flag to jump to metacircular evaluator


package main

import (
	_ "expvar"
	"net/http"
	"os"

	"github.com/bmizerany/pat"
	"github.com/codegangsta/negroni"
	"github.com/meatballhat/negroni-logrus"
	"github.com/unrolled/render"
)

func main() {
	m := pat.New()
	n := negroni.New(negroni.NewRecovery(), negroni.NewStatic(http.Dir("assets")))
	l := negronilogrus.NewMiddleware()
	o := render.New(render.Options{
		Layout: "layout",
	})

	n.Use(l)
	n.UseHandler(m)

	m.Get("/debug/vars", http.DefaultServeMux)

	m.Get("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		o.HTML(w, http.StatusOK, "index", "world")
	}))

	var addr string
	if len(os.Getenv("TIMEOFF_PORT")) > 0 {
		addr = ":" + os.Getenv("TIMEOFF_PORT")
	} else {
		addr = ":3000"
	}

	l.Logger.Infof("Listening on %s", addr)
	l.Logger.Fatal(http.ListenAndServe(addr, n))
}

package main

import (
	_ "expvar"
	"net/http"
	"os"

	"github.com/bmizerany/pat"
	"github.com/codegangsta/negroni"
	"github.com/meatballhat/negroni-logrus"
	"github.com/unrolled/render"
)

func main() {
	m := pat.New()
	n := negroni.New(negroni.NewRecovery(), negroni.NewStatic(http.Dir("assets")))
	l := negronilogrus.NewMiddleware()
	o := render.New(render.Options{
		Layout: "layout",
	})

	n.Use(l)
	n.UseHandler(m)

	m.Get("/debug/vars", http.DefaultServeMux)

	m.Get("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		o.HTML(w, http.StatusOK, "index", "world")
	}))

	var addr string

	if len(os.Getenv("TIMEOFF_ADDR")) > 0 {
		addr = os.Getenv("TIMEOFF_ADDR")
	} else {
		addr = ":3000"
	}

	l.Logger.Infof("Listening on %s", addr)
	l.Logger.Fatal(http.ListenAndServe(addr, n))
}

Allow listen address to be specified by env var


package scout

import (
	"context"
	"strings"

	"github.com/datawire/dlib/dexec"
	"github.com/datawire/dlib/dlog"
)

func runSwVers(ctx context.Context, versionName string) string {
	cmd := dexec.CommandContext(ctx, "sw_vers", "-"+versionName)
	cmd.DisableLogging = true
	r, err := cmd.Output()
	if err != nil {
		dlog.Warnf(ctx, "Could not get os metadata %s: %v", versionName, err)
		return "unknown"
	}
	return strings.TrimSpace(string(r))
}

func getOsMetadata(ctx context.Context) map[string]interface{} {
	osMeta := map[string]interface{}{
		"os_version":       runSwVers(ctx, "productVersion"),
		"os_build_version": runSwVers(ctx, "buildVersion"),
		"os_name":          runSwVers(ctx, "productName"),
	}
	return osMeta
}

package scout

import (
	"bufio"
	"bytes"
	"context"
	"strings"

	"github.com/datawire/dlib/dexec"
	"github.com/datawire/dlib/dlog"
)

func getOsMetadata(ctx context.Context) map[string]interface{} {
	osMeta := map[string]interface{}{
		"os_version":       "unknown",
		"os_build_version": "unknown",
		"os_name":          "unknown",
	}
	cmd := dexec.CommandContext(ctx, "sw_vers")
	cmd.DisableLogging = true
	if r, err := cmd.Output(); err != nil {
		dlog.Warnf(ctx, "Could not get os metadata: %v", err)
	} else {
		sc := bufio.NewScanner(bytes.NewReader(r))
		for sc.Scan() {
			fs := strings.Fields(sc.Text())
			if len(fs) == 2 {
				switch fs[0] {
				case "ProductName:":
					osMeta["os_name"] = fs[1]
				case "ProductVersion:":
					osMeta["os_version"] = fs[1]
				case "BuildVersion:":
					osMeta["os_build_version"] = fs[1]
				}
			}
		}
	}
	return osMeta
}

Speed up getOsMetadata() on macOS


// leftpad.go

/*
 This package implements the leftpad function, inspired by the NPM (JS)
 package of the same name.

 Two functions are defined:

     import "leftpad"

	 // pad with spacex
     str, err := LeftPad(s, n)

     // pad with specified character
     str, err := func LeftPadStr(s, n, c)

 */
package leftpad

import (
	"errors"
	"fmt"
	"strings"
)

var ErrInvalidChar = errors.New("Invalid character")

func doLeftPad(s string, n int, c string) (string, error) {
	if n < 0 {
		return "", errors.New(fmt.Sprintf("Invalid length %d", n))
	}

	if len(c) != 1 {
		return "", ErrInvalidChar
	}

	toAdd := n - len(s)
	if toAdd <= 0 {
		return s, nil
	}

	return strings.Repeat(c, toAdd) + s, nil
}

func LeftPad(s string, n int) (string, error) {
    return doLeftPad(s, n, " ")
}

func LeftPadStr(s string, n int, c string) (string, error) {
	return doLeftPad(s, n, c)
}

/*
 This package implements the leftpad function, inspired by the NPM (JS)
 package of the same name.

 Two functions are defined:

 import "leftpad"

 // pad with spaces
 str, err := LeftPad(s, n)

 // pad with specified character
 str, err := func LeftPadStr(s, n, c)

*/
package leftpad

import (
	"errors"
	"fmt"
	"strings"
)

var ErrInvalidChar = errors.New("Invalid character")

func doLeftPad(s string, n int, c string) (string, error) {
	if n < 0 {
		return "", errors.New(fmt.Sprintf("Invalid length %d", n))
	}

	if len(c) != 1 {
		return "", ErrInvalidChar
	}

	toAdd := n - len(s)
	if toAdd <= 0 {
		return s, nil
	}

	return strings.Repeat(c, toAdd) + s, nil
}

func LeftPad(s string, n int) (string, error) {
	return doLeftPad(s, n, " ")
}

func LeftPadStr(s string, n int, c string) (string, error) {
	return doLeftPad(s, n, c)
}

Fix formatting and spelling in block comment


package jiradata

import (
	"strings"
)

// Find will search the transitions for one that matches
// the given name.  It will return a valid trantion that matches
// or nil
func (t Transitions) Find(name string) *Transition {
	name = strings.ToLower(name)
	matches := []Transitions{}
	for _, trans := range t {
		if strings.Compare(strings.ToLower(trans.Name), name) == 0 {
			return trans
		}
		if strings.Contains(strings.ToLower(trans.Name), name) {
			matches = append(matches, trans)
		}
	}
	if len(matches) > 0 {
		return matches[0]
	}
	return nil
}

package jiradata

import (
	"strings"
)

// Find will search the transitions for one that matches
// the given name.  It will return a valid trantion that matches
// or nil
func (t Transitions) Find(name string) *Transition {
	name = strings.ToLower(name)
	matches := []Transitions{}
	for _, trans := range t {
		if strings.ToLower(trans.Name) == name {
			return trans
		}
		if strings.Contains(strings.ToLower(trans.Name), name) {
			matches = append(matches, trans)
		}
	}
	if len(matches) > 0 {
		return matches[0]
	}
	return nil
}

Address comments for direct name match


package main

import (
	"github.com/codegangsta/negroni"
	"github.com/hariharan-uno/cors"
	"github.com/joshsoftware/curem/config"
)

func main() {

	c := make(map[string]string)
	c["name"] = "test"
	c["url"] = "localhost"
	c["leads"] = "newlead"
	c["contacts"] = "newcontact"

	config.Configure(c)

	opts := cors.Options{
		AllowAllOrigins: true,
		AllowMethods:    []string{"GET", "POST", "PATCH", "DELETE"},
	}

	n := negroni.Classic()
	n.Use(negroni.HandlerFunc(opts.Allow))

	n.UseHandler(r) // r is a *mux.Router defined in contact_api.go
	n.Run(":3000")
}

package main

import (
	"github.com/codegangsta/negroni"
	"github.com/hariharan-uno/cors"
	"github.com/joshsoftware/curem/config"
)

func main() {

	c := make(map[string]string)
	c["name"] = "dev"
	c["url"] = "localhost"
	c["leads"] = "newlead"
	c["contacts"] = "newcontact"

	config.Configure(c)

	opts := cors.Options{
		AllowAllOrigins: true,
		AllowMethods:    []string{"GET", "POST", "PATCH", "DELETE"},
	}

	n := negroni.Classic()
	n.Use(negroni.HandlerFunc(opts.Allow))

	n.UseHandler(r) // r is a *mux.Router defined in contact_api.go
	n.Run(":3000")
}

Change db name to dev


package main

//go:generate $GOPATH/bin/ego -o templates/ego.go -package=template templates

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

func main() {
	handler, err := OpenHandlerFromEnv()
	if err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("/", handler.Handler)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	http.ListenAndServe(":"+port, nil)
}

package main

//go:generate $GOPATH/bin/ego -o templates/ego.go -package=template templates

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

func main() {
	handler, err := OpenHandlerFromEnv()
	if err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("/", handler.Handler)

	listen := os.Getenv("LISTEN")
	if listen == "" {
		listen = ":8080"
	}
	http.ListenAndServe(listen, nil)
}

Change PORT to LISTEN environment variable name


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))
}

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 memStatsBeforeGC, memStatsAfterGC runtime.MemStats
	runtime.ReadMemStats(&memStatsBeforeGC)
	runtime.GC()
	runtime.ReadMemStats(&memStatsAfterGC)
	fmt.Fprintf(writer, "Allocated memory: %s (%s after GC)
\n",
		format.FormatBytes(memStatsBeforeGC.Alloc),
		format.FormatBytes(memStatsAfterGC.Alloc))
	fmt.Fprintf(writer, "System memory: %s (%s after GC)
\n",
		format.FormatBytes(memStatsBeforeGC.Sys),
		format.FormatBytes(memStatsAfterGC.Sys))
}

Add after Garbage Collection memory statistics to status pages.


package main

import (
	"fmt"
	"github.com/jzelinskie/geddit"
	"github.com/nlopes/slack"
	"io/ioutil"
)

func getSlackToken() string {
	dat, err := ioutil.ReadFile("slack-token")
	if err != nil {
		fmt.Println("Cannot read slack token")
		panic(err)
	}
	return string(dat)
}

func main() {
	session, err := geddit.NewLoginSession("login", "password", "gedditAgent v1")
	fmt.Println(session)
	fmt.Println(err)

	subOpts := geddit.ListingOptions{
		Limit: 10,
	}
	nnFeed, err := session.SubredditSubmissions("neuralnetworks", geddit.NewSubmissions, subOpts)
	fmt.Println(nnFeed)
}

package main

import (
	"fmt"
	"github.com/mgadzhi/slack-pechkin/reddit"
	"github.com/nlopes/slack"
	"io/ioutil"
	"strings"
)

func getSlackToken() string {
	dat, err := ioutil.ReadFile("slack-token")
	if err != nil {
		fmt.Println("Cannot read slack token")
		panic(err)
	}
	return strings.TrimSpace(string(dat))
}

func main() {
	r := reddit.NewReddit()
	submissions := r.GetLastSubmissions("programming")

	slackToken := getSlackToken()
	fmt.Println(slackToken)
	api := slack.New(slackToken)
	fmt.Println(api)
	postParams := slack.PostMessageParameters{
		AsUser: true,
	}
	for i, s := range submissions {
		fmt.Println(i, s)
		channelID, timestamp, err := api.PostMessage("main", s, postParams)
		fmt.Println(channelID, timestamp, err)
	}

}

Send 10 newest links from r/programming to slack


package main

import (
	"flag"
	"net"
)

func main() {
	flag.Parse()
	hostname := flag.Arg(0)

	addr, _ := net.LookupHost(hostname)
	for _, v := range addr {
		ptrAddr, _ := net.LookupAddr(v)
		println(v, "->", ptrAddr[0])
	}
}

package main

import (
	"net"
	"os"

	flags "github.com/jessevdk/go-flags"
)

func main() {
	parser := flags.NewParser(nil, flags.Default)
	parser.Usage = "HOSTNAME [OPTIONS]"
	args, _ := parser.Parse()

	if len(args) == 0 {
		os.Exit(1)
	}

	hostname := args[0]
	addr, _ := net.LookupHost(hostname)
	for _, v := range addr {
		ptrAddr, _ := net.LookupAddr(v)
		println(v, "->", ptrAddr[0])
	}
}

Use go-flags and add help


package cheerio

import (
	"testing"
)

func TestFetchSourceRepoURI(t *testing.T) {
	tests := []struct {
		pkg         string
		wantRepoURI string
	}{
		{"flask_cm", "https://github.com/futuregrid/flask_cm"},
	}

	for _, test := range tests {
		repoURI, err := DefaultPyPI.FetchSourceRepoURI(test.pkg)
		if err != nil {
			t.Error("FetchSourceRepoURI error:", err)
			continue
		}
		if test.wantRepoURI != repoURI {
			t.Errorf("%s: want repoURI == %q, got %q", test.pkg, test.wantRepoURI, repoURI)
		}
	}
}

package cheerio

import (
	"testing"
)

func TestFetchSourceRepoURI(t *testing.T) {
	tests := []struct {
		pkg         string
		wantRepoURI string
	}{
		{"flask_cm", "https://github.com/futuregrid/flask_cm"},
		{"zipaccess", "https://github.com/iki/zipaccess"},
	}

	for _, test := range tests {
		repoURI, err := DefaultPyPI.FetchSourceRepoURI(test.pkg)
		if err != nil {
			t.Error("FetchSourceRepoURI error:", err)
			continue
		}
		if test.wantRepoURI != repoURI {
			t.Errorf("%s: want repoURI == %q, got %q", test.pkg, test.wantRepoURI, repoURI)
		}
	}
}

Add example with remote .zip file


package raftmdb

import (
	"bytes"
	"encoding/binary"
	"github.com/ugorji/go/codec"
)

// Decode reverses the encode operation on a byte slice input
func decodeMsgPack(buf []byte, out interface{}) error {
	r := bytes.NewBuffer(buf)
	hd := codec.MsgpackHandle{}
	dec := codec.NewDecoder(r, &hd)
	return dec.Decode(out)
}

// Encode writes an encoded object to a new bytes buffer
func encodeMsgPack(in interface{}) (*bytes.Buffer, error) {
	buf := bytes.NewBuffer(nil)
	hd := codec.MsgpackHandle{}
	enc := codec.NewEncoder(buf, &hd)
	err := enc.Encode(in)
	return buf, err
}

// Converts bytes to an integer
func bytesToUint64(b []byte) uint64 {
	return binary.BigEndian.Uint64(b)
}

// Converts a uint to a byte slice
func uint64ToBytes(u uint64) []byte {
	buf := make([]byte, 8)
	binary.BigEndian.PutUint64(buf, u)
	return buf
}

package raftmdb

import (
	"bytes"
	"encoding/binary"
	"github.com/hashicorp/go-msgpack/codec"
)

// Decode reverses the encode operation on a byte slice input
func decodeMsgPack(buf []byte, out interface{}) error {
	r := bytes.NewBuffer(buf)
	hd := codec.MsgpackHandle{}
	dec := codec.NewDecoder(r, &hd)
	return dec.Decode(out)
}

// Encode writes an encoded object to a new bytes buffer
func encodeMsgPack(in interface{}) (*bytes.Buffer, error) {
	buf := bytes.NewBuffer(nil)
	hd := codec.MsgpackHandle{}
	enc := codec.NewEncoder(buf, &hd)
	err := enc.Encode(in)
	return buf, err
}

// Converts bytes to an integer
func bytesToUint64(b []byte) uint64 {
	return binary.BigEndian.Uint64(b)
}

// Converts a uint to a byte slice
func uint64ToBytes(u uint64) []byte {
	buf := make([]byte, 8)
	binary.BigEndian.PutUint64(buf, u)
	return buf
}

Switch to hashicorp version of msgpack


package main

import (
	"github.com/hashicorp/terraform/helper/schema"
	"github.com/keybase/go-keychain"
	"log"
	"runtime"
)

func passwordRetrievalFunc(env_var string, dv interface{}) schema.SchemaDefaultFunc {
	return func() (interface{}, error) {
		if runtime.GOOS == "darwin" {
			log.Println("[INFO] On macOS so trying the keychain")
			query := keychain.NewItem()
			query.SetSecClass(keychain.SecClassGenericPassword)
			query.SetService("alkscli")
			query.SetAccount("alksuid")
			query.SetMatchLimit(keychain.MatchLimitOne)
			query.SetReturnData(true)
			results, err := keychain.QueryItem(query)
			if err != nil {
				log.Println("[WARN] Error accessing the macOS keychain. Falling back to environment variables")
				log.Println(err)
			} else {
				return string(results[0].Data), nil
			}
		}

		return schema.EnvDefaultFunc(env_var, dv)()
	}
}

package main

import (
	"log"
	"runtime"

	"github.com/hashicorp/terraform/helper/schema"
	"github.com/keybase/go-keychain"
)

func passwordRetrievalFunc(envVar string, dv interface{}) schema.SchemaDefaultFunc {
	return func() (interface{}, error) {
		if runtime.GOOS == "darwin" {
			log.Println("[INFO] On macOS so trying the keychain")
			query := keychain.NewItem()
			query.SetSecClass(keychain.SecClassGenericPassword)
			query.SetService("alkscli")
			query.SetAccount("alksuid")
			query.SetMatchLimit(keychain.MatchLimitOne)
			query.SetReturnData(true)
			results, err := keychain.QueryItem(query)
			if err != nil {
				log.Println("[WARN] Error accessing the macOS keychain. Falling back to environment variables")
				log.Println(err)
			} else {
				return string(results[0].Data), nil
			}
		}

		return schema.EnvDefaultFunc(envVar, dv)()
	}
}

Fix some things for code smell


package lager

import (
	"io"
	"sync"
)

const logBufferSize = 1024

// A Sink represents a write destination for a Logger. It provides
// a thread-safe interface for writing logs
type Sink interface {
	//Log to the sink.  Best effort -- no need to worry about errors.
	Log(level LogLevel, payload []byte)
}

type writerSink struct {
	writer      io.Writer
	minLogLevel LogLevel
	writeL      *sync.Mutex
}

func NewWriterSink(writer io.Writer, minLogLevel LogLevel) Sink {
	return &writerSink{
		writer:      writer,
		minLogLevel: minLogLevel,
		writeL:      new(sync.Mutex),
	}
}

func (sink *writerSink) Log(level LogLevel, log []byte) {
	if level < sink.minLogLevel {
		return
	}

	sink.writeL.Lock()
	sink.writer.Write(log)
	sink.writer.Write([]byte("\n"))
	sink.writeL.Unlock()
}

package lager

import (
	"io"
	"sync"
)

// A Sink represents a write destination for a Logger. It provides
// a thread-safe interface for writing logs
type Sink interface {
	//Log to the sink.  Best effort -- no need to worry about errors.
	Log(level LogLevel, payload []byte)
}

type writerSink struct {
	writer      io.Writer
	minLogLevel LogLevel
	writeL      *sync.Mutex
}

func NewWriterSink(writer io.Writer, minLogLevel LogLevel) Sink {
	return &writerSink{
		writer:      writer,
		minLogLevel: minLogLevel,
		writeL:      new(sync.Mutex),
	}
}

func (sink *writerSink) Log(level LogLevel, log []byte) {
	if level < sink.minLogLevel {
		return
	}

	sink.writeL.Lock()
	sink.writer.Write(log)
	sink.writer.Write([]byte("\n"))
	sink.writeL.Unlock()
}

Remove unused constant from sink


package main

import (
	"fmt"
	"github.com/levigross/grequests"
	"github.com/ryanskidmore/GoWork"
	"strings"
)

func main() {
	response, err := grequests.Get("http://127.0.0.1:3000/register", nil)
	if err != nil {
		panic("Unable to register:" + err.Error())
	}
	respdata := strings.Split(response.String(), ",")
	id := respdata[0]
	clienttest := respdata[1]
	worker, err := gowork.NewWorker("w4PYxQjVP9ZStjWpBt5t28CEBmRs8NPx", id, clienttest)
	testresponse, err := grequests.Post("http://127.0.0.1:3000/verify", &grequests.RequestOptions{Params: map[string]string{"id": id, "clientresp": worker.Verification.ClientResponse}})
	if err != nil {
		panic("Unable to verify:" + err.Error())
	}
	worker = worker.SetAuthenticationKey(testresponse.String())
	fmt.Println(worker.SessionAuthenticationKey)
}

package main

import (
	"fmt"
	"github.com/levigross/grequests"
	"github.com/ryanskidmore/GoWork"
	"strings"
)

func main() {
	response, err := grequests.Get("http://127.0.0.1:3000/register", nil)
	if err != nil {
		panic("Unable to register:" + err.Error())
	}
	respdata := strings.Split(response.String(), ",")
	id := respdata[0]
	clienttest := respdata[1]
	worker, err := gowork.NewWorker("w4PYxQjVP9ZStjWpBt5t28CEBmRs8NPx", id, clienttest)
	testresponse, err := grequests.Post("http://127.0.0.1:3000/verify", &grequests.RequestOptions{Params: map[string]string{"id": id, "clientresp": worker.Verification.ClientResponse}})
	if err != nil {
		panic("Unable to verify:" + err.Error())
	}
	worker = worker.SetAuthenticationKey(testresponse.String())
	fmt.Println(worker.SessionAuthenticationKey)
	testresponse, err = grequests.Post("http://127.0.0.1:3000/get_work", &grequests.RequestOptions{Params: map[string]string{"id": id, "sessionauthkey": worker.SessionAuthenticationKey}})
	fmt.Println(testresponse.String())
}

Add the 'get_work' part in the client example


package balance

import (
	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	orCommon "github.com/notegio/openrelay/common"
	tokenModule "github.com/notegio/openrelay/token"
	"github.com/notegio/openrelay/types"
	"math/big"
)

type rpcBalanceChecker struct {
	conn bind.ContractBackend
}

func (funds *rpcBalanceChecker) GetBalance(tokenAsset types.AssetData, userAddrBytes *types.Address) (*big.Int, error) {
	token, err := tokenModule.NewToken(orCommon.ToGethAddress(tokenAsset.Address()), funds.conn)
	if err != nil {
		return nil, err
	}
	return token.BalanceOf(nil, orCommon.ToGethAddress(userAddrBytes))
}

func (funds *rpcBalanceChecker) GetAllowance(tokenAsset types.AssetData, ownerAddress, spenderAddress *types.Address) (*big.Int, error) {
	token, err := tokenModule.NewToken(orCommon.ToGethAddress(tokenAsset.Address()), funds.conn)
	if err != nil {
		return nil, err
	}
	return token.Allowance(nil, orCommon.ToGethAddress(ownerAddress), orCommon.ToGethAddress(spenderAddress))
}

func NewRpcERC20BalanceChecker(conn bind.ContractBackend) (BalanceChecker) {
	return &rpcBalanceChecker{conn}
}

package balance

import (
	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	orCommon "github.com/notegio/openrelay/common"
	tokenModule "github.com/notegio/openrelay/token"
	"github.com/notegio/openrelay/types"
	"math/big"
)

type rpcERC20BalanceChecker struct {
	conn bind.ContractBackend
}

func (funds *rpcERC20BalanceChecker) GetBalance(tokenAsset types.AssetData, userAddrBytes *types.Address) (*big.Int, error) {
	token, err := tokenModule.NewToken(orCommon.ToGethAddress(tokenAsset.Address()), funds.conn)
	if err != nil {
		return nil, err
	}
	return token.BalanceOf(nil, orCommon.ToGethAddress(userAddrBytes))
}

func (funds *rpcERC20BalanceChecker) GetAllowance(tokenAsset types.AssetData, ownerAddress, spenderAddress *types.Address) (*big.Int, error) {
	token, err := tokenModule.NewToken(orCommon.ToGethAddress(tokenAsset.Address()), funds.conn)
	if err != nil {
		return nil, err
	}
	return token.Allowance(nil, orCommon.ToGethAddress(ownerAddress), orCommon.ToGethAddress(spenderAddress))
}

func NewRpcERC20BalanceChecker(conn bind.ContractBackend) (BalanceChecker) {
	return &rpcERC20BalanceChecker{conn}
}

Update balance checker struct name


// Copyright 2016 Marcel Gotsch. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package goserv

import (
	"net/http"
)

// A Request represents an HTTP request received by the Server.
//
// It embeds the native http.Request, thus all native fields are still available
// through Request. Every Request has it's own Context providing a key-value store to share
// data between multiple Handlers. In case that the Route handling the Request has parameters, the parameter
// values are extracted from the Request's path and stored in .Params.
type Request struct {
	// Embedded http.Request.
	*http.Request

	// Request specific key-value store to share data between Handlers
	Context *Context

	// Key-value store containing named parameter values extracted from
	// the Request's path. See Route.
	Params Params

	// Sanitized http.Request.URL.Path
	SanitizedPath string
}

func newRequest(r *http.Request) *Request {
	return &Request{r, newContext(), make(Params), SanitizePath(r.URL.Path)}
}

// Copyright 2016 Marcel Gotsch. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package goserv

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

// A Request represents an HTTP request received by the Server.
//
// It embeds the native http.Request, thus all native fields are still available
// through Request. Every Request has it's own Context providing a key-value store to share
// data between multiple Handlers. In case that the Route handling the Request has parameters, the parameter
// values are extracted from the Request's path and stored in .Params.
type Request struct {
	// Embedded http.Request.
	*http.Request

	// Request specific key-value store to share data between Handlers
	Context *Context

	// Key-value store containing named parameter values extracted from
	// the Request's path. See Route.
	Params Params

	// Sanitized http.Request.URL.Path
	SanitizedPath string
}

// JSON parses the request's body using the encoding/json Decoder. In case
// of a decoding error the error is returned.
//
// Note: The request's body is closed after calling this method.
func (r *Request) JSON(v interface{}) error {
	err := json.NewDecoder(r.Body).Decode(v)
	r.Body.Close()

	if err != nil {
		return err
	}

	return nil
}

func newRequest(r *http.Request) *Request {
	return &Request{r, newContext(), make(Params), SanitizePath(r.URL.Path)}
}

Add JSON decoder to Request


package api

import (
	"testing"

	"github.com/chromium/hstspreload.appspot.com/database"
)

func TestCheckConnection(t *testing.T) {
	ms := database.MockState{}
	a := API{database.Mock{State: &ms}}
	if err := a.CheckConnection(); err != nil {
		t.Errorf("%s", err)
	}

	ms.FailCalls = true
	if err := a.CheckConnection(); err == nil {
		t.Errorf("connection should fail")
	}
}

package api

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/chromium/hstspreload.appspot.com/database"
)

func TestCheckConnection(t *testing.T) {
	ms := database.MockState{}
	a := API{database.Mock{State: &ms}}
	if err := a.CheckConnection(); err != nil {
		t.Errorf("%s", err)
	}

	ms.FailCalls = true
	if err := a.CheckConnection(); err == nil {
		t.Error("connection should fail")
	}
}

func TestStatus(t *testing.T) {
	ms := database.MockState{}
	a := API{database.Mock{State: &ms}}

	w := httptest.NewRecorder()

	r, err := http.NewRequest("GET", "?domain=garron.net", nil)
	if err != nil {
		t.Fatal(err)
	}

	b := &bytes.Buffer{}
	w.Body = b

	a.Status(w, r)

	s := database.DomainState{}
	if err := json.Unmarshal(w.Body.Bytes(), &s); err != nil {
		t.Fatal(err)
	}

	if s.Name != "garron.net" {
		t.Errorf("Wrong name: %s", s.Name)
	}
	if s.Status != database.StatusUnknown {
		t.Errorf("Wrong status: %s", s.Status)
	}

}

Implement a test for api.Status().


package gform

import (
	"github.com/AllenDang/w32"
)

type MouseEventData struct {
    X, Y   int
    Button int
    Wheel  int
}

type DropFilesEventData struct {
    X, Y  int
	Files []string
}

type PaintEventData struct {
	Canvas *Canvas
}

type LVEndLabelEditEventData struct {
	Item *w32.LVITEM
}

type LVDBLClickEventData struct {
	NmItem *w32.NMITEMACTIVATE
}

type KeyUpEventData struct {
	VKey, Code int
}

package gform

import (
	"github.com/AllenDang/w32"
)

type RawMsg struct {
    Hwnd           w32.HWND
    Msg            uint
    WParam, LParam uintptr
}

type MouseEventData struct {
    X, Y   int
    Button int
    Wheel  int
}

type DropFilesEventData struct {
    X, Y  int
	Files []string
}

type PaintEventData struct {
	Canvas *Canvas
}

type LVEndLabelEditEventData struct {
	Item *w32.LVITEM
}

type LVDBLClickEventData struct {
	NmItem *w32.NMITEMACTIVATE
}

type KeyUpEventData struct {
	VKey, Code int
}

Add "RawMsg" struct to wrap windows message.


package bigsequence

import (
	"testing"
	"github.com/johnny-morrice/godelbrot/base"
	"github.com/johnny-morrice/godelbrot/bigbase"
)

func TestBigMandelbrotSequence(t *testing.T) {
	const prec = 53
	const iterLimit = 10

	app := &bigbase.MockRenderApplication{
		MockRenderApplication: base.MockRenderApplication{
			Base: base.BaseConfig{
				DivergeLimit: 4.0,
			},
			PictureWidth: 10,
			PictureHeight: 10,
		},
	}
	app.UserMin = bigbase.MakeBigComplex(0.0, 0.0, prec)
	app.UserMax = bigbase.MakeBigComplex(10.0, 10.0, prec)
	numerics := Make(app)
	out := numerics.Sequence()

	const expectedCount = 100
	actualArea := numerics.Area()

	if expectedCount != actualArea {
		t.Error("Expected area of", expectedCount,
			"but received", actualArea)
	}

	members := make([]base.PixelMember, actualArea)

	i := 0
	for point := range out {
		members[i] = point
		i++
	}
	actualCount := len(members)

	if expectedCount != actualCount {
		t.Error("Expected", expectedCount, "members but there were", actualCount)
	}
}

package bigsequence

import (
	"testing"
	"github.com/johnny-morrice/godelbrot/base"
	"github.com/johnny-morrice/godelbrot/bigbase"
)

func TestBigMandelbrotSequence(t *testing.T) {
	const prec = 53
	const iterLimit = 10

	app := &bigbase.MockRenderApplication{
		MockRenderApplication: base.MockRenderApplication{
			Base: base.BaseConfig{
				DivergeLimit: 4.0,
			},
			PictureWidth: 10,
			PictureHeight: 10,
		},
	}
	app.UserMin = bigbase.MakeBigComplex(0.0, 0.0, prec)
	app.UserMax = bigbase.MakeBigComplex(10.0, 10.0, prec)
	numerics := Make(app)
	out := numerics.Sequence()

	const expectedCount = 100
	actualCount := len(out)

	if expectedCount != actualCount {
		t.Error("Expected", expectedCount, "members but there were", actualCount)
	}
}

Fix failing unit tests for bigsequence


package main

import (
	"fmt"
	"runtime"

	"github.com/datawire/ambassador/pkg/supervisor"
)

var notifyRAI *RunAsInfo

// Notify displays a desktop banner notification to the user
func Notify(p *supervisor.Process, message string) {
	if notifyRAI == nil {
		var err error
		notifyRAI, err = GuessRunAsInfo(p)
		if err != nil {
			p.Log(err)
			notifyRAI = &RunAsInfo{}
		}
	}

	var args []string
	switch runtime.GOOS {
	case "darwin":
		script := fmt.Sprintf("display notification \"Edge Control Daemon\" with title \"%s\"", message)
		args = []string{"osascript", "-e", script}
	case "linux":
		args = []string{"notify-send", "Edge Control Daemon", message}
	default:
		return
	}

	p.Logf("NOTIFY: %s", message)
	cmd := notifyRAI.Command(p, args...)
	if err := cmd.Run(); err != nil {
		p.Logf("ERROR while notifying: %v", err)
	}
}

// MaybeNotify displays a notification only if a value changes
func MaybeNotify(p *supervisor.Process, name string, old, new bool) {
	if old != new {
		Notify(p, fmt.Sprintf("%s: %t -> %t", name, old, new))
	}
}

package main

import (
	"fmt"
	"runtime"

	"github.com/datawire/ambassador/pkg/supervisor"
)

var (
	notifyRAI     *RunAsInfo
	notifyEnabled = false
)

// Notify displays a desktop banner notification to the user
func Notify(p *supervisor.Process, message string) {
	p.Logf("----------------------------------------------------------------------")
	p.Logf("NOTIFY: %s", message)
	p.Logf("----------------------------------------------------------------------")

	if !notifyEnabled {
		return
	}

	if notifyRAI == nil {
		var err error
		notifyRAI, err = GuessRunAsInfo(p)
		if err != nil {
			p.Log(err)
			notifyRAI = &RunAsInfo{}
		}
	}

	var args []string
	switch runtime.GOOS {
	case "darwin":
		script := fmt.Sprintf("display notification \"Edge Control Daemon\" with title \"%s\"", message)
		args = []string{"osascript", "-e", script}
	case "linux":
		args = []string{"notify-send", "Edge Control Daemon", message}
	default:
		return
	}

	cmd := notifyRAI.Command(p, args...)
	if err := cmd.Run(); err != nil {
		p.Logf("ERROR while notifying: %v", err)
	}
}

// MaybeNotify displays a notification only if a value changes
func MaybeNotify(p *supervisor.Process, name string, old, new bool) {
	if old != new {
		Notify(p, fmt.Sprintf("%s: %t -> %t", name, old, new))
	}
}

Make it possible to disable notifications; disable them


package uct

import "flag"

//This is the QML compiler for uct.
var Qml bool

var QmlAssembly = Assemblable{}

func init() {
	flag.BoolVar(&Qml, "qml", false, "Target QML")

	for k, v := range JavascriptAssembly {
		QmlAssembly[k] = v
	}

	QmlAssembly["QML"] = QmlAssembly["JAVASCRIPT"]
	delete(QmlAssembly, "JAVASCRIPT")

	RegisterAssembler(QmlAssembly , &Qml, "js", "//")
}

package uct

import "flag"

//This is the QML compiler for uct.
var Qml bool

var QmlAssembly = Assemblable{}

func init() {
	flag.BoolVar(&Qml, "qml", false, "Target QML")

	for k, v := range JavascriptAssembly {
		QmlAssembly[k] = v
	}

	QmlAssembly["QML"] = QmlAssembly["JAVASCRIPT"]
	delete(QmlAssembly, "JAVASCRIPT")

	RegisterAssembler(QmlAssembly , &Qml, "qml", "//")
}

Fix bug with QML/JS being replaced.


package utils

import (
	"os"
	"os/user"
	"path/filepath"
	"testing"

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

func TestNormalizingHomeDirectories(t *testing.T) {
	t.Parallel()

	usr, err := user.Current()
	assert.NoError(t, err)

	fp, err := NormalizeFilePath(filepath.Join(`~`, `.ssh`))
	assert.NoError(t, err)
	assert.Equal(t, filepath.Join(usr.HomeDir, `.ssh`), fp)
	assert.True(t, filepath.IsAbs(fp))
}

func TestNormalizingFilePaths(t *testing.T) {
	t.Parallel()

	workingDir, err := os.Getwd()
	assert.NoError(t, err)

	fp, err := NormalizeFilePath(filepath.Join(`.`, `builds`))
	assert.NoError(t, err)
	assert.Equal(t, workingDir+`/builds`, fp)
	assert.True(t, filepath.IsAbs(fp))
}

func TestNormalizingEmptyPaths(t *testing.T) {
	t.Parallel()

	fp, err := NormalizeFilePath("")
	assert.NoError(t, err)
	assert.Equal(t, "", fp)
}

package utils

import (
	"os"
	"os/user"
	"path/filepath"
	"testing"

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

func TestNormalizingHomeDirectories(t *testing.T) {
	t.Parallel()

	usr, err := user.Current()
	assert.NoError(t, err)

	fp, err := NormalizeFilePath(filepath.Join(`~`, `.ssh`))
	assert.NoError(t, err)
	assert.Equal(t, filepath.Join(usr.HomeDir, `.ssh`), fp)
	assert.True(t, filepath.IsAbs(fp))
}

func TestNormalizingFilePaths(t *testing.T) {
	t.Parallel()

	workingDir, err := os.Getwd()
	assert.NoError(t, err)

	fp, err := NormalizeFilePath(filepath.Join(`.`, `builds`))
	assert.NoError(t, err)
	assert.Equal(t, filepath.Join(workingDir,`builds`), fp)
	assert.True(t, filepath.IsAbs(fp))
}

func TestNormalizingEmptyPaths(t *testing.T) {
	t.Parallel()

	fp, err := NormalizeFilePath("")
	assert.NoError(t, err)
	assert.Equal(t, "", fp)
}

Make path assertions windows friendly


//+build !yara3.3,!yara3.4,!yara3.5,!yara3.6

package yara

import (
	"testing"
)

func setupCompiler(t *testing.T) *Compiler {
	c, err := NewCompiler()
	if err != nil {
		t.Fatal(err)
	}
	c.SetIncludeCallback(func(name, rulefile, namespace string) []byte {
		t.Logf(`Processing include "%s" (from ns="%s", file="%s")`, name, namespace, rulefile)
		if name == "existing" {
			return []byte(`rule ext { condition: true }`)
		}
		return nil
	})
	return c
}

func TestCompilerIncludeCallback(t *testing.T) {
	c := setupCompiler(t)
	var err error
	if err = c.AddString(`include "existing"`, ""); err != nil {
		t.Fatalf(`Failed to include "existing" rule "file": %s`, err)
	}
	if err = c.AddString(`rule int { condition: ext }`, ""); err != nil {
		t.Fatalf(`Failed to define rule referring to included rule: %s`, err)
	}

	c = setupCompiler(t)
	if err = c.AddString(`include "non-existing"`, ""); err != nil {
		t.Logf("Compiler returned error on attempt to include non-existing rule: %s", err)
	} else {
		t.Fatal(`Compiler did not return error on non-existing include rule`)
	}
}

Add build tags to yara 3.7-specific tests


package ssha_test

import (
	"testing"

	"github.com/jsimonetti/pwscheme/ssha"
)

func TestValidate(t *testing.T) {
	pass := "test123"
	hash := "{SSHA}lJj507aRaXGguk1uTQoKmKQRV/7N1oB7pmhWdw=="

	if res, err := ssha.Validate(pass, hash); res != true {
		t.Error("Validate password fails", err)
	}
}

func TestGenerate(t *testing.T) {
	pass := "test123"
	hash := ssha.Generate(pass)

	if res, err := ssha.Validate(pass, hash); res != true {
		t.Error("Generate of password fails", err)
	}
}

package ssha_test

import (
	"testing"

	"github.com/jsimonetti/pwscheme/ssha"
)

func TestValidate(t *testing.T) {
	pass := "test123"
	hash := "{SSHA}JFZFs0oHzxbMwkSJmYVeI8MnTDy/276a"

	if res, err := ssha.Validate(pass, hash); res != true {
		t.Error("Validate password fails", err)
	}
}

func TestGenerate(t *testing.T) {
	pass := "test123"
	hash := ssha.Generate(pass)

	if res, err := ssha.Validate(pass, hash); res != true {
		t.Error("Generate of password fails", err)
	}
}

Add an actually working hash


// Copyright 2013 Chris McGee <sirnewton_01@yahoo.ca>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build windows

package main

import(
	"fmt"
	"os/exec"
)

func openBrowser(url string) {
	cmd := exec.Command("cmd", "/c", "start", url)
	err = cmd.Run()
	if err != nil {
		fmt.Printf("%v\n", url)
	}
}

// Copyright 2013 Chris McGee <sirnewton_01@yahoo.ca>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build windows

package main

import(
	"fmt"
	"os/exec"
)

func openBrowser(url string) {
	cmd := exec.Command("cmd", "/c", "start", url)
	err := cmd.Run()
	if err != nil {
		fmt.Printf("%v\n", url)
	}
}

Fix compile error on windows browser handling module.


package clcgo

import (
	"encoding/json"
	"errors"
	"fmt"
)

type DataCenters struct {
	DataCenters []DataCenter
}

type DataCenter struct {
	ID   string
	Name string
}

const DataCentersURL = APIRoot + "/datacenters/%s"

func (d DataCenters) URL(a string) (string, error) {
	return fmt.Sprintf(DataCentersURL, a), nil
}

func (d *DataCenters) Unmarshal(j []byte) error {
	return json.Unmarshal(j, &d.DataCenters)
}

type DataCenterCapabilities struct {
	DataCenter DataCenter `json:"-"`
	Templates  []struct {
		Name        string
		Description string
	}
}

const DataCenterCapabilitiesURL = DataCentersURL + "/%s/deploymentCapabilities"

func (d DataCenterCapabilities) URL(a string) (string, error) {
	if d.DataCenter.ID == "" {
		return "", errors.New("Need a DataCenter with an ID")
	}

	return fmt.Sprintf(DataCenterCapabilitiesURL, a, d.DataCenter.ID), nil
}

func (d *DataCenterCapabilities) Unmarshal(j []byte) error {
	return json.Unmarshal(j, &d)
}

package clcgo

import (
	"encoding/json"
	"errors"
	"fmt"
)

type DataCenters []DataCenter

type DataCenter struct {
	ID   string
	Name string
}

const DataCentersURL = APIRoot + "/datacenters/%s"

func (d DataCenters) URL(a string) (string, error) {
	return fmt.Sprintf(DataCentersURL, a), nil
}

func (d *DataCenters) Unmarshal(j []byte) error {
	return json.Unmarshal(j, &d)
}

type DataCenterCapabilities struct {
	DataCenter DataCenter `json:"-"`
	Templates  []struct {
		Name        string
		Description string
	}
}

const DataCenterCapabilitiesURL = DataCentersURL + "/%s/deploymentCapabilities"

func (d DataCenterCapabilities) URL(a string) (string, error) {
	if d.DataCenter.ID == "" {
		return "", errors.New("Need a DataCenter with an ID")
	}

	return fmt.Sprintf(DataCenterCapabilitiesURL, a, d.DataCenter.ID), nil
}

func (d *DataCenterCapabilities) Unmarshal(j []byte) error {
	return json.Unmarshal(j, &d)
}

Change DataCenters from struct to slice


package waitfor

import (
	"errors"
	"time"

	"golang.org/x/net/context"
)

var ErrTimeoutExceeded = errors.New("timeout exceeded")

type Check func() bool

func ConditionWithTimeout(condition Check, interval, timeout time.Duration) error {
	errChan := make(chan error)
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	go Condition(condition, interval, errChan, ctx)

	err := <-errChan
	if err == context.DeadlineExceeded {
		return ErrTimeoutExceeded
	}

	return err
}

func Condition(condition Check, interval time.Duration, errChan chan error, ctx context.Context) {
	if condition() {
		errChan <- nil
		return
	}

	for {
		select {
		case <-ctx.Done():
			errChan <- ctx.Err()
			return
		case <-time.After(interval):
			if condition() {
				errChan <- nil
				return
			}
		}
	}
}

package waitfor

import (
	"errors"
	"time"

	"golang.org/x/net/context"
)

var ErrTimeoutExceeded = errors.New("timeout exceeded")

type Check func() bool

func ConditionWithTimeout(condition Check, interval, timeout time.Duration) error {
	errChan := make(chan error)
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	go Condition(condition, interval, errChan, ctx)

	select {
	case err := <-errChan:
		return err
	case <-ctx.Done():
		return ErrTimeoutExceeded
	}
}

func Condition(condition Check, interval time.Duration, errChan chan error, ctx context.Context) {
	if condition() {
		errChan <- nil
		return
	}

	for {
		select {
		case <-ctx.Done():
			errChan <- ctx.Err()
			return
		case <-time.After(interval):
			if condition() {
				errChan <- nil
				return
			}
		}
	}
}

Return if single check exceeds timeout


package testdb

import (
	r "github.com/dancannon/gorethink"
	"github.com/materials-commons/mcstore/pkg/db"
)

var session *r.Session

func RSession() *r.Session {
	if session == nil {
		session = db.RSessionUsingMust("localhost:30815", "mctestdb")
	}
	return session
}

// RSessionErr always returns a nil err. It will panic if it cannot
// get a db session. This function is meant to be used with the
// databaseSessionFilter for unit testing.
func RSessionErr() (*r.Session, error) {
	return RSession(), nil
}

Add RSessionErr for unit testing with databaseSessionFilter


package integration_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/sclevine/agouti"
	. "github.com/sclevine/agouti/dsl"
	. "github.com/sclevine/agouti/matchers"
)

var _ = Feature("Conflicts", func() {
	It("should allow dot-importing matchers, dsl, ginkgo, and gomega", func() {
		Expect(agouti.Capabilities{}).To(Equal(agouti.Capabilities{}))
		Expect(HaveTitle("title")).To(Equal(HaveTitle("title")))
	})
})

package integration_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/sclevine/agouti"
	. "github.com/sclevine/agouti/matchers"
)

var _ = Describe("Conflicts", func() {
	It("should allow importing agouti while dot-importing matchers, ginkgo, and gomega", func() {
		Expect(agouti.Capabilities{}).To(Equal(agouti.Capabilities{}))
		Expect(HaveTitle("title")).To(Equal(HaveTitle("title")))
	})
})

Remove dsl package from conflicts test to fix build errors


package messagebirdtest

import (
	"net/http"
	"net/http/httptest"
	"os"
	"testing"
)

var server *httptest.Server

var responseBody []byte
var status int

// EnableServer starts a fake server, runs the test and closes the server.
func EnableServer(m *testing.M) {
	initAndStartServer()
	exitCode := m.Run()
	closeServer()

	os.Exit(exitCode)
}

func initAndStartServer() {
	server = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// status and responseBody are defined in returns.go.
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		if _, err := w.Write(responseBody); err != nil {
			panic(err.Error())
		}
	}))
}

func closeServer() {
	server.Close()
}

// WillReturn sets the body (r) and status (s) for the test server to respond with.
func WillReturn(b []byte, s int) {
	responseBody = b
	status = s
}

func WillReturnAccessKeyError() {
	responseBody = []byte(`
		{
			"errors": [
				{
					"code":2,
					"description":"Request not allowed (incorrect access_key)",
					"parameter":"access_key"
				}
			]
		}`)
	status = 405
}

package messagebirdtest

import (
	"net/http"
	"net/http/httptest"
	"os"
	"testing"
)

var server *httptest.Server

var responseBody []byte
var status int

// EnableServer starts a fake server, runs the test and closes the server.
func EnableServer(m *testing.M) {
	initAndStartServer()
	exitCode := m.Run()
	closeServer()

	os.Exit(exitCode)
}

func initAndStartServer() {
	server = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// status and responseBody are defined in returns.go.
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		if _, err := w.Write(responseBody); err != nil {
			panic(err.Error())
		}
	}))
}

func closeServer() {
	server.Close()
}

// WillReturn sets the body (r) and status (s) for the test server to respond with.
func WillReturn(b []byte, s int) {
	responseBody = b
	status = s
}

func WillReturnAccessKeyError() {
	responseBody = []byte(`
		{
			"errors": [
				{
					"code":2,
					"description":"Request not allowed (incorrect access_key)",
					"parameter":"access_key"
				}
			]
		}`)
	status = 401
}

Fix incorrect status code for requests with incorrect access keys


package db

import (
	"firempq/db/cldb"
	"firempq/log"
	"os"
	"sync"

	. "firempq/api"
)

var database DataStorage = nil
var lock sync.Mutex

// GetDatabase returns DataStorage singleton.
func GetDatabase() DataStorage {
	lock.Lock()
	defer lock.Unlock()
	return getDatabase()
}

func SetDatabase(ds DataStorage) {
	database = ds
}

func getDatabase() DataStorage {
	if database == nil {
		var err error
		database, err = cldb.NewLevelDBStorage("databasedir")
		if err != nil {
			log.Error("Cannot initialize FireMPQ database: %s", err)
			os.Exit(255)
		}
	}

	if database.IsClosed() {
		database = nil
		return getDatabase()
	}
	return database
}

package db

import (
	"firempq/db/cldb"
	"firempq/db/ldb"
	"firempq/log"
	"os"
	"sync"

	. "firempq/api"
)

var database DataStorage = nil
var lock sync.Mutex
var useGoLevelDB = false

// GetDatabase returns DataStorage singleton.
func GetDatabase() DataStorage {
	lock.Lock()
	defer lock.Unlock()
	return getDatabase()
}

func SetDatabase(ds DataStorage) {
	database = ds
}

func getDatabase() DataStorage {
	if database == nil {
		var err error
		if useGoLevelDB {
			database, err = ldb.NewLevelDBStorage("databasedir")
		} else {
			database, err = cldb.NewLevelDBStorage("databasedir")
		}
		if err != nil {
			log.Error("Cannot initialize FireMPQ database: %s", err)
			os.Exit(255)
		}
	}

	if database.IsClosed() {
		database = nil
		return getDatabase()
	}
	return database
}

Add flag to switch between goleveldb and levigo.


package twweather

import "testing"

func TestGetTemperture(t *testing.T) {
	weather.UpdateStationStatusWithData(sampleXML)
	station := weather.GetStation("橫山")

	temperture, err := station.GetTemperture(true)

	if err != nil {
		t.Log(err)
		t.Fail()
		return
	}

	if temperture != 26.6 {
		t.Logf("Should got 26.6, got %f", temperture)
		t.Fail()
	}
}

func TesttestWeatherElementValid(t *testing.T) {
	weather.UpdateStationStatusWithData(sampleXML)
	station := weather.GetStation("橫山")
	isValid := station.testWeatherElementValid("SUM")
	if isValid {
		t.Errorf("SUM data of 橫山 should be invalid")
	}
	isValid = station.testWeatherElementValid("H_FXT")
	if !isValid {
		t.Errorf("H_FXT data of 橫山 should be valid")
	}
}

Add test for some private method.


package statsd

import (
	"io"
	"testing"
	"time"

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

type statsdWriterWrapper struct {
	io.WriteCloser
}

func (statsdWriterWrapper) SetWriteTimeout(time.Duration) error {
	return nil
}

func TestCustomWriterBufferConfiguration(t *testing.T) {
	client, err := NewWithWriter(statsdWriterWrapper{})
	if err != nil {
		t.Fatal(err)
	}

	assert.Equal(t, OptimalUDPPayloadSize, client.bufferPool.bufferMaxSize)
	assert.Equal(t, DefaultUDPBufferPoolSize, cap(client.bufferPool.pool))
	assert.Equal(t, DefaultUDPBufferPoolSize, cap(client.sender.queue))
}

package statsd

import (
	"testing"
	"time"

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

type statsdWriterWrapper struct{}

func (statsdWriterWrapper) SetWriteTimeout(time.Duration) error {
	return nil
}

func (statsdWriterWrapper) Close() error {
	return nil
}

func (statsdWriterWrapper) Write(p []byte) (n int, err error) {
	return 0, nil
}

func TestCustomWriterBufferConfiguration(t *testing.T) {
	client, err := NewWithWriter(statsdWriterWrapper{})
	if err != nil {
		t.Fatal(err)
	}
	defer client.Close()

	assert.Equal(t, OptimalUDPPayloadSize, client.bufferPool.bufferMaxSize)
	assert.Equal(t, DefaultUDPBufferPoolSize, cap(client.bufferPool.pool))
	assert.Equal(t, DefaultUDPBufferPoolSize, cap(client.sender.queue))
}

Fix race condition in the test


package ast

// AnonymousFunction represents a anonymous function as an expression.
type AnonymousFunction struct {
	signature Signature
	body      interface{}
}

// NewAnonymousFunction creates a anonymous function.
func NewAnonymousFunction(s Signature, b interface{}) AnonymousFunction {
	return AnonymousFunction{s, b}
}

// Signature returns a signature of an anonymous function.
func (f AnonymousFunction) Signature() Signature {
	return f.signature
}

// Body returns a body expression of an anonymous function.
func (f AnonymousFunction) Body() interface{} {
	return f.body
}

package ast

import "fmt"

// AnonymousFunction represents a anonymous function as an expression.
type AnonymousFunction struct {
	signature Signature
	body      interface{}
}

// NewAnonymousFunction creates a anonymous function.
func NewAnonymousFunction(s Signature, b interface{}) AnonymousFunction {
	return AnonymousFunction{s, b}
}

// Signature returns a signature of an anonymous function.
func (f AnonymousFunction) Signature() Signature {
	return f.signature
}

// Body returns a body expression of an anonymous function.
func (f AnonymousFunction) Body() interface{} {
	return f.body
}

func (f AnonymousFunction) String() string {
	return fmt.Sprintf("(\\ (%v) %v)", f.signature, f.body)
}

Implement Stringer for anonymous function


package main

import (
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"fmt"
)

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", homeHandler)
	r.HandleFunc("/products", productsHandler)
	r.HandleFunc("/product/{productId}", productHandler)

	log.Fatal(http.ListenAndServe(":3000", r))
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Ready")
}

func productsHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Products")
}

func productHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	productId := vars["productId"]
	fmt.Fprintf(w, "You selected %s", productId)
}

//Simple Product controller
package main

import (
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"fmt"
)

type Product struct {
	Id    string `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

var products = make([]Product, 10)

//populate test users
func init() {
	createTestUsers()
}

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", homeHandler)
	r.HandleFunc("/products", productsHandler)
	r.HandleFunc("/product/{productId}", productHandler)

	log.Fatal(http.ListenAndServe(":3000", r))
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Ready")
}

func productsHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Products")
	fmt.Fprintf(w, "The product is %v", products)
}

func productHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	productId := vars["productId"]
	fmt.Fprintf(w, "You selected %s", productId)
}

func createTestUsers() {
	products[0] = Product{"1", "Daniel", "daniel.bryant@test.com"}
	products[1] = Product{"2", "Ashley", "ashley@test.com"}
	products[2] = Product{"3", "Rusty", "rusty@test.com"}
}

Create test users and return simple array


/*
Copyright 2015 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License 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 types

import (
	"fmt"
)

// NamespacedName comprises a resource name, with a mandatory namespace,
// rendered as "<namespace>/<name>".  Being a type captures intent and
// helps make sure that UIDs, namespaced names and non-namespaced names
// do not get conflated in code.  For most use cases, namespace and name
// will already have been format validated at the API entry point, so we
// don't do that here.  Where that's not the case (e.g. in testing),
// consider using NamespacedNameOrDie() in testing.go in this package.

type NamespacedName struct {
	Namespace string
	Name      string
}

const (
	Separator = '/'
)

// String returns the general purpose string representation
func (n NamespacedName) String() string {
	return fmt.Sprintf("%s%c%s", n.Namespace, Separator, n.Name)
}

/*
Copyright 2015 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License 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 types

// NamespacedName comprises a resource name, with a mandatory namespace,
// rendered as "<namespace>/<name>".  Being a type captures intent and
// helps make sure that UIDs, namespaced names and non-namespaced names
// do not get conflated in code.  For most use cases, namespace and name
// will already have been format validated at the API entry point, so we
// don't do that here.  Where that's not the case (e.g. in testing),
// consider using NamespacedNameOrDie() in testing.go in this package.

type NamespacedName struct {
	Namespace string
	Name      string
}

const (
	Separator = '/'
)

// String returns the general purpose string representation
func (n NamespacedName) String() string {
	return n.Namespace + string(Separator) + n.Name
}

Optimize string building for NamespacedName


package main

import (
	"bytes"
	"fmt"
	"github.com/teddywing/git-checkout-history/utils"
	"os"
	"os/exec"
)

func main() {
	args := os.Args[1:]

	if len(args) > 0 {
		utils.Store(args[0])

		cmd := exec.Command("git", "checkout", args[0])
		var out bytes.Buffer
		cmd.Stdout = &out
		err := cmd.Run()
		if err != nil {
			fmt.Fprintf(os.Stderr, err.Error())
		}
		fmt.Println(out.String())
	}
}

package main

import (
	"bytes"
	"fmt"
	"github.com/teddywing/git-checkout-history/utils"
	"os"
	"os/exec"
)

func main() {
	args := os.Args[1:]

	if len(args) > 0 {
		utils.Store(args[0])

		cmd := exec.Command("git", "checkout", args[0])
		var out bytes.Buffer
		cmd.Stderr = &out
		err := cmd.Run()
		if err != nil {
			fmt.Fprintf(os.Stderr, err.Error())
		}
		fmt.Println(out.String())
	}
}

Print `git checkout` stderr output


package common

import (
	"encoding/json"
	"math"
)

// PlotValue represents a graph plot value.
type PlotValue float64

// MarshalJSON handles JSON marshaling of the PlotValue type.
func (value PlotValue) MarshalJSON() ([]byte, error) {
	if math.IsNaN(float64(value)) || math.Floor(float64(value)) == 0 {
		return json.Marshal(nil)
	}

	return json.Marshal(float64(value))
}

package common

import (
	"encoding/json"
	"math"
)

// PlotValue represents a graph plot value.
type PlotValue float64

// MarshalJSON handles JSON marshaling of the PlotValue type.
func (value PlotValue) MarshalJSON() ([]byte, error) {
	// Make NaN and very small values null
	if math.IsNaN(float64(value)) || math.Exp(float64(value)) == 1 {
		return json.Marshal(nil)
	}

	return json.Marshal(float64(value))
}

Fix near-zero plot values handling.


package log

type Logger interface {
	Fatal(v ...interface{})
	Fatalf(format string, v ...interface{})
	Fatalln(v ...interface{})
	Panic(v ...interface{})
	Panicf(format string, v ...interface{})
	Panicln(v ...interface{})
	Print(v ...interface{})
	Printf(format string, v ...interface{})
	Println(v ...interface{})
}

type DebugLogger interface {
	Debug(level uint8, v ...interface{})
	Debugf(level uint8, format string, v ...interface{})
	Debugln(level uint8, v ...interface{})
	Logger
}

package log

type Logger interface {
	Fatal(v ...interface{})
	Fatalf(format string, v ...interface{})
	Fatalln(v ...interface{})
	Panic(v ...interface{})
	Panicf(format string, v ...interface{})
	Panicln(v ...interface{})
	Print(v ...interface{})
	Printf(format string, v ...interface{})
	Println(v ...interface{})
}

type DebugLogger interface {
	Debug(level uint8, v ...interface{})
	Debugf(level uint8, format string, v ...interface{})
	Debugln(level uint8, v ...interface{})
	Logger
	SetLevel(maxLevel int16)
}

Add SetLevel() to lib/log.DebugLogger interface.


package schedule

type ScheduleEntries int

type CommitSchedule [][]int

const (
	NOT_A_FIELD ScheduleEntries = -1
	EMPTY       ScheduleEntries = 0
	ONE         ScheduleEntries = 1
	TWO         ScheduleEntries = 2
	THREE       ScheduleEntries = 3
	FOUR        ScheduleEntries = 4
)

func BuildCommitSchedule(days []time.Time) CommitSchedule {
	// get weeks, which determine width and height is seven
	// fill entries with EMPTY or NOT_A_FIELD
	return nil
}

package schedule

import (
	"time"
)

type ScheduleEntries int

type CommitSchedule [][]int

const (
	NOT_A_FIELD ScheduleEntries = -1
	EMPTY       ScheduleEntries = 0
	ONE         ScheduleEntries = 1
	TWO         ScheduleEntries = 2
	THREE       ScheduleEntries = 3
	FOUR        ScheduleEntries = 4

	NUM_WEEK_DAYS = 7
)

// BuildCommitSchedule returns an empty CommitSchedule, where all fiels are
// initialized with EMPTY except those which are not in the range of days.
// The CommitSchedule is a table of ints.
func BuildCommitSchedule(days []time.Time) CommitSchedule {
	// get weeks, which determine width and height is seven
	// fill entries with EMPTY or NOT_A_FIELD
	schedule := make(CommitSchedule, 0) // TODO figure out num weeks
	// firstWeek := buildFirstWeek(days[0].Weekday())
	// lastWeek := buildLastWeek(days[len(days)-1].Weekday())
	// TODO get days inbetween first and last week and join them
	return schedule
}

func buildFirstWeek(day time.Weekday) []int {
	var firstWeek []int
	for i := 0; i < NUM_WEEK_DAYS; i++ {
		firstWeek = append(firstWeek, i)
	}
	return firstWeek
}

func buildLastWeek(day time.Weekday) []int {
	var lastWeek []int
	for i := 0; i < NUM_WEEK_DAYS; i++ {
		lastWeek = append(lastWeek, i)
	}
	return lastWeek
}

Add impl to pass compiliation, not yet tests.


// Copyright 2016 Google Inc. 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.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License 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 version

var (
	// Major is the current major version of master branch..
	Major = 0
	// Minor is the current minor version of master branch.
	Minor = 1
	// Patch is the curernt patched version of the master branch.
	Patch = 0
	// Release is the current release level of the master branch. Valid values
	// are dev (developement unreleased), rcX (release candidate with current
	// iteration), stable (indicates a final released version).
	Release = "rc2"
)

// Copyright 2016 Google Inc. 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.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License 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 version

var (
	// Major is the current major version of master branch..
	Major = 0
	// Minor is the current minor version of master branch.
	Minor = 1
	// Patch is the curernt patched version of the master branch.
	Patch = 0
	// Release is the current release level of the master branch. Valid values
	// are dev (developement unreleased), rcX (release candidate with current
	// iteration), stable (indicates a final released version).
	Release = "stable"
)

Cut stable release for 0.1.0


// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.

package recursion

// PowerSet returns a power set of s.
// The length of s must be less then size of int.
// If the size is equal or bigger, then nil interface and false is returned.
func PowerSet(s []interface{}) (ps []interface{}, ok bool) {
	if len(s) >= intSize {
		return ps, false
	}

	for i := 0; i < (1 << uint(len(s))); i++ {
		x := i
		var ss []interface{}
		for x > 0 {
			lsb := x & -x // x & -x is same as x & ^(x - 1).

			// Compute the index of x's least significant bit.
			i := 0
			p := 1
			for lsb&p == 0 { // lsb must always be greater then 0, which is always true 'cause x > 0.
				p <<= 1
				i++
			}

			ss = append(ss, s[i])
			x &= (x - 1) // This ensures that the iteration count will be the same as number of 1 bits in x.
			// x == 0 indicates sub-set end.
		}
		ps = append(ps, ss)
	}

	return ps, true
}

// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.

package recursion

// PowerSet returns a power set of s.
// The length of s must be less then size of int.
// If the size is equal or bigger, then nil interface and false is returned.
func PowerSet(s []interface{}) (ps []interface{}, ok bool) {
	if len(s) >= intSize {
		return ps, false
	}

	for i := 0; i < (1 << uint(len(s))); i++ {
		var ss []interface{}
		// x == 0 indicates sub-set end.
		// x &= (x - 1) ensures that the iteration count will be the same as number of bits set to 1 in x.
		for x := i; x > 0; x &= (x - 1) {
			lsb, i := x&-x, 0                    // x&-x is same as x&^(x - 1).
			for p := 1; lsb&p == 0; p = p << 1 { // lsb must always be greater then 0, which is always true 'cause x > 0.
				i++ // Compute the index of x's least significant bit.
			}
			ss = append(ss, s[i])
		}
		ps = append(ps, ss)
	}

	return ps, true
}

Make PowerSet method more compact


package errors

import "fmt"

type HttpError interface {
	Error
	StatusCode() int
	Headers() string
	Body() string
}

type httpError struct {
	statusCode  int
	headers     string
	body        string
	code        string
	description string
}

type HttpNotFoundError struct {
	*httpError
}

func NewHttpError(statusCode int, header string, body string, code string, description string) HttpError {
	err := httpError{
		statusCode:  statusCode,
		headers:     header,
		body:        body,
		code:        code,
		description: description,
	}
	switch statusCode {
	case 404:
		return HttpNotFoundError{&err}
	default:
		return &err
	}
}

func (err *httpError) StatusCode() int {
	return err.statusCode
}

func (err *httpError) Headers() string {
	return err.headers
}

func (err *httpError) Body() string {
	return err.body
}

func (err *httpError) Error() string {
	return fmt.Sprintf(
		"Server error, status code: %d, error code: %s, message: %s",
		err.statusCode,
		err.code,
		err.description,
	)
}

func (err *httpError) ErrorCode() string {
	return err.code
}

package errors

import "fmt"

type HttpError interface {
	error
	StatusCode() int   // actual HTTP status code
	ErrorCode() string // error code returned in response body from CC or UAA
	Headers() string   // see: known_error_codes.go
	Body() string
}

type httpError struct {
	statusCode  int
	headers     string
	body        string
	code        string
	description string
}

type HttpNotFoundError struct {
	*httpError
}

func NewHttpError(statusCode int, header string, body string, code string, description string) HttpError {
	err := httpError{
		statusCode:  statusCode,
		headers:     header,
		body:        body,
		code:        code,
		description: description,
	}
	switch statusCode {
	case 404:
		return HttpNotFoundError{&err}
	default:
		return &err
	}
}

func (err *httpError) StatusCode() int {
	return err.statusCode
}

func (err *httpError) Headers() string {
	return err.headers
}

func (err *httpError) Body() string {
	return err.body
}

func (err *httpError) Error() string {
	return fmt.Sprintf(
		"Server error, status code: %d, error code: %s, message: %s",
		err.statusCode,
		err.code,
		err.description,
	)
}

func (err *httpError) ErrorCode() string {
	return err.code
}

Add comments to HTTPError interface


package gtf

import (
	"testing"
	"bytes"
	"html/template"
)

func AssertEqual(t *testing.T, buffer *bytes.Buffer, testString string) {
	if buffer.String() != testString {
		t.Error()
	}
	buffer.Reset()
}

func ParseTest(buffer *bytes.Buffer, body string) {
	tpl := template.New("test").Funcs(GtfFuncMap)
	tpl.Parse(body)
	tpl.Execute(buffer, "")
}

func TestGtfFuncMap(t *testing.T) {
	var buffer bytes.Buffer

	ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringReplace \" \" }}")
	AssertEqual(t, &buffer, "TheGoProgrammingLanguage")

	ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringDefault \"default value\" }}")
	AssertEqual(t, &buffer, "The Go Programming Language")

	ParseTest(&buffer, "{{ \"\" | stringDefault \"default value\" }}")
	AssertEqual(t, &buffer, "default value")

	ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringLower }}")
	AssertEqual(t, &buffer, "the go programming language")
}

package gtf

import (
	"testing"
	"bytes"
	"html/template"
)

func AssertEqual(t *testing.T, buffer *bytes.Buffer, testString string) {
	if buffer.String() != testString {
		t.Error()
	}
	buffer.Reset()
}

func ParseTest(buffer *bytes.Buffer, body string) {
	tpl := template.New("test").Funcs(GtfFuncMap)
	tpl.Parse(body)
	tpl.Execute(buffer, "")
}

func TestGtfFuncMap(t *testing.T) {
	var buffer bytes.Buffer

	ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringReplace \" \" }}")
	AssertEqual(t, &buffer, "TheGoProgrammingLanguage")

	ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringDefault \"default value\" }}")
	AssertEqual(t, &buffer, "The Go Programming Language")

	ParseTest(&buffer, "{{ \"\" | stringDefault \"default value\" }}")
	AssertEqual(t, &buffer, "default value")

	ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringLength }}")
	AssertEqual(t, &buffer, "27")

	ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringLower }}")
	AssertEqual(t, &buffer, "the go programming language")
}

Add a test for stringLength.


package api

import (
	"github.com/docker/notary/signer"
	"github.com/docker/notary/signer/keys"

	pb "github.com/docker/notary/proto"
)

func FindKeyByID(sigServices signer.SigningServiceIndex, keyID *pb.KeyID) (*pb.PublicKey, signer.SigningService, error) {
	for _, service := range sigServices {
		key, err := service.KeyInfo(keyID)
		if err == nil {
			return key, service, nil
		}
	}

	return nil, nil, keys.ErrInvalidKeyID
}

package api

import (
	"github.com/docker/notary/signer"
	"github.com/docker/notary/signer/keys"

	pb "github.com/docker/notary/proto"
)

// FindKeyByID looks for the key with the given ID in each of the
// signing services in sigServices. It returns the first matching key it finds,
// or ErrInvalidKeyID if the key is not found in any of the signing services.
func FindKeyByID(sigServices signer.SigningServiceIndex, keyID *pb.KeyID) (*pb.PublicKey, signer.SigningService, error) {
	for _, service := range sigServices {
		key, err := service.KeyInfo(keyID)
		if err == nil {
			return key, service, nil
		}
	}

	return nil, nil, keys.ErrInvalidKeyID
}

Add documentation for FindKeyByID function


package main

import (
	"fmt"
	"strconv"
)

func main() {
	for i := 1; i <= 100; i++ {
		var output string
		switch {
		case i%15 == 0:
			output = "fizzbuzz"
		case i%3 == 0:
			output = "fizz"
		case i%5 == 0:
			output = "buzz"
		default:
			output = strconv.Itoa(i)
		}
		fmt.Println(output)
	}
}

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var output string
	for i := 1; i <= 100; i++ {
		switch {
		case i%15 == 0:
			output = "fizzbuzz"
		case i%3 == 0:
			output = "fizz"
		case i%5 == 0:
			output = "buzz"
		default:
			output = strconv.Itoa(i)
		}
		fmt.Println(output)
	}
}

Move var initialization out of loop


package crawler

// TODO: Implement
func (p *Prospector) isFileRenamed(file string, info os.FileInfo, missingfiles map[string]os.FileInfo) string {
	// Can we detect if a file was renamed on Windows?
	// NOTE(driskell): What about using golang's func os.SameFile(fi1, fi2 FileInfo) bool?
	return ""
}

func (p *Prospector) isFileRenamedResumelist(file string, info os.FileInfo, initial map[string]*FileState) string {
	// Can we detect if a file was renamed on Windows?
	// NOTE(driskell): What about using golang's func os.SameFile(fi1, fi2 FileInfo) bool?
	return ""
}

package crawler

import (
	"os"

	"github.com/elastic/filebeat/input"
)

// TODO: Implement
func (p *Prospector) isFileRenamed(file string, info os.FileInfo, missingfiles map[string]os.FileInfo) string {
	// Can we detect if a file was renamed on Windows?
	// NOTE(driskell): What about using golang's func os.SameFile(fi1, fi2 FileInfo) bool?
	return ""
}

func (p *Prospector) isFileRenamedResumelist(file string, info os.FileInfo, initial map[string]*input.FileState) string {
	// Can we detect if a file was renamed on Windows?
	// NOTE(driskell): What about using golang's func os.SameFile(fi1, fi2 FileInfo) bool?
	return ""
}

Fix compile error on Windows.


package assert

import (
	"fmt"
	"io"
	"os"
)

type location struct {
	Test     string
	FileName string
	Line     int
}

type errorLogger interface {
	Log(location *location, message string)
}

var theLogger errorLogger = &errorLoggerImpl{writer: os.Stdout}

type errorLoggerImpl struct {
	writer       io.Writer
	prevTestName string
	prevTestLine int
}

const (
	failOutput                  = "--- FAIL: %s\n\t%s:%d\n\t\t%s\n"
	failOutputWithoutFailLine   = "\t%s:%d\n\t\t%s\n"
	failOutputWithoutLineNumber = "\t\t%s\n"
)

func (logger *errorLoggerImpl) Log(location *location, message string) {
	args := []interface{}{location.Test, location.FileName, location.Line, message}
	if logger.prevTestName != location.Test {
		fmt.Fprintf(logger.writer, failOutput, args...)
	} else {
		if logger.prevTestLine != location.Line {
			fmt.Fprintf(logger.writer, failOutputWithoutFailLine, args[1:]...)
		} else {
			fmt.Fprintf(logger.writer, failOutputWithoutLineNumber, message)
		}
	}
	logger.prevTestName = location.Test
	logger.prevTestLine = location.Line
}

package assert

import (
	"fmt"
	"io"
	"os"
)

type location struct {
	Test     string
	FileName string
	Line     int
}

type errorLogger interface {
	Log(location *location, message string)
}

var theLogger errorLogger = &errorLoggerImpl{writer: os.Stdout}

type errorLoggerImpl struct {
	writer       io.Writer
	prevTestName string
	prevTestLine int
}

const (
	failOutput                  = "--- FAIL: %s\n\t%s:%d\n\t\t%s\n"
	failOutputWithoutFailLine   = "\t%s:%d\n\t\t%s\n"
	failOutputWithoutLineNumber = "\t\t%s\n"
)

func (logger *errorLoggerImpl) Log(location *location, message string) {
	args := []interface{}{location.Test, location.FileName, location.Line, message}
	if logger.prevTestName != location.Test {
		fmt.Fprintf(logger.writer, failOutput, args...)
	} else if logger.prevTestLine != location.Line {
		fmt.Fprintf(logger.writer, failOutputWithoutFailLine, args[1:]...)
	} else {
		fmt.Fprintf(logger.writer, failOutputWithoutLineNumber, message)
	}
	logger.prevTestName = location.Test
	logger.prevTestLine = location.Line
}

Refactor the error logger A BIT.


package vcr_test

import (
	"io/ioutil"
	"net/http"
	"strings"
	"testing"

	"github.com/dnaeon/go-vcr/recorder"
)

func TestSimple(t *testing.T) {
	// Start our recorder
	r, err := recorder.New("fixtures/golang-org")
	if err != nil {
		t.Fatal(err)
	}
	defer r.Stop()

	// Create an HTTP client and inject our transport
	client := &http.Client{
		Transport: r.Transport, // Inject our transport!
	}

	url := "http://golang.org/"
	resp, err := client.Get(url)
	if err != nil {
		t.Fatalf("Failed to get url %s: %s", url, err)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("Failed to read response body: %s", err)
	}

	wantTitle := "<title>The Go Programming Language</title>"
	bodyContent := string(body)

	if !strings.Contains(bodyContent, wantTitle) {
		t.Errorf("Title %s not found in response", wantTitle)
	}
}

package vcr_test

import (
	"io/ioutil"
	"net/http"
	"strings"
	"testing"

	"github.com/dnaeon/go-vcr/recorder"
)

func TestSimple(t *testing.T) {
	// Start our recorder
	r, err := recorder.New("fixtures/golang-org")
	if err != nil {
		t.Fatal(err)
	}
	defer r.Stop() // Make sure recorder is stopped once done with it

	// Create an HTTP client and inject our transport
	client := &http.Client{
		Transport: r.Transport, // Inject our transport!
	}

	url := "http://golang.org/"
	resp, err := client.Get(url)
	if err != nil {
		t.Fatalf("Failed to get url %s: %s", url, err)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("Failed to read response body: %s", err)
	}

	wantTitle := "<title>The Go Programming Language</title>"
	bodyContent := string(body)

	if !strings.Contains(bodyContent, wantTitle) {
		t.Errorf("Title %s not found in response", wantTitle)
	}
}

Add commment to stop recorder once done with it


/*
Copyright 2016 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License 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 DNS provides a backend for the skydns DNS server started by the
// kubedns cluster addon. It exposes the 2 interface method: Records and
// ReverseRecord, which skydns invokes according to the DNS queries it
// receives. It serves these records by consulting an in memory tree
// populated with Kubernetes Services and Endpoints received from the Kubernetes
// API server.
package dns // import "k8s.io/kubernetes/pkg/dns"

Use Go canonical import paths


package shade

import (
	"fmt"
	"time"
)

type File struct {
	Filename     string
	Filesize     int64
	ModifiedTime time.Time
	Chunksize    int
	Chunks       []Chunk
	AesKey       []byte
}

type Chunk struct {
	Index  int
	Sha256 []byte
}

func (f *File) String() string {
	out := fmt.Sprintf("{Filename: %s, Filesize: %d, Chunksize: %d, AesKey: %s, Chunks:", f.Filename, f.Filesize, f.Chunksize)
	sep := ", "
	if len(f.Chunks) < 2 {
		out += " "
	} else {
		out += "\n"
		sep = ",\n"
	}
	for i, c := range f.Chunks {
		if i == len(f.Chunks) {
			out += c.String() + sep
		} else {
			out += c.String()
		}
	}
	return out
}

func (c *Chunk) String() string {
	return fmt.Sprintf("{Index: %d, Sha256: %x}", c.Index, c.Sha256)
}

package shade

import (
	"fmt"
	"time"
)

type File struct {
	Filename     string
	Filesize     int64
	ModifiedTime time.Time
	Chunksize    int
	Chunks       []Chunk
	AesKey       []byte
}

type Chunk struct {
	Index  int
	Sha256 []byte
}

func (f *File) String() string {
	out := fmt.Sprintf("{Filename: %q, Filesize: %d, Chunksize: %d, AesKey: %q, Chunks:", f.Filename, f.Filesize, f.Chunksize, f.AesKey)
	sep := ", "
	if len(f.Chunks) < 2 {
		out += " "
	} else {
		out += "\n"
		sep = ",\n"
	}
	for i, c := range f.Chunks {
		if i == len(f.Chunks) {
			out += c.String() + sep
		} else {
			out += c.String()
		}
	}
	return out
}

func (c *Chunk) String() string {
	return fmt.Sprintf("{Index: %d, Sha256: %x}", c.Index, c.Sha256)
}

Fix bug in AesKey printing, quote strings.


package main

import (
	"io"
	"os"

	"github.com/anacrolix/torrent"
)

// SeekableContent describes an io.ReadSeeker that can be closed as well.
type SeekableContent interface {
	io.ReadSeeker
	io.Closer
}

// FileEntry helps reading a torrent file.
type FileEntry struct {
	*torrent.File
	Reader *torrent.Reader
}

// Seek seeks to the correct file position, paying attention to the offset.
func (f FileEntry) Seek(offset int64, whence int) (int64, error) {
	return (*f.Reader).Seek(offset+f.File.Offset(), whence)
}

func (f FileEntry) Read(p []byte) (n int, err error) {
	return (*f.Reader).Read(p)
}

func (f FileEntry) Close() error {
	return (*f.Reader).Close()
}

// NewFileReader sets up a torrent file for streaming reading.
func NewFileReader(f *torrent.File) (SeekableContent, error) {
	torrent := f.Torrent()
	reader := torrent.NewReader()

	// We read ahead 1% of the file continuously.
	reader.SetReadahead(f.Length() / 100)
	reader.SetResponsive()
	_, err := reader.Seek(f.Offset(), os.SEEK_SET)

	return &FileEntry{
		File:   f,
		Reader: &reader,
	}, err
}

package main

import (
	"io"
	"os"

	"github.com/anacrolix/torrent"
)

// SeekableContent describes an io.ReadSeeker that can be closed as well.
type SeekableContent interface {
	io.ReadSeeker
	io.Closer
}

// FileEntry helps reading a torrent file.
type FileEntry struct {
	*torrent.File
	torrent.Reader
}

// NewFileReader sets up a torrent file for streaming reading.
func NewFileReader(f *torrent.File) (SeekableContent, error) {
	torrent := f.Torrent()
	reader := torrent.NewReader()

	// We read ahead 1% of the file continuously.
	reader.SetReadahead(f.Length() / 100)
	reader.SetResponsive()
	_, err := reader.Seek(f.Offset(), os.SEEK_SET)

	return &FileEntry{
		File:   f,
		Reader: reader,
	}, err
}

Update FileEntry including torrent.Reader interface properly