package tokenizer

import (
	"io/ioutil"
	"testing"
)

func TestEnglish001(t *testing.T) {
	files := []string{
		"testdata/input-org-syn.txt",
		"testdata/input-te-wiki.txt",
	}

	for _, fn := range files {
		t.Logf("TEST    : %s", fn)
		bs, err := ioutil.ReadFile(fn)
		if err != nil {
			t.Fatalf("FATAL   : Input data file '%s' could not be read : %s", fn, err.Error())
		}

		size := len(bs)
		ti := NewTextTokenIterator(string(bs))
		var toks []*TextToken
		for err = ti.MoveNext(); err == nil; err = ti.MoveNext() {
			toks = append(toks, ti.Item())
		}

		lt := toks[len(toks)-1]
		if lt.End() != size - 1 {
			t.Errorf("FAIL    : Token offset drift by EOF.  Expected : %d, observed : %d", size, lt.End())
		}
		t.Logf("SUCCESS : %s", fn)
	}
}

package tokenizer

import (
	"io/ioutil"
	"testing"
)

func TestEnglish001(t *testing.T) {
	files := []string{
		"testdata/input-org-syn.txt",
		"testdata/input-te-wiki.txt",
	}

	for _, fn := range files {
		t.Logf("%-8s : %s", "TEST", fn)
		bs, err := ioutil.ReadFile(fn)
		if err != nil {
			t.Fatalf("%-8s : Input data file '%s' could not be read : %s", "FATAL", fn, err.Error())
		}

		size := len(bs)
		ti := NewTextTokenIterator(string(bs))
		var toks []*TextToken
		for err = ti.MoveNext(); err == nil; err = ti.MoveNext() {
			toks = append(toks, ti.Item())
		}

		lt := toks[len(toks)-1]
		if lt.End() != size - 1 {
			t.Errorf("%-8s : Token offset drift by EOF.  Expected : %d, observed : %d", "FAIL", size, lt.End())
		}
		t.Logf("%-8s : %s", "SUCCESS", fn)
	}
}

Make minor formatting change in tests


package config

import (
	"time"
)

// Client is the aptomictl config representation
type Client struct {
	Debug bool `validate:"-"`
	API   API  `validate:"required"`
	Auth  Auth `validate:"required"`
	HTTP  HTTP `validate:"required"`
}

// HTTP is the config for low level HTTP client
type HTTP struct {
	Timeout time.Duration
}

// IsDebug returns true if debug mode enabled
func (c Client) IsDebug() bool {
	return c.Debug
}

// Auth represents client auth configs
type Auth struct {
	Username string `validate:"required"`
}

package config

import (
	"time"
)

// Client is the aptomictl config representation
type Client struct {
	Debug  bool   `validate:"-"`
	Output string `validate:"required"`
	API    API    `validate:"required"`
	Auth   Auth   `validate:"required"`
	HTTP   HTTP   `validate:"required"`
}

// HTTP is the config for low level HTTP client
type HTTP struct {
	Timeout time.Duration
}

// IsDebug returns true if debug mode enabled
func (c Client) IsDebug() bool {
	return c.Debug
}

// Auth represents client auth configs
type Auth struct {
	Username string `validate:"required"`
}

Add output config for CLI to specify type of the output


package base

const (
	defaultTimeFormat = "2006-01-02-15-04-05"
)

type Config struct {
	// TimeFormat is used for a directory path
	TimeFormat string

	// RootDir
	RootDir string

	// TempDir
	TempDir string
}

func (cfg *Config) InitDefaults() {
	cfg.TimeFormat = defaultTimeFormat
}

package base

const (
	defaultTimeFormat = "2006-01-02-15-04-05"
)

type Config struct {
	// TimeFormat is used for a directory path
	TimeFormat string

	// RootDir
	RootDir string

	// TempDir
	TempDir string
}

func (cfg *Config) InitDefaults() {
	if cfg.TimeFormat == "" {
		cfg.TimeFormat = defaultTimeFormat
	}
}

Set time format if it is empty


//
// Copyright (c) 2014 The heketi 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 requests

// Structs for messages
type VolumeInfoResp struct {
	Name string `json:"name"`
	Size uint64 `json:"size"`
	Id   uint64 `json: "id"`
}

type VolumeCreateRequest struct {
	Name string `json:"name"`
	Size uint64 `json:"size"`
}

type VolumeListResponse struct {
	Volumes []VolumeInfoResp `json:"volumes"`
}

//
// Copyright (c) 2014 The heketi 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 requests

// Structs for messages
type VolumeInfoResp struct {
	Name string `json:"name"`
	Size uint64 `json:"size"`
	Id   uint64 `json:"id"`
}

type VolumeCreateRequest struct {
	Name string `json:"name"`
	Size uint64 `json:"size"`
}

type VolumeListResponse struct {
	Volumes []VolumeInfoResp `json:"volumes"`
}

Fix issue found by go vet


package xstrings

import (
	"strings"
)

// Upcase returns a copy of string s
// with all lowercase letters replaced
// with their uppercase counterparts.

func Upcase(s string) string {
	return strings.ToUpper(s)
}

Fix spacing for documentation to work.


package server

import (
	"github.com/b2aio/typhon/auth"
	"github.com/golang/protobuf/proto"
	"golang.org/x/net/context"
)

// Request received by the server
type Request interface {
	context.Context

	// Id of this message, used to correlate the response
	Id() string
	// ContentType of the payload
	ContentType() string
	// Payload of raw bytes received from the transport
	Payload() []byte
	// Body is the Unmarshalled `Payload()`. If `RequestType()` is set on
	// the `Endpoint`, we can attempt to unmarshal it for you
	Body() interface{}
	// SetBody of this request
	SetBody(interface{})
	// Service which this request was intended for
	Service() string
	// Endpoint to be called on the receiving service
	Endpoint() string
	// ScopedRequest makes a client request within the scope of the current request
	// @todo change the request & response interface to decouple from protobuf
	ScopedRequest(service string, endpoint string, req proto.Message, resp proto.Message) error

	// Session provided on this request
	Session() auth.Session
	// SetSession for this request, useful at api level and for mocking
	SetSession(auth.Session)

	// Server is a reference to the server currently processing this request
	Server() Server
}

package server

import (
	"fmt"

	"github.com/b2aio/typhon/auth"
	"github.com/golang/protobuf/proto"
	"golang.org/x/net/context"
)

// Request received by the server
type Request interface {
	context.Context

	// Id of this message, used to correlate the response
	Id() string
	// ContentType of the payload
	ContentType() string
	// Payload of raw bytes received from the transport
	Payload() []byte
	// Body is the Unmarshalled `Payload()`. If `RequestType()` is set on
	// the `Endpoint`, we can attempt to unmarshal it for you
	Body() interface{}
	// SetBody of this request
	SetBody(interface{})
	// Service which this request was intended for
	Service() string
	// Endpoint to be called on the receiving service
	Endpoint() string
	// ScopedRequest makes a client request within the scope of the current request
	// @todo change the request & response interface to decouple from protobuf
	ScopedRequest(service string, endpoint string, req proto.Message, resp proto.Message) error

	// Session provided on this request
	Session() auth.Session
	// SetSession for this request, useful at api level and for mocking
	SetSession(auth.Session)

	// Server is a reference to the server currently processing this request
	Server() Server
}

// RecoverServerFromContext retrieves the server in which this context is executing
func RecoverServerFromContext(ctx context.Context) (Server, error) {
	if req, ok := ctx.(Request); ok {
		return req.Server(), nil
	}

	return nil, fmt.Errorf("Server not present in context")
}

Allow server to be recovered from the context


package cli

import (
	"os"
	"strconv"
	"strings"

	"github.com/spf13/cobra"
)

func flag(cmd *cobra.Command, f string) string {
	s := cmd.Flag(f).DefValue
	if cmd.Flag(f).Changed {
		s = cmd.Flag(f).Value.String()
	}

	return s
}

func GetCliStringFlag(cmd *cobra.Command, f string) string {
	return flag(cmd, f)
}

func GetCliIntFlag(cmd *cobra.Command, f string) int {
	v, err := strconv.Atoi(flag(cmd, f))
	if err != nil {
		return 0
	}

	return v
}

func BinName() string {
	return strings.TrimPrefix(os.Args[0], "./")
}

package cli

import (
	"os"
	"path/filepath"
	"strconv"

	"github.com/spf13/cobra"
)

func flag(cmd *cobra.Command, f string) string {
	s := cmd.Flag(f).DefValue
	if cmd.Flag(f).Changed {
		s = cmd.Flag(f).Value.String()
	}

	return s
}

func GetCliStringFlag(cmd *cobra.Command, f string) string {
	return flag(cmd, f)
}

func GetCliIntFlag(cmd *cobra.Command, f string) int {
	v, err := strconv.Atoi(flag(cmd, f))
	if err != nil {
		return 0
	}

	return v
}

func BinName() string {
	return filepath.Base(os.Args[0])
}

Use base name only for bin name.


// gddoexp is a command line tool crated to list eligible packages for
// archiving in GoDoc.org
package main

import (
	"fmt"

	"github.com/golang/gddo/database"
	"github.com/rafaeljusto/gddoexp"
)

func main() {
	db, err := database.New()
	if err != nil {
		fmt.Println("error connecting to database:", err)
		return
	}

	pkgs, err := db.AllPackages()
	if err != nil {
		fmt.Println("error retrieving all packages:", err)
		return
	}

	for _, pkg := range pkgs {
		if archive, err := gddoexp.ShouldArchivePackage(pkg.Path, db); err != nil {
			fmt.Println(err)
		} else if archive {
			fmt.Printf("package “%s” should be archived\n", pkg.Path)
		}
	}
}

// gddoexp is a command line tool crated to list eligible packages for
// archiving in GoDoc.org
package main

import (
	"fmt"
	"net/http"
	"os"
	"path"

	"github.com/golang/gddo/database"
	"github.com/gregjones/httpcache"
	"github.com/gregjones/httpcache/diskcache"
	"github.com/rafaeljusto/gddoexp"
)

func main() {
	// add cache to avoid to repeated requests to Github
	gddoexp.HTTPClient = &http.Client{
		Transport: httpcache.NewTransport(
			diskcache.New(path.Join(os.Getenv("HOME"), ".gddoexp")),
		),
	}

	db, err := database.New()
	if err != nil {
		fmt.Println("error connecting to database:", err)
		return
	}

	pkgs, err := db.AllPackages()
	if err != nil {
		fmt.Println("error retrieving all packages:", err)
		return
	}

	for _, pkg := range pkgs {
		if archive, err := gddoexp.ShouldArchivePackage(pkg.Path, db); err != nil {
			fmt.Println(err)
		} else if archive {
			fmt.Printf("package “%s” should be archived\n", pkg.Path)
		}
	}
}

Add HTTP cache in Github request/response


package plugin

import "os"

/**
	* This function is called by the plugin to setup their server. This allows us to call Run on the plugin
	* os.Args[1] port CF_CLI rpc server is running on
	* os.Args[2] **OPTIONAL**
		* SendMetadata - used to fetch the plugin metadata
**/
func Start(cmd Plugin) {
	cliConnection := NewCliConnection(os.Args[1])

	cliConnection.pingCLI()
	if cliConnection.isMetadataRequest() {
		cliConnection.sendPluginMetadataToCliServer(cmd.GetMetadata())
	} else {
		cmd.Run(cliConnection, os.Args[2:])
	}
}

func (plugingCliConnection *cliConnection) isMetadataRequest() bool {
	return len(os.Args) == 3 && os.Args[2] == "SendMetadata"
}

package plugin

import "os"

/**
	* This function is called by the plugin to setup their server. This allows us to call Run on the plugin
	* os.Args[1] port CF_CLI rpc server is running on
	* os.Args[2] **OPTIONAL**
		* SendMetadata - used to fetch the plugin metadata
**/
func Start(cmd Plugin) {
	cliConnection := NewCliConnection(os.Args[1])

	cliConnection.pingCLI()
	if isMetadataRequest(os.Args) {
		cliConnection.sendPluginMetadataToCliServer(cmd.GetMetadata())
	} else {
		cmd.Run(cliConnection, os.Args[2:])
	}
}

func isMetadataRequest(args []string) bool {
	return len(args) == 3 && args[2] == "SendMetadata"
}

Remove move method off of other file's struct


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

package time

import (
	"testing";
	"time";
)

