package hoverfly_test

import (
	"bytes"
	"encoding/json"
	"io/ioutil"

	"github.com/SpectoLabs/hoverfly/functional-tests"
	"github.com/dghubble/sling"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("/api/v2/simulation/schema", func() {

	var (
		hoverfly *functional_tests.Hoverfly
	)

	BeforeEach(func() {
		hoverfly = functional_tests.NewHoverfly()
		hoverfly.Start()
	})

	AfterEach(func() {
		hoverfly.Stop()
	})

	Context("GET", func() {

		It("Should get the JSON schema", func() {
			req := sling.New().Get("http://localhost:" + hoverfly.GetAdminPort() + "/api/v2/simulation/schema")
			res := functional_tests.DoRequest(req)
			Expect(res.StatusCode).To(Equal(200))

			fileBytes, _ := ioutil.ReadFile("../../schema.json")
			fileBuffer := new(bytes.Buffer)
			json.Compact(fileBuffer, fileBytes)

			responseJson, err := ioutil.ReadAll(res.Body)
			Expect(err).To(BeNil())

			Expect(responseJson).To(Equal(fileBuffer.Bytes()))
		})
	})
})

package hoverfly_test

import (
	"bytes"
	"encoding/json"
	"io/ioutil"

	"github.com/SpectoLabs/hoverfly/functional-tests"
	"github.com/dghubble/sling"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("/api/v2/simulation/schema", func() {

	var (
		hoverfly *functional_tests.Hoverfly
	)

	BeforeEach(func() {
		hoverfly = functional_tests.NewHoverfly()
		hoverfly.Start()
	})

	AfterEach(func() {
		hoverfly.Stop()
	})

	Context("GET", func() {

		It("Should get the JSON schema", func() {
			req := sling.New().Get("http://localhost:" + hoverfly.GetAdminPort() + "/api/v2/simulation/schema")
			res := functional_tests.DoRequest(req)
			Expect(res.StatusCode).To(Equal(200))

			fileBytes, err := ioutil.ReadFile("../../schema.json")
			Expect(err).To(BeNil(), "schema.json not found")

			fileBuffer := new(bytes.Buffer)
			json.Compact(fileBuffer, fileBytes)

			responseJson, err := ioutil.ReadAll(res.Body)
			Expect(err).To(BeNil())

			Expect(responseJson).To(Equal(fileBuffer.Bytes()))
		})
	})
})

Update functional test to error correctly if a needed file is missing


/*
Copyright 2018 The Kubernetes Authors.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package hack

/*
Package imports dependencies required for "dep ensure" to fetch all of the go package dependencies needed
by kubebuilder commands to work without rerunning "dep ensure".

Example: make sure the testing libraries and apimachinery libraries are fetched by "dep ensure" so that
dep ensure doesn't need to be rerun after "kubebuilder create resource".

This is necessary for subsequent commands - such as building docs, tests, etc - to work without rerunning "dep ensure"
afterward.
*/
import _ "github.com/kubernetes-sigs/kubebuilder/pkg/imports"

/*
Copyright 2018 The Kubernetes Authors.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*
Package imports dependencies required for "dep ensure" to fetch all of the go package dependencies needed
by kubebuilder commands to work without rerunning "dep ensure".

Example: make sure the testing libraries and apimachinery libraries are fetched by "dep ensure" so that
dep ensure doesn't need to be rerun after "kubebuilder create resource".

This is necessary for subsequent commands - such as building docs, tests, etc - to work without rerunning "dep ensure"
afterward.
*/
package hack

import _ "github.com/kubernetes-sigs/kubebuilder/pkg/imports"

Move the package comments above package


package bowling

import "testing"

func TestGutterGame(t *testing.T) {
	game := new(Game)

	for i := 0; i < 20; i++ {
		game.Roll(0)
	}

	score := game.Score()

	if score != 0 {
		t.Error("Gutter game:", "Expected", 0, "was", score)
	}
}

func TestAllOnes(t *testing.T) {
	game := new(Game)

	for i := 0; i < 20; i++ {
		game.Roll(1)
	}

	score := game.Score()

	if score != 20 {
		t.Error("All ones:", "Expected", 20, "was", score)
	}
}

package bowling

import "testing"

func (g *Game) RollMany(runs int, pins int) {
	for i := 0; i < runs; i++ {
		g.Roll(pins)
	}
}

func TestGutterGame(t *testing.T) {
	game := new(Game)
	game.RollMany(20, 0)
	score := game.Score()

	if score != 0 {
		t.Error("Gutter game:", "Expected", 0, "was", score)
	}
}

func TestAllOnes(t *testing.T) {
	game := new(Game)
	game.RollMany(20, 1)
	score := game.Score()

	if score != 20 {
		t.Error("All ones:", "Expected", 20, "was", score)
	}
}

Refactor test to provide `RollMany` function


package hostpool

import (
	"github.com/bitly/go-hostpool"
)

func ExampleNewEpsilonGreedy() {
	hp := hostpool.NewEpsilonGreedy([]string{"a", "b"}, 0, &hostpool.LinearEpsilonValueCalculator{})
	hostResponse := hp.Get()
	hostname := hostResponse.Host()
	err := nil // (make a request with hostname)
	hostResponse.Mark(err)
}

package hostpool_test

import (
	"github.com/bitly/go-hostpool"
)

func ExampleNewEpsilonGreedy() {
	hp := hostpool.NewEpsilonGreedy([]string{"a", "b"}, 0, &hostpool.LinearEpsilonValueCalculator{})
	hostResponse := hp.Get()
	_ = hostResponse.Host()
	hostResponse.Mark(nil)
}

Fix import cycle and build error


package refmt_test

import (
	"bytes"
	"fmt"

	"github.com/polydawn/refmt"
	"github.com/polydawn/refmt/obj/atlas"
)

func ExampleJsonEncodeDefaults() {
	type MyType struct {
		X string
		Y int
	}

	MyType_AtlasEntry := atlas.BuildEntry(MyType{}).
		StructMap().Autogenerate().
		Complete()

	atl := atlas.MustBuild(
		MyType_AtlasEntry,
		// this is a vararg... stack more entries here!
	)

	var buf bytes.Buffer
	encoder := refmt.NewAtlasedJsonEncoder(&buf, atl)
	err := encoder.Marshal(MyType{"a", 1})
	fmt.Println(buf.String())
	fmt.Printf("%v\n", err)

	// Output:
	// {"x":"a","y":1}
	// <nil>
}

package refmt_test

import (
	"bytes"
	"fmt"

	"github.com/polydawn/refmt"
	"github.com/polydawn/refmt/obj/atlas"
)

func ExampleJsonEncodeAtlasDefaults() {
	type MyType struct {
		X string
		Y int
	}

	MyType_AtlasEntry := atlas.BuildEntry(MyType{}).
		StructMap().Autogenerate().
		Complete()

	atl := atlas.MustBuild(
		MyType_AtlasEntry,
		// this is a vararg... stack more entries here!
	)

	var buf bytes.Buffer
	encoder := refmt.NewAtlasedJsonEncoder(&buf, atl)
	err := encoder.Marshal(MyType{"a", 1})
	fmt.Println(buf.String())
	fmt.Printf("%v\n", err)

	// Output:
	// {"x":"a","y":1}
	// <nil>
}

func ExampleJsonEncodeAtlasCustom() {
	type MyType struct {
		X string
		Y int
	}

	MyType_AtlasEntry := atlas.BuildEntry(MyType{}).
		StructMap().
		AddField("X", atlas.StructMapEntry{SerialName: "overrideName"}).
		// and no "Y" mapping at all!
		Complete()

	atl := atlas.MustBuild(
		MyType_AtlasEntry,
		// this is a vararg... stack more entries here!
	)

	var buf bytes.Buffer
	encoder := refmt.NewAtlasedJsonEncoder(&buf, atl)
	err := encoder.Marshal(MyType{"a", 1})
	fmt.Println(buf.String())
	fmt.Printf("%v\n", err)

	// Output:
	// {"overrideName":"a"}
	// <nil>
}

Add example of building your own struct mapping atlas, with details.


// Copyright 2016 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package prometheus

import "time"

// Observer is the interface that wraps the Observe method, used by Histogram
// and Summary to add observations.
type Observer interface {
	Observe(float64)
}

type Timer struct {
	begin    time.Time
	observer Observer
	gauge    Gauge
}

func StartTimer() *Timer {
	return &Timer{begin: time.Now()}
}

func (t *Timer) With(o Observer) *Timer {
	t.observer = o
	return t
}

func (t *Timer) WithGauge(g Gauge) *Timer {
	t.gauge = g
	return t
}

func (t *Timer) Stop() {
	if t.observer != nil {
		t.observer.Observe(time.Since(t.begin).Seconds())
	}
	if t.gauge != nil {
		t.gauge.Set(time.Since(t.begin).Seconds())
	}
}

// Copyright 2016 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package prometheus

import "time"

// Observer is the interface that wraps the Observe method, used by Histogram
// and Summary to add observations.
type Observer interface {
	Observe(float64)
}

type observerFunc func(float64)

func (o observerFunc) Observe(value float64) {
	o(value)
}

type Timer struct {
	begin    time.Time
	observer Observer
}

func StartTimer() *Timer {
	return &Timer{begin: time.Now()}
}

func (t *Timer) With(o Observer) *Timer {
	t.observer = o
	return t
}

func (t *Timer) WithGauge(g Gauge) *Timer {
	t.observer = observerFunc(g.Set)
	return t
}

func (t *Timer) Stop() {
	if t.observer != nil {
		t.observer.Observe(time.Since(t.begin).Seconds())
	}
}

Add observerFunc to observe with a Gauge


package main

import (
	"fmt"
	"time"

	"net/url"

	"code.cloudfoundry.org/cli/cf/api/resources"
	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
	"code.cloudfoundry.org/cli/cf/models"
	"code.cloudfoundry.org/cli/cf/net"
)

type EventRepo struct {
	config  coreconfig.Reader
	gateway net.Gateway
}

func NewEventRepo(config coreconfig.Repository, gateway net.Gateway) (repo EventRepo) {
	repo.config = config
	repo.gateway = gateway
	return
}

func (r EventRepo) GetAppEvents(app models.Application, since time.Time, callback func(models.EventFields) bool) error {
	return r.gateway.ListPaginatedResources(
		r.config.APIEndpoint(),
		fmt.Sprintf("/v2/events?q=actee:%s&q=timestamp%3E%s", app.GUID, url.QueryEscape(since.Format(time.RFC3339))),
		resources.EventResourceNewV2{},
		func(resource interface{}) bool {
			return callback(resource.(resources.EventResourceNewV2).ToFields())
		})
}

package main

import (
	"fmt"
	"time"

	"net/url"

	"code.cloudfoundry.org/cli/cf/api/resources"
	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
	"code.cloudfoundry.org/cli/cf/models"
	"code.cloudfoundry.org/cli/cf/net"
)

type EventRepo struct {
	config  coreconfig.Reader
	gateway net.Gateway
}

func NewEventRepo(config coreconfig.Repository, gateway net.Gateway) (repo EventRepo) {
	repo.config = config
	repo.gateway = gateway
	return
}

func (r EventRepo) GetAppEvents(app models.Application, since time.Time, callback func(models.EventFields) bool) error {
	return r.gateway.ListPaginatedResources(
		r.config.APIEndpoint(),
		fmt.Sprintf("/v2/events?q=actee:%s&q=timestamp%s", app.GUID, url.QueryEscape(">"+since.Format(time.RFC3339))),
		resources.EventResourceNewV2{},
		func(resource interface{}) bool {
			return callback(resource.(resources.EventResourceNewV2).ToFields())
		})
}

Fix string formatting in URL path


package charts

import "bytes"

type ChartType string

const (
	UnknownChart ChartType = "UnknownChart"
	SimpleBar    ChartType = "SimpleBar"
	SimpleLine   ChartType = "SimpleLine"
)

type DataType string

type DataTypes []DataType

const (
	UnknownType DataType = "UnknownType"
	Text        DataType = "Text"
	Number      DataType = "Number"
	Time        DataType = "Time"
)

var charts map[string]ChartType

func sequence(types DataTypes) string {
	var seq bytes.Buffer

	for _, t := range types {
		seq.WriteString(t.String())
	}

	return seq.String()
}

func Detect(types DataTypes) ChartType {
	if chart, ok := charts[sequence(types)]; ok {
		return chart
	}

	return UnknownChart
}

func (ct ChartType) String() string {
	return string(ct)
}

func (t DataType) String() string {
	return string(t)
}

func init() {
	charts = make(map[string]ChartType)

	charts[sequence(DataTypes{Text, Number})] = SimpleBar
	charts[sequence(DataTypes{Number, Number})] = SimpleBar
	charts[sequence(DataTypes{Time, Number})] = SimpleLine
}

package charts

import "bytes"

type ChartType int

const (
	UnknownChart ChartType = iota
	SimpleBar
	SimpleLine
)

type DataType int

type DataTypes []DataType

const (
	UnknownType DataType = iota
	Text
	Number
	Time
)

var charts map[string]ChartType

func sequence(types DataTypes) string {
	var seq bytes.Buffer

	for _, t := range types {
		seq.WriteString(t.String())
	}

	return seq.String()
}

func Detect(types DataTypes) ChartType {
	if chart, ok := charts[sequence(types)]; ok {
		return chart
	}

	return UnknownChart
}

func (ct ChartType) String() string {
	switch ct {
	case SimpleBar:
		return "SimpleBar"
	case SimpleLine:
		return "SimpleLine"
	}

	return "UnknownChart"
}

func (t DataType) String() string {
	switch t {
	case Text:
		return "Text"
	case Number:
		return "Number"
	case Time:
		return "Time"
	}

	return "Unknown"
}

func init() {
	charts = make(map[string]ChartType)

	charts[sequence(DataTypes{Text, Number})] = SimpleBar
	charts[sequence(DataTypes{Number, Number})] = SimpleBar
	charts[sequence(DataTypes{Time, Number})] = SimpleLine
}

Revert "Use string as underlining data type"


package main

import (
	"github.com/cburkert/go-statusbar/reporters/battery"
	"github.com/cburkert/go-statusbar/reporters/volume"
)

func main() {
	statusBar := NewStatusBar(" | ")
	statusBar.AddReporter(volume.NewVolumeReporter())
	statusBar.AddReporter(battery.NewPowerReporter("/sys/class/power_supply/"))
	statusBar.AddReporter(&DateReporter{"Mon 02 Ý 15:04"})
	statusBar.Run()
}

package main

import (
	"github.com/cburkert/go-statusbar/reporters/battery"
	"github.com/cburkert/go-statusbar/reporters/volume"
)

func main() {
	statusBar := NewStatusBar(" | ")
	statusBar.AddReporter(volume.NewVolumeReporter())
	statusBar.AddReporter(battery.NewPowerReporter("/sys/class/power_supply/"))
	statusBar.AddReporter(NewDateReporter("Mon 02 Ý 15:04"))
	statusBar.Run()
}

Use creator function for DateReporter


package hugolib

const Version = "0.13-DEV"

var (
	CommitHash string
	BuildDate  string
)

var hugoInfo *HugoInfo

// HugoInfo contains information about the current Hugo environment
type HugoInfo struct {
	Version    string
	Generator  string
	CommitHash string
	BuildDate  string
}

func init() {
	hugoInfo = &HugoInfo{
		Version:    Version,
		CommitHash: CommitHash,
		BuildDate:  BuildDate,
		Generator:  `<meta name="generator" content="Hugo ` + Version + `" />`,
	}
}

package hugolib

import (
	"html/template"
)

const Version = "0.13-DEV"

var (
	CommitHash string
	BuildDate  string
)

var hugoInfo *HugoInfo

// HugoInfo contains information about the current Hugo environment
type HugoInfo struct {
	Version    string
	Generator  template.HTML
	CommitHash string
	BuildDate  string
}

func init() {
	hugoInfo = &HugoInfo{
		Version:    Version,
		CommitHash: CommitHash,
		BuildDate:  BuildDate,
		Generator:  `<meta name="generator" content="Hugo ` + Version + `" />`,
	}
}

Fix the Hugo.Generator tag so it can be used


// Package main is used for testing of generated 'views' listing.
// There is no way to include a new import dynamically, thus
// we are running this test from generate_test.go
// as a new command using exec package.
package main

import (
	"../assets/views"

	"github.com/anonx/sunplate/log"
)

func main() {
	if l := len(views.Context); l != 2 {
		log.Error.Fatalf("Length of views.Context expected to be equal to 2, it is %d instead.", l)
	}

	//
	// Make sure templates are presented in the format we expect.
	//
	for k, v := range expectedValues {
		if views.Context[k] != v {
			log.Error.Fatalf("'%s' wasn't found in %#v.", k, views.Context)
		}
	}
}

var expectedValues = map[string]string{
	"testdata/views/test1.template": "testdata/views/test1.template",
	"testdata/views/test2.template": "testdata/views/test2.template",
}

// Package main is used for testing of generated 'views' listing.
// There is no way to include a new import dynamically, thus
// we are running this test from generate_test.go
// as a new command using exec package.
package main

import (
	"../assets/views"

	"github.com/anonx/sunplate/log"
)

func main() {
	if l := len(views.Context); l != 2 {
		log.Error.Fatalf("Length of views.Context expected to be equal to 2, it is %d instead.", l)
	}

	//
	// Make sure templates are presented in the format we expect.
	//
	for k, v := range expectedValues {
		if views.Context[k] != v {
			log.Error.Fatalf("'%s' wasn't found in %#v.", k, views.Context)
		}
	}
}

var expectedValues = map[string]string{
	"test1.template": "testdata/views/test1.template",
	"test2.template": "testdata/views/test2.template",
}

Update expected results of generated liting


package wally

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

	rdb "github.com/dancannon/gorethink"
	"github.com/nylar/odlaw"
)

func GrabUrl(url string) ([]byte, error) {
	resp, err := http.Get(url)
	if err != nil {
		return []byte{}, err
	}

	data, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	if err != nil {
		return []byte{}, err
	}
	return data, nil
}

func Crawler(url string, session *rdb.Session) error {
	data, err := GrabUrl(url)
	if err != nil {
		return err
	}

	doc := odlaw.NewDocument(string(data))
	title := odlaw.ExtractTitle(doc)
	author := odlaw.ExtractAuthor(doc)
	content := odlaw.ExtractText(doc)

	d := Document{
		Source:  url,
		Title:   title,
		Author:  author,
		Content: content,
	}
	if err := d.Put(session); err != nil {
		return err
	}

	indexes := Indexer(content, d.Id)

	if _, err := rdb.Db(Database).Table(IndexTable).Insert(indexes).RunWrite(session); err != nil {
		return err
	}

	return nil
}

package wally

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

	rdb "github.com/dancannon/gorethink"
	"github.com/nylar/odlaw"
)

