package mp4parser

import "time"
import "fmt"

//MediaInfo contain media information
type MediaInfo struct {
	width             float64 //
	height            float64 //found in tkhd
	soundSamplingRate uint32

	creationTime *time.Time
	modifTime    *time.Time
	duration     *time.Duration // result of duration/time_scale(field in mvhd)
}

func (m *MediaInfo) String() string {
	return fmt.Sprintf(
		"creationTime:%v\nmodifTime:%v\nduration:%v\nwidth:%.2f\theight:%.2f\tsound samlping rate:%dHz",
		m.creationTime, m.modifTime, m.duration, m.width, m.height, m.soundSamplingRate)
}

func (m *MediaInfo) Width() float64 {
	return m.width
}

func (m *MediaInfo) Height() float64 {
	return m.height
}

func (m *MediaInfo) SamplingRate() uint32 {
	return m.soundSamplingRate
}

func (m *MediaInfo) CreationTime() time.Time {
	return *m.creationTime
}

func (m *MediaInfo) ModifiedTime() *time.Time {
	return m.modifTime
}

func (m *MediaInfo) Duration() *time.Duration {
	return m.duration
}

Add exported getter methods for all fields in MediaInfo


package goalfred

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

// Normalize fixes problems with string encoding regarding the usage of special characters in Alfred.
// For more info on this topic, please refer to this thread: http://www.alfredforum.com/topic/2015-encoding-issue/
func Normalize(input string) (output string, err error) {
	iconv := exec.Command("iconv", "-f", "UTF-8")
	iconvIn, err := iconv.StdinPipe()
	iconvOut, err := iconv.StdoutPipe()

	iconv.Start()
	iconvIn.Write([]byte(input))
	iconvIn.Close()

	iconvOutput, err := ioutil.ReadAll(iconvOut)
	iconv.Wait()

	output = string(iconvOutput)

	return
}

package goalfred

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

// Normalize fixes problems with string encoding regarding the usage of special characters in Alfred.
// For more info on this topic, please refer to this thread: http://www.alfredforum.com/topic/2015-encoding-issue/
func Normalize(input string) (output string, err error) {
	iconv := exec.Command("iconv", "-f", "UTF8-MAC")
	iconvIn, err := iconv.StdinPipe()
	iconvOut, err := iconv.StdoutPipe()

	iconv.Start()
	iconvIn.Write([]byte(input))
	iconvIn.Close()

	iconvOutput, err := ioutil.ReadAll(iconvOut)
	iconv.Wait()

	output = string(iconvOutput)

	return
}

Revert "Test setting the encoding to UTF-8 instead of UTF8-MAC"


package terraform_test

import (
	"bytes"

	"github.com/cloudfoundry/bosh-bootloader/terraform"

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

var _ = Describe("Cmd", func() {
	var (
		stdout *bytes.Buffer
		stderr *bytes.Buffer

		cmd terraform.Cmd
	)

	BeforeEach(func() {
		stdout = bytes.NewBuffer([]byte{})
		stderr = bytes.NewBuffer([]byte{})

		cmd = terraform.NewCmd(stdout, stderr)
	})

	It("runs terraform with args", func() {
		err := cmd.Run("/tmp", []string{"apply", "some-arg"})
		Expect(err).NotTo(HaveOccurred())

		Expect(stdout).To(ContainSubstring("working directory: /private/tmp"))
		Expect(stdout).To(ContainSubstring("apply some-arg"))
	})

	Context("failure case", func() {
		It("returns an error when terraform fails", func() {
			err := cmd.Run("", []string{"fast-fail"})
			Expect(err).To(MatchError("exit status 1"))

			Expect(stderr).To(ContainSubstring("failed to terraform"))
		})
	})
})

package terraform_test

import (
	"bytes"

	"github.com/cloudfoundry/bosh-bootloader/terraform"

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

var _ = Describe("Cmd", func() {
	var (
		stdout *bytes.Buffer
		stderr *bytes.Buffer

		cmd terraform.Cmd
	)

	BeforeEach(func() {
		stdout = bytes.NewBuffer([]byte{})
		stderr = bytes.NewBuffer([]byte{})

		cmd = terraform.NewCmd(stdout, stderr)
	})

	It("runs terraform with args", func() {
		err := cmd.Run("/tmp", []string{"apply", "some-arg"})
		Expect(err).NotTo(HaveOccurred())

		Expect(stdout).To(MatchRegexp("working directory: (.*)/tmp"))
		Expect(stdout).To(ContainSubstring("apply some-arg"))
	})

	Context("failure case", func() {
		It("returns an error when terraform fails", func() {
			err := cmd.Run("", []string{"fast-fail"})
			Expect(err).To(MatchError("exit status 1"))

			Expect(stderr).To(ContainSubstring("failed to terraform"))
		})
	})
})

Fix cmd test to check for tmp directory


package main

import (
	"log"
	"os"
	"fmt"
	"github.com/timakin/ts/loader"
	"github.com/codegangsta/cli"
)

var Commands = []cli.Command{
	commandAll,
	commandBiz,
	commandHack,
}

var commandAll = cli.Command{
	Name:  "all",
	Usage: "",
	Description: `
`,
	Action: doAll,
}

var commandBiz = cli.Command{
	Name:  "biz",
	Usage: "",
	Description: `
`,
	Action: doBiz,
}

var commandHack = cli.Command{
	Name:  "hack",
	Usage: "",
	Description: `
`,
	Action: doHack,
}

func debug(v ...interface{}) {
	if os.Getenv("DEBUG") != "" {
		log.Println(v...)
	}
}

func assert(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func doAll(c *cli.Context) {
	hn := make(chan []string)
	go loader.GetHNFeed(hn)
	phres := <- hn
	fmt.Printf("%s",phres)
}

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}

package main

import (
	"log"
	"os"
	"fmt"
	"github.com/timakin/ts/loader"
	"github.com/codegangsta/cli"
)

var Commands = []cli.Command{
	commandAll,
	commandBiz,
	commandHack,
}

var commandAll = cli.Command{
	Name:  "all",
	Usage: "",
	Description: `
`,
	Action: doAll,
}

var commandBiz = cli.Command{
	Name:  "biz",
	Usage: "",
	Description: `
`,
	Action: doBiz,
}

var commandHack = cli.Command{
	Name:  "hack",
	Usage: "",
	Description: `
`,
	Action: doHack,
}

func debug(v ...interface{}) {
	if os.Getenv("DEBUG") != "" {
		log.Println(v...)
	}
}

func assert(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func doAll(c *cli.Context) {
	hn := make(chan loader.ResultData)
	go loader.GetHNFeed(hn)
	phres := <- hn
	fmt.Printf("%s",phres)
}

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}

Enable to get response appropriately from HN


package engine

import "fmt"

type Dot struct {
	X uint8
	Y uint8
}

// Equals compares two dots
func (d1 Dot) Equals(d2 Dot) bool {
	return d1 == d2 || (d1.X == d2.X && d1.Y == d2.Y)
}

// Implementing json.Marshaler interface
func (d Dot) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf("[%d,%d]", d.X, d.Y)), nil
}

func (d Dot) String() string {
	return fmt.Sprintf("[%d, %d]", d.X, d.Y)
}

// DistanceTo calculates distance between two dots
func (from Dot) DistanceTo(to Dot) (res uint16) {
	if !from.Equals(to) {
		if from.X > to.X {
			res = uint16(from.X - to.X)
		} else {
			res = uint16(to.X - from.X)
		}

		if from.Y > to.Y {
			res += uint16(from.Y - to.Y)
		} else {
			res += uint16(to.Y - from.Y)
		}
	}

	return
}

package engine

import "fmt"

type Dot struct {
	X uint8
	Y uint8
}

// Equals compares two dots
func (d1 Dot) Equals(d2 Dot) bool {
	return d1 == d2 || (d1.X == d2.X && d1.Y == d2.Y)
}

// Implementing json.Marshaler interface
func (d Dot) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf("[%d,%d]", d.X, d.Y)), nil
}

func (d Dot) Hash() string {
	return string([]byte{d.X, d.Y})
}

func (d Dot) String() string {
	return fmt.Sprintf("[%d, %d]", d.X, d.Y)
}

// DistanceTo calculates distance between two dots
func (from Dot) DistanceTo(to Dot) (res uint16) {
	if !from.Equals(to) {
		if from.X > to.X {
			res = uint16(from.X - to.X)
		} else {
			res = uint16(to.X - from.X)
		}

		if from.Y > to.Y {
			res += uint16(from.Y - to.Y)
		} else {
			res += uint16(to.Y - from.Y)
		}
	}

	return
}

Create Hash method to engine.Dot


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

package graphs

// FindCelebrity returns an index into 2D slice f that represents a celebrity
// on the party who doesn't know no one. -1 is returned if such a celebrity
// doesn't exists in f or if a person exists who doesn't know the celebrity.
// The time complexity is O(n), and O(1) additional space is needed.
func FindCelebrity(f [][]bool) int {
	r, c := 0, 1 // c starts at 1 'cause it's after start of diagonal (A<->A, B<->B, C<->C, ...)
	for c < len(f) {
		if f[r][c] {
			r, c = c, c+1 // All candidates less then c are not celebrity candidates.
		} else {
			c++ // r is still a celebrity candidate but c is not.
		}
	}
	for _, status := range f[r] { // Check if selected candidate is really a celebrity.
		if status {
			return -1
		}
	}
	return r
}

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

package graphs

// FindCelebrity returns an index into 2D slice f that represents a celebrity
// on the party who doesn't know no one. -1 is returned if such a celebrity
// doesn't exists in f or if a person exists who doesn't know the celebrity.
// The time complexity is O(n), and O(1) additional space is needed.
func FindCelebrity(f [][]bool) int {
	row, col := 0, 1 // col starts at 1 'cause it's after start of a diagonal (A<->A, B<->B, C<->C, ...)
	for col < len(f) {
		if f[row][col] {
			row, col = col, col+1 // All candidates less then col are not celebrity candidates.
		} else {
			col++ // row is still a celebrity candidate but col is not.
		}
	}
	for _, status := range f[row] { // Check if selected candidate is really a celebrity.
		if status {
			return -1
		}
	}
	return row
}

Change local variables names in graphs.FindCelebrity function


package main

import (
	"fmt"
	"github.com/davecheney/gpio"
	"os"
	"os/signal"
	"time"
)

func main() {
	// set GPIO25 to output mode
	pin, err := gpio.OpenPin(25)
	if err != nil {
		fmt.Printf("Error opening pin! %s\n", err)
		return
	}
	pin.SetMode(gpio.ModeOutput)

	// turn the led off on exit
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for _ = range c {
			fmt.Printf("\nClearing and unexporting the pin.\n")
			pin.Clear()
			pin.Close()
			os.Exit(0)
		}
	}()

	for {
		pin.Set()
		time.Sleep(100 * time.Millisecond)
		pin.Clear()
		time.Sleep(100 * time.Millisecond)
	}
}

package main

import (
	"fmt"
	"github.com/davecheney/gpio"
	"os"
	"os/signal"
	"time"
)

func main() {
	// set GPIO25 to output mode
	pin, err := gpio.OpenPin(25, gpio.ModeOutput)
	if err != nil {
		fmt.Printf("Error opening pin! %s\n", err)
		return
	}

	// turn the led off on exit
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for _ = range c {
			fmt.Printf("\nClearing and unexporting the pin.\n")
			pin.Clear()
			pin.Close()
			os.Exit(0)
		}
	}()

	for {
		pin.Set()
		time.Sleep(100 * time.Millisecond)
		pin.Clear()
		time.Sleep(100 * time.Millisecond)
	}
}

Update example to use updated interface


package gobot

type commander struct {
	commands map[string]func(map[string]interface{}) interface{}
}

// Commander is the interface which describes the behaviour for a Driver or Adaptor
// which exposes API commands.
type Commander interface {
	// Command returns a command given a name. Returns nil if the command is not found.
	Command(string) (command func(map[string]interface{}) interface{})
	// Commands returns a map of commands.
	Commands() (commands map[string]func(map[string]interface{}) interface{})
	// AddCommand adds a command given a name.
	AddCommand(name string, command func(map[string]interface{}) interface{})
}

// NewCommander returns a new Commander.
func NewCommander() Commander {
	return &commander{
		commands: make(map[string]func(map[string]interface{}) interface{}),
	}
}

func (c *commander) Command(name string) (command func(map[string]interface{}) interface{}) {
	command, _ = c.commands[name]
	return
}

func (c *commander) Commands() map[string]func(map[string]interface{}) interface{} {
	return c.commands
}

func (c *commander) AddCommand(name string, command func(map[string]interface{}) interface{}) {
	c.commands[name] = command
}

package gobot

type commander struct {
	commands map[string]func(map[string]interface{}) interface{}
}

// Commander is the interface which describes the behaviour for a Driver or Adaptor
// which exposes API commands.
type Commander interface {
	// Command returns a command given a name. Returns nil if the command is not found.
	Command(string) (command func(map[string]interface{}) interface{})
	// Commands returns a map of commands.
	Commands() (commands map[string]func(map[string]interface{}) interface{})
	// AddCommand adds a command given a name.
	AddCommand(name string, command func(map[string]interface{}) interface{})
}

// NewCommander returns a new Commander.
func NewCommander() Commander {
	return &commander{
		commands: make(map[string]func(map[string]interface{}) interface{}),
	}
}

