package gocipher

func LetterNumberEncrypt(text string) []int {
	runes := []rune(text)
	numbers := make([]int, len(runes))
	for i, rune := range runes {
		if rune >= 'A' && rune <= 'Z' {
			numbers[i] = int(rune - 'A' + 1)
		} else if rune >= 'a' && rune <= 'z' {
			numbers[i] = int(rune - 'a' + 1)
		}
	}
	return numbers
}

func LetterNumberDecrypt(numbers []int) string {
	runes := make([]rune, len(numbers))
	for i, number := range numbers {
		runes[i] = rune(number + 'A' - 1)
	}
	return string(runes)
}

package gocipher

// LetterNumberEncrypt - Converts letters to the corresponding number.
// e.g. "ABC...XYZ" becomes []int{1, 2, 3 ... 24, 25, 26}
func LetterNumberEncrypt(text string) []int {
	runes := []rune(text)
	numbers := make([]int, len(runes))
	for i, rune := range runes {
		if rune >= 'A' && rune <= 'Z' {
			numbers[i] = int(rune - 'A' + 1)
		} else if rune >= 'a' && rune <= 'z' {
			numbers[i] = int(rune - 'a' + 1)
		}
	}
	return numbers
}

// LetterNumberDecrypt - Converts numbers to the corresponding letter.
// e.g. []int{1, 2, 3 ... 24, 25, 26} becomes "ABC...XYZ"
func LetterNumberDecrypt(numbers []int) string {
	runes := make([]rune, len(numbers))
	for i, number := range numbers {
		runes[i] = rune(number + 'A' - 1)
	}
	return string(runes)
}

Add letter to number doc comments


package gofakes3

import (
	"net/http"
	"strings"
)

var (
	corsHeaders = []string{
		"Accept",
		"Accept-Encoding",
		"Authorization",
		"Content-Disposition",
		"Content-Length",
		"Content-Type",
		"X-Amz-Date",
		"X-Amz-User-Agent",
		"X-CSRF-Token",
		"x-amz-acl",
		"x-amz-meta-filename",
		"x-amz-meta-from",
		"x-amz-meta-private",
		"x-amz-meta-to",
	}
	corsHeadersString = strings.Join(corsHeaders, ", ")
)

type withCORS struct {
	r   http.Handler
	log Logger
}

func (s *withCORS) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD")
	w.Header().Set("Access-Control-Allow-Headers", corsHeadersString)

	if r.Method == "OPTIONS" {
		return
	}

	s.r.ServeHTTP(w, r)
}

package gofakes3

import (
	"net/http"
	"strings"
)

var (
	corsHeaders = []string{
		"Accept",
		"Accept-Encoding",
		"Authorization",
		"Content-Disposition",
		"Content-Length",
		"Content-Type",
		"X-Amz-Date",
		"X-Amz-User-Agent",
		"X-CSRF-Token",
		"x-amz-acl",
		"x-amz-content-sha256",
		"x-amz-meta-filename",
		"x-amz-meta-from",
		"x-amz-meta-private",
		"x-amz-meta-to",
		"x-amz-security-token",
	}
	corsHeadersString = strings.Join(corsHeaders, ", ")
)

type withCORS struct {
	r   http.Handler
	log Logger
}

func (s *withCORS) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD")
	w.Header().Set("Access-Control-Allow-Headers", corsHeadersString)
	w.Header().Set("Access-Control-Expose-Headers", "ETag")

	if r.Method == "OPTIONS" {
		return
	}

	s.r.ServeHTTP(w, r)
}

Support multipart uploads from browser


package plaintext

import (
	"strings"
)

// returns the mimetype of the full filename if none
func getSuffix(filename string) string {
	idx := strings.LastIndex(filename, ".")
	if idx == -1 || idx+1 == len(filename) {
		return filename
	}
	return filename[idx+1:]
}

// ExtractorByFilename returns an plaintext extractor based on
// filename heuristic
func ExtractorByFilename(filename string) (Extractor, error) {
	var e Extractor
	var err error
	switch getSuffix(filename) {
	case "md":
		e, err = NewMarkdownText()
	case "html":
		e, err = NewHTMLText()
	case "go", "h", "c", "java":
		e, err = NewGolangText()
	default:
		e, err = NewIdentity()
	}
	if err != nil {
		return nil, err
	}
	return e, nil
}

package plaintext

import (
	"strings"
)

// returns the mimetype of the full filename if none
func getSuffix(filename string) string {
	idx := strings.LastIndex(filename, ".")
	if idx == -1 || idx+1 == len(filename) {
		return filename
	}
	return filename[idx+1:]
}

// ExtractorByFilename returns an plaintext extractor based on
// filename heuristic
func ExtractorByFilename(filename string) (Extractor, error) {
	var e Extractor
	var err error
	switch getSuffix(filename) {
	case "md":
		e, err = NewMarkdownText()
	case "html":
		e, err = NewHTMLText()
	case "go", "h", "c", "java", "hxx", "cxx":
		e, err = NewGolangText()
	default:
		e, err = NewIdentity()
	}
	if err != nil {
		return nil, err
	}
	return e, nil
}

Use golang parser for .hxx and .cxx files


// errchk $G $D/$F.go

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

package main

import (
	OS "os"  // should require semicolon here; this is no different from other decls
	IO "io"
)

func main() {
}

// errchk $G $D/$F.go

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

package main

import (
	OS "os"  // should require semicolon here; this is no different from other decls
	IO "io"  // ERROR "missing"
)

func main() {
}

Add ERROR comment for errmsg to look for.


package apixu

import (
	"os"
	"testing"
)

func getAPIKey() string {
	return os.Getenv("APIXU_KEY")
}

func TestCurrentWeather(t *testing.T) {

}

package apixu

import (
	"os"
	"testing"
)

var cities = []string{
	"Cairo",
	"London",
	"Paris",
	"Berlin",
	"New York",
}

func getAPIKey() string {
	return os.Getenv("APIXU_KEY")
}

func TestInvalidAPIKey(t *testing.T) {
	client := NewClient("Invalid_Key")
	_, err := client.Current("Paris")

	if err == nil {
		t.Error("Worked with invalid key")
	}
}

func TestCurrentWeatherValidCities(t *testing.T) {
	client := NewClient(getAPIKey())

	for _, city := range cities {
		_, err := client.Current(city)

		if err != nil {
			t.Errorf("There was an error getting current weather of %s: %v", city, err)
		}
	}
}

func TestCurrentWeatherInValidCity(t *testing.T) {
	client := NewClient(getAPIKey())
	_, err := client.Current("Unknown City")

	if err == nil {
		t.Errorf("No errors getting current weather of invalid city name")
	}
}

func TestForecastWeatherValidCities(t *testing.T) {
	days := []int{1, 5, 10}
	client := NewClient(getAPIKey())

	for _, day := range days {
		for _, city := range cities {
			_, err := client.Forecast(city, day)

			if err != nil {
				t.Errorf("There was an error getting forecast weather of %s days %d: %v", city, day, err)
			}
		}
	}
}

func TestForecastWeatherInValidCities(t *testing.T) {
	days := []int{1, 5, 10}
	client := NewClient(getAPIKey())

	for _, day := range days {
		_, err := client.Forecast("Unknown City", day)

		if err == nil {
			t.Errorf("No errors getting forecast weather of invalid city name")
		}
	}
}

Add currentWeather and forecastWeather tests


package coreutils

import (
	"os"
	"os/exec"
)

// ExecCommand executes a command with args and returning the stringified output
func ExecCommand(command string, args []string, redirect bool) string {
	if ExecutableExists(command) { // If the executable exists
		var output []byte
		runner := exec.Command(command, args...)

		if redirect { // If we should redirect output to var
			output, _ = runner.CombinedOutput() // Combine the output of stderr and stdout
		} else {
			runner.Stdout = os.Stdout
			runner.Stderr = os.Stderr
			runner.Start()
		}

		return string(output[:])
	} else { // If the executable doesn't exist
		return command + " is not an executable."
	}
}

// ExecutableExists checks if an executable exists
func ExecutableExists(executableName string) bool {
	_, existsErr := exec.LookPath(executableName)
	return (existsErr == nil)
}

package coreutils

import (
	"os"
	"os/exec"
)

// ExecCommand executes a command with args and returning the stringified output
func ExecCommand(command string, args []string, redirect bool) string {
	if ExecutableExists(command) { // If the executable exists
		var output []byte
		runner := exec.Command(command, args...)

		if redirect { // If we should redirect output to var
			output, _ = runner.CombinedOutput() // Combine the output of stderr and stdout
		} else {
			runner.Stdout = os.Stdout
			runner.Stderr = os.Stderr
			runner.Wait()
		}

		return string(output[:])
	} else { // If the executable doesn't exist
		return command + " is not an executable."
	}
}

// ExecutableExists checks if an executable exists
func ExecutableExists(executableName string) bool {
	_, existsErr := exec.LookPath(executableName)
	return (existsErr == nil)
}

Call Wait() instead of Start() so we wait for the command to finish before output.


package main

import (
	"reflect"
	"testing"
)

var parseIndexesListTests = []struct {
	list    string
	indexes []int
}{
	// Only one index
	{
		list:    "10",
		indexes: []int{9},
	},
	{
		list:    "120",
		indexes: []int{119},
	},

	// Multiple indexes
	{
		list:    "10,120",
		indexes: []int{9, 119},
	},
	{
		list:    "10,120,50",
		indexes: []int{9, 119, 49},
	},
	{
		list:    "3,2,1,0",
		indexes: []int{2, 1, 0, -1},
	},
}

func TestParseIndexesList(t *testing.T) {
	for _, test := range parseIndexesListTests {
		expect := test.indexes
		actual, err := parseIndexesList(test.list)
		if err != nil {
			t.Errorf("parseIndexesList(%q) returns %q, want nil",
				test.list, err)
		}
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("parseIndexesList(%q) = %v, want %v",
				test.list, actual, expect)
		}
	}
}

Remove test to summarize NewIndexes and parseIndexesList


package main

import (
	"context"
	"log"
	"os"

	"github.com/zmb3/spotify"
	"golang.org/x/oauth2/clientcredentials"
)