func GrabUrl(url string) ([]byte, error) {
	resp, err := http.Get(url)
	if err != nil {
		return []byte{}, err
	}

	data, _ := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()

	return data, nil
}

func Crawler(url string, session *rdb.Session) error {
	data, err := GrabUrl(url)
	if err != nil {
		return err
	}

	doc := odlaw.NewDocument(string(data))
	title := odlaw.ExtractTitle(doc)
	author := odlaw.ExtractAuthor(doc)
	content := odlaw.ExtractText(doc)

	d := Document{
		Source:  url,
		Title:   title,
		Author:  author,
		Content: content,
	}
	if err := d.Put(session); err != nil {
		return err
	}

	indexes := Indexer(content, d.Id)

	if _, err := rdb.Db(Database).Table(IndexTable).Insert(indexes).RunWrite(session); err != nil {
		return err
	}

	return nil
}

Remove error from ioutil.ReadAll because it's very hard to make it fail


package goDLX

// Matrix is the fundamental unit in the Algorithm X implementation
// as described in [Knuth, Donald (2000). "Dancing Links". _Millenial Perspectives in Computer Science_. P159 *187*.
// Name and size only apply to columns
type Matrix struct {
	L, R, U, D, C *Matrix
	Name          string
	size          int  // count of 1s in the column
	optional      bool // optional columns do not have to be satisfied but can be only once
	head          bool // checked for the root or head node
}

// New returns an empty matrix. This creates a single head or root node to which
// all other nodes are linked. According to the algorithm, only the left and right
// values are used for the root element.
func New() *Matrix {
	n := new(Matrix)
	n.initRoot()
	return n
}

func (r *Matrix) initRoot() {
	r.L = r
	r.R = r
	r.head = true
}

package goDLX

// Matrix is the fundamental unit in the Algorithm X implementation
// as described in [Knuth, Donald (2000). "Dancing Links". _Millenial Perspectives in Computer Science_. P159 *187*.
// Name and size only apply to columns
type Matrix struct {
	L, R, U, D, C *Matrix
	Name          string
	size          int  // count of 1s in the column
	optional      bool // optional columns do not have to be satisfied but can be only once
	head          bool // checked for the root or head node
}

// New returns an empty matrix. This creates a single head or root node to which
// all other nodes are linked. According to the algorithm, only the left and right
// values are used for the root element.
func New() *Matrix {
	r := new(Matrix)
	r.initRoot()
	return r
}

func (r *Matrix) initRoot() {
	r.L = r
	r.R = r
	r.head = true
}

Refactor `New()` for naming convention


package main

import (
  . "github.com/franela/goblin"

  "errors"
  "testing"
)

func Test(t *testing.T) {
  g := Goblin(t)

  g.Describe("Run", func() {
    extensionError := errors.New("run could not determine how to run this file because it does not have a known extension")

    g.Describe(".command_for_file", func() {
      g.Describe("when a filename is given with a known extension", func() {
        g.It("should be a valid command", func() {
          command, err := commandForFile("hello.rb")
          g.Assert(command).Equal("ruby hello.rb")
          g.Assert(err).Equal(nil)
        })
      })

      g.Describe("when a filename is given without a known extension", func() {
        g.It("should return an error", func() {
          _, err := commandForFile("hello.unknown")
          g.Assert(err).Equal(extensionError)
        })
      })

      g.Describe("when a filename is given without any extension", func() {
        g.It("should return an error", func() {
          _, err := commandForFile("hello")
          g.Assert(err).Equal(extensionError)
        })
      })
    })
  })
}

package main

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

  "errors"
  "testing"
)

func Test(t *testing.T) {
  RegisterFailHandler(Fail)
  RunSpecs(t, "Run")
}

var _ = Describe("Run", func() {
  extensionError := errors.New("run could not determine how to run this file because it does not have a known extension")

  Describe(".command_for_file", func() {
    Context("when a filename is given with a known extension", func() {
      It("should be a valid command", func() {
        command, err := commandForFile("hello.rb")
        Expect(command).To(Equal("ruby hello.rb"))
        Expect(err).To(BeNil())
      })
    })

    Context("when a filename is given without a known extension", func() {
      It("should return an error", func() {
        _, err := commandForFile("hello.unknown")
        Expect(err).To(Equal(extensionError))
      })
    })

    Context("when a filename is given without any extension", func() {
      It("should return an error", func() {
        _, err := commandForFile("hello")
        Expect(err).To(Equal(extensionError))
      })
    })
  })
})

Switch from goblin to ginkgo for testing


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

package resourceadapters

import (
	"github.com/juju/errors"
	charmresource "gopkg.in/juju/charm.v6-unstable/resource"

	"github.com/juju/juju/api"
	"github.com/juju/juju/resource/cmd"
)

// DeployResources uploads the bytes for the given files to the server and
// creates pending resource metadata for the all resource mentioned in the
// metadata. It returns a map of resource name to pending resource IDs.
func DeployResources(serviceID string, files map[string]string, resources map[string]charmresource.Meta, conn api.Connection) (ids map[string]string, err error) {
	client, err := newAPIClient(conn)
	if err != nil {
		return nil, errors.Trace(err)
	}

	ids, err = cmd.DeployResources(serviceID, files, resources, client)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return ids, nil
}

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

package resourceadapters

import (
	"github.com/juju/errors"
	"gopkg.in/juju/charm.v6-unstable"
	charmresource "gopkg.in/juju/charm.v6-unstable/resource"

	"github.com/juju/juju/api"
	"github.com/juju/juju/resource/cmd"
)

// DeployResources uploads the bytes for the given files to the server and
// creates pending resource metadata for the all resource mentioned in the
// metadata. It returns a map of resource name to pending resource IDs.
func DeployResources(serviceID string, files map[string]string, resources map[string]charmresource.Meta, conn api.Connection) (ids map[string]string, err error) {
	client, err := newAPIClient(conn)
	if err != nil {
		return nil, errors.Trace(err)
	}

	var cURL *charm.URL
	ids, err = cmd.DeployResources(cmd.DeployResourcesArgs{
		ServiceID:     serviceID,
		CharmURL:      cURL,
		Specified:     files,
		ResourcesMeta: resources,
		Client:        client,
	})
	if err != nil {
		return nil, errors.Trace(err)
	}
	return ids, nil
}

Fix the DeployResources() call args.


package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"testing"

	. "github.com/VonC/godbg"
	. "github.com/smartystreets/goconvey/convey"
)

func TestGoPanic(t *testing.T) {
	Convey("Test main", t, func() {
		fmt.Println("test main")
		files, err := ioutil.ReadDir("./tests")
		if err != nil {
			Pdbgf("Unable to access tests folder\n'%v'\n", err)
			t.Fail()
		}
		for _, file := range files {
			Pdbgf(file.Name())
			if in, err = os.Open("tests/" + file.Name()); err == nil {
				Pdbgf("ok open")
				main()
			} else {
				Pdbgf("Unable to access open file '%v'\n'%v'\n", file.Name(), err)
				t.Fail()
			}
		}
	})
}

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"testing"

	. "github.com/VonC/godbg"
	. "github.com/smartystreets/goconvey/convey"
)

func TestGoPanic(t *testing.T) {
	Convey("Test main", t, func() {
		fmt.Println("test main")
		files, err := ioutil.ReadDir("./tests")
		if err != nil {
			Pdbgf("Unable to access tests folder\n'%v'\n", err)
			t.Fail()
		}
		for _, file := range files {
			if file.Name() != "exceptionstack2" {
				continue
			}
			Pdbgf(file.Name())
			if in, err = os.Open("tests/" + file.Name()); err == nil {
				Pdbgf("ok open")
				main()
			} else {
				Pdbgf("Unable to access open file '%v'\n'%v'\n", file.Name(), err)
				t.Fail()
			}
		}
	})
}