export func TestTick(t *testing.T) {
	const (
		Delta uint64 = 100*1e6;
		Count uint64 = 10;
	);
	c := Tick(Delta);
	t0 := Nanoseconds();
	for i := 0; i < Count; i++ {
		<-c;
	}
	t1 := Nanoseconds();
	ns := t1 - t0;
	target := int64(Delta*Count);
	slop := target*2/10;
	if ns < target - slop || ns > target + slop {
		t.Fatalf("%d ticks of %g ns took %g ns, expected %g", Count, float64(Delta), float64(ns), float64(target));
	}
}

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

package time

import (
	"testing";
	"time";
)

export func TestTick(t *testing.T) {
	const (
		Delta = 100*1e6;
		Count = 10;
	);
	c := Tick(Delta);
	t0 := Nanoseconds();
	for i := 0; i < Count; i++ {
		<-c;
	}
	t1 := Nanoseconds();
	ns := t1 - t0;
	target := int64(Delta*Count);
	slop := target*2/10;
	if ns < target - slop || ns > target + slop {
		t.Fatalf("%d ticks of %g ns took %g ns, expected %g", Count, float64(Delta), float64(ns), float64(target));
	}
}

Remove types from constants, since they didn't match what Tick() expected.


package main

import (
	"fmt"
	"net/http"
	"os"
	"strconv"

	"github.com/scottjbarr/genpass"
)

func main() {
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	bind := fmt.Sprintf(":%v", port)

	http.HandleFunc("/", indexHandler)
	if err := http.ListenAndServe(bind, nil); err != nil {
		panic(err)
	}
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
	length := r.URL.Query().Get("length")

	// parse the length param
	l, _ := strconv.ParseInt(length, 64, 10)
	if l == 0 {
		l = 64
	}

	fmt.Fprintf(w, "%s\n", genpass.Generate(l))
}

package main

import (
	"fmt"
	"net/http"
	"os"
	"strconv"

	"github.com/scottjbarr/genpass"
)

func main() {
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	bind := fmt.Sprintf(":%v", port)

	http.HandleFunc("/", indexHandler)
	if err := http.ListenAndServe(bind, nil); err != nil {
		panic(err)
	}
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
	length := r.URL.Query().Get("length")

	// parse the length param
	l, _ := strconv.ParseInt(length, 10, 64)
	if l == 0 {
		l = 64
	}

	fmt.Fprintf(w, "%s\n", genpass.Generate(l))
}

Fix length parsing from http param


package main

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

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

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

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

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

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

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

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

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}

package main

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

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

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

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

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

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

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

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

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}

Change the target set for channel


/*
Copyright 2014 Google Inc. All rights reserved.

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

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

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

package api

// This file contains API types that are unversioned.

// APIVersions lists the api versions that are available, to allow
// version negotiation. APIVersions isn't just an unnamed array of
// strings in order to allow for future evolution, though unversioned
type APIVersions struct {
	Versions []string `json:"versions"`
}

// RootPaths lists the paths available at root.
// For example: "/healthz", "/api".
type RootPaths struct {
	Paths []string `json:"paths"`
}

// preV1Beta3 returns true if the provided API version is an API introduced before v1beta3.
func PreV1Beta3(version string) bool {
	return version == "v1beta1" || version == "v1beta2"
}

func LabelSelectorQueryParam(version string) string {
	if PreV1Beta3(version) {
		return "labels"
	}
	return "label-selector"
}

func FieldSelectorQueryParam(version string) string {
	if PreV1Beta3(version) {
		return "fields"
	}
	return "field-selector"
}

Make label and field selector query strings versionable.


package lang

type APIPolicy struct {
	Namespace map[string]*PolicyNamespace
}

type APIPolicyNamespace struct {
	Services     map[string]*Service
	Contracts    map[string]*Contract
	Clusters     map[string]*Cluster
	Rules        map[string]*Rule
	ACLRules     map[string]*Rule
	Dependencies map[string]*Dependency
}

func (view *PolicyView) APIPolicy() *APIPolicy {
	// if we're changing data in any map, we should copy map as well
	// don't change existing object, make copy of them

	return &APIPolicy{}
}

package lang

// APIPolicy is a Policy representation for API filtered for specific user
type APIPolicy struct {
	Namespace map[string]*APIPolicyNamespace
}

// APIPolicyNamespace is a PolicyNamespace representation for API filtered for specific user
type APIPolicyNamespace struct {
	Services     map[string]*Service
	Contracts    map[string]*Contract
	Clusters     map[string]*Cluster
	Rules        map[string]*Rule
	ACLRules     map[string]*Rule
	Dependencies map[string]*Dependency
}

// APIPolicy returns Policy representation for API filtered for specific user
func (view *PolicyView) APIPolicy() *APIPolicy {
	// if we're changing data in any map, we should copy map as well
	// don't change existing object, make copy of them

	return &APIPolicy{}
}

Add comments and fix APIPolicy/Namespace type


package keys

import "fmt"

// Kind expresses usage of the ambient internal key.
type Kind int

const (
	// Delete represents deletion of this key.
	Delete = 0
	// Value represents value setting of this key.
	Value   = 1
	maxKind = Value

	// Seek is maximum(Value, Delete), which is a valid Kind and
	// serves as start point for keys with same sequence.
	//
	// See InternalComparator.Compare for ordering among internal keys.
	Seek = maxKind
)

func (k Kind) String() string {
	switch k {
	case Delete:
		return "value deletion"
	case Value:
		return "value setting"
	}
	return fmt.Sprintf("unknown kind: %d", k)
}

package keys

import "fmt"

// Kind expresses usage of the ambient internal key.
type Kind int

const (
	// XXX Don't change those values, together with user keys there are
	// persisted to files.

	// Delete represents deletion of this key.
	Delete = 0
	// Value represents value setting of this key.
	Value   = 1
	maxKind = Value

	// Seek is maximum(Value, Delete), which is a valid Kind and
	// serves as start point for keys with same sequence.
	//
	// See InternalComparator.Compare for ordering among internal keys.
	Seek = maxKind
)

func (k Kind) String() string {
	switch k {
	case Delete:
		return "value deletion"
	case Value:
		return "value setting"
	}
	return fmt.Sprintf("unknown kind: %d", k)
}

Add CHANGE CAUTION for values of keys.Kind


package webbrowser

import (
	"errors"
	"net/url"
	"os/exec"
)

var (
	ErrCantOpen     = errors.New("webbrowser.Open: can't open webpage")
	ErrNoCandidates = errors.New("webbrowser.Open: no browser candidate found for your OS.")
)

//
var Candidates []Browser

// Browser
type Browser interface {
	Open(string) error
}

// GenericBrowser
type GenericBrowser struct {
	cmd  string
	args []string
}

func (gb GenericBrowser) Open(s string) error {
	u, err := url.Parse(s)
	if err != nil {
		return err
	}

	u.Scheme = "http"
	s = u.String()

	cmd := exec.Command(gb.cmd, append(gb.args, s)...)
	return cmd.Run()
}

func Open(s string) error {
	if len(Candidates) == 0 {
		return ErrNoCandidates
	}

	for _, b := range Candidates {
		err := b.Open(s)
		if err == nil {
			return nil
		}
	}

	return ErrCantOpen
}

// Register a browser connector and, optionally, connection.
func Register(name Browser) {
	// Append
	Candidates = append(Candidates, name)
	// Prepend
	// Candidates = append([]Browser{name}, Candidates...)
}

package webbrowser

import (
	"errors"
	"net/url"
	"os/exec"
)

var (
	ErrCantOpen     = errors.New("webbrowser.Open: can't open webpage")
	ErrNoCandidates = errors.New("webbrowser.Open: no browser candidate found for your OS.")
)

//
var Candidates []Browser

// Browser
type Browser interface {
	Open(string) error
}

// GenericBrowser
type GenericBrowser struct {
	cmd  string
	args []string
}

func (gb GenericBrowser) Open(s string) error {
	u, err := url.Parse(s)
	if err != nil {
		return err
	}

	// Enforce a scheme so linux and darwin work properly
	if u.Scheme != "https" {
		u.Scheme = "http"
	}
	s = u.String()

	cmd := exec.Command(gb.cmd, append(gb.args, s)...)
	return cmd.Run()
}

// Open opens an URL on the first available candidate found.
func Open(s string) error {
	if len(Candidates) == 0 {
		return ErrNoCandidates
	}

	for _, b := range Candidates {
		err := b.Open(s)
		if err == nil {
			return nil
		}
	}

	return ErrCantOpen
}

// Register registers in the Candidates list (append to end).
func Register(name Browser) {
	Candidates = append(Candidates, name)
}

// RegisterPrep registers in the Candidates list (prepend to start).
func RegisterPrep(name Browser) {
	Candidates = append([]Browser{name}, Candidates...)
}

Enforce HTTP Scheme on Open and added docs.


package horizon

import (
	"bytes"
	"fmt"
	gctx "github.com/goji/context"
	"github.com/stellar/go-horizon/render/problem"
	"github.com/zenazn/goji/web"
	. "github.com/zenazn/goji/web/middleware"
	"log"
	"net/http"
	"runtime/debug"
)

func RecoverMiddleware(c *web.C, h http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		reqID := GetReqID(*c)

		defer func() {
			if err := recover(); err != nil {
				printPanic(reqID, err)
				debug.PrintStack()
				//TODO: include stack trace if in debug mode
				problem.Render(gctx.FromC(*c), w, problem.ServerError)
			}
		}()

		h.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}

func printPanic(reqID string, err interface{}) {
	var buf bytes.Buffer

	if reqID != "" {
		fmt.Fprintf(&buf, "[%s] ", reqID)
	}
	fmt.Fprintf(&buf, "panic: %+v", err)

	log.Print(buf.String())
}

package horizon

import (
	"net/http"
	"runtime/debug"

	gctx "github.com/goji/context"
	"github.com/stellar/go-horizon/log"
	"github.com/stellar/go-horizon/render/problem"
	"github.com/zenazn/goji/web"
)

func RecoverMiddleware(c *web.C, h http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		ctx := gctx.FromC(*c)

		defer func() {
			if err := recover(); err != nil {
				log.Errorf(ctx, "panic: %+v", err)
				log.Errorf(ctx, "backtrace: %s", debug.Stack())

				//TODO: include stack trace if in debug mode
				problem.Render(gctx.FromC(*c), w, problem.ServerError)
			}
		}()

		h.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}

Integrate recover middleware with new log


package templates

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

{{ .Name}}:
  {{ range .Services }}{{ .GetName }}:
    {{ range $key, $value := .GetParameters }}{{ $key }}: {{ $value }}
    {{ end }}
  {{ end }}
`
}

package templates

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

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

Add units to template file


package dns

import (
	"testing"
)

func TestDynamicUpdateParsing(t *testing.T) {
	prefix := "example.com. IN "
	for _, typ := range TypeToString {
		if typ == "CAA" || typ == "OPT" || typ == "AXFR" || typ == "IXFR" || typ == "ANY" || typ == "TKEY" ||
			typ == "TSIG" || typ == "ISDN" || typ == "UNSPEC" || typ == "NULL" || typ == "ATMA" {
			continue
		}
		r, e := NewRR(prefix + typ)
		if e != nil {
			t.Log("failure to parse: " + prefix + typ)
			t.Fail()
		} else {
			t.Logf("parsed: %s", r.String())
		}
	}
}

func TestDynamicUpdateUnpack(t *testing.T) {
	// From https://github.com/miekg/dns/issues/150#issuecomment-62296803
	buf := []byte{171, 68, 40, 0, 0, 1, 0, 0, 0, 2, 0, 0, 7, 101, 120, 97, 109, 112, 108, 101, 0, 0, 6, 0, 1, 192, 12, 0, 1, 0, 255, 0, 0, 0, 0, 0, 0, 192, 12, 0, 1, 0, 1, 0, 0, 0, 0, 0, 4, 127, 0, 0, 1}
	msg := new(Msg)
	err := msg.Unpack(buf)
	if err != nil {
		t.Log("failed to unpack: " + err.Error())
//		t.Fail()
	}
}

Add Test for dynamic unpack failure


package utils

import "sync"

// ConcurrentSlice type that can be safely shared between goroutines
type ConcurrentSlice struct {
	sync.RWMutex
	items []interface{}
}

// ConcurrentSliceItem contains the index/value pair of an item in a
// concurrent slice
type ConcurrentSliceItem struct {
	Index int
	Value interface{}
}

// NewConcurrentSlice creates a new concurrent slice
func NewConcurrentSlice() *ConcurrentSlice {
	cs := &ConcurrentSlice{
		items: make([]interface{}, 0),
	}

	return cs
}

// Append adds an item to the concurrent slice
func (cs *ConcurrentSlice) Append(item interface{}) {
	cs.Lock()
	defer cs.Unlock()

	cs.items = append(cs.items, item)
}

// Iter iterates over the items in the concurrent slice
// Each item is sent over a channel, so that
// we can iterate over the slice using the builin range keyword
func (cs *ConcurrentSlice) Iter() <-chan ConcurrentSliceItem {
	c := make(chan ConcurrentSliceItem)

	f := func() {
		cs.Lock()
		defer cs.Lock()
		for index, value := range cs.items {
			c <- ConcurrentSliceItem{index, value}
		}
		close(c)
	}
	go f()

	return c
}

// List type represents a slice of strings
type List []string

// Contains returns a boolean indicating whether the list
// contains the given string.
func (l List) Contains(x string) bool {
	for _, v := range l {
		if v == x {
			return true
		}
	}

	return false
}

Implement utils.List type with a Contains() method


package models

import "github.com/koding/bongo"

func (nc *NotificationContent) AfterCreate() {
	bongo.B.AfterCreate(nc)
}

func (nc *NotificationContent) AfterUpdate() {
	bongo.B.AfterUpdate(nc)
}

func (nc *NotificationContent) AfterDelete() {
	bongo.B.AfterDelete(nc)
}

func NewNotificationContent() *NotificationContent {
	return &NotificationContent{}
}

func (n *NotificationContent) GetId() int64 {
	return n.Id
}

func (n NotificationContent) TableName() string {
	return "notification.notification_content"
}

// Create checks for NotificationContent using type_constant and target_id
// and creates new one if it does not exist.
func (n *NotificationContent) Create() error {
	if err := n.FindByTarget(); err != nil {
		if err != bongo.RecordNotFound {
			return err
		}
		return bongo.B.Create(n)
	}

	return nil
}

func (n *NotificationContent) One(q *bongo.Query) error {
	return bongo.B.One(n, n, q)
}

func (n *NotificationContent) ById(id int64) error {
	return bongo.B.ById(n, id)
}

func (n *NotificationContent) Some(data interface{}, q *bongo.Query) error {
	return bongo.B.Some(n, data, q)
}

Add some method to notificationcontent


package main

import (
	"fmt"
	"net/http"
)

func helloWorld(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello World!")
}

func startPage(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, test server started on 8080 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing")
}

func showInfo(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Inforamtion page for test project.\nLanguage - Go\nPlatform - Google Application Engine")
}

func init() {

	http.HandleFunc("/", startPage)
	http.HandleFunc("/helloworld", helloWorld)
	http.HandleFunc("/showinfo", showInfo)
	//Wrong code for App Enine - server cant understand what it need to show
	//http.ListenAndServe(":80", nil)
}

/*
func main() {
	fmt.Println("Hello, test server started on 80 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing")
	http.HandleFunc("/", startPage)
	http.HandleFunc("/helloworld", helloWorld)
	http.HandleFunc("/showinfo", showInfo)
	http.ListenAndServe(":80", nil)
}
*/
//goapp serve app.yaml
//goapp deploy -application golangnode0 -version 0