func main() {
	config := &clientcredentials.Config{
		ClientID:     os.Getenv("SPOTIFY_ID"),
		ClientSecret: os.Getenv("SPOTIFY_SECRET"),
		TokenURL:     spotify.TokenURL,
	}
	token, err := config.Token(context.Background())
	if err != nil {
		log.Fatalf("couldn't get token: %v", err)
	}

	client := spotify.Authenticator{}.NewClient(token)

	tracks, err := client.GetPlaylistTracks("37i9dQZF1DWWzVPEmatsUB")
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Playlist has %d total tracks", tracks.Total)
	for page := 1; ; page++ {
		log.Printf("  Page %d has %d tracks", page, len(tracks.Tracks))
		err = client.NextPage(tracks)
		if err == spotify.ErrNoMorePages {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
	}
}

package main

import (
	"context"
	"log"
	"os"

	"github.com/zmb3/spotify"
	"golang.org/x/oauth2/clientcredentials"
)

func main() {
	config := &clientcredentials.Config{
		ClientID:     os.Getenv("SPOTIFY_ID"),
		ClientSecret: os.Getenv("SPOTIFY_SECRET"),
		TokenURL:     spotify.TokenURL,
	}
	token, err := config.Token(context.Background())
	if err != nil {
		log.Fatalf("couldn't get token: %v", err)
	}

	client := spotify.Authenticator{}.NewClient(token)
	tracks, err := client.GetPlaylistTracks("57qttz6pK881sjxj2TAEEo")
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Playlist has %d total tracks", tracks.Total)
	for page := 1; ; page++ {
		log.Printf("  Page %d has %d tracks", page, len(tracks.Tracks))
		err = client.NextPage(tracks)
		if err == spotify.ErrNoMorePages {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
	}
}

Include longer playlist in pagination example


package disruptor

import "sync/atomic"

type SharedWriter struct {
	written   *Cursor
	upstream  Barrier
	capacity  int64
	gate      *Cursor
	mask      int64
	shift     uint8
	committed []int32
}

func NewSharedWriter(write *SharedWriterBarrier, upstream Barrier) *SharedWriter {
	return &SharedWriter{
		written:   write.written,
		upstream:  upstream,
		capacity:  write.capacity,
		gate:      NewCursor(),
		mask:      write.mask,
		shift:     write.shift,
		committed: write.committed,
	}
}

func (this *SharedWriter) Reserve(count int64) int64 {
	for {
		previous := this.written.Load()
		upper := previous + count

		for upper-this.capacity > this.gate.Load() {
			this.gate.Store(this.upstream.Read(0))
		}

		if atomic.CompareAndSwapInt64(&this.written.sequence, previous, upper) {
			return upper
		}
	}
}

func (this *SharedWriter) Commit(lower, upper int64) {
	// POTENTIAL TODO: start from upper and work toward lower
	// this may have the effect of keeping a batch together which
	// might otherwise be split up...
	for lower <= upper {
		this.committed[lower&this.mask] = int32(lower >> this.shift)
		lower++
	}
}

package disruptor

import "sync/atomic"

type SharedWriter struct {
	written   *Cursor
	upstream  Barrier
	capacity  int64
	gate      *Cursor
	mask      int64
	shift     uint8
	committed []int32
}

func NewSharedWriter(write *SharedWriterBarrier, upstream Barrier) *SharedWriter {
	return &SharedWriter{
		written:   write.written,
		upstream:  upstream,
		capacity:  write.capacity,
		gate:      NewCursor(),
		mask:      write.mask,
		shift:     write.shift,
		committed: write.committed,
	}
}

func (this *SharedWriter) Reserve(count int64) int64 {
	for {
		previous := this.written.Load()
		upper := previous + count

		for upper-this.capacity > this.gate.Load() {
			this.gate.Store(this.upstream.Read(0))
		}

		if atomic.CompareAndSwapInt64(&this.written.sequence, previous, upper) {
			return upper
		}
	}
}

func (this *SharedWriter) Commit(lower, upper int64) {
	if lower == upper {
		this.committed[upper&this.mask] = int32(upper >> this.shift)
	} else {
		// working down the array keeps all items in the commit together
		// otherwise the reader(s) could split up the group
		for upper >= lower {
			this.committed[upper&this.mask] = int32(upper >> this.shift)
			upper--
		}

	}
}

Comment about keeping a commit together; also removed for loop where possible.


package main

import (
	"log"
	"net/http"

	"github.com/gorilla/mux"
)

const (
	PORT = ":8080"
)

func main() {
	router := mux.NewRouter()
	router.HandleFunc("/", roothandler)
	err := http.ListenAndServe(PORT, router)
	if err != nil {
		log.Fatal(err)
	}

}

package main

import (
	"log"
	"net/http"

	"github.com/gorilla/mux"
)

const (
	PORT = ":8080"
)

func rootHandler(w http.responsewriter, r *http.request) {

}

func todoHandler(w http.responsewriter, r *http.request) {

}

func addHandler(w http.responsewriter, r *http.request) {

}

func editHandler(w http.responsewriter, r *http.request) {

}

func delHandler(w http.responsewriter, r *http.request) {

}

func finishHandler(w http.responsewriter, r *http.request) {

}

func userHandler(w http.responsewriter, r *http.request) {

}

func userDelHandler(w http.responsewriter, r *http.request) {

}

func loginHandler(w http.responsewriter, r *http.request) {

}

func registerHandler(w http.responsewriter, r *http.request) {

}

func logoutHandler(w http.responsewriter, r *http.request) {

}

func resetHandler(w http.responsewriter, r *http.request) {

}

func main() {
	router := mux.NewRouter()
	router.HandleFunc("/", rootHandler)

	router.HandleFunc("/todo", todoHandler)
	router.HandleFunc("/todo/{id}", todoHandler)
	router.HandleFunc("/todo/add", addHandler)
	router.HandleFunc("/todo/edit/{id}", editHandler)
	router.HandleFunc("/todo/del/{id}", delHandler)

	router.HandleFunc("/finish/{id}", finishHandler)

	router.HandleFunc("/user", userHandler)
	router.HandleFunc("/user/{id}", userHandler)
	router.HandleFunc("/user/del/{id}", userDelHandler)

	router.HandleFunc("/register", registerHandler)
	router.HandleFunc("/login", loginHandler)
	router.HandleFunc("/logout", logoutHandler)
	router.HandleFunc("/resetpass", resetHandler)
	err := http.ListenAndServe(PORT, router)
	if err != nil {
		log.Fatal(err)
	}

}

Add base routes and base functions


// Package uuid creates pseudo uuid by using crypto/rand.
package uuid

import (
	"crypto/rand"
	"fmt"
)

var (
	DEBUG bool = false // Enable / disable debug messages from this package.
)

// New() creates pseudo uuid.
func New() (uuid string, err error) {
	b := make([]byte, 16)

	_, err = rand.Read(b)
	if err != nil {
		if DEBUG {
			fmt.Printf("rand.Read() err: %v", err)
		}
		return "", err
	}

	uuid = fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
	return uuid, nil
}

// Package uuid creates pseudo uuid by using crypto/rand.
package uuid

import (
	"crypto/rand"
	"fmt"
)

var (
	DEBUG bool = false // Enable / disable debug messages from this package.
)

// New creates pseudo uuid.
func New() (uuid string, err error) {
	b := make([]byte, 16)

	_, err = rand.Read(b)
	if err != nil {
		if DEBUG {
			fmt.Printf("rand.Read() err: %v", err)
		}
		return "", err
	}

	uuid = fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
	return uuid, nil
}

Fix func names in comments to remove golint warnings.


package main

import (
    "fmt"
    "os"
    "path/filepath"
    "github.com/dmulholland/clio/go/clio"
    "sort"
)

// Help text for the 'tags' command.
var tagsHelp = fmt.Sprintf(`
Usage: %s tags [FLAGS] [OPTIONS]

  List the tags in a database.

Options:
  -f, --file <str>          Database file. Defaults to the last used file.

Flags:
      --help                Print this command's help text and exit.
`, filepath.Base(os.Args[0]))

// Callback for the 'tags' command.
func tagsCallback(parser *clio.ArgParser) {

    // Load the database.
    _, _, db := loadDB(parser)

    // Assemble a map of tags.
    tagmap := db.TagMap()

    // Extract a sorted slice of tag strings.
    tags := make([]string, 0)
    for tag := range tagmap {
        tags = append(tags, tag)
    }
    sort.Strings(tags)

    // Print the tag list.
    line("-")
    fmt.Println("  Tags")
    line("-")
    for _, tag := range tags {
        fmt.Printf("  %s [%d]\n", tag, len(tagmap[tag]))
    }
    line("-")
}

package main

import (
    "fmt"
    "os"
    "path/filepath"
    "github.com/dmulholland/clio/go/clio"
    "sort"
)

// Help text for the 'tags' command.
var tagsHelp = fmt.Sprintf(`
Usage: %s tags [FLAGS] [OPTIONS]

  List the tags in a database.

Options:
  -f, --file <str>          Database file. Defaults to the last used file.

Flags:
      --help                Print this command's help text and exit.
`, filepath.Base(os.Args[0]))

// Callback for the 'tags' command.
func tagsCallback(parser *clio.ArgParser) {

    // Load the database.
    _, _, db := loadDB(parser)

    // Assemble a map of tags.
    tagmap := db.TagMap()

    // Extract a sorted slice of tag strings.
    tags := make([]string, 0)
    for tag := range tagmap {
        tags = append(tags, tag)
    }
    sort.Strings(tags)

    // Print the tag list.
    if len(tags) > 0 {
        line("-")
        fmt.Println("  Tags")
        line("-")
        for _, tag := range tags {
            fmt.Printf("  %s [%d]\n", tag, len(tagmap[tag]))
        }
        line("-")
    } else {
        line("-")
        fmt.Println("  No Tags")
        line("-")
    }
}

Fix tag command when empty


package struct_mommy_test

import (
    "fmt"

    "github.com/mrfuxi/struct-mommy"
)

type MyStruct struct {
    FieldA float32
    FieldB uint8
}

func ExampleMake() {
    obj := MyStruct{}

    struct_mommy.SetSeed(26)
    struct_mommy.Make(&obj)

    fmt.Printf("FieldA %v\nFieldB %v", obj.FieldA, obj.FieldB)
    // Output:
    // FieldA -1.5426473e+38
    // FieldB 42
}

func ExampleDefine() {
    obj := MyStruct{}

    struct_mommy.SetSeed(26)
    struct_mommy.Make(&obj, struct_mommy.Define("FieldA", 2.0))

    fmt.Printf("FieldA %v\nFieldB %v", obj.FieldA, obj.FieldB)
    // Output:
    // FieldA 2
    // FieldB 42
}

Add example for using Define


package main

import (
	"log"
	"net/http"
)

func main() {
	var g GMHook
	err := http.ListenAndServe("localhost:4000", g)
	if err != nil {
		log.Fatal(err)
	}
}

package main

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

func main() {
	var g GMHook
	err := http.ListenAndServe(":"+os.Getenv("PORT"), g)
	if err != nil {
		log.Fatal(err)
	}
}

Make sure to bind to the correct port


package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"os/exec"
)

func executeCmd(command string, args ...string) {
	cmd := exec.Command(command, args...)
	cmdReader, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatal(os.Stderr, "Error creating StdoutPipe for Cmd", err)
	}

	defer cmdReader.Close()

	scanner := bufio.NewScanner(cmdReader)
	go func() {
		for scanner.Scan() {
			fmt.Printf("%s\n", scanner.Text())
		}
	}()

	err = cmd.Start()
	if err != nil {
		log.Fatal(os.Stderr, "Error starting Cmd", err)
	}

	err = cmd.Wait()
	// go generate command will fail when no generate command find.
	if err != nil {
		if err.Error() != "exit status 1" {
			fmt.Println(err)
			log.Fatal(err)
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"os/exec"
)

func executeCmd(command string, args ...string) {
	cmd := exec.Command(command, args...)

	stdOut, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatal(os.Stderr, "Error creating StdoutPipe for Cmd", err)
	}

	defer stdOut.Close()

	scanner := bufio.NewScanner(stdOut)
	go func() {
		for scanner.Scan() {
			fmt.Printf("%s\n", scanner.Text())
		}
	}()

	stdErr, err := cmd.StderrPipe()
	if err != nil {
		log.Fatal(os.Stderr, "Error creating StderrPipe for Cmd", err)
	}

	defer stdErr.Close()

	stdErrScanner := bufio.NewScanner(stdErr)
	go func() {
		for stdErrScanner.Scan() {
			fmt.Printf("%s\n", stdErrScanner.Text())
		}
	}()

	err = cmd.Start()
	if err != nil {
		log.Fatal(os.Stderr, "Error starting Cmd", err)
	}

	err = cmd.Wait()
	// go generate command will fail when no generate command find.
	if err != nil {
		if err.Error() != "exit status 1" {
			fmt.Println(err)
			log.Fatal(err)
		}
	}
}

Add listening to the std out as well.


// +build OMIT

package main

import (
	"fmt"
	"sync"
	"time"
)

// SafeCounter is safe to use concurrently.
type SafeCounter struct {
	v   map[string]int
	mux sync.Mutex
}

// Inc increments the counter for the given key.
func (c *SafeCounter) Inc(key string) {
	c.mux.Lock()
	// Lock so only one goroutine at a time can access the map c.v.
	c.v[key]++
	c.mux.Unlock()
}

// Value returns the current value of the counter for the given key.
func (c *SafeCounter) Value(key string) int {
	c.mux.Lock()
	// Lock so only one goroutine at a time can access the map c.v.
	defer c.mux.Unlock()
	return c.v[key]
}

func main() {
	c := SafeCounter{v: make(map[string]int)}
	for i := 0; i < 1000; i++ {
		go c.Inc("somekey")
	}

	time.Sleep(time.Second)
	fmt.Println(c.Value("somekey"))
}

// +build OMIT

package main

import (
	"fmt"
	"sync"
	"time"
)

// SafeCounter is safe to use concurrently.
type SafeCounter struct {
	mu sync.Mutex
	v  map[string]int
}

// Inc increments the counter for the given key.
func (c *SafeCounter) Inc(key string) {
	c.mu.Lock()
	// Lock so only one goroutine at a time can access the map c.v.
	c.v[key]++
	c.mu.Unlock()
}

// Value returns the current value of the counter for the given key.
func (c *SafeCounter) Value(key string) int {
	c.mu.Lock()
	// Lock so only one goroutine at a time can access the map c.v.
	defer c.mu.Unlock()
	return c.v[key]
}

func main() {
	c := SafeCounter{v: make(map[string]int)}
	for i := 0; i < 1000; i++ {
		go c.Inc("somekey")
	}

	time.Sleep(time.Second)
	fmt.Println(c.Value("somekey"))
}

Rename mux -> mu to follow convention


package helpers

import (
	"html/template"

	"github.com/acsellers/multitemplate"
)

// Available helper modules "forms", "general", "link", "asset"
func LoadHelpers(modules ...string) {
	loadFuncs(coreFuncs)
	for _, module := range modules {
		switch module {
		case "all":
			loadFuncs(formTagFuncs)
			loadFuncs(selectTagFuncs)
			loadFuncs(generalFuncs)
			loadFuncs(linkFuncs)
			loadFuncs(assetFuncs)
		case "forms":
			loadFuncs(formTagFuncs)
			loadFuncs(selectTagFuncs)
		case "general":
			loadFuncs(generalFuncs)
		case "link":
			loadFuncs(linkFuncs)
		case "asset":
			loadFuncs(assetFuncs)
		}
	}
}

func loadFuncs(tf template.FuncMap) {
	for k, f := range tf {
		multitemplate.LoadedFuncs[k] = f
	}
}

package helpers

import (
	"html/template"

	"github.com/acsellers/multitemplate"
)

// Available helper modules "forms", "general", "link", "asset"
func LoadHelpers(modules ...string) {
	loadFuncs(coreFuncs)
	for _, module := range modules {
		switch module {
		case "all":
			loadFuncs(formTagFuncs)
			loadFuncs(selectTagFuncs)
			loadFuncs(generalFuncs)
			loadFuncs(linkFuncs)
			loadFuncs(assetFuncs)
		case "forms":
			loadFuncs(formTagFuncs)
			loadFuncs(selectTagFuncs)
		case "general":
			loadFuncs(generalFuncs)
		case "link":
			loadFuncs(linkFuncs)
		case "asset":
			loadFuncs(assetFuncs)
		}
	}
}

func GetHelpers(modules ...string) template.FuncMap {
	tf := template.FuncMap{}
	getFuncs(tf, coreFuncs)
	for _, module := range modules {
		switch module {
		case "all":
			getFuncs(tf, formTagFuncs)
			getFuncs(tf, selectTagFuncs)
			getFuncs(tf, generalFuncs)
			getFuncs(tf, linkFuncs)
			getFuncs(tf, assetFuncs)
		case "forms":
			getFuncs(tf, formTagFuncs)
			getFuncs(tf, selectTagFuncs)
		case "general":
			getFuncs(tf, generalFuncs)
		case "link":
			getFuncs(tf, linkFuncs)
		case "asset":
			getFuncs(tf, assetFuncs)
		}
	}
	return tf
}

func loadFuncs(tf template.FuncMap) {
	for k, f := range tf {
		multitemplate.LoadedFuncs[k] = f
	}
}

func getFuncs(host, source template.FuncMap) {
	for k, f := range source {
		host[k] = f
	}
}

Add new way to retrieve functions from helpers


package decorator

import (
	"time"

	sparta "github.com/mweagle/Sparta"
	gocf "github.com/mweagle/go-cloudformation"
	"github.com/sirupsen/logrus"
)

// LambdaVersioningDecorator returns a TemplateDecorator
// that is responsible for including a versioning resource
// with the given lambda function
func LambdaVersioningDecorator() sparta.TemplateDecoratorHookFunc {
	return func(serviceName string,
		lambdaResourceName string,
		lambdaResource gocf.LambdaFunction,
		resourceMetadata map[string]interface{},
		S3Bucket string,
		S3Key string,
		buildID string,
		template *gocf.Template,
		context map[string]interface{},
		logger *logrus.Logger) error {

		lambdaResName := sparta.CloudFormationResourceName("LambdaVersion",
			buildID,
			time.Now().UTC().String())
		versionResource := &gocf.LambdaVersion{
			FunctionName: gocf.GetAtt(lambdaResourceName, "Arn").String(),
		}
		lambdaVersionRes := template.AddResource(lambdaResName, versionResource)
		lambdaVersionRes.DeletionPolicy = "Retain"
		// That's it...
		return nil
	}
}

package decorator

import (
	"context"
	"time"

	sparta "github.com/mweagle/Sparta"
	gocf "github.com/mweagle/go-cloudformation"
	"github.com/sirupsen/logrus"
)

// LambdaVersioningDecorator returns a TemplateDecorator
// that is responsible for including a versioning resource
// with the given lambda function
func LambdaVersioningDecorator() sparta.TemplateDecoratorHookFunc {
	return func(ctx context.Context,
		serviceName string,
		lambdaResourceName string,
		lambdaResource gocf.LambdaFunction,
		resourceMetadata map[string]interface{},
		lambdaFunctionCode *gocf.LambdaFunctionCode,
		buildID string,
		template *gocf.Template,
		logger *logrus.Logger) (context.Context, error) {

		lambdaResName := sparta.CloudFormationResourceName("LambdaVersion",
			buildID,
			time.Now().UTC().String())
		versionResource := &gocf.LambdaVersion{
			FunctionName: gocf.GetAtt(lambdaResourceName, "Arn").String(),
		}
		lambdaVersionRes := template.AddResource(lambdaResName, versionResource)
		lambdaVersionRes.DeletionPolicy = "Retain"
		// That's it...
		return ctx, nil
	}
}

Update decorators to new signature


// +build f030x6

package tim

import (
	"unsafe"

	"stm32/hal/raw/mmap"
)

//emgo:const
var (
	// Advanced-control timers.
	TIM1 = (*Periph)(unsafe.Pointer(mmap.TIM1_BASE))

	// General-purpose timers.
	TIM3 = (*Periph)(unsafe.Pointer(mmap.TIM3_BASE))

	// General-purpose timers (1-channel).
	TIM14 = (*Periph)(unsafe.Pointer(mmap.TIM14_BASE))

	// General-purpose timers (1-channel with complementary output).
	TIM16 = (*Periph)(unsafe.Pointer(mmap.TIM16_BASE))
	TIM17 = (*Periph)(unsafe.Pointer(mmap.TIM17_BASE))
)

// +build f303xe

package tim

import (
	"unsafe"

	"stm32/hal/raw/mmap"
)

//emgo:const
var (
	// Advanced-control timers.
	TIM1  = (*Periph)(unsafe.Pointer(mmap.TIM1_BASE))
	TIM8  = (*Periph)(unsafe.Pointer(mmap.TIM8_BASE))
	TIM20 = (*Periph)(unsafe.Pointer(mmap.TIM20_BASE))

	// General-purpose timers.
	TIM2  = (*Periph)(unsafe.Pointer(mmap.TIM2_BASE)) // 32-bit
	TIM3  = (*Periph)(unsafe.Pointer(mmap.TIM3_BASE))
	TIM4  = (*Periph)(unsafe.Pointer(mmap.TIM4_BASE))

	// Basic timers.
	TIM6 = (*Periph)(unsafe.Pointer(mmap.TIM6_BASE))
	TIM7 = (*Periph)(unsafe.Pointer(mmap.TIM7_BASE))

	// General-purpose timers (1-channel).
	TIM16 = (*Periph)(unsafe.Pointer(mmap.TIM15_BASE))
	TIM17 = (*Periph)(unsafe.Pointer(mmap.TIM17_BASE))

	// General-purpose timers (2-channel).
	TIM15 = (*Periph)(unsafe.Pointer(mmap.TIM15_BASE))
)

Fix timer instances for F3.


package exporter

import (
	"net"
	"net/url"
	"time"

	"github.com/prometheus/common/log"
)

// UnixStatsReader reads uwsgi stats from specified unix socket.
type UnixStatsReader struct {
	filename string
}

func init() {
	StatsReaderCreators = append(StatsReaderCreators, newHTTPStatsReader)
}

func newUnixStatsReader(u *url.URL, uri string, timeout time.Duration) StatsReader {
	if u.Scheme != "unix" {
		return nil
	}

	return &UnixStatsReader{
		filename: u.Path,
	}
}

func (reader *UnixStatsReader) Read() (*UwsgiStats, error) {
	conn, err := net.Dial("unix", string(reader.filename))
	if err != nil {
		log.Errorf("Error while reading uwsgi stats from unix socket: %s", reader.filename)
		return nil, err
	}
	defer conn.Close()

	uwsgiStats, err := parseUwsgiStatsFromIO(conn)
	if err != nil {
		log.Errorf("Failed to unmarshal JSON: %s", err)
		return nil, err
	}
	return uwsgiStats, nil
}

package exporter

import (
	"net"
	"net/url"
	"time"

	"github.com/prometheus/common/log"
)

// UnixStatsReader reads uwsgi stats from specified unix socket.
type UnixStatsReader struct {
	filename string
}

func init() {
	StatsReaderCreators = append(StatsReaderCreators, newUnixStatsReader)
}

func newUnixStatsReader(u *url.URL, uri string, timeout time.Duration) StatsReader {
	if u.Scheme != "unix" {
		return nil
	}

	return &UnixStatsReader{
		filename: u.Path,
	}
}

func (reader *UnixStatsReader) Read() (*UwsgiStats, error) {
	conn, err := net.Dial("unix", string(reader.filename))
	if err != nil {
		log.Errorf("Error while reading uwsgi stats from unix socket: %s", reader.filename)
		return nil, err
	}
	defer conn.Close()

	uwsgiStats, err := parseUwsgiStatsFromIO(conn)
	if err != nil {
		log.Errorf("Failed to unmarshal JSON: %s", err)
		return nil, err
	}
	return uwsgiStats, nil
}

Fix wrong unix socket handler


package shadowfax

import (
	"crypto/rand"
	"io"

	"gopkg.in/basen.v1"
	"gopkg.in/errgo.v1"
)

// Nonce is a 24-byte number that should be used once per message.
type Nonce [24]byte

// DecodeNonce decodes a nonce from its Base58 string representation.
func DecodeNonce(s string) (*Nonce, error) {
	var nonce Nonce
	buf, err := basen.Base58.DecodeString(s)
	if err != nil {
		return nil, err
	}
	if len(buf) != 24 {
		return nil, errgo.Newf("invalid nonce length %q", buf)
	}
	copy(nonce[:], buf)
	return &nonce, nil
}

// Encode encodes the nonce to a Base58 string representation.
func (n Nonce) Encode() string {
	return basen.Base58.EncodeToString(n[:])
}

// NewNonce returns a new random nonce.
func NewNonce() (*Nonce, error) {
	n := new(Nonce)
	_, err := io.ReadFull(rand.Reader, n[:])
	if err != nil {
		return nil, errgo.Mask(err)
	}
	return n, nil
}

package shadowfax

import (
	"crypto/rand"
	"io"

	"gopkg.in/basen.v1"
	"gopkg.in/errgo.v1"
)

// Nonce is a 24-byte number that should be used once per message.
type Nonce [24]byte

// DecodeNonce decodes a nonce from its Base58 string representation.
func DecodeNonce(s string) (*Nonce, error) {
	var nonce Nonce
	buf, err := basen.Base58.DecodeString(s)
	if err != nil {
		return nil, err
	}
	copy(nonce[:], buf)
	return &nonce, nil
}

// Encode encodes the nonce to a Base58 string representation.
func (n Nonce) Encode() string {
	return basen.Base58.EncodeToString(n[:])
}

// NewNonce returns a new random nonce.
func NewNonce() (*Nonce, error) {
	n := new(Nonce)
	_, err := io.ReadFull(rand.Reader, n[:])
	if err != nil {
		return nil, errgo.Mask(err)
	}
	return n, nil
}

Remove length assertion, since leading zeroes are not encoded.


package main

import (
	"encoding/csv"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
)

func main() {
	var (
		truststore, csvURL string
		csvPEMPos          int
	)
	if len(os.Args) != 2 {
		log.Fatalf("usage: %s <mozilla|microsoft>", os.Args[0])
	}
	truststore = os.Args[1]
	switch truststore {
	case "mozilla":
		csvURL = "https://mozillacaprogram.secure.force.com/CA/IncludedCACertificateReportPEMCSV"
		csvPEMPos = 28
	case "microsoft":
		csvURL = "https://mozillacaprogram.secure.force.com/CA/apex/IncludedCACertificateReportForMSFTCSVPEM"
		csvPEMPos = 6
	}
	resp, err := http.Get(csvURL)
	if err != nil {
		log.Fatal(err)
	}
	r := csv.NewReader(resp.Body)
	defer resp.Body.Close()
	records, err := r.ReadAll()
	if err != nil {
		log.Fatal(err)
	}
	for _, record := range records {
		if len(record) < csvPEMPos+1 {
			continue
		}
		fmt.Println(strings.Trim(record[csvPEMPos], `'`))
	}
}

package main

import (
	"encoding/csv"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
)

func main() {
	var (
		truststore, csvURL string
		csvPEMPos          int
	)
	if len(os.Args) != 2 {
		log.Fatalf("usage: %s <mozilla|microsoft>", os.Args[0])
	}
	truststore = os.Args[1]
	switch truststore {
	case "mozilla":
		csvURL = "https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReportPEMCSV"
		csvPEMPos = 28
	case "microsoft":
		csvURL = "https://ccadb-public.secure.force.com/microsoft/IncludedCACertificateReportForMSFTCSVPEM"
		csvPEMPos = 6
	}
	resp, err := http.Get(csvURL)
	if err != nil {
		log.Fatal(err)
	}
	r := csv.NewReader(resp.Body)
	defer resp.Body.Close()
	records, err := r.ReadAll()
	if err != nil {
		log.Fatal(err)
	}
	for _, record := range records {
		if len(record) < csvPEMPos+1 {
			continue
		}
		fmt.Println(strings.Trim(record[csvPEMPos], `'`))
	}
}

Fix CCADB URLs in truststore retriever


// Copyright (C) 2018 Google Inc.
//
// 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.

// +build windows

package linker

import "syscall"

// ProcAddress returns the address of the function with the given name.
func ProcAddress(name string) uintptr {
	proc, err := syscall.GetProcAddress(0, name)
	if err != nil {
		return nil
	}
	return proc
}

// Copyright (C) 2018 Google Inc.
//
// 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.

// +build windows

package linker

import "syscall"

// ProcAddress returns the address of the function with the given name.
func ProcAddress(name string) uintptr {
	proc, err := syscall.GetProcAddress(0, name)
	if err != nil {
		return 0
	}
	return proc
}

Fix build failure on windows.


package i18n

import (
	"net/http"

	"golang.org/x/text/language"
)

// A Parser is a funcion that returns a list of accepted languages, most preferred first.
type Parser func(*http.Request) []language.Tag

// ParseAcceptLanguage parses the Accept-Language header.
func ParseAcceptLanguage(r *http.Request) []language.Tag {
	t, _, _ := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
	return t
}

// ParseFormValue parses the "locale" form value.
func ParseFormValue(r *http.Request) []language.Tag {
	t, _ := language.Parse(r.FormValue("locale"))
	return []language.Tag{t}
}

// TODO: Parsers for location, GeoIP, subdomain, TLD, request path.

package i18n

import (
	"net/http"

	"golang.org/x/text/language"
)

// A Parser is a funcion that returns a list of accepted languages, most preferred first.
type Parser func(*http.Request) []language.Tag

// ParseAcceptLanguage parses the Accept-Language header.
func ParseAcceptLanguage(r *http.Request) []language.Tag {
	t, _, err := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
	if err != nil {
		return nil
	}
	return t
}

// ParseCookie parses the "locale" cookie.
func ParseCookie(r *http.Request) []language.Tag {
	c, err := r.Cookie("locale")
	if err != nil {
		return nil
	}
	t, err := language.Parse(c.Value)
	if err != nil {
		return nil
	}
	return []language.Tag{t}
}

// ParseFormValue parses the "locale" form value.
func ParseFormValue(r *http.Request) []language.Tag {
	t, err := language.Parse(r.FormValue("locale"))
	if err != nil {
		return nil
	}
	return []language.Tag{t}
}

// TODO: Parsers for location, GeoIP, subdomain, TLD, request path.

Add ParseCookie and handle parsing errors


package tools

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"strings"
	"unicode"
	"unicode/utf8"
)