Introduce focusing on specific test file


package api

import (
	"testing"
)

func TestValidateConfig(t *testing.T) {

	if New().validateConfig().Error() != "Modulepath must be set before starting the API server" {
		t.Error("validateConfig should return an error when the modulepath hasn't been set")
	}

	subject := New()
	subject.Config["modulepath"] = "stub modulepath"
	if subject.validateConfig() != nil {
		t.Error("validateConfig should return nil when the modulepath has been set")
	}
}

package api

import (
	"testing"
)

func TestValidateConfig(t *testing.T) {

	if New().validateConfig().Error() != "Modulepath must be set before starting the API server" {
		t.Error("validateConfig should return an error when the modulepath hasn't been set")
	}

	subject1 := New()
	subject1.Config["modulepath"] = "stub modulepath"
	subject1.Config["fileurl"] = "stub fileurl"
	if subject1.validateConfig() != nil {
		t.Error("validateConfig should return nil when the modulepath and fileurl have been set")
	}

	subject2 := New()
	subject2.Config["modulepath"] = "stub modulepath"
	if subject2.validateConfig().Error() != "Fileurl must be set before starting the API server" {
		t.Error("validateConfig should return an error when the fileurl hasn't been set")
	}

}

Add test for fileurl input validation


package main

import (
	"fmt"
	"github.com/voxelbrain/pixelpixel/pixelutils"
	"time"
)

func main() {
	wall, _ := pixelutils.PixelPusher()
	pixel := pixelutils.NewPixel()
	bigPixel := pixelutils.DimensionChanger(pixel, 5*4, 18)
	textPixel := pixelutils.NewImageWriter(bigPixel, pixelutils.Green)

	colon := ":"
	for {
		pixelutils.Empty(bigPixel)
		if colon == ":" {
			colon = " "
		} else {
			colon = ":"
		}

		textPixel.Cls()
		fmt.Fprintf(textPixel, "%02d%s%02d", time.Now().Hour(), colon, time.Now().Minute())
		wall <- pixel
		time.Sleep(500 * time.Millisecond)
	}
}

package main

import (
	"fmt"
	"github.com/voxelbrain/pixelpixel/pixelutils"
	"time"
)

func colonGenerator() <-chan string {
	c := make(chan string)
	go func() {
		for {
			c <- ":"
			c <- " "
		}
	}()
	return c
}

func main() {
	wall, _ := pixelutils.PixelPusher()
	pixel := pixelutils.NewPixel()
	bigPixel := pixelutils.DimensionChanger(pixel, 5*4, 18)
	textPixel := pixelutils.NewImageWriter(bigPixel, pixelutils.Green)

	colons := colonGenerator()
	for {
		pixelutils.Empty(bigPixel)
		textPixel.Cls()
		fmt.Fprintf(textPixel, "%02d%s%02d", time.Now().Hour(), <-colons, time.Now().Minute())
		wall <- pixel
		time.Sleep(500 * time.Millisecond)
	}
}

Use generator for clock example


package appui

import (
	"io"

	"github.com/moncho/dry/ui"
	"github.com/nsf/termbox-go"
)

//Stream shows the content of the given stream on screen
func Stream(screen *ui.Screen, stream io.ReadCloser, keyboardQueue chan termbox.Event, closeView chan<- struct{}) {
	defer func() {
		closeView <- struct{}{}
	}()
	screen.Clear()
	screen.Sync()
	v := ui.NewLess(DryTheme)
	//TODO make sure that io errors can be safely ignored
	go io.Copy(v, stream)
	if err := v.Focus(keyboardQueue); err != nil {
		ui.ShowErrorMessage(screen, keyboardQueue, closeView, err)
	}

	stream.Close()
	termbox.HideCursor()
	screen.Clear()
	screen.Sync()
}

package appui

import (
	"io"

	"github.com/docker/docker/pkg/stdcopy"
	"github.com/moncho/dry/ui"
	"github.com/nsf/termbox-go"
)

//Stream shows the content of the given stream on screen
func Stream(screen *ui.Screen, stream io.ReadCloser, keyboardQueue chan termbox.Event, closeView chan<- struct{}) {
	defer func() {
		closeView <- struct{}{}
	}()
	screen.Clear()
	screen.Sync()
	v := ui.NewLess(DryTheme)
	//TODO make sure that io errors can be safely ignored
	go stdcopy.StdCopy(v, v, stream)
	if err := v.Focus(keyboardQueue); err != nil {
		ui.ShowErrorMessage(screen, keyboardQueue, closeView, err)
	}

	stream.Close()
	termbox.HideCursor()
	screen.Clear()
	screen.Sync()
}

Use StdCopy to write logs to buffer


package index

type Index struct {
	br    *blob_reader
	Docs  map[uint32][]byte
	Attrs map[string][]IbDoc
}

func Open(name string) (*Index, error) {
	var in Index
	var err error

	in.br, err = open_blob_reader(name)
	if err != nil {
		return nil, err
	}

	in.Docs = make(map[uint32][]byte)
	for _, d := range in.br.get_documents() {
		in.Docs[d.Doc.Id] = in.br.get_document_data(&d)
	}

	in.Attrs = make(map[string][]IbDoc)
	for _, a := range in.br.get_invattrs() {
		in.Attrs[in.br.get_attr_name(&a)] = in.br.get_attr_docs(&a)
	}
	return &in, nil
}

func (in *Index) Close() {
	in.br.close()
}

package index

import (
	"bconf"
)

type Index struct {
	br    *blob_reader
	Docs  map[uint32][]byte
	Attrs map[string][]IbDoc
	Meta bconf.Bconf
	header string
}

func Open(name string) (*Index, error) {
	var in Index
	var err error

	in.br, err = open_blob_reader(name)
	if err != nil {
		return nil, err
	}

	in.Docs = make(map[uint32][]byte)
	for _, d := range in.br.get_documents() {
		in.Docs[d.Doc.Id] = in.br.get_document_data(&d)
	}

	in.Attrs = make(map[string][]IbDoc)
	for _, a := range in.br.get_invattrs() {
		in.Attrs[in.br.get_attr_name(&a)] = in.br.get_attr_docs(&a)
	}

	in.Meta.LoadJson(in.br.get_meta())

	in.Header()	// Pre-cache the header to avoid race conditions.

	return &in, nil
}

func (in Index) Header() string {
	if in.header == "" {
		in.Meta.GetNode("attr", "order").ForeachSorted(func(k, v string) {
			if in.header != "" {
				in.header += "\t"
			}
			in.header += v
		})
	}
	return in.header
}

func (in Index) Close() {
	in.br.close()
}

Implement meta by using the bconf package (separate repository).


package response

import (
	"warcluster/entities"
)

type StateChange struct {
	baseResponse
	Missions   map[string]*entities.Mission      `json:",omitempty"`
	RawPlanets map[string]*entities.Planet       `json:"-"`
	Planets    map[string]*entities.PlanetPacket `json:",omitempty"`
	Suns       map[string]*entities.Sun          `json:",omitempty"`
}

func NewStateChange() *StateChange {
	r := new(StateChange)
	r.Command = "state_change"
	return r
}

func (s *StateChange) Sanitize(player *entities.Player) {
	s.Planets = SanitizePlanets(player, s.RawPlanets)
}

package response

import (
	"warcluster/entities"
)

type StateChange struct {
	baseResponse
	Missions   map[string]*entities.Mission      `json:",omitempty"`
	RawPlanets map[string]*entities.Planet       `json:"-"`
	Planets    map[string]*entities.PlanetPacket `json:",omitempty"`
	Suns       map[string]*entities.Sun          `json:",omitempty"`
}

func NewStateChange() *StateChange {
	r := new(StateChange)
	r.Command = "state_change"
	r.Missions = make(map[string]*entities.Mission)
	r.RawPlanets = make(map[string]*entities.Planet)
	r.Planets = make(map[string]*entities.PlanetPacket)
	r.Suns = make(map[string]*entities.Sun)
	return r
}

func (s *StateChange) Sanitize(player *entities.Player) {
	s.Planets = SanitizePlanets(player, s.RawPlanets)
}

Initialize all maps in the StateChange when created


package indexing

import (
  "bytes"
  "testing"
)

var testWrites = []struct {
  docs []Document
  out string
}{
  {[]Document{},
    // Header | End of Docs
    "searchme\x00\x00"}, // terminator + doc terminator
  {[]Document{{"path", "content"}},
    // Header | Doc paths + Terminator | term + terminator + doc id (0)
    "searchme\x00path\x00\x00content\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
}

func TestWrite(t *testing.T) {
  for _, testCase := range testWrites {
    i := NewIndex()
    buf := new(bytes.Buffer)
    for _, doc := range testCase.docs {
      i.Add(doc)
    }
    i.Write(buf)

    result := string(buf.Bytes())
    if testCase.out != result {
      t.Fatalf("Expected: %q Actual %q", testCase.out, result)
    }
  }
}

package indexing

import (
  "bytes"
  "testing"
)

var testWrites = []struct {
  docs []Document
  out string
}{
  {[]Document{},
    // Header | End of Docs
    "searchme\x00\x00"}, // terminator + doc terminator
  {[]Document{{"path", "content"}},
    // Header | Doc paths + Terminator | term + terminator + doc id (0)
    "searchme\x00path\x00\x00content\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
}

func TestWrite(t *testing.T) {
  for testNum, testCase := range testWrites {
    i := NewIndex()
    buf := new(bytes.Buffer)
    for _, doc := range testCase.docs {
      i.Add(doc)
    }
    i.Write(buf)

    result := string(buf.Bytes())
    if testCase.out != result {
      t.Fatalf("%d. Expected: %q Actual %q", testNum, testCase.out, result)
    }
  }
}

Add test number to assertion


package main

import(
        "testing"
)

func TestFindURLs(t *testing.T) {
        if len(FindURLs("Wie sieht es aus wenn man http://starship-factory.ch/blah?foo=bar http://foo?baz=quux sagt?")) == 0 {
                t.Error("no urls found")
        }
        if len(FindURLs("Wie sieht es aus wenn man http://starship-factory.ch/blah?foo=bar http://foo?baz=quux sagt?")) == 0 {
                t.Error("no urls found")
        }
}

package main

import(
        "testing"
)

func TestFindURLs(t *testing.T) {
        var res []string
        var teststrings = map[string][]string{
                "Wie sieht es aus wenn man http://starship-factory.ch/blah?foo=bar sagt?":[]string{"http://starship-factory.ch/blah?foo=bar"},
                "Wie sieht es aus wenn man http://starship-factory.ch/blah?foo=bar http://foo?baz=quux sagt?":[]string{"http://starship-factory.ch/blah?foo=bar", "http://foo?baz=quux"},
                "http://starship-factory.ch/blah?foo=bar.":[]string{"http://starship-factory.ch/blah?foo=bar"},
        }
        for teststring, expected := range teststrings {
                res = FindURLs(teststring)
                if len(res) != len(expected) {
                        t.Error("Wrong number of URLs. Expected: ", expected, ", got ", res, ".")
                }
        }
}

Make it easier to add new test cases.


package godless

import (
	"errors"
	"fmt"
)

func TerminalConsole(addr string) error {
	fmt.Printf("The console should send user commands to '%v'.\n", addr)
	fmt.Println("Data found in the APIResponse should be formatted in a human readable manner.")
	fmt.Println("")
	fmt.Println("Some functions that will help:")
	fmt.Println("\tClient.SendQuery(query *Query) APIResponse")
	fmt.Println("\tCompileQuery(source string) *Query")
	fmt.Println("")
	fmt.Println("Use this terminal package:")
	fmt.Println("\tgithub.com/jroimartin/gocui")
	fmt.Println("")
	fmt.Println("Have a lot of fun!")
	fmt.Println("")

	return errors.New("not implemented")
}

package godless

import (
	"errors"
	"fmt"
)

func TerminalConsole(addr string) error {
	fmt.Printf("The console should send user commands to '%v'.\n", addr)
	fmt.Println("Data found in the APIResponse should be formatted in a human readable manner.")
	fmt.Println("")
	fmt.Println("Some functions that will help:")
	fmt.Println("\tClient.SendQuery(query *Query) (APIResponse, error)")
	fmt.Println("\tCompileQuery(source string) *Query")
	fmt.Println("")
	fmt.Println("Use this terminal package:")
	fmt.Println("\tgithub.com/jroimartin/gocui")
	fmt.Println("")
	fmt.Println("Have a lot of fun!")
	fmt.Println("")

	return errors.New("not implemented")
}

Fix a Gavin hint :)


package chuper

import (
	"net/url"

	"github.com/PuerkitoBio/fetchbot"
	"github.com/Sirupsen/logrus"
)

type Context interface {
	Cache() Cache
	Queue() Enqueuer
	Log(fields map[string]interface{}) *logrus.Entry
	URL() *url.URL
	SourceURL() *url.URL
}

type Ctx struct {
	*fetchbot.Context
	C Cache
	L *logrus.Logger
}

func (c *Ctx) Cache() Cache {
	return c.C
}

func (c *Ctx) Queue() Enqueuer {
	return &Queue{c.Q}
}

func (c *Ctx) Log(fields map[string]interface{}) *logrus.Entry {
	data := logrus.Fields{}
	for k, v := range fields {
		data[k] = v
	}
	return c.L.WithFields(data)
}

func (c *Ctx) URL() *url.URL {
	return c.Cmd.URL()
}

func (c *Ctx) SourceURL() *url.URL {
	switch cmd := c.Cmd.(type) {
	case *Cmd:
		return cmd.SourceURL()
	case *CmdBasicAuth:
		return cmd.SourceURL()
	default:
		return nil
	}
}

package chuper

import (
	"net/url"

	"github.com/PuerkitoBio/fetchbot"
	"github.com/Sirupsen/logrus"
)

type Context interface {
	Cache() Cache
	Queue() Enqueuer
	Log(fields map[string]interface{}) *logrus.Entry
	URL() *url.URL
	Method() string
	SourceURL() *url.URL
}

type Ctx struct {
	*fetchbot.Context
	C Cache
	L *logrus.Logger
}

func (c *Ctx) Cache() Cache {
	return c.C
}

func (c *Ctx) Queue() Enqueuer {
	return &Queue{c.Q}
}

func (c *Ctx) Log(fields map[string]interface{}) *logrus.Entry {
	data := logrus.Fields{}
	for k, v := range fields {
		data[k] = v
	}
	return c.L.WithFields(data)
}

func (c *Ctx) URL() *url.URL {
	return c.Cmd.URL()
}

func (c *Ctx) Method() string {
	return c.Cmd.Method()
}

func (c *Ctx) SourceURL() *url.URL {
	switch cmd := c.Cmd.(type) {
	case *Cmd:
		return cmd.SourceURL()
	case *CmdBasicAuth:
		return cmd.SourceURL()
	default:
		return nil
	}
}

Add Method to Context interface


// 13 december 2015

package ui

// #cgo LDFLAGS: -L${SRCDIR} -lui -framework CoreFoundation -lpthread
// #include <CoreFoundation/CoreFoundation.h>
// #include <pthread.h>
// extern void _CFRunLoopSetCurrent(CFRunLoopRef);
// extern pthread_t _CFMainPThread;
import "C"

// OS X cares very deeply if we don't run on the very first thread the OS creates
// why? who knows. it's stupid and completely indefensible. let's use undocumented APIs to get around it.
// apple uses them too: http://www.opensource.apple.com/source/kext_tools/kext_tools-19.2/kextd_main.c?txt
// apple HAS SUGGESTED them too: http://lists.apple.com/archives/darwin-development/2002/Sep/msg00250.html
// gstreamer uses them too: http://cgit.freedesktop.org/gstreamer/gst-plugins-good/tree/sys/osxvideo/osxvideosink.m
func ensureMainThread() {
	// TODO set to nil like the apple code?
	C._CFRunLoopSetCurrent(C.CFRunLoopGetMain())
	// TODO is this part necessary?
	C._CFMainPThread = C.pthread_self()
}

// 13 december 2015

package ui

// #cgo LDFLAGS: -L${SRCDIR} -lui -framework CoreFoundation -lpthread -rpath @executable_path
// /* (thanks to http://jorgen.tjer.no/post/2014/05/20/dt-rpath-ld-and-at-rpath-dyld/ for the @executable_path clarifiaction */
// #include <CoreFoundation/CoreFoundation.h>
// #include <pthread.h>
// extern void _CFRunLoopSetCurrent(CFRunLoopRef);
// extern pthread_t _CFMainPThread;
import "C"

// OS X cares very deeply if we don't run on the very first thread the OS creates
// why? who knows. it's stupid and completely indefensible. let's use undocumented APIs to get around it.
// apple uses them too: http://www.opensource.apple.com/source/kext_tools/kext_tools-19.2/kextd_main.c?txt
// apple HAS SUGGESTED them too: http://lists.apple.com/archives/darwin-development/2002/Sep/msg00250.html
// gstreamer uses them too: http://cgit.freedesktop.org/gstreamer/gst-plugins-good/tree/sys/osxvideo/osxvideosink.m
func ensureMainThread() {
	// TODO set to nil like the apple code?
	C._CFRunLoopSetCurrent(C.CFRunLoopGetMain())
	// TODO is this part necessary?
	C._CFMainPThread = C.pthread_self()
}

Set up rpath properly on OS X.


// Copyright (c) 2013 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 or at
// https://developers.google.com/open-source/licenses/bsd.

// golint lints the Go source files named on its command line.
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"

	"github.com/golang/lint"
)