//Command to run test version:
//goapp serve app.yaml
//Command to deploy/update application:
//goapp deploy -application golangnode0 -version 0

package main

import (
	"fmt"
	"net/http"
)

func helloWorld(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello World!")
}

func startPage(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, test server started on 8080 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing")
}

func showInfo(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Inforamtion page for test project.\nLanguage - Go\nPlatform - Google Application Engine")
}

func init() {

	http.HandleFunc("/", startPage)
	http.HandleFunc("/helloworld", helloWorld)
	http.HandleFunc("/showinfo", showInfo)
	//Wrong code for App Enine - server cant understand what it need to show
	//http.ListenAndServe(":80", nil)
}

/*
func main() {
	fmt.Println("Hello, test server started on 80 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing")
	http.HandleFunc("/", startPage)
	http.HandleFunc("/helloworld", helloWorld)
	http.HandleFunc("/showinfo", showInfo)
	http.ListenAndServe(":80", nil)
}
*/

Correct version for deploy to GAE


package svg

// InstructionType tells our path drawing library which function it has
// to call
type InstructionType int

// These are instruction types that we use with our path drawing library
const (
	PathInstruction InstructionType = iota
	MoveInstruction
	CircleInstruction
	CurveInstruction
	LineInstruction
	HLineInstruction
	CloseInstruction
)

// DrawingInstruction contains enough information that a simple drawing
// library can draw the shapes contained in an SVG file.
//
// The struct contains all necessary fields but only the ones needed (as
// indicated byt the InstructionType) will be non-nil.
type DrawingInstruction struct {
	Kind        InstructionType
	M           *Tuple
	C1          *Tuple
	C2          *Tuple
	T           *Tuple
	Radius      *float64
	Fill        *string
	StrokeWidth *float64
}

package svg

// InstructionType tells our path drawing library which function it has
// to call
type InstructionType int

// These are instruction types that we use with our path drawing library
const (
	PathInstruction InstructionType = iota
	MoveInstruction
	CircleInstruction
	CurveInstruction
	LineInstruction
	HLineInstruction
	CloseInstruction
)

// DrawingInstruction contains enough information that a simple drawing
// library can draw the shapes contained in an SVG file.
//
// The struct contains all necessary fields but only the ones needed (as
// indicated byt the InstructionType) will be non-nil.
type DrawingInstruction struct {
	Kind        InstructionType
	M           *Tuple
	C1          *Tuple
	C2          *Tuple
	T           *Tuple
	Radius      *float64
	StrokeWidth *float64
	Fill        *string
	Stroke      *string
}

Add more fields to the DrawingInstructions


package streaming

import (
	"net/url"

	"github.com/ChimeraCoder/anaconda"
)

func StartUserStream(api *anaconda.TwitterApi) anaconda.Stream {
	v := url.Values{}
	v.Set("with", "user")
	v.Set("replies", "all")
	return api.UserStream(v)
}

package streaming

import (
	"net/url"

	"github.com/ChimeraCoder/anaconda"
)

func StartUserStream(api *anaconda.TwitterApi) *anaconda.Stream {
	v := url.Values{}
	v.Set("with", "user")
	v.Set("replies", "all")
	return api.UserStream(v)
}

Fix wrong stream return type


package engine

import (
	"encoding/json"
	"fmt"
)

type Dot struct {
	X uint8
	Y uint8
}

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

// Implementing json.Marshaler interface
func (d Dot) MarshalJSON() ([]byte, error) {
	return json.Marshal([]uint16{uint16(d.X), uint16(d.Y)})
}

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

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

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

	return
}

package engine

import (
	"encoding/json"
	"fmt"
)

type Dot struct {
	X uint8
	Y uint8
}

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

// Implementing json.Marshaler interface
func (d Dot) MarshalJSON() ([]byte, error) {
	return json.Marshal([]uint8{d.X, d.Y})
}

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

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

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

	return
}

Fix engine.Dot: do not convert x and y to uint16 for json marshaling


package server

import (
	"fmt"
	"log"
	"time"
	"warcluster/entities"
	"warcluster/server/response"
)

// StartMissionary is used when a call to initiate a new mission is rescived.
// 1. When the delay ends the thread ends the mission calling EndMission
// 2. The end of the mission is bradcasted to all clients and the mission entry is erased from the DB.
func StartMissionary(mission *entities.Mission) {
	target_key := fmt.Sprintf("planet.%d_%d", mission.Target[0], mission.Target[1])
	time.Sleep(time.Duration(mission.TravelTime * 1e6))

	target_entity, err := entities.Get(target_key)
	if err != nil {
		log.Print("Error in target planet fetch: ", err.Error())
		return
	}
	target := target_entity.(*entities.Planet)

	target.UpdateShipCount()

	result := entities.EndMission(target, mission)
	state_change := response.NewStateChange()
	state_change.Planets = map[string]entities.Entity{
		result.GetKey(): result,
	}
	response.Send(state_change, sessions.Broadcast)
	entities.Delete(mission.GetKey())
}

package server

import (
	"fmt"
	"log"
	"time"
	"warcluster/entities"
	"warcluster/server/response"
)

// StartMissionary is used when a call to initiate a new mission is rescived.
// 1. When the delay ends the thread ends the mission calling EndMission
// 2. The end of the mission is bradcasted to all clients and the mission entry is erased from the DB.
func StartMissionary(mission *entities.Mission) {
	target_key := fmt.Sprintf("planet.%d_%d", mission.Target[0], mission.Target[1])
	time.Sleep(time.Duration(mission.TravelTime * 1e6))

	target_entity, err := entities.Get(target_key)
	if err != nil {
		log.Print("Error in target planet fetch: ", err.Error())
		return
	}
	target := target_entity.(*entities.Planet)
	target.UpdateShipCount()

	result := entities.EndMission(target, mission)
	entities.Save(result)

	state_change := response.NewStateChange()
	state_change.Planets = map[string]entities.Entity{
		result.GetKey(): result,
	}
	response.Send(state_change, sessions.Broadcast)

	entities.Delete(mission.GetKey())
}

Save the target planet at the end of each mission


package route

import (
	"fmt"

	"github.com/mailgun/predicate"
)

// IsValid checks whether expression is valid
func IsValid(expr string) bool {
	_, err := parse(expr, &match{})
	return err == nil
}

func parse(expression string, result *match) (matcher, error) {
	p, err := predicate.NewParser(predicate.Def{
		Functions: map[string]interface{}{
			"Host":       hostTrieMatcher,
			"HostRegexp": hostRegexpMatcher,

			"Path":       pathTrieMatcher,
			"PathRegexp": pathRegexpMatcher,

			"Method":       methodTrieMatcher,
			"MethodRegexp": methodRegexpMatcher,

			"Header":       headerTrieMatcher,
			"HeaderRegexp": headerRegexpMatcher,
		},
		Operators: predicate.Operators{
			AND: newAndMatcher,
		},
	})
	if err != nil {
		return nil, err
	}
	out, err := p.Parse(expression)
	if err != nil {
		return nil, err
	}
	m, ok := out.(matcher)
	if !ok {
		return nil, fmt.Errorf("unknown result type: %T", out)
	}
	m.setMatch(result)
	return m, nil
}

package route

import (
	"fmt"

	"github.com/vulcand/predicate"
)

// IsValid checks whether expression is valid
func IsValid(expr string) bool {
	_, err := parse(expr, &match{})
	return err == nil
}

func parse(expression string, result *match) (matcher, error) {
	p, err := predicate.NewParser(predicate.Def{
		Functions: map[string]interface{}{
			"Host":       hostTrieMatcher,
			"HostRegexp": hostRegexpMatcher,

			"Path":       pathTrieMatcher,
			"PathRegexp": pathRegexpMatcher,

			"Method":       methodTrieMatcher,
			"MethodRegexp": methodRegexpMatcher,

			"Header":       headerTrieMatcher,
			"HeaderRegexp": headerRegexpMatcher,
		},
		Operators: predicate.Operators{
			AND: newAndMatcher,
		},
	})
	if err != nil {
		return nil, err
	}
	out, err := p.Parse(expression)
	if err != nil {
		return nil, err
	}
	m, ok := out.(matcher)
	if !ok {
		return nil, fmt.Errorf("unknown result type: %T", out)
	}
	m.setMatch(result)
	return m, nil
}

Move from github.com/mailgun/... to github.com/vulcand/... for dependencies.


package codecs

import (
	"bytes"
	"math"
	"math/rand"
	"testing"
)

func TestG722Payloader(t *testing.T) {
	p := G722Payloader{}

	const (
		testlen = 10000
		testmtu = 1500
	)

	//generate random 8-bit g722 samples
	samples := make([]byte, testlen)
	_, err := rand.Read(samples)

	if err != nil {
		//according to go docs, this should never ever happen
		t.Fatal("RNG Error!")
	}

	//make a copy, for payloader input
	samplesIn := make([]byte, testlen)
	copy(samplesIn, samples)

	//split our samples into payloads
	payloads := p.Payload(testmtu, samplesIn)

	outcnt := int(math.Ceil(float64(testlen) / testmtu))
	if len(payloads) != outcnt {
		t.Fatalf("Generated %d payloads instead of %d", len(payloads), outcnt)
	}

	if !bytes.Equal(samplesIn, samples) {
		t.Fatal("Modified input samples")
	}

	samplesOut := bytes.Join(payloads, []byte{})

	if !bytes.Equal(samplesIn, samplesOut) {
		t.Fatal("Output samples don't match")
	}
}

package codecs

import (
	"bytes"
	"crypto/rand"
	"math"
	"testing"
)