func ComputeHmac256(message string, secret string) string {
	key := []byte(secret)
	h := hmac.New(sha256.New, key)
	h.Write([]byte(message))
	return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

func Capitalize(s string) string {
	if s == "" {
		return ""
	}
	r, n := utf8.DecodeRuneInString(s)
	return string(unicode.ToUpper(r)) + s[n:]
}

func JsonToGolang(in *string) (out string) {
	res := strings.Split(*in, "_")
	out = ""
	for _, s := range res {
		out += Capitalize(s)
	}
	return out
}

func CaseInsensitiveContains(s, substr string) bool {
	s, substr = strings.ToUpper(s), strings.ToUpper(substr)
	return strings.Contains(s, substr)
}

Add new case insensitive string contains


package graph

type Vertex struct{}

type Edge struct {
	start Vertex
	end   Vertex
}

type Graph struct{}

func New() *Graph {
	return &Graph{}
}

func (g *Graph) Edges(v *Vertex) []*Edge {
	return nil
}

package graph

type Vertex struct{}

type Edge struct {
	start Vertex
	end   Vertex
}

type Graph struct {
	// All vertexes this Graph has
	vertexes *vertexSet
	// Edges per vertex
	edges map[*Vertex][]*Edge
}

func New() *Graph {
	return &Graph{
		vertexes: NewVertexSet(100),
		edges:    make(map[*Vertex][]*Edge, 100),
	}
}

func (g *Graph) Edges(v *Vertex) []*Edge {
	if edges, ok := g.edges[v]; ok {
		return edges
	}
	return nil
}

Add vertexSet and implement Edges method


package tasks

import (
	"errors"
	"reflect"
)

var (
	// ErrTaskMustBeFunc ...
	ErrTaskMustBeFunc = errors.New("Task must be a func type")
	// ErrTaskReturnsNoValue ...
	ErrTaskReturnsNoValue = errors.New("Taks must return at least a single value")
	// ErrLastReturnValueMustBeError ..
	ErrLastReturnValueMustBeError = errors.New("Last return value of a task must be error")
)

// ValidateTask validates task function using reflection and makes sure
// it has a proper signature. Functions used as tasks must return at least a
// single value and the last return type must be error
func ValidateTask(task interface{}) error {
	v := reflect.ValueOf(task)
	t := v.Type()

	// Task must be a function
	if t.Kind() != reflect.Func {
		return ErrTaskMustBeFunc
	}

	// Task must return at least a single value
	if t.NumOut() < 1 {
		return ErrTaskReturnsNoValue
	}

	// Last return value must be error
	lastReturnType := t.Out(t.NumOut() - 1)
	errorInterface := reflect.TypeOf((*error)(nil)).Elem()
	if !lastReturnType.Implements(errorInterface) {
		return ErrLastReturnValueMustBeError
	}

	return nil
}

package tasks

import (
	"errors"
	"reflect"
)

var (
	// ErrTaskMustBeFunc ...
	ErrTaskMustBeFunc = errors.New("Task must be a func type")
	// ErrTaskReturnsNoValue ...
	ErrTaskReturnsNoValue = errors.New("Task must return at least a single value")
	// ErrLastReturnValueMustBeError ..
	ErrLastReturnValueMustBeError = errors.New("Last return value of a task must be error")
)

// ValidateTask validates task function using reflection and makes sure
// it has a proper signature. Functions used as tasks must return at least a
// single value and the last return type must be error
func ValidateTask(task interface{}) error {
	v := reflect.ValueOf(task)
	t := v.Type()

	// Task must be a function
	if t.Kind() != reflect.Func {
		return ErrTaskMustBeFunc
	}

	// Task must return at least a single value
	if t.NumOut() < 1 {
		return ErrTaskReturnsNoValue
	}

	// Last return value must be error
	lastReturnType := t.Out(t.NumOut() - 1)
	errorInterface := reflect.TypeOf((*error)(nil)).Elem()
	if !lastReturnType.Implements(errorInterface) {
		return ErrLastReturnValueMustBeError
	}

	return nil
}

Fix typo in error message


package cloudwatch

import (
	"os"
	"testing"
)

func TestDefaultSessionConfig(t *testing.T) {
	cases := []struct {
		expected  string
		export    bool
		exportVar string
		exportVal string
	}{
		{
			expected:  "us-east-1",
			export:    false,
			exportVar: "",
			exportVal: "",
		},
		{
			expected:  "ap-southeast-1",
			export:    true,
			exportVar: "AWS_DEFAULT_REGION",
			exportVal: "ap-southeast-1",
		},
		{
			expected:  "us-west-2",
			export:    true,
			exportVar: "AWS_REGION",
			exportVal: "us-west-2",
		},
	}

	for _, c := range cases {
		if c.export == true {
			os.Setenv(c.exportVar, c.exportVal)
		}

		config := DefaultSessionConfig()

		if *config.Region != c.expected {
			t.Errorf("expected %q to be %q", *config.Region, c.expected)
		}

		if c.export == true {
			os.Unsetenv(c.exportVar)
		}
	}
}

package cloudwatch

import (
	"os"
	"testing"
)

func TestDefaultSessionConfig(t *testing.T) {
	// Cleanup before the test
	os.Unsetenv("AWS_DEFAULT_REGION")
	os.Unsetenv("AWS_REGION")

	cases := []struct {
		expected  string
		export    bool
		exportVar string
		exportVal string
	}{
		{
			expected:  "us-east-1",
			export:    false,
			exportVar: "",
			exportVal: "",
		},
		{
			expected:  "ap-southeast-2",
			export:    true,
			exportVar: "AWS_DEFAULT_REGION",
			exportVal: "ap-southeast-2",
		},
		{
			expected:  "us-west-2",
			export:    true,
			exportVar: "AWS_REGION",
			exportVal: "us-west-2",
		},
	}

	for _, c := range cases {
		if c.export == true {
			os.Setenv(c.exportVar, c.exportVal)
		}

		config := DefaultSessionConfig()

		if *config.Region != c.expected {
			t.Errorf("expected %q to be %q", *config.Region, c.expected)
		}

		if c.export == true {
			os.Unsetenv(c.exportVar)
		}
	}
}

Update the client test to clean up before tests


package controllers

import (
	"github.com/jgraham909/revmgo"
	"github.com/robfig/revel"
	"html/template"
)

func init() {
	revel.TemplateFuncs["add"] = func(a, b int) int { return a + b }
	revel.TemplateFuncs["get"] = func(a []string, b int) string { return a[b] }
	revel.TemplateFuncs["html"] = func(s string) template.HTML { return template.HTML(s) }
	revel.TemplateFuncs["contains"] = func(a string, b []string) bool {
		for i := range b {
			if a == b[i] {
				return true
			}
		}
		return false
	}
	revmgo.ControllerInit()
}

package controllers

import (
	"github.com/jgraham909/revmgo"
	"github.com/robfig/revel"
	"html/template"
	"strings"
)

func init() {
	revel.TemplateFuncs["add"] = func(a, b int) int { return a + b }
	revel.TemplateFuncs["get"] = func(a []string, b int) string { return a[b] }
	revel.TemplateFuncs["html"] = func(s string) template.HTML { return template.HTML(s) }
	revel.TemplateFuncs["clean"] = func(s string) string {
		s = strings.Replace(s, `<strong>`, ``, -1)
		s = strings.Replace(s, `</strong>`, ``, -1)
		return s
	}
	revel.TemplateFuncs["contains"] = func(a string, b []string) bool {
		for i := range b {
			if a == b[i] {
				return true
			}
		}
		return false
	}
	revmgo.ControllerInit()
}

Add html cleaning function as workaround


package channels

type ThermoStatActuator interface {
	SetTemperatureSetPoint(float64) error
}

type ThermoStatState struct {
	Target *float64 `json:"target,omitempty"`
}

type ThermoStatChannel struct {
	baseChannel
	actuator ThermoStatActuator
}

func NewThermoStatChannel(actuator ThermoStatActuator) *ThermoStatChannel {
	return &ThermoStatChannel{
		baseChannel: baseChannel{protocol: "thermostat"},
		actuator:    actuator,
	}
}

func (c *ThermoStatChannel) Set(state *ThermoStatState) error {
	if state != nil && state.Target != nil {
		return c.actuator.SetTemperatureSetPoint(*state.Target)
	} else {
		return nil
	}
}

func (c *ThermoStatChannel) SendState(state *ThermoStatState) error {
	return c.SendEvent("state", state)
}

package channels

type ThermoStatActuator interface {
	SetTemperatureSetPoint(float64) error
}

type ThermoStatChannel struct {
	baseChannel
	actuator ThermoStatActuator
}

func NewThermoStatChannel(actuator ThermoStatActuator) *ThermoStatChannel {
	return &ThermoStatChannel{
		baseChannel: baseChannel{protocol: "thermostat"},
		actuator:    actuator,
	}
}

func (c *ThermoStatChannel) Set(state float64) error {
	return c.actuator.SetTemperatureSetPoint(state)
}

func (c *ThermoStatChannel) SendState(state float64) error {
	return c.SendEvent("state", state)
}

Make thermostat state just a float64


package uuid_test

import (
	"fmt"

	"github.com/northbright/uuid"
)

func ExampleNew() {
	for i := 0; i < 5; i++ {
		uuid, _ := uuid.New()
		fmt.Printf("%v\n", uuid)
	}
	// Output:
}

package uuid_test

import (
	"log"

	"github.com/northbright/uuid"
)

func ExampleNew() {
	for i := 0; i < 5; i++ {
		uuid, _ := uuid.New()
		log.Printf("%v", uuid)
	}
	// Output:
}

Replace fmt with log to fix test fail


package stripe

import (
	"testing"

	assert "github.com/stretchr/testify/require"
	"github.com/stripe/stripe-go/form"
)

func TestSourceObjectParams_AppendTo(t *testing.T) {
	// Test to make sure that TypeData makes it to the root object level of
	// encoding
	{
		params := &SourceObjectParams{
			TypeData: map[string]string{
				"foo": "bar",
			},
		}
		body := &form.Values{}
		form.AppendTo(body, params)
		t.Logf("body = %+v", body)
		assert.Equal(t, []string{"bar"}, body.Get("foo"))
	}
}

package stripe

import (
	"testing"

	assert "github.com/stretchr/testify/require"
	"github.com/stripe/stripe-go/form"
)

func TestSourceObjectParams_AppendTo(t *testing.T) {
	// Test to make sure that TypeData makes it to the root object level of
	// encoding
	{
		params := &SourceObjectParams{
			Type: "source_type",
			TypeData: map[string]string{
				"foo": "bar",
			},
		}
		body := &form.Values{}
		form.AppendTo(body, params)
		t.Logf("body = %+v", body)
		assert.Equal(t, []string{"bar"}, body.Get("source_type[foo]"))
	}
}

Fix source test to properly verify TypeData encoding


package river

import "github.com/synapse-garden/sg-proto/store"

// Survey is a survey request constant.
type Survey []byte

// Response is a response request constant (may be suffixed with an ID.)
type Response []byte

var (
	// Byte request / response constants.
	HUP     = Survey("HUP")
	OK      = Response("OK")
	UNKNOWN = Response("IDK")

	// RiverBucket stores Rivers and their users.  Buckets in RiverBucket
	// correspond to Streams from StreamBucket by ID, and every River ID in
	// the bucket corresponds to a connected River.
	RiverBucket = store.Bucket("rivers")

	// HangupBucket is where Respondents are stored.  Pass this to
	// NewSurvey as the first Bucket argument for most Surveys.
	HangupBucket = store.Bucket("hangups")
)

package river

import "github.com/synapse-garden/sg-proto/store"

// Survey is a survey request constant.
type Survey []byte

// Response is a response request constant (may be suffixed with an ID.)
type Response []byte

var (
	// Byte request / response constants.
	HUP     = Survey("HUP")
	OK      = Response("OK")
	UNKNOWN = Response("IDK")

	// RiverBucket stores Rivers and their users.  Buckets in RiverBucket
	// correspond to Streams from StreamBucket by ID, and every River ID in
	// the bucket corresponds to a connected River.
	RiverBucket = store.Bucket("rivers")

	// ResponderBucket is where Responders are kept, for hangup.
	ResponderBucket = store.Bucket("responders")

	// HangupBucket is where Respondents are stored.  Pass this to
	// NewSurvey as the first Bucket argument for most Surveys.
	HangupBucket = store.Bucket("hangups")
)

Add rivers.ResponderBucket for responder hangups


// +build appengine

package main

import (
	"net/http"
	"sync"
	"time"

	_ "gnd.la/admin"                 // required for make-assets command
	_ "gnd.la/blobstore/driver/gcs"  // enable Google Could Storage blobstore driver
	_ "gnd.la/cache/driver/memcache" // enable memcached cache driver
	// Uncomment the following line to use Google Cloud SQL
	//_ "gnd.la/orm/driver/mysql"
)

var (
	wg sync.WaitGroup
)

func _app_engine_app_init() {
	// Make sure App is initialized before the rest
	// of this function runs.
	for App == nil {
		time.Sleep(5 * time.Millisecond)
	}
	if err := App.Prepare(); err != nil {
		panic(err)
	}
	http.Handle("/", App)
	wg.Done()
}

// Only executed on the development server. Required for
// precompiling assets.
func main() {
	wg.Wait()
}

func init() {
	wg.Add(1)
	go _app_engine_app_init()
}

// +build appengine

package main

import (
	"net/http"
	"sync"
	"time"

	_ "gnd.la/blobstore/driver/gcs"  // enable Google Could Storage blobstore driver
	_ "gnd.la/cache/driver/memcache" // enable memcached cache driver
	_ "gnd.la/commands"              // required for make-assets command
	// Uncomment the following line to use Google Cloud SQL
	//_ "gnd.la/orm/driver/mysql"
)

var (
	wg sync.WaitGroup
)

func _app_engine_app_init() {
	// Make sure App is initialized before the rest
	// of this function runs.
	for App == nil {
		time.Sleep(5 * time.Millisecond)
	}
	if err := App.Prepare(); err != nil {
		panic(err)
	}
	http.Handle("/", App)
	wg.Done()
}

// Only executed on the development server. Required for
// precompiling assets.
func main() {
	wg.Wait()
}

func init() {
	wg.Add(1)
	go _app_engine_app_init()
}

Update import in GAE template


package main

import (
	"fmt"
	"testing"
)

func TestTax2011QuickDeduction(t *testing.T) {
	fmt.Println("Year 2011:")

	afterTax, qdWithTax := tax2011QuickDeduction(0)
	fmt.Printf("Atfer Tax:%v\n", afterTax)
	for k, v := range qdWithTax {
		if k > 0 {
			fmt.Printf("%v: %v\n", k/12.0, v)
		}
	}
	afterTax, qdWithoutTax := tax2011QuickDeduction(1)
	fmt.Printf("Atfer Tax:%v\n", afterTax)
	for k, v := range qdWithoutTax {
		if k > 0 {
			fmt.Printf("%v: %v\n", k/12.0, v)

		}
	}
}

func TestTax2018QuickDeduction(t *testing.T) {
	tqd := tax2018QuickDeduction()
	fmt.Println("Year 2018:")
	for k, v := range tqd {
		if k > 0 {
			fmt.Printf("%v: %v\n", k/12, v/12)
		}
	}
}

package main

import (
	"fmt"
	"testing"
)

func TestTax2011QuickDeduction(t *testing.T) {
	fmt.Println("Year 2011:")
	rate := tax2011Rate()
	beforeTax := []float64{
		18000,
		54000,
		108000,
		420000,
		660000,
		960000,
		-1,
	}
	afterTax, qdWithTax := quickDeduction(0, beforeTax, rate)
	fmt.Printf("Atfer Tax:%v\n", afterTax)
	for k, v := range qdWithTax {
		if k > 0 {
			fmt.Printf("%v: %v\n", k/12.0, v)
		}
	}
	afterTax, qdWithoutTax := quickDeduction(1, beforeTax, rate)
	fmt.Printf("Atfer Tax:%v\n", afterTax)
	for k, v := range qdWithoutTax {
		if k > 0 {
			fmt.Printf("%v: %v\n", k/12.0, v)

		}
	}
}

Update individual income tax test case


package main

import (
	"log"
	"fmt"
	"os"
	"net/http"
	"github.com/julienschmidt/httprouter"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	fmt.Fprintln(w, "HTTP working over a socket!")
}

func Test(w http.ResponseWriter, r * http.Request, params httprouter.Params) {
	fmt.Fprintln(w, params.ByName("string"))
}

func main() {
	router := httprouter.New()
	router.GET("/", Index)
	router.GET("/test/:string", Test)

	log.Fatal(ListenAndServeUnix("/tmp/dokku-api.sock", os.FileMode(0666), router))
}

package main

import (
	"log"
	"fmt"
	"os"
	"net/http"
	"github.com/julienschmidt/httprouter"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	fmt.Println("Index!")
	fmt.Fprintln(w, "HTTP working over a socket!")
}

func Test(w http.ResponseWriter, r * http.Request, params httprouter.Params) {
	fmt.Fprintln(w, params.ByName("string"))
}

func main() {
	router := httprouter.New()
	router.GET("/", Index)
	router.GET("/test/:string", Test)

	if _, err := os.Stat("/tmp/dokku-api/api.sock"); os.IsNotExist(err) {
		os.MkdirAll("/tmp/dokku-api", 0777)
	}

	log.Fatal(ListenAndServeUnix("/tmp/dokku-api/api.sock", os.FileMode(0666), router))
}

Put socket in its own directory inside /tmp


package main

import "net/http"
import "os"
import "strings"
import "fmt"

func main() {
    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }
    http.HandleFunc("/", IpResponse)
    http.ListenAndServe(":" + port, nil)
}