var minConfidence = flag.Float64("min_confidence", 0.8, "minimum confidence of a problem to print it")

func main() {
	flag.Parse()

	// TODO(dsymonds): Support linting of stdin.
	for _, filename := range flag.Args() {
		lintFile(filename)
	}
}

func lintFile(filename string) {
	src, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Printf("Failed reading file: %v", err)
		return
	}

	l := new(lint.Linter)
	ps, err := l.Lint(filename, src)
	if err != nil {
		log.Printf("Failed parsing file: %v", err)
		return
	}
	for _, p := range ps {
		if p.Confidence >= *minConfidence {
			fmt.Printf("%s:%v: %s\n", filename, p.Position, p.Text)
		}
	}
}

// Copyright (c) 2013 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 or at
// https://developers.google.com/open-source/licenses/bsd.

// golint lints the Go source files named on its command line.
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"

	"github.com/golang/lint"
)

var minConfidence = flag.Float64("min_confidence", 0.8, "minimum confidence of a problem to print it")

func main() {
	flag.Parse()

	// TODO(dsymonds): Support linting of stdin.
	for _, filename := range flag.Args() {
		lintFile(filename)
	}
}

func lintFile(filename string) {
	src, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Printf("Failed reading %v: %v", filename, err)
		return
	}

	l := new(lint.Linter)
	ps, err := l.Lint(filename, src)
	if err != nil {
		log.Printf("Failed parsing %v: %v", filename, err)
		return
	}
	for _, p := range ps {
		if p.Confidence >= *minConfidence {
			fmt.Printf("%s:%v: %s\n", filename, p.Position, p.Text)
		}
	}
}

Include filename in reading/parsing errors.


//+build linux freebsd

package glfw3

//#define GLFW_EXPOSE_NATIVE_X11
//#define GLFW_EXPOSE_NATIVE_GLX
//#include <X11/extensions/Xrandr.h>
//#include "glfw/include/GLFW/glfw3.h"
//#include "glfw/include/GLFW/glfw3native.h"
import "C"

func (w *Window) GetX11Window() (C.Window, error) {
	return C.glfwGetX11Window(w.data), fetchError()
}

func (w *Window) GetGLXContext() (C.GLXContext, error) {
	return C.glfwGetGLXContext(w.data), fetchError()
}

func GetX11Display() (*C.Display, error) {
	return C.glfwGetX11Display(), fetchError()
}

// +build linux freebsd

package glfw3

//#define GLFW_EXPOSE_NATIVE_X11
//#define GLFW_EXPOSE_NATIVE_GLX
//#include <X11/extensions/Xrandr.h>
//#include "glfw/include/GLFW/glfw3.h"
//#include "glfw/include/GLFW/glfw3native.h"
import "C"

func (w *Window) GetX11Window() (C.Window, error) {
	return C.glfwGetX11Window(w.data), fetchError()
}

func (w *Window) GetGLXContext() (C.GLXContext, error) {
	return C.glfwGetGLXContext(w.data), fetchError()
}

func GetX11Display() (*C.Display, error) {
	return C.glfwGetX11Display(), fetchError()
}

Use idiomatic form for build constraints.


package v1

import (
	"net/http"
	"time"

	"github.com/codegangsta/martini"
	"github.com/coopernurse/gorp"
	"github.com/hackedu/backend/v1/model"
	"github.com/hackedu/backend/v1/route"
	"github.com/martini-contrib/binding"
	"github.com/zachlatta/cors"
)

func Setup(m *martini.ClassicMartini) {
	// TODO: Only apply middleware on /v1/** routes
	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins: true,
		AllowMethods:    []string{"GET", "POST"},
		MaxAge:          5 * time.Minute,
	}))
	m.MapTo(Dbm, (*gorp.SqlExecutor)(nil))

	m.Get("/v1/schools", route.GetSchools)

	m.Post("/v1/users", binding.Bind(model.User{}), route.AddUser)

	// OPTIONS catchall for CORS.
	m.Options("/**", func() int {
		return http.StatusOK
	})
}

package v1

import (
	"net/http"
	"time"

	"github.com/codegangsta/martini"
	"github.com/coopernurse/gorp"
	"github.com/hackedu/backend/v1/model"
	"github.com/hackedu/backend/v1/route"
	"github.com/martini-contrib/binding"
	"github.com/martini-contrib/cors"
)

func Setup(m *martini.ClassicMartini) {
	// TODO: Only apply middleware on /v1/** routes
	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins: true,
		AllowMethods:    []string{"GET", "POST"},
		MaxAge:          5 * time.Minute,
	}))
	m.MapTo(Dbm, (*gorp.SqlExecutor)(nil))

	m.Get("/v1/schools", route.GetSchools)

	m.Post("/v1/users", binding.Bind(model.User{}), route.AddUser)

	// OPTIONS catchall for CORS.
	m.Options("/**", func() int {
		return http.StatusOK
	})
}

Use github.com/martini-contrib/cors instead of github.com/zachlatta/cors.


package main

import (
  "testing"
  . "github.com/franela/goblin"
)

func Test(t *testing.T) {
  g := Goblin(t)

  g.Describe("Run", func() {
    g.Describe(".command_for_file", func() {
      g.Describe("when a filename is given with a known extension", func() {
        g.It("should be a valid command", func() {
          g.Assert(Run.command_for_file("hello.rb")).Equal("ruby hello.rb")
        })
      })

      g.Describe("when a filename is given without a known extension", func() {
        g.It("should be nil", func() {
          g.Assert(Run.command_for_file("hello.unknown")).Equal(nil)
        })
      })

      g.Describe("when a filename is given without any extension", func() {
        g.It("should be nil", func() {
          g.Assert(Run.command_for_file("hello")).Equal(nil)
        })
      })
    })
  })
}

package main

import (
  "errors"
  "testing"
  . "github.com/franela/goblin"
)

func Test(t *testing.T) {
  g := Goblin(t)

  g.Describe("Run", func() {
    g.Describe(".command_for_file", func() {
      g.Describe("when a filename is given with a known extension", func() {
        g.It("should be a valid command", func() {
          command, err := commandForFile("hello.rb")
          g.Assert(command).Equal("ruby hello.rb")
          g.Assert(err).Equal(nil)
        })
      })

      g.Describe("when a filename is given without a known extension", func() {
        g.It("should return an error", func() {
          _, err := commandForFile("hello.unknown")
          g.Assert(err).Equal(errors.New("run could not determine how to run this file because it does not have a known extension"))
        })
      })

      g.Describe("when a filename is given without any extension", func() {
        g.It("should return an error", func() {
          _, err := commandForFile("hello")
          g.Assert(err).Equal(errors.New("run could not determine how to run this file because it does not have a known extension"))
        })
      })
    })
  })
}

Update tests so they pass


package main

// scanning an HTTP response for phrases

import (
	"http"
	"mahonia.googlecode.com/hg"
)

// phrasesInResponse scans the content of an http.Response for phrases,
// and returns a map of phrases and counts.
func phrasesInResponse(res *http.Response) map[string]int {
	defer res.Body.Close()
	wr := newWordReader(res.Body, mahonia.NewDecoder("UTF-8")) // TODO: support other encodings, HTML entities
	ps := newPhraseScanner()
	ps.scanByte(' ')
	buf := make([]byte, 4096)
	for {
		n, err := wr.Read(buf)
		if err != nil {
			break
		}
		for _, c := range buf[:n] {
			ps.scanByte(c)
		}
	}
	ps.scanByte(' ')

	return ps.tally
}

package main

// scanning an HTTP response for phrases

import (
	"http"
	"mahonia.googlecode.com/hg"
	"strings"
)

// phrasesInResponse scans the content of an http.Response for phrases,
// and returns a map of phrases and counts.
func phrasesInResponse(res *http.Response) map[string]int {
	defer res.Body.Close()

	contentType := res.Header.Get("Content-Type")

	wr := newWordReader(res.Body, decoderForContentType(contentType))
	ps := newPhraseScanner()
	ps.scanByte(' ')
	buf := make([]byte, 4096)
	for {
		n, err := wr.Read(buf)
		if err != nil {
			break
		}
		for _, c := range buf[:n] {
			ps.scanByte(c)
		}
	}
	ps.scanByte(' ')

	return ps.tally
}

func decoderForContentType(t string) mahonia.Decoder {
	t = strings.ToLower(t)
	var result mahonia.Decoder

	i := strings.Index(t, "charset=")
	if i != -1 {
		charset := t[i+len("charset="):]
		i = strings.Index(charset, ";")
		if i != -1 {
			charset = charset[:i]
		}
		result = mahonia.NewDecoder(charset)
	}

	if result == nil {
		result = mahonia.FallbackDecoder(mahonia.NewDecoder("UTF-8"), mahonia.NewDecoder("windows-1252"))
	}

	if strings.Contains(t, "html") {
		result = mahonia.FallbackDecoder(mahonia.EntityDecoder(), result)
	}

	return result
}