func TestG722Payloader(t *testing.T) {
	p := G722Payloader{}

	const (
		testlen = 10000
		testmtu = 1500
	)

	//generate random 8-bit g722 samples
	samples := make([]byte, testlen)
	_, err := rand.Read(samples)

	if err != nil {
		t.Fatal("RNG Error: ", err)
	}

	//make a copy, for payloader input
	samplesIn := make([]byte, testlen)
	copy(samplesIn, samples)

	//split our samples into payloads
	payloads := p.Payload(testmtu, samplesIn)

	outcnt := int(math.Ceil(float64(testlen) / testmtu))
	if len(payloads) != outcnt {
		t.Fatalf("Generated %d payloads instead of %d", len(payloads), outcnt)
	}

	if !bytes.Equal(samplesIn, samples) {
		t.Fatal("Modified input samples")
	}

	samplesOut := bytes.Join(payloads, []byte{})

	if !bytes.Equal(samplesIn, samplesOut) {
		t.Fatal("Output samples don't match")
	}
}

Use crypto/rand instead of math/rand


package moeparser

import (
	"fmt"
	"testing"
)

func TestBbCodeParse(t *testing.T) {
	testString := `Something [b][i][img=http://sauyon.com/blah.png][/i][/i] [b]hi[/b=what]
This seems to work very well :D [url][/url] [size=12px]something
[url]http://sauyon.com/wrappedinurl[/url] [url=http://sauyon.com] [img=//sauyon.com]What[/img] [url][/url]`

	out, err := BbCodeParse(testString)
	if err != nil {
		fmt.Printf("Parsing failed! Error:", err)
	}
	fmt.Println("Parse succeeeded. Output is:")
	fmt.Println(out)

	testString1 := "[url=http://google.com/][img]http://www.google.com/intl/en_ALL/images/logo.gif[/img][/url]"
	out1, err := BbCodeParse(testString1)
	if err != nil {
		fmt.Printf("Parsing failed! Error:", err)
	}
	fmt.Println("Parse succeeeded. Output is:")
	fmt.Println(out1)
}

package moeparser_test

import (
	"fmt"
	"moeparser"
	"testing"
)

func TestBbCodeParse(t *testing.T) {
	testString := `Something [b][i][img=http://sauyon.com/blah.png][/i][/i] [b]hi[/b=what]
This seems to work very well :D [url][/url] [size=12px]something
[url]http://sauyon.com/wrappedinurl[/url] [url=http://sauyon.com] [img=//sauyon.com]What[/img] [url][/url]`

	out, err := BbCodeParse(testString)
	if err != nil {
		fmt.Printf("Parsing failed! Error:", err)
	}
	fmt.Println("Parse succeeeded. Output is:")
	fmt.Println(out)

	testString1 := "[url=http://google.com/][img]http://www.google.com/intl/en_ALL/images/logo.gif[/img][/url]"
	out1, err := BbCodeParse(testString1)
	if err != nil {
		fmt.Printf("Parsing failed! Error:", err)
	}
	fmt.Println("Parse succeeeded. Output is:")
	fmt.Println(out1)
}

Move test code to package moeparser_test


package main

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

var bindaddr = flag.String("bind-address", ":8080", "Address to respond to HTTP requests on")

func main() {
	log.SetFlags(0)
	flag.Parse()
	go h.run()
	go readInput()
	http.HandleFunc("/stream", serveStream)
	err := http.ListenAndServe(*bindaddr, nil)
	if err != nil {
		log.Fatal("Error starting web server: ", err)
	}
}

package main

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

var bindaddr = flag.String("bind-address", ":8080", "Address to respond to HTTP requests on")
var staticdir = flag.String("static-dir", "", "Static directory to serve at /")

func main() {
	log.SetFlags(0)
	flag.Parse()
	go h.run()
	go readInput()

	http.HandleFunc("/stream", serveStream)
	if *staticdir != "" {
		fs := http.FileServer(http.Dir(*staticdir))
		http.Handle("/", fs)
	}
	err := http.ListenAndServe(*bindaddr, nil)
	if err != nil {
		log.Fatal("Error starting web server: ", err)
	}
}

Support serving a static directory along with the websocket stream


package set

import (
	"testing"
)

// BenchmarkAdd checks the performance of the set.Add() method
func BenchmarkAdd(b *testing.B) {
	// Create a new set
	set := New()

	// Run set.Add() b.N times
	for i := 0; i < b.N; i++ {
		set.Add(i)
	}
}

// benchmarkCartesianProduct checks the performance of the set.CartesianProduct() method
func benchmarkCartesianProduct(n int, s *Set, t *Set) {
	// Run set.CartesianProduct() n times
	for i := 0; i < n; i++ {
		s.CartesianProduct(t)
	}
}

// BenchmarkCartesianProductSmall checks the performance of the set.CartesianProduct() method
// over a small data set
func BenchmarkCartesianProductSmall(b *testing.B) {
	benchmarkCartesianProduct(b.N, New(1, 2), New(2, 1))
}

// BenchmarkCartesianProductLarge checks the performance of the set.CartesianProduct() method
// over a large data set
func BenchmarkCartesianProductLarge(b *testing.B) {
	benchmarkCartesianProduct(b.N, New(1, 2, 3, 4, 5, 6, 7, 8, 9), New(9, 8, 7, 6, 5, 4, 3, 2, 1))
}

Add BenchmarkCartesianProduct(), small and large variants


package main

import (
	"fmt"
	"hge"
)

var h *hge.HGE

func FrameFunc() int {
	if h.Input_GetKeyState(hge.K_ESCAPE) {
		return 1
	}

	return 0
}

func main() {
	h = hge.Create(hge.VERSION)
	defer h.Release()

	h.System_SetState(hge.FRAMEFUNC, FrameFunc)
	h.System_SetState(hge.TITLE, "HGE Tutorial 01 - Minimal HGE application")
	h.System_SetState(hge.WINDOWED, true)
	h.System_SetState(hge.USESOUND, false)

	h.System_Log("Test")
	h.System_Log("Test vararg: %s %d", "test", 15)

	if h.System_Initiate() {
		defer h.System_Shutdown()
		h.System_Log("Test")
		h.System_Log("Test vararg: %s %d", "test", 15)
		h.System_Start()
	} else {
		fmt.Println("Error: ", h.System_GetErrorMessage())
	}

	h.System_Log("Test")
}

package main

import (
	"fmt"
	"hge"
)

var h *hge.HGE

func FrameFunc() int {
	if h.Input_GetKeyState(hge.K_ESCAPE) {
		return 1
	}

	return 0
}

func main() {
	h = hge.Create(hge.VERSION)
	defer h.Release()

	h.System_SetState(hge.LOGFILE, "tutorial01.log")
	h.System_SetState(hge.FRAMEFUNC, FrameFunc)
	h.System_SetState(hge.TITLE, "HGE Tutorial 01 - Minimal HGE application")
	h.System_SetState(hge.WINDOWED, true)
	h.System_SetState(hge.USESOUND, false)

	h.System_Log("Test")
	h.System_Log("Test vararg: %s %d", "test", 15)

	if h.System_Initiate() {
		defer h.System_Shutdown()
		h.System_Log("Test")
		h.System_Log("Test vararg: %s %d", "test", 15)
		h.System_Start()
	} else {
		fmt.Println("Error: ", h.System_GetErrorMessage())
	}

	h.System_Log("Test")
}

Add a logfile for tutorial01


package cloudflare_test

import (
	"fmt"
	"log"

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

func ExampleAPI_ListLoadBalancers() {
	// Construct a new API object.
	api, err := cloudflare.New("deadbeef", "test@example.com")
	if err != nil {
		log.Fatal(err)
	}

	// Fetch the zone ID.
	id, err := api.ZoneIDByName("example.com") // Assuming example.com exists in your Cloudflare account
	if err != nil {
		log.Fatal(err)
	}

	// List LBs configured in zone.
	lbList, err := api.ListLoadBalancers(id)
	if err != nil {
		log.Fatal(err)
	}

	for _, lb := range lbList {
		fmt.Println(lb)
	}
}

func ExampleAPI_PoolHealthDetails() {
	// Construct a new API object.
	api, err := cloudflare.New("deadbeef", "test@example.com")
	if err != nil {
		log.Fatal(err)
	}

	// Fetch pool health details.
	healthInfo, err := api.PoolHealthDetails("example-pool-id")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(healthInfo)
}

Add an example load balancing test


package main

import (
	// "fmt"
	"os"
	"strings"
	"testing"
)

func TestGeneral(t *testing.T) {
	defer os.RemoveAll("data")
	p := Open("testpage")
	err := p.Update("**bold**")
	if err != nil {
		t.Error(err)
	}
	if strings.TrimSpace(p.RenderedPage) != "
bold
" {
		t.Errorf("Did not render: '%s'", p.RenderedPage)
	}
	err = p.Update("**bold** and *italic*")
	if err != nil {
		t.Error(err)
	}
	p.Save()

	p2 := Open("testpage")
	if strings.TrimSpace(p2.RenderedPage) != "
bold and italic
" {
		t.Errorf("Did not render: '%s'", p2.RenderedPage)
	}

}

package main

import (
	// "fmt"
	"os"
	"strings"
	"testing"
)

func TestGeneral(t *testing.T) {
	pathToData = "testdata"
	os.MkdirAll(pathToData, 0755)
	defer os.RemoveAll(pathToData)
	p := Open("testpage")
	err := p.Update("**bold**")
	if err != nil {
		t.Error(err)
	}
	if strings.TrimSpace(p.RenderedPage) != "
bold
" {
		t.Errorf("Did not render: '%s'", p.RenderedPage)
	}
	err = p.Update("**bold** and *italic*")
	if err != nil {
		t.Error(err)
	}
	p.Save()

	p2 := Open("testpage")
	if strings.TrimSpace(p2.RenderedPage) != "
bold and italic
" {
		t.Errorf("Did not render: '%s'", p2.RenderedPage)
	}

}

Create special folder for tests


package engi

type Entity struct {
	id         string
	components []Component
	requires   []string
}

func NewEntity(requires []string) *Entity {
	return &Entity{requires: requires}
}

func (e *Entity) DoesRequire(name string) bool {
	for _, requirement := range e.requires {
		if requirement == name {
			return true
		}
	}

	return false
}

func (e *Entity) AddComponent(component Component) {
	e.components = append(e.components, component)
}

func (e *Entity) GetComponent(name string) Component {
	for _, component := range e.components {
		if component.Name() == name {
			return component
		}
	}
	return nil
}

func (e *Entity) ID() string {
	return e.id
}

package engi

type Entity struct {
	id         string
	components []Component
	requires   map[string]bool
}

func NewEntity(requires []string) *Entity {
	e := &Entity{requires: make(map[string]bool)}
	for _, req := range requires {
		e.requires[req] = true
	}
	return e
}

func (e *Entity) DoesRequire(name string) bool { return e.requires[name] }

func (e *Entity) AddComponent(component Component) {
	e.components = append(e.components, component)
}

func (e *Entity) GetComponent(name string) Component {
	for _, component := range e.components {
		if component.Name() == name {
			return component
		}
	}
	return nil
}

func (e *Entity) ID() string {
	return e.id
}

Change Entity.requires into a map for faster lookups.


package main

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

func proto_0_0(inFlag, outFlag bool, errFlag, workdir string, args []string) error {
	proc := exec.Command(args[0], args[1:]...)
	proc.Dir = workdir

	done := make(chan bool)
	done_count := 0
	done_count += wrapStdin(proc, os.Stdin, inFlag, done)
	if outFlag {
		done_count += wrapStdout(proc, os.Stdout, 'o', done)
	}
	if errFlag == "out" && outFlag {
		done_count += wrapStderr(proc, os.Stdout, 'o', done)
	} else if errFlag == "err" {
		done_count += wrapStderr(proc, os.Stdout, 'e', done)
	} else if errFlag != "nil" {
		fmt.Fprintf(os.Stderr, "undefined redirect: '%v'\n", errFlag)
		fatal("undefined redirect")
	}

	err := proc.Run()
	for i := 0; i < done_count; i++ {
		<-done
	}
	return err
}

package main

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

func proto_0_0(inFlag, outFlag bool, errFlag, workdir string, args []string) error {
	proc := exec.Command(args[0], args[1:]...)
	proc.Dir = workdir

	done := make(chan bool)
	done_count := 0
	done_count += wrapStdin(proc, os.Stdin, inFlag, done)
	if outFlag {
		done_count += wrapStdout(proc, os.Stdout, 'o', done)
	}
	switch errFlag {
	case "out":
		if outFlag {
			done_count += wrapStderr(proc, os.Stdout, 'o', done)
		}
	case "err":
		done_count += wrapStderr(proc, os.Stdout, 'e', done)
	case "nil":
		// no-op
	default:
		fmt.Fprintf(os.Stderr, "undefined redirect: '%v'\n", errFlag)
		fatal("undefined redirect")
	}

	err := proc.Run()
	for i := 0; i < done_count; i++ {
		<-done
	}
	return err
}