func IpResponse(response http.ResponseWriter, request *http.Request) {
    ip := request.Header.Get("X-Forwarded-For")
    if ip == "" {
        ip = request.RemoteAddr
    }

    colonPosition := strings.Index(ip, ":")
    if colonPosition > -1 {
        ip = ip[:colonPosition]
    }

    commaPosition := strings.Index(ip, ",")
    if commaPosition > -1 {
        ip = ip[:commaPosition]
    }

    fmt.Println(ip)
    response.Write([]byte(ip))
}

package main

import "net/http"
import "os"
import "strings"
import "fmt"

func main() {
    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }
    http.HandleFunc("/", IpResponse)
    http.ListenAndServe(":" + port, nil)
}

func IpResponse(response http.ResponseWriter, request *http.Request) {
    ip := request.Header.Get("X-Forwarded-For")
    if ip == "" {
        ip = request.RemoteAddr
    }

    colonPosition := strings.LastIndex(ip, ":")
    if colonPosition > -1 {
        ip = ip[:colonPosition]
    }

    commaPosition := strings.Index(ip, ",")
    if commaPosition > -1 {
        ip = ip[:commaPosition]
    }

    fmt.Println(ip)
    response.Write([]byte(ip))
}

Add support for ipv6 (which has colons in the IP address)