Use charset from Content-Type header instead of assuming all pages are UTF-8.


package sys

import "runtime"

func DumpStack() string {
	buf := make([]byte, 1024)
	for runtime.Stack(buf, true) == cap(buf) {
		buf = make([]byte, cap(buf)*2)
	}
	return string(buf)
}

package sys

import "runtime"

const dumpStackBufSizeInit = 4096

func DumpStack() string {
	buf := make([]byte, dumpStackBufSizeInit)
	for {
		n := runtime.Stack(buf, true)
		if n < cap(buf) {
			return string(buf[:n])
		}
		buf = make([]byte, cap(buf)*2)
	}
}

Fix DumpStack to return the correct part of the buffer.


package prompt

import (
	"github.com/AlecAivazis/survey/v2"
	"log"
)

type Prompt interface {
	Confirm(string) bool
}

func NewPrompt() Prompt {
	return prompt{}
}

type prompt struct{}

func NewPromptContext(interactive bool, prompt Prompt) PromptContext{
	return PromptContext{
		Interactive: interactive,
		Prompt: prompt,
	}
}

type PromptContext struct {
	Interactive bool
	Prompt Prompt
}

func (p prompt) Confirm(message string) bool {
	if message == "" {
		message = "Confirm?"
	}

	confirmPrompt := &survey.Confirm{
		Default: false,
		Message: message,
	}

	confirmation := false
	err := survey.AskOne(confirmPrompt, &confirmation)
	if err != nil {
		log.Printf("error occured when getting input from user: %s", err)
		return false
	}

	return confirmation
}

package prompt

//go:generate mockgen -destination ../internal/mock/prompt/survey.go -package mock -source survey.go

import (
	"github.com/AlecAivazis/survey/v2"
	"log"
)

type Prompt interface {
	Confirm(string) bool
}

func NewPrompt() Prompt {
	return prompt{}
}

type prompt struct{}

func NewPromptContext(interactive bool, prompt Prompt) PromptContext{
	return PromptContext{
		Interactive: interactive,
		Prompt: prompt,
	}
}

type PromptContext struct {
	Interactive bool
	Prompt Prompt
}

func (p prompt) Confirm(message string) bool {
	if message == "" {
		message = "Confirm?"
	}

	confirmPrompt := &survey.Confirm{
		Default: false,
		Message: message,
	}

	confirmation := false
	err := survey.AskOne(confirmPrompt, &confirmation)
	if err != nil {
		log.Printf("error occured when getting input from user: %s", err)
		return false
	}

	return confirmation
}

Add go:generate comment to generate mock of prompt


package markdown

import (
	"io/ioutil"
	"path"
	"strings"
	"testing"
)

func TestParse(t *testing.T) {
	m := new(Markdown)
	files, _ := ioutil.ReadDir("./data")
	for _, f := range files {
		fileName := f.Name()
		filePath := path.Join("./data/", fileName)
		fileExt := path.Ext(filePath)
		if ".md" != fileExt {
			continue
		}
		markdown, _ := ioutil.ReadFile(filePath)
		input := string(markdown)

		basename := strings.Replace(fileName, fileExt, "", 1)
		htmlPath := strings.Join([]string{"./data/", basename, ".html"}, "")

		html, _ := ioutil.ReadFile(htmlPath)
		expected := string(html)

		result := m.parse(input)
		if result != expected {
			t.Errorf("'%s' expected but was '%s'.", expected, result)
		}

	}
}

package markdown

import (
	"io/ioutil"
	"path"
	"strings"
	"testing"
)

func TestParse(t *testing.T) {
	files, _ := ioutil.ReadDir("./data")
	for _, f := range files {
		fileName := f.Name()
		filePath := path.Join("./data/", fileName)
		fileExt := path.Ext(filePath)
		if ".md" != fileExt {
			continue
		}
		markdown, _ := ioutil.ReadFile(filePath)
		input := string(markdown)

		basename := strings.Replace(fileName, fileExt, "", 1)
		htmlPath := strings.Join([]string{"./data/", basename, ".html"}, "")

		html, _ := ioutil.ReadFile(htmlPath)
		expected := string(html)

		result := parse(input)
		if result != expected {
			t.Errorf("'%s' expected but was '%s'.", expected, result)
		}

	}
}

Replace method of struct with function.


package values_test

import (
	"testing"

	"github.com/xgfone/go-tools/values"
)

func TestSlice(t *testing.T) {
	ms := []interface{}{"test"}
	ss := []interface{}{11, "aa", values.SMap{"abcd": 11, "ok": false, "slice": values.Slice(ms)}, true}
	s := values.Slice(ss)

	if _, ok := s.Int(0); !ok {
		t.Fail()
	}

	if _, ok := s.String(1); !ok {
		t.Fail()
	}

	if v, ok := s.SMap(2); !ok {
		t.Fail()
	} else {
		if _, ok := v.Int("abcd"); !ok {
			t.Fail()
		}

		if _, ok := v.Bool("ok"); !ok {
			t.Fail()
		}

		if _s, ok := v.Slice("slice"); !ok {
			t.Fail()
		} else {
			if _, ok := _s.String(0); !ok {
				t.Fail()
			}
		}
	}

	if _, ok := s.Bool(3); !ok {
		t.Fail()
	}
}

package values_test

import (
	"testing"

	"github.com/xgfone/go-tools/values"
)

func TestSlice(t *testing.T) {
	ms := []interface{}{"test"}
	ss := []interface{}{11, "aa", values.SMap{"abcd": 11, "ok": false, "slice": values.Slice(ms)}, true}
	s := values.Slice(ss)

	if v, ok := s.Int(0); !ok || v != 11 {
		t.Fail()
	}

	if v, ok := s.String(1); !ok || v != "aa" {
		t.Fail()
	}

	if v, ok := s.SMap(2); !ok {
		t.Fail()
	} else {
		if vv, ok := v.Int("abcd"); !ok || vv != 11 {
			t.Fail()
		}

		if vv, ok := v.Bool("ok"); !ok || vv != false {
			t.Fail()
		}

		if _s, ok := v.Slice("slice"); !ok {
			t.Fail()
		} else {
			if v, ok := _s.String(0); !ok || v != "test" {
				t.Fail()
			}
		}
	}

	if _, ok := s.Bool(3); !ok {
		t.Fail()
	}
}

Enhance the test of values


package campfire

import (
    "fmt"
)

type Message struct {
    conn *Connection

    Id        int    `json:"id,omitempty"`
    Type      string `json:"type"`
    UserId    int    `json:"user_id,omitempty"`
    RoomId    int    `json:"room_id,omitempty"`
    Body      string `json:"body"`
    Starred   bool   `json:"starred,omitempty"`
    CreatedAt string `json:"created_at,omitempty"`
}

type MessageResult struct {
    Message *Message `json:"message"`
}

// Star favorites a message
func (m *Message) Star() error {
    return m.conn.Post(fmt.Sprintf("/messages/%d/star", m.Id), nil)
}

// Unstar unfavorites a message
func (m *Message) Unstar() error {
    return m.conn.Delete(fmt.Sprintf("/messages/%d/unstar", m.Id))
}

// Connection returns the connection bound to this message
func (m *Message) Connection() *Connection {
    return m.conn
}

Add an accessor for the connection


package neko

import (
	"github.com/julienschmidt/httprouter"
	"mime/multipart"
	"net/http"
)

type routerParams struct {
	req    *http.Request
	params httprouter.Params
}

func (c *routerParams) ByGet(name string) string {
	val := c.params.ByName(name)
	if val == "" {
		val = c.req.URL.Query().Get(name)
	}
	return val
}

func (c *routerParams) ByPost(name string) string {
	return c.req.FormValue(name)
}

func (c *routerParams) File(name string) (multipart.File, *multipart.FileHeader, error) {
	return c.req.FormFile(name)
}

package neko

import (
	"encoding/json"
	"github.com/julienschmidt/httprouter"
	"mime/multipart"
	"net/http"
	"io/ioutil"
)

type routerParams struct {
	req    *http.Request
	params httprouter.Params
}

func (c *routerParams) ByGet(name string) string {
	val := c.params.ByName(name)
	if val == "" {
		val = c.req.URL.Query().Get(name)
	}
	return val
}

func (c *routerParams) ByPost(name string) string {
	return c.req.FormValue(name)
}

func (c *routerParams) File(name string) (multipart.File, *multipart.FileHeader, error) {
	return c.req.FormFile(name)
}

func (c *routerParams) Json() *jsonParams {
	defer c.req.Body.Close()

	data, _ := ioutil.ReadAll(c.req.Body)
	objJson := &jsonParams{ data: map[string]string{}}
	objJson.source = string(data)
	json.Unmarshal(data, &objJson.data);

	return objJson
}

type jsonParams struct {
	source string
	data map[string]string
}

func (c *jsonParams) Get(name string) string {
	if len(c.data) == 0 {
		return ""
	}
	return c.data[name]
}

func (c *jsonParams) String() string {
	return c.source
}

Add parameter to get json data


package utility

import (
	"encoding/json"
	"github.com/bitspill/bitsig-go"
	"github.com/btcsuite/btcutil"
)

var utilIsTestnet bool = false

func SetTestnet(testnet bool) {
	utilIsTestnet = testnet
}

func Testnet() bool {
	return utilIsTestnet
}

func CheckAddress(address string) bool {
	var err error
	if utilIsTestnet {
		_, err = btcutil.DecodeAddress(address, &FloTestnetParams)
	} else {
		_, err = btcutil.DecodeAddress(address, &FloParams)
	}
	if err != nil {
		return false
	}
	return true
}

func CheckSignature(address string, signature string, message string) (bool, error) {
	if utilIsTestnet {
		return bitsig_go.CheckSignature(address, signature, message, "FLO", &FloTestnetParams)
	}
	return bitsig_go.CheckSignature(address, signature, message, "FLO", &FloParams)
}

// reference: Cory LaNou, Mar 2 '14 at 15:21, http://stackoverflow.com/a/22129435/2576956
func IsJSON(s string) bool {
	var js map[string]interface{}
	return json.Unmarshal([]byte(s), &js) == nil
}

package utility

import (
	"encoding/json"
	"github.com/bitspill/bitsig-go"
	"github.com/btcsuite/btcutil"
)

var utilIsTestnet bool = false

func SetTestnet(testnet bool) {
	utilIsTestnet = testnet
}

func Testnet() bool {
	return utilIsTestnet
}

func CheckAddress(address string) bool {
	var err error
	if utilIsTestnet {
		_, err = btcutil.DecodeAddress(address, &FloTestnetParams)
	} else {
		_, err = btcutil.DecodeAddress(address, &FloParams)
	}
	if err != nil {
		return false
	}
	return true
}

func CheckSignature(address string, signature string, message string) (bool, error) {
	if utilIsTestnet {
		return bitsig_go.CheckSignature(address, signature, message, "Florincoin", &FloTestnetParams)
	}
	return bitsig_go.CheckSignature(address, signature, message, "Florincoin", &FloParams)
}

// reference: Cory LaNou, Mar 2 '14 at 15:21, http://stackoverflow.com/a/22129435/2576956
func IsJSON(s string) bool {
	var js map[string]interface{}
	return json.Unmarshal([]byte(s), &js) == nil
}

Revert to v0.10 method of signature generation


package turnpike_test

import (
	"code.google.com/p/go.net/websocket"
	"github.com/jcelliott/turnpike"
	"net/http"
)

func ExampleClient_NewClient() {
	c := turnpike.NewClient()
	err := c.Connect("ws://127.0.0.1:8080/ws", "http://localhost/")
	if err != nil {
		fmt.Println("Error connecting:", err)
		return
	}

	c.Call("rpc:test")
}

package turnpike_test

import (
	"github.com/jcelliott/turnpike"
)

func ExampleClient_NewClient() {
	c := turnpike.NewClient()
	err := c.Connect("ws://127.0.0.1:8080/ws", "http://localhost/")
	if err != nil {
		panic("Error connecting:" + err.Error())
	}

	c.Call("rpc:test")
}

Simplify and fix client example


/*
package proto defines a set of structures used to negotiate an update between an
an application (the client) and an equinox update service.
*/
package proto

import "time"

type PatchKind string

const (
	PatchRaw    PatchKind = "none"
	PatchBSDIFF PatchKind = "bsdiff"
)

type Request struct {
	AppID         string `json:"app_id"`
	Channel       string `json:"channel"`
	OS            string `json:"os"`
	Arch          string `json:"arch"`
	GoARM         string `json:"goarm"`
	TargetVersion string `json:"target_version"`

	CurrentVersion string `json:"current_version"`
	CurrentSHA256  string `json:"current_sha256"`
}

type Response struct {
	Available   bool      `json:"available"`
	DownloadURL string    `json:"download_url"`
	Checksum    string    `json:"checksum"`
	Signature   string    `json:"signature"`
	Patch       PatchKind `json:"patch_type"`
	Version     string    `json:"version"`
	Release     Release   `json:"release"`
}