Fix logic error in error flag handling


package commands

import (
	"fmt"

	"github.com/camd67/moebot/moebot_bot/util/db"
	"github.com/camd67/moebot/moebot_bot/util/reddit"
)

type RandomCommand struct {
	RedditHandle *reddit.Handle
}

func (ac *RandomCommand) Execute(pack *CommPackage) {
	send, err := ac.RedditHandle.GetRandomImage("awwnime")
	if err != nil {
		pack.session.ChannelMessageSend(pack.channel.ID, "Ooops... Looks like this command isn't working right now. Sorry!")
		return
	}

	pack.session.ChannelMessageSendComplex(pack.channel.ID, send)
}

func (ac *RandomCommand) GetPermLevel() db.Permission {
	return db.PermAll
}
func (ac *RandomCommand) GetCommandKeys() []string {
	return []string{"RANDOM", "R"}
}
func (ac *RandomCommand) GetCommandHelp(commPrefix string) string {
	return fmt.Sprintf("`%[1]s r` or `%[1]s random` - Posts a cute anime character.", commPrefix)
}

package commands

import (
	"fmt"

	"github.com/camd67/moebot/moebot_bot/util/db"
	"github.com/camd67/moebot/moebot_bot/util/reddit"
)

type RandomCommand struct {
	RedditHandle *reddit.Handle
}

func (ac *RandomCommand) Execute(pack *CommPackage) {
	send, err := ac.RedditHandle.GetRandomImage("awwnime")
	if err != nil {
		pack.session.ChannelMessageSend(pack.channel.ID, "Ooops... Looks like this command isn't working right now. Sorry!")
		return
	}

	pack.session.ChannelMessageSendComplex(pack.channel.ID, send)
}

func (ac *RandomCommand) GetPermLevel() db.Permission {
	return db.PermAll
}
func (ac *RandomCommand) GetCommandKeys() []string {
	return []string{"RANDOM", "R"}
}
func (ac *RandomCommand) GetCommandHelp(commPrefix string) string {
	return fmt.Sprintf("`%[1]s random` - Posts a cute anime character.", commPrefix)
}

Update help text to only display the andom alias


package multihash

import (
	"errors"
)

// ErrSumNotSupported is returned when the Sum function code is not implemented
var ErrSumNotSupported = errors.New("Function not implemented. Complain to lib maintainer.")

var ErrLenTooLarge = errors.New("requested length was too large for digest")

// Sum obtains the cryptographic sum of a given buffer. The length parameter
// indicates the length of the resulting digest and passing a negative value
// use default length values for the selected hash function.
func Sum(data []byte, code uint64, length int) (Multihash, error) {
	// Get the algorithm.
	hasher, err := GetHasher(code)
	if err != nil {
		return nil, err
	}

	// Feed data in.
	hasher.Write(data)

	// Compute hash.
	//  Use a fixed size array here: should keep things on the stack.
	var space [64]byte
	sum := hasher.Sum(space[0:0])

	// Deal with any truncation.
	if length < 0 {
		length = hasher.Size()
	}
	if len(sum) < length {
		return nil, ErrLenTooLarge
	}
	if length >= 0 {
		sum = sum[:length]
	}

	// Put the multihash metainfo bytes at the front of the buffer.
	// FIXME: this does many avoidable allocations, but it's the shape of the Encode method arguments that forces this.
	return Encode(sum, code)
}

package multihash

import (
	"errors"
)

// ErrSumNotSupported is returned when the Sum function code is not implemented
var ErrSumNotSupported = errors.New("Function not implemented. Complain to lib maintainer.")

var ErrLenTooLarge = errors.New("requested length was too large for digest")

// Sum obtains the cryptographic sum of a given buffer. The length parameter
// indicates the length of the resulting digest and passing a negative value
// use default length values for the selected hash function.
func Sum(data []byte, code uint64, length int) (Multihash, error) {
	// Get the algorithm.
	hasher, err := GetHasher(code)
	if err != nil {
		return nil, err
	}

	// Feed data in.
	hasher.Write(data)

	// Compute final hash.
	//  A new slice is allocated.  FUTURE: see other comment below about allocation, and review together with this line to try to improve.
	sum := hasher.Sum(nil)

	// Deal with any truncation.
	if length < 0 {
		length = hasher.Size()
	}
	if len(sum) < length {
		return nil, ErrLenTooLarge
	}
	if length >= 0 {
		sum = sum[:length]
	}

	// Put the multihash metainfo bytes at the front of the buffer.
	//  FUTURE: try to improve allocations here.  Encode does several which are probably avoidable, but it's the shape of the Encode method arguments that forces this.
	return Encode(sum, code)
}

Remove misplaced optimism about escape analysis.


package crypto
import (
	"testing"
	"fmt"
	"github.com/stretchr/testify/assert"
)

func TestEncrypt(t *testing.T) {
	authKey := []byte("545e0716f2fea0c7a9c46c74fec46c71")
	expected := map[string]interface{}{"entity": "something2"}
	res, _ := Encrypt(expected, authKey, authKey)
	r, _ := Decrypt(res, authKey, authKey)
	assert.Equal(t, expected, r)
}

func TestDecrypt(t *testing.T) {
	authKey := []byte("545e0716f2fea0c7a9c46c74fec46c71")
	input := "WmtlMxl4d_VTfUYnl-A0Uycpr2e3VswKDwoPd03XtoY=.JZMk6FZloYh5BL0K7dHGSyTqB4lTgd9annrFEgLTELnxR3bHweL2"
	expected := map[string]interface{}{"entity": "something2"}
	r, _ := Decrypt(input, authKey, authKey)
	assert.Equal(t, expected, r)

}

package crypto
import (
	"testing"
	"github.com/stretchr/testify/assert"
)

func TestEncrypt(t *testing.T) {
	authKey := []byte("545e0716f2fea0c7a9c46c74fec46c71")
	expected := map[string]interface{}{"entity": "something2"}
	res, _ := Encrypt(expected, authKey, authKey)
	r, _ := Decrypt(res, authKey, authKey)
	assert.Equal(t, expected, r)
}

func TestDecrypt(t *testing.T) {
	authKey := []byte("545e0716f2fea0c7a9c46c74fec46c71")
	input := "WmtlMxl4d_VTfUYnl-A0Uycpr2e3VswKDwoPd03XtoY=.JZMk6FZloYh5BL0K7dHGSyTqB4lTgd9annrFEgLTELnxR3bHweL2"
	expected := map[string]interface{}{"entity": "something2"}
	r, _ := Decrypt(input, authKey, authKey)
	assert.Equal(t, expected, r)

}

Remove fmt import since no more use, need to add git hooks :-/


package main

import (
	"testing"
)

func TestParseMaintainer(t *testing.T) {
	cases := []struct {
		in   []byte
		want *Maintainer
	}{
		{[]byte("JohnDoe"), &Maintainer{Name: "JohnDoe"}},
		{[]byte("John Doe"), &Maintainer{Name: "John Doe"}},
		{[]byte(" John Doe"), &Maintainer{Name: "John Doe"}},
		{[]byte("John Doe "), &Maintainer{Name: "John Doe"}},
	}
	for _, c := range cases {
		got, _ := ParseMaintainer(c.in)
		if got != c.want {
			t.Errorf("ParseMaintainer(%q) == %v, want %v", c.in, got, c.want)
		}
	}
}

package main

import (
	"testing"
)

func TestParseMaintainer(t *testing.T) {
	cases := []struct {
		in   []byte
		want *Maintainer
	}{
		{[]byte("JohnDoe"), &Maintainer{Name: "JohnDoe"}},
		{[]byte("John Doe"), &Maintainer{Name: "John Doe"}},
		{[]byte(" John Doe"), &Maintainer{Name: "John Doe"}},
		{[]byte("John Doe "), &Maintainer{Name: "John Doe"}},
	}
	for _, c := range cases {
		got, _ := ParseMaintainer(c.in)
		if got.Name != c.want.Name {
			t.Errorf(
				"ParseMaintainer(%q).Name == %q, want %q",
				c.in,
				got.Name,
				c.want.Name,
			)
		}
	}
}

Fix a test not to compare structs directly


package db

import (
	"database/sql"
	"fmt"

	"github.com/rafaeljusto/cctldstats/config"
)

// Connection database connection.
var Connection *sql.DB

// Connect performs the database connection. Today the following databases are supported: mysql and postgres
func Connect() (err error) {
	var connParams string
	switch config.CCTLDStats.Database.Kind {
	case "mysql":
		connParams = fmt.Sprintf("%s:%s@tcp(%s)/%s",
			config.CCTLDStats.Database.Username,
			config.CCTLDStats.Database.Password,
			config.CCTLDStats.Database.Host,
			config.CCTLDStats.Database.Name,
		)
	case "postgres":
		connParams = fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=verify-full",
			config.CCTLDStats.Database.Username,
			config.CCTLDStats.Database.Password,
			config.CCTLDStats.Database.Host,
			config.CCTLDStats.Database.Name,
		)
	}

	Connection, err = sql.Open(config.CCTLDStats.Database.Kind, connParams)
	return
}

package db

import (
	"database/sql"
	"fmt"

	"github.com/rafaeljusto/cctldstats/config"
)

// Connection database connection.
var Connection *sql.DB

// Connect performs the database connection. Today the following databases are supported: mysql and postgres
func Connect() (err error) {
	var connParams string
	switch config.CCTLDStats.Database.Kind {
	case "mysql":
		connParams = fmt.Sprintf("%s:%s@tcp(%s)/%s",
			config.CCTLDStats.Database.Username,
			config.CCTLDStats.Database.Password,
			config.CCTLDStats.Database.Host,
			config.CCTLDStats.Database.Name,
		)
	case "postgres":
		connParams = fmt.Sprintf("postgres://%s:%s@%s/%s",
			config.CCTLDStats.Database.Username,
			config.CCTLDStats.Database.Password,
			config.CCTLDStats.Database.Host,
			config.CCTLDStats.Database.Name,
		)
	}

	Connection, err = sql.Open(config.CCTLDStats.Database.Kind, connParams)
	return
}

Disable SSL mode in DB connection for now


package main

import (
	"flag"
	"runtime"

	"gonico"
)

const (
	startHelp    = "Set start page"
	endHelp      = "Set end page"
	outHelp      = "Set download path"
	intervalHelp = "Polling interval time (min)"
)

var (
	start    = flag.Int("start", 1, startHelp)
	end      = flag.Int("end", 1, endHelp)
	out      = flag.String("out", "", outHelp)
	interval = flag.Int("interval", 30, intervalHelp)
)

func init() {
	flag.IntVar(start, "s", 1, startHelp)
	flag.IntVar(end, "e", 1, endHelp)
	flag.StringVar(out, "o", "", outHelp)
	flag.IntVar(interval, "i", 30, intervalHelp)
}

func main() {
	flag.Parse()
	runtime.GOMAXPROCS(runtime.NumCPU())

	gonico.GetVideoInfo("sm9")
}

package main

import (
	"flag"
	"runtime"

	"gonico"
)

const (
	urlHelp = "The movie url or id from which you want to extract movie infomation."
)

func main() {
	movieUrl := flag.String("url", "foo", urlHelp)
	flag.Parse()

	runtime.GOMAXPROCS(runtime.NumCPU())

	gonico.GetVideoInfo(*movieUrl)
}

Add a command line flag


package evaluation

import "fmt"

func Err(ctx *Context, msg, tag string, fmts ...interface{}) Object {
	msg = fmt.Sprintf(msg, fmts...)

	e := &Instance{
		Base: ctx.Get("Error"),
	}

	if e.Base == nil {
		panic("Since the prelude isn't loaded, errors cannot be thrown!")
	}

	e.Data = map[string]Object{
		"tag": &String{Value: tag},
		"msg": &String{Value: msg},
	}

	return e
}

func IsErr(o Object) bool {
	if instance, ok := o.(*Instance); ok {
		return instance.Base.(*Class).Name == "Error"
	}

	return false
}

package evaluation

import "fmt"