package datacenter

type GetDCReq struct {
	DataCenter string `valid:"required" URIParam:"yes"`
}

type GetDCRes struct {
	SupportsPremiumStorage     bool
	SupportsSharedLoadBalancer bool
	DeployableNetworks         []DeployableNetwork
	Templates                  []Template
}

type DeployableNetwork struct {
	Name      string
	NetworkId string
	Type      string
	AccountId string
}

type Template struct {
	Name               string
	Description        string
	StorageSizeGB      int64
	Capabilities       []string
	ReservedDrivePaths []string
	DrivePathLength    int64
}

package datacenter

type GetDCReq struct {
	DataCenter string `valid:"required" URIParam:"yes"`
}

type GetDCRes struct {
	SupportsPremiumStorage     bool
	SupportsSharedLoadBalancer bool
	SupportsBareMetalServers   bool
	DeployableNetworks         []DeployableNetwork
	Templates                  []Template
	ImportableOsTypes          []ImportableOSType
}

type DeployableNetwork struct {
	Name      string
	NetworkId string
	Type      string
	AccountId string
}

type Template struct {
	Name               string
	Description        string
	StorageSizeGB      int64
	Capabilities       []string
	ReservedDrivePaths []string
	DrivePathLength    int64
}

type ImportableOSType struct {
	Id                 int64
	Description        string
	LabProductCode     string
	PremiumProductCode string
	Type               string
}

Add some newly appeared props of the deployment capabilities response


package main

import (
	"os"

	"github.com/facebookgo/grace/gracehttp"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

func main() {
	e := echo.New()

	e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
		Skipper: middleware.DefaultSkipper,
		Format:  "{\"time\"\":\"${time_rfc3339_nano}\", \"remote_ip\":\"${remote_ip}\", \"host\":\"${host}\", \"method\":\"${method}\", \"uri\":\"${uri}\", \"status\":${status}, latency:${latency}, \"latency_human\":\"${latency_human}\", \"bytes_in\":${bytes_in}, \"bytes_out\":${bytes_out}}\n",
		Output:  os.Stdout,
	}))
	e.Use(middleware.Recover())

	dbh := DBHandler{}
	err := dbh.initDB()
	if err != nil {
		e.Logger.Panic(err)
	}
	e.Logger.Printf("DB handler initiated")

	e.File("/favicon.ico", "images/favicon.ico")

	e.GET("/indicators", dbh.getIndicators)
	e.GET("/health/:indicator/github.com/:owner/:repo", dbh.getHealth)
	e.Logger.Printf("%d routes created: %v", len(e.Routes()), e.Routes())

	e.Server.Addr = ":8080"

	e.Logger.Fatal(gracehttp.Serve(e.Server))
}

package main

import (
	"os"

	"github.com/facebookgo/grace/gracehttp"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

func main() {
	e := echo.New()

	e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
		Skipper: middleware.DefaultSkipper,
		Format:  "{\"time\":\"${time_rfc3339_nano}\", \"remote_ip\":\"${remote_ip}\", \"host\":\"${host}\", \"method\":\"${method}\", \"uri\":\"${uri}\", \"status\":${status}, latency:${latency}, \"latency_human\":\"${latency_human}\", \"bytes_in\":${bytes_in}, \"bytes_out\":${bytes_out}}\n",
		Output:  os.Stdout,
	}))
	e.Use(middleware.Recover())

	dbh := DBHandler{}
	err := dbh.initDB()
	if err != nil {
		e.Logger.Panic(err)
	}
	e.Logger.Printf("DB handler initiated")

	e.File("/favicon.ico", "images/favicon.ico")

	e.GET("/indicators", dbh.getIndicators)
	e.GET("/health/:indicator/github.com/:owner/:repo", dbh.getHealth)
	e.Logger.Printf("%d routes created: %v", len(e.Routes()), e.Routes())

	e.Server.Addr = ":8080"

	e.Logger.Fatal(gracehttp.Serve(e.Server))
}

Remove extra " in logger


// Cozy Cloud is a personal platform as a service with a focus on data.
// Cozy Cloud can be seen as 4 layers, from inside to outside:
//
// 1. A place to keep your personal data
//
// 2. A core API to handle the data
//
// 3. Your web apps, and also the mobile & desktop clients
//
// 4. A coherent User Experience
//
// It's also a set of values: Simple, Versatile, Yours. These values mean a lot
// for Cozy Cloud in all aspects. From an architectural point, it declines to:
//
// - Simple to deploy and understand, not built as a galaxy of optimized
// microservices managed by kubernetes that only experts can debug.
//
// - Versatile, can be hosted on a Raspberry Pi for geeks to massive scale on
// multiple servers by specialized hosting. Users can install apps.
//
// - Yours, you own your data and you control it. If you want to take back your
// data to go elsewhere, you can.
package main

import (
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/cozy/cozy-stack/cmd"
)

func main() {
	if err := cmd.RootCmd.Execute(); err != nil {
		log.Errorf(err.Error())
		os.Exit(1)
	}
}

// Cozy Cloud is a personal platform as a service with a focus on data.
// Cozy Cloud can be seen as 4 layers, from inside to outside:
//
// 1. A place to keep your personal data
//
// 2. A core API to handle the data
//
// 3. Your web apps, and also the mobile & desktop clients
//
// 4. A coherent User Experience
//
// It's also a set of values: Simple, Versatile, Yours. These values mean a lot
// for Cozy Cloud in all aspects. From an architectural point, it declines to:
//
// - Simple to deploy and understand, not built as a galaxy of optimized
// microservices managed by kubernetes that only experts can debug.
//
// - Versatile, can be hosted on a Raspberry Pi for geeks to massive scale on
// multiple servers by specialized hosting. Users can install apps.
//
// - Yours, you own your data and you control it. If you want to take back your
// data to go elsewhere, you can.
package main