type Release struct {
	Title       string    `json:"title"`
	Version     string    `json:"version"`
	Description string    `json:"description"`
	CreateDate  time.Time `json:"create_date"`
}

/*
package proto defines a set of structures used to negotiate an update between an
an application (the client) and an equinox update service.
*/
package proto

import "time"

type PatchKind string

const (
	PatchRaw    PatchKind = "none"
	PatchBSDIFF PatchKind = "bsdiff"
)

type Request struct {
	AppID         string `json:"app_id"`
	Channel       string `json:"channel"`
	OS            string `json:"os"`
	Arch          string `json:"arch"`
	GoARM         string `json:"goarm"`
	TargetVersion string `json:"target_version"`

	CurrentVersion string `json:"current_version"`
	CurrentSHA256  string `json:"current_sha256"`
}

type Response struct {
	Available   bool      `json:"available"`
	DownloadURL string    `json:"download_url"`
	Checksum    string    `json:"checksum"`
	Signature   string    `json:"signature"`
	Patch       PatchKind `json:"patch_type,string"`
	Version     string    `json:"version"`
	Release     Release   `json:"release"`
}

type Release struct {
	Title       string    `json:"title"`
	Version     string    `json:"version"`
	Description string    `json:"description"`
	CreateDate  time.Time `json:"create_date"`
}

Make sure JSON scheme is a string


package executordispatch

import (
	"path/filepath"

	"polydawn.net/repeatr/def"
	"polydawn.net/repeatr/executor"
	"polydawn.net/repeatr/executor/chroot"
	"polydawn.net/repeatr/executor/nsinit"
	"polydawn.net/repeatr/executor/null"
)

// TODO: This should not require a global string -> class map :|
// Should attempt to reflect-find, trying main package name first.
// Will make simpler to use extended transports, etc.

func Get(desire string) executor.Executor {
	var executor executor.Executor

	switch desire {
	case "null":
		executor = &null.Executor{}
	case "nsinit":
		executor = &nsinit.Executor{}
	case "chroot":
		executor = &chroot.Executor{}
	default:
		panic(def.ValidationError.New("No such executor %s", desire))
	}

	// Set the base path to operate from
	executor.Configure(filepath.Join(def.Base(), "executor", desire))

	return executor
}

package executordispatch

import (
	"path/filepath"

	"polydawn.net/repeatr/def"
	"polydawn.net/repeatr/executor"
	"polydawn.net/repeatr/executor/chroot"
	"polydawn.net/repeatr/executor/nsinit"
	"polydawn.net/repeatr/executor/null"
	"polydawn.net/repeatr/executor/runc"
)

// TODO: This should not require a global string -> class map :|
// Should attempt to reflect-find, trying main package name first.
// Will make simpler to use extended transports, etc.

func Get(desire string) executor.Executor {
	var executor executor.Executor

	switch desire {
	case "null":
		executor = &null.Executor{}
	case "nsinit":
		executor = &nsinit.Executor{}
	case "chroot":
		executor = &chroot.Executor{}
	case "runc":
		executor = &runc.Executor{}
	default:
		panic(def.ValidationError.New("No such executor %s", desire))
	}

	// Set the base path to operate from
	executor.Configure(filepath.Join(def.Base(), "executor", desire))

	return executor
}

Add runc to usable executor options!


package types

import (
	"fmt"
)

type Result struct {
	Code CodeType
	Data []byte
	Log  string // Can be non-deterministic
}

func NewResult(code CodeType, data []byte, log string) Result {
	return Result{
		Code: code,
		Data: data,
		Log:  log,
	}
}

func (res Result) IsOK() bool {
	return res.Code == CodeType_OK
}

func (res Result) Error() string {
	return fmt.Sprintf("TMSP error code:%v, data:%X, log:%v", res.Code, res.Data, res.Log)
}

//----------------------------------------

func NewResultOK(data []byte, log string) Result {
	return Result{
		Code: CodeType_OK,
		Data: data,
		Log:  log,
	}
}

func NewError(code CodeType, log string) Result {
	return Result{
		Code: code,
		Log:  log,
	}
}

Add NewError -> Result with no data


package cmd

import (
	"os"

	"github.com/gsamokovarov/jump/cli"
	"github.com/gsamokovarov/jump/config"
	"github.com/gsamokovarov/jump/shell"
)

func shellCmd(args cli.Args, _ *config.Config) {
	hint := args.CommandName()
	if len(hint) == 0 {
		hint = os.Getenv("SHELL")
	}

	sh := shell.Guess(hint)

	cli.Outf("%s", sh.MustCompile("j"))
}

func init() {
	cli.RegisterCommand("shell", "Display a shell integration script.", shellCmd)
}

package cmd

import (
	"os"

	"github.com/gsamokovarov/jump/cli"
	"github.com/gsamokovarov/jump/config"
	"github.com/gsamokovarov/jump/shell"
)

func shellCmd(args cli.Args, _ *config.Config) {
	hint := args.CommandName()
	if len(hint) == 0 {
		hint = os.Getenv("SHELL")
	}

	sh := shell.Guess(hint)
	shortcut := args.Get("--shortcut", "j")

	cli.Outf("%s", sh.MustCompile(shortcut))
}

func init() {
	cli.RegisterCommand("shell", "Display a shell integration script.", shellCmd)
}

Make the shortcut configurable so @luhova can replace z


package main

import "trace"

const (
	imageW = 640
	imageH = 480
)

func createRandomImage() [][]trace.Color {
	image := make([][]trace.Color, imageH)
	for i := range image {
		image[i] = make([]trace.Color, imageW)
		for j := range image[i] {
			image[i][j].R = float64(i) / float64(imageH)
			image[i][j].G = float64(j) / float64(imageW)
			image[i][j].B = 0.0

			//log.Printf("%d %d %+v | ", i, j, image[i][j])
		}
		//log.Printf("\n")
	}
	return image
}

func main() {
	c := trace.NewContext(imageW, imageH)

	o2w := trace.NewM44()
	o2w.Translate(trace.NewV3(-2, 0, -5))/*.scale(trace.NewV3(1.0, 2.0, 1.0))*/
	c.AddPrimitive(trace.NewSphere(o2w))

	o2w = trace.NewM44()
	o2w.Translate(trace.NewV3(2, 0, -5))
	c.AddPrimitive(trace.NewTriangle(o2w))

	image := trace.Render(c)
	//image := createRandomImage()
	trace.WriteImageToPPM(image, "render")
}

package main

import "trace"

const (
	imageW = 640
	imageH = 480
)

func main() {
	c := trace.NewContext(imageW, imageH)

	o2w := trace.NewM44()
	o2w.Translate(trace.NewV3(-2, 0, -5))/*.scale(trace.NewV3(1.0, 2.0, 1.0))*/
	c.AddPrimitive(trace.NewSphere(o2w))

	o2w = trace.NewM44()
	o2w.Translate(trace.NewV3(0, 0, -5)).Scale(trace.NewV3(1, 2, 1))
	c.AddPrimitive(trace.NewSphere(o2w))

	o2w = trace.NewM44()
	o2w.Translate(trace.NewV3(2, 0, -5))
	c.AddPrimitive(trace.NewTriangle(o2w))

	image := trace.Render(c)
	trace.WriteImageToPPM(image, "render")
}

Add scaled sphere to check that works


// Generates reference files for a given language

// +build !release

package main

import "ldss/lib"

type generateReference struct {
	appinfo
}

func init() {
	addApp("generate-reference", &generateReference{})
}

func (app *generateReference) run() {
	lang, err := lib.LookupLanguage(app.args[0])
	if err != nil {
		panic(err)
	}
	app.fmt.Println(lang.String())
}

// Generates reference files for a given language

// +build !release

package main

import (
	"ldss/lib"
)

type generateReference struct {
	appinfo
}

func init() {
	addApp("generate-reference", &generateReference{})
}

func (app *generateReference) run() {
	langId := app.args[1]
	app.efmt.Println(langId)
	lang, err := lib.LookupLanguage(langId)
	if err != nil {
		panic(err)
	}
	app.efmt.Println(lang.String())
	messages := lib.DownloadAll(lang, false)
	for m := range messages {
		app.efmt.Println(m.String())
	}
	catalog, err := lang.Catalog()
	if err != nil {
		panic(err)
	}

	for _, b := range catalog.Books() {
		app.runBook(b)
	}
	for _, f := range catalog.Folders() {
		app.runFolder(f)
	}
}

func (app *generateReference) runFolder(f *lib.Folder) {
	app.fmt.Printf("%v:%v:%v\n", f.ID(), f.Name(), f.Path())
	for _, b := range f.Books() {
		app.runBook(b)
	}
	for _, f := range f.Folders() {
		app.runFolder(f)
	}
}

func (app *generateReference) runBook(b *lib.Book) {
	app.fmt.Printf("%v:%v\n", b.Name(), b.Path())
	nodes, err := b.Index()
	if err != nil {
		app.efmt.Println(err)
		return
	}
	for _, n := range nodes {
		app.runNode(n)
	}
}

func (app *generateReference) runNode(n *lib.Node) {

}

Work on generated reference files


package bencode

type Bytes []byte

var (
	_ Unmarshaler = &Bytes{}
	_ Marshaler   = &Bytes{}
)

func (me *Bytes) UnmarshalBencode(b []byte) error {
	*me = append([]byte(nil), b...)
	return nil
}

func (me *Bytes) MarshalBencode() ([]byte, error) {
	return *me, nil
}

package bencode

type Bytes []byte

var (
	_ Unmarshaler = &Bytes{}
	_ Marshaler   = &Bytes{}
	_ Marshaler   = Bytes{}
)

func (me *Bytes) UnmarshalBencode(b []byte) error {
	*me = append([]byte(nil), b...)
	return nil
}

func (me Bytes) MarshalBencode() ([]byte, error) {
	return me, nil
}

Make bencode.Bytes work with pointer and nonpointer receivers


package stringutil

import "sync"

type StringDeduplicator struct {
	lock       bool
	mutex      sync.Mutex
	mapping    map[string]string
	statistics StringDuplicationStatistics
}

type StringDuplicationStatistics struct {
	DuplicateBytes   uint64
	DuplicateStrings uint64
	UniqueBytes      uint64
	UniqueStrings    uint64
}

func NewStringDeduplicator(lock bool) *StringDeduplicator {
	return &StringDeduplicator{lock: lock, mapping: make(map[string]string)}
}

func (d *StringDeduplicator) Clear() {
	d.clear()
}

func (d *StringDeduplicator) DeDuplicate(str string) string {
	return d.deDuplicate(str)
}

func (d *StringDeduplicator) GetStatistics() StringDuplicationStatistics {
	return d.getStatistics()
}

package stringutil

import "sync"

type StringDeduplicator struct {
	lock       bool
	mutex      sync.Mutex
	mapping    map[string]string
	statistics StringDuplicationStatistics
}

type StringDuplicationStatistics struct {
	DuplicateBytes   uint64
	DuplicateStrings uint64
	UniqueBytes      uint64
	UniqueStrings    uint64
}

// NewStringDeduplicator will create a StringDeduplicator which may be used to
// eliminate duplicate string contents. It maintains an internal map of unique
// strings. If lock is true then each method call will take an exclusive lock.
func NewStringDeduplicator(lock bool) *StringDeduplicator {
	return &StringDeduplicator{lock: lock, mapping: make(map[string]string)}
}

// Clear will clear the internal map and statistics.
func (d *StringDeduplicator) Clear() {
	d.clear()
}

// DeDuplicate will return a string which has the same contents as str. This
// method should be called for every string in the application.
func (d *StringDeduplicator) DeDuplicate(str string) string {
	return d.deDuplicate(str)
}

// GetStatistics will return de-duplication statistics.
func (d *StringDeduplicator) GetStatistics() StringDuplicationStatistics {
	return d.getStatistics()
}

Add basic documentation for lib/stringutil package.


// +build js

package ninchat

import (
	"github.com/gopherjs/gopherjs/js"
)

type duration int64

const (
	second      duration = 1000
	millisecond          = 1
)

type timeTime int64

func timeNow() timeTime {
	return timeTime(js.Global.Get("Date").New().Call("getTime").Int64())
}

func timeAdd(t timeTime, d duration) timeTime {
	return t + timeTime(d)
}

func timeSub(t1, t2 timeTime) duration {
	return duration(t1 - t2)
}

type timer struct {
	C chan struct{}

	id *js.Object
}

func newTimer(timeout duration) (t *timer) {
	t = &timer{
		C: make(chan struct{}),
	}

	if timeout >= 0 {
		t.Reset(timeout)
	}

	return
}

func (timer *timer) Active() bool {
	return timer.id != nil
}

func (timer *timer) Reset(timeout duration) {
	timer.Stop()

	timer.id = js.Global.Call("setTimeout", func() {
		timer.id = nil

		go func() {
			timer.C <- struct{}{}
		}()
	}, timeout)
}

func (timer *timer) Stop() {
	if timer.id != nil {
		js.Global.Call("clearTimeout", timer.id)
		timer.id = nil
	}
}

// +build js

package ninchat

import (
	"github.com/gopherjs/gopherjs/js"
)

type duration int64

const (
	second      duration = 1000
	millisecond          = 1
)

type timeTime int64

func timeNow() timeTime {
	return timeTime(js.Global.Get("Date").New().Call("getTime").Int64())
}