// Command returns the command interface whene passed a valid command name
func (c *commander) Command(name string) (command func(map[string]interface{}) interface{}) {
	command, _ = c.commands[name]
	return
}

// Commands returns the entire map of valid commands
func (c *commander) Commands() map[string]func(map[string]interface{}) interface{} {
	return c.commands
}

// AddCommand adds a new command, when passed a command name and the command interface.
func (c *commander) AddCommand(name string, command func(map[string]interface{}) interface{}) {
	c.commands[name] = command
}

Add missing godocs for Commander type


package binaryutils

import (
	"encoding/binary"
	"io/ioutil"
)

func BE32(data []byte, index int) int {
	return int(binary.BigEndian.Uint32(data[index : index+4]))
}

func LE32(data []byte, index int) int {
	return int(binary.LittleEndian.Uint32(data[index : index+4]))
}

func LE24(data []byte, index int) int {
	threebytes := data[index : index+3]
	onebyte := []byte{0x00}
	threebytes = append(onebyte, threebytes...)
	return int(binary.LittleEndian.Uint32(threebytes))
}

func BE16(data []byte, index int) int {
	return int(binary.BigEndian.Uint16(data[index : index+2]))
}

func LE16(data []byte, index int) int {
	return int(binary.LittleEndian.Uint16(data[index : index+2]))
}

func FourCharString(data []byte, index int) string {
	return string(data[index : index+4])
}

func ReadXoredFile(fileName string, code byte) (out []byte, err error) {
	out, err = ioutil.ReadFile(fileName)
	for i := range out {
		out[i] = out[i] ^ code
	}
	return out, err
}

package binaryutils

import (
	"encoding/binary"
	"io/ioutil"
)

func BE32(data []byte, index int) int {
	return int(binary.BigEndian.Uint32(data[index : index+4]))
}

func LE32(data []byte, index int) int {
	return int(binary.LittleEndian.Uint32(data[index : index+4]))
}

func LE24(data []byte, index int) int {
	fourbytes := []byte{data[index], data[index+1], data[index+2], 0x00}
	return int(binary.LittleEndian.Uint32(fourbytes))
}

func BE16(data []byte, index int) int {
	return int(binary.BigEndian.Uint16(data[index : index+2]))
}

func LE16(data []byte, index int) int {
	return int(binary.LittleEndian.Uint16(data[index : index+2]))
}

func FourCharString(data []byte, index int) string {
	return string(data[index : index+4])
}

func ReadXoredFile(fileName string, code byte) (out []byte, err error) {
	out, err = ioutil.ReadFile(fileName)
	for i := range out {
		out[i] = out[i] ^ code
	}
	return out, err
}

Fix 24bit little endian parser


// +build darwin linux

package main

import (
	"log"
	"strconv"
	"syscall"
)

var realUid int

func init() {
	sudoUid, ok := syscall.Getenv("SUDO_UID")
	if ok {
		var err error
		realUid, err = strconv.Atoi(sudoUid)
		if err != nil {
			log.Fatal("SUDO_UID", err)
		}
	} else {
		realUid = syscall.Getuid()
	}
}

func gainRoot(reason string) {
	e := syscall.Seteuid(0)
	if e != nil {
		log.Fatalf(msgErrGainRoot, e, reason)
	}
	debug("euid", syscall.Geteuid())
}

func dropRoot() {
	e := syscall.Seteuid(realUid)
	if e != nil {
		log.Fatal(e)
	}
	debug("euid", syscall.Geteuid())
}

// +build darwin linux

package main

import (
	"log"
	"strconv"
	"syscall"
)

var realUid int

func init() {
	sudoUid, ok := syscall.Getenv("SUDO_UID")
	if ok {
		var err error
		realUid, err = strconv.Atoi(sudoUid)
		if err != nil {
			log.Fatal("SUDO_UID", err)
		}
	} else {
		realUid = syscall.Getuid()
	}
}

func gainRoot(reason string) {
	e := syscall.Setreuid(-1, 0)
	if e != nil {
		log.Fatalf(msgErrGainRoot, e, reason)
	}
	debug("euid", syscall.Geteuid())
}

func dropRoot() {
	e := syscall.Setreuid(-1, realUid)
	if e != nil {
		log.Fatal(e)
	}
	debug("euid", syscall.Geteuid())
}

Use setreuid instead of seteuid for compatibility


package shared

type ServerStateEnvironment struct {
	Addresses              []string `json:"addresses"`
	Architectures          []string `json:"architectures"`
	Certificate            string   `json:"certificate"`
	CertificateFingerprint string   `json:"certificate_fingerprint"`
	Driver                 string   `json:"driver"`
	DriverVersion          string   `json:"driver_version"`
	Kernel                 string   `json:"kernel"`
	KernelArchitecture     string   `json:"kernel_architecture"`
	KernelVersion          string   `json:"kernel_version"`
	Server                 string   `json:"server"`
	ServerPid              int      `json:"server_pid"`
	ServerVersion          string   `json:"server_version"`
	Storage                string   `json:"storage"`
	StorageVersion         string   `json:"storage_version"`
}

type ServerState struct {
	APICompat   int                    `json:"api_compat"`
	Auth        string                 `json:"auth"`
	Environment ServerStateEnvironment `json:"environment"`
	Config      map[string]interface{} `json:"config"`
	Public      bool                   `json:"public"`
}

type BriefServerState struct {
	Config map[string]interface{} `json:"config"`
}

func (c *ServerState) Brief() BriefServerState {
	retstate := BriefServerState{Config: c.Config}
	return retstate
}

package shared

type ServerStateEnvironment struct {
	Addresses              []string `json:"addresses"`
	Architectures          []string `json:"architectures"`
	Certificate            string   `json:"certificate"`
	CertificateFingerprint string   `json:"certificate_fingerprint"`
	Driver                 string   `json:"driver"`
	DriverVersion          string   `json:"driver_version"`
	Kernel                 string   `json:"kernel"`
	KernelArchitecture     string   `json:"kernel_architecture"`
	KernelVersion          string   `json:"kernel_version"`
	Server                 string   `json:"server"`
	ServerPid              int      `json:"server_pid"`
	ServerVersion          string   `json:"server_version"`
	Storage                string   `json:"storage"`
	StorageVersion         string   `json:"storage_version"`
}

type ServerState struct {
	APIExtensions []string               `json:"api_extensions"`
	APIStatus     string                 `json:"api_status"`
	APIVersion    string                 `json:"api_version"`
	Auth          string                 `json:"auth"`
	Environment   ServerStateEnvironment `json:"environment"`
	Config        map[string]interface{} `json:"config"`
	Public        bool                   `json:"public"`
}

type BriefServerState struct {
	Config map[string]interface{} `json:"config"`
}

func (c *ServerState) Brief() BriefServerState {
	retstate := BriefServerState{Config: c.Config}
	return retstate
}

Fix API info reporting in "lxc info"


package httphandlers

import (
	"github.com/gin-gonic/gin"
	"github.com/pufferpanel/pufferd/logging"
)

func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				logging.Errorf("Error handling route\n%+v", err)
			}
		}()

		c.Next();
	}
}

package httphandlers

import (
	"github.com/gin-gonic/gin"
	"github.com/pufferpanel/pufferd/logging"
	"runtime/debug"
)

func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				c.Status(500)
				logging.Errorf("Error handling route\n%+v\n%s", err, debug.Stack())
			}
		}()

		c.Next();
	}
}

Improve logging to print stacktrace on error


package raft

import (
	"bytes"
	"encoding/json"
	"testing"
)

func BenchmarkAppendEntriesEncoding(b *testing.B) {
	req, _ := createTestAppendEntriesRequest(2000)
    for i := 0; i < b.N; i++ {
		var buf bytes.Buffer
        json.NewEncoder(&buf).Encode(req)
    }
}

func BenchmarkAppendEntriesDecoding(b *testing.B) {
	req, buf := createTestAppendEntriesRequest(2000)
    for i := 0; i < b.N; i++ {
        json.NewDecoder(bytes.NewReader(buf)).Decode(req)
    }
}

func createTestAppendEntriesRequest(entryCount int) (*AppendEntriesRequest, []byte) {
	entries := make([]*LogEntry, 0)
	for i := 0; i < entryCount; i++ {
		entries = append(entries, newLogEntry(nil, 1, 2, &joinCommand{Name: "localhost:1000"}))
	}
	req := newAppendEntriesRequest(1, "leader", 1, 1, entries, 1)
	buf, _ := json.Marshal(req)

	return req, buf
}

package raft

import (
	"bytes"
	"encoding/json"
	"testing"
)

func BenchmarkAppendEntriesEncoding(b *testing.B) {
	req, tmp := createTestAppendEntriesRequest(2000)
    for i := 0; i < b.N; i++ {
		var buf bytes.Buffer
        json.NewEncoder(&buf).Encode(req)
    }
	b.SetBytes(int64(len(tmp)))
}

func BenchmarkAppendEntriesDecoding(b *testing.B) {
	req, buf := createTestAppendEntriesRequest(2000)
    for i := 0; i < b.N; i++ {
        json.NewDecoder(bytes.NewReader(buf)).Decode(req)
    }
	b.SetBytes(int64(len(buf)))
}

func createTestAppendEntriesRequest(entryCount int) (*AppendEntriesRequest, []byte) {
	entries := make([]*LogEntry, 0)
	for i := 0; i < entryCount; i++ {
		entries = append(entries, newLogEntry(nil, 1, 2, &joinCommand{Name: "localhost:1000"}))
	}
	req := newAppendEntriesRequest(1, "leader", 1, 1, entries, 1)
	buf, _ := json.Marshal(req)

	return req, buf
}

Add throughput metrics to benchmark.


package main

import (
	"html/template"
	"log"
	"os"
	"time"
)

// Must method parses the template to ensure no errors;
// New method creates and returns a new template
var report = template.Must(template.New("issuelist").Parse(IssueList))

func main() {
	result, err := SearchIssues(os.Args[1:])
	if err != nil {
		log.Fatal(err)
	}
	if err := report.Execute(os.Stdout, result); err != nil {
		log.Fatal(err)
	}
}

func daysAgo(t time.Time) int {
	return int(time.Since(t).Hours() / 24)
}

package main

import (
	"html/template"
	"log"
	"os"
	"time"
)

// Must method parses the template to ensure no errors;
// New method creates and returns a new template
var report = template.Must(template.New("issuelist").

	// Funcs adds daysAgo as a function accessible inside the template
	Funcs(template.FuncMap{"daysAgo": daysAgo}).Parse(IssueList))

func main() {
	result, err := SearchIssues(os.Args[1:])
	if err != nil {
		log.Fatal(err)
	}
	if err := report.Execute(os.Stdout, result); err != nil {
		log.Fatal(err)
	}
}

func daysAgo(t time.Time) int {
	return int(time.Since(t).Hours() / 24)
}

Add daysAgo func to template


package main

import (
	"fmt"
	"github.com/Symantec/Dominator/imagepublishers/amipublisher"
	libjson "github.com/Symantec/Dominator/lib/json"
	"log"
	"os"
)

func listUnpackersSubcommand(args []string, logger *log.Logger) {
	err := listUnpackers(logger)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error preparing unpackers: %s\n", err)
		os.Exit(1)
	}
	os.Exit(0)
}

func listUnpackers(logger *log.Logger) error {
	results, err := amipublisher.ListUnpackers(targets, skipTargets,
		*unpackerName, logger)
	if err != nil {
		return err
	}
	return libjson.WriteWithIndent(os.Stdout, "    ", results)
}

package main

import (
	"fmt"
	"github.com/Symantec/Dominator/imagepublishers/amipublisher"
	libjson "github.com/Symantec/Dominator/lib/json"
	"log"
	"os"
)

func listUnpackersSubcommand(args []string, logger *log.Logger) {
	err := listUnpackers(logger)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error listing unpackers: %s\n", err)
		os.Exit(1)
	}
	os.Exit(0)
}

func listUnpackers(logger *log.Logger) error {
	results, err := amipublisher.ListUnpackers(targets, skipTargets,
		*unpackerName, logger)
	if err != nil {
		return err
	}
	return libjson.WriteWithIndent(os.Stdout, "    ", results)
}

Fix error message in ami-publisher list-unpackers subcommand.


package templates

func ScopeTemplateContent() string {
	return `#cloud-config

{{ .Name}}:
  {{ range .Services }}{{ .GetName }}:
    {{ range $key, $value := .GetParameters }}{{ $key }}: {{ $value }}
    {{ end }}
  {{ end }}units:
    {{ range .Units }}- name: {{ .GetName }}
      command: {{ .GetCommand }}
		{{ end }}
`
}

Fix identation error on template


package main

import (
	"os"
	"os/exec"
	"strconv"
)