import (
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/cozy/cozy-stack/cmd"
)

func main() {
	if err := cmd.RootCmd.Execute(); err != nil {
		log.Error(err.Error())
		os.Exit(1)
	}
}

Use Error instead of Errorf


package main

func main() {
	ci, err := apiConn.allCommits()

	if err != nil {
		panic(err)
	}

	sortedMsg, _ := sortedChangeLogMessages(ci)

	//fmt.Printf("Sorted messages:\n%+v\n", sortedMsg)

	err = generateChangeLogHTML(sortedMsg, "ChangeLog.html")

	if err != nil {
		panic(err)
	}
}

package main

import "flag"

func init() {
	flag.StringVar(&configInfo.ToSha, "ToSha", configInfo.ToSha, "Set commit hash up to which the change log should be generated")
}

func main() {
	flag.Parse()

	ci, err := apiConn.allCommits()

	if err != nil {
		panic(err)
	}

	sortedMsg, _ := sortedChangeLogMessages(ci)

	err = generateChangeLogHTML(sortedMsg, "ChangeLog.html")

	if err != nil {
		panic(err)
	}
}

Enable to set the ToSha hash as a command line option.


package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"strconv"

	"github.com/rtwire/mock/service"
)

var (
	port = flag.Int("port", 8085, "service port number")
)

func main() {
	flag.Parse()

	url := fmt.Sprintf("http://localhost:%d/v1/mainnet/", *port)
	log.Printf("RTWire service running at %s.", url)

	addr := ":" + strconv.Itoa(*port)
	log.Fatal(http.ListenAndServe(addr, service.New()))
}

package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"

	"github.com/rtwire/mock/service"
)

var (
	addr = flag.String("addr", ":8085", "service address")
)

func main() {
	flag.Parse()

	url := fmt.Sprintf("http://%s/v1/mainnet/", *addr)
	log.Printf("RTWire service running at %s.", url)

	log.Fatal(http.ListenAndServe(*addr, service.New()))
}

Allow mock to use user specified interface.


package bitbucket

import (
	"code.cloudfoundry.org/lager"
	"github.com/concourse/atc/auth/verifier"
	"net/http"
)

type RepositoryVerifier struct {
	repositories    []RepositoryConfig
	bitbucketClient Client
}

func NewRepositoryVerifier(repositories []RepositoryConfig, bitbucketClient Client) verifier.Verifier {
	return RepositoryVerifier{
		repositories:    repositories,
		bitbucketClient: bitbucketClient,
	}
}

func (verifier RepositoryVerifier) Verify(logger lager.Logger, httpClient *http.Client) (bool, error) {
	logger.Info("validating-repositories", lager.Data{
		"want": verifier.repositories,
	})
	for _, repository := range verifier.repositories {
		accessable, err := verifier.bitbucketClient.Repository(httpClient, repository.OwnerName, repository.RepositoryName)
		if err != nil {
			logger.Error("failed-to-get-repository", err, lager.Data{
				"repository": repository,
			})
			return false, err
		}

		if accessable {
			logger.Info("validated-repository", lager.Data{
				"have": repository,
				"want": verifier.repositories,
			})
			return true, nil
		}
	}

	logger.Info("not-validated-repositores", lager.Data{
		"want": verifier.repositories,
	})

	return false, nil
}

package bitbucket

import (
	"code.cloudfoundry.org/lager"
	"github.com/concourse/atc/auth/verifier"
	"net/http"
)

type RepositoryVerifier struct {
	repositories    []RepositoryConfig
	bitbucketClient Client
}

func NewRepositoryVerifier(repositories []RepositoryConfig, bitbucketClient Client) verifier.Verifier {
	return RepositoryVerifier{
		repositories:    repositories,
		bitbucketClient: bitbucketClient,
	}
}

func (verifier RepositoryVerifier) Verify(logger lager.Logger, httpClient *http.Client) (bool, error) {
	for _, repository := range verifier.repositories {
		accessable, err := verifier.bitbucketClient.Repository(httpClient, repository.OwnerName, repository.RepositoryName)
		if err != nil {
			logger.Error("failed-to-get-repository", err, lager.Data{
				"repository": repository,
			})
			return false, err
		}

		if accessable {
			return true, nil
		}
	}

	logger.Info("not-validated-repositores", lager.Data{
		"want": verifier.repositories,
	})

	return false, nil
}

Remove debug logs that were used during development


package gocaa

import (
	"fmt"
	"net/url"
)

type HTTPError struct {
	StatusCode int
	Url        *url.URL
}

func (e HTTPError) Error() string {
	return fmt.Sprintf("%i on %s", e.StatusCode, e.Url.String())
}

type InvalidImageSizeError struct {
	Entitytype string
	Size       int
}

func (e InvalidImageSizeError) Error() string {
	return fmt.Sprintf("%s doesn't support image size %i", e.Entitytype, e.Size)
}

package gocaa

import (
	"fmt"
	"net/url"
)

type HTTPError struct {
	StatusCode int
	Url        *url.URL
}

func (e HTTPError) Error() string {
	return fmt.Sprintf("%d on %s", e.StatusCode, e.URL.String())
}

type InvalidImageSizeError struct {
	Entitytype string
	Size       int
}

func (e InvalidImageSizeError) Error() string {
	return fmt.Sprintf("%s doesn't support image size %d", e.Entitytype, e.Size)
}

Use the correct identifier in Sprintf calls


Test complex polygons and nonsensical nested boxes


// gogl provides a framework for representing and working with graphs.
package gogl

// Constants defining graph capabilities and behaviors.
const (
  E_DIRECTED, EM_DIRECTED = 1 << iota, 1 << iota - 1
  E_UNDIRECTED, EM_UNDIRECTED
  E_WEIGHTED, EM_WEIGHTED
  E_TYPED, EM_TYPED
  E_SIGNED, EM_SIGNED
  E_LOOPS, EM_LOOPS
  E_MULTIGRAPH, EM_MULTIGRAPH
)

type Vertex interface{}

type Graph interface {
	EachVertex(f func(vertex Vertex))
	EachEdge(f func(source Vertex, target Vertex))
	EachAdjacent(vertex Vertex, f func(adjacent Vertex))
	HasVertex(vertex Vertex) bool
	GetSubgraph([]Vertex) Graph
}

type MutableGraph interface {
	Graph
	AddVertex(v interface{}) bool
	RemoveVertex(v interface{}) bool
}

type DirectedGraph interface {
	Graph
	Transpose() DirectedGraph
	IsAcyclic() bool
	GetCycles() [][]interface{}
}

type MutableDirectedGraph interface {
	MutableGraph
	DirectedGraph
	addDirectedEdge(source interface{}, target interface{}) bool
	removeDirectedEdge(source interface{}, target interface{}) bool
}

type Edge interface {
	Tail() Vertex
	Head() Vertex
}

// gogl provides a framework for representing and working with graphs.
package gogl

// Constants defining graph capabilities and behaviors.
const (
  E_DIRECTED, EM_DIRECTED = 1 << iota, 1 << iota - 1
  E_UNDIRECTED, EM_UNDIRECTED
  E_WEIGHTED, EM_WEIGHTED
  E_TYPED, EM_TYPED
  E_SIGNED, EM_SIGNED
  E_LOOPS, EM_LOOPS
  E_MULTIGRAPH, EM_MULTIGRAPH
)

type Vertex interface{}

type Edge struct {
	Tail, Head Vertex
}

type Graph interface {
	EachVertex(f func(vertex Vertex))
	EachEdge(f func(edge Edge))
	EachAdjacent(vertex Vertex, f func(adjacent Vertex))
	HasVertex(vertex Vertex) bool
	Order() uint
	Size() uint
	GetSubgraph([]Vertex) Graph
}

type MutableGraph interface {
	Graph
	AddVertex(v interface{}) bool
	RemoveVertex(v interface{}) bool
}

type DirectedGraph interface {
	Graph
	Transpose() DirectedGraph
	IsAcyclic() bool
	GetCycles() [][]interface{}
}

type MutableDirectedGraph interface {
	MutableGraph
	DirectedGraph
	addDirectedEdge(source interface{}, target interface{}) bool
	removeDirectedEdge(source interface{}, target interface{}) bool
}

Replace Edge interface with basic struct, add Size and Order methods.


package main

import (
	"os"
	"fmt"
	"path/filepath"
	"os/exec"
)

func main() {
	workingDirectory, error := os.Getwd()

	if error != nil {
		fmt.Println(error)
		os.Exit(1)
	}

	workingDirectory, error = filepath.Abs(workingDirectory)

	if error != nil {
		fmt.Println(error)
		os.Exit(1)
	}

	os.Setenv("GOPATH", workingDirectory)

	command := exec.Command("go", os.Args[1:]...)
	command.Stdin  = os.Stdin
	command.Stdout = os.Stdout
	command.Stderr = os.Stderr
	if error := command.Run(); error != nil {
		fmt.Println(error)
	}
}

package main

import (
	"os"
	"fmt"
	"path/filepath"
	"os/exec"
)

func main() {
	workingDirectory, error := os.Getwd()

	if error != nil {
		fmt.Println(error)
		os.Exit(1)
	}

	workingDirectory, error = filepath.Abs(workingDirectory)

	if error != nil {
		fmt.Println(error)
		os.Exit(1)
	}

	os.Setenv("GOPATH", workingDirectory)

	command := exec.Command("go", os.Args[1:]...)
	command.Stdin  = os.Stdin
	command.Stdout = os.Stdout
	command.Stderr = os.Stderr
	if error := command.Run(); error != nil {
		fmt.Println(error)
		os.Exit(1)
	}
}

Make sure that we exit with a non-zero status if the command fails


// Package db2 is the replacement for db.  It provides low level db connection
// and query capabilities.
package db2

// PageQuery represents a portion of a Query struct concerned with paging
// through a large dataset.
type PageQuery struct {
	Cursor string
	Order  string
	Limit  uint64
}

// Package db2 is the replacement for db.  It provides low level db connection
// and query capabilities.
package db2

// Pageable records have a defined order, and the place withing that order
// is determined by the paging token
type Pageable interface {
	PagingToken() string
}

// PageQuery represents a portion of a Query struct concerned with paging
// through a large dataset.
type PageQuery struct {
	Cursor string
	Order  string
	Limit  uint64
}

Fix breakage due to Pageable being removed