func timeAdd(t timeTime, d duration) timeTime {
	return t + timeTime(d)
}

func timeSub(t1, t2 timeTime) duration {
	return duration(t1 - t2)
}

type timer struct {
	C chan struct{}

	id *js.Object
}

func newTimer(timeout duration) (t *timer) {
	t = &timer{
		C: make(chan struct{}, 1),
	}

	if timeout >= 0 {
		t.Reset(timeout)
	}

	return
}

func (timer *timer) Active() bool {
	return timer.id != nil
}

func (timer *timer) Reset(timeout duration) {
	timer.Stop()

	timer.id = js.Global.Call("setTimeout", func() {
		timer.id = nil
		timer.C <- struct{}{}
	}, timeout)
}

func (timer *timer) Stop() {
	if timer.id != nil {
		js.Global.Call("clearTimeout", timer.id)
		timer.id = nil
	}
}

Fix JavaScript timer to never leak resources


package server

import (
	"strings"

	"github.com/bmorton/deployster/fleet"
)

type ExtractableUnit fleet.Unit

func (eu *ExtractableUnit) ExtractBaseName() string {
	s := strings.Split(eu.Name, "-")
	return s[0]
}

func (eu *ExtractableUnit) ExtractVersion() string {
	s := strings.Split(eu.Name, "-")
	end := strings.Index(s[1], "@")
	return s[1][:end]
}

func (eu *ExtractableUnit) ExtractInstance() string {
	s := strings.Split(eu.Name, "@")
	end := strings.Index(s[1], ".")
	return s[1][:end]
}

package server

import (
	"strings"

	"github.com/bmorton/deployster/fleet"
)

// ExtractableUnit is the local struct for a fleet.Unit with added functions
// for extracting the name, version, and instance that deployster encodes into
// the Fleet unit name.
type ExtractableUnit fleet.Unit

// ExtractBaseName returns the name of the service from the Fleet unit name.
// Given "railsapp-cf2e8ac@1.service" this returns "railsapp"
func (eu *ExtractableUnit) ExtractBaseName() string {
	s := strings.Split(eu.Name, "-")
	return s[0]
}

// ExtractVersion returns the version of the service from the Fleet unit name.
// Given "railsapp-cf2e8ac@1.service" this returns "cf2e8ac"
func (eu *ExtractableUnit) ExtractVersion() string {
	s := strings.Split(eu.Name, "-")
	end := strings.Index(s[1], "@")
	return s[1][:end]
}

// ExtractInstance returns the instance of the service from the Fleet unit name.
// Given "railsapp-cf2e8ac@1.service" this returns "1"
func (eu *ExtractableUnit) ExtractInstance() string {
	s := strings.Split(eu.Name, "@")
	end := strings.Index(s[1], ".")
	return s[1][:end]
}

Add documentation to ExtractableUnit in the server package.


/*
Only (e.g. OnlyInt32) filters the value stream of an observable and lets
only the values of a specific type pass.

So in case of OnlyInt32 it will only let int32 values pass through.
*/
package Only

/*
Only filters the value stream of an observable and lets only the
values of a specific type pass.

So in case of OnlyInt32 it will only let int32 values pass through.
*/
package Only

Make Only operator appear correctly in pkg.go.dev


package gobrightbox

// Volume represents a Brightbox Volume
// https://api.gb1.brightbox.com/1.0/#volume
type Volume struct {
	ID          string
	Name        string
	Status      string
	Description string
	Encrypted   bool
	Size        int
	StorageType string `json:"storage_type"`
	Server      *Server
	Account     *Account
	Image       *Image
}

// VolumeOptions is used to create and update volumes
// create and update servers.
type VolumeOptions struct {
	ID    string  `json:"-"`
	Size  *int    `json:"size,omitempty"`
	Image *string `json:"image,omitempty"`
}

// VolumeResizeOptions is used to change the size of a volume
type VolumeResizeOptions struct {
	From int
	To   int
}

// ResizeVolume changes the size of a volume
func (c *Client) ResizeVolume(identifier string, options *VolumeResizeOptions) error {
	_, err := c.MakeAPIRequest("POST", "/1.0/volumes/"+identifier+"/resize", options, nil)
	return err
}

package gobrightbox

// Volume represents a Brightbox Volume
// https://api.gb1.brightbox.com/1.0/#volume
type Volume struct {
	ID          string
	Name        string
	Status      string
	Description string
	Encrypted   bool
	Size        int
	StorageType string `json:"storage_type"`
	Server      *Server
	Account     *Account
	Image       *Image
}

// VolumeOptions is used to create and update volumes
// create and update servers.
type VolumeOptions struct {
	ID    string  `json:"-"`
	Size  *int    `json:"size,omitempty"`
	Image *string `json:"image,omitempty"`
}

// VolumeResizeOptions is used to change the size of a volume
type VolumeResizeOptions struct {
	From int `json:"from"`
	To   int `json:"to"`
}

// ResizeVolume changes the size of a volume
func (c *Client) ResizeVolume(identifier string, options *VolumeResizeOptions) error {
	_, err := c.MakeAPIRequest("POST", "/1.0/volumes/"+identifier+"/resize", options, nil)
	return err
}

Add struct labels to ResizeOptions


package crawler

import (
	"net/url"
)

type Fetcher interface {
	// Fetch returns the body of URL and
	// a slice of URLs found on that page.
	Fetch(url string) (body string, urls []string, err error)
}

type Page struct {
	Url    *url.URL
	Links  []*url.URL
	Assets []string
}

type Link struct {
	Source *url.URL
	Target *url.URL
}

package crawler

import (
	"net/url"
)

type Fetcher interface {
	// Fetch returns the body of URL and
	// a slice of URLs found on that page.
	Fetch(url string) (body string, urls []string, err error)
}

type Page struct {
	Url    *url.URL
	Links  []*Link
	Assets []string
}

type Link struct {
	Source *url.URL
	Target *url.URL
}

Store links as Link type


/*
Package consts implements constants for the entire project
*/
package consts

// ConfigurationFileName is the configuration file name of Goyave
const ConfigurationFileName = ".goyave.toml"

/*
Package consts implements constants for the entire project
*/
package consts

// ConfigurationFileName is the configuration file name of Goyave
const ConfigurationFileName = ".goyave"

Change .goyave.toml file to .goyave


package v1

import "git.zxq.co/ripple/rippleapi/common"

type setAllowedData struct {
	UserID  int `json:"user_id"`
	Allowed int `json:"allowed"`
}

// UserManageSetAllowedPOST allows to set the allowed status of an user.
func UserManageSetAllowedPOST(md common.MethodData) common.CodeMessager {
	data := setAllowedData{}
	if err := md.RequestData.Unmarshal(&data); err != nil {
		return ErrBadJSON
	}
	if data.Allowed < 0 || data.Allowed > 2 {
		return common.SimpleResponse(400, "Allowed status must be between 0 and 2")
	}
	_, err := md.DB.Exec("UPDATE users SET allowed = ? WHERE id = ?", data.Allowed, data.UserID)
	if err != nil {
		md.Err(err)
		return Err500
	}
	query := `
SELECT users.id, users.username, register_datetime, rank,
	latest_activity, users_stats.username_aka,
	users_stats.country, users_stats.show_country
FROM users
LEFT JOIN users_stats
ON users.id=users_stats.id
WHERE users.id=?
LIMIT 1`
	return userPuts(md, md.DB.QueryRow(query, data.UserID))
}

package v1

import (
	"time"

	"git.zxq.co/ripple/rippleapi/common"
)

type setAllowedData struct {
	UserID  int `json:"user_id"`
	Allowed int `json:"allowed"`
}

// UserManageSetAllowedPOST allows to set the allowed status of an user.
func UserManageSetAllowedPOST(md common.MethodData) common.CodeMessager {
	data := setAllowedData{}
	if err := md.RequestData.Unmarshal(&data); err != nil {
		return ErrBadJSON
	}
	if data.Allowed < 0 || data.Allowed > 2 {
		return common.SimpleResponse(400, "Allowed status must be between 0 and 2")
	}
	var banDatetime int64
	if data.Allowed == 0 {
		banDatetime = time.Now().Unix()
	}
	_, err := md.DB.Exec("UPDATE users SET allowed = ?, ban_datetime = ? WHERE id = ?", data.Allowed, banDatetime, data.UserID)
	if err != nil {
		md.Err(err)
		return Err500
	}
	query := `
SELECT users.id, users.username, register_datetime, rank,
	latest_activity, users_stats.username_aka,
	users_stats.country, users_stats.show_country
FROM users
LEFT JOIN users_stats
ON users.id=users_stats.id
WHERE users.id=?
LIMIT 1`
	return userPuts(md, md.DB.QueryRow(query, data.UserID))
}

Update ban_datetime on allowed status change


package main

import (
	"log"
	"time"
)

var (
	onemin  = time.Minute * 1
	fivemin = time.Minute * 5
	tenmin  = time.Minute * 10
	onehour = time.Hour * 1

	oneminTimer  = time.NewTimer(onemin)
	fiveminTimer = time.NewTimer(fivemin)
	tenminTimer  = time.NewTimer(tenmin)
	onehourTimer = time.NewTimer(onehour)
)

func StartDispatcher() {
	go func() {
		for {
			select {
			case <-oneminTimer.C:
				err := ProcessCheck(onemin)
				if err != nil {
					log.Println("Failed to process checks: ", err.Error())
				}
			case <-fiveminTimer.C:
				err := ProcessCheck(fivemin)
				if err != nil {
					log.Println("Failed to process checks: ", err.Error())
				}
			case <-tenminTimer.C:
				err := ProcessCheck(tenmin)
				if err != nil {
					log.Println("Failed to process checks: ", err.Error())
				}
			case <-onehourTimer.C:
				err := ProcessCheck(onehour)
				if err != nil {
					log.Println("Failed to process checks: ", err.Error())
				}
			}
		}
	}()
}

package main

import (
	"log"
	"time"
)

var (
	onemin  = time.Minute * 1
	fivemin = time.Minute * 5
	tenmin  = time.Minute * 10
	onehour = time.Hour * 1

	oneminTicker  = time.NewTicker(onemin)
	fiveminTicker = time.NewTicker(fivemin)
	tenminTicker  = time.NewTicker(tenmin)
	onehourTicker = time.NewTicker(onehour)
)

func StartDispatcher() {
	go func() {
		for {
			select {
			case <-oneminTicker.C:
				err := ProcessCheck(onemin)
				if err != nil {
					log.Println("Failed to process checks: ", err.Error())
				}
			case <-fiveminTicker.C:
				err := ProcessCheck(fivemin)
				if err != nil {
					log.Println("Failed to process checks: ", err.Error())
				}
			case <-tenminTicker.C:
				err := ProcessCheck(tenmin)
				if err != nil {
					log.Println("Failed to process checks: ", err.Error())
				}
			case <-onehourTicker.C:
				err := ProcessCheck(onehour)
				if err != nil {
					log.Println("Failed to process checks: ", err.Error())
				}
			}
		}
	}()
}

Switch to the proper "Ticker" implementation


package markdown

import (
	"fmt"
	"strings"
	"sync"
	"testing"
	"time"
)

func TestWatcher(t *testing.T) {
	expected := "12345678"
	interval := time.Millisecond * 100
	i := 0
	out := ""
	stopChan := TickerFunc(interval, func() {
		i++
		out += fmt.Sprint(i)
	})
	// wait little more because of concurrency
	time.Sleep(interval * 9)
	stopChan <- struct{}{}
	if !strings.HasPrefix(out, expected) {
		t.Fatalf("Expected to have prefix %v, found %v", expected, out)
	}
	out = ""
	i = 0
	var mu sync.Mutex
	stopChan = TickerFunc(interval, func() {
		i++
		mu.Lock()
		out += fmt.Sprint(i)
		mu.Unlock()
	})
	time.Sleep(interval * 10)
	mu.Lock()
	res := out
	mu.Unlock()
	if !strings.HasPrefix(res, expected) || res == expected {
		t.Fatalf("expected (%v) must be a proper prefix of out(%v).", expected, out)
	}
}

package markdown

import (
	"fmt"
	"strings"
	"sync"
	"testing"
	"time"
)

func TestWatcher(t *testing.T) {
	expected := "12345678"
	interval := time.Millisecond * 100
	i := 0
	out := ""
	stopChan := TickerFunc(interval, func() {
		i++
		out += fmt.Sprint(i)
	})
	// wait little more because of concurrency
	time.Sleep(interval * 12)
	stopChan <- struct{}{}
	if !strings.HasPrefix(out, expected) {
		t.Fatalf("Expected to have prefix %v, found %v", expected, out)
	}
	out = ""
	i = 0
	var mu sync.Mutex
	stopChan = TickerFunc(interval, func() {
		i++
		mu.Lock()
		out += fmt.Sprint(i)
		mu.Unlock()
	})
	time.Sleep(interval * 15)
	mu.Lock()
	res := out
	mu.Unlock()
	if !strings.HasPrefix(res, expected) || res == expected {
		t.Fatalf("expected (%v) must be a proper prefix of out(%v).", expected, out)
	}
}

Fix race condition on AppVeyor. Increase timeout a bit.


package alice