// Err returns an error object with the message and tag provided
func Err(ctx *Context, msg, tag string, fmts ...interface{}) Object {
	msg = fmt.Sprintf(msg, fmts...)

	e := &Instance{
		Base: ctx.Get("Error"),
	}

	if e.Base == nil {
		panic("Since the prelude isn't loaded, errors cannot be thrown!")
	}

	e.Data = map[string]Object{
		"tag": &String{Value: tag},
		"msg": &String{Value: msg},
	}

	return e
}

// IsErr checks if an object is an instance of Error
func IsErr(o Object) bool {
	if instance, ok := o.(*Instance); ok {
		return instance.Base.(*Class).Name == "Error"
	}

	return false
}

Add comments to error functions


package image

import (
	"io"
	"os"

	"github.com/dnephin/dobi/tasks/context"
	docker "github.com/fsouza/go-dockerclient"
)

// RunPush pushes an image to the registry
func RunPush(ctx *context.ExecuteContext, t *Task, _ bool) (bool, error) {
	pushTag := func(tag string) error {
		return pushImage(ctx, t, tag)
	}
	if err := t.ForEachTag(ctx, pushTag); err != nil {
		return false, err
	}
	t.logger().Info("Pushed")
	return true, nil
}

func pushImage(ctx *context.ExecuteContext, t *Task, tag string) error {
	repo, err := parseAuthRepo(tag)
	if err != nil {
		return err
	}

	return Stream(os.Stdout, func(out io.Writer) error {
		return ctx.Client.PushImage(docker.PushImageOptions{
			Name:          tag,
			OutputStream:  out,
			RawJSONStream: true,
			// TODO: timeout
		}, ctx.GetAuthConfig(repo))
	})
}

package image

import (
	"io"
	"os"

	"github.com/dnephin/dobi/tasks/context"
	docker "github.com/fsouza/go-dockerclient"
)

// RunPush pushes an image to the registry
func RunPush(ctx *context.ExecuteContext, t *Task, _ bool) (bool, error) {
	pushTag := func(tag string) error {
		return pushImage(ctx, tag)
	}
	if err := t.ForEachTag(ctx, pushTag); err != nil {
		return false, err
	}
	t.logger().Info("Pushed")
	return true, nil
}

func pushImage(ctx *context.ExecuteContext, tag string) error {
	repo, err := parseAuthRepo(tag)
	if err != nil {
		return err
	}

	return Stream(os.Stdout, func(out io.Writer) error {
		return ctx.Client.PushImage(docker.PushImageOptions{
			Name:          tag,
			OutputStream:  out,
			RawJSONStream: true,
			// TODO: timeout
		}, ctx.GetAuthConfig(repo))
	})
}

Fix lint error, unused param


//go:build linux && cgo && !agent
// +build linux,cgo,!agent

package state

import (
	"context"
	"testing"

	"github.com/lxc/lxd/lxd/db"
	"github.com/lxc/lxd/lxd/firewall"
	"github.com/lxc/lxd/lxd/sys"
)

// NewTestState returns a State object initialized with testable instances of
// the node/cluster databases and of the OS facade.
//
// Return the newly created State object, along with a function that can be
// used for cleaning it up.
func NewTestState(t *testing.T) (*State, func()) {
	node, nodeCleanup := db.NewTestNode(t)
	cluster, clusterCleanup := db.NewTestCluster(t)
	os, osCleanup := sys.NewTestOS(t)

	cleanup := func() {
		nodeCleanup()
		clusterCleanup()
		osCleanup()
	}

	state := NewState(context.TODO(), node, cluster, nil, os, nil, nil, nil, firewall.New(), nil)

	return state, cleanup
}

//go:build linux && cgo && !agent
// +build linux,cgo,!agent

package state

import (
	"context"
	"testing"

	"github.com/lxc/lxd/lxd/db"
	"github.com/lxc/lxd/lxd/firewall"
	"github.com/lxc/lxd/lxd/sys"
)

// NewTestState returns a State object initialized with testable instances of
// the node/cluster databases and of the OS facade.
//
// Return the newly created State object, along with a function that can be
// used for cleaning it up.
func NewTestState(t *testing.T) (*State, func()) {
	node, nodeCleanup := db.NewTestNode(t)
	cluster, clusterCleanup := db.NewTestCluster(t)
	os, osCleanup := sys.NewTestOS(t)

	cleanup := func() {
		nodeCleanup()
		clusterCleanup()
		osCleanup()
	}

	state := NewState(context.TODO(), node, cluster, nil, os, nil, nil, nil, firewall.New(), nil, nil, func() {})

	return state, cleanup
}

Update tests with NewState usage


package statemachine

import (
	"log"
	"os"
)

type Handler func() string

type Machine struct {
	Handlers map[string]Handler
	Logger   *log.Logger
}

type StateMachineError struct {
	State string
}

func (sme StateMachineError) Error() string {
	return "statemachine: No handler function registered for state: " + sme.State
}

func NewMachine() Machine {
	return Machine{
		Handlers: map[string]Handler{},
		Logger:   log.New(os.Stdout, "statemachine: ", 0),
	}
}

func (machine Machine) AddState(stateName string, handlerFn Handler) {
	machine.Handlers[stateName] = handlerFn
}

func (machine Machine) Run() (success bool, error error) {
	state := "INIT"
	machine.Logger.Println("Starting in state: INIT")
	for {
		if handler, present := machine.Handlers[state]; present {
			oldstate := state
			state = handler()
			machine.Logger.Printf("State transition: %s -> %s\n", oldstate, state)
			if state == "END" {
				machine.Logger.Println("Terminating")
				return true, nil
			}
		} else {
			return false, StateMachineError{state}
		}
	}
}

package statemachine

import (
	"log"
	"os"
)

type Handler func() string

type Machine struct {
	Handlers map[string]Handler
	Logger   *log.Logger
}

type StateMachineError struct {
	State string
}

func (sme StateMachineError) Error() string {
	return "ERROR: No handler function registered for state: " + sme.State
}

func NewMachine() Machine {
	return Machine{
		Handlers: map[string]Handler{},
		Logger:   log.New(os.Stdout, "statemachine: ", 0),
	}
}

func (machine Machine) AddState(stateName string, handlerFn Handler) {
	machine.Handlers[stateName] = handlerFn
}

func (machine Machine) Run() (success bool, error error) {
	state := "INIT"
	machine.Logger.Println("INFO: Starting in state: INIT")
	for {
		if handler, present := machine.Handlers[state]; present {
			oldstate := state
			state = handler()
			machine.Logger.Printf("INFO: State transition: %s -> %s\n", oldstate, state)
			if state == "END" {
				machine.Logger.Println("INFO: Terminating")
				return true, nil
			}
		} else {
			err := StateMachineError{state}
			machine.Logger.Print(err)
			return false, err
		}
	}
}

Add levels to log output


package netascii

import (
	"bufio"
	"bytes"
	"io"
)

func WriteTo(b []byte, bw *bufio.Writer) (n int, err error) {
	b = bytes.Replace(b, []byte{'\r', 0}, []byte{'\r'}, -1)
	b = bytes.Replace(b, []byte{'\r', '\n'}, []byte{'\n'}, -1)
	n, err = bw.Write(b)
	if err != nil {
		return 0, err
	}
	return n, nil
}

func Convert(b []byte) []byte {
	b = bytes.Replace(b, []byte{'\r', 0}, []byte{'\r'}, -1)
	b = bytes.Replace(b, []byte{'\r', '\n'}, []byte{'\n'}, -1)
	return b
}

func ReadFull(r io.Reader, buf []byte) (n int, err error) {
	if len(buf) == 0 {
		return 0, io.ErrShortBuffer
	}
	n, err = r.Read(buf)
	if err != nil {
		return 0, err
	}
	buf = bytes.Replace(buf, []byte{'\r', 0}, []byte{'\r'}, -1)
	buf = bytes.Replace(buf, []byte{'\r', '\n'}, []byte{'\n'}, -1)

	return n, nil
}

package netascii

import (
	"bufio"
	"bytes"
	"io"
)

func WriteTo(b []byte, bw *bufio.Writer) (n int, err error) {
	b = bytes.Replace(b, []byte{'\r', 0}, []byte{'\r'}, -1)
	b = bytes.Replace(b, []byte{'\r', '\n'}, []byte{'\n'}, -1)
	n, err = bw.Write(b)
	if err != nil {
		return n, err
	}
	return n, nil
}

func Convert(b []byte) []byte {
	b = bytes.Replace(b, []byte{'\r', 0}, []byte{'\r'}, -1)
	b = bytes.Replace(b, []byte{'\r', '\n'}, []byte{'\n'}, -1)
	return b
}

func ReadFull(r io.Reader, buf []byte) (n int, err error) {
	if len(buf) == 0 {
		return 0, io.ErrShortBuffer
	}
	n, err = r.Read(buf)
	if err != nil {
		return 0, err
	}
	buf = bytes.Replace(buf, []byte{'\r', 0}, []byte{'\r'}, -1)
	buf = bytes.Replace(buf, []byte{'\r', '\n'}, []byte{'\n'}, -1)

	return n, nil
}

Return the actual size written to bw, even when an error occurs.


package dexcom

//go:generate ../gen_crc_table/gen_crc_table

func crc16(msg []byte) []byte {
	res := uint16(0)
	for _, b := range msg {
		res = res<<8 ^ crc16Table[byte(res>>8)^b]
	}
	return MarshalUint16(res)
}

package dexcom

//go:generate ../crcgen/crcgen

func crc16(msg []byte) []byte {
	res := uint16(0)
	for _, b := range msg {
		res = res<<8 ^ crc16Table[byte(res>>8)^b]
	}
	return MarshalUint16(res)
}

Change CRC table generator to "crcgen"


package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"log"
	"net/http"
	"time"
)

func main() {
	addr := flag.String("addr", ":4000", "HTTP network address")
	certFile := flag.String("certfile", "cert.pem", "certificate PEM file")
	keyFile := flag.String("keyfile", "key.pem", "key PEM file")
	flag.Parse()

	tlsConfig := &tls.Config{
		PreferServerCipherSuites: true,
		CurvePreferences:         []tls.CurveID{tls.X25519, tls.CurveP256},
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/ping", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Pong")
	})
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		// The "/" pattern matches everything, so we need to check
		// that we're at the root here.
		if req.URL.Path != "/" {
			http.NotFound(w, req)
			return
		}
		fmt.Fprintf(w, "Welcome to the home page!")
	})

	srv := &http.Server{
		Addr:         *addr,
		Handler:      mux,
		TLSConfig:    tlsConfig,
		IdleTimeout:  time.Minute,
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	log.Printf("Starting server on %s", *addr)
	err := srv.ListenAndServeTLS(*certFile, *keyFile)
	log.Fatal(err)
}

package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"log"
	"net/http"
)

func main() {
	addr := flag.String("addr", ":4000", "HTTP network address")
	certFile := flag.String("certfile", "cert.pem", "certificate PEM file")
	keyFile := flag.String("keyfile", "key.pem", "key PEM file")
	flag.Parse()

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		if req.URL.Path != "/" {
			http.NotFound(w, req)
			return
		}
		fmt.Fprintf(w, "Proudly served with Go and HTTPS!")
	})

	srv := &http.Server{
		Addr:    *addr,
		Handler: mux,
		TLSConfig: &tls.Config{
			MinVersion:               tls.VersionTLS13,
			PreferServerCipherSuites: true,
		},
	}

	log.Printf("Starting server on %s", *addr)
	err := srv.ListenAndServeTLS(*certFile, *keyFile)
	log.Fatal(err)
}

Tweak server to be shorter