func main() {
	uid := strconv.Itoa(os.Getuid())

	cmdargs := append([]string{"run", "-u", uid, "--rm", "-i"}, os.Args[1:]...)
	cmd := exec.Command("docker", cmdargs...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Run()
}

package main

import (
	"os"
	"os/exec"
	"strconv"
)

func main() {
	uid := strconv.Itoa(os.Getuid())

	cmdargs := append([]string{"run", "-u", uid, "--rm", "-i", "--"}, os.Args[1:]...)
	cmd := exec.Command("docker", cmdargs...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Run()
}

Use -- to prevent illegal args passing to run


package main

import (
	"fmt"
	"github.com/bluele/slack"
)

// Please change these values to suit your environment
const (
	token       = "your-api-token"
	channelName = "general"
)

func main() {
	api := slack.New(token)
	channel, err := api.FindChannelByName(channelName)
	if err != nil {
		panic(err)
	}
	msgs, err := api.ChannelsHistory(&slack.ChannelsHistoryOpt{
		Channel: channel.Id,
	})
	if err != nil {
		panic(err)
	}
	for _, msg := range msgs {
		fmt.Println(msg.UserId, msg.Text)
	}
}

package main

import (
	"fmt"
	"github.com/bluele/slack"
)

// Please change these values to suit your environment
const (
	token       = "your-api-token"
	channelName = "general"
)

func main() {
	api := slack.New(token)
	channel, err := api.FindChannelByName(channelName)
	if err != nil {
		panic(err)
	}
	msgs, err := api.ChannelsHistoryMessages(&slack.ChannelsHistoryOpt{
		Channel: channel.Id,
	})
	if err != nil {
		panic(err)
	}
	for _, msg := range msgs {
		fmt.Println(msg.UserId, msg.Text)
	}
}

Use last API to load history messages from channel


package main

import "./specify"

func init() {
	specify.Behavior("Math", func(it *specify.It) {

		it.Should("add integers", func(expect *specify.Expect) {

			expect.That(1 + 2).Should.Be(4);
			expect.That("foo").Should.Be("bar");

		})

	})
}

package main

import "./specify"

func init() {
	specify.Behavior("Math", func(it *specify.It) {
		it.Should("add", func(expect *specify.Expect) {
			expect.That(1 + 2).Should.Be(3);
		});

		it.Should("multiply", func(expect *specify.Expect) {
			expect.That(2 * 4).Should.Be(6);
		});
	});

	specify.Behavior("Strings", func(it *specify.It) {
		it.Should("concatenate", func(expect *specify.Expect) {
			expect.That("foo" + "bar").Should.Be("bar")
		});
	});
}

Refactor spec to be more BDDish.


package cryptopals

import (
	"encoding/base64"
	"fmt"
	"math/big"
	"testing"
)

func TestDecryptRsaParityOracle(t *testing.T) {
	priv := generateRsaPrivateKey(1024)
	pub := priv.public()

	fmt.Printf("n: %v\n\n", pub.n)

	encoded := "VGhhdCdzIHdoeSBJIGZvdW5kIHlvdSBkb24ndCBwbGF5IGFyb3VuZCB3aXRoIHRoZSBGdW5reSBDb2xkIE1lZGluYQ=="
	message, _ := base64.RawStdEncoding.DecodeString(encoded)
	m1 := new(big.Int).SetBytes(message)

	server := &parityOracleServer{priv: *priv}
	c := pub.encrypt(m1)
	m2 := challenge46{}.DecryptRsaParityOracle(server, pub, c)

	s1 := string(m1.Bytes())
	s2 := string(m2.Bytes())

	fmt.Println(s1)
	fmt.Println(s2)
}

package cryptopals

import (
	"encoding/base64"
	"fmt"
	"math/big"
	"testing"
)

func TestDecryptRsaParityOracle(t *testing.T) {
	priv := generateRsaPrivateKey(1024)
	pub := priv.public()

	encoded := "VGhhdCdzIHdoeSBJIGZvdW5kIHlvdSBkb24ndCBwbGF5IGFyb3VuZCB3aXRoIHRoZSBGdW5reSBDb2xkIE1lZGluYQ=="
	message, _ := base64.RawStdEncoding.DecodeString(encoded)
	m1 := new(big.Int).SetBytes(message)

	server := &parityOracleServer{priv: *priv}
	c := pub.encrypt(m1)
	m2 := challenge46{}.DecryptRsaParityOracle(server, pub, c)

	s1 := string(m1.Bytes())
	s2 := string(m2.Bytes())

	fmt.Println(s1)
	fmt.Println(s2)
}

Remove unneeded call to Println


package collector

import (
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
)

func HttpGet(endpoint string) (body []byte, err error) {
	response, err := http.Get(endpoint)
	if err != nil {
		return nil, err
	}
	if response.StatusCode < 200 || response.StatusCode >= 300 {
		return nil, errors.New(fmt.Sprintf(
			"Got response code when querying %s: %d", endpoint, response.StatusCode))
	}
	return ioutil.ReadAll(response.Body)
}

package collector

import (
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
)

const (
	userAgent = "metrics-collector/1.0"
)

func HttpGet(endpoint string) (body []byte, err error) {
	// Configure custom UA header for tracing in mesos logs
	request, err := http.NewRequest("GET", endpoint, nil)
	if err != nil {
		return nil, err
	}
	request.Header.Set("User-Agent", userAgent)

	client := http.Client{}
	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}
	if response.StatusCode < 200 || response.StatusCode >= 300 {
		return nil, errors.New(fmt.Sprintf(
			"Got response code when querying %s: %d", endpoint, response.StatusCode))
	}
	return ioutil.ReadAll(response.Body)
}

Include User-Agent header in outgoing HTTP requests


/*
 * Copyright (C) 2019 IBM, 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 ofthe 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 specificlanguage governing permissions and
 * limitations under the License.
 *
 */

package main

import (
	aws "github.com/skydive-project/skydive/contrib/exporters/awsflowlogs/mod"
	"github.com/skydive-project/skydive/contrib/exporters/core"
	sa "github.com/skydive-project/skydive/contrib/exporters/secadvisor/mod"
)

func main() {
	core.Main("/etc/skydive/uber.yml")
}

func init() {
	core.TransformerHandlers.Register("awsflowlogs", aws.NewTransform, false)
	core.TransformerHandlers.Register("vpclogs", sa.NewTransform, false)
}

/*
 * Copyright (C) 2019 IBM, 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 ofthe 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 specificlanguage governing permissions and
 * limitations under the License.
 *
 */

package main

import (
	aws "github.com/skydive-project/skydive/contrib/exporters/awsflowlogs/mod"
	"github.com/skydive-project/skydive/contrib/exporters/core"
	sa "github.com/skydive-project/skydive/contrib/exporters/secadvisor/mod"
)

func main() {
	core.Main("/etc/skydive/allinone.yml")
}

func init() {
	core.TransformerHandlers.Register("awsflowlogs", aws.NewTransform, false)
	core.TransformerHandlers.Register("vpclogs", sa.NewTransform, false)
}

Fix default config file name


package testutil

import (
	"time"
	"testing"
	"github.com/hashicorp/consul/consul/structs"
)

type testFn func() (bool, error)
type errorFn func(error)

func WaitForResult(test testFn, error errorFn) {
	retries := 100

	for retries > 0 {
		time.Sleep(100 * time.Millisecond)
		retries--

		success, err := test()
		if success {
			return
		}

		if retries == 0 {
			error(err)
		}
	}
}

type rpcFn func(string, interface {}, interface {}) error

func WaitForLeader(t *testing.T, rpc rpcFn, dc string) structs.IndexedNodes {
	var out structs.IndexedNodes
	WaitForResult(func() (bool, error) {
		args := &structs.RegisterRequest{
			Datacenter: dc,
		}
		err := rpc("Catalog.ListNodes", args, &out)
		return out.QueryMeta.KnownLeader, err
	}, func(err error) {
		t.Fatalf("failed to find leader: %v", err)
	})
	return out
}

package testutil

import (
	"time"
	"testing"
	"github.com/hashicorp/consul/consul/structs"
)

type testFn func() (bool, error)
type errorFn func(error)

func WaitForResult(test testFn, error errorFn) {
	retries := 1000

	for retries > 0 {
		time.Sleep(10 * time.Millisecond)
		retries--

		success, err := test()
		if success {
			return
		}

		if retries == 0 {
			error(err)
		}
	}
}

type rpcFn func(string, interface {}, interface {}) error

func WaitForLeader(t *testing.T, rpc rpcFn, dc string) structs.IndexedNodes {
	var out structs.IndexedNodes
	WaitForResult(func() (bool, error) {
		args := &structs.RegisterRequest{
			Datacenter: dc,
		}
		err := rpc("Catalog.ListNodes", args, &out)
		return out.QueryMeta.KnownLeader, err
	}, func(err error) {
		t.Fatalf("failed to find leader: %v", err)
	})
	return out
}

Speed up test runs in `WaitForResult`


/*
 * Copyright (c) 2014 ZionSoft. All rights reserved.
 * Use of this source code is governed by a BSD-style license
 * that can be found in the LICENSE file.
 */

package translation

import (
    "net/http"
    "net/url"

    "appengine"
    "appengine/blobstore"

    "src/core"
)

func DownloadTranslationHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != "GET" {
        panic(&core.Error{http.StatusMethodNotAllowed, ""})
    }

    // parses query parameters
    params, err := url.ParseQuery(r.URL.RawQuery)
    if err != nil {
        panic(&core.Error{http.StatusBadRequest, ""})
    }

    // TODO supports other query params

    blobKey := params.Get("blobKey")

    translations := loadTranslations(appengine.NewContext(r))
    for _, t := range translations {
        if (string)(t.BlobKey) == blobKey {
            blobstore.Send(w, appengine.BlobKey(blobKey))
            return
        }
    }

    panic(&core.Error{http.StatusBadRequest, ""})
}

/*
 * Copyright (c) 2014 ZionSoft. All rights reserved.
 * Use of this source code is governed by a BSD-style license
 * that can be found in the LICENSE file.
 */

package translation

import (
    "net/http"
    "net/url"

    "appengine"
    "appengine/blobstore"

    "src/core"
)

func DownloadTranslationHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != "GET" {
        panic(&core.Error{http.StatusMethodNotAllowed, ""})
    }

    // parses query parameters
    params, err := url.ParseQuery(r.URL.RawQuery)
    if err != nil {
        panic(&core.Error{http.StatusBadRequest, ""})
    }

    // TODO supports other query params

    blobKey := params.Get("blobKey")

    translations := loadTranslations(appengine.NewContext(r))
    for _, t := range translations {
        if (string)(t.BlobKey) == blobKey {
            blobstore.Send(w, appengine.BlobKey(blobKey))
            return
        }
    }

    panic(&core.Error{http.StatusNotFound, ""})
}

Return 404 instead of 400 if the translation is not found.


package utils

import (
	"math/rand"
	"sync"
	"testing"

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

func TestRandomString(t *testing.T) {
	rand.Seed(42)
	s1 := RandomString(10)
	s2 := RandomString(20)

	rand.Seed(42)
	s3 := RandomString(10)
	s4 := RandomString(20)

	assert.Len(t, s1, 10)
	assert.Len(t, s2, 20)
	assert.Len(t, s3, 10)
	assert.Len(t, s4, 20)

	assert.NotEqual(t, s1, s2)
	assert.Equal(t, s1, s3)
	assert.Equal(t, s2, s4)
}

func TestRandomStringConcurrentAccess(t *testing.T) {
	n := 10000
	var wg sync.WaitGroup
	wg.Add(n)
	for i := 0; i < n; i++ {
		go func() {
			RandomString(10)
			wg.Done()
		}()
	}
	wg.Wait()
}

package utils

import (
	"math/rand"
	"sync"
	"testing"

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

func TestRandomString(t *testing.T) {
	rand.Seed(42)
	s1 := RandomString(10)
	s2 := RandomString(20)

	rand.Seed(42)
	s3 := RandomString(10)
	s4 := RandomString(20)

	assert.Len(t, s1, 10)
	assert.Len(t, s2, 20)
	assert.Len(t, s3, 10)
	assert.Len(t, s4, 20)

	assert.NotEqual(t, s1, s2)
	assert.Equal(t, s1, s3)
	assert.Equal(t, s2, s4)
}

func TestRandomStringConcurrentAccess(t *testing.T) {
	n := 10000
	var wg sync.WaitGroup
	wg.Add(n)

	ms := make(map[string]struct{})
	var mu sync.Mutex

	for i := 0; i < n; i++ {
		go func() {
			s := RandomString(10)
			defer wg.Done()
			mu.Lock()
			defer mu.Unlock()
			if _, ok := ms[s]; ok {
				t.Fatal("should be unique strings")
			}
			var q struct{}
			ms[s] = q
		}()
	}
	wg.Wait()
}

Check uniqueness of generated RandomStrings


package webapp

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

type WebApp struct {
	*mux.Router
	handler http.Handler
}

type routeAgent interface {
	BindRoute(app *WebApp)
}

func NewWebApp() *WebApp {
	app := &WebApp{
		Router: mux.NewRouter()}
	app.handler = app.Router
	return app
}

type Middleware func(http.Handler) http.Handler

// PreRequest of WebApp adds a pre-request handler.
// The lastest added middleware is called first.
func (app *WebApp) UseMiddleware(f Middleware) {
	app.handler = f(app.handler)
}

func (app *WebApp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	app.handler.ServeHTTP(w, r)
}

// UseAgent of WebApp adds the routes of a routeAgent to the app receiver by calling agent.BindRoute.
func (app *WebApp) UseAgent(agent routeAgent) {
	agent.BindRoute(app)
}

package webapp

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

type WebApp struct {
	*mux.Router
	handler http.Handler
}

type routeAgent interface {
	BindRoute(app *WebApp)
}

func NewWebApp() *WebApp {
	app := &WebApp{
		Router: mux.NewRouter()}
	app.handler = app.Router
	return app
}

type Middleware func(http.Handler) http.Handler

// UseMiddleware of *WebApp adds a webapp.Middleware to the app.
// The lastest added middleware functions first.
func (app *WebApp) UseMiddleware(f Middleware) {
	app.handler = f(app.handler)
}

func (app *WebApp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	app.handler.ServeHTTP(w, r)
}

// UseAgent of *WebApp adds the routes of a routeAgent to the app receiver by calling agent.BindRoute.
func (app *WebApp) UseAgent(agent routeAgent) {
	agent.BindRoute(app)
}

Update some outdated function documentation


package main

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

func main() {
	go http.ListenAndServe(":8282", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %s", html.EscapeString(r.URL.Path))
	}))

	res, err := http.Get("http://localhost:8282/world")
	if err != nil {
		log.Fatal(err)
	}
	contents, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Server responded with: %s", contents)
}