// Module is a marker interface for structs that defines how to initialize instances.
type Module interface {
	// IsModule indicates if this is a module.
	IsModule() bool
}

// BaseModule is an implementation of Module interface. It should be embeded into each module defined in the
// application.
//
// A typical module is defined as follows:
//
//	type ExampleModule struct {
//		alice.BaseModule
//		Foo Foo `alice:""`		// associated by type
//		Bar Bar `alice:"Bar"`	// associated by name
//		URL string				// not associated. Provided by creating the module.
//	}
//
//	func (m *ExampleModule) Baz() Baz {
//		return Baz{}
//	}
type BaseModule struct{}

// IsModule indicates it is a module.
func (b *BaseModule) IsModule() bool {
	return true
}

Fix code format in documentation


package envh

import (
	"regexp"
	"testing"

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

func TestCreateTreeFromDelimiterFilteringByRegexp(t *testing.T) {
	setTestingEnvsForTree()

	n := createTreeFromDelimiterFilteringByRegexp(regexp.MustCompile("ENVH"), "_")

	for key, expected := range map[string]string{"TEST3": "test1", "TEST4": "test2", "TEST6": "test3", "TEST1": "test5", "TEST2": "test4"} {
		nodes := n.findAllChildsByKey(key, true)

		assert.Len(t, *nodes, 1, "Must contains 1 element")
		assert.Equal(t, expected, (*nodes)[0].value, "Must have correct value")
	}

	nodes := n.findAllChildsByKey("TEST2", false)

	assert.Len(t, *nodes, 2, "Must contains 2 elements")
}

package envh

import (
	"regexp"
	"testing"

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

func TestCreateTreeFromDelimiterFilteringByRegexp(t *testing.T) {
	setTestingEnvsForTree()

	n := createTreeFromDelimiterFilteringByRegexp(regexp.MustCompile("ENVH"), "_")

	for key, expected := range map[string]string{"TEST3": "test1", "TEST4": "test2", "TEST6": "test3", "TEST1": "test5", "TEST2": "test4"} {
		nodes := n.findAllChildsByKey(key, true)

		assert.Len(t, *nodes, 1, "Must contains 1 element")
		assert.Equal(t, expected, (*nodes)[0].value, "Must have correct value")
	}
}

func TestCreateTreeFromDelimiterFilteringByRegexpAndFindAllKeysWithAKey(t *testing.T) {
	setTestingEnvsForTree()

	n := createTreeFromDelimiterFilteringByRegexp(regexp.MustCompile("ENVH"), "_")

	nodes := n.findAllChildsByKey("TEST2", false)

	assert.Len(t, *nodes, 2, "Must contains 2 elements")
}

Split test function in 2 functions


package reception

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

type (
	keysAPI interface {
		Get(path string) (*etcd.Response, error)
		Set(path, value string, opts *etcd.SetOptions) error
		Watcher(path string) etcd.Watcher
	}

	etcdShim struct {
		api etcd.KeysAPI
	}
)

func (s *etcdShim) Get(path string) (*etcd.Response, error) {
	return s.api.Get(context.Background(), path, &etcd.GetOptions{
		Recursive: true,
	})
}

func (s *etcdShim) Set(path, value string, opts *etcd.SetOptions) error {
	_, err := s.api.Set(context.Background(), path, value, opts)
	return err
}

func (s *etcdShim) Watcher(path string) etcd.Watcher {
	return s.api.Watcher(path, &etcd.WatcherOptions{Recursive: true})
}

package reception

import (
	"context"

	etcd "github.com/coreos/etcd/client"
)

type (
	keysAPI interface {
		Get(path string) (*etcd.Response, error)
		Set(path, value string, opts *etcd.SetOptions) error
		Watcher(path string) etcd.Watcher
	}

	etcdShim struct {
		api etcd.KeysAPI
	}
)

func (s *etcdShim) Get(path string) (*etcd.Response, error) {
	return s.api.Get(context.Background(), path, &etcd.GetOptions{
		Recursive: true,
	})
}

func (s *etcdShim) Set(path, value string, opts *etcd.SetOptions) error {
	_, err := s.api.Set(context.Background(), path, value, opts)
	return err
}

func (s *etcdShim) Watcher(path string) etcd.Watcher {
	return s.api.Watcher(path, &etcd.WatcherOptions{Recursive: true})
}

Update one remaining context import.


package tarantool

type BinaryPacketPool struct {
	queue chan *BinaryPacket
}

func newPackedPacketPool() *BinaryPacketPool {
	return &BinaryPacketPool{
		queue: make(chan *BinaryPacket, 512),
	}
}

func (p *BinaryPacketPool) GetWithID(requestID uint64) (pp *BinaryPacket) {
	select {
	case pp = <-p.queue:
		pp.Reset()
		pp.pool = p
	default:
		pp = &BinaryPacket{}
		pp.Reset()
	}
	pp.packet.requestID = requestID
	return
}

func (p *BinaryPacketPool) Get() *BinaryPacket {
	return p.GetWithID(0)
}

func (p *BinaryPacketPool) Put(pp *BinaryPacket) {
	pp.pool = nil
	p.queue <- pp
}

func (p *BinaryPacketPool) Close() {
	close(p.queue)
}

package tarantool

type BinaryPacketPool struct {
	queue chan *BinaryPacket
}

func newPackedPacketPool() *BinaryPacketPool {
	return &BinaryPacketPool{
		queue: make(chan *BinaryPacket, 1024),
	}
}

func (p *BinaryPacketPool) GetWithID(requestID uint64) (pp *BinaryPacket) {
	select {
	case pp = <-p.queue:
	default:
		pp = &BinaryPacket{}
	}

	pp.Reset()
	pp.pool = p
	pp.packet.requestID = requestID
	return
}

func (p *BinaryPacketPool) Get() *BinaryPacket {
	return p.GetWithID(0)
}

func (p *BinaryPacketPool) Put(pp *BinaryPacket) {
	pp.pool = nil
	select {
	case p.queue <- pp:
	default:
	}
}

func (p *BinaryPacketPool) Close() {
	close(p.queue)
}

Fix the binary packet pool and x2 its capacity


package sluice

import (
	"testing"

	. "github.com/smartystreets/goconvey/convey"
)

func Test(t *testing.T) {
	Convey("Sluice can...", t, func() {
		gondola := New()

		Convey("pump values", func() {
			gondola.Push("x")
			gondola.Push("y")
			gondola.Push("z")
			So(<-gondola.Next(), ShouldEqual, "x")
			So(<-gondola.Next(), ShouldEqual, "y")
			So(<-gondola.Next(), ShouldEqual, "z")
		})

		Convey("block when empty", func() {
			var answered bool
			select {
			case <-gondola.Next():
				answered = true
			default:
				answered = false
			}
			So(answered, ShouldEqual, false)

			Convey("answers even dropped channels", func() {
				secondReq := gondola.Next()
				gondola.Push("1")
				// we still don't expect an answer,
				//  because the "1" routed to the channel in the prev test.
				select {
				case <-secondReq:
					answered = true
				default:
					answered = false
				}
				So(answered, ShouldEqual, false)

				Convey("definitely answers eventually", func() {
					gondola.Push("2")
					So(<-secondReq, ShouldEqual, "2")
				})
			})
		})
	})
}

package sluice

import (
	"testing"

	. "github.com/smartystreets/goconvey/convey"
)

func Test(t *testing.T) {
	Convey("Sluice can...", t, func() {
		gondola := New()

		Convey("pump values", func() {
			gondola.Push("x")
			gondola.Push("y")
			gondola.Push("z")
			So(<-gondola.Next(), ShouldEqual, "x")
			So(<-gondola.Next(), ShouldEqual, "y")
			So(<-gondola.Next(), ShouldEqual, "z")
		})

		Convey("block when empty", func() {
			var answered bool
			select {
			case <-gondola.Next():
				answered = true
			default:
				answered = false
			}
			So(answered, ShouldEqual, false)

			Convey("answers even dropped channels", func() {
				gondola.Push("1")
				// we still don't expect an answer,
				//  because the "1" routed to the channel in the prev test.
				secondReq := gondola.Next()
				select {
				case <-secondReq:
					answered = true
				default:
					answered = false
				}
				So(answered, ShouldEqual, false)

				Convey("definitely answers eventually", func() {
					gondola.Push("2")
					So(<-secondReq, ShouldEqual, "2")
				})
			})
		})
	})
}

Fix a sluice test with probablistic failure.


package acgen

import (
	"fmt"
	"io"
	"sync"
)

type Command struct {
	Name  string
	Flags []*Flag
}

type Flag struct {
	Short       []string
	Long        []string
	Arg         string
	Description string
}

type Generator func(w io.Writer, c *Command) error

var (
	generatorsMu sync.Mutex
	generators   = make(map[string]Generator)
)

func RegisterGenerator(name string, g Generator) {
	generatorsMu.Lock()
	defer generatorsMu.Unlock()
	if _, dup := generators[name]; dup {
		panic("RegisterGenerator called twice for generator " + name)
	}
	generators[name] = g
}

func LookGenerator(name string) (g Generator, err error) {
	generatorsMu.Lock()
	defer generatorsMu.Unlock()
	if _, ok := generators[name]; !ok {
		return nil, fmt.Errorf("%s: is not supported", name)
	}
	return generators[name], nil
}

package acgen

import (
	"fmt"
	"io"
	"sync"
)

// A Command represents a command which has flags.
type Command struct {
	Name  string
	Flags []*Flag
}

// A Flag represents the information of a flag.
type Flag struct {
	Short       []string // short options
	Long        []string // long options
	Arg         string   // argument's name
	Description string   // help message
}

// A Generator writes a completion for command to w.
type Generator func(w io.Writer, c *Command) error

var (
	generatorsMu sync.Mutex
	generators   = make(map[string]Generator)
)

// RegisterGenerator makes a completion generator available
// by the provided name.
func RegisterGenerator(name string, g Generator) {
	generatorsMu.Lock()
	defer generatorsMu.Unlock()
	if _, dup := generators[name]; dup {
		panic("RegisterGenerator called twice for generator " + name)
	}
	generators[name] = g
}

// LookGenerator returns a completion generator
// specified by its completion generator name.
func LookGenerator(name string) (g Generator, err error) {
	generatorsMu.Lock()
	defer generatorsMu.Unlock()
	if _, ok := generators[name]; !ok {
		return nil, fmt.Errorf("%s: is not supported", name)
	}
	return generators[name], nil
}

Add comments for types and functions to be published


package libtorrent

// #cgo pkg-config: libtorrent-rasterbar openssl
// #cgo darwin LDFLAGS: -lm -lstdc++
// #cgo linux LDFLAGS: -lm -lstdc++ -ldl -lrt
// #cgo windows CXXFLAGS: -DIPV6_TCLASS=39 -O0 -g
// #cgo windows LDFLAGS: -static-libgcc -static-libstdc++
import "C"

package libtorrent

// #cgo pkg-config: libtorrent-rasterbar openssl
// #cgo darwin LDFLAGS: -lm -lstdc++
// #cgo linux LDFLAGS: -lm -lstdc++ -ldl -lrt
// #cgo windows CXXFLAGS: -DIPV6_TCLASS=39
// #cgo windows LDFLAGS: -static-libgcc -static-libstdc++
import "C"

Remove debug flags in cgo


package handlers

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

//ReturnInternalServerError returns an Internal Server Error
func ReturnInternalServerError(w http.ResponseWriter, message string) {
	log.Println(message)
	response := make(map[string]string)
	response["status"] = "false"
	w.WriteHeader(http.StatusInternalServerError)
	json.NewEncoder(w).Encode(response)
}

//ReturnStatusBadRequest returns a Bad Request Error
func ReturnStatusBadRequest(w http.ResponseWriter, message string) {
	log.Println(message)
	response := make(map[string]string)
	response["status"] = "false"
	w.WriteHeader(http.StatusBadRequest)
	json.NewEncoder(w).Encode(response)
}

//ReturnUnauthorized returns a Unauthorized Error
func ReturnUnauthorized(w http.ResponseWriter, message string) {
	log.Println(message)
	response := make(map[string]string)
	response["Status"] = "false"
	w.WriteHeader(http.StatusUnauthorized)
	json.NewEncoder(w).Encode(response)
}

package handlers

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

//ReturnInternalServerError returns an Internal Server Error
func ReturnInternalServerError(w http.ResponseWriter, message string) {
	log.Println(message)
	response := make(map[string]interface{})
	response["status"] = false
	w.WriteHeader(http.StatusInternalServerError)
	json.NewEncoder(w).Encode(response)
}

//ReturnStatusBadRequest returns a Bad Request Error
func ReturnStatusBadRequest(w http.ResponseWriter, message string) {
	log.Println(message)
	response := make(map[string]interface{})
	response["status"] = false
	w.WriteHeader(http.StatusBadRequest)
	json.NewEncoder(w).Encode(response)
}

//ReturnUnauthorized returns a Unauthorized Error
func ReturnUnauthorized(w http.ResponseWriter, message string) {
	log.Println(message)
	response := make(map[string]interface{})
	response["Status"] = false
	w.WriteHeader(http.StatusUnauthorized)
	json.NewEncoder(w).Encode(response)
}

Change response status type from string to bool