/*
Copyright 2016 Skippbox, Ltd.
Copyright 2017 André Cruz

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 main

import (
	"flag"
	"log"

	"github.com/edevil/kubewatch/cmd"
)

func main() {
	cmd.Execute()
}

func init() {
	flag.CommandLine.Parse([]string{})
	log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
}

/*
Copyright 2016 Skippbox, Ltd.
Copyright 2017 André Cruz

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 main

import (
	"flag"
	"log"

	"github.com/edevil/kubewatch/cmd"
)

func main() {
	flag.CommandLine.Parse([]string{"-v", "4", "-logtostderr=true"})
	cmd.Execute()
}

func init() {
	log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
}

Configure glog to output to stderr


package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"

	"code.google.com/p/goauth2/oauth"
	"github.com/google/go-github/github"
)

func ListRepos(config *Config) {
	t := &oauth.Transport{
		Token: &oauth.Token{AccessToken: config.OauthToken},
	}

	client := github.NewClient(t.Client())

	// list all repositories for the authenticated user
	repos, _, err := client.Repositories.ListByOrg(config.Organization, nil)

	if err != nil {
		fmt.Println(err)
	}

	//fmt.Println(github.Stringify(repos))
	fmt.Println("Repositories")
	for _, repo := range repos {
		fmt.Printf("  %s\n", *repo.Name)
	}
}

func main() {
	file, e := ioutil.ReadFile("./privy.cfg")
	if e != nil {
		fmt.Printf("File error: %v\n", e)
		os.Exit(1)
	}

	var config Config
	json.Unmarshal(file, &config)
	fmt.Printf("Config: %v\n", config)

	ListRepos(&config)
}

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"

	"code.google.com/p/goauth2/oauth"
	"github.com/google/go-github/github"
)

func ListRepos(config *Config) {
	t := &oauth.Transport{
		Token: &oauth.Token{AccessToken: config.OauthToken},
	}

	client := github.NewClient(t.Client())

	// list all repositories for the authenticated user
	repos, _, err := client.Repositories.ListByOrg(config.Organization, nil)

	if err != nil {
		fmt.Println(err)
	}

	//fmt.Println(github.Stringify(repos))
	fmt.Println("Repositories")
	for _, repo := range repos {
		fmt.Printf("  %s\n", *repo.Name)
	}
}

func main() {
	file, e := ioutil.ReadFile("./privy.cfg")
	if e != nil {
		log.Fatal("File error: ", e)
	}

	var config Config
	json.Unmarshal(file, &config)
	fmt.Printf("Config: %v\n", config)

	ListRepos(&config)
}

Exit with log.Fatal instead of os.Exit


package main

import (
	"bytes"
	"fmt"
	"net/http"
	"regexp"
)

func main() {
	resp, _ := http.Get("http://hichannel.hinet.net/radio/mobile/index.do?id=232")
	defer resp.Body.Close()
	html := new(bytes.Buffer)
	html.ReadFrom(resp.Body)
	//fmt.Println(html.String())
	reg := regexp.MustCompile(`var url = '([\S]+)'`)
	url_string := reg.FindAllStringSubmatch(html.String(), -1)
	//fmt.Println(url_string[0][1])

	replace := regexp.MustCompile(`\\\/`)
	replace_string := replace.ReplaceAllString(url_string[0][1], `/`)
	fmt.Println(replace_string)

}

package main

import (
	"bytes"
	"fmt"
	"net/http"
	"regexp"
)

func main() {
	resp, _ := http.Get("http://hichannel.hinet.net/radio/mobile/index.do?id=232")
	defer resp.Body.Close()
	html := new(bytes.Buffer)
	html.ReadFrom(resp.Body)
	//fmt.Println(html.String())
	reg := regexp.MustCompile(`var url = '([\S]+)'`)
	url_string := reg.FindAllStringSubmatch(html.String(), -1)
	//fmt.Println(url_string[0][1])

	replace := regexp.MustCompile(`\\\/`)
	replace_string := replace.ReplaceAllString(url_string[0][1], `/`)
	fmt.Println(replace_string)

	//fmt.Println("----- test open -----\r\n")
	//exec.Command("open", "-a", "firefox").Run()
}

Add test mac open, but not work.


package main

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

type item struct {
    node string
    value int
}

type Node struct {
    head item
    left item
    right item
}

func split(x int) (a, b, c int){
    a = 1
    b = 2
    c = 3
    return
}

func getChildren(a Node) (b, c item) {
    b = a.left
    c = a.right
    return
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
    })

    http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request){
        fmt.Fprintf(w, "Hi")
    })

    log.Fatal(http.ListenAndServe(":8081", nil))

}

package main

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

type article struct {
    title string
    datePosted int
    desc string
    content string
}

func homePage(w http.ResponseWriter, r *http.Request){
    fmt.Fprintf(w, "Welcome to the HomePage!")
    fmt.Println("Endpoint Hit: homePage")
}

func returnArticle(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "returns a specific article")
    fmt.Println("Endpoint Hit: returnArticle")
}

func returnAllArticles(w http.ResponseWriter, r *http.Request){
    fmt.Fprintf(w, "All Articles")
    fmt.Println("Endpoint Hit: returnAllArticles")
}

func addArticle(w http.ResponseWriter, r *http.Request){
    fmt.Fprintf(w, "Adds an article to list of articles")
    fmt.Println("Endpoint Hit: addArticle")
}

func delArticle(w http.ResponseWriter, r *http.Request){
    fmt.Fprintf(w, "deletes a specific article")
    fmt.Println("Endpoint Hit: delArticle")
}

func handleRequests() {
    http.HandleFunc("/", homePage)
    http.HandleFunc("/all", returnAllArticles)
    http.HandleFunc("/single", returnArticle)
    http.HandleFunc("/delete", delArticle)
    http.HandleFunc("/add", addArticle)
    log.Fatal(http.ListenAndServe(":8081", nil))
}

func main() {
    handleRequests()
}

Structure of a basic REST API


// +build darwin

package libfuse

import (
	"os"

	"bazil.org/fuse"
)

func getPlatformSpecificMountOptions(m Mounter) ([]fuse.MountOption, error) {
	options := []fuse.MountOption{}

	// Add kbfuse support.
	// Workaround osxfuse and bazil.org/fuse issue with a required env for the
	// daemon path. The issue is being tracked here: https://github.com/bazil/fuse/issues/113
	os.Setenv("MOUNT_KBFUSE_DAEMON_PATH", "/Library/Filesystems/kbfuse.fs/Contents/Resources/mount_kbfuse")

	kbfusePath := fuse.OSXFUSEPaths{
		DevicePrefix: "/dev/kbfuse",
		Load:         "/Library/Filesystems/kbfuse.fs/Contents/Resources/load_kbfuse",
		Mount:        "/Library/Filesystems/kbfuse.fs/Contents/Resources/mount_kbfuse",
	}
	// Allow both kbfuse and osxfuse 3.x locations by default.
	options = append(options,
		fuse.OSXFUSELocations(kbfusePath),
		fuse.OSXFUSELocations(fuse.OSXFUSELocationV3))

	// Volume name option is only used on OSX (ignored on other platforms).
	volName, err := volumeName(m.Dir())
	if err != nil {
		return nil, err
	}

	options = append(options, fuse.VolumeName(volName))

	return options, nil
}

// +build darwin

package libfuse

import (
	"os"

	"bazil.org/fuse"
)

func getPlatformSpecificMountOptions(m Mounter) ([]fuse.MountOption, error) {
	options := []fuse.MountOption{}

	// Add kbfuse support.
	// Workaround osxfuse and bazil.org/fuse issue with a required env for the
	// daemon path. The issue is being tracked here: https://github.com/bazil/fuse/issues/113
	os.Setenv("MOUNT_KBFUSE_DAEMON_PATH", "/Library/Filesystems/kbfuse.fs/Contents/Resources/mount_kbfuse")

	kbfusePath := fuse.OSXFUSEPaths{
		DevicePrefix: "/dev/kbfuse",
		Load:         "/Library/Filesystems/kbfuse.fs/Contents/Resources/load_kbfuse",
		Mount:        "/Library/Filesystems/kbfuse.fs/Contents/Resources/mount_kbfuse",
	}
	// Allow both kbfuse and osxfuse 3.x locations by default.
	options = append(options, fuse.OSXFUSELocations(kbfusePath, fuse.OSXFUSELocationV3))

	// Volume name option is only used on OSX (ignored on other platforms).
	volName, err := volumeName(m.Dir())
	if err != nil {
		return nil, err
	}

	options = append(options, fuse.VolumeName(volName))

	return options, nil
}

Fix osxfuse locations (forgot to add to last commit)


package exporter

import (
	log "github.com/sirupsen/logrus"
	"github.com/foomo/petze/watch"
)

func LogResultHandler(result watch.Result) {
	logger := log.WithFields(log.Fields{
		"service_id": result.ID,
		"runtime":    result.RunTime,
		"timeout":    result.Timeout,
	})

	if len(result.Errors) > 0 {
		for _, err := range result.Errors {
			if err.Comment != "" {
				logger = logger.WithField("comment", err.Comment)
			}
			logger.WithField("type", err.Type).Error(err.Error)
		}
	} else {
		logger.Info("run complete")
	}

}

package exporter

import (
	log "github.com/sirupsen/logrus"
	"github.com/foomo/petze/watch"
)

func LogResultHandler(result watch.Result) {
	logger := log.WithFields(log.Fields{
		"service_id": result.ID,
		"runtime":    result.RunTime,
		"timeout":    result.Timeout,
	})

	if len(result.Errors) > 0 {
		for _, err := range result.Errors {
			if err.Comment != "" {
				logger = logger.WithField("comment", err.Comment)
			}
			logger.WithField("type", err.Type).Error(err.Error)
		}
	} else {
		logger.Info("run completed without errors")
	}

}

Update message for run completion


// +build !darwin

package main

import (
	"log"
)

func run(cpus, mem, diskSz int, userData string, args []string) {
	log.Fatalf("'run' is not support yet on your OS")
}

// +build !darwin

package main

import (
	"log"
)

func run(cpus, mem, diskSz int, userData string, args []string) {
	log.Fatalf("'run' is not supported yet on your OS")
}

Fix typo in `moby run`


package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/gentlemanautomaton/serviceresolver"
	"github.com/scjalliance/resourceful/guardian"
)

func collectEndpoints(ctx context.Context) (endpoints []guardian.Endpoint, err error) {
	services, err := serviceresolver.DefaultResolver.Resolve(ctx, "resourceful")
	if err != nil {
		return nil, fmt.Errorf("failed to locate resourceful endpoints: %v", err)
	}
	if len(services) == 0 {
		return nil, errors.New("unable to detect host domain")
	}
	for _, service := range services {
		for _, addr := range service.Addrs {
			endpoint := guardian.Endpoint(fmt.Sprintf("http://%s:%d", addr.Target, addr.Port))
			endpoints = append(endpoints, endpoint)
		}
	}
	return endpoints, nil
}

package main

import (
	"context"
	"errors"
	"fmt"
	"strings"

	"github.com/gentlemanautomaton/serviceresolver"
	"github.com/scjalliance/resourceful/guardian"
)

func collectEndpoints(ctx context.Context) (endpoints []guardian.Endpoint, err error) {
	services, err := serviceresolver.DefaultResolver.Resolve(ctx, "resourceful")
	if err != nil {
		return nil, fmt.Errorf("failed to locate resourceful endpoints: %v", err)
	}
	if len(services) == 0 {
		return nil, errors.New("unable to detect host domain")
	}
	for _, service := range services {
		for _, addr := range service.Addrs {
			endpoint := guardian.Endpoint(fmt.Sprintf("http://%s:%d", strings.TrimSuffix(addr.Target, "."), addr.Port))
			endpoints = append(endpoints, endpoint)
		}
	}
	return endpoints, nil
}

Remove trailing dots from collected endpoint domain names


// Copyright 2015-2017, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// 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 mview adds materialized views via events on the MySQL binary log.
package mview

// Copyright 2015-2017, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// 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 mview adds materialized views via events on the MySQL binary log.
//
//
// https://de.slideshare.net/MySQLGeek/flexviews-materialized-views-for-my-sql
// https://github.com/greenlion/swanhart-tools
//
// https://hashrocket.com/blog/posts/materialized-view-strategies-using-postgresql
// Queries returning aggregate, summary, and computed data are frequently used
// in application development. Sometimes these queries are not fast enough.
// Caching query results using Memcached or Redis is a common approach for
// resolving these performance issues. However, these bring their own
// challenges. Before reaching for an external tool it is worth examining what
// techniques PostgreSQL offers for caching query results.
//
// http://www.eschrade.com/page/indexing-in-magento-or-the-wonderful-world-of-materialized-views/
package mview

Add more ideas / URLs


package torrent

import (
	"encoding/hex"
)

type PeerID [20]byte

func (me PeerID) String() string {
	if me[0] == '-' && me[7] == '-' {
		return string(me[:8]) + hex.EncodeToString(me[8:])
	}
	return hex.EncodeToString(me[:])
}

package torrent

import (
	"encoding/hex"
)

// Peer client ID.
type PeerID [20]byte

// Pretty prints the ID as hex, except parts that adher to the Peer ID
// Conventions of BEP 20.
func (me PeerID) String() string {
	if me[0] == '-' && me[7] == '-' {
		return string(me[:8]) + hex.EncodeToString(me[8:])
	}
	return hex.EncodeToString(me[:])
}

Add some helpful comments to type PeerID


package main

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

var ARGV []string

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

	if len(ARGV) == 0 {
		// Read stdin only
		io.Copy(os.Stdout, os.Stdin)

	} else {
		// Read ARGV only
		for _, filename := range ARGV {
			if filename == "--" {
				continue
			}

			// - means read stdin as a special case
			if filename == "-" {
				filename = "/dev/stdin"
			}

			// Otherwise we're after a file itself
			f, err := os.Open(filename)
			if err != nil {
				fmt.Fprintf(os.Stderr, "gocat: %s: No such file or directory\n", filename)
				continue
			}

			// Copy our output across!
			io.Copy(os.Stdout, f)
		}

	}
}

package main

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

var ARGV []string

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

	if len(ARGV) == 0 {
		// Read stdin only
		io.Copy(os.Stdout, os.Stdin)

	} else {
		// Read ARGV only
		for _, filename := range ARGV {
			// - means read stdin as a special case
			if filename == "-" {
				filename = "/dev/stdin"
			}

			// Otherwise we're after a file itself
			f, err := os.Open(filename)
			if err != nil {
				fmt.Fprintf(os.Stderr, "gocat: %s: No such file or directory\n", filename)
				continue
			}

			// Copy our output across!
			io.Copy(os.Stdout, f)
		}

	}
}

Remove hack for `go run`


package common

import (
	"encoding/json"
)

type TaskData struct {
	FullyQualifiedNodeName    string
	RexFullyQualifiedNodeName string
	Zookeepers                []string
	ClusterName               string
	NodeID                    string
}

func (s *TaskData) Serialize() ([]byte, error) {
	b, err := json.Marshal(s)
	return b, err
}

func DeserializeTaskData(data []byte) (TaskData, error) {
	t := TaskData{}
	err := json.Unmarshal(data, &t)
	return t, err
}

type CoordinatedData struct {
	NodeName    string
	DisterlPort int
	PBPort      int
	HTTPPort    int
	Hostname	string
}

func (s *CoordinatedData) Serialize() ([]byte, error) {
	b, err := json.Marshal(s)
	return b, err
}

func DeserializeCoordinatedData(data []byte) (CoordinatedData, error) {
	t := CoordinatedData{}
	err := json.Unmarshal(data, &t)
	return t, err
}

type DisterlData struct {
	NodeName    string
	DisterlPort int
}

func (s *DisterlData) Serialize() ([]byte, error) {
	b, err := json.Marshal(s)
	return b, err
}

func DeserializeDisterlData(data []byte) (DisterlData, error) {
	t := DisterlData{}
	err := json.Unmarshal(data, &t)
	return t, err
}

Fix gofmt relaxed problem with common


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

package main

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

type mainModel struct {
	grid *sudoku.Grid
}

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

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

	model.grid.Fill()

	draw(model)

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

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

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

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

package main

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

type mainModel struct {
	grid *sudoku.Grid
}

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

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

	model.grid.Fill()

	draw(model)

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

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

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

Fix rendering of the sudoku puzzle.


package main

import (
  "github.com/ricallinson/forgery"
  "github.com/spacedock-io/index/common"
)

func Routes(server *f.Server) {
  /*
    Library repository routes
   */
  server.Put("/v1/repositories/:repo/auth", LibraryAuth)
  server.Put("/v1/repositories/:repo", CreateLibrary)
  server.Delete("/v1/repositories/:repo", DeleteLibrary)
  server.Put("/v1/repositories/:repo/images", UpdateLibraryImage)
  server.Get("/v1/repositories/:repo/images", GetLibraryImage)

  /*
    User routes
   */
  server.Get("/v1/users", common.CheckAuth, Login)
  server.Post("/v1/users", CreateUser)
  server.Put("/v1/users", common.CheckAuth, UpdateUser)

  /*
    User repository routes
   */
  server.Put("/v1/repositories/:namespace/:repo/auth", RepoAuth)
  server.Put("/v1/repositories/:namespace/:repo", CreateRepo)
  server.Delete("/v1/repositories/:namespace/:repo", DeleteRepo)
  server.Put("/v1/repositories/:namespace/:repo/images", UpdateUserImage)
  server.Get("/v1/repositories/:namespace/:repo/images", GetUserImage)

  // Search route
  server.Get("/v1/search", Search)
}