package main

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

func main() {
	go http.ListenAndServe(":8282", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %s", html.EscapeString(r.URL.Path))
	}))

	res, err := http.Get("http://localhost:8282/world")
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	contents, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Server responded with: %s", contents)
}

Refactor to use defer idiomatically


// Package elicit is a native go BDD testing framework using markdown for executable specifications
package elicit

import (
	"flag"
	"regexp"
)

var (
	reportFile = flag.String("elicit.report", "", "Path to save an execution report")
)

// New creates a new elicit context which stores specs, steps and transforms
func New() *Context {
	ctx := &Context{
		stepImpls:  map[*regexp.Regexp]interface{}{},
		transforms: map[*regexp.Regexp]StepArgumentTransform{},
	}

	ctx.log.ctx = ctx
	ctx.log.outpath = *reportFile

	ctx.transforms.init()

	return ctx
}

// Package elicit is a native go BDD testing framework using markdown for executable specifications
package elicit

import (
	"flag"
	"fmt"
	"path/filepath"
	"regexp"
)

var (
	reportFile = flag.String("elicit.report", "", "Path to save an execution report")
)

// New creates a new elicit context which stores specs, steps and transforms
func New() *Context {
	ctx := &Context{
		stepImpls:  map[*regexp.Regexp]interface{}{},
		transforms: map[*regexp.Regexp]StepArgumentTransform{},
	}

	ctx.log.ctx = ctx

	if *reportFile != "" {
		if reportFileAbs, err := filepath.Abs(*reportFile); err != nil {
			panic(fmt.Errorf("determining absolute path for %s: %s", *reportFile, err))
		} else {
			ctx.log.outpath = reportFileAbs
		}
	}

	ctx.transforms.init()

	return ctx
}

Fix Bug with Relative Report Paths


// GCloud - Go Packages for Cloud Services.
// Copyright (c) 2013 Garrett Woodworth (https://github.com/gwoo).

package identity

import ()

type Account struct{}

// GCloud - Go Packages for Cloud Services.
// Copyright (c) 2013 Garrett Woodworth (https://github.com/gwoo).

package identity

import ()

type Account struct {
	Key   string
	Token string
}

Add some fields to Account.


package clc

import (
	"github.com/CenturyLinkCloud/clc-sdk/aa"
	"github.com/CenturyLinkCloud/clc-sdk/alert"
	"github.com/CenturyLinkCloud/clc-sdk/api"
	"github.com/CenturyLinkCloud/clc-sdk/dc"
	"github.com/CenturyLinkCloud/clc-sdk/group"
	"github.com/CenturyLinkCloud/clc-sdk/lb"
	"github.com/CenturyLinkCloud/clc-sdk/server"
	"github.com/CenturyLinkCloud/clc-sdk/status"
)

type Client struct {
	client *api.Client

	Server *server.Service
	Status *status.Service
	AA     *aa.Service
	Alert  *alert.Service
	LB     *lb.Service
	Group  *group.Service
	DC     *dc.Service
}

func New(config api.Config) *Client {
	c := &Client{
		client: api.New(config),
	}

	c.Server = server.New(c.client)
	c.Status = status.New(c.client)
	c.AA = aa.New(c.client)
	c.Alert = alert.New(c.client)
	c.LB = lb.New(c.client)
	c.Group = group.New(c.client)
	c.DC = dc.New(c.client)

	return c
}

func (c *Client) Alias(alias string) *Client {
	c.client.Config().Alias = alias
	return c
}

Add support for using multiple aliases


package main

import "os"
import "fmt"
import "net"
import "bufio"

func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:1350")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	for {
		data, err := bufio.NewReader(conn).ReadString('\n')
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		fmt.Printf(data)
	}
}

package main

import "os"
import "fmt"
import "net"
import "bufio"
import "bytes"

import "github.com/UniversityRadioYork/ury-rapid-go/tokeniser"

func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:1350")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	t := tokeniser.NewTokeniser()
	for {
		data, err := bufio.NewReader(conn).ReadBytes('\n')
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		lines := t.Parse(data)
		buffer := new(bytes.Buffer)
		for _, line := range lines {
			for _, word := range line {
				buffer.WriteString(word + " ")
			}
			fmt.Println(buffer.String())
		}
	}
}

Print lines as they come in


package dockercommand

import (
	docker "github.com/fsouza/go-dockerclient"
	"os"
)

type Docker struct {
	client *docker.Client
}

func NewDocker(endpoint string) (*Docker, error) {
	endpoint = resolveDockerEndpoint(endpoint)
	client, err := docker.NewClient(resolveDockerEndpoint(endpoint))
	if err != nil {
		return nil, err
	}
	return &Docker{client}, nil
}

func resolveDockerEndpoint(input string) string {
	if len(input) != 0 {
		return input
	}
	if len(os.Getenv("DOCKER_HOST")) != 0 {
		return os.Getenv("DOCKER_HOST")
	}
	return "unix:///var/run/docker.sock"
}

package dockercommand

import (
	"crypto/tls"
	"crypto/x509"
	"io/ioutil"
	"log"
	"net/http"
	"os"

	docker "github.com/fsouza/go-dockerclient"
)

type Docker struct {
	client *docker.Client
}

func NewDocker(endpoint string) (*Docker, error) {
	endpoint = resolveDockerEndpoint(endpoint)
	client, err := docker.NewClient(resolveDockerEndpoint(endpoint))
	if err != nil {
		return nil, err
	}

	if len(os.Getenv("DOCKER_CERT_PATH")) != 0 {
		cert, err := tls.LoadX509KeyPair(os.Getenv("DOCKER_CERT_PATH")+"/cert.pem", os.Getenv("DOCKER_CERT_PATH")+"/key.pem")
		if err != nil {
			log.Fatal(err)
		}

		caCert, err := ioutil.ReadFile(os.Getenv("DOCKER_CERT_PATH") + "/ca.pem")
		if err != nil {
			log.Fatal(err)
		}
		caCertPool := x509.NewCertPool()
		caCertPool.AppendCertsFromPEM(caCert)

		tlsConfig := &tls.Config{
			Certificates: []tls.Certificate{cert},
			RootCAs:      caCertPool,
		}
		tlsConfig.BuildNameToCertificate()
		tr := &http.Transport{
			TLSClientConfig: tlsConfig,
		}
		client.HTTPClient.Transport = tr

	}

	return &Docker{client}, nil
}

func resolveDockerEndpoint(input string) string {
	if len(input) != 0 {
		return input
	}
	if len(os.Getenv("DOCKER_HOST")) != 0 {
		return os.Getenv("DOCKER_HOST")
	}
	return "unix:///var/run/docker.sock"
}

Handle TLS with Docker 1.3+


package main

import (
    "fmt"
    "flag"
    "bufio"
    "os"
    "encoding/json"
    "github.com/gemsi/grok"
)

func main() {
    pattern := flag.String("pattern", "%{GREEDYDATA:msg}", "a grok expression")
    namedcapture := flag.Bool("namedcapture", false, "parse only named captures (default is false)")
    flag.Parse()

    var g *grok.Grok

    if *namedcapture {
      g = grok.New(grok.NAMEDCAPTURE)
    } else {
      g = grok.New();
    }

    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        line := scanner.Text()

        values, _ := g.Parse(*pattern, line)
        delete(values, "")

        encoded, _ := json.Marshal(values)
        fmt.Println(string(encoded))
    }
}

package main

import (
	"bufio"
	"encoding/json"
	"flag"
	"fmt"
	"os"

	"github.com/gemsi/grok"
)

func main() {
	pattern := flag.String("pattern", "%{GREEDYDATA:msg}", "a grok expression")
	namedcapture := flag.Bool("namedcapture", false, "parse only named captures (default is false)")
	flag.Parse()

	var g *grok.Grok

	if *namedcapture {
		g = grok.NewWithConfig(&grok.Config{NamedCapturesOnly: true})
	} else {
		g = grok.New()
	}

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := scanner.Text()

		values, _ := g.Parse(*pattern, line)
		delete(values, "")

		encoded, _ := json.Marshal(values)
		fmt.Println(string(encoded))
	}
}

Change to match the gemsi/grok New() usage update


package hdf5

// #include "hdf5.h"
//
// herr_t _go_hdf5_unsilence_errors(void) {
//   return H5Eset_auto2(H5E_DEFAULT, (H5E_auto2_t)(H5Eprint), stderr);
// }
//
// herr_t _go_hdf5_silence_errors(void) {
//   return H5Eset_auto2(H5E_DEFAULT, NULL, NULL);
// }
import "C"

import (
	"fmt"
)

// DisplayErrors enables/disables HDF5's automatic error printing
func DisplayErrors(b bool) error {
	switch b {
	case true:
		if err := h5err(C._go_hdf5_unsilence_errors()); err != nil {
			return fmt.Errorf("hdf5: could not call H5E_set_auto(): %v", err)
		}
	default:
		if err := h5err(C._go_hdf5_silence_errors()); err != nil {
			return fmt.Errorf("hdf5: could not call H5E_set_auto(): %v", err)
		}
	}
	return nil
}

func init() {
	err := DisplayErrors(false)
	if err != nil {
		panic(err.Error())
	}
}

// EOF

package hdf5

// #include "hdf5.h"
//
// herr_t _go_hdf5_unsilence_errors(void) {
//   return H5Eset_auto2(H5E_DEFAULT, (H5E_auto2_t)(H5Eprint), stderr);
// }
//
// herr_t _go_hdf5_silence_errors(void) {
//   return H5Eset_auto2(H5E_DEFAULT, NULL, NULL);
// }
import "C"

import (
	"fmt"
)

// DisplayErrors enables/disables HDF5's automatic error printing
func DisplayErrors(on bool) error {
	var err error
	if on {
		err = h5err(C._go_hdf5_unsilence_errors())
	} else {
		err = h5err(C._go_hdf5_silence_errors())
	}
	if err != nil {
		return fmt.Errorf("hdf5: could not call H5E_set_auto(): %v", err)
	}
	return nil
}

func init() {
	if err := DisplayErrors(false); err != nil {
		panic(err)
	}
}

// EOF

Replace switch on bool with if-else


// Copyright (c) 2014, Rob Thornton
// All rights reserved.
// This source code is governed by a Simplied BSD-License. Please see the
// LICENSE included in this distribution for a copy of the full license
// or, if one is not included, you may also find a copy at
// http://opensource.org/licenses/BSD-2-Clause

package comp_test

import (
	"testing"

	//	"github.com/rthornton128/calc1/comp"
)

func TestCompileFile(t *testing.T) {
	/*comp.CompileFile("c1", "(+ 5 3)")
	comp.CompileFile("c2", "(- 5 3)")
	comp.CompileFile("c3", "(- 10 2 4)")
	comp.CompileFile("c4", "(+ (+ 2 3) 3)")
	comp.CompileFile("c5", "(% (+ 2 8) 2)")
	comp.CompileFile("c6", "(/ (* 4 3) (+ 3 3))")*/
}

package comp_test

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

	"github.com/rthornton128/calc1/comp"
)

func TestInteger(t *testing.T) {
	test_handler(t, "42", "42")
}

func TestSimpleExpression(t *testing.T) {
	test_handler(t, "(+ 5 3)", "8")
}

func TestSimpleExpressionWithComments(t *testing.T) {
	test_handler(t, ";comment 1\n(* 5 3); comment 2", "15")
}

func TestComplexExpression(t *testing.T) {
	test_handler(t, "(- (* 9 (+ 2 3)) (+ (/ 20 (% 15 10)) 1))", "40")
}

func test_handler(t *testing.T, src, expected string) {
	defer tearDown()

	comp.CompileFile("test", src)

	out, err := exec.Command("gcc.exe", "-Wall", "-Wextra", "-std=c99",
		"-o test.exe", "test.c").CombinedOutput()

	if err != nil {
		t.Log(string(out))
		t.Fatal(err)
	}
	var output []byte
	output, err = exec.Command(" test.exe").Output()
	if err != nil {
		t.Fatal(err)
	}
	if string(output) != expected {
		t.Fatal("For " + src + " expected " + expected + " got " + string(output))
	}
}

func tearDown() {
	os.Remove("test.c")
	os.Remove(" test.exe")
}

Fix scan bug not properly fixed by commit 20f422c052 and add compiler tests


package main

import (
	"fmt"
	"log"
	"os"
	"bufio"

	"image"
	"image/png"
	"draw2d"
)

func saveToPngFile(filePath string, m image.Image) {
	f, err := os.Open(filePath, os.O_CREAT|os.O_WRONLY, 0600)
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}
	defer f.Close()
	b := bufio.NewWriter(f)
	err = png.Encode(b, m)
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}
	err = b.Flush()
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}
	fmt.Printf("Wrote %s OK.\n", filePath)
}

func main() {
	i := image.NewRGBA(200, 200)
	gc := draw2d.NewGraphicContext(i)
	gc.MoveTo(10.0, 10.0)
	gc.LineTo(100.0, 10.0)
	gc.Stroke()

	saveToPngFile("../../TestPath.png", i)
}

package main

import (
	"fmt"
	"log"
	"os"
	"bufio"

	"image"
	"image/png"
	"draw2d.googlecode.com/svn/trunk/draw2d/src/pkg/draw2d"
)

func saveToPngFile(filePath string, m image.Image) {
	f, err := os.Open(filePath, os.O_CREAT|os.O_WRONLY, 0600)
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}
	defer f.Close()
	b := bufio.NewWriter(f)
	err = png.Encode(b, m)
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}
	err = b.Flush()
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}
	fmt.Printf("Wrote %s OK.\n", filePath)
}

func main() {
	i := image.NewRGBA(200, 200)
	gc := draw2d.NewGraphicContext(i)
	gc.MoveTo(10.0, 10.0)
	gc.LineTo(100.0, 10.0)
	gc.Stroke()
	saveToPngFile("TestPath.png", i)
}

Modify getting started to use svn url


package main

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

const(
  LUNCHY_VERSION = "0.1.0"
)

func printUsage() {
  fmt.Printf("Lunchy %s, the friendly launchctl wrapper\n", LUNCHY_VERSION)
  fmt.Println("Usage: lunchy [start|stop|restart|list|status|install|show|edit] [options]")
}

func findPlists(path string) []string {
  result := []string{}
  files, err := ioutil.ReadDir(path)

  if err != nil {
    return result
  }

  for _, file := range files {
    if (filepath.Ext(file.Name())) == ".plist" {
      result = append(result, file.Name())
    }
  }

  return result
}

func printList() {
  path  := fmt.Sprintf("%s/Library/LaunchAgents", os.Getenv("HOME"))
  files := findPlists(path)

  for _, file := range files {
    fmt.Println(file)
  }
}

func main() {
  args := os.Args

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

  printList()
}

package main

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

const(
  LUNCHY_VERSION = "0.1.0"
)

func printUsage() {
  fmt.Printf("Lunchy %s, the friendly launchctl wrapper\n", LUNCHY_VERSION)
  fmt.Println("Usage: lunchy [start|stop|restart|list|status|install|show|edit] [options]")
}

func findPlists(path string) []string {
  result := []string{}
  files, err := ioutil.ReadDir(path)

  if err != nil {
    return result
  }

  for _, file := range files {
    if (filepath.Ext(file.Name())) == ".plist" {
      result = append(result, file.Name())
    }
  }

  return result
}

func printList() {
  path  := fmt.Sprintf("%s/Library/LaunchAgents", os.Getenv("HOME"))
  files := findPlists(path)

  for _, file := range files {
    fmt.Println(file)
  }
}

func main() {
  args := os.Args

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

  switch args[1] {
  default:
    printUsage()
    os.Exit(1)
  case "list":
    printList()
    return
  }
}

Use switch to handle user command


package sphere

import (
	"bytes"
	"encoding/gob"
	"encoding/json"
	"errors"
)

// Packet indicates the data of the message
type Packet struct {
	Success bool       `json:"success"`
	Type    PacketType `json:"type"`
	Channel string     `json:"channel,omitempty"`
	Cid     int        `json:"cid,omitempty"`
	Rid     int        `json:"rid,omitempty"`
	Error   error      `json:"error,omitempty"`
	Message *Message   `json:"message,omitempty"`
}

// ParsePacket returns Packet from bytes
func ParsePacket(data []byte) (*Packet, error) {
	var p *Packet
	if err := json.Unmarshal(data, &p); err != nil {
		return nil, errors.New("packet format is invalid")
	}
	return p, nil
}

// Packet.toJSON returns json byte array from Packet
func (p *Packet) toJSON() ([]byte, error) {
	return json.Marshal(p)
}

// Packet.toBytes returns byte array from Packet
func (p *Packet) toBytes() ([]byte, error) {
	var buf bytes.Buffer
	enc := gob.NewEncoder(&buf)
	err := enc.Encode(p)
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

package sphere

import (
	"bytes"
	"encoding/gob"
	"encoding/json"
	"errors"
)

// Packet indicates the data of the message
type Packet struct {
	Type      PacketType `json:"type"`
	Namespace string     `json:"namespace,omitempty"`
	Room      string     `json:"room,omitempty"`
	Cid       int        `json:"cid,omitempty"`
	Rid       int        `json:"rid,omitempty"`
	Error     *Error     `json:"error,omitempty"`
	Message   *Message   `json:"message,omitempty"`
	Machine   string     `json:"-"`
}

// ParsePacket returns Packet from bytes
func ParsePacket(data []byte) (*Packet, error) {
	var p *Packet
	if err := json.Unmarshal(data, &p); err != nil {
		return nil, errors.New("packet format is invalid")
	}
	return p, nil
}

// Packet.toJSON returns json byte array from Packet
func (p *Packet) toJSON() ([]byte, error) {
	return json.Marshal(p)
}

// Packet.toBytes returns byte array from Packet
func (p *Packet) toBytes() ([]byte, error) {
	var buf bytes.Buffer
	enc := gob.NewEncoder(&buf)
	err := enc.Encode(p)
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

Remove unused success and use "Error" object


package webseed

import (
	"net/url"
	"testing"

	qt "github.com/frankban/quicktest"
)

func TestTrailingPath(t *testing.T) {
	c := qt.New(t)
	test := func(parts []string, result string) {
		unescaped, err := url.QueryUnescape(trailingPath(parts[0], parts[1:]))
		if !c.Check(err, qt.IsNil) {
			return
		}
		c.Check(unescaped, qt.Equals, result)
	}
	test([]string{"a_b-c", "d + e.f"}, "a_b-c/d + e.f")
	test([]string{"a_1-b_c2", "d 3. (e, f).g"},
		"a_1-b_c2/d 3. (e, f).g",
	)
}

func TestTrailingPathForEmptyInfoName(t *testing.T) {
	qt.Check(t, trailingPath("", []string{`ノ┬─┬ノ ︵ ( \o°o)\`}), qt.Equals, "%E3%83%8E%E2%94%AC%E2%94%80%E2%94%AC%E3%83%8E+%EF%B8%B5+%28+%5Co%C2%B0o%29%5C")
	qt.Check(t, trailingPath("", []string{"hello", "world"}), qt.Equals, "hello/world")
	qt.Check(t, trailingPath("war", []string{"and", "peace"}), qt.Equals, "war/and/peace")
}

Test that empty info names are ignored in multi-file torrent webseed URLs


package integration_test

import (
	"path/filepath"

	"github.com/cloudfoundry/libbuildpack/cutlass"

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

var _ = Describe("pushing an app a second time", func() {
	const (
		DownloadRegexp = `Download \[.*/dotnet-sdk\..*\.tar\.xz\]`
		CopyRegexp     = `Copy \[.*/dotnet-sdk\..*\.tar\.xz\]`
	)

	var app *cutlass.App

	BeforeEach(func() {
		SkipUnlessUncached()

		app = cutlass.New(filepath.Join(bpDir, "fixtures", "simple_source_web_2.0"))
		app.SetEnv("BP_DEBUG", "true")
	})

	AfterEach(func() {
		PrintFailureLogs(app.Name)
		app = DestroyApp(app)
	})

	It("uses the cache for manifest dependencies", func() {
		PushAppAndConfirm(app)
		Expect(app.Stdout.String()).To(MatchRegexp(DownloadRegexp))
		Expect(app.Stdout.String()).ToNot(MatchRegexp(CopyRegexp))

		app.Stdout.Reset()
		PushAppAndConfirm(app)
		Expect(app.Stdout.String()).To(MatchRegexp(CopyRegexp))
		Expect(app.Stdout.String()).ToNot(MatchRegexp(DownloadRegexp))
	})
})

package integration_test

import (
	"path/filepath"

	"github.com/cloudfoundry/libbuildpack/cutlass"

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

var _ = Describe("pushing an app a second time", func() {
	const (
		DownloadRegexp = `Download \[.*/dotnet-sdk\..*\.tar\.xz\]`
		CopyRegexp     = `Copy \[.*/dotnet-sdk\..*\.tar\.xz\]`
	)

	var app *cutlass.App

	BeforeEach(func() {
		SkipUnlessUncached()

		app = cutlass.New(filepath.Join(bpDir, "fixtures", "simple_source_web_2.0"))
		app.SetEnv("BP_DEBUG", "true")
		app.Buildpacks = []string{"dotnet_core_buildpack"}
	})

	AfterEach(func() {
		PrintFailureLogs(app.Name)
		app = DestroyApp(app)
	})

	It("uses the cache for manifest dependencies", func() {
		PushAppAndConfirm(app)
		Expect(app.Stdout.String()).To(MatchRegexp(DownloadRegexp))
		Expect(app.Stdout.String()).ToNot(MatchRegexp(CopyRegexp))

		app.Stdout.Reset()
		PushAppAndConfirm(app)
		Expect(app.Stdout.String()).To(MatchRegexp(CopyRegexp))
		Expect(app.Stdout.String()).ToNot(MatchRegexp(DownloadRegexp))
	})
})

Fix bug with buildpacks field not being set


package main

import (
	"flag"
	"fmt"
	"github.com/keybase/client/go/libkb"
	bserver "github.com/keybase/kbfs/bserver"
	"log"
	"math/rand"
	"testing"
	"time"
)

var (
	BServerRemote = flag.Bool("kbfs.bserverRemote", false, "which bserver to use, local or remote")
)

func init() {
	flag.Parse()
}

func TestMain(m *testing.M) {

	log.SetFlags(log.LstdFlags | log.Lshortfile)

	libkb.G.Init()
	libkb.G.ConfigureConfig()
	libkb.G.ConfigureLogging()
	libkb.G.ConfigureSocketInfo()

	rand.Seed(time.Now().UnixNano())

	if *BServerRemote == true {
		fmt.Printf("Testing Using Remote Backend: %s\n", bserver.Config.BServerAddr)
		bserver.InitConfig("../bserver/testconfig.json")
		bserver.Config.TestNoSession = true
		bserver.StartBServer()
	}

	m.Run()
}

package main

import (
	"flag"
	"fmt"
	"log"
	"math/rand"
	"os"
	"testing"
	"time"

	"github.com/keybase/client/go/libkb"
	bserver "github.com/keybase/kbfs/bserver"
)

var (
	BServerRemote = flag.Bool("kbfs.bserverRemote", false, "which bserver to use, local or remote")
)

func init() {
	flag.Parse()
}

func TestMain(m *testing.M) {

	log.SetFlags(log.LstdFlags | log.Lshortfile)

	libkb.G.Init()
	libkb.G.ConfigureConfig()
	libkb.G.ConfigureLogging()
	libkb.G.ConfigureSocketInfo()

	rand.Seed(time.Now().UnixNano())

	if *BServerRemote == true {
		fmt.Printf("Testing Using Remote Backend: %s\n", bserver.Config.BServerAddr)
		bserver.InitConfig("../bserver/testconfig.json")
		bserver.Config.TestNoSession = true
		bserver.StartBServer()
	}

	os.Exit(m.Run())
}

Call os.Exit() with m.Run()'s return value


package handler

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

	"github.com/yuuki/dynamond/log"
)

func JSON(w http.ResponseWriter, status int, v interface{}) error {
	res, err := json.Marshal(v)
	if err != nil {
		return err
	}

	w.WriteHeader(status)
	w.Header().Set("Content-Type", "application/json")
	w.Write(res)
	return nil
}

func BadRequest(w http.ResponseWriter, msg string) {
	log.Println(msg)

	var data struct {
		Error  string `json:"error"`
	}
	data.Error = msg
	JSON(w, http.StatusBadRequest, data)
	return
}

func NotFound(w http.ResponseWriter) {
	http.Error(w, "404 Not Found", http.StatusNotFound)
}

func ServerError(w http.ResponseWriter, msg string) {
	log.Println(msg)

	var data struct {
		Error  string `json:"error"`
	}
	data.Error = msg
	JSON(w, http.StatusInternalServerError, data)
	return
}

package handler

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

	"github.com/yuuki/dynamond/log"
)

func JSON(w http.ResponseWriter, status int, v interface{}) {
	res, err := json.Marshal(v)
	if err != nil {
		ServerError(w, err.Error())
		return
	}

	w.WriteHeader(status)
	w.Header().Set("Content-Type", "application/json")
	w.Write(res)
}

func BadRequest(w http.ResponseWriter, msg string) {
	log.Println(msg)

	var data struct {
		Error  string `json:"error"`
	}
	data.Error = msg
	JSON(w, http.StatusBadRequest, data)
	return
}

func NotFound(w http.ResponseWriter) {
	http.Error(w, "404 Not Found", http.StatusNotFound)
}

func ServerError(w http.ResponseWriter, msg string) {
	log.Println(msg)

	var data struct {
		Error  string `json:"error"`
	}
	data.Error = msg
	JSON(w, http.StatusInternalServerError, data)
	return
}

Add handling errors of json marshal


package websocket

import (
	"net/http"

	"github.com/gorilla/websocket"
	"github.com/spring1843/chat-server/src/chat"
	"github.com/spring1843/chat-server/src/shared/logs"
)

var (
	chatServerInstance *chat.Server
	upgrader           = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
)

// Handler is a http handler function that implements WebSocket
func Handler(w http.ResponseWriter, r *http.Request) {
	logs.Infof("Call to websocket /wp form %s", r.RemoteAddr)
	chatConnection := NewChatConnection()
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		logs.ErrIfErrf(err, "Error upgrading websocket connection.")
		return
	}
	chatConnection.Connection = conn
	go chatServerInstance.ReceiveConnection(chatConnection)
	go chatConnection.writePump()
	chatConnection.readPump()
	logs.Infof("End of call to websocket /wp form %s", r.RemoteAddr)
}

// SetWebSocket sets the chat server instance
func SetWebSocket(chatServerParam *chat.Server) {
	chatServerInstance = chatServerParam
}

package websocket

import (
	"net/http"

	"github.com/gorilla/websocket"
	"github.com/spring1843/chat-server/src/chat"
	"github.com/spring1843/chat-server/src/shared/logs"
)

var (
	chatServerInstance *chat.Server
	upgrader           = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin:     checkOrigin,
	}
)

// TODO validate CORS headers here
func checkOrigin(r *http.Request) bool {
	return true
}

// Handler is a http handler function that implements WebSocket
func Handler(w http.ResponseWriter, r *http.Request) {
	logs.Infof("Call to websocket /wp form %s", r.RemoteAddr)
	chatConnection := NewChatConnection()
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		logs.ErrIfErrf(err, "Error upgrading websocket connection.")
		return
	}
	chatConnection.Connection = conn
	go chatServerInstance.ReceiveConnection(chatConnection)
	go chatConnection.writePump()
	chatConnection.readPump()
	logs.Infof("End of call to websocket /wp form %s", r.RemoteAddr)
}

// SetWebSocket sets the chat server instance
func SetWebSocket(chatServerParam *chat.Server) {
	chatServerInstance = chatServerParam
}

Check http origin for Websocket


/*	MEL app backend

	Author:		Alastair Hughes
	Contact:	<hobbitalastair at yandex dot com>
*/

package main

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

// Handle a single HTTP request.
func MELHandler(writer http.ResponseWriter, request *http.Request) {

	fmt.Printf("Handling request for %q\n", html.EscapeString(request.URL.Path))

	name, password, ok := request.BasicAuth()
	if !ok {
		writer.WriteHeader(401) // Auth required
		return
	}
	if name != "" || password != "" {
		// TODO: Implement checking against the db.
		writer.WriteHeader(403) // Invalid auth
		return
	}

	fmt.Fprintf(writer, "%q: authenticated as %s\n",
		html.EscapeString(request.URL.Path), name)
}

func main() {
	http.ListenAndServe(":8080", http.HandlerFunc(MELHandler))
}

// vim: sw=4 ts=4 noexpandtab

/*
MEL app backend.

Author:		Alastair Hughes
Contact:	<hobbitalastair at yandex dot com>
*/

package main

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

// Handle a single HTTP request.
func Handle(writer http.ResponseWriter, request *http.Request) {

	fmt.Printf("Handling request for %q\n", html.EscapeString(request.URL.Path))

	// Authenticate.
	name, password, ok := request.BasicAuth()
	if !ok {
		http.Error(writer, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		return
	}
	if name != "" || password != "" {
		// TODO: Implement checking against the db.
		http.Error(writer, http.StatusText(http.StatusForbidden), http.StatusForbidden)
		return
	}
	fmt.Fprintf(writer, "%q: authenticated as %s\n",
		html.EscapeString(request.URL.Path), name)

	// Parse the URL and return the corresponding value.
}

func main() {
	http.ListenAndServe(":8080", http.HandlerFunc(Handle))
}

// vim: sw=4 ts=4 noexpandtab

Rewrite to use http.* for errors, fix function style


package main

const daemonBinary = "dockerd"

// DaemonProxy acts as a cli.Handler to proxy calls to the daemon binary
type DaemonProxy struct{}

// NewDaemonProxy returns a new handler
func NewDaemonProxy() DaemonProxy {
	return DaemonProxy{}
}

// Command returns a cli command handler if one exists
func (p DaemonProxy) Command(name string) func(...string) error {
	return map[string]func(...string) error{
		"daemon": p.CmdDaemon,
	}[name]
}

Remove reflection on CLI init


// +build windows

package config

import (
	"os"
	"path/filepath"
)

func defaultDirectory() string {
	base := filepath.Base(os.Args[0])
	ext := filepath.Ext(base)

	drv := os.Getenv("SystemDrive")
	pdDir := "ProgramData"
	name := base[0 : len(base)-len(ext)]

	return filepath.Join(drv, pdDir, name, name)
}

Remove build tag from windows file.


package main

import (
	"errors"
	"fmt"
)

type ErrMalformedDB struct {
	Bucket string
}

func (e ErrMalformedDB) Error() string {
	return fmt.Sprintf("malformed database no %s bucket", e.Bucket)
}

type ErrNoService struct {
	Name string
}

func (e ErrNoService) Error() string {
	return fmt.Sprintf("no service %s found", e.Name)
}

type ErrInvalidPath struct {
	Path string
}

func (e ErrInvalidPath) Error() string {
	return fmt.Sprintf("path %s not valid", e.Path)
}

type ErrNoAlias struct {
	Alias string
}

func (e ErrNoAlias) Error() string {
	return fmt.Sprintf("no alias %s defined", e.Alias)
}

var (
	ErrInitDB           = errors.New("no services, run service init")
	ErrNoInfoBucket     = ErrMalformedDB{Bucket: "info"}
	ErrNoServicesBucket = ErrMalformedDB{Bucket: "services"}
	ErrNoPaths          = ErrMalformedDB{Bucket: "paths"}
	ErrNoServiceSet     = errors.New("no service set, use 'rest service use <service>' to set the current service to use")
	ErrNoAliases        = errors.New("no aliases defined")
)

package main

import (
	"errors"
	"fmt"
)

type ErrMalformedDB struct {
	Bucket string
}

func (e ErrMalformedDB) Error() string {
	return fmt.Sprintf("malformed database no %s bucket, initialise a service try 'rest help service init' for init help", e.Bucket)
}

type ErrNoService struct {
	Name string
}

func (e ErrNoService) Error() string {
	return fmt.Sprintf("no service %s found", e.Name)
}

type ErrInvalidPath struct {
	Path string
}

func (e ErrInvalidPath) Error() string {
	return fmt.Sprintf("path %s not valid", e.Path)
}

type ErrNoAlias struct {
	Alias string
}

func (e ErrNoAlias) Error() string {
	return fmt.Sprintf("no alias %s defined", e.Alias)
}

var (
	ErrInitDB           = errors.New("no services, run service init")
	ErrNoInfoBucket     = ErrMalformedDB{Bucket: "info"}
	ErrNoServicesBucket = ErrMalformedDB{Bucket: "services"}
	ErrNoPaths          = ErrMalformedDB{Bucket: "paths"}
	ErrNoServiceSet     = errors.New("no service set, use 'rest service use <service>' to set the current service to use")
	ErrNoAliases        = errors.New("no aliases defined")
)

Improve malformed db error messages


package main

import (
	"fmt"
	"net/http"

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

func fetchLicenseList() ([]github.License, error) {
	// Create default client
	client := github.NewClient(nil)

	// Fetch list of LICENSE from Github API
	list, res, err := client.Licenses.List()
	if err != nil {
		return nil, err
	}

	if res.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("invalid status code from GitHub\n %s\n", res.String())
	}

	return list, nil
}

// fetchLicense fetches LICENSE file from Github API.
// if something wrong returns error.
func fetchLicense(key string) (string, error) {

	// Create default client
	client := github.NewClient(nil)

	// Fetch a LICENSE from Github API
	Debugf("Fetch license from GitHub API by key: %s", key)
	license, res, err := client.Licenses.Get(key)
	if err != nil {
		return "", err
	}

	if res.StatusCode != http.StatusOK {
		return "", fmt.Errorf("invalid status code from GitHub\n %s\n", res.String())
	}
	Debugf("Fetched license name: %s", *license.Name)

	return *license.Body, nil
}

package main

import (
	"fmt"
	"net/http"

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

func fetchLicenseList() ([]*github.License, error) {
	// Create default client
	client := github.NewClient(nil)

	// Fetch list of LICENSE from Github API
	list, res, err := client.Licenses.List()
	if err != nil {
		return nil, err
	}

	if res.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("invalid status code from GitHub\n %s\n", res.String())
	}

	return list, nil
}

// fetchLicense fetches LICENSE file from Github API.
// if something wrong returns error.
func fetchLicense(key string) (string, error) {

	// Create default client
	client := github.NewClient(nil)

	// Fetch a LICENSE from Github API
	Debugf("Fetch license from GitHub API by key: %s", key)
	license, res, err := client.Licenses.Get(key)
	if err != nil {
		return "", err
	}

	if res.StatusCode != http.StatusOK {
		return "", fmt.Errorf("invalid status code from GitHub\n %s\n", res.String())
	}
	Debugf("Fetched license name: %s", *license.Name)

	return *license.Body, nil
}

Update the type of the license list of Github API


// 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 signal

import (
	"syscall"
	"testing"
)

func TestSignal(t *testing.T) {
	// Send this process a SIGHUP.
	syscall.Syscall(syscall.SYS_KILL, uintptr(syscall.Getpid()), syscall.SIGHUP, 0)

	if sig := (<-Incoming).(UnixSignal); sig != 1 {
		t.Error("signal was %v, want %v", sig, 1)
	}
}

// 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 signal

import (
	"syscall"
	"testing"
)

func TestSignal(t *testing.T) {
	// Send this process a SIGHUP.
	syscall.Syscall(syscall.SYS_KILL, uintptr(syscall.Getpid()), syscall.SIGHUP, 0)

	if sig := (<-Incoming).(UnixSignal); sig != 1 {
		t.Errorf("signal was %v, want %v", sig, 1)
	}
}

Use t.Errorf for formatted error output.


package gitmediafilters

import (
	".."
	"../client"
	"io"
	"os"
)

func Smudge(writer io.Writer, sha string) error { // stdout, sha
	mediafile := gitmedia.LocalMediaPath(sha)
	reader, err := gitmediaclient.Get(mediafile)
	if err != nil {
		return &SmudgeError{sha, mediafile, err.Error()}
	}

	defer reader.Close()

	mediaWriter, err := os.Create(mediafile)
	defer mediaWriter.Close()

	if err != nil {
		return &SmudgeError{sha, mediafile, err.Error()}
	}

	multiWriter := io.MultiWriter(writer, mediaWriter)

	_, err = io.Copy(multiWriter, reader)
	if err != nil {
		return &SmudgeError{sha, mediafile, err.Error()}
	}

	return nil
}

type SmudgeError struct {
	Sha          string
	Filename     string
	ErrorMessage string
}

func (e *SmudgeError) Error() string {
	return e.ErrorMessage
}

package gitmediafilters

import (
	".."
	"../client"
	"io"
	"os"
)

func Smudge(writer io.Writer, sha string) error {
	mediafile := gitmedia.LocalMediaPath(sha)

	if stat, err := os.Stat(mediafile); err != nil || stat == nil {
		reader, err := gitmediaclient.Get(mediafile)
		if err != nil {
			return &SmudgeError{sha, mediafile, err.Error()}
		}
		defer reader.Close()

		mediaWriter, err := os.Create(mediafile)
		if err != nil {
			return &SmudgeError{sha, mediafile, err.Error()}
		}
		defer mediaWriter.Close()

		if err := copyFile(reader, writer, mediaWriter); err != nil {
			return &SmudgeError{sha, mediafile, err.Error()}
		}
	} else {
		reader, err := os.Open(mediafile)
		if err != nil {
			return &SmudgeError{sha, mediafile, err.Error()}
		}
		defer reader.Close()

		if err := copyFile(reader, writer); err != nil {
			return &SmudgeError{sha, mediafile, err.Error()}
		}
	}

	return nil
}

func copyFile(reader io.ReadCloser, writers ...io.Writer) error {
	multiWriter := io.MultiWriter(writers...)

	_, err := io.Copy(multiWriter, reader)
	return err
}

type SmudgeError struct {
	Sha          string
	Filename     string
	ErrorMessage string
}

func (e *SmudgeError) Error() string {
	return e.ErrorMessage
}

Create media file when it doesn't exist, use local copy when it does


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

// +build plan9

package rand

import (
	"context"
	"crypto/rand"
)

var defaultContextReader = &cryptoRandReader{}

type cryptoRandReader struct{}

// ReadContext implements a cancelable read.
func (r *cryptoRandReader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
	ch := make(chan struct{})
	go func() {
		n, err = rand.Reader.Read(b)
		close(ch)
	}()
	select {
	case <-ctx.Done():
		return 0, ctx.Err()
	case <-ch:
		return n, err
	}
}

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

// +build plan9 windows

package rand

import (
	"context"
	"crypto/rand"
)

var defaultContextReader = &cryptoRandReader{}

type cryptoRandReader struct{}

// ReadContext implements a cancelable read.
func (r *cryptoRandReader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
	ch := make(chan struct{})
	go func() {
		n, err = rand.Reader.Read(b)
		close(ch)
	}()
	select {
	case <-ctx.Done():
		return 0, ctx.Err()
	case <-ch:
		return n, err
	}
}

Use Go crypto/rand as rand implementation for Windows


package metrics

import (
	"testing"
	"time"
)

func Test_RegisterServer(t *testing.T) {

	metricsPort := 31111

	metricsServer := MetricsServer{}
	metricsServer.Register(metricsPort)

	cancel := make(chan bool)
	go metricsServer.Serve(cancel)

	time.AfterFunc(time.Millisecond*500, func() {
		cancel <- true
	})
}

package metrics

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

func Test_Register_ProvidesBytes(t *testing.T) {

	metricsPort := 31111

	metricsServer := MetricsServer{}
	metricsServer.Register(metricsPort)

	cancel := make(chan bool)
	go metricsServer.Serve(cancel)

	defer func() {
		cancel <- true
	}()

	retries := 10

	for i := 0; i < retries; i++ {
		req, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/metrics", metricsPort), nil)

		res, err := http.DefaultClient.Do(req)

		if err != nil {
			t.Logf("cannot get metrics, or not ready: %s", err.Error())

			time.Sleep(time.Millisecond * 100)
			continue
		}

		wantStatus := http.StatusOK
		if res.StatusCode != wantStatus {
			t.Errorf("metrics gave wrong status, want: %d, got: %d", wantStatus, res.StatusCode)
			t.Fail()
			return
		}

		if res.Body == nil {
			t.Errorf("metrics response should have a body")
			t.Fail()
			return
		}
		defer res.Body.Close()

		return
	}

	t.Errorf("unable to get expected response from metrics server")
	t.Fail()
}

Update test for metrics server


package main
import (
	"fmt"
	"goof/plugs"
	"github.com/codegangsta/cli"
	"os"
)

func main() {
	var (
		plug string
		debug bool
	)

	app := cli.NewApp()
	app.Name = "goof"
	app.Usage = "Extracts blogs from top web magazines"
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name: "plug",
			Value: "",
			Usage: "Tells which plug needs to be invoked",
			Destination: &plug,
		},
		cli.BoolFlag{
			Name: "debug",
			Usage: "Turns on the debug mode",
			Destination: &debug,
		},
	}
	app.Action = func(c *cli.Context) {
		if debug {
			os.Setenv("DEBUG", "*")
		}

		switch plug {
		case "tech-crunch":
			t := plugs.NewTechCrunch()
			posts := t.Next()

			for i := range posts {
				fmt.Printf("%s\n", posts[i].Json())
			}
			break
		default:
			panic("invalid plug name")
		}

	}
	app.Run(os.Args)
}

package main
import (
	"fmt"
	"goof/plugs"
	"github.com/codegangsta/cli"
	"os"
)

func main() {
	var (
		plug string
		debug bool
		page int
	)

	app := cli.NewApp()
	app.Name = "goof"
	app.Usage = "Extracts blogs from top web magazines"
	app.Flags = []cli.Flag{
		cli.IntFlag{
			Name: "page",
			Value: 1,
			Usage: "Tells how many pages need to be extracted",
			Destination: &page,
		},
		cli.StringFlag{
			Name: "plug",
			Value: "",
			Usage: "Tells which plug needs to be invoked",
			Destination: &plug,
		},
		cli.BoolFlag{
			Name: "debug",
			Usage: "Turns on the debug mode",
			Destination: &debug,
		},
	}
	app.Action = func(c *cli.Context) {
		if debug {
			os.Setenv("DEBUG", "*")
		}

		switch plug {
		case "tech-crunch":
			t := plugs.NewTechCrunch()

			for p := 1; p <= page; p++ {
				posts := t.Next()

				for i := range posts {
					fmt.Printf("%s\n", posts[i].Json())
				}
			}
			break
		default:
			panic("invalid plug name")
		}

	}
	app.Run(os.Args)
}

Add functionality for multiple pages


package types

import sdk "github.com/cosmos/cosmos-sdk/types"

func (disabledValidator ProposedDisableValidator) HasApprovalFrom(address sdk.AccAddress) bool {
	addrStr := address.String()
	for _, approval := range disabledValidator.Approvals {
		if approval.Address == addrStr {
			return true
		}
	}

	return false
}

func (disabledValidator ProposedDisableValidator) HasRejectDisableFrom(address sdk.AccAddress) bool {
	addrStr := address.String()
	for _, rejectDisable := range disabledValidator.RejectApprovals {
		if rejectDisable.Address == addrStr {
			return true
		}
	}

	return false
}

Add function for checking has reject disable from some account


package assets

import (
	"gnd.la/log"
	"io"
)

type cssBundler struct {
}

func (c *cssBundler) Bundle(w io.Writer, r io.Reader, opts Options) error {
	p, n, err := reducer("css", w, r)
	if err != nil {
		return err
	}
	log.Debugf("Reduced CSS size from %d to %d bytes", p, n)
	return err
}

func (c *cssBundler) Type() Type {
	return TypeCSS
}

func init() {
	RegisterBundler(&cssBundler{})
}

package assets

import (
	"io"
	"os/exec"

	"gnd.la/log"
)

var (
	cleanCSSPath, _ = exec.LookPath("cleancss")
)

type cssBundler struct {
}

func (c *cssBundler) Bundle(w io.Writer, r io.Reader, opts Options) error {
	if cleanCSSPath != "" {
		return command(cleanCSSPath, []string{"--s0"}, w, r, opts)
	}
	p, n, err := reducer("css", w, r)
	if err != nil {
		return err
	}
	log.Debugf("Reduced CSS size from %d to %d bytes", p, n)
	return err
}

func (c *cssBundler) Type() Type {
	return TypeCSS
}

func init() {
	RegisterBundler(&cssBundler{})
}

Add support for bundling CSS locally with cleancss


package errors

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

type HttpError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

var HttpErrors map[string]*HttpError = map[string]*HttpError {
	"ErrorApiKeyMandatory": &HttpError{Code: 403, Message: "apikey is mandatory"},
	"ErrorApiKeyInvalid":   &HttpError{Code: 403, Message: "given apikey is invalid"},
}

func NewHttpError(w http.ResponseWriter, err string) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("X-Content-Type-Options", "nosniff")
	w.WriteHeader(HttpErrors[err].Code)
	w.Write(HttpErrors[err].getJSON())
}

func (e *HttpError) getJSON() []byte {
	jsonError, _ := json.Marshal(e)
	return jsonError
}

package errors

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

type HttpError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

var HttpErrors map[string]*HttpError = map[string]*HttpError {
	"ErrorApiKeyMandatory": &HttpError{Code: 401, Message: "apikey is mandatory"},
	"ErrorApiKeyInvalid":   &HttpError{Code: 401,Message: "given apikey is invalid"},
}

func NewHttpError(w http.ResponseWriter, err string) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("X-Content-Type-Options", "nosniff")
	w.WriteHeader(HttpErrors[err].Code)
	w.Write(HttpErrors[err].getJSON())
}

func (e *HttpError) getJSON() []byte {
	jsonError, _ := json.Marshal(e)
	return jsonError
}

Fix wrong http code for errors


package filter

import (
	"testing"
	"time"

	"github.com/toomore/gogrs/tradingdays"
	"github.com/toomore/gogrs/twse"
)

var stock = twse.NewTWSE("2618", tradingdays.FindRecentlyOpened(time.Now()))

func TestCheckGroup(t *testing.T) {
	for i, v := range AllList {
		t.Log(i, v.No(), v.String(), v.Mindata(), v.CheckFunc(stock))
	}
}

func TestCheckGroup_String(t *testing.T) {
	for i, v := range AllList {
		t.Log(i, v.No(), v)
	}
}

package filter

import (
	"testing"
	"time"

	"github.com/toomore/gogrs/twse"
	"github.com/toomore/gogrs/utils"
)

var stocklist = []*twse.Data{
	twse.NewTWSE("2618", time.Date(2017, 4, 7, 0, 0, 0, 0, utils.TaipeiTimeZone)),
	twse.NewTWSE("2618", time.Date(2017, 3, 21, 0, 0, 0, 0, utils.TaipeiTimeZone)),
	twse.NewTWSE("1201", time.Date(2017, 3, 21, 0, 0, 0, 0, utils.TaipeiTimeZone)),
	twse.NewTWSE("4938", time.Date(2017, 3, 21, 0, 0, 0, 0, utils.TaipeiTimeZone)),
	//twse.NewTWSE("4938", time.Date(2017, time.Now().Month()+1, 21, 0, 0, 0, 0, utils.TaipeiTimeZone)),
}

func TestCheckGroup(t *testing.T) {
	for _, stock := range stocklist {
		for i, v := range AllList {
			t.Log(i, v.No(), v.String(), v.Mindata(), v.CheckFunc(stock))
		}
	}
}

func TestCheckGroup_String(t *testing.T) {
	for i, v := range AllList {
		t.Log(i, v.No(), v)
	}
}

Add more test for filter


package coinbase

type Message struct {
  Type string `json:"type"`
  TradeId int `json:"trade_id,number"`
  OrderId string `json:"order_id"`
  Sequence int `json:"sequence,number"`
  MakerOrderId string `json:"maker_order_id"`
  TakerOrderId string `json:"taker_order_id"`
  Time Time `json:"time,string"`
  RemainingSize float64 `json:"remaining_size,string"`
  NewSize float64 `json:"new_size,string"`
  OldSize float64 `json:"old_size,string"`
  Size float64 `json:"size,string"`
  Price float64 `json:"price,string"`
  Side string `json:"side"`
  Reason string `json:"reason"`
}

package coinbase

type Message struct {
  Type string `json:"type"`
  TradeId int `json:"trade_id,number"`
  OrderId string `json:"order_id"`
  Sequence int `json:"sequence,number"`
  MakerOrderId string `json:"maker_order_id"`
  TakerOrderId string `json:"taker_order_id"`
  Time Time `json:"time,string"`
  RemainingSize float64 `json:"remaining_size,string"`
  NewSize float64 `json:"new_size,string"`
  OldSize float64 `json:"old_size,string"`
  Size float64 `json:"size,string"`
  Price float64 `json:"price,string"`
  Side string `json:"side"`
  Reason string `json:"reason"`
  OrderType string `json:"order_type"`
  Funds float64 `json:"funds,string"`
  NewFunds float64 `json:"new_funds,string"`
  OldFunds float64 `json:"old_funds,string"`
}

Add new fields to Message.


// +build !jenkins

package main

import (
	"github.com/jmcvetta/neoism"
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestCreate(t *testing.T) {
	assert := assert.New(t)
	person := person{UUID: "123", Name: "Test", Identifiers: []identifier{identifier{fsAuthority, "FACTSET_ID"}}}

	db, err := neoism.Connect("http://localhost:7474/db/data")
	assert.NoError(err, "Failed to connect to Neo4j")
	peopleDriver = NewPeopleCypherDriver(db)

	assert.NoError(peopleDriver.Write(person), "Failed to write person")

	storedPerson, found, err := peopleDriver.Read("123")

	assert.NoError(err, "Error finding person")
	assert.True(found, "Didn't find person")
	assert.Equal(person, storedPerson, "people should be the same")
}

Tag tests that require a local neo4j instance to not run for tests run for: go test -tags jenkins


package state_machine

import "strings"

type State struct {
	State           string
	StateChangeLogs []StateChangeLog
}

func (state *State) SetState(name string) {
	state.State = name
}

func (state *State) GetState() string {
	return state.State
}

func (s *State) UnmarshalJSON(data []byte) error {
	s.SetState(strings.Trim(string(data), "\""))

	return nil
}

package state_machine

import "strings"

type State struct {
	State           string
	StateChangeLogs []StateChangeLog `sql:"-"`
}

func (state *State) SetState(name string) {
	state.State = name
}

func (state *State) GetState() string {
	return state.State
}

func (s *State) UnmarshalJSON(data []byte) error {
	s.SetState(strings.Trim(string(data), "\""))

	return nil
}

Save save StateChangeLog from embedded structs


package funcs

import (
	"fmt"

	"github.com/sacloud/usacloud/command"
	"github.com/sacloud/usacloud/command/params"
)

func PrivateHostCreate(ctx command.Context, params *params.CreatePrivateHostParam) error {

	client := ctx.GetAPIClient()
	api := client.GetPrivateHostAPI()
	p := api.New()

	// set params

	p.SetName(params.Name)
	p.SetDescription(params.Description)
	p.SetTags(params.Tags)
	p.SetIconByID(params.IconId)

	// set plan(There have only one plan now)
	plans, err := client.Product.GetProductPrivateHostAPI().Find()
	if err != nil || len(plans.PrivateHostPlans) == 0 {
		return fmt.Errorf("PrivateHostCreate is failed: can't find any private-host plan %s", err)
	}
	p.SetPrivateHostPlanByID(plans.PrivateHostPlans[0].ID)

	// call Create(id)
	res, err := api.Create(p)
	if err != nil {
		return fmt.Errorf("PrivateHostCreate is failed: %s", err)
	}

	return ctx.GetOutput().Print(res)

}

package funcs

import (
	"fmt"

	"github.com/sacloud/usacloud/command"
	"github.com/sacloud/usacloud/command/params"
)

func PrivateHostCreate(ctx command.Context, params *params.CreatePrivateHostParam) error {

	client := ctx.GetAPIClient()
	api := client.GetPrivateHostAPI()
	p := api.New()

	// set params

	p.SetName(params.Name)
	p.SetDescription(params.Description)
	p.SetTags(params.Tags)
	p.SetIconByID(params.IconId)

	// set plan(There have only one plan now)
	plans, err := client.Product.GetProductPrivateHostAPI().FilterBy("Class", "dynamic").Find()
	if err != nil || len(plans.PrivateHostPlans) == 0 {
		return fmt.Errorf("PrivateHostCreate is failed: can't find any private-host plan %s", err)
	}
	p.SetPrivateHostPlanByID(plans.PrivateHostPlans[0].ID)

	// call Create(id)
	res, err := api.Create(p)
	if err != nil {
		return fmt.Errorf("PrivateHostCreate is failed: %s", err)
	}

	return ctx.GetOutput().Print(res)

}

Use filtering parameter at ProductPrivateHost API


package rfc3797

import (
	"math"
)

func main() {

}

func Entropy(n int, p int) int {
	i := 0
	result := 0.0

	// These cases represent invalid input values.
	if (n < 1) || (n >= p) {
		return 0.0
	}

	for i = p; i > (p - n); i-- {
		result += math.Log(float64(i))
	}

	for i = n; i > 1; i-- {
		result -= math.Log(float64(i))
	}

	// Convert to the number of bits required.
	result /= math.Log(float64(2))

	// Return the number of bits reqr'd.
	return int(math.Ceil(result))
}

package rfc3797

import (
	"math"
)

func main() {

}

func usage() {

}

func Entropy(n int, p int) int {
	i := 0
	result := 0.0

	// These cases represent invalid input values.
	if (n < 1) || (n >= p) {
		return 0
	}

	for i = p; i > (p - n); i-- {
		result += math.Log(float64(i))
	}

	for i = n; i > 1; i-- {
		result -= math.Log(float64(i))
	}

	// Convert to the number of bits required.
	result /= math.Log(float64(2))

	// Return the number of bits reqr'd.
	return int(math.Ceil(result))
}

Return value for degenerate cases is more clearly not a float.


package commands

import (
	"testing"
)

func TestHelloworld(t *testing.T) {
	want := "Hello world!"
	got := "Hello world!"

	if got != want {
		t.Errorf("Expected '%v' got '%v'", want, got)
	}
}

package commands

import (
	"testing"
)

func TestHelloworld(t *testing.T) {
	want := "Hello world!"
	got := Helloworld([]string{"any string"})

	if got != want {
		t.Errorf("Expected '%v' got '%v'", want, got)
	}
}

Fix for helloworld command test


package main

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

func GetInfo(url string) map[string]interface{} {
	resp, err := http.Get(url)
	Check(err)
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	var data map[string]interface{}
	var jErr = json.Unmarshal(body, &data)
	Check(jErr)

	return data
}

func ShowInfo(args []string) {
	var url string
	if len(args) > 0 {
		url = fmt.Sprintf("https://bandwidth.waits.io/info.json?ip=%s", args[0])
	} else {
		url = "https://bandwidth.waits.io/info.json"
	}
	info := GetInfo(url)
	location := fmt.Sprintf("%s, %s", info["city"], info["country"])
	fmt.Printf("IPv4 address:\t%s\nHostname:\t%s\nLocation:\t%s\n", info["ip"], info["host"], location)
}

func ShowIp() {
	info := GetInfo("https://bandwidth.waits.io/info.json")
	fmt.Printf("%s\n", info["ip"])
}

package main

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

func GetInfo(url string) map[string]interface{} {
	resp, err := http.Get(url)
	Check(err)
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	var data map[string]interface{}
	var jErr = json.Unmarshal(body, &data)
	Check(jErr)

	return data
}

func ShowInfo(args []string) {
	var url string
	if len(args) > 0 {
		url = fmt.Sprintf("https://ntwrk.waits.io/info.json?ip=%s", args[0])
	} else {
		url = "https://ntwrk.waits.io/info.json"
	}
	info := GetInfo(url)
	var location string
	if info["city"] != nil {
		location = fmt.Sprintf("%s, %s", info["city"], info["country"])
	} else {
		location = fmt.Sprintf("%s", info["country"])
	}
	fmt.Printf("IPv4 address:\t%s\nHostname:\t%s\nLocation:\t%s\n", info["ip"], info["host"], location)
}

func ShowIp() {
	info := GetInfo("https://ntwrk.waits.io/info.json")
	fmt.Printf("%s\n", info["ip"])
}

Change API host to ntwrk.waits.io


package util

import (
	"os/exec"
	"reflect"
	"sort"
	"strings"
	"testing"
)

func TestRootNames(t *testing.T) {
	// NOTE: will fail if there are newlines in /*.
	want, err := exec.Command("ls", "/").Output()
	mustOK(err)
	wantNames := strings.Split(strings.Trim(string(want), "\n"), "\n")
	for i := range wantNames {
		wantNames[i] = "/" + wantNames[i]
	}

	names := RootNames()

	sort.Strings(wantNames)
	sort.Strings(names)

	if !reflect.DeepEqual(names, wantNames) {
		t.Errorf("RootNames() -> %s, want %s", names, wantNames)
	}
}

package util

import (
	"os/exec"
	"reflect"
	"sort"
	"strings"
	"testing"
)

func TestRootNames(t *testing.T) {
	// NOTE: will fail if there are newlines in /*.
	want, err := exec.Command("ls", "-A", "/").Output()
	mustOK(err)
	wantNames := strings.Split(strings.Trim(string(want), "\n"), "\n")
	for i := range wantNames {
		wantNames[i] = "/" + wantNames[i]
	}

	names := RootNames()

	sort.Strings(wantNames)
	sort.Strings(names)

	if !reflect.DeepEqual(names, wantNames) {
		t.Errorf("RootNames() -> %s, want %s", names, wantNames)
	}
}

Use "ls -A" to test against RootNames.


package rel

// A Pair consisting of an element and its real value.
type Pair struct {
	Element interface{}
	Value   float64
}

// MakePair evaluates the input function f at the input x and returns
// the associated (element, mass) pair.
func MakePair(f func(interface{}) float64, x interface{}) *Pair {
	return &Pair{
		Element: x,
		Value:   f(x),
	}
}

package rel

// A Pair consisting of an element and its real value.
type Pair struct {
	Element interface{}
	Value   float64
}

// NewPair creates a *Pair from the input interface and value.
func NewPair(elem interface{}, val float64) *Pair {
	return &Pair{
		Element: elem,
		Value:   val,
	}
}

Replace MakePair with NewPair constructor.


package main

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

func main() {

	http.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, "gatekeeper v0")
	})

	log.Fatal(http.ListenAndServe(":800", nil))
}

package main

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

type gatekeeper struct {
    objects map[string] struct {
        value string
        owner string
        permissions map[string]bool
    }

    owners map[string]bool
}

func(g *gatekeeper) Get(item, key string) (value string, err error) {
    err = errors.New("No Such Item or Permission Denied")

    o, ok := g.objects[item]
    if !ok {
        return
    }

    ok = o.permissions[key]
    if !ok {
        return
    }

    return o.value, nil
}

func (g *gatekeeper) Set(item, key string) (err error) {
    err = errors.New("Permission Denied")

    ok := g.owners[key]
    if !ok {
        return
    }

    v, found := g.objects[item]

    if (found && v.owner != key) {
        return
    }

    v.value = item
    g.objects[item] = v
    return nil
}

func (g * gatekeeper) AddAccess(item, key, newkey string) (err error) {
    err = errors.New("Permission Denied")

    ok := g.owners[key]
    if !ok {
        return
    }

    v, found := g.objects[item]

    if (found && v.owner != key) {
        return
    }

    v.permissions[newkey] = true
    g.objects[item] = v
    return nil
}

func (g * gatekeeper) RemoveAccess(item, key, newkey string) (err error) {
    err = errors.New("Permission Denied")

    ok := g.owners[key]
    if !ok {
        return
    }

    v, found := g.objects[item]

    if (found && v.owner != key) {
        return
    }

    v.permissions[newkey] = false
    g.objects[item] = v
    return nil
}

func main() {

	http.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, "gatekeeper v0")
	})

	log.Fatal(http.ListenAndServe(":800", nil))
}

Add the core datastructure and some items


package middleware

import (
	"github.com/labstack/echo"
	"strings"
	"net/http"
	"log"
)

func ServerInfo(pipe echo.HandlerFunc) echo.HandlerFunc{
	return func (c echo.Context) error{
		c.Response().Header().Set(echo.HeaderServer, "GoChat/1.0")
		c.Response().Header().Set("Author", "Ethan Garnier")
		return pipe(c)
	}
}

func checkCookies (pipe echo.HandlerFunc) echo.HandlerFunc{
	return func (c echo.Context) error{
		cookie, err := c.Cookie("session_id")
		if err != nil{
			if strings.Contains(err.Error(), "named cookie not present"){
				return c.String(http.StatusUnauthorized, "Seems like the cookie monster was here..\n You do not have any cookies")
			}

			log.Printf("Error: %v \n", err)
			return err

		}

		if cookie.Value == "cookie_value"{
			return pipe(c)
		}

		return c.String(http.StatusUnauthorized, "You do not have the correct cookie")
	}
}

package middleware

import (
	"github.com/labstack/echo"
	"strings"
	"net/http"
	"log"
)

func ServerInfo(pipe echo.HandlerFunc) echo.HandlerFunc{
	return func (c echo.Context) error{
		c.Response().Header().Set(echo.HeaderServer, "GoChat/1.0")
		c.Response().Header().Set("Author", "Ethan Garnier")
		return pipe(c)
	}
}

func checkCookies (pipe echo.HandlerFunc) echo.HandlerFunc{
	return func (c echo.Context) error{
		cookie, err := c.Cookie("session_id")
		if err != nil{
			if strings.Contains(err.Error(), "named cookie not present"){
				return c.String(http.StatusUnauthorized, "Seems like the cookie monster was here..\n You do not have any cookies")
			}

			log.Printf("Error: %v \n", err)
			return err

		}

		//Need to add the ability to read a users cookie value
		if cookie.Value == "cookie_value"{
			return pipe(c)
		}

		return c.String(http.StatusUnauthorized, "You do not have the correct cookie")
	}
}

Use UUID with cookie checker


package webserver

import (
    "fmt"
    "reflect"
)

/*
Interacts with urls.go to route requests to their corresponding functions.
Wires the capture groups from a url's regex to the callbacks arguments
*/

type router struct {
    *callbackHandler
}

func NewRouter() *router {
    cbh := newcallbackHandler()
    r := router{cbh}

    return &r
}

func (r *router) RegisterCallback(url string, callback interface{}) error {
    err := r.registerCallback(url, callback)
    if err != nil {
        return err
    }

    return nil
}

func (r *router) RouteRequest(url string) {
    cb, err := r.findCallback(url)
    if err != nil {
        fmt.Println(err)
    }else {
        cbV := reflect.ValueOf(cb)
        args := []reflect.Value{reflect.ValueOf(7)}
        cbV.Call(args)
    }
}

package webserver

import (
    "net/http"
    "reflect"
)

/*
Interacts with urls.go to route requests to their corresponding functions.
Wires the capture groups from a url's regex to the callbacks arguments
*/

type router struct {
    cbh *callbackHandler
}

func NewRouter() *router {
    cbh := newcallbackHandler()
    r := router{cbh}

    return &r
}

func (r *router) RegisterCallback(url string, callback interface{}) error {
    err := r.registerCallback(url, callback)
    if err != nil {
        return err
    }

    return nil
}

func (r *router) routeRequest(req *http.Request) string {
    cb, err := r.cbh.findCallback(req.URL.Path)
    if err != nil {
        fmt.Println(err)
    }else {
        cbV := reflect.ValueOf(cb)
        args := []reflect.Value{reflect.ValueOf(7)}
        cbV.Call(args)
    }
}

Refactor to remove embedded urls struct


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

package container

import (
	"launchpad.net/juju-core/environs"
	"launchpad.net/juju-core/environs/config"
	"launchpad.net/juju-core/state"
	"launchpad.net/juju-core/state/api"
)

// A Container represents a containerized virtual machine.
type Container interface {
	Name() string
	Instance() environs.Instance
	Create(
		series, nonce string,
		tools *state.Tools,
		environConfig *config.Config,
		stateInfo *state.Info,
		apiInfo *api.Info) error
	Start() error
	Stop() error
	Destroy() error
}

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

package container

import (
	"launchpad.net/juju-core/environs/config"
	"launchpad.net/juju-core/instance"
	"launchpad.net/juju-core/state"
	"launchpad.net/juju-core/state/api"
)

// A Container represents a containerized virtual machine.
type Container interface {
	instance.Instance
	Create(
		series, nonce string,
		tools *state.Tools,
		environConfig *config.Config,
		stateInfo *state.Info,
		apiInfo *api.Info) error
	Start() error
	Stop() error
	Destroy() error
}

Make a Container contain an instance.Instance.