/*
Copyright 2016 The Kubernetes Authors.

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

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

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

package main

import (
	"github.com/spf13/pflag"
	"k8s.io/kubernetes/cmd/kube-dns/app"
	"k8s.io/kubernetes/cmd/kube-dns/app/options"
	_ "k8s.io/kubernetes/pkg/client/metrics/prometheus" // for client metric registration
	"k8s.io/kubernetes/pkg/util/flag"
	"k8s.io/kubernetes/pkg/util/logs"
	"k8s.io/kubernetes/pkg/version/verflag"
)

func main() {
	config := options.NewKubeDNSConfig()
	config.AddFlags(pflag.CommandLine)

	flag.InitFlags()
	logs.InitLogs()
	defer logs.FlushLogs()

	verflag.PrintAndExitIfRequested()
	server := app.NewKubeDNSServerDefault(config)
	server.Run()
}

/*
Copyright 2016 The Kubernetes Authors.

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

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

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

package main

import (
	"github.com/spf13/pflag"
	"k8s.io/kubernetes/cmd/kube-dns/app"
	"k8s.io/kubernetes/cmd/kube-dns/app/options"
	_ "k8s.io/kubernetes/pkg/client/metrics/prometheus" // for client metric registration
	"k8s.io/kubernetes/pkg/util/flag"
	"k8s.io/kubernetes/pkg/util/logs"
	_ "k8s.io/kubernetes/pkg/version/prometheus" // for version metric registration
	"k8s.io/kubernetes/pkg/version/verflag"
)

func main() {
	config := options.NewKubeDNSConfig()
	config.AddFlags(pflag.CommandLine)

	flag.InitFlags()
	logs.InitLogs()
	defer logs.FlushLogs()

	verflag.PrintAndExitIfRequested()
	server := app.NewKubeDNSServerDefault(config)
	server.Run()
}

Split the version metric out to its own package


package crypto

import (
	"testing"
)

// TestRandIntnPanics tests that RandIntn panics if n <= 0.
func TestRandIntnPanics(t *testing.T) {
	defer func() {
		if r := recover(); r == nil {
			t.Error("expected panic for n <= 0")
		}
	}()
	RandIntn(0)
	RandIntn(-1)
}

package crypto

import (
	"testing"
)

// TestRandIntnPanics tests that RandIntn panics if n <= 0.
func TestRandIntnPanics(t *testing.T) {
	defer func() {
		if r := recover(); r == nil {
			t.Error("expected panic for n <= 0")
		}
	}()

	_, err := RandIntn(0)
	if err != nil {
		t.Error("expected panic on n <= 0, not error")
	}

	_, err = RandIntn(-1)
	if err != nil {
		t.Error("expected panic on n <= 0, not error")
	}
}

Add error checks to TestRandIntnPanics


// Utility scans spectrum and shows channels on which Crazyflies found
package main

import (
	"log"

	"github.com/krasin/crazyradio"
)

func main() {
	st, err := crazyradio.Start(nil)
	if err != nil {
		log.Fatal(err)
	}
	addr, err := st.Scan()
	if err != nil {
		log.Fatalf("Scan failed: %v", err)
	}
	log.Printf("Found crazyflies: %v", addr)
}

// Utility scans spectrum and shows channels on which Crazyflies found
package main

import (
	"log"

	"github.com/krasin/crazyradio"
	"github.com/krasin/crazyradio/usb"
)

func main() {
	st, err := crazyradio.Start(usb.Hub)
	if err != nil {
		log.Fatal(err)
	}
	addr, err := st.Scan()
	if err != nil {
		log.Fatalf("Scan failed: %v", err)
	}
	log.Printf("Found crazyflies: %v", addr)
}

Fix nil reference panic in crazyradio-scan. Pass usb.Hub to station.Start, instead of nil


// +build freebsd,!cgo

/*
   Copyright The containerd 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 console

//
// Implementing the functions below requires cgo support.  Non-cgo stubs
// versions are defined below to enable cross-compilation of source code
// that depends on these functions, but the resultant cross-compiled
// binaries cannot actually be used.  If the stub function(s) below are
// actually invoked they will display an error message and cause the
// calling process to exit.
//

func openpt() (*os.File, error) {
	panic("openpt() support requires cgo.")
}

// +build freebsd,!cgo

/*
   Copyright The containerd 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 console

import (
	"os"
)

//
// Implementing the functions below requires cgo support.  Non-cgo stubs
// versions are defined below to enable cross-compilation of source code
// that depends on these functions, but the resultant cross-compiled
// binaries cannot actually be used.  If the stub function(s) below are
// actually invoked they will display an error message and cause the
// calling process to exit.
//

func openpt() (*os.File, error) {
	panic("openpt() support requires cgo.")
}

Add missing import in freebsd nocgo stub


package dice

import "testing"

func TestRollable(t *testing.T) {
    var attackDie AttackDie
    var defenseDie DefenseDie
    attackDie.Roll()
    defenseDie.Roll()
}

package dice

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

func TestRollable_AttackDie(t *testing.T) {
	assert := assert.New(t)

	var attackDie AttackDie
	var blanks, focuses, hits, crits int
	attackDie.Roll()

	for i := 0; i < 1000; i++ {
		switch attackDie.Result() {
		case BLANK:
			blanks++
		case FOCUS:
			focuses++
		case HIT:
			hits++
		case CRIT:
			crits++
		}
	}

	assert.InEpsilon(int(1000*2.0/8), blanks, 50)
	assert.InEpsilon(int(1000*2.0/8), focuses, 50)
	assert.InEpsilon(int(1000*3.0/8), hits, 50)
	assert.InEpsilon(int(1000*1.0/8), crits, 50)
}

func TestRollable_DefenseDie(t *testing.T) {
	assert := assert.New(t)

	var defenseDie DefenseDie
	var blanks, focuses, evades int
	defenseDie.Roll()

	for i := 0; i < 1000; i++ {
		switch defenseDie.Result() {
		case BLANK:
			blanks++
		case FOCUS:
			focuses++
		case EVADE:
			evades++
		}
	}

	assert.InEpsilon(int(1000*3.0/8), blanks, 50)
	assert.InEpsilon(int(1000*2.0/8), focuses, 50)
	assert.InEpsilon(int(1000*3.0/8), evades, 50)
}

Add test for die rolling.


package herd

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

var httpdHerd *Herd

func (herd *Herd) startServer(portNum uint, daemon bool) error {
	listener, err := net.Listen("tcp", fmt.Sprintf(":%d", portNum))
	if err != nil {
		return err
	}
	httpdHerd = herd
	http.HandleFunc("/", statusHandler)
	http.HandleFunc("/listSubs", listSubsHandler)
	http.HandleFunc("/showSubs", showAllSubsHandler)
	http.HandleFunc("/showDeviantSubs", showDeviantSubsHandler)
	http.HandleFunc("/showCompliantSubs", showCompliantSubsHandler)
	if daemon {
		go http.Serve(listener, nil)
	} else {
		http.Serve(listener, nil)
	}
	return nil
}

func (herd *Herd) addHtmlWriter(htmlWriter HtmlWriter) {
	herd.htmlWriters = append(herd.htmlWriters, htmlWriter)
}

package herd

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

var httpdHerd *Herd

func (herd *Herd) startServer(portNum uint, daemon bool) error {
	listener, err := net.Listen("tcp", fmt.Sprintf(":%d", portNum))
	if err != nil {
		return err
	}
	httpdHerd = herd
	http.HandleFunc("/", statusHandler)
	http.HandleFunc("/listSubs", listSubsHandler)
	http.HandleFunc("/showAllSubs", showAllSubsHandler)
	http.HandleFunc("/showDeviantSubs", showDeviantSubsHandler)
	http.HandleFunc("/showCompliantSubs", showCompliantSubsHandler)
	if daemon {
		go http.Serve(listener, nil)
	} else {
		http.Serve(listener, nil)
	}
	return nil
}

func (herd *Herd) addHtmlWriter(htmlWriter HtmlWriter) {
	herd.htmlWriters = append(herd.htmlWriters, htmlWriter)
}

Fix bug: list of all subs did not work.


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

package time

import (
	"testing";
	"time";
)

export func TestTick(t *testing.T) {
	const (
		Delta uint64 = 100*1e6;
		Count uint64 = 10;
	);
	c := Tick(Delta);
	t0 := Nanoseconds();
	for i := 0; i < Count; i++ {
		<-c;
	}
	t1 := Nanoseconds();
	ns := t1 - t0;
	target := int64(Delta*Count);
	slop := target*2/10;
	if ns < target - slop || ns > target + slop {
		t.Fatalf("%d ticks of %g ns took %g ns, expected %g", Count, float64(Delta), float64(ns), float64(target));
	}
}

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

package time

import (
	"testing";
	"time";
)

export func TestTick(t *testing.T) {
	const (
		Delta = 100*1e6;
		Count = 10;
	);
	c := Tick(Delta);
	t0 := Nanoseconds();
	for i := 0; i < Count; i++ {
		<-c;
	}
	t1 := Nanoseconds();
	ns := t1 - t0;
	target := int64(Delta*Count);
	slop := target*2/10;
	if ns < target - slop || ns > target + slop {
		t.Fatalf("%d ticks of %g ns took %g ns, expected %g", Count, float64(Delta), float64(ns), float64(target));
	}
}

Remove types from constants, since they didn't match what Tick() expected.


package version

type Version struct {
	GitSHA  string
	Version string
}

var VersionInfo = Version{
	GitSHA:  gitSha,
	Version: version,
}

const gitSha = "unknown"
const version = "0.1"

package version

type Version struct {
	GitCommit string
	Version   string
}

var VersionInfo = unknownVersion

var unknownVersion = Version{
	GitCommit: "unknown git commit",
	Version: "unknown version",
}

Change back to git commit


package collector

import "github.com/prometheus/client_golang/prometheus"

const namespace = "ipmi"

var (
	temperatures = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, "", "temperatures"),
		"Contains the collected temperatures from IPMI",
		[]string{"sensor"},
		nil,
	)

	fanspeed = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, "", "fan_speed"),
		"Fan Speed in RPM",
		[]string{"fan"},
		nil,
	)

	voltages = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, "", "voltages"),
		"Contains the voltages from IPMI",
		[]string{"sensor"},
		nil,
	)

        current = prometheus.NewDesc(
                prometheus.BuildFQName(namespace, "", "current"),
                "Contains the current from IPMI",
                []string{"sensor"},
                nil,
        )

	intrusion = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, "", "intrusion_status"),
		"Indicates if a chassis is open",
		nil,
		nil,
	)

	powersupply = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, "", "power_supply_status"),
		"Indicates if a power supply is operational",
		[]string{"PSU"},
		nil,
	)
)

Fix go format with go fmt


package main

import (
	"log"

	"pault.ag/go/debian/control"
	"pault.ag/go/debian/dependency"
	"pault.ag/go/resolver"
)

func main() {
	log.SetFlags(log.Lshortfile)

	// TODO configurable path?  perhaps allow for an optional *.dsc instead?
	con, err := control.ParseControlFile("debian/control")
	if err != nil {
		log.Fatalf("error: %v\n", err)
	}

	// TODO configurable or something
	suite := "unstable"
	arch := "amd64"
	index, err := resolver.GetBinaryIndex(
		"http://httpredir.debian.org/debian",
		suite,
		"main",
		arch,
	)
	if err != nil {
		log.Fatalf("error: %v\n", err)
	}

	allCan := true
	allPossi := append(
		con.Source.BuildDepends.GetAllPossibilities(),
		con.Source.BuildDependsIndep.GetAllPossibilities()...,
	)

	depArch, err := dependency.ParseArch("any")
	if err != nil {
		log.Fatalf("error: %v\n", err)
	}

	allBins := []control.BinaryIndex{}
	for _, possi := range allPossi {
		can, why, bins := index.ExplainSatisfies(*depArch, possi)
		if !can {
			log.Printf("%s: %s\n", possi.Name, why)
			allCan = false
		} else {
			// TODO more smarts for which dep out of bins to use
			allBins = append(allBins, bins[0])
		}
	}

	if !allCan {
		log.Fatalf("Unsatisfied possi; exiting.\n")
	}
}

Throw in some initial basic code so we have something to work with


package helpers

func ConvertTypeForJS(s string) string {
	conv := map[string]string{
		"array":   "array",
		"boolean": "boolean",
		"integer": "number",
		"number":  "number",
		"object":  "object",
		"string":  "string",
	}
	return conv[s]
}

package helpers

func ConvertTypeForJS(s string) string {
	v, ok := map[string]string{
		"integer": "number",
	}[s]
	if !ok {
		return s
	}
	return v
}

Return given type when target is not found


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

package util

import (
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

const (
	millisecondsInSecond = 1000
	secondsInMinute      = 60
	minutesInHour        = 60
)

func ParseDuration(duration int) (seconds, minutes, hours int) {
	seconds = duration / millisecondsInSecond
	if seconds >= secondsInMinute {
		minutes = seconds / secondsInMinute
		seconds -= minutes * secondsInMinute
	}
	if minutes >= minutesInHour {
		hours = minutes / minutesInHour
		minutes -= hours * minutesInHour
	}
	return
}

func DurationString(seconds, minutes, hours int) (duration string) {
	duration = formatNumber(minutes) + ":" + formatNumber(seconds)
	if hours > 0 {
		duration = formatNumber(hours) + ":" + duration
	}
	return
}

func formatNumber(num int) (formatted string) {
	if num < 10 {
		formatted += "0"
	}
	formatted += strconv.Itoa(num)
	return
}

func SanitizePath(path string) string {
	if strings.HasPrefix(path, "~") {
		path = strings.Replace(path, "~", os.Getenv("HOME"), 1)
	}
	return filepath.Clean(path)
}

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

package util

import (
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

const (
	millisecondsInSecond = 1000
	secondsInMinute      = 60
	minutesInHour        = 60
)

func ParseDuration(milliseconds int) (seconds, minutes, hours int) {
	seconds = milliseconds / millisecondsInSecond
	if seconds >= secondsInMinute {
		minutes = seconds / secondsInMinute
		seconds -= minutes * secondsInMinute
	}
	if minutes >= minutesInHour {
		hours = minutes / minutesInHour
		minutes -= hours * minutesInHour
	}
	return
}

func DurationString(seconds, minutes, hours int) (duration string) {
	duration = formatNumber(minutes) + ":" + formatNumber(seconds)
	if hours > 0 {
		duration = formatNumber(hours) + ":" + duration
	}
	return
}

func formatNumber(num int) (formatted string) {
	if num < 10 {
		formatted += "0"
	}
	formatted += strconv.Itoa(num)
	return
}

func SanitizePath(path string) string {
	if strings.HasPrefix(path, "~") {
		path = strings.Replace(path, "~", os.Getenv("HOME"), 1)
	}
	return filepath.Clean(path)
}

Rename duration arg to milliseconds in ParseDuration


package app

import (
	"fmt"
	"os"
	"runtime"
	"text/template"

	"github.com/Sirupsen/logrus"
	"github.com/docker/libcompose/version"
	"github.com/urfave/cli"
)

var versionTemplate = `Version:      {{.Version}} ({{.GitCommit}})
Go version:   {{.GoVersion}}
Built:        {{.BuildTime}}
OS/Arch:      {{.Os}}/{{.Arch}}`

// Version prints the libcompose version number and additionnal informations.
func Version(c *cli.Context) {
	if c.Bool("short") {
		fmt.Println(version.VERSION)
		return
	}

	tmpl, err := template.New("").Parse(versionTemplate)
	if err != nil {
		logrus.Fatal(err)
	}

	v := struct {
		Version   string
		GitCommit string
		GoVersion string
		BuildTime string
		Os        string
		Arch      string
	}{
		Version:   version.VERSION,
		GitCommit: version.GITCOMMIT,
		GoVersion: runtime.Version(),
		BuildTime: version.BUILDTIME,
		Os:        runtime.GOOS,
		Arch:      runtime.GOARCH,
	}

	if err := tmpl.Execute(os.Stdout, v); err != nil {
		logrus.Fatal(err)
	}
	fmt.Printf("\n")
	return
}

package app

import (
	"fmt"
	"os"
	"runtime"
	"text/template"

	"github.com/Sirupsen/logrus"
	"github.com/docker/libcompose/version"
	"github.com/urfave/cli"
)

var versionTemplate = `Version:      {{.Version}} ({{.GitCommit}})
Go version:   {{.GoVersion}}
Built:        {{.BuildTime}}
OS/Arch:      {{.Os}}/{{.Arch}}`

// Version prints the libcompose version number and additionnal informations.
func Version(c *cli.Context) error {
	if c.Bool("short") {
		fmt.Println(version.VERSION)
		return nil
	}

	tmpl, err := template.New("").Parse(versionTemplate)
	if err != nil {
		logrus.Fatal(err)
	}

	v := struct {
		Version   string
		GitCommit string
		GoVersion string
		BuildTime string
		Os        string
		Arch      string
	}{
		Version:   version.VERSION,
		GitCommit: version.GITCOMMIT,
		GoVersion: runtime.Version(),
		BuildTime: version.BUILDTIME,
		Os:        runtime.GOOS,
		Arch:      runtime.GOARCH,
	}

	if err := tmpl.Execute(os.Stdout, v); err != nil {
		logrus.Fatal(err)
	}
	fmt.Printf("\n")
	return nil
}

Update Version signature to remove warning


package handler

import (
	"go/build"
	"log"
	"net/http"
	"path/filepath"

	"github.com/shurcooL/go/gopherjs_http"
	"github.com/shurcooL/httpfs/httputil"
	"github.com/shurcooL/httpfs/vfsutil"
)

func init() {
	// HACK: This code registers routes at root on default mux... That's not very nice.
	http.Handle("/table-of-contents.js", httputil.FileHandler{gopherjs_http.Package("github.com/shurcooL/frontend/table-of-contents")})
	http.Handle("/table-of-contents.css", httputil.FileHandler{vfsutil.File(filepath.Join(importPathToDir("github.com/shurcooL/frontend/table-of-contents"), "style.css"))})
}

func importPathToDir(importPath string) string {
	p, err := build.Import(importPath, "", build.FindOnly)
	if err != nil {
		log.Fatalln(err)
	}
	return p.Dir
}

package handler

import (
	"go/build"
	"log"
	"net/http"
	"path/filepath"

	"github.com/shurcooL/go/gopherjs_http"
	"github.com/shurcooL/httpfs/httputil"
	"github.com/shurcooL/httpfs/vfsutil"
)

func init() {
	// HACK: This code registers routes at root on default mux... That's not very nice.
	http.Handle("/table-of-contents.js", httputil.FileHandler{File: gopherjs_http.Package("github.com/shurcooL/frontend/table-of-contents")})
	http.Handle("/table-of-contents.css", httputil.FileHandler{File: vfsutil.File(filepath.Join(importPathToDir("github.com/shurcooL/frontend/table-of-contents"), "style.css"))})
}

func importPathToDir(importPath string) string {
	p, err := build.Import(importPath, "", build.FindOnly)
	if err != nil {
		log.Fatalln(err)
	}
	return p.Dir
}

Use keyed fields in composite literal.


package main

// gitVersion returns the tag of the HEAD, if one exists,
// or else the commit hash.
func gitVersion() string {
	tag := cmd("git", "tag", "--contains", "HEAD").OutputLine()

	if tag != "" {
		return tag
	}

	return cmd("git", "rev-parse", "--short", "HEAD").OutputLine()
}

package main

import "os/exec"

// gitVersion returns one of the following:
// - Git tag of the HEAD if one exists, or
// - Commit hash of the HEAD, or
// - Empty string if Git is not in the PATH.
func gitVersion() string {
	cmdName := "git"

	if _, err := exec.LookPath(cmdName); err != nil {
		return ""
	}

	tag := cmd(cmdName, "tag", "--contains", "HEAD").OutputLine()
	if tag != "" {
		return tag
	}

	return cmd(cmdName, "rev-parse", "--short", "HEAD").OutputLine()
}

Check that Git is in the PATH


package langdet

// Token represents a text token and its occurence in an analyzed text
type Token struct {
	Occurrence int
	Key        string
}

// ByOccurrence represents an array of tokens which can be sorted by occurrences of the tokens.
type ByOccurrence []Token

func (a ByOccurrence) Len() int      { return len(a) }
func (a ByOccurrence) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByOccurrence) Less(i, j int) bool {
	if a[i].Occurrence == a[j].Occurrence {
		return a[i].Key < a[i].Key
	}
	return a[i].Occurrence < a[j].Occurrence
}

// Language represents a language by its name and the profile ( map[token]OccurrenceRank )
type Language struct {
	Profile map[string]int
	Name    string
}

// DetectionResult represents the result from comparing 2 Profiles. It includes the confidence which is basically the
// the relative distance between the two profiles.
type DetectionResult struct {
	Name       string
	Confidence int
}

//ResByConf represents an array of DetectionResult and can be sorted by Confidence.
type ResByConf []DetectionResult

func (a ResByConf) Len() int           { return len(a) }
func (a ResByConf) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ResByConf) Less(i, j int) bool { return a[i].Confidence > a[j].Confidence }

package langdet

// Token represents a text token and its occurence in an analyzed text
type Token struct {
	Occurrence int
	Key        string
}

// ByOccurrence represents an array of tokens which can be sorted by occurrences of the tokens.
type ByOccurrence []Token

func (a ByOccurrence) Len() int      { return len(a) }
func (a ByOccurrence) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByOccurrence) Less(i, j int) bool {
	if a[i].Occurrence == a[j].Occurrence {
		return a[i].Key < a[j].Key
	}
	return a[i].Occurrence < a[j].Occurrence
}

// Language represents a language by its name and the profile ( map[token]OccurrenceRank )
type Language struct {
	Profile map[string]int
	Name    string
}

// DetectionResult represents the result from comparing 2 Profiles. It includes the confidence which is basically the
// the relative distance between the two profiles.
type DetectionResult struct {
	Name       string
	Confidence int
}

//ResByConf represents an array of DetectionResult and can be sorted by Confidence.
type ResByConf []DetectionResult

func (a ResByConf) Len() int           { return len(a) }
func (a ResByConf) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ResByConf) Less(i, j int) bool { return a[i].Confidence > a[j].Confidence }

Fix typo in ngram sorting code.


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

package ptypes

// IntWeight returns number of bits set to 1 in x.
func IntWeight(x uint64) (w int) {
	for x > 0 {
		w++
		x &= (x - 1)
	}
	return w
}

// ClosestInt returns integer closest to x with the same weight.
func ClosestInt(x uint64) (ci uint64, ok bool) {
	for i := uint(0); i < 63; i++ {
		if (x>>i)&1 != (x >> (i + 1) & 1) {
			x ^= 1<<i | 1<<(i+1)
			return x, true
		}
	}
	return 0, false // If all bits are 0 or 1.
}

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

package ptypes

// IntWeight returns number of bits set to 1 in x.
func IntWeight(x uint64) (w int) {
	for x > 0 {
		w++
		x &= (x - 1)
	}
	return w
}

// ClosestInt returns integer closest to x with the same weight.
// The time complexity is O(n), where n is the integer width.
// The O(1) additional space is needed.
func ClosestInt(x uint64) (ci uint64, ok bool) {
	for i := uint(0); i < 63; i++ {
		if (x>>i)&1 != x>>(i+1)&1 {
			x ^= 1<<i | 1<<(i+1)
			return x, true
		}
	}
	return 0, false // If all bits are 0 or 1.
}

Add time/space compexity analysis for ptypes.ClosestInt function


// +build windows

package main

import (
	"io"
	"os"

	"github.com/gorilla/websocket"
	"github.com/mattn/go-colorable"

	"github.com/lxc/lxd/shared/logger"
)

// Windows doesn't process ANSI sequences natively, so we wrap
// os.Stdout for improved user experience for Windows client
type WrappedWriteCloser struct {
	io.Closer
	wrapper io.Writer
}

func (wwc *WrappedWriteCloser) Write(p []byte) (int, error) {
	return wwc.wrapper.Write(p)
}

func (c *execCmd) getStdout() io.WriteCloser {
	return &WrappedWriteCloser{os.Stdout, colorable.NewColorableStdout()}
}

func (c *execCmd) getTERM() (string, bool) {
	return "dumb", true
}

func (c *execCmd) controlSocketHandler(control *websocket.Conn) {
	// TODO: figure out what the equivalent of signal.SIGWINCH is on
	// windows and use that; for now if you resize your terminal it just
	// won't work quite correctly.
	err := c.sendTermSize(control)
	if err != nil {
		logger.Debugf("error setting term size %s", err)
	}
}

// +build windows

package main

import (
	"io"
	"os"
	"os/signal"
	"syscall"

	"github.com/gorilla/websocket"
	"github.com/mattn/go-colorable"

	"github.com/lxc/lxd/shared/logger"
)

// Windows doesn't process ANSI sequences natively, so we wrap
// os.Stdout for improved user experience for Windows client
type WrappedWriteCloser struct {
	io.Closer
	wrapper io.Writer
}

func (wwc *WrappedWriteCloser) Write(p []byte) (int, error) {
	return wwc.wrapper.Write(p)
}

func (c *execCmd) getStdout() io.WriteCloser {
	return &WrappedWriteCloser{os.Stdout, colorable.NewColorableStdout()}
}

func (c *execCmd) getTERM() (string, bool) {
	return "dumb", true
}

func (c *execCmd) controlSocketHandler(control *websocket.Conn) {
	ch := make(chan os.Signal, 10)
	signal.Notify(ch, os.Interrupt)

	closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")
	defer control.WriteMessage(websocket.CloseMessage, closeMsg)

	for {
		sig := <-ch
		switch sig {
		case os.Interrupt:
			logger.Debugf("Received '%s signal', forwarding to executing program.", sig)
			err := c.forwardSignal(control, syscall.SIGINT)
			if err != nil {
				logger.Debugf("Failed to forward signal '%s'.", syscall.SIGINT)
				return
			}
		default:
			break
		}
	}
}

Fix signal handler for Windows