package main

import (
  "github.com/ricallinson/forgery"
  "github.com/spacedock-io/index/common"
)

func Routes(server *f.Server) {
  /*
    Library repository routes
   */
  server.Put("/v1/repositories/:repo/auth", LibraryAuth)
  server.Put("/v1/repositories/:repo", CreateLibrary)
  server.Delete("/v1/repositories/:repo", DeleteLibrary)
  server.Put("/v1/repositories/:repo/images", UpdateLibraryImage)
  server.Get("/v1/repositories/:repo/images", GetLibraryImage)

  /*
    User routes
   */
  server.Get("/v1/users", common.CheckAuth, Login)
  server.Post("/v1/users", CreateUser)
  server.Put("/v1/users/:username", common.CheckAuth, UpdateUser)

  /*
    User repository routes
   */
  server.Put("/v1/repositories/:namespace/:repo/auth", RepoAuth)
  server.Put("/v1/repositories/:namespace/:repo", CreateRepo)
  server.Delete("/v1/repositories/:namespace/:repo", DeleteRepo)
  server.Put("/v1/repositories/:namespace/:repo/images", UpdateUserImage)
  server.Get("/v1/repositories/:namespace/:repo/images", GetUserImage)

  // Search route
  server.Get("/v1/search", Search)
}

Add :username param to PUT /v1/users/:username


package main

import (
	"text/template"

	"github.com/ovn-org/libovsdb/ovsdb"
)

const MODEL_TEMPLATE = `
// Code generated by "libovsdb.modelgen"
// DO NOT EDIT.

package {{ .PackageName }}

import (
	"github.com/ovn-org/libovsdb/client"
)

// FullDatabaseModel() returns the DatabaseModel object to be used in libovsdb
func FullDatabaseModel() (*client.DBModel, error) {
	return client.NewDBModel("{{ .DatabaseName }}", map[string]client.Model{
    {{ range $tableName, $structName := .Tables }} "{{ $tableName }}" : &{{ $structName }}{},
    {{ end }}
	})
}
`

//DBModelTemplateData is the data needed for template processing
type DBModelTemplateData struct {
	PackageName  string
	DatabaseName string
	Tables       map[string]string
}

//NewDBModelGenerator returns a new DBModel generator
func NewDBModelGenerator(pkg string, schema *ovsdb.DatabaseSchema) Generator {
	templateData := DBModelTemplateData{
		PackageName:  pkg,
		DatabaseName: schema.Name,
		Tables:       map[string]string{},
	}
	for tableName := range schema.Tables {
		templateData.Tables[tableName] = StructName(tableName)
	}
	modelTemplate := template.Must(template.New("DBModel").Parse(MODEL_TEMPLATE))
	return newGenerator("model.go", modelTemplate, templateData)
}

package main

import (
	"text/template"

	"github.com/ovn-org/libovsdb/ovsdb"
)

const MODEL_TEMPLATE = `
// Code generated by "libovsdb.modelgen"
// DO NOT EDIT.

package {{ .PackageName }}

import (
	"github.com/ovn-org/libovsdb/client"
)

// FullDatabaseModel returns the DatabaseModel object to be used in libovsdb
func FullDatabaseModel() (*client.DBModel, error) {
	return client.NewDBModel("{{ .DatabaseName }}", map[string]client.Model{
    {{ range $tableName, $structName := .Tables }} "{{ $tableName }}" : &{{ $structName }}{},
    {{ end }}
	})
}
`

//DBModelTemplateData is the data needed for template processing
type DBModelTemplateData struct {
	PackageName  string
	DatabaseName string
	Tables       map[string]string
}

//NewDBModelGenerator returns a new DBModel generator
func NewDBModelGenerator(pkg string, schema *ovsdb.DatabaseSchema) Generator {
	templateData := DBModelTemplateData{
		PackageName:  pkg,
		DatabaseName: schema.Name,
		Tables:       map[string]string{},
	}
	for tableName := range schema.Tables {
		templateData.Tables[tableName] = StructName(tableName)
	}
	modelTemplate := template.Must(template.New("DBModel").Parse(MODEL_TEMPLATE))
	return newGenerator("model.go", modelTemplate, templateData)
}

Fix comment on generated FullDatabaseModel


package main

import "log"

const (
	// outputRoot is the output directory
	// for the build artifacts.
	outputRoot = "dist"
)

var (
	// appName is the name of the
	// application to be built.
	appName string

	// appVersion is the version of
	// the application to be built.
	appVersion = "latest"
)

func main() {
	var err error

	appName, err = currentFolderName()
	if err != nil {
		log.Println(err)
		return
	}

	appVersion, err = gitVersion()
	if err != nil {
		log.Println(err)
		return
	}

	config := NewConfig()
	err = config.Load()
	if err != nil {
		log.Println(err)
		return
	}

	targetPlatforms, err := config.Targets.ToPlatforms()
	if err != nil {
		log.Println(err)
		return
	}

	err = runGoBuildChain(targetPlatforms)
	if err != nil {
		log.Println(err)
		return
	}

	err = archiveBuilds()
	if err != nil {
		log.Println(err)
		return
	}
}

package main

import "log"

const (
	// outputRoot is the output directory
	// for the build artifacts.
	outputRoot = "dist"
)

var (
	// appName is the name of the
	// application to be built.
	appName string

	// appVersion is the version of
	// the application to be built.
	appVersion = "latest"
)

func main() {
	var err error

	appName, err = currentFolderName()
	if err != nil {
		log.Printf("Error while getting folder name of current work directory: %v", err)
		return
	}

	appVersion, err = gitVersion()
	if err != nil {
		log.Printf("Error while getting version from Git: %v", err)
		return
	}

	config := NewConfig()
	err = config.Load()
	if err != nil {
		log.Printf("Error while loading config: %v", err)
		return
	}

	targetPlatforms, err := config.Targets.ToPlatforms()
	if err != nil {
		log.Printf("Error while converting targets from config to platforms: %v", err)
		return
	}

	err = runGoBuildChain(targetPlatforms)
	if err != nil {
		log.Printf("Error while running Go build chain: %v", err)
		return
	}

	err = archiveBuilds()
	if err != nil {
		log.Printf("Error while archiving builds: %v", err)
		return
	}
}

Add context to error messages before printing them


package main

import (
	"flag"
	"fmt"

	"github.com/samertm/meowy/server"
)

func main() {
	host := flag.String("host", "localhost", "sets the host name.")
	port := flag.String("port", "5849", "sets the port.")
	prefix := flag.String("prefix", "", "sets prefix (for if meowy listens on a path that isn't \"/\"")
	flag.Parse()
	ip := *host + ":" + *port
	fmt.Println("listening on", ip)
	if *prefix != "" {
		fmt.Println("with prefix", *prefix)
	}
	server.ListenAndServe(ip, *prefix)
}

package main

import (
	"flag"
	"fmt"

	"github.com/samertm/meowy/server"
)

func main() {
	host := flag.String("host", "localhost", "sets the host name.")
	port := flag.String("port", "5849", "sets the port.")
	prefix := flag.String("prefix", "", "sets prefix (for if meowy listens on a path that isn't \"/\"")
	flag.Parse()
	ip := *host + ":" + *port
	fmt.Println("listening on", ip)
	if *prefix != "" {
		fmt.Println("with prefix", *prefix)
		var front, back string
		if (*prefix)[0] != '/' {
			front = "/"
		}
		if (*prefix)[len(*prefix)-1] != '/' {
			back = "/"
		}
		*prefix = front + *prefix + back
	}
	server.ListenAndServe(ip, *prefix)
}

Make prefix conform to application


package main

import (
	"fmt"
	"log"

	evdev "github.com/gvalkov/golang-evdev"
)

type Event interface {
	String() string
}

func main() {
	kbdEvent, err := NewK().Lookup()
	if err != nil {
		log.Fatal(err)
	}

	kbd := fmt.Sprintf("/dev/input/%s", kbdEvent)

	log.Println(kbd)

	dev, err := evdev.Open(kbd)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(dev)

	for i := 0; i >= 0; i++ {
		ievent, err := dev.ReadOne()
		if err != nil {
			log.Fatal(err)
		}

		if ievent.Type == 1 && ievent.Value == 1 {
			kevent := evdev.NewKeyEvent(ievent)
			log.Println(kevent.Scancode)
		}
	}
}

func KBLog(eventID int, e Event) {
	log.Printf("[%d] -> %s", eventID, e.String())
}

package main

import (
	"fmt"
	"log"

	evdev "github.com/gvalkov/golang-evdev"
)

type Event interface {
	String() string
}

var (
	scanCode uint16
)

func main() {
	keyboard := NewK("iso9995")
	kbdEvent, err := keyboard.Lookup()
	if err != nil {
		log.Fatal(err)
	}

	kbd := fmt.Sprintf("/dev/input/%s", kbdEvent)

	log.Println(kbd)

	dev, err := evdev.Open(kbd)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(dev)

	for {
		ievent, err := dev.ReadOne()
		if err != nil {
			log.Fatal(err)
		}

		if ievent.Type == 1 {
			kevent := evdev.NewKeyEvent(ievent)
			scanCode = kevent.Scancode

			if ievent.Value == 0 {
				switch {
				case scanCode == keyboard.Mapper.LeftShift || scanCode == keyboard.Mapper.RightShift:
					keyboard.Mapper.ShiftOff()
				case scanCode == keyboard.Mapper.Alt || scanCode == keyboard.Mapper.AltGr:
					keyboard.Mapper.AltOff()
				}
			}

			if ievent.Value == 1 {
				switch {
				case scanCode == keyboard.Mapper.LeftShift || scanCode == keyboard.Mapper.RightShift:
					keyboard.Mapper.ShiftOn()
				case scanCode == keyboard.Mapper.Alt || scanCode == keyboard.Mapper.AltGr:
					keyboard.Mapper.AltOn()
				case scanCode == keyboard.Mapper.CapsLock:
					keyboard.Mapper.CapsLockFlip()
				default:
					keyboard.Mapper.Print(scanCode)
				}
			}
		}
	}
}

Print text based on stuff


package main

import (
  "os"
  "fmt"
  "github.com/codegangsta/cli"
  "github.com/aws/aws-sdk-go/service/cloudformation"
)

func main() {
  app := cli.NewApp()
  app.Name = "forecast"
  app.Usage = "cloudformation dry-run"
  app.Action = func(c *cli.Context) {
    svc := cloudformation.New(nil)
    resp, err := svc.ListStacks(nil)
    if err != nil {
      println(err.Error())
      return
    }

    fmt.Println(resp)
  }

  app.Run(os.Args)
}

package main

import (
  "os"
  "fmt"
  "github.com/codegangsta/cli"
  "github.com/aws/aws-sdk-go/service/cloudformation"
)

func main() {
  app := cli.NewApp()
  app.Name = "forecast"
  app.Usage = "cloudformation dry-run"

  app.Commands = []cli.Command{
    {
      Name:      "list",
      Aliases:     []string{"l"},
      Usage:     "list stacks",
      Action: func(c *cli.Context) {
        svc := cloudformation.New(nil)
        resp, err := svc.ListStacks(nil)
        if err != nil {
          println(err.Error())
          return
        }

        fmt.Println(resp)
      },
    },
  }

  app.Run(os.Args)
}

Add list subcommand to list